two limit questions related to $\sin$

Question: I stuck with these 2 limits, can you help me please?
$1.\displaystyle\quad \lim_{n \to \infty }\frac{\sin1+2\sin\frac{1}{2}+3\sin\frac{1}{3}+\cdots+n\sin\frac{1}{n}}{n}$
$2.\displaystyle\quad \lim_{n \to \infty }\frac{n}{\frac{1}{\sin1}+\frac{1/2}{\sin1/2}+\frac{1/3}{\sin1/3}+\cdots+\frac{1/n}{\sin1/n}}
$
Thanks in advance.
Comment: try to prove: if $\lim_{n\to\infty}a_n=1$ then $\lim(a_1+\dots+a_n)/n=1$
Comment: @Tina : It's not true that $\displaystyle\sum_{i=1}^n n\sin\frac1n=1$.  But it is true that $\displaystyle\lim_{n\to\infty}n\sin\frac1n=1$.  That's what user8268 was suggesting you use.
Comment: @user8268 This is exactly the point where i stuck, how can I to prove that $\sum_{i=1}^{n}n\sin\frac{1}{n}=1$?
Comment: The first one: http://math.stackexchange.com/questions/390115/find-lim-limits-n-rightarrow-infty-dfrac-sin-12-sin-frac12-cdotsn
Answer: We will use unnecessarily explicit inequalities to prove the result.
In the first limit, the general term on top can be rewritten as $\dfrac{\sin(1/k)}{1/k}$. This reminds us of the $\frac{\sin x}{x}$ whose limit as $x\to 0$ we needed in beginning calculus.
Note that for $0\lt x\le 1$, the power series
$$x-\frac{x^3}{3!}+\frac{x^5}{5!} -\frac{x^7}{7!}+\cdots$$
for $\sin x$ is an alternating series. It follows that for $0\lt x\le 1$,
$$x-\frac{x^3}{6}\lt \sin x\lt x.$$
and therefore
$$1-\frac{x^2}{6}\lt \frac{\sin x}{x}\lt 1.$$
Put $x=1/k$. We get
$$1-\frac{1}{6k^2}\lt \frac{\sin(1/k)}{1/k} \lt 1.\tag{$1$}$$
Add up, $k=1$ to $k=n$, and divide by $n$ Recall that
$$\frac{1}{1^2}+\frac{1}{2^2}+\frac{1}{3^2}+\cdots =\frac{\pi^2}{6}.$$
We find that
$$1-\frac{\pi^2}{36n}\lt \frac{\sin1+2\sin\frac{1}{2}+3\sin\frac{1}{3}+\cdots+n\sin\frac{1}{n}}{n}\lt 1.$$
From this, it follows immediately that our limit is $1$.
A very similar argument works for the second limit that was asked about. It is convenient to consider instead the reciprocal, and calculate
$$\lim_{n \to \infty }\frac{\frac{1}{\sin1}+\frac{1/2}{\sin1/2}+\frac{1/3}{\sin1/3}+\cdots+\frac{1/n}{\sin1/n}}{n}.$$
We can then use the inequality
$$1\lt \frac{1/k}{\sin(1/k)} \lt \frac{1}{1-\frac{1}{6k^2}},$$
which is simple to obtain from the Inequalities $(1)$.
Having the $1-\frac{1}{6k^2}$ in the denominator is inconvenient, so we can for example use the inequality $\dfrac{1}{1-\frac{1}{6k^2}}\lt 1+\dfrac{1}{k^2}$ to push through almost the same proof as the first one.
Answer: As $n \to \infty , \sin(1/n)\to 1/n , n\sin(1/n)\to 1$. Now, by Cesaro mean
$\lim\limits_{n \to \infty} \sum_{1}^{n}n\sin(1/n)\to n$.
Distributing the it over numerator and denominator
$\lim\limits_{n \to \infty} \frac{\sum_{1}^{n}n\sin(1/n)}{n}= \frac{\lim\limits_{n \to \infty }n\sin(1/n)}{n}=1$
So, the answer to the first part is 1 . Same argument holds for the second part too.
Comment: $\sum_{1}^{n}n\sin(1/n)$ is not a very good notation, since you use $n$ both in range and as a variable. I think that $\sum_{k=1}^{n}k\sin(1/k)$ would be better.
Comment: Thanks for the edit Martin. This was my first answer at math stackexchange. Will keep it in mind.
Answer: the first one , you can use the stolz theorem directly.
or use the result:
if
$\lim\limits_{n\to \infty}a_n=a$, then $\lim\limits_{n\to \infty}\frac{a_1+a_2+.....a_n}{n}=a$, you can use the $\epsilon-N$ to illustrate it...
the second is the same
Comment: This is exactly the point where i stuck, how can I to prove that $\sum_{i=1}^{n}n\sin\frac{1}{n}=1$?Thanks.
Comment: your above gauss is wrong because $\lim\limits_(n\sin\frac{1}{n})\to 1$, therefore, the series cannot be convengent....

two limit questions related to $\sin$


Sum of exponential random variables follows Gamma, confused by the parameters

Question: I've learned sum of exponential random variables follows Gamma distribution.
But everywhere I read the parametrization is different.  For instance, Wiki describes the relationship, but don't say what their parameters actually mean?  Shape, scale, rate, 1/rate?
Exponential distribution:  $x$~$exp(\lambda)$
$$f(x|\lambda )=\lambda {{e}^{-\lambda x}}$$
$$E[x]=1/ \lambda$$
$$var(x)=1/{{\lambda}^2}$$
Gamma distribution: $\Gamma(\text{shape}=\alpha, \text{scale}=\beta)$
$$f(x|\alpha ,\beta )=\frac{1}{{{\beta }^{\alpha }}}\frac{1}{\Gamma (\alpha )}{{x}^{\alpha -1}}{{e}^{-\frac{x}{\beta }}}$$
$$E[x]=\alpha\beta$$
$$var[x]=\alpha{\beta}^{2}$$
In this setting, what is $\sum\limits_{i=1}^{n}{{{x}_{i}}}$?  What would the correct parametrization be?  How about extending this to chi-square?
Comment: As a rough-and-ready rule of thumb, probabilists tend to use $\Gamma(t,\lambda)$ to denote a Gamma distribution with mean $\frac{t}{\lambda}$ (that is, $f(x) = \frac{\lambda}{\Gamma(t)}\cdot (\lambda x)^{t-1}\exp(-\lambda x)\mathbf 1_{(0,\infty)}$ while statisticians tend to use $\Gamma(\alpha,\beta)$ to denote a Gamma random variable with mean $\alpha\beta$, not $\alpha/\beta$ the way you have it.  [Wikipedia](http://en.wikipedia.org/wiki/Gamma_distribution) describes both conventions.
Comment: Two hints: 1. remember to check by dimensionality consistency. (eg. does the parameter have the same dimensionality of $x$, or its recyprocal...?)  2. because here the parameter of the gamma is an integer, it might be slightly easier to use plain factorials, and the Erlang distribution (of course, it's the same)
Comment: sorry, you are correct.
Comment: @edwin So please edit your question to correct the expressions for mean and variance.
Comment: @DilipSarwate edited!
Comment: If you write $x/\text{parameter}$ in the density, you have a scale parameter. If you write $x\cdot \text{parameter}$ in the density you have a rate parameter (there are other parameterizations still). Just be sure to use the same parameterization throughout -- if you need to switch to a different parameterization you either do it at the very start or the very end.
Answer: The sum of $n$ iid exponential distributions with scale $\theta$ (rate $\theta^{-1}$) is gamma-distributed with shape $n$ and scale $\theta$ (rate $\theta^{-1}$).
Comment: @jbuddy_13 Yes.
Comment: So, if an event such as time for a webpage to process a hit request was exponentially distributed, Gamma might be used to model the time it takes to process x hit requests? (Assumes only 1 hit could be processed at a time, which is an illustrative assumption but not a practical/plausible one.)
Comment: So, a Gamma dist is both an rv and a process (collection of rvs indexed over time or space.) I always figured it was one or the other, but sounds like a process is a special type of rv.
Answer: The sum of $n$ independent Gamma random variables $\sim \Gamma(t_i, \lambda)$ is a Gamma random variable $\sim \Gamma\left(\sum_i t_i, \lambda\right)$. It does not matter what the second parameter means (scale or inverse of scale) as long as all $n$ random variable have the same second parameter.  This idea extends readily
to $\chi^2$ random variables which are a special case of Gamma random variables.
Comment: I am not referring to your link.
Comment: If you think that is confusing, wait till you encounter normal random variables.  There are _at least_ [three different interpretations](http://stats.stackexchange.com/a/19301/6633) of $X \sim N(\mu,s)$ that statisticians use.
Comment: The thing that confuses me is some books write $exp(\lambda)$ where $\lambda$ is the rate, while others meant 1/rate.  Is there a consistent notation?  Unless I see the pdf, I will not know what they mean.
Comment: lol, that is just ruining innocent souls that want to study the subject.  I personally think that is just poorly written on the author's part, at the same time, I do agree that I need to adapt the ability to spot wrong things.  But still, not when I am taking baby steps.
Comment: Oh well, as the author of the Answer to the other Question, I am disappointed that you think that that Answer is poorly written. Suggestions for improving it are most welcome.
Answer: gamma distribution is made of exponential distribution that is exponential distribution is base for gamma distribution.
then if $f(x|\lambda)=\lambda e^{−\lambda x}$ we have $\sum_n x_i \sim \text{Gamma}(n,\lambda)$, as long as all $X_i$ are independent.
$$f(x|\alpha,\beta)=\frac{\beta^α}{\Gamma(\alpha)} \cdot x^{\alpha−1} \cdot e^{−x\beta} $$
Comment: Your assertion $\sum x_i \sim \text{Gamma}(n,\lambda)$ is incorrect unless you qualify it by insisting that the $x_i$ are _independent_ random variables.
Comment: I formatted the maths part of your answer. Please check if this is still what you wanted to express.


Save Excel as PDF

Question: I open an Excel file in c#, make some changes and I want to save it as pdf file.
I have searched about it and find this:
Microsoft.Office.Interop.Excel._Workbook oWB;
oWB.ExportAsFixedFormat(XlFixedFormatType.xlTypePDF, "D:\\xxxxx.pdf");

but this code sometimes opens a form and a printer must be selected! I don't know why?!
Is there any other way for exporting PDF from Excel?
I saw that Workbook.saveas() has a Fileformat object. How can we use it?
Comment: U can go with [this](https://sautinsoft.com/convert-excel-xls-to-pdf/xlsx-to-pdf-dotnet-csharp.php)
Comment: What is a Charp?
Comment: @Taw sorry csharp (C#) . i have missed 's'
Answer: Check out Spire.Xls, below is the code for converting Excel to PDF.
Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

//If you want to make the excel content fit to pdf page
//workbook.ConverterSetting.SheetFitToPage = true;

workbook.SaveToFile("result.pdf", Spire.Xls.FileFormat.PDF);

It has a free version which you can use without charge:
https://www.e-iceblue.com/Introduce/free-xls-component.html (Also available on NuGet)
Comment: I didn't know why someone vote not useful. This answer shows other way for exporting PDF from excel.
Answer: If you're looking for an alternative approach, then check out GemBox.Spreadsheet:
https://www.nuget.org/packages/GemBox.Spreadsheet/
Here is how you can save Excel to PDF with it:
ExcelFile excel = ExcelFile.Load("D:\\xxxxx.xlsx");
excel.Save("D:\\xxxxx.pdf");

Or you can write it as following:
XlsxLoadOptions loadOptions = new XlsxLoadOptions();
ExcelFile excel = ExcelFile.Load("D:\\xxxxx.xlsx", loadOptions);

PdfSaveOptions saveOptions = new PdfSaveOptions();
excel.Save("D:\\xxxxx.pdf", saveOptions);

Comment: I didn't know why anyone vote not useful. This answer shows other way for exporting PDF from excel.
Answer: Use iTextSharp.  It is native .NET code.  Doesn't require any Excel interop -
https://www.nuget.org/packages/itextsharp/
Comment: How can you save Excel to PDF with iTextSharp? To my understanding that library doesn't support reading Excel files....
Comment: @NixonUposseen I thought it would be obvious.  But you would just use https://www.nuget.org/packages/ExcelDataReader/ first
Comment: Also, I was unable to find any build-in interoperability between these two libraries, have you accomplished this task with them? If yes, your answer currently lacks any decent information about how we can do that...
Answer: You can do this using this API. Please see documentation for further detail.
http://cdn.bytescout.com/help/BytescoutPDFExtractorSDK/html/55590148-5bef-4338-ac16-1de4056a952b.htm
Comment: I think he wants to go the other way: save an Excel file as a PDF, not parse a PDF into Excel.
Comment: But I believe if he can explore the documentation, he will definitely find a solution there. As these packages provide both Excel to PDF and also PDF to excel. But the thing is he may explore. I am suggesting this because this API was a life savor for me when I stuck in the same type of issues. You can explore yourself, here is the link to that http://cdn.bytescout.com/help/BytescoutPDFSDK/index.html?_ga=2.60376301.1763457983.1520808212-62881910.1507833269

Save Excel as PDF


how can i import member in civicrm Drupal

Question: Hi, I have a csv file with all member information. I want to import this file in civicrm. Although i have seen an import option in the civicrm menu, that option is not working for me. I have many other fields which are not present in the import option.
How can i import a csv file in civicrm?
Answer: A good way to start is by exporting into a csv and then you can see what the Primary fields are. Do a search then select a contact and on the 'Actions' dropdown box select 'Export Contacts'. A wizard will guide you. Select Primary Fields for you first attempt. Open the exported CSV file in Excel and see about 75 Primary fields. If you need something more you can add custom fields to CiviCRM.
When you want to import your own CSV you will need to map your fields to CiviCRM fields.
Try it on the CiviCRM demo site http://drupal.demo.civicrm.org/


Why isn't my database being created in ASP.NET MVC4 with EF CodeFirst

Question: I've been following along with a tutorial by Julie Lerman about using EF CodeFirst to generate the database from code.  I'm using MVC4 and working with the default controllers.  All I want to do is generate the database.  However, in her tutorial, she's working with a console application and calling a create_blog method in her Main function.  The create_blog function does the work of creating the database as the name suggests.
In my Global.asax, I have this:
Database.SetInitializer(new CIT.Models.SampleData());

This is my SampleData class:
 public class SampleData : CreateDatabaseIfNotExists<Context>
    {
        protected override void Seed(Context context)
        {
            base.Seed(context);

            new List<Software> {
                    new Software { Title = "Adobe Creative Suite", Version = "CS6", SerialNumber = "1234634543", Platform = "Mac", Notes = "Macs rock!", PurchaseDate = "2012-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Adobe" }}},
                    new Software { Title = "Apple iLife", Version = "2012", SerialNumber = "123463423453", Platform = "Mac", Notes = "Macs still rock!", PurchaseDate = "2012-11-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "81st Street" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Apple" }}},
                    new Software { Title = "Microsoft Office", Version = "2012", SerialNumber = "12346231434543", Platform = "PC", Notes = "Macs really rock!", PurchaseDate = "2011-12-04", Suite = true, SubscriptionEndDate = null, SeatCount = 4, SoftwareTypes = new List<SoftwareType> { new SoftwareType { Type="Suite" }}, Locations = new List<Location> { new Location { LocationName = "Paradise" }}, Publishers = new List<SoftwarePublisher> { new SoftwarePublisher { Publisher = "Microsoft" }}}
                }.ForEach(s => context.Software.Add(s));

        }
    }

I get no errors when I compile.  I just get no database. I looked in my App_Data and all that's there is the default database.  I have a dbContext that is getting called because when I had errors in it, they pointed to that file.  Do I need to have some kind of create method that is called when the site first compiles?
Answer: SetInitializer only sets the initializer strategy and the strategy is executed the first time you access the database. Try adding the following after calling SetInitializer
using (var context = new Context()) { context.Database.Initialize(true); }

Comment: Nope.  That didn't do it.  Shouldn't it be creating a connection string in my web.config?
Comment: If you haven't specified a default connection factory in your web.config, Code First uses the [SqlConnectionFactory](http://msdn.microsoft.com/en-us/library/system.data.entity.infrastructure.sqlconnectionfactory(v=vs.103).aspx) pointing to .\SQLEXPRESS. So have a look in your .\SQLEXPRESS instance.
Comment: SetInitializer only sets the initializer strategy and the strategy is executed the first time you access the database. Try adding the following after calling SetInitializer `using (var context = new Context())
            {
                context.Database.Initialize(true);
            }`
Comment: I put it in my Application_start after the SetInitializer call and got this error: Error 1 'System.Web.HttpApplication.Context' is a 'property' but is used like a 'type' D:\Websites\CIT\CIT\Global.asax.cs 21 38 CIT
Comment: Namespace issue.  Fixed it.


How to Parse a String to Double

Question: Here is my string
  20.0e-6

I'm parsing it like
String Ans=Double.Parse("20.0e-6")

Now i'm getting the result like  2E-05
But the required output should be like
            0.00002
How to get this?
Comment: Your problem has nothing to do with parsing a string to double, but with converting a double to string.
Comment: yeah.... you are correct. But i need a string `0.00002` and not `2E-05`
Comment: Is that legal C#... or is it VB?
Comment: Why isn't it? String can be capitalised, and variable names can be also.
Comment: @Miguel: Thanks, forgot string and String are the same in C#.
Answer: The result of Double.Parse is a Double, not a string. You need to output a string from the double, using ToString.
You should also use an overload of Double.Parse that has a NumberStyles parameter. Using the Float value allows exponent notation:
string Ans=Double.Parse("20.0e-6", NumberStyles.Float).ToString("0.#####");

If you don't want to risk exceptions (InvlidCastException for example), you can use TryParse:
Double res;
if (Double.TryParse("20.0e-6", NumberStyles.Float,
                    CultureInfo.InvariantCulture ,res))
{
  string Ans = res.ToString("0.#####");
}

Comment: I would recommend using the TryParse method on Double instead (best practice and all).
Comment: `Cannot implicitly convert type 'double' to 'string'`.
String Ans=Double.Parse("20.0e-6", NumberStyles.Float).ToString() gives the same result
Comment: @Pramodh - Of course. You are trying to convert a string to a Double, then assign the result back to a string. As for the error with `ToString` - you need to provide a format string for it to convert properly. Answer updated.
Answer: It's the same number, but if you want to modify the output of the string, use a formatter on your ToString()
http://msdn.microsoft.com/en-us/library/dwhawy9k.aspx
So
String Ans=Double.Parse("20.0e-6").ToString("0.0####")

Comment: Yeah it'll definitely crash. In reality you're best off using TryParse and applying String.Format("{0:0.0####", myDouble). I just wanted to illustrate the use of ToString to format the number.
Answer: One way to get the result you want is to use String.Format as follow:
double x = 20.0e-6;

string y = string.Format("{0:0.######}",x);

Console.WriteLine(y);

Given your example, this outputs the value 0.00002
EDIT
I've just realised that this is actually the opposite of your question so in the aim of keeping the answer useful i'll add the following:
Given a string, you can parse as double and then apply the same logic as above. Probably not the most elegant solution however it offers another way to get the result you want.
string x = "20.0e-6";

var y = double.Parse(p);

Console.WriteLine(String.Format("{0:0.######}",y));

Comment: agreed. I was keeping it simple and assuming the coder already follows good practices.
Comment: What if my source string has a typo in it?? E.g. 20.0f-06 .....  I would always recommend using `double.TryParse` ....

How to Parse a String to Double


Creating a bat file which executes SQL scripts

Question: I have a folder into which a number of MSQL scripts get dropped into after each weekly sprint. For example, 10 scripts were placed into the folder today. I had to then open each script individually and run it against the applicable database. The database that it needs to be run against is in the name of the file.
e.g. [2] [CRMdata]UpdateProc.sql
The [2] represents the sequence in which it is run, so script [1] needs to be run before it.
[CRMdata] is the database I have to run it against.
This process is very tiresome, especially if there are 50 scripts to run sequentially.
I was wondering if there was an easier way to do this?
Perhpas a .bat file, which reads the filename, and executes the scripts sequentially based on the script number, as well as executing it against the database specified in the file name.
Any help is much appreciated.
Thanks.
Comment: I'm assuming this is Windows, since you say "batch file". You'll have a less frustrating time if you use a better scripting language, such as VBscript or Javascript via Windows Scripting host, or Powershell. With one of these, it would be more or less trivial to do (read the file names, parse them and build your commands).
Comment: What is `MSQL`? `MS SQL` or `MySQL`?
Comment: I would definately use VBScript for this one. Use FileSystemObject to get the list of scripts.
Answer: First, when you need to run things, consider using SQL Server Job Agent.  This is a good way to schedule simple things.
For a task like this, I would recommend PowerShell in combination with "sqlcmd".  This command is actually the answer to your question, since it will run scripts from the command line.
However, go a step further.  Schedule a job that runs once per week (or whenever you want it run).  Have it consist of one step, a PowerShell script.  This can then loop through all the scripts in the directory, extract the file name from the name, and run the script using sqlcmd.  Along the way, also log what you are doing in a table so you can spot errors.
Answer: I don't know anything about executing SQL with MSQL. You will have to work out how to run each script against the proper database using whatever command-line utility is provided for MSQL.
I can help you with a batch file that will sort the SQL files in the correct sequence order, and parse out the name of the database.
The job is much easier in batch if the sequence numbers are zero prefixed to be a constant width. I'm assuming it is OK to rename the files, so that is what this solution does.
I also assumed you will never have more than 999 files to process. The code can easily be modified to handle more.
Some changes will have to be made if any file names contain the <code>!</code> character because delayed expansion will corrupt the expansion of the FOR variables. But that is an unlikely problem.
<code>@echo off
setlocal enableDelayedExpansion

:: Change the definition to point to the folder that contains the scripts
set "folder=sqlCodeFolder"

:: The mask will only match the pattern that you indicated in your question
set "mask=[*] [*]*.sql"

:: Rename the .sql files so that the sequence numbers are zero prefixed
:: to width of 3. This enables the default alpha sort of the directory to be
:: in the proper sequence
for /f "tokens=1* delims=[]" %%A in ('dir /b "%folder%\%mask%"') do (
  set seq=00%%A
  ren "%folder%\[%%A]%%B" "[!seq:~-3!]%%B"
)

::Process the renamed files in order
for %%F in ("%folder%\%mask%") do (
  for /f "tokens=2 delims=[] " %%D in ("%%~nF") do (
    rem %%F contains the full path to the sql file
    rem %%D contains the name of the database, without enclosing []
    rem Replace the echo line below with the proper command to run your script
    echo run %%F against database [%%D]
  )
)
</code>


Does C# app exit automatically dispose managed resources?

Question: I am fully aware that using statements are the way to handle IDisposables. Please do not repeat this advice in comments.
When a C# .NET 4.5 (or higher) application closes, what happens to the IDisposables which were not properly disposed?
I know some have a finalizer for disposing unmanaged resources.
But let's say I have a console app, with a static Stream variable. Is it disposed when I close the console app?
What about a HttpClient? And how do you know in which situations it does and in which is does not?
Alright, now some actual background info. I often store certain IDisposables as fields, forcing my class to implement IDisposable. The end user should use using. But what if that does not happen?
Is it merely unnecessary memory until GC? Or do you suddenly have a memory leak?
Comment: Short answer: [no](https://ericlippert.com/2015/05/18/when-everything-you-know-is-wrong-part-one/)
Answer: It's important to distinguish between objects implementing IDisposable and objects with finalizers. In most cases (probably preferably all), objects with finalizers also implement IDisposable but they are in fact two distinct things, most often used together.
A finalizer is a mechanism to say to the .NET Runtime that before it can collect the object, it has to execute the finalizer. This happens when the .NET Runtime detects that an object is eligible for garbage collection. Normally, if the object does not have a finalizer, it will be collected during this collection. If it has a finalizer, it will instead be placed onto a list, the "freachable queue", and there is a background thread that monitors this thread. Sometimes after the collection has placed the object onto this queue, the finalizer thread will process the object from this queue and call the finalizer method.
Once this has happened, the object is again eligible for collection, but it has also been marked as finalized, which means that when the garbage collector finds the object in a future collection cycle, it no longer places it on this queue but collects it normally.
Note that in the above paragraphs of text, IDisposable is not mentioned once, and there is a good reason for that. None of the above relies on IDisposable at all.
Now, objects implementing IDisposable may or may not have a finalizer. The general rule is that if the object itself owns unmanaged resources it probably should and if it doesn't it probably shouldn't. (I'm hesitant to say always and never here since there always seems to be someone that is able to find a cornercase where it makes sense one way or another but breaks the "typically" rule)
A TL;DR summary of the above could be that a finalizer is a way to get a (semi-)guaranteed cleanup of the object when it is collected, but exactly when that happens is not directly under the programmers control, whereas implementing IDisposable is a way to control this cleanup directly from code.
Anyway, with all that under our belt, let's tackle your specific questions:

When a C# .NET 4.5 (or higher) application closes, what happens to the IDisposables which were not properly disposed?
Answer: Nothing. If they have a finalizer, the finalizer thread will try to pick them up, since when the program terminates, all objects become eligible for collection. The finalizer thread is not allowed to run "forever" to do this, however, so it may also run out of time. If, on the other hand, the object implementing IDisposable does not have a finalizer it will simply be collected normally (again, IDisposable has no bearing at all on garbage collection).

But let's say I have a console app, with a static Stream variable. Is it disposed when I close the console app?
Answer: No, it will not be disposed. Stream by itself is a base class, so depending on the concrete derived class it may or may not have a finalizer. It follows the same rule as above, however, so if it doesn't have a finalizer it will simply be collected. Examples, MemoryStream does not have a finalizer, whereas FileStream does.

What about a HttpClient? And how do you know in which situations it does and in which is does not
Answer: The reference source for HttpClient seems to indicate that HttpClient does not have a finalizer. It will thus simply be collected.

Alright, now some actual background info. I often store certain IDisposables as fields, forcing my class to implement IDisposable. The end user should use using. But what if that does not happen?
Answer: If you forget/don't call IDisposable.Dispose() on objects implementing IDisposable, everything I've stated here regarding finalizers will still happen, once the object is eligible for collection. Other than that, nothing special will happen. Whether the object implements IDisposable or not have no bearing on the garbage collection process, only the presence of a finalizer has.

Is it merely unnecessary memory until GC? Or do you suddenly have a memory leak
Answer: Undetermined from this simple information. It depends on what the Dispose method would do. For instance, if the object has registered itself somewhere so that there is a reference to it, somewhere, for some code to stop using the object may not actually make the object eligible for collection. The Dispose method might be responsible for unregistering it, removing the last reference(s) to it. So this depends on the object. Merely the fact that the object implements IDisposable does not create a memory leak. If the last reference to the object is removed, the object becomes eligible for collection and will be collected during a future collection cycle.

Remarks:

Note that the above text is also probably simplified. A full collection cycle to actually "collect memory" is probably not done on application termination as there is no point. The operating system will free the memory allocated by the process when it terminates anyway. When an application terminates, .NET Framework makes every reasonable effort to call finalizers for objects that haven't yet been garbage collected, unless such cleanup has been suppressed (by a call to the library method GC.SuppressFinalize, for example). .NET 5 (including .NET Core) and later versions don't call finalizers as part of application termination.1 (I have no additional knowledge one way or another what kind of optimizations is done here)

The more important part here is that you need to distinguish between memory (or other) leaks during program execution and after program execution

When the process terminates, the operating system will reclaim all memory allocated to it, it will close all handles (which may keep sockets, files, etc. open), all threads will be terminated. In short, the program is completely removed from memory
The process may have left tidbits of itself around though, which are not cleaned up unless the process took care to do this beforehand. An open file is closed, as stated above, but it may not have been completely written and thus may be corrupt in some way.
During program execution, leaks may make the program grow in terms of allocated memory, it may allocate too many handles because it fail to close the ones it no longer needs, etc. and this is important in terms of handling IDisposable and finalizers correctly, but when the process terminates, this is no longer a problem.
Comment: I don't think anything gets 'collected' when an application exits. That would be so pointless. Finalized maybe.
Comment: Yep, I doubt it as well, but I'm not sure there are two pieces of code that finds objects for finalization either, it may be that they just ask GC to run a full cycle to identify these objects, but this is far beyond my knowledge.
Comment: Objects with a finalizer (~destructor) are kept on the Finalizer Queue. No need to do a memory sweep to find them. That's the queue where you kick them out with SuppressFinalize .
Comment: Are you saying they are added to that queue when constructed? I thought they were added as part of GC?
Comment: @LasseVågsætherKarlsen there are two finalization-related queues - finalization queue stores a list of all objects with finalizers (populated when such object is being created) and freachable queue (populated by moving references from finalization queue when an object would be normally collected)
Answer: Nothing gets disposed automatically, ever.
Classes that implements the IDisposable interface are designed like that because they either use IDisposable fields (like in your case) or the use unmanaged resources (There are exceptions to this rule, but that's out of scope for this answer).
There is no part of the CLR that calls the Dispose method.
The GC will collect the reference and unless instructed otherwise (by using GC.SuppressFinalize(), will then move the reference to the finalizer queue, where
it will finalized by calling it's finalize method.
If, and only if, the class have explicitly override the finalize method and  calls Dispose in the finalize method, then the instance will finally be disposed.
So, if you want to ensure your classes gets disposed by the finalizer, you must override the finalize method in your class. However, Beware - Implementing the Finalize method correctly is hard!
That being said, when you implement the IDisposable interface, you are telling whoever is using this class that it should be disposed. Whether they actually dispose it or not is no longer your responsibility - it's theirs. So if there actually is a memory leak (and that's quite possible there will be one) - assuming your class implemented the IDisposable interface correctly, that's not your problem.
Comment: Points for "Nothing gets disposed automatically, ever."
Comment: But they do... Ever disposed the iterator of a foreach() ?  or a Thread?
Comment: IEnumeable produces an  `Iterator : IDisposable`
Comment: Doesn't "because the c# compiler explicitly calls it's Dispose" mean something gets disposed automatically?
Comment: @ZoharPeled: My point was that even though non-generic `IEnumerable` does not implement `IDisposable`, the code generated by `foreach` will call an `IDisposable.Dispose` method if the object instance is of a class which implements that interface.  Not to say when programmers should call the method, but to mention a case where it will get called automatically even though it's not obvious that it will.
Comment: @bommelding [`System.Threading.Thread`](https://learn.microsoft.com/en-us/dotnet/api/system.threading.thread?view=netframework-4.7.2) does not implement the `IDisposable` interface, and as for the iterator of a foreach, I'm not sure what you mean by that.
Comment: @bommelding This iterator is being disposed because the c# compiler explicitly calls it's Dispose method. If you look at [c# specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/statements#iteration-statements), scroll down to the `foreach` statement, you will see exactly how it's done.
Comment: @bommelding Also, btw, `IEnumerable` produces an `IEnumerator`, that does not implement the `IDisposable` interface. An `IEnumerable` produces an `IEnumerator` that does implement the `IDisposable` interface.
Comment: @bommelding well, if you want to nitpick, then yes, I guess that's automatic.
Comment: @ZoharPeled: Some implementations of `IEnumerable` do implement `IDisposable` and `foreach` will, if given a class that implements `IEnumerable` but not `Enumerable`, generate code that checks whether the supplied instance implements `IDisposable` and call its dispose method if so.  Some collections may enumerate very slowly if many enumerators are created and abandoned without being disposed, and without an intervening GC cycle.
Comment: @supercat this post is almost 4 years old now, and if I was to write it today I would probably do it a little differently. My point was that some code has to call the `Dispose` method, since the run time doesn't do that automatically (even if this code was automatically generated by the compiler).
Answer: The process is about to disappear. That means the OS is going to stop providing any memory to support that process's address space1. All memory is "reclaimed" anyway. It's also going to terminate all threads within the process. So no further processing will occur. All handles will be closed anyway.
The things you have to worry about are the external realities. E.g. if you have an undisposed Stream, has it flushed everything it needs to if it's attached to something over the network or a file?
Yes, if you're storing Disposables yourself, you should implement IDisposable. But if you don't have any unmanaged resources, don't implement a finalizer. By the time a finalizer runs, you shouldn't be accessing any other managed objects from that code, so it's too late to dispose of them.
If someone forgets to Dispose your objects, that's their error, and you've done as much as you should by advertising that you should be disposed via the IDisposable interface.

1Processes don't have memory. They have an address space managed by the OS. At times, it may be necessary that some parts of that address space are in memory. That's the OS's job in the age of virtual memory, and it only every really "loans" the physical memory temporarily to any given process. It can take it away again at any time
Comment: Points for the better explaining of "processes don't have memory".
Answer:
Does C# app exit automatically dispose managed resources?

Well, yes and no, but technically: no.
If the IDisposable interface is implemented correctly, the dispose function will be called when the object is collected. If it isn't correctly implemented, there will be a leak if unmanaged resources are used.

When a C# .NET 4.5 (or higher) application closes, what happens to the IDisposables which were not properly disposed?

The process space is freed. If the IDisposable implicitly reserves memory in other process spaces, and is not correctly disposed: you have a leak.

But let's say I have a console app, with a static Stream variable. Is it disposed when I close the console app?

It is, although implicit, it can lead to unexpected result for example when you kill the process. For example: a TCP port might be in a wait state.

What about a HttpClient? And how do you know in which situations it does and in which is does not?

Same as above.

Alright, now some actual background info. I often store certain IDisposables as fields, forcing my class to implement IDisposable. The end user should use using. But what if that does not happen?

You should implement it correctly, but advise to dispose. For example a file handle. If it isn't properly disposed, another call to the file might fail because the file is still open. This might be resolved at GC, but you don't know when.

Is it merely unnecessary memory until GC? Or do you suddenly have a memory leak?

It more, leaks, open ports, open handles, video memory consumption etc.

For a correct implementation of IDisposable see: Proper use of the IDisposable interface
If you read it, you can imagine not all 3th party lib's are implementing it correctly.


On execution of following program I'm getting this error Line 11 if list[mid]<n: IndentationError: expected an indented block

Question: pos = -1
def search(list, n):
<code>l = 0
u = len(list)-1

while l <= u:
    mid = (l+u) // 2

    if list[mid] == n:
        globals()['pos'] = mid
        return True
    else:
        if list[mid] < n:
            l = mid+1;
        else:
            u = mid-1;

return False
</code>
list = [4,7,8,12,45,99,102,702,10987,56666]
n = 10
if search(list, n):
print("Found at ",pos+1)
else:
print("Not Found")
Answer: It works fine, i think you have a different white space in line number 11. Try to update white spaces. You should only have tabs or spaces, you should not mix them.


Markov Chain with two components

Question: I am trying to understand a question with the following Markov Chain:

As can be seen, the chain consists of two components. If I start at state 1, I understand that the steady-state probability of being in state 3 for example is zero, because all states 1,2,3,4 are transient. But what I do not understand is that is it possible to consider the second component as a separate Markov chain? And would it be correct to say that the limiting probabilities of the second chain considered separately exist? For example, if I start at state 5, then can we say that the steady-state probabilities of any of the states in the right Markov chain exist and are positive?
Answer: Yes, you can. Actually this Markov chain is reducible, with two communicating classes (as you have correctly observed),

$C_1=\{1,2,3,4\}$, which is not closed and therefore any stationary distribution assigns zero probability to it and
$C_2=\{5,6,7\}$ which is closed.

As stated for example in this answer,

Every stationary distribution of a Markov chain is concentrated on the closed communicating classes.

In general the following holds

Theorem: Every Markov Chain with a finite state space has a unique stationary
  distribution unless the chain has two or more closed communicating classes.
Note: If there are two or more communicating classes but only one closed then the stationary
  distribution is unique and concentrated only on the closed class.

So, here you can treat the second class as a separate chain but you do not need to. No matter where you start you can calculate the steady-state probabilities and they will be concentrated on the class $C_2$.
Comment: Yeah, I see that little block in bottom-right corner of transition matrix :) $$\begin{pmatrix}
0 &\frac{1}{2} & \frac{1}{2} & 0 & 0 & 0 & 0\\
\frac{1}{2}& 0 & 0 & \frac{1}{2} & 0 & 0 & 0\\
\frac{1}{3} &\frac{1}{3} & \frac{1}{3} & 0 & 0 & 0 & 0\\
0 &\frac{1}{2}& 0 & 0 & \frac{1}{2} & 0 & 0\\
0 & 0 & 0 & 0 & 0 & 1 & 0\\
0 & 0 & 0 & 0 & \frac{1}{2} & 0 & \frac{1}{2}\\
0 & 0 & 0 & 0 & 0 & 1 & 0
\end{pmatrix}$$
Comment: When studying long-run behaviors we focus only on the recurrent classes. Limiting probabilities and stationary are different (but limiting are a subset of stationary). This is for the reason that for example the sequence $\{0,1,0,1,0,1,\ldots\}$ does not have a limit, but spends $1/2$ of time in state $0$ and $1/2$ of the time in $1$. So, to return to your question, the class $C_2$ is ergodic etc. but not the chain as a whole. Depending on the definition you can say that the limiting distribution is $0$ for states in $C_1$ but is better to say that you focus on $C_2$.
Comment: @Stef Thanks so much for the answer. One more thing that I am confused about. I read that a Markov Chain can only be considered to have a limiting distribution (and are ergodic) if "all" of its states are irreducible and non-transient, so when we obtain the steady-state probabilities by solving the simultaneous equations of the system as a whole, aren't they a limiting distribution? Or is there a difference between having a limiting distribution and being ergodic? Can we have a limiting distribution without the chain being ergodic?

Markov Chain with two components


ChatBot responder somente quando uma palavra específica estiver contida na frase

Question: Estou criando um ChatBot no Telegram que pode responder a perguntas de usuários do grupo. O bot precisa de uma palavra-chave para começar a conversar. Essa palavra seria o seu nome, "Joker". Assim, somente quando a palavra Joker fosse mencionada em uma frase ele começaria a interagir com os usuários do grupo ou quando uma resposta fosse encaminhada a ele. Utilizando Python 3.7.4.
Exemplo:

Usuário: Acho que o Joker entende mais desse assunto
Bot: Que assunto?
Usuário: Sobre a matança de focas no sertão do Ceará, Joker.
Bot: Sobre o que você está falando?

Mas não tenho ideia de como implementar essa ação.
def respond(self, message):
    """
   Receive message from user and returns corresponding answer.
   """
    if len(message) > 50 and self.watson_usage:
        top_answer = get_analysis(message)
        return f"Hmm, você está falando sobre {top_answer}"
    elif re.search("Joker", message) or len(message) > 0:
        return self.comm.get_response(self.clean(message))
    else:
        return "Algo de errado não está certo"\
               " Digite /info para saber mais."

Comment: Você precisa ter uma lista de comandos predefinidos. Se você está buscando fazer algo como a assistente da Google (que responde inúmeras perguntas formuladas das mais diferentes formas, além de ser tolerante a erros), tenha um orçamento de milhões de dólares primeiro.
Comment: Eu já possuo um arquivo .yml com inúmeras perguntas e respostas predefinidas. Ele não precisa ser tolerante a erros. Não é algo assim "astronômico" ao estilo Assistente do Google. O ChatBot em si, funciona sem problemas, respondendo as perguntas ou dando uma resposta padrão quando não tem uma resposta em seu banco de dados. Mas, a intenção é a de ele responder no grupo, somente quando o nome dele fosse mencionado em uma frase e não, ficar respondendo a qualquer mensagem que é enviada no grupo, como é o que acontece.
Answer: O que eu percebo no seu código, é que a primeira condição não verifica se existe "joker" na mensagem. Presumo que ele está resondendo sempre "Hm, você está falando sobre ..."
Para corrigir somente isto, mude a primeira condição para:
if 'Joker' in message and len(message) > 50 and self.watson_usage:

Caso você não entenda Python, a condição verifica:

Se 'Joker' está na mensagem
Se a mensagem contém mais de 50 caracteres
(Presumo eu) se você excedeu a sua cota do IBM Watson

Do jeito que está, joker precisa ter a primeira letra maiúscula para disparar o código. Suponho que o ideal seria que ele respondesse a qualquer combinação de minúsculas e maiúsculas.
Neste caso, este é o código:
def respond(self, message):
    """
    Receive message from user and returns corresponding answer.
    """
    if re.search("joker", message, re.IGNORECASE):
        joker_na_mensagem = True
    else:
        joker_na_mensagem = False

    if joker_na_mensagem and len(message) > 50 and self.watson_usage:
        top_answer = get_analysis(message)
        return f"Hmm, você está falando sobre {top_answer}"
    elif joker_na_mensagem and len(message.strip()) == len('joker'):
        return "Algo de errado não está certo. Digite /info para saber mais."
    elif joker_na_mensagem:
        return self.comm.get_response(self.clean(message))

Edit 1: alterei a segunda condição, onde (presumo) o bot iria responder a qualquer mensagem que tivesse mais que 0 caracteres, independentemente de ser mencionado. Eliminei o requisito dos caracteres, pois, se 'Joker' está na mensagem, quer dizer que ela é maior que 0 caracteres.
Edit 2: alterei a última condição. Agora, a função só retorna a mensagem de erro caso alguém mencione o bot e não diga mais nada. Ou seja:

Usuário: Joker
  Bot: Algo de errado não está certo [...]

Edit 3: altera a ordem das condições, pois a segunda condição anulava a terceira.
Comment: Como os caracteres foram insuficientes no comentário, coloquei como uma resposta abaixo.
Comment: Então, @SeuMadruga, eu estou utilizando o Python 3.7.4. Atualizei o código. O Bot persiste em reagir a qualquer mensagem enviada ao grupo. Isso parece ser coisa do Chaves. Tinha que ser o Chaves.
Comment: Houve um progresso.O Bot reage como erro a qualquer mensagem que não contenha Joker na frase e retorna uma das respostas predefinidas a perguntas que ele ainda não aprendeu.
Usuário: Olá

Bot: Algo de errado não está certo Digite /info para saber mais.

Usuário: Olá joker

Bot: Não compreendi, você pode me falar como eu deveria ter respondido?
Comment: Traceback (most recent call last):
  File "bot/application.py", line 19, in
    from bot.communication import Communication
  File "E:\01 - Projeto ChatBot Master\bot\communication.py", line 67
    joker_na_mensagem = True
                    ^
IndentationError: expected an indented block
Comment: @Jacob erro de identação. Tenta agora.
Comment: Agora acontece o seguinte:

File "E:\01 - Projeto ChatBot Master\bot\communication.py", line 74
    return f"Hmm, você está falando sobre {top_answer}"
    ^
SyntaxError: 'return' outside function
Comment: @Jacob Aparentemente, não há nada de errado. Você mexeu na identação? Eu já corrigi. Copia de novo e vê se funciona.
Comment: Não aparece mais nenhum erro. Porém, o Bot responde com "None" para mensagens que não contenha "Joker". E as que contém Joker na frase, ele responde com uma das respostas predefinidas, de que ele ainda não aprendeu. Não sei se seria possível, mas ele responder com as respostas já predefinidas. Tipo, que ele compreendesse a pergunta, ignorando o Joker na frase. O Joker na frase, faz com que ele não saiba dar uma resposta dentre todas as possíveis cadastradas. Desculpe se parecer confuso.
Comment: @Jacob é possível, mas está fora do escopo desta pergunta. Faça outra pergunta e elabore esta questão, e me avise aqui.
Comment: Então @SeuMadruga. Postei a nova pergunta.


How to record from amp to PC or Android device?

Question: I have a Blackstar FLY 3 amp (this: https://blackstaramps.com/product/fly-3/), which provides a 3.5 mm output jack. This works great for headphones, but I've had no success getting this signal to any of my Android devices or laptops.
Here are the things I've tried so far:

USB adapters. First, I think I mistakenly bought a USB adapter for speakers, so that failed. I then acquired this doodad: https://www.amazon.de/dp/B07N355W9M?psc=1&ref=ppx_yo2ov_dt_b_product_details , but that was also of no use.
Two different 3.5 mm male-male cables. One has two rings on the plugs at both ends, and the other has three. I plug one end into the amp, and the other into the Android or PC. Depending on which app and which input settings I use, I get either ambient mic sounds or silence on the line.

I suspect the problem has something to do with the cable. I guess the output is not sending on the "mic" channel, so my various devices don't see it.
Can somebody please suggest the right kind of cable for this purpose? Also, I'd love to know about a simple and effective (and preferably free) Android or Windows app that does this job. I'm using Audacity on the PC.
Comment: mobile phone 3.5mm inputs are typically 3-ring; PC ones are typically one. From [the manual](https://blackstaramps.com/wp-content/uploads/2021/08/fly-handbook.pdf), "This output emulates the tonal characteristics of a guitar speaker cabinet and
provides a natural valve overdrive tone for connection to a recording device or mixing desk, and for use with headphones. To make full use of the stereo reverb, use a stereo jack to two mono jacks splitter lead to feed two channels of the recording device or mixer. The output will also function into a mono guitar type lead."
Comment: In other words: your three-ring plug left one ring doing nothing in the amp, while your two-ring one was treated by the Android as output. Try a _one_-ring mono one, into the PC, or maybe a stereo-to-mono adapter.
Answer: You need a USB sound card with line input. Don't worry too much about distinction between "mobile" and "desktop" models, Android phones are more or less computers in this regard. Plug the headphone/line output from the amplifier to the input on the sound card. Adjust amp volume and input sensitivity/gain if you have one so that the input does not max out. That's it.
Recording through the 3.5mm jack will not work, because it is designed for headset with high impedance microphone. Even if you manage to build a cable that has the right connections, the signal levels will be too far off for the result to sound good. This is also the reason why cables like this aren't sold.


How can I get an HTTP response body as a string?

Question: I know there used to be a way to get it with Apache Commons as documented here:
http://hc.apache.org/httpclient-legacy/apidocs/org/apache/commons/httpclient/HttpMethod.html
...and an example here:
http://www.kodejava.org/examples/416.html
...but I believe this is deprecated.
Is there any other way to make an http get request in Java and get the response body as a string and not a stream?
Comment: Since the question and all the answers seem to be about apache libraries, this should be tagged as such. I don't see anything without using 3rdparty libs.
Comment: related: https://stackoverflow.com/questions/21574478
Answer: Here are two examples from my working project.

Using EntityUtils and HttpEntity
HttpResponse response = httpClient.execute(new HttpGet(URL));
HttpEntity entity = response.getEntity();
String responseString = EntityUtils.toString(entity, "UTF-8");
System.out.println(responseString);

Using BasicResponseHandler
HttpResponse response = httpClient.execute(new HttpGet(URL));
String responseString = new BasicResponseHandler().handleResponse(response);
System.out.println(responseString);

Comment: The only problem I faced with method 1 is, the entity object is consumed when you do `response.getEntity()` and it is now available as `responseString`. if you try to do a response.getEntity() again, it'll return `IllegalStateException`.
Comment: What is httpClient?!
Comment: @AndreasL. httpClient is of type HttpClient ( org.apache.commons.httpclient package)
Comment: Its so common to get the response content as string or byte array or something. Would be nice with an API directly on Entity to give you that. Having to look for this to find this util class.
Comment: I upvoted. Please consider adding the full "imports" statements.
Comment: Worked in my case - getting body from CloseableHttpClient response.
Comment: Worth noting that the first method will get you the response body regardless of the HTTP status, whereas the second method throws exception for non-2xx HTTP statuses.
Comment: How would you retrieve the response body for non-2xx HTTP statuses?
Comment: I am getting "Attempted read from closed stream." error while using body = EntityUtils.toString(response.getEntity());
Comment: You should add how you've instantiated `httpClient` as its not necessarily clear to all readers
Answer: Every library I can think of returns a stream. You could use IOUtils.toString() from Apache Commons IO to read an InputStream into a String in one method call. E.g.:
URL url = new URL("http://www.example.com/");
URLConnection con = url.openConnection();
InputStream in = con.getInputStream();
String encoding = con.getContentEncoding();
encoding = encoding == null ? "UTF-8" : encoding;
String body = IOUtils.toString(in, encoding);
System.out.println(body);

Update: I changed the example above to use the content encoding from the response if available. Otherwise it'll default to UTF-8 as a best guess, instead of using the local system default.
Comment: Actually charset is specified in contentType like "charset=...", but not in contentEncoding, which contains something like 'gzip'
Comment: this will corrupt text in many cases as the method uses the system default text encoding which varies based on OS and user settings.
Comment: @McDowell: oops thanks, I linked the javadoc for the method with encoding but I forgot to use it in the example. I added UTF-8 to the example for now, although technically should use the `Content-Encoding` header from the response if available.
Comment: this   function causes  the input stream  to  be closed, is there a  way @WhiteFang34 i  can print  my  response   and  continue  to  use the http  entity
Comment: Do I have to close the InputStream?
Comment: this is link for apache commons https://mvnrepository.com/artifact/commons-io/commons-io/2.11.0
Answer: Here's an example from another simple project I was working on using the httpclient library from Apache:
String response = new String();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("j", request));
HttpEntity requestEntity = new UrlEncodedFormEntity(nameValuePairs);

HttpPost httpPost = new HttpPost(mURI);
httpPost.setEntity(requestEntity);
HttpResponse httpResponse = mHttpClient.execute(httpPost);
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
    response = EntityUtils.toString(responseEntity);
}

just use EntityUtils to grab the response body as a String.  very simple.
Answer: This is relatively simple in the specific case, but quite tricky in the general case.
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet("http://stackoverflow.com/");
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
System.out.println(EntityUtils.getContentMimeType(entity));
System.out.println(EntityUtils.getContentCharSet(entity));

The answer depends on the Content-Type HTTP response header.
This header contains information about the payload and might define the encoding of textual data. Even if you assume text types, you may need to inspect the content itself in order to determine the correct character encoding. E.g. see the HTML 4 spec for details on how to do that for that particular format.
Once the encoding is known, an InputStreamReader can be used to decode the data.
This answer depends on the server doing the right thing - if you want to handle cases where the response headers don't match the document, or the document declarations don't match the encoding used, that's another kettle of fish.
Comment: how to get it as HashMap ? I get response as Json, how to read that?
Answer: Below is a simple way of accessing the response as a String using Apache HTTP Client library.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;

//...

HttpGet get;
HttpClient httpClient;

// initialize variables above

ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpClient.execute(get, responseHandler);

Answer: The Answer by McDowell is correct one. However if you try other suggestion in few of the posts above.
HttpEntity responseEntity = httpResponse.getEntity();
if(responseEntity!=null) {
   response = EntityUtils.toString(responseEntity);
   S.O.P (response);
}

Then it will give you illegalStateException stating that content is already consumed.
Answer: How about just this?
org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));

Answer: We can use the below code also to get the HTML Response in java
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.HttpResponse;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import org.apache.log4j.Logger;

public static void main(String[] args) throws Exception {
    HttpClient client = new DefaultHttpClient();
    //  args[0] :-  http://hostname:8080/abc/xyz/CheckResponse
    HttpGet request1 = new HttpGet(args[0]);
    HttpResponse response1 = client.execute(request1);
    int code = response1.getStatusLine().getStatusCode();

    try (BufferedReader br = new BufferedReader(new InputStreamReader((response1.getEntity().getContent())));) {
        // Read in all of the post results into a String.
        String output = "";
        Boolean keepGoing = true;
        while (keepGoing) {
            String currentLine = br.readLine();

            if (currentLine == null) {
                keepGoing = false;
            } else {
                output += currentLine;
            }
        }

        System.out.println("Response-->" + output);
    } catch (Exception e) {
        System.out.println("Exception" + e);

    }
}

Comment: This is a very good response, this is what I need to display, the response after posting data to the server. Well done.
Answer: Here is a vanilla Java answer:
import java.net.http.HttpClient;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest;
import java.net.http.HttpRequest.BodyPublishers;

...
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
  .uri(targetUrl)
  .header("Content-Type", "application/json")
  .POST(BodyPublishers.ofString(requestBody))
  .build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
String responseString = (String) response.body();

Comment: One correction! `.uri(URI.create(targetUrl))`, not `.uri(targetUrl)` !
Answer: Here's a lightweight way to do so:
String responseString = "";
for (int i = 0; i < response.getEntity().getContentLength(); i++) {
    responseString +=
    Character.toString((char)response.getEntity().getContent().read());
}

With of course responseString containing website's response and response being type of HttpResponse, returned by HttpClient.execute(request)
Answer: Following is the code snippet which shows better way to handle the response body as a String whether it's a valid response or error response for the HTTP POST request:
BufferedReader reader = null;
OutputStream os = null;
String payload = "";
try {
    URL url1 = new URL("YOUR_URL");
    HttpURLConnection postConnection = (HttpURLConnection) url1.openConnection();
    postConnection.setRequestMethod("POST");
    postConnection.setRequestProperty("Content-Type", "application/json");
    postConnection.setDoOutput(true);
    os = postConnection.getOutputStream();
    os.write(eventContext.getMessage().getPayloadAsString().getBytes());
    os.flush();

    String line;
    try{
        reader = new BufferedReader(new InputStreamReader(postConnection.getInputStream()));
    }
    catch(IOException e){
        if(reader == null)
            reader = new BufferedReader(new InputStreamReader(postConnection.getErrorStream()));
    }
    while ((line = reader.readLine()) != null)
        payload += line.toString();
}
catch (Exception ex) {
            log.error("Post request Failed with message: " + ex.getMessage(), ex);
} finally {
    try {
        reader.close();
        os.close();
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        return null;
    }
}

Answer: If you are using Jackson to deserialize the response body, one very simple solution is to use request.getResponseBodyAsStream() instead of request.getResponseBodyAsString()
Answer: Using Apache commons Fluent API, it can be done as mentioned below,
String response = Request.Post("http://www.example.com/")
                .body(new StringEntity(strbody))
                .addHeader("Accept","application/json")
                .addHeader("Content-Type","application/json")
                .execute().returnContent().asString();


node:internal/errors:464 ErrorCaptureStackTrace(err); ^ Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Question: Why do I keep getting this error?
Iam using nodejs, and am not that familiar with backend programming, so I cant really know whats going on,
If anyone is fimiliar with this error or knows what causing, PLEASE HELP ME
Here is my code??
    async function verify() {
        const ticket = await client.verifyIdToken({
            idToken: token,
            audience: CLIENT_ID,  // Specify the CLIENT_ID of the app that accesses the backend
        });
        const payload = ticket.getPayload();
        const userid = payload['sub'];
      }
      verify()
      .then(()=>{
          res.cookie('session-token', token);
          res.send('success')
      })
      .catch(console.error);

})

const stripe = require('stripe')(process.env.STRIPE_PRIVATE_KEY)

app.post("/create-checkout-session", async (req,res)=>{
    try{
const session = await stripe.checkout.sessions.create({
payment_method_types:['card'],
mode:'payment',
line_items: req.body.items.map(item=>{

    return{
        price_data:{
            currency:item.currency,
            product_data:{
                name:item.name
            },
            unit_amount: item.priceInCents,
        },
        quantity:item.quantity
    }
}),
success_url:`${process.env.SERVER_URL}/success.html`,
cancel_url:`${process.env.SERVER_URL}/cancel.html`
})
res.json({url:session.url})
    }catch(e){
res.status(500).json({error:e.message})
    }

    res.json({url:'Hi'})
})````

Answer: you are trying to set
Http headers after they are sent.
This error is occuring because your code is using res.json in both try and catch blocks. It means res.json() will be executed no matter error occurs or not. Which sends json response.
Then you are using res.json outside the try/catch blocks, it means you're trying to send response after it is already sent.
And that is causing this error.


C# How to fix this code from multi-line text to label on marquee text moving right to left?

Question: I made a program that text is moving right to left(marquee).
But, I can't make use multi-line text to label.
Who can help me?
single line text is good work. But if multi-line, just get last sentence.
<code>private void timer1_Tick(object sender, EventArgs e)
{
    string screentext = clsBas.SCREEN_TEXT;//include in Multi-line text;
    string[] result = screentext.Split(new string[] { "\r\n" }, StringSplitOptions.None);
    string space = "                          ";

    foreach (string news in result)
    {
       lblScreenText.Text = news + space;
       if (lblScreenText.Left < 0 && (Math.Abs(lblScreenText.Left) >
lblScreenText.Width))
       lblScreenText.Left = lblScreenText.Width;
       lblScreenText.Left -= 2;
    }
}
</code>
Answer: Try using Environment.NewLine and append to text.
Better way to do it, is to use textbox multi-line and make it read-only.


expressjs TypeError: Cannot set property 'session' of undefined

Question: Getting this error when trying to run start my express server with node server.js, and I can't seem to figure out what is the cause.  I believe that I have made my app up to date with express 4.0, but maybe someone can point out my error here:
/home/trevor.panhorst/public_html/server/routes/api.js:236
    req.session = null;
                ^
TypeError: Cannot set property 'session' of undefined
    at Object.exports.logout         (/home/trevor.panhorst/public_html/server/routes/api.js:236:17)
    at Object.<anonymous> (/home/trevor.panhorst/public_html/server/server.js:96:34)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:906:3

Here's the relevent code:
In server.js... just some dependencies
var express = require('express'),
    routes = require('./routes'),
    api = require('./routes/api'),
    connString = "postgres://...:...@...:5432",
    cookieParser = require('../node_modules/cookie-parser'),
    errorHandler = require('../node_modules/errorhandler'),
    bodyParser = require('../node_modules/body-parser'),
    session = require('../node_modules/express-session');
 var app = module.exports = express();

.
.
.
Here are my set/use declerations
app.set('port', 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(require('connect').bodyParser());
app.use(allowCrossDomain);
app.use(express.static(__dirname + '../'));
app.use(cookieParser());
app.use(session());

.
.
.
and here are my express routes
// clear cookie session on logout
app.post(baseUrl + 'logout', api.logout());

// redirect all others to the index (HTML5 history)
app.get('*', routes.index);

// Start server

app.listen(app.get('port'), function () {
    console.log("Express server listening on port %d in %s mode",
    app.get('port'), app.settings.env);

.
.
.
in api.js
just some dependencies
var pg = require('../../node_modules/pg'),
    session = require('../../node_modules/express-session'),
    connString = "postgres://...:...@...:5432";

.
.
.
and here is my simple logout function...
  exports.logout = function(req, res){
        req.session = null;
    };

Comment: `api = require('./routes/api'),`  where is this code? It seems that your request(`req`) object is null. When does this occurs?
Answer: Wow, I got it. wrong way:
app.post(baseUrl + 'logout', api.logout());

right way:
app.post(baseUrl + 'logout', api.logout);


How can I make this JSON.stringify work properly

Question: I have a small issue to make my arrays into the json I want to. I have made this code:

var arrData = [{label:Test,value:199.12}, {label:Test2,value:1024}]
var data = [];
for (var i = 0; i < arrData.length; i++) {
  data.push(JSON.stringify({
    label: arrData[i][2],
    value: arrData[i][3]
  }).replace(/\"/g, "").replace("\\r", ""))
}

It also does the job properly. But I do want it to be in this format:

{ label: 'Food', value: 90 },

I want to have the ' ' on the label data and I want to remove the double "" punctuation mark outside the json. Since my current json looks like this:
"{label:Test,value:199.12}", "{label:Test2,value:1024}",

Comment: `JSON.stringify` *does* work properly. What you seem to want is to produce invalid JSON.
Comment: *"Since my current json looks like this"* The code in the question definitely **won't** produce that "JSON" (which isn't JSON).
Comment: Please update the snippet I made with relevant data
Comment: @Ayrton it should actually be `{"label":"Test","value":199.12}`. Anything else is not valid.
Comment: JSON is not actually the same as a Javascript object - it's somewhat simplified. You can only use double quotes on labels (you are not allowed to omit them) and as Ayton pointed out, you can only use double quotes to signify string literals. You need to either write the program that receives this structure to accept proper JSON, or write your own stringify function that follows your own rules if you really want to make up your own data format.
Answer: { label: 'Food', value: 90 } isn't valid JSON so you cannot create it using JSON.stringify.
It isn't any standard serialisation format (although it is a valid JavaScript literal) so if you want to serialise data to it, you'll need to write a custom serialiser.
You could loop over the properties of the object and append them, the associated values, and whatever quotes and commas your format demands, to a string.


Where can i find good transcriptions?

Question:
Possible Duplicate:
Sites with a good selection of sheet music

i have been searching for sheet music for the song Don't Mess With Mr. T by Stanley Turrentine for quite some time on google, but it has so far yielded no results. does anyone know a good website with transcripted tunes, or have a transcription of the specific song they can share? i play an Eb alto saxophone if that helps, but i can always transpose it if key is an issue
Answer: I'm sorry to say that websites such as you request are often run illegal. When you reproduce a work that is copyrighted you have to have the permission from the authors, which they often* don't have. I would advise you to start to transcribe yourself. It's much more rewarding.
*I've NEVER encountered one that had.
Comment: *sigh* what a shame. not a problem, I am able to transcribe songs myself, i was just hoping to find an easier solution for one of my students.
Comment: on the other hand, is the sheet music published by anyone for purchase?
Comment: you could search sheetmusicplus.com or amazon.com or whatever webstores there might be.
Comment: Note that http://www.mysongbook.com/ has the permission, but only has a few songs and only work with Guitar Pro 6
Answer: Putting aside legality, which is a very valid issue in itself, there are a number of ways that you can get the music (or listener's interpretations of the music) for certain songs you want to play.

(For Guitarists mainly, but applicable to all musicians) Tabs. You can take the tab and convert it back into the music notes (if you are a non-guitarist, using a fretboard diagram) and transpose up or down as you need to. You can find these for shedloads of songs, from tonnes of sites on the web these days.
Chords. Again, you can get these from hundreds of sites, and gives you a starting point for notes of melodies or riffs that you can go on to figure out by ear. Some websites, such as Ultimate Guitar, actually have transposing tools on their pages for chord sheets, so you can get into the key you want.
Guitar Pro Tabs: These are downloadable files that open in a program (the best free one in my opinion is Tux Guitar) and you can edit and play them. The advantage of this is particularly if you wish to play a guitar line on another instrument: the program displays notation as well as tab, so you can play what is given. Again, you can transpose as you need.
Midi: Musical Instrument Digital Interface files are files that have multitracks of musical data that can be interpreted and played by software. If you find one for the song you want, you can open them in Sibelius or other notation program, and see which different MIDI instrument if playing what, as it displays the MIDI notes as notation.
Buy them from eBay or Amazon or other online services: they have tonnes of them available; from sheets up to songbooks.

Incidentally I had a look for any Midi's or tab files for the song you quoted, I couldn't find anything. Unlucky
Hope this helps!

Where can i find good transcriptions?


A question on nowhere dense sets.

Question: Consider the $2$ definitions:
A set $A$ in a topological space $(X,\tau)$ is said to be a nowhere dense set if it is not dense in any nonempty open set.
A Set $A$ in a topological space $(X,\tau)$ is said to be a nowhere dense set if $(\bar A)^0=\phi$.
I understand the two definitions as statements and know they are equivalent.
Suppose that $(\bar A)^0=\phi$,now take any open ball $V$ in $X$.Let if possible,for each open ball $U$ in $V$,$U\cap A\neq \phi$.Now for each of the open balls in $V$,choose an element of $A$ and consider the collection as $A_0$.Now for any point$v$ in $V$,every neighborhood of $v$ contains a point of $A_0$ by its construction.So,$V\subset \bar A_0 \subset \bar A$,i.e. $\bar A$ contains an open set which contradicts $(\bar A)^0=\phi$.
Conversely,suppose for each open ball $V$ in $X$,there exists $U$ open such that $U\subset V$ and $U\cap A=\phi$.To show,$\bar A$ can contain no open set.If possible $\bar A$ contains an open ball $V$,then for any open ball $U$ in $V$,if we take a point $x\in U$ then $x\in \bar A$,so $x$ is an adherent point of $A$ and since $U\in \eta_x$,so,$U\cap A\neq \phi$.
But I have not yet found the reason behind its name 'nowhere dense' i.e. I cannot feel it properly.I am looking for some diagram that would build my intuition on nowhere dense set.I have studied examples like Cantor set,but yet I am feeling uncomfortable with the notion of nowhere dense sets and why it means that points are not clustered very tightly in topological sense?I also want to know what is the motivation behind defining nowhere dense sets.

The above picture shows that for every open set $V$(yellow) in $(X,d)$,there is an open set $U\subset V$ (shown in white) which does not intersect $A$.
Some other constructions of nowhere dense sets are Cantor like construction,it forces the resulting set to be nowhere dense by deleting some open ball from each of the open balls of the whole set.For example Cantor set,Smith-Volterra Cantor set,Cantor dust in $\mathbb R^n$ and Cantor Cirlcle,Fractals-of-Cirlces that ca be found here.
Answer: This is based on an old (early 20th century) usage (gone mostly out of style) to call a set $A$ "somewhere $P$" if there is some non-empty open set $O$ such that $O \cap A$ has property $P$ in $O$ (somewhere = 'inside some non-trival open set') and a set that is "not somewhere dense", was called "nowhere dense" for short. This only explains the origin of this specific name. The definition is useful because of its connection to Baire's theorem and meagre sets.
Comment: @Kishalay Sarkar: There is a corresponding use of "everywhere" that is used to describe the situation when some given property is true for the intersection of the given set with each nonempty open set (e.g. "everywhere dense" was the term that, in older literature, was used for what we now just call "dense"). Unfortunately, the use of "nowhere" in "nowhere differentiable function" doesn't follow this convention!
Answer: Nowhere dense means not somewhere dense.
A set $A$ is somewhere dense when
exists open $U$ with $A\cap U$ dense within $U$.

A question on nowhere dense sets.


American billards, foul in last ball (black)

Question: I searched a lot about last ball fouls, but I couldnt conclude any answers.
I got two scenarios:

If only black ball remains and Player A fouls, what does Player B do?

Can player B do free-shot? I mean, place the ball anywhere on the table?
Must player B place the ball anywhere before the starting line? And can he shoot the black ball directly? What if the black ball is also in the starting line area? Must he shoot to the other lane before touching black ball?

What if Player A has some balls and Player B doesnt, and its Player A's turn. For the scenarios in the 1. item, he can gain advantage by fouling?
Answer: This is according to US 8-Ball Rules.
If the black ball is the only ball remaining, there are only 3 basic types of foul that can be committed:

1) Complete miss (scratch)
2) Remove the ball from the table
3) Other foul, such as touching the cue ball.

7.1 of the referenced document states that:

If the 8-ball was pocketed the result shall be a loss of game (see 4.2, Game Loss).

otherwise the ball is in hand.
7.2 (scratching) states:

Pocketing the cue ball or driving it off the table is a ball in hand foul. If a scratch occurs while shooting the 8-ball, but the 8-ball was not pocketed or removed from the table, the game continues with ball in hand to the opponent (scratching on the 8-ball is not a loss of game as long as the 8-ball is still in play).

and 7.5 states:

If a player removes the 8-ball from the pool table, it results in a loss of game (see 4.2, Game Loss).

So if the foul involves the black ball leaving the playing area of the table, it results in losing the game, otherwise it is ball in hand.
Part 2 doesn't appear to make sense - if the black ball is the only ball remaining, how does Player A have balls left?
Comment: so in foul scenarios, its stated that it would result in ball-in-hand. thanks for the answer. for part 2, i meant that player A has some balls and if fouling would not cause ball-in-hand, he can gain advantage by fouling because, if player B has to shoot from behind of the starting line, he might foul or even lose depending on how far/hard is the position?
Comment: for part 2, what would it be then if player A fouls either intentionally or mistakenly? lets say pocketed the cue ball?
Comment: intentional fouls usually forfeit the game immediately, and to gain an advantage from unintentional fouls is impossible - a ball in hand means the  opponent can place the cue ball wherever they want.


Parked domain not being redirected

Question: I own a domain, pricipal.com. When I try to access it the redirect link gets stuck. I see in Chrome Developer tools that URL has status code 400. What causes this failure and how can I trouble shoot it?
Comment: Offtopic. Not a programming question. We are not general webserver tech support.
Answer: Reason of the failure: A 400 means that the request was malformed. In other words, the data stream sent by the client to the server didn't follow the rules
"redirect link gets stuck" ..
There are two type of solution one is simply removing cache and cookie of your browser. Another is little bit difficult. Try to set up your dns properly. If you are using CPANEL, sometimes ROOT User or admin of the server change addon/parked domain default directory which usually create redirecting loop.In short Servers Wrong configuration may cause this trouble. Try to park another domain and see what happen if that domain show you the same error contact with your server administrator
Comment: Thank you very much @SMJobayerAlam
Comment: `import requests
try:
    r = requests.head("http://pizzhut.com")
    print(r.status_code)
except requests.ConnectionError:
    print("failed to connect")`
I'm sorry to follow up with this so late but howcome I get 302 returuned here when in the browser its 400?

Parked domain not being redirected


PHP string assign to array variable

Question: I have written some php code, trying what is to assign a string (tag_of_organization) to a variable and then latter to assign it to array newvar. As i am totally new to php and search a lot for it but cannot find anything, so i am asking it here how to do this. here it is
$organ='tag_of_organization';
$newvar = array();
$newvar["tag_of_organization"] =$organ;

Comment: Yes, and...? What is the problem or question?
Comment: @abid: Can't help asking: What would be the use of that? What are you trying to accomplish?
Comment: @geomagas Story is long i am writing this code to check for two ids in two tables actually this code runs on the request coming from android code when the id matches in one of the two tables i want to assign it a string that will tell the android that from which table it is. This string will be use in android code in if condition on which the android code will decide to open the related activity. All is ok but i am in doubt about the above code.
Comment: Ok, next question: You need it in a different format than what you already have? Because, from where I'm standing, you're answering your own question. Could you elaborate? _(preferably by editing/extending the question)_
Answer: Try with:
$newvar[$organ] = $organ;

Answer: You are already correct. put print_r to test print your array
$organ='tag_of_organization';
$newvar = array();
$newvar["tag_of_organization"] =$organ;
print_r($newvar);

Output
Array ( [tag_of_organization] => tag_of_organization )

Update
you want dynamic result
$organ='tag_of_organization';
$newvar = array();
$newvar[$organ] =$organ;
print_r($newvar);

Output
Array ( [tag_of_organization] => tag_of_organization )

PHP string assign to array variable


Sequence $0\leq a_{n}-l\leq \dfrac{\pi^{2} }{2^{2n+1}}$

Question:
Let for $n\geq 2\quad a_{n}=\prod\limits_{k=2}^{n}\cos\left(\dfrac{\pi }{2^{k}}\right)$ and
   $b_{n}=a_{n}\cos\left(\dfrac{\pi }{2^{n}}\right)$ and let  $c_{n}=a_{n}\sin\left(\dfrac{\pi }{2^{n}}\right)$

Show $(a_n)$ is bounded and decreasing $(b_n)$ is increasing and studying$(C_n)_{n}$
Deduce the value of the limit $l$ town of  $a_n$ and $b_n$
Show that $0\leq a_{n}-l\leq \dfrac{\pi^{2} }{2^{2n+1}}$ (note that: $|1-\cos x|\leq \dfrac{x^{2}}{2})$

The original of text

For 1
$a_n$ is decreasing :
let  $u_n=u_{n-1}\cos(\frac{\pi}{2^n})\quad \forall n\geq 3$
we got  $u_{n-1}-u_n=(1-cos(\frac{\pi}{2^n})u_{n-1}$ which is positive since product of two numbers.
Bounded:
Let $n \geq 2$. we've $\cos a \geq 0$ when $a\in [0,\frac{\pi}{2}]$. since $ \frac{\pi}{2^k}\in [0,2]$ for all $k\in \{{2,\ldots,n}\},\ u_n$ is product $n-1$ positive number.
is positive.
$b_n$ is increasing:
Let $(v_n)u_n \sin({\pi}{2^n})$
the last question which is important
Answer: Hint: If I were you, I'd use: $\sin(2u) = 2\sin(u)\cos(u)$ with u = $\frac{\pi}{2^n}$; that might give you a more useful formula for $(a_n)$. In fact you can calculate the value of $c_n$ using this. Look at the last term of the product and see if you can find a recurrence somewhere.
Edit:
More precisely: $c_n = a_n*\sin(\frac{\pi}{2^n}) =\cos(\frac{\pi}{2^n})*\sin(\frac{\pi}{2^n})*\prod\limits_{k=2}^{n-1}\cos\left(\dfrac{\pi }{2^{k}}\right) = \frac{1}{2}\sin(2*\frac{\pi}{2^n})*a_{n-1} $
$\implies c_n = \frac{1}{2}\sin(\frac{\pi}{2^{n-1}})a_{n-1} = \frac{1}{2}c_{n-1}$
$\implies c_n = \frac{c_2}{2^{n-2}}$ (geometrical sequence)
Hence you get: $$a_n = \frac{1}{2^{n-1}\sin(\frac{\pi}{2^n})}$$
Comment: if you just could give more details with formula not with words to upvote ur post
Comment: @Educ Ok, I didn't want to spoil you the pleasure of finding this on your own :)
Comment: But now you spoiled it. Why?
Comment: @Did Because there is not middle steps. I did not see how I could be more precise without giving him this. However the answer is not complete, he still has to prove his statements. Was I wrong? The part from "More precisely..." to the end was not here at first..
Comment: i can't get ur point after i got the expression of $a_n$ how can that help me to show $0\leq a_{n}-l\leq \dfrac{\pi^{2} }{2^{2n+1}}$ and my try is correct for question 1
Comment: @Educ just so you know I'm french (I say this because of the original text) so if you want to talk in french in private it's possible :)
As for your question, are you familiar with limited expansions (développements limités) ? You have the result: $\sin(u) = u + o(u)$ when $u \rightarrow 0$, use it to get "l", and then you can look for your inequality using (for instance) : $u - \frac{u^3}{6} \leq \sin(u) \leq u $ or the one given (haven't tried it but fiddling with it should do the trick, will try it later).


What is Generative Training?

Question: I know that the difference between generative and discriminative classifiers is that the generative ones directly model the distribution of the observed data while the discriminative ones do not.
But then I come across the term discriminative training in which there are Minimum Classification Error(MCE) and Maximum Mutual Information(MMI) estimation. These two methods seems to estimate the parameters for the generative classifiers. It confuses me where the discriminative comes from.
Answer:
Generative training is to $\hat M$(learned model) close to the overall joint distribution $P^{*}(Y,X)$ while discriminative training is to get $\hat P(Y|X)$ to be close to $P^{*}(Y|X)$. And the discriminative training is usually performed in the context of undirected models.

What is Generative Training?


If a line parallel to $y=-7x+3$ touches the parabola $2x^2-3x+2$ in the point $(x_0,y_0)$, what is the value of $4x_0+y_0$?

Question: I tried solving this but I've no idea how to find the point where a line of the form $y=-7x+n$ intersects a given parabola.
Hints are welcome. Don't know calculus (don't even know if it's applicable here, but either way).
Answer: The slope of the tangent line to the parabola at $(x_0,y_0)$ is given by $4x_0-3$, but this should be $-7$. Thus $x_0=-1$. This gives $y_0=2(-1)^2-3(-1)+2=7$. Now you can compute $4x_0+y_0$.
I didn't read your comment about calculus: so here is one without calculus:
Let the tangent line be $y=-7x+b$, then the intersection with parabola can be computed as:
$$-7x+b=2x^2-3x+2.$$
This leads to
$$2x^2+4x+(2-b)=0.$$
For tangency it should have equal roots, thus discriminant $4^2-8(2-b)=0$. Now you get your $b$ and you can compute $(x_0,y_0)$ from here.
Answer: Hint: the line $y=ax+b$ meets the parabola $y=cx^2+dx+e$ when $ax+b=cx^2+dx+e$ - can you see why?
Second hint: the tangent to a parabola meets it at just one point as you will see from a simple sketch
Comment: But I still have 3 unknown variables and only two equations? Unless I am missing something.
Comment: @JohnDoe $ax+b=cx^2+dx+e$ is **one** equation in **one** unknown because you already know $a,b,c,d,e$.
Comment: @JohnDoe You have two unknowns, because setting the expressions equal eliminates $y$. You have $x$ still as unknown, and what you have called $n$ in your question. But you have two conditions - the first is that $x$ is a root of the quadratic, and the second is that $n$ is such that the quadratic has a single root. These conditions are enough. You need to deploy what you know about quadratics (e.g. complete the square) to reach a solution.
Comment: Yep, I got the right answer. Thanks :)
Comment: No need to complete the square, just set the discriminant to zero.
Comment: @JohnDoe The two are equivalent. Here writing $2x^2+4x+2-n=2(x+1)^2-n$ is an obvious move and you can read off $x_0=-1$ immediately without having to compute $n$ at all, and then get $y_0$ from the quadratic. And of course $n=0$ is obvious too.


Is this Function of Product of variable and Ratio of CDF and PDF of Standard Normal Distribution Convex?

Question: Let $G\left(x\right)=x\frac{\phi\left(x\right)}{\Phi\left(x\right)}$. Here, $\phi$ and $\mathbf{\Phi}$ are the standard normal PDF and CDF, respectively. Is $G\left(x\right)$ convex? It has been shown earlier that $f\left(x\right)=\frac{\phi\left(x\right)}{\Phi\left(x\right)}$ is convex.
Please provide proof that $G\left(x\right)=x^{2}+x\frac{\phi\left(x\right)}{\Phi\left(x\right)}$ is convex $\forall x>0 $. Here, $\phi$ and $\mathbf{\Phi}$ are the standard normal PDF and CDF, respectively.
STEPS TRIED
I have tried the calculus method and have a formula for the second derivate, but am not able to show that it is positive $\forall x > 0$. Please let me know if you need any further details.
Comment: Please provide proof that $G\left(x\right)=x^{2}+x\frac{\phi\left(x\right)}{\Phi\left(x\right)}$ is convex $\forall x>0 $. Here, $\phi$ and $\mathbf{\Phi}$ are the standard normal PDF and CDF, respectively.

#STEPS TRIED

I have tried the calculus method and have a formula for the second derivate, but am not able to show that it is positive $\forall x > 0$. Please let me know if you need any further details.
Comment: The "STEPS TRIED" does not display. Please type using Mathjax so we can see what you tried. Here is a tutorial: http://meta.math.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: Hey @KittyL … Please note this is a rather old question …  But I believe, it is not convex as we also see in the graph below. I used the simple derivative test to try, but was not able to show this.
Comment: Sorry, it was in the review queue, so I commented absentmindedly.
Comment: But thank you for the pointer … It will be useful for other questions ...
Answer: No, it is not possible. $\frac{\phi(x)}{\Phi(x)}$ is positive, decreasing and convex on $\mathbb{R}^+$, but $x\cdot\frac{\phi(x)}{\Phi(x)}$ is increasing in a right neighbourhood of zero and decreasing for large values of $x$. Since it is positive on $\mathbb{R}^+$ and $\lim_{x \to +\infty} x\cdot\frac{\phi(x)}{\Phi(x)}=0$, it must have an inflection point somewhere. For instance, the inflection point is near $x=1.6$:
$\hspace1in$
Comment: Thanks Jack. How about $F\left(x\right)=x^{2}+x\frac{\phi\left(x\right)}{\Phi\left(x\right)}$ ? Would this be convex? Would you evaluate the limit you mention using L'Hopital's rule?
Comment: @texmex: yes to both questions.
Comment: Thanks Jack. Which software do you use to get plots like the above? Do you know any freeware that I can use to get graphs of complicated functions?
Comment: @texmex: I use Mathematica, but you may use GNUplot or any free CAS that is able to interface with GNUplot, like Sage.
Comment: Could you point out a way to prove this without numerical methods? I am trying calculus and seem to get stuck. Proof that this is convex: $F(x)=x^2+xϕ(x)/Φ(x)$
Answer: This graph of the various distribution functions should help demonstrate the convexity visually. Hope this helps. Thanks for all the pointers and useful suggestions.


Show $\lim\limits_{n\to\infty}\int_{0}^{\infty}e^{-x}\sin(\frac{n}{x})~\text{d}x=0$

Question: I'm having trouble showing $$\lim_{n\to\infty}\int_{0}^{\infty}e^{-x}\sin\left(\frac{n}{x}\right)~\text{d}x=0$$ The integrand doesn't converge for any $x$ so I don't know how to use the standard Lebesgue convergence theorems. Thank you for any hints.
Comment: @Zarrax, may be you should post this as answer?
Comment: @Norbert good idea, just did...
Answer: Hint: change variables to ${\displaystyle {1 \over x}}$ and apply the Riemann-Lebesgue lemma.
Answer: The change variables shouble be $u=\frac{n}{x}$. That way, $x=\frac{n}{u}$, and $dx = n\frac{du}{u^2}$. The integral then becomes: $\displaystyle\int_0^{+\infty} \frac{n}{u^2}e^{-\frac{n}{u}}\sin(u)du = \int_0^{+\infty} f_n(u)du$ with $f_n(u)=\frac{n}{u^2}e^{-\frac{n}{u}}\sin(u)$. $\forall n$, we have: $\displaystyle\lim_{u\rightarrow 0}f_n(u)=0$, $\displaystyle\lim_{u\rightarrow +\infty}f_n(u)=0$, $f_n$ is integrable on $\mathbb{R}^+$.
Let us now find $m_n$ such as $||f_n||_{\infty}\leq m_n$. For that we study $g_n(u)= \frac{n}{u^2}e^{-\frac{n}{u}}$. $g_n'(u) = (-\frac{2n}{u^3}+\frac{n^2}{u^4})e^{-\frac{n}{u}}= \frac{n}{u^3}(-2+\frac{n}{u})e^{-\frac{n}{u}}$, and so we see that $g_n$ reaches its maximun when $u=\frac{n}{2}$, and $g_n(\frac{n}{2}) = \frac{4}{n}e^{-2}$.
Finally, $\forall x\in \mathbb{R}^+$ we have $|f_n(x)|\leq\frac{4}{n}e^{-2}\rightarrow 0$, which enables us to use the theorem of the dominated convergence to say that $\displaystyle\lim_{n\rightarrow +\infty}\int_0^{+\infty}f_n = 0$
EDIT: Clarification on the theorem of the dominated convergence: It is easy to see that for all $u>1$, $g_n(u)$ is decreasing in $n$. Let's take an $\varepsilon>0$, and find $N$ and $A>1$ such as $\int_A^{+\infty}g_n(u)du\leq\frac{\varepsilon}{2}$ (a). Then we can apply without any problem the dominated convergence on $[0,A]$, so $\displaystyle\lim_{n\rightarrow +\infty}\int_0^A f_n(u)du=0$, so we can find $N'$ such as $\forall n\geq N'$, $|\int_0^Afn|\leq \frac{\varepsilon}{2}$ (b).
And when you add up inequalities (a) and (b), you get: $\forall n\geq\max(N,N')$, $|\int_0^{+\infty}f_n|\leq\varepsilon$, which achieves the demonstration.
Comment: But $\frac{4}{n} \mathrm{e}^{-2}$ is not integrable over $\mathbb{R}^+$. Am I failing to see how to apply the DOM?
Comment: @Sasha edited for you
Comment: Thank you for the edit. The point of departure, i.e. $g_n(u) = n u^{-2} \exp(-n/u)$ is decreasing in $n$ for all $u$, is incorrect. $g_n(u)$ increases for $0\leqslant n \leqslant u^{-1}$ and decreases afterwards.
Comment: @Sasha that's right, but it's fine if we take $A>1$
Answer: Let
$$
 I_n = \int_0^\infty \mathrm{e}^{-x} \sin\left(\frac{n}{x}\right) \mathrm{d} x = \Im\left( \underbrace{\int_0^\infty \exp\left(-x + i \frac{n}{x}\right)\mathrm{d}x}_{J_n} \right)
$$
We can rotate the contour by angle $\phi$ clock-wise, so as to keep the real part of the argument of exponent negative, i.e. for $0 \leqslant \phi<\frac{\pi}{2}$:
$$
  J_n = \int_0^\infty \exp\left(-x + i \frac{n}{x}\right)\mathrm{d}x = \int_0^{\mathrm{e}^{-i \phi} \infty} \exp\left(-z + i \frac{n}{z}\right)\mathrm{d}z = \int_0^\infty \exp\left(-r \mathrm{e}^{-i \phi} + i \frac{n}{r}\mathrm{e}^{i \phi}\right) \mathrm{e}^{-i \phi} \mathrm{d}r
$$
The above is a table integral (Gradshteyn&Ryzhik 3.471.9, also see question 128687):
$$
   J_n = 2 \sqrt{n} \mathrm{e}^{-i \frac{\pi }{4}} K_1\left(2 \sqrt{n} \mathrm{e}^{-i \frac{\pi }{4}}\right) = \sqrt{2n} (1-i) K_1\left(\sqrt{2n} (1-i)\right)
$$
where $K_\nu(x)$ denoted the modified Bessel function of the second kind. The original integral is thus:
$$
    I_n = \sqrt{2n} \Im\left( (1-i) K_1\left(\sqrt{2n} (1-i)\right) \right) = \sqrt{2n} \left( \operatorname{kei}_1\left(2\sqrt{n}\right) - \operatorname{ker}_1\left(2\sqrt{n}\right) \right)
$$
where $\operatorname{ker}_\nu(z)$ , $\operatorname{kei}_\nu(z)$ are Kelvin functions. The large argument expansion of $K_\alpha(x)$ is well-known:
$$
    J_n = \frac{\pi}{2} \sqrt{\sqrt{2n} (1-i)} \exp\left(-\sqrt{2n} (1-i)\right) \left( 1 + \mathcal{O}\left(\frac{1}{\sqrt{n}}\right)\right) = \sqrt{\pi} n^{1/4} \exp\left(-\sqrt{2n} + i \left(\sqrt{2n} - \frac{\pi}{8}\right)\right)
$$
It now easily follows that
$$
    \lim_{n \uparrow \infty} I_n =\Im \lim_{n \uparrow \infty} J_n  = 0
$$
Comment: For the unfamiliar: $K_\nu(z)$ is the modified Bessel function of the second kind.


Trying to bind adapter to listView and I see a blank screen on my phone

Question: I kind of binded an adapter to listView and I don't get any error, however, I don't see an output either.
I am a very beginner and I spent more than 3 hours experimenting with this code and couldn't come up with solution
Here is my MainActivityFragment code:
public MainActivityFragment() {
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    String[] forecastArray = {
            "String 1",
            "String 2",
            "String 3",
            "String 4",
            "String 5",
            "String 6",
            "String 7",
            "String 8",
            "String 9"

    };
    List<String> weekForecast = new ArrayList<>(
            Arrays.asList(forecastArray)
    );
    ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast,
            R.id.list_item_forecast_textView, weekForecast);

    View v = inflater.inflate(R.layout.fragment_main, container, false);
    ListView lv = (ListView) v.findViewById(R.id.listView_forecast);
    lv.setAdapter(mForecastAdapter);

    return inflater.inflate(R.layout.fragment_main, container, false);
}

Comment: show your R.layout.list_item_forecast layout code
Answer: You have to return your inflated view.
 public MainActivityFragment() {
  }

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
         String[] forecastArray = {
            "String 1",
            "String 2",
            "String 3",
            "String 4",
            "String 5",
            "String 6",
            "String 7",
            "String 8",
            "String 9"

    };
    List<String> weekForecast = new ArrayList<>(
            Arrays.asList(forecastArray)
    );
    ArrayAdapter<String> mForecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast,
            R.id.list_item_forecast_textView, weekForecast);

    View v = inflater.inflate(R.layout.fragment_main, container, false);
    ListView lv = (ListView) v.findViewById(R.id.listView_forecast);
    lv.setAdapter(mForecastAdapter);

       return v;
    }

Comment: Thanks a lot, it helped me out
Answer: I think you should return v; instead of return inflater.inflate(R.layout.fragment_main, container, false);


Division by factorized polynomials in Macaulay2

Question: I have this problem dividing by factorized polynomials, for example
(x_1^4-x_2^4)//(factor(x_1^2-x_2^2))
does not work because the numerator is of "class R" (R is the ring kk[x_1..x_n]) and the denominator is of "class Product".
How to convert elements of class Product to class R?
I'd appreciate your help.
Comment: have you tried to ask this in [Macaulay2 Google Discussion Group](https://groups.google.com/forum/#!forum/macaulay2)? The link to it is on Macaulay2 front page.
Comment: Yes Alexander, I posted it there first, have received no answer :) This is a silly question... but anyway the answer was useful, didn't know about the 'value' function.
Comment: Do you know a command eg to get (1,2) out of `(x^2+2*y)` and `ideal(x^2,y)` in M2?
Answer: You could use value, as follows.
$ M2
Macaulay2, version 1.6
with packages: ConwayPolynomials, Elimination, IntegralClosure, LLLBases, PrimaryDecomposition, ReesAlgebra, TangentCone

i1 : kk = QQ

o1 = QQ

o1 : Ring

i2 : R = kk[x_1..x_5]

o2 = R

o2 : PolynomialRing

i3 : p = (x_1^4-x_2^4)

      4    4
o3 = x  - x
      1    2

o3 : R

i4 : q = factor(x_1^2-x_2^2)

o4 = (- x  + x )(x  + x )(-1)
         1    2   1    2

o4 : Expression of class Product

i5 : value(q)

       2    2
o5 = x  - x
       1    2

o5 : R

i6 : p // value(q)

       2    2
o6 = x  + x
       1    2

o6 : R