text:
Q: React Proxy error: Could not proxy request /api/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED) I have a React frontend that uses jwt to authenticate with the Django backend.  The backend works and is connecting just fine using django views, but when I try to proxy a request from React, it gives me a Connection Refused error.

Proxy error: Could not proxy request /api/auth/token/obtain/ from localhost:3000 to http://localhost:8000 (ECONNREFUSED).

Connecting to http://localhost:8000/api/auth/token/obtain/ works normally.  And sending a POST request with Axios also works normally and returns the token json.  But when I proxy it with node, it doesn't work.
In my package.json I have:
  "proxy": {
    "/api/*":  {
      "target": "http://localhost:8000"
    }
  },

Edit:  Public repo.  You can run easily if you have docker installed. (uses 1 image and 2 containers).  After cloning just run docker-compose build, then docker-compose up.
Edit2: Headers of request:
*General*
Request URL: http://localhost:3000/api/auth/token/obtain/
Request Method: POST
Status Code: 500 Internal Server Error
Remote Address: [::1]:3000
Referrer Policy: no-referrer-when-downgrade

*Response Headers*
HTTP/1.1 500 Internal Server Error
X-Powered-By: Express
Date: Mon, 30 Apr 2018 21:23:17 GMT
Connection: keep-alive
Transfer-Encoding: chunked

*Request Headers
POST /api/auth/token/obtain/ HTTP/1.1
Host: localhost:3000
Connection: keep-alive
Content-Length: 45
Pragma: no-cache
Cache-Control: no-cache
Origin: http://localhost:3000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36
Content-Type: application/json
Accept: */*
Referer: http://localhost:3000/login
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9,fr;q=0.8,ja;q=0.7

A: Didn't actually get the answer here I was looking for but had an alternative solution work for me. I think it's specifically related to Node v17, as that's when it started happening for me but the solution was pretty simple.
I updated:
"proxy": "http://localhost:8000"

To:
"proxy": "http://127.0.0.1:8000"

In case it's relevant (I don't think it is) - I was proxying to a Django server.

A: So the issue was since both the Node dev environment and the Django dev environment were running in separate docker containers, so localhost was referring to the node container, not the bridged network.
So the key was to use container links, which are automatically created when using docker-compose, and use that as the hostname.  So I changed it to
"proxy": {
    "/api":  {
        "target": "http://django:8000"
    }
},

And that worked, as long as you launch both containers with the same docker-compose command, otherwise you have to manually specify external_links in your docker-compose.yml file.

A: If you don't feel like setting up docker compose, you can also use a docker network:

create network and run docker containers within that network

docker network create webapp_network

docker run -d -p 5000:5000 --name webapp_backend --network webapp_network webapp_backend_image

docker run -d -p 3000:3000 --name webapp_frontend --network webapp_network webapp_frontend_image

Added a line in package.json of my frontend React webapp:
"proxy": "http://webapp_backend:5000"

note you can now refer to your backend using the container name instead of localhost

A: I faced a similar issue but in Mac machine. I changed localhost to 127.0.0.1 in the package.json and that worked for me as below:
"proxy": "http://127.0.0.1:5000"

A: If your on a newer version CRA 2.0+ you'll need to do this via a manual proxy.
https://facebook.github.io/create-react-app/docs/proxying-api-requests-in-development#configuring-the-proxy-manually

A: I'm running into the same problem as well. Most search results mention adding "secure": false or "ignorePath": true to your proxy config. Something like this:
"proxy": {
    "/api/*":  {
      "target": "http://localhost:8000",
      "secure": false
    }
  },

May be worth a try but unfortunately none of this worked for me. Although each address (http://localhost:3000 and http://localhost:8000) work completely fine in the browser, maybe since the container is actually proxying it needs to use a Docker address?
EDIT--
Alright I think I figured it out. I believe it did have to do with the container to container communication. Looking in your docker-compose, your api server is called django. Change your package.json file to this:
"proxy": {
    "/api/*":  {
      "target": "http://django:8000",
      "secure": false
    }
  }

A: Could see the error after upgrading yesterday Docker to version v19.03.13 (on Mac), restarting Docker fixed the issue. The application also runs Node.js/React, but not Django. Basically, I had issues with connection to MongoDB Atlas related to authentication/fetching anything from the cloud database.

A: Choosing the exact value for localhost to populate the "target" property is mostly the solution (it can be localhost, 127.0.0.1, [::1] ).
A mac user should type in terminal to get the solution:
sudo lsof -iTCP -sTCP:LISTEN -n -P

A: The correct answer will be to use manual proxy with

*

*target = docker address django:4000

*correct HOST header localhost:8000
because if Django uses reverse function which returns absolute url

reverse('preview-mail', args=[mail.pk],request=request)

you need to have correct HOST header for it, or you may get the result URL like
https://django:4000/your-url`
const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    proxy('/api', {
      target: 'http://django:4000',
      changeOrigin: true,
      secure: false,
      pathRewrite: {
        '^/api': ''
      },
      onProxyReq: function (proxyReq, req, res) {
          proxyReq.setHeader("host", 'localhost:8000')
      }
    })
  )
}

A: If you're working on a MERN stack app, make sure you're not in the client folder. You need to be in the root. While in the root, run this command in the terminal.                  npm run start:dev

A: For NodeJs backend this can be solved by adding a line of code in the package.json file of the backend
"devstart": "nodemon server.js --ignore './location of frontend react directory'",

A: In my case, my server was running on port 3001, but I had "proxy": "http://localhost:3000" in the package.json file of my React fronted project


text:
Q: Use Consolas font family in lstlisting (the whole document is in Vietnamese) I am typing a document in Vietnamese about C++, so of course there will be some code. I will use lstlisting environment as it is the best choice for code.
However, the \ttfamily (default monospace font) seems to be too wide for me. I want to use Consolas instead. However, inconsolata package does not work when there is this line in the preamble:
\usepackage[utf8]{vietnam}

or
\usepackage[vietnamese=nohyphenation]{hyphsubst}
\usepackage[vietnamese]{babel}

Without one of these, all Vietnamese letters (like ể or ồ) will disappear in the PDF, though inconsolata works.
I am using pdfLaTeX. I know that I can change to XeLaTeX to type in Consolas easily, but it seems to be a bit too complicated for me to convert a preamble from pdfLaTeX to XeLaTeX. I've tried four or five times without success.
Anyone can give me some idea? Thank you very much in advance!
Here is my shortened preamble if you can convert it to XeLaTeX or LuaLaTeX:
\documentclass[11pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{vietnam}
\usepackage[unicode]{hyperref}
\usepackage{inconsolata}
\usepackage{listings}
\lstset{basicstyle=\footnotesize\fontfamily{zi4}\selectfont,}
...

My full code can be found here.

A: As you said you would be willing to try Xe-/LuaLaTeX, I have made an attempt to convert the part that you ask about to LuaLaTeX (involving a font change to the Palatino-like TeX Gyre Pagella).
listings may still handle your unicode sequences ("Vietnamese letters") badly, so you should use the literate option.
\documentclass[11pt,a4paper]{article}
\usepackage[vietnamese=nohyphenation]{hyphsubst}
\usepackage[vietnamese]{babel}
\usepackage[unicode]{hyperref}
\usepackage[left=2cm,right=2cm,top=2cm,bottom=2cm]{geometry}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{listings}
\usepackage{xcolor}
\usepackage{indentfirst}
\usepackage{marvosym} %For emoji
\usepackage{fontspec}
\usepackage{unicode-math}
\setmainfont{TeX Gyre Pagella}
\setsansfont{TeX Gyre Heros}
\setmonofont{Inconsolata}
\setmathfont{TeX Gyre Pagella Math}

\setlength{\parskip}{1ex}
\setlength{\parindent}{3ex}
\hypersetup{
    colorlinks=true,
    linkcolor=black,
    filecolor=black,
    urlcolor=darkscarlet,
    citecolor=darkscarlet
}
\urlstyle{tt}
\definecolor{darkscarlet}{rgb}{0.34, 0.01, 0.1}
\definecolor{ultramarineblue}{rgb}{0.25, 0.4, 0.96}
\definecolor{alizarin}{rgb}{0.82, 0.1, 0.26}
\definecolor{cadmiumgreen}{rgb}{0.0, 0.42, 0.24}
\definecolor{desertsand}{rgb}{0.93, 0.79, 0.69}
\lstdefinestyle{mystyle}{
    backgroundcolor=\color{white},
    commentstyle=\color{alizarin},
    keywordstyle=\color{ultramarineblue},
    stringstyle=\color{cadmiumgreen},
    basicstyle=\footnotesize\ttfamily,%\ttfamily,
    breakatwhitespace=false,
    breaklines=true,
    captionpos=b,
    keepspaces=true,
    showspaces=false,
    showstringspaces=false,
    showtabs=false,
    tabsize=2,
    language=C++,
    frame=single
}
\lstset{style=mystyle}
\pagestyle{plain}
\begin{document}
Một cái code đơn giản trong C++: (\textit{A simple code written in C++:})
\begin{lstlisting}
#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"Hello World!";
}
\end{lstlisting}
\end{document}

A: If you plan to use Vietnamese characters in listings (for comments, I guess), I'd recommend using minted.
There are a few monospaced fonts that support the T5 (Vietnamese) encoding. Here are some examples, the last one is inconsolata that, however, lacks support for Vietnamese, so it's not apt for the purpose.
\documentclass[11pt,a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{vietnam}
\usepackage{minted}
\usepackage{inconsolata}
\usepackage[unicode]{hyperref}

%%% this is only for the inconsolata example
\makeatletter
\define@key{FV}{fontencoding}%
  {\ifstrempty{#1}%
    {\let\FV@FontEncoding\relax}%
    {\ifstrequal{#1}{none}%
      {\let\FV@FontEncoding\relax}%
      {\def\FV@FontEncoding{\fontencoding{#1}}}}}
 \expandafter\def\expandafter\FV@SetupFont\expandafter{%
   \expandafter\FV@FontEncoding\FV@SetupFont}
 \fvset{fontencoding=none}
\makeatother
%%% end

%%% this is only for the txtt example
\makeatletter
\input{t5txtt.fd}
\DeclareFontShape{T5}{txtt}{m}{it}{<->ssub * txtt/m/sl}{}
\makeatother
%%% end

\begin{document}

\subsubsection*{TXTT}

\setminted{fontfamily=txtt}

\begin{minted}{cpp}
#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"Hello World!";
}
// Một cái code đơn giản trong C++
\end{minted}

\subsubsection*{LMTT}

\setminted{fontfamily=lmtt}

\begin{minted}{cpp}
#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"Hello World!";
}
// Một cái code đơn giản trong C++
\end{minted}

\subsubsection*{QCR}

\setminted{fontfamily=qcr}

\begin{minted}{cpp}
#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"Hello World!";
}
// Một cái code đơn giản trong C++
\end{minted}

\subsubsection*{ZLMTT}

\setminted{fontfamily=zlmtt}

\begin{minted}{cpp}
#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"Hello World!";
}
// Một cái code đơn giản trong C++
\end{minted}

\subsubsection*{ZI4}

\fvset{fontencoding=T1}
\setminted{fontfamily=zi4}

\begin{minted}{cpp}
#include<bits/stdc++.h>
using namespace std;
int main(){
    cout<<"Hello World!";
}
\end{minted}

\end{document}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Hurt: to feel pain in part of your body Hurt: to feel pain in part of your body
Can I say 'this pain really hurts in my back' instead of 'my back hurts'?

A:
Q. Can I say 'this pain really hurts in my back' instead of 'my back hurts'?

A. No you cannot because the pain does not hurt, it is the back that hurts. Pain is a symptom of the back being hurt.

'My back really hurts!'

My back is really painful

hurt; verb: to feel pain in a part of your body, or to injure someone or cause them pain. Ref C.E.D.
pain; noun [ C or U ]; a feeling of physical suffering caused by injury or illness. Ref C.E.D.


text:
Q: Javascript Regex to coerce url string returned from $.param into MVC model binding convention The following jQuery code:
 $.param({
                  Parts: [{ hasLabel: "label", hasType: "type", hasIndex : 1 }],
                  LastKey : "LastKey",
                  Term : "Term"
         })

gives the following output:
 "Parts%5B0%5D%5BhasLabel%5D=label&Parts%5B0%5D%5BhasType%5D=type&Parts%5B0%5D%5BhasIndex%5D=1&LastKey=LastKey&Term=Term"

which decodes to (using decodeURI()) :
 "Parts[0][hasLabel]=label&Parts[0][hasType]=type&Parts[0][hasIndex]=0&LastKey=LastKey&Term=Term"

However, the default model binder in MVC expects the following:
 "Parts[0].hasLabel=label&Parts[0].hasType=type&Parts[0].hasIndex=0&LastKey=LastKey&Term=Term"

I'm looking for a Javascript Regex to coerce the encoded string into a (still encoded) string , but one that decodes to the correct model binding convention.

A: The following should do the trick:
var params = "Parts[0][hasLabel]=label&Parts[0][hasType]=type&Parts[0][hasIndex]=0&LastKey=LastKey&Term=Term";
var mvcParams = params.replace(/\[([^0-9]+)\]/g,'.$1');

EDIT:
To work on an encoded string do the following:
var params = "Parts%5B0%5D%5BhasLabel%5D=label&Parts%5B0%5D%5BhasType%5D=type&Parts%5B0%5D%5BhasIndex%5D=1&LastKey=LastKey&Term=Term";
var mvcParams = params.replace(/%5b([^0-9]+)%5d/gi,'.$1');


text:
Q: Best practice to store constants for file names and property list names What would you consider best practice to store constants (like file names for property lists) in objective-c?
I would like to improve the hard coded "Config.plist" in the following code:
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"Config" ofType:@"plist"];
NSDictionary *rows = [[NSDictionary alloc]initWithContentsOfFile:plistPath];

A: The best solution usually is to move this kind of logic into a model object like MYConfiguration. That way you can query MYConfiguration with explicit methods, and never directly access the NSDictionary.
Regarding the name of that file, there are many approaches to abstracting it, depending on how much reuse you really need (it is possible to go overboard here).
First is the constant. In MYConfiguration.m, you can put a private constant like this:
static NSString * const kConfigurationFileBaseName = @"Config";

You can also have a method that returns the path:
- (NSString *)pathToConfigurationFile {
  return [[NSBundle mainBundle] pathForResource:kConfigurationFileBaseName ofType:@"plist"];
}

It's not uncommon to hard-code the name of the file directly in pathToConfigurationFile rather than having a constant. Constants often are only needed in cases where the value is used more than once. If a given constant only appears one time, then moving the value elsewhere can sometimes make the code harder to understand. These are just guidelines, not rules.
If you need the constant itself to be publicly available, then you declare it this way in MYConfiguration.h:
extern NSString * const kMYConfigurationFileBaseName;

and then define it in .m:
NSString * const kMYConfigurationFileBaseName = @"Config";

But the key in all of this is that you define these constants in a header related to the use of the constant. You don't create some central "MYGlobals" dumping ground for everything.

A: You could use NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:(id) forKey:(NSString *)];
[[NSUserDefaults standardUserDefaults] synchronize];

When dealing with objects like NSDictionary, you may have to convert it to an instance of NSData. This can be done with the following methods:
[NSKeyedArchiver archivedDataWithRootObject:(id)];

and
[NSKeyedUnarchiver unarchiveObjectWithData:(NSData *)];

respectively.


text:
Q: ViewModel fica NULL quando efetuado um submit na View Principal - Asp.Net Core MVC Tenho uma ViewModel (FilialViewModel) que possui uma propriedade do tipo PessoaViewModel. A View principal está atrelada à FilialViewModel e sempre que eu faço um submit, a propriedade do tipo PessoaViewModel fica NULL. Isso se dá pelo fato de que, no momento que chamo a PartialView Pessoa, Eu passo FilialViewModel.PessoaViewModel... Ao efetuar o submit, são carregados apenas os campos de FilialViewModel... Alguém sabe como resolver isso?
public class FilialViewModel
{
    [Key]
    public int PessoaFilialId { get; set; }

    [DisplayName("Tipo de Filial")]
    [Required(ErrorMessage = "Escolha um Tipo de Filial")]
    public FilialTipo FilialTipo { get; set; }

    public PessoaViewModel PessoaViewModel { get; set; }

}

public class PessoaViewModel
{
    [Key]
    public int Id { get; set; }

    [DisplayName("Natureza")]
    [Required(ErrorMessage = "Escolha uma Natureza")]
    public PessoaNatureza PessoaNatureza { get; set; }
    [DisplayName("Natureza")]
}

View Filial:
@model Retaguarda.Application.ViewModels.Filial.FilialViewModel
@{

}

            <vc:summary />
           @await Html.PartialAsync("~/Views/Pessoa/_Pessoa.cshtml", Model.PessoaViewModel)

View Pessoa:
@model Retaguarda.Application.ViewModels.Pessoa.PessoaViewModel
@using Retaguarda.Domain.Enuns.Pessoa
@{
    ViewData["Title"] = "Pessoa";
}

@Html.HiddenFor(model => model.Id, new { @class = "hidden-id" })

    Natureza
    <select id="pessoaNatureza" data-modal="" asp-for="PessoaNatureza" asp-items="Model.PessoasNaturezas" title="Selecione uma opção" class="form-control"><option value=""></option></select>

Controller:
[HttpPost]
[Authorize(Policy = "CanWriteFilialData")]
[Route("filial-gerenciar/cadastrar-novo")]
[ValidateAntiForgeryToken]
public IActionResult Create(FilialViewModel filialViewModel)
{
    if (!ModelState.IsValid) return View(filialViewModel);
    _filialAppService.Register(filialViewModel);

    if (IsValidOperation())
        ViewBag.Sucesso = "Filial cadastrada!";
    // return Json(new { success = true, message = "Pessoa Excuída!" });
    return View(filialViewModel);

}

A: PessoaViewModel vem nulo por que em nenhum momento ela foi instanciada.
Pode resolver isso instanciando em um construtor:
public class FilialViewModel
{
    public FilialViewModel()
    {
        PessoaViewModel = new PessoaViewModel();
    }

    [Key]
    public int PessoaFilialId { get; set; }

    [DisplayName("Tipo de Filial")]
    [Required(ErrorMessage = "Escolha um Tipo de Filial")]
    public FilialTipo FilialTipo { get; set; }

    public PessoaViewModel PessoaViewModel { get; set; }

}


text:
Q: Fluent NHibernate - exception occurred during configuration of persistence layer I am using Fluent NHibernate with an external 'hibernate.cfg.xml' file.
Following is the configuration code where I am getting error:
       var configuration = new Configuration();
       configuration.Configure();

       _sessionFactory = Fluently.Configure(configuration)
                .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Template>())
                .BuildSessionFactory();

        return _sessionFactory;

But When NHibernate is trying to configure, I am getting floowing error:
An exception occurred during configuration of persistence layer.
The inner exception says:

The ProxyFactoryFactory was not configured.
  Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.

I googled and according to some solutions I found, I have made following changes:

*

*Add following dlls to my app bin:
Castle.Core.dll, Castle.DynamicProxy2.dll, NHibernate.ByteCode.Castle.dll

*Added follwing property in hibernate.cfg.xml
<property name="proxyfactory.factory_class">NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle</property>
But still I am getting the same exception.

A: As Alex InTechno said, this might be the error in the definition of your Mapping files or in mapped entities. I experienced the same error, when I have forgot that all properties in mapped classes have to be defined as virtual.
public String Name {get;set;}
public virtual String Name { get; set; }

A: The problem might be in your hibernate.cfg.xml, double check that is using 2.2 version and if well formed.
The mapping should start like this:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">

Along with the error you post, maybe more information is supplied because that error is quite generic to the configuration parser. If not, maybe you can give more details of your hibernate.cfg.xml.

A: I had this error too. It fires when you don't copy the mapping file (hibernate.cfg.xml) to the build directory.
Solution:

*

*In Solution explorer, right click on the mapping file (hibernate.cfg.xml), choose Properties, then make sure that Copy To Output Directory has Copy if newer selected).

A: Exception with the text of PotentialReasons
* Database was not configured through Database method.

might be also thrown by the FluentConfiguration.BuildConfiguration() method in the case your mappings are wrong (i.e. .*Map classes were not successfully parsed) and you have configured database not with .Database() method.
This is a bit confusingly that it is discovered only at the step of building configuration, not when these classes are being added from assembly (by AddFromAssemblyOf<>)
You can check whether your *Map classes are successfully converted to HBM by executing a line
m.FluentMappings.Add(typeof(YourMappedTypeMap)).ExportTo(@"c:\Temp\fluentmaps"))

A: I had the same issue with NUnit tests under Resharper 8.1
Tick "ReSharper | Options | Tools | Unit Testing | Use separate AppDomain for each assembly with tests" checkbox fixed it

A: Well, I was able to resolve that error by placing .cfg.xml file in bin of calling app.
But now, I am getting another error :-(
FluentNHibernate.Cfg.FluentConfigurationException was unhandled
Message: An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
* Database was not configured through Database method.
Here is my hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="dialect">NHibernate.Dialect.MsSql2005Dialect</property>
    <property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
    <property name="connection.connection_string">Server=dev\sql2005;Initial Catalog=TestDB;Integrated Security=True</property>
    <property name="show_sql">true</property>
  </session-factory>
</hibernate-configuration>

Any thoughts?

A: Trying to configure the database in App.config and the mappings via Fluent NHibernate, I also got a FluentNHibernateException saying

*

*Database was not configured through Database method.

The link to show details was deactivated, so I couldn't get any further information. Searching for hours I finally found out that my connection string had an error ("pasword=xyz;" instead of "password=xyz;")

A: Try to set modifier protected in set_id and set_sampelList. for example:
public virtual int Id {
    get; protected set;
}

and
public virtual IList<Store> StoresStockedIn {
    get; protected set;
}

A: I begin receiving the
* Database was not configured through Database method.
error message while attempting to connect to a DB/2 database without having made any changes to my code.  After verifying that the configuration file was being copied to the build directory and verifying that my XML was well-formed and conformed to version 2.2, I finally went to check the database to ensure that nothing had changed.
It turned out that the password for the connecting account had expired.  It wasn't invalid nor was the account inactive--the password was merely expired.  I am not sure why the expired password manifested in such an odd error message.

A: It seems like this error can be a bunch of different things.  I got the same error and eventually figured out it was because I had excluded an unused view and mapping from the project.  No idea how this was causing the error but as soon as I added it back the error was gone.


text:
Q: Can I develop Windows Phone 7.1 apps using Windows Phone 8 SDK? Basically, if I download the WP8 SDK, can I develop WP7 apps with it?
Or can I only create WP8 apps?
Thanks.

A: The Windows Phone 8 SDK supports 7.1 projects but only in Visual Studio 2012.
Only 8.0 is available in Visual Studio 2013, however you can still use the 2012 Express IDE installed with the SDK to develop apps for both.

A: No, the APIs are not the same.
look here and download what you need
http://developer.windowsphone.com/en-us/downloadsdk

A: Unfortunately not, you'll have to download the seperate SDKs and use the workaround here: http://blogs.msdn.com/b/astebner/archive/2012/02/29/10274694.aspx, as far as I know.


text:
Q: how to embed an youtube video on my html page? I want to include a few youtube link on my webpage...Can anyone help me with this? I am relly new to this and i have no idea about the formats or things like these....Could you explain me what should I use and how to embed it between my html code?
Thank you very much

A: Just:

*

*Visit video's page

*Click the Share button

*Click the Embed button

*Copy/paste the code

Some videos are set to not be embeddable.

A: Try googling for "embed youtube video html". There's only 11.6 Million results, but you should be able to find something there.

*

*YouTube on Your Site

A: Just below the video in the youtube page there is a button named "Share".
Clicking that will expand the sharing box. Just click share and you will get an iframe which you can just copy and paste in your websites html.

A: you may find these youtube search results helpful


text:
Q: Is there on install event in android? Is there some event/receiver or something for handling first execution after installation or directly after installation? Or Do I need it emulate with preferences?

A: There is the ACTION_PACKAGE_ADDED Broadcast Intent, but the application being installed doesn't receive this.
So checking if a preference is set is probably the easiest solution.
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(this);
boolean firstRun = p.getBoolean(PREFERENCE_FIRST_RUN, true);
p.edit().putBoolean(PREFERENCE_FIRST_RUN, false).commit();

A: See Get referrer after installing app from Android Market - you can put whatever you want in there. I believe this is how Plan B works - the app that can send back your phone's location after it's stolen, that you install from the website after it's been stolen.

A: I don't think there is such a thing, and I don't think this would be a good idea : usually you have to handle not only installations but some updates (say : a new version with features) or the proper initialization of some resources.
For the resources, the best way is to check them directly.
For the version, I use the database, it's so easy.

A: The SQLiteOpenHelper's OnUpgrade method is called when the database version changed. I suppose this could be used to do other things than just handling the new schema.


text:
Q: Use XmlDeserializer in factory method? I have the following class representing an XML configuration stored in the DB:
using System.IO;
using System.Xml;
using System.Xml.Serialization;

[XmlRoot("ModalConfiguration")]
public class XmlConfiguration
{
    [XmlElement("Field1")]
    public XmlConfigurationField Field1 { get; set; }
    [XmlElement("Field2")]
    public XmlConfigurationField Field2 { get; set; }
    [XmlElement("Field3")]
    public XmlConfigurationField Field3 { get; set; }

    public static XmlConfiguration GetFromXmlString(string xmlString)
    {
        using (TextReader reader = new StringReader(xmlString))
        {
            var xmlSerializer = new XmlSerializer(typeof(XmlConfiguration));
            return xmlSerializer.Deserialize(reader) as XmlConfiguration;
        }
    }

    public string ToXmlString()
    {
        var sw = new StringWriter();
        using (XmlWriter writer = XmlWriter.Create(sw))
        {
            var xmlSerializer = new XmlSerializer(typeof(XmlConfiguration));
            xmlSerializer.Serialize(writer, this);
            return sw.ToString();
        }
    }
}

A co-worker told me that this is not a good practice, especially the static factory method, since the type should not be aware of how is it built. Instead, he suggested me to create a separated class with two methods, one which takes an XML string a returns a XmlConfiguration object, and one which takes an object and returns a string; and to leave this class as a simple DTO.
However, I see no problem in the object itself knowing about the internals of its construction (by deserialization), and on the contrary I think that we achieve a nice encapsulation with my approach.
What do you think, can you point out some advantages or disadvantages of the two approaches?

A: How you approach serialization and deserialization depends on the deployment environment and the context. More specifically, how critical is this component in the overall scheme of things will affect how you approach reliability, security, testability and other ...ilities.
Naive serialization makes the assumptions that
   - the version of what you exported is the same as what you import.
   - no corruption occurs in the export format
   - no malicious users are targeting your DTO. If none of those are now a problem for you, then your approach might work.
Other serialization approaches might be used in the future: Java, JSON, different versions of XML, for instance, and some of them might occur in the same deployment. By separating your factory from the underlying data, you run less chance of overwhelming the underlying data with the non-trivial import/export logic.
Small projects with small requirements can roll these aspects together into the same class.

A: Your design is OK if this is the only class that is being serialized.   But...
Every class that is written under this design will need GetFromXmlString and ToXmlString implementation since it is class specific.
It should be separated out so serialization can handle any class that has serialization markup.  Here's an example of a generic serialization for any string to object:
        public static T XmlStringToObject<T>(this string xml, string nameSpace=null)
        {
            if (string.IsNullOrWhiteSpace(xml)) return default(T);

            var serializer = nameSpace == null ? new XmlSerializer(typeof (T)) : new XmlSerializer(typeof (T), nameSpace);

            if (!_diagnosticsOn) return (T) serializer.Deserialize(new StringReader(xml));

            serializer.UnknownNode += serializer_UnknownNode;
            serializer.UnknownElement += serializer_UnknownElement;
            serializer.UnknownAttribute += serializer_UnknownAttribute;
            return (T) serializer.Deserialize(new StringReader(xml));
        }

Now any XML string that you want to convert to an object can be done.  One can also take any object and turn it into an XML string:
        public static string ToXmlString<T>(this T obj)
        {
            using (var writer = new StringWriter())
            {
                obj.ToXml(writer);
                return writer.ToString();
            }
        }

        private static void ToXml<T>(this T obj, StringWriter writer)
        {
            new XmlSerializer(typeof (T)).Serialize(writer, obj);
        }

So, this is clear separation.  The original class is still decorated with the XML serialization attributes so that XML serialization can occur.  If one wants to do JSON or some other format, just add those attributes (DataMember, etc) to the original class so that JSOn serialization can occur.
Again, if this is just a small project, your approach is fine, but for larger projects I would separate it out when dealing with potentially 10s to 100s of DTOs.


text:
Q: SQL Query Help on separating return result Example: On the phone table, someone has two phone number SQL would give me the a second row of the same person with different phone number instead of second column.  What query do I use to check if person_id appears more than once insert second row of data in a separate column?
I hope this make sense. Thanks in advance!

A: Try something like this:
SELECT person_id, COUNT(person_id) AS 'PersonIDCount' FROM phone_table
GROUP BY person_id
HAVING COUNT(person_id) > 1

The query will return all records where the same person_id key was inserted more than once.


text:
Q: find the $a_{111}$ if $a_{n+11}=a_{n+5}+2a_{n}$ Let sequence $\{a_{n}\}$ such $$a_{1}=a_{2}=\cdots=a_{10}=0,a_{11}=2$$,such
$$a_{n+11}=a_{n+5}+2a_{n}$$
Find the $a_{111}$
I want show this sequence is Periodic series。following is some try
$$a_{n+11}=a_{n+5}+2a_{n}$$
$$a_{n+17}=a_{n+11}+2a_{n+6}=a_{n+5}+2a_{n}+2a_{n+6}$$

A: We easily see that the generating function of this sequence is
$$
A(x)=\sum_{k=1}^\infty a_kx^k=\frac{2x^{11}}{1-x^6-2x^{11}}.
$$
By the sum formula of a geometric series $1/(1-q)=\sum_{k=0}^\infty q^k$ at $q=x^6+2x^{11}$ we arrive at the following identity of formal power series
$$
A(x)=2x^{11}\sum_{k=0}^\infty(x^6+2x^{11})^k.
$$
By the binomial formula the $k$th term contributes terms like $\binom{a+b}{a}x^{6a}(2^bx^{11b})$ where $a+b=k$. This term has degree $6a+11b$, and we are only interested in terms of degree $100$.
The parameters $a$ and $b$ are non-negative integers. It is relatively easy to figure out that the only solutions of $$6a+11b=100\qquad(*)$$ are $(a,b)=(2,8)$ and $(a,b)=(13,2)$. A good way is to observe that $(*)$ implies the congruence $6a\equiv100\equiv1\pmod{11}$, whence $a\equiv2\pmod{11}$.
Hence
$$
a_{111}=\binom{10}22^9+\binom{15}22^3=23880.
$$

This method may be useful whenever we have a suitably sparse recurrence relation. I don't recall having seen a general description of this though (but my recollection is not what it once was). Its usefulness is somewhat limited, because with higher indices the number of terms begins to grow. The actual problem may have been carefully drafted not to make this approach too arduous. The index $111$ was in a range where the number of terms was quite manageable.

A: I just put it in a spreadsheet.  The sequence is not periodic.  I find $a_{111}=23880$ but don't see a neat way to get that.
Added:  if I had to do it by hand I would just follow the recurrence backwards
$$a_{111}=a_{105}+2a_{100}\\=a_{99}+4a_{94}+4a_{89}\\
=a_{93}+6a_{88}+12a_{83}+8a_{78}$$
It will take about $18$ such lines.  After about $10$ lines terms will disappear off the end because of the known $0$ values.  It is a fair amount of work this way.


text:
Q: Working with Ruby on Rails 3.2 and Mailchimp Is there an actual gem or plugin for working with the mailchimp API in ruby on rails projects?
I tried the gems Gibbon and Hominid. But I'm not happy with them.


text:
Q: How to get total number of hours between two dates in sql server? Consider two dates 2010-03-18 22:30:45 and 2010-03-19 03:30:15 .... How to get the number of hours and minutes in between the two dates in sql server.....

A: You want the DATEDIFF function:
SELECT DATEDIFF(hh, @date1, @date2)

A: The problem with William Salzman's answer is that it returns strange answers if the first time is not on the hour. So 10:30 to 12:00 gives 2 hours and -30 minutes.
If that isn't what you want, then this will give you 1 hour and 30 minutes:
select
    CONVERT(int,DATEDIFF(mi, @date1, @date2) / 60) as Hrs_Difference,
    CONVERT(int,DATEDIFF(mi, @date1, @date2) % 60) as Mins_Difference

A: @codeka answered with the hours part (from your title) but in the body of your question you asked for hours and minutes so, here is one way
 select DATEDIFF(hh, @date1, @date2) as Hours_Difference,
    DATEDIFF(mi,DATEADD(hh,DATEDIFF(hh, @date1, @date2),@date1),@date2) as Minutes_Difference

What this does in the first part is what @codeka showed.  It gives you the datediff between the two dates in actual full hours.  The second term in the sql gives the datediff in minutes between the (first date + the hours elapsed) and the second date. You have to eliminate the hours from the equation in the minutes part or you will get the actual minutes between the dates.  Datediff and its allowed Datepart identifiers can be researched here:
http://msdn.microsoft.com/en-us/library/ms189794.aspx

A: DATEDIFF function will solve your problem of getting hours difference.
you can check this as :
select DATEDIFF(hh, getdate()-1, GETDATE()) HoursDifference

It will give you result of 24 hours
Thanks

A: It seems there are various ways to answer this, but for me, I've always believe in the notion of starting small - as in get the overall value and then convert it UP to the answer you want.
Assuming date2 is greater than date1:
A simple mathematical difference multiplied by 24 hours in a day works:
CAST(date2 - date1 as NUMERIC(18,4)) * 24.00 AS [HrsDiff]

Or using Will's answer using [min] for minutes:
CAST(DATEDIFF(mi, date1, date2) AS NUMERIC(18,4)) / 60 AS [HrsDiff]

So the minute total is divided by 60 to give you the hours.
The first option gives you a big decimal, whereas the 2nd option rounds it up to the nearest decimal.


text:
Q: If The Field Is NULL The Number Will Not Appear - USING PHP I have a blank data in mysql, and when I call it that blank data. The Number will Appear... Example

*

*Sample Data

*--Blank--

*Sample Data

I want to remove the Number 2. so that it will become 1-2..
$num = 0;

I use $num++ foreach data;
$num = 0;

mysql_connect('localhost','root','');

mysql_select_db('dbase');

$SQL = " SELECT * FROM table ";
$query = mysql_query($SQL);

while($data = mysql_fetch_assoc($query))
{
 $num++;

 echo $num;

 echo $data['Name']

}

OUTPUT :
1. SAMPLE
2.
3. SAMPLE

I want to make this
1. SAMPLE
2. SAMPLE

A: You could use an if statement to check if the value is empty.
Do this:
If($data['Name'] != ''){
   $num++;
   echo $num;
   echo $data['Name'];
}

A: You could add a condition in a WHERE clause on the SQL query so that only the rows you want to display are returned, I'd also recommend you add an ORDER BY clause to your query, so the result is more deterministic. And if you only need one column returned (the `Name` column), then specify the column in the SELECT list, instead of returning all columns in the table.
SELECT t.Name
    FROM table t
WHERE t.name <> ''
   ORDER BY t.name


text:
Q: Difference between running EJB from WAR vs. separate EJB container Are there any differences in capabilities of the EJB when defining / running it from a WAR vs. an EJB container? What are the benefits vs. drawbacks of deciding on one approach vs. other.
What capabilities do we lose when accessing it from a WAR?
In our case, the developers want to use the EJB for creating / accessing REST webservice.
One of our architects has mentioned below.  And for this reason he wants to have a separate EJB that would be added ( the jar ) to EAR but also to WAR for using it as REST endpoint. i would prefer not to have it in multiple places
I'd prefer our approach to put transaction/service based code in EJBs to
leverage Container Managed Transactions, JPA, MDB and all the good stuff EJBs
have to offer.

From the documentation I have read on using EJB as a REST service implementation, it says
Add the EJB class to the WEB-INF/classes directory of your WAR file or to a
JAR that is located in your WEB-INF/lib directory. When a client makes a request
to a JAX-RS annotated enterprise bean, the JAX-RS runtime environment looks up
and uses an EJB instance of the class to invoke the resource method.

So, I want to know, if we put the EJB in the WAR - as in creating the source in the WAR's source so that the class will be added to WEB-INF/classes when the WAR is built, instead of having to put the same ejb jar in two different places based on what it is used for - as a REST webservice endpoint vs. other capabilities, will it satisfy all the requirements or I will have to put the jar in two places?
I am using Websphere 8.5 with EJB 3.1, if that makes a difference in the answer.

A: There are two primary differences highlighted in section 15.4 of the EJB 3.1 specification:

*

*All EJBs in a WAR share the component namespace (java:comp) with the WAR and all other EJBs in the WAR.  Normally, each EJB has its own component namespace.  This makes it easier to share reference names and bindings (though this can be done explicitly in EE 6 with java:module or java:app), but it increases the chance of conflict in a large WAR.

*EJB classes are loaded by the WAR class loader.  In practice, this doesn't matter much, it's just something to be aware of if you encounter class loading problems.

If you want to use an EJB as a REST service, you must package the EJB in the WAR.  If you're concerned about "duplicating" EJB logic inside the WAR and for an EJB module, you could declare a base class in the EJB module, and then declare subclasses in the WAR and EJB modules that extend the base class and are annotated @Stateless or @Singleton.

A: Regarding EJB capabilities there is no difference between packaging an EJB in a WAR or in an EJB module.
There are situations where you have to package EJBs in WARs e.g. if you have a REST endpoint which is at the same time an EJB.
Most often WARs encapsulate frontend functionality. In these situations it is just from a design perspective not advisable to put the EJBs into WARs.


text:
Q: how to pass two arguments to function using sys.argv[][python] i want to pass two command line arguments.so am giving two arguments to the function .but my code giving me a following error.
importData() takes exactly 2 arguments (1 given) and am running my script
"python insert.py 10 20", insert.py is my python file name.
import MySQLdb as mdb
import sys
con = mdb.connect(host="localhost", user="root", passwd="Yogi123$", db="test")
cur = con.cursor()

def importData(count1,count):
    #print count
    for i in range(int(count1),int(count)):
        #print i
        name='jyothi'+str(i)
        #print name
        email='jyothi'+str(i)+'suragani@gmail.com'
        cur.execute("INSERT INTO example (name,email) VALUES ('%s','%s')" %(name,email))
        con.commit()
con.close

if __name__ == '__main__':
    data = importData(sys.argv[2])


text:
Q: What's the word for "the item which is sold"? I'm looking for a single word that describes a part or item being sold. The word should describe the individual items, not the product line, and should make no delineation between different products. It should just mean "an item which we sell, or is sold". Here's a simple example:
You work at a store that sells widgets. There are multiple product lines. You've got your standard widgets and your deluxe widgets. You have multiple stock of each product.
I want to say somethings like the following:
"Check that all the items to be sold are properly packaged"
"Each item to be sold must be tested before going on the shelf"
"Count how many deluxe items to be sold are in stock"
"Product" does not work as it describes the entire product line. "Part" is too vague, as it has too many other meanings, including the same as "product". "Stock" or "Stock item" does not work as it specifically means things which are in inventory.

A: Product is certainly preferable to item being sold, but have to be a little careful how we use it. This seems like a good working definition of the word:

product a set of identical items produced for sale, e.g. "the new product will double our profits"
products multiple of such sets, e.g. "the two new products will quadruple our profits"

You seem to be asking, how do you refer to a single element of such a set?
We observe product is a mass noun which refers to a set of things. Bars of soap and liters of water use units to identify a discrete part of the mass nouns soap and water. Similarly, unit of product could be used to identify a single item to be sold, although it sounds overly formal and almost academic.

"Check that all the units of product are properly packaged."
"Each unit of product must be tested before going on the shelf."
"Count how many deluxe units of product are in stock."

Another option is to use notional agreement, a grammatical convention that allows a group noun to be used with a plural verb when the individuality of its parts is important. This type of construct sounds strange to me, but it is purportedly not as rare in British English.

"Check that all the product are properly packaged."
"Count how many deluxe product are in stock."

Going by ear, the second example ("Each of the product must be tested") is almost certainly wrong, although a real plural noun would work ("Each of the widgets must be tested"). Either notionally plural nouns are more limited than syntactically plural nouns, or my American ears are balking at something technically acceptable.
Although I hope we all enjoyed this brief look into mass nouns, I suggest you use item or unit in those sentences, or, if applicable, identify the thing being packaged, shelved, or stocked more specifically.

A: I'd go with ware.

*

*articles of merchandise or manufacture; goods:

*any intangible items, as services or products of artistic or intellectual creativity, that are salable

(dictionary.com)
"Check that all the wares are properly packaged"
Of course, the definition of "ware" also suggests goods.
"Each good must be tested before going on the shelf"
"Count how many deluxe goods are in stock"


text:
Q: Impute mean based on cluster I have a binary classification task with high class imbalance - the mean y is 0.014.  Data consists of 100,000 rows and 40 columns. If I select rows where no column is NA I only get 10,000 rows back i.e. there are many NAs.
I know how to impute mean in python:
imp = Imputer(missing_values='NaN', strategy='mean', axis=0) #column wise
imp.fit(X)
X = imp.transform(X)

I want to first group observations clusters (e.g. via PCA or another method), then impute the mean based on clusters. Question: Is it (i) statistically sensible and (ii) possible in python?
I think I might use the following methods:

*

*logistic regression

*KNN

*Neural networks

A: Questions about Python are off topic here.
Statistically, if 90% of your data is missing, you have some serious problems. Imputing the mean, either the overall mean or the cluster mean, is going to cause problems.
Missing data is a huge area. There are lots of methods and the proper method depends on many factors.  The most important is probably whether the data are missing completely at random (MCAR), missing at random (MAR) or missing not at random.  Also important is whether the missingness is monotone or not.
But with so much missing data, I'd be very leery of any solution.


text:
Q: Determining if linear transformation from $\mathbb{R}^3$ to $\mathbb{R}^4$ is onto and/or one to one I have this question that I'm struggling with

Let $T(2,1,4) = (3,0,-3,6)$ and $T(1,-1,3) = (2,0,-2,4)$
is $T$ onto and/or one to one?

I tried breaking down the vectors as a combination on  $\mathbb{R}^3$ standard basis like this
$$2T(1,0,0) + T (0,1,0) + 4T(0,0,1) = (3,0,-3,6)$$
$$T(1,0,0) - T (0,1,0) + 3T(0,0,1) = (2,0,-2,4)$$
to understand how $T$ looks like but i have no clue how to continue.

A: Hint for the one-to-one part: note that
$$\frac{1}{3}T(2,1,4) = (1,0,-1,2)=\frac{1}{2}T(1,−1,3)$$
and recall that $T$ is linear.
Do you know any example of linear map from $\mathbb{R}^3$ onto $\mathbb{R}^4$?


text:
Q: gVim insert serial number before each matched pattern using regex I am using gVim on Windows. I have an XML file with content (extracted) like this:
      <ExtendedAttributes />
    </Activity>
    <Activity Id="ded54c70-1ef4-4aeb-852e-3740882c36ff" Name="Activity 1">
      <Performers>
        <Performer>2212646c-2674-4329-9ddc-1f8376e952e1</Performer>
      </Performers>
    </Activity>
    <Activity Id="cf70ec72-4d49-434a-abf3-aa3e8dc000b5" Name="Activity 2">
      <Description>This is a dummy description</Description>
      <Implementation>
        <Task />

I want to add a ID before the name of each activity, i.e.
<Activity Id="ded54c70-1ef4-4aeb-852e-3740882c36ff" Name="Activity 1">

will become
<Activity Id="ded54c70-1ef4-4aeb-852e-3740882c36ff" Name="10 Activity 1">

and
<Activity Id="cf70ec72-4d49-434a-abf3-aa3e8dc000b5" Name="Activity 2">

will become
<Activity Id="cf70ec72-4d49-434a-abf3-aa3e8dc000b5" Name="20 Activity 2">

and so on. I tried \(<Activity Id="[0-9a-f-]*" Name="\)\@<=[A-Za-z ,]\+ which can get the value of the "Name" attribute. But when I try to use the command :let i=0 | g/.... | let i=i+1 mentioned in http://vim.wikia.com/wiki/Making_a_list_of_numbers , I can never make it works. All I can do is to replace the names with the serial number (while I want the [serial number] [name] instead )
Could anyone shed some light?
Thank you very much.
Oliver
[edit]
I tried the followings:
:let @a=1 | %s/\(<Activity Id="[0-9a-f-]*" Name="\)\@<=\([A-Za-z() ,&?;/]\+\)/\=(@a+setreg('a',@a+1))/g

but it replaced the name with number only,
:let @a=1 | %s/\(<Activity Id="[0-9a-f-]*" Name="\)\@<=\([A-Za-z() ,&?;/]\+\)/\=(@a+setreg('a',@a+1)).\2/g

but I get "invalid expression",
:let @a=1 | %s/\(<Activity Id="[0-9a-f-]*" Name="\)\@<=\([A-Za-z() ,&?;/]\+\)/\=(@a+setreg('a',@a+1)).' '.\2/g

but I get "invalid expression",
:let @a=1 | %s/\(<Activity Id="[0-9a-f-]*" Name="\)\@<=\([A-Za-z() ,&?;/]\+\)/\=join((@a+setreg('a',@a+1)),' ',\2)/g

but I get "invalid argument for join()",
:let @a=1 | %s/\(<Activity Id="[0-9a-f-]*" Name="\)\@<=\([A-Za-z() ,&?;/]\+\)/\=(@a+setreg('a',@a+1))+\2/g

but I get "invalid expression".

A: Assuming your desired ID is the number following Activity multiplied by 10 (that's what i understand from your example), this could be done with:
:%s/Activity \(\d\+\)/\=submatch(1) * 10 . " " . submatch(0)

Breakdown…

*

*Perform the substitution on every line:
:%s/...

*Search for Activity, followed by a space, followed by one or more numbers, capture the numbers:
.../Activity \(\d\+\)/...

*Use the captured number and the whole match in a "sub-replace expression":
.../\=submatch(1)*10 . " " . submatch(0)

where we concatenate the captured number by 10, a space, and the whole match.
See :help sub-replace.

A: I finally figured out a way to do the task in 2 steps:
1) Insert a static string that are not likely to appear in the content (e.g. ##%%##%%) by the command:
:%s/\(<Activity Id="[0-9a-f-]*" Name="\)\@<=\([A-Za-z() ,&?;/]\+\)/##%%##%% \2/g
2) Replace the static string with number sequence:
:let @a=1 | %s/##%%##%%/\=(@a+setreg('a',@a+1))/g
It is not a perfect solution, indeed.  Any solution for 1 step only are welcomed. Thank you very much.

A: This one changes only at Activity that is at the end of the line.
First, we try the search separately
/Name="\zs[^"]*\ze"

Then ask our beloved vim
let @a=10 | %s//\=(@a+setreg('a', @a+10)) . " " . submatch(0)


text:
Q: Plot multiple columns combined I've tried to find an answer to this question, but I'm stuck...
I've several sheets where I collect statistic for my trading account performance, where each sheet represents a single month. All the sheets are alike (in terms of table structure) but number of rows is different.
One of the columns represents my current equity and change after each trade.
I would like to plot the values of this column from ALL the months sheets to a single chart in a continues order.
 - The data from January comes first.
 - The data from February after it
 - The data from March after and so on.
End result: I would like to get an equity curve of my account.
How can I do that?


text:
Q: getting error undefined variable for different functions Hello so i have a page where i call data from database to view it. on that page i have done a search function which is separated as below. but after creating the main function im having error: Undefined variable: db. i do not understand why is it looking for 'db' when the search function is a different function?
my blade file :

Answer Few Questions

       @foreach($db as $intentName => $questionAnswer)

       <?php
       $number = 0;
       ?>

                   {{$intentName}}

         <form action="{{action('AltHr\Chatbot\ChatbotController@savedmb', [$companyID, $entityType])}}" method="post">
               {{csrf_field()}}

           <button type="button" class="btn alt-btn alt-btn-green pull-right add-new">Add Answer</button>
           <button type="submit" class="btn alt-btn alt-btn-green pull-right">Save</button>

          @foreach($questionAnswer['q1'] as $question => $questionID)

User:

 {{$question}}

                   @endforeach

                   @foreach($questionAnswer['q2'] as $question => $questionID)

User:

 {{$question}}

                   @endforeach

                   @foreach($questionAnswer['q3'] as $question => $questionID)

User:

 {{$question}}

                   @endforeach

Answer:

             <input type="text" name="newAnswer[]" value="">

               </form>

                <?php
        $number++;
       ?>

                @endforeach

mainfunction:

 public function addType($companyID, $entityType)
 {
  $data = [];
  $intentTypes = DiraQuestion::select('intent')->where('company_id', $companyID)->groupBy('intent')->get();

  foreach ($intentTypes as $intent)
  {
   $data[$intent->intent] = $intent->intent;
  }

  $db = [];
  $dmb = DiraMasterBot::all();
  foreach ($dmb AS $datum)
  {
   if (!isset($db[$datum->description])) $db[$datum->description] = ['intent' => [], 'q1' => [], 'q2' => [], 'q3' => []];
   $db[$datum->description]['intent'][$datum->intent] = $datum->id;

   if (!isset($db[$datum->description])) $db[$datum->description] = ['intent' => [], 'q1' => [], 'q2' => [], 'q3' => []];
   $db[$datum->description]['q1'][$datum->sampleQ1] = $datum->id;

   if (!isset($db[$datum->description])) $db[$datum->description] = ['intent' => [], 'q1' => [], 'q2' => [], 'q3' => []];
   $db[$datum->description]['q2'][$datum->sampleQ2] = $datum->id;

   if (!isset($db[$datum->description])) $db[$datum->description] = ['intent' => [], 'q1' => [], 'q2' => [], 'q3' => []];
   $db[$datum->description]['q3'][$datum->sampleQ3] = $datum->id;
  }

  ksort($db);
  // dd($db);

  return view('AltHr.Chatbot.addType', compact('db','data','entityType','companyID'));
 }

search function:

 public function search(Request $request, $companyID, $entityType)
 {
  $data = [];
  $intentTypes = DiraQuestion::select('intent')->where('company_id', $companyID)->groupBy('intent')->get();

  foreach ($intentTypes as $intent)
  {
   $data[$intent->intent] = $intent->intent;
  }

  $q = $request->q;
     $user = DiraQuestion::select('eVal')->where('company_id', $companyID)->where('eType', $entityType)->where('eVal','LIKE','%'.$q.'%')->groupBy('eVal')->get();

     return view('AltHr.Chatbot.addType', compact('data','entityType','companyID'))->withDetails($user)->withQuery($q);
 }

A: Because you're returning the same view which is 'AltHr.Chatbot.addType'. So in that view file you are using $db variable in foreach loop. You should either check if $db variable is set before foreach loop or return another view without $db variable.


text:
Q: Positioning problems I've encountered this problem in which three of my anchors are not allowing the other three to get their right position but when I change the position to absolute it works fine but the three anchors merged with each other, is there a way that I can make this problem go away?
Any help will be appreciated
.R-news {
   width: 18rem;
   height: 18rem;
   margin:.5rem;
   background-color: #fff;
   box-shadow: 0 2px 0 0 #fff, 1px 3px 4px #333;
   float:right;
   clear:both;
}
.R-news img {
   height: 11rem;
   width:18rem;
}

Fiddle

A: Place your right floats before your other content in your markup. You also have to make sure the widths don't collide with each other. Check out my example.

...

...

http://jsfiddle.net/gr84a/10/


text:
Q: $M_n(F)$ contains an isomorphic copy of every extension of $F$ of degree $d \leq n.$ Source of the following Problem:Prob. $19.(b).,$ Section $13.2,$ from Abstract Algebra by Dummit and Foote(Second Edition).

Let $K$ be an extension of $F$ of degree $n.$ Prove that $K$ is isomorphic to a subfield of the ring $M_n(F),$ so $M_n(F)$ contains an isomorphic copy of every extension of $F$ of degree $d \leq n.$

I proved that $K$ is isomorphic to a subfield of the ring $M_n(F)$. I stuck in the next part, though from my previous question this it is clear that whenever $d | n$ it is true. But

Is it true if $d<n$ and $d$ does not divide $n.$

A: That's simply false, at least if one assumes the identity of $K$ maps
to the identity of $M_n(F)$. For an extension $K/F$ of degree $d$, $K$
can only have
an $F$-embedding in $M_n(F)$ if $d\mid n$.
Suppose $K$ embeds in $M_n(F)$. Then the space $C$ of column vectors of
height $n$ is a left $M_n(F)$-module, and so by restriction of scalars becomes a
vector space over $K$. If $\dim_K C=m$, then $n=\dim_K C=md$. Therefore
$d\mid n$.
But if one admits non-unital ring homomorphisms, then $M_d(F)$ embeds
in $M_n(F)$ for $d\le n$ by
$$A\mapsto\pmatrix{A&0\\0&0}$$
so the answer becomes yes if you accept this.


text:
Q: Drawing custom icon on form I'm creating a custom control in C# winforms. I've added an ICON to the resource, this icon is then drawn onto the control using the code below:
using (Icon oIcon = Properties.Resources.DropDownCustom)
{
    Rectangle RectangleIcon = new Rectangle((DropDownRectangle.X + ((DropDownRectangle.Width / 2) - (oIcon.Width / 2))),
        (DropDownRectangle.Y + (((DropDownRectangle.Height / 2) - (oIcon.Height / 2)) + 1)),
        oIcon.Width,
        oIcon.Height);
    graphics.DrawIcon(oIcon, RectangleIcon);
}

This all works fine no problem, but then I decided to add an option to the control properties to allow the developer to load their own icon to use rather than use the one I've placed in the resource. I created a private Icon variable:
private Icon _DropDownCustom;

changed the "using" line in the above code to read:
using (Icon oIcon = _DropDownCustom)

and then added to the constructor the following line to set the default value to the one in the resources.
_DropDownCustom = Properties.Resources.DropDownCustom;

I've then added an Icon property so the developer can use thier own icon:
[Category("Appearance"), DisplayName("IconDropDown")]
public Icon IconDropDownCustom
{
    get { return _DropDownCustom; }
    set { _DropDownCustom = value; this.Invalidate(); }
}

All this seems to be working fine, except now, when I view the control on a form (in development mode) it paints the icon onto the control - great, but as soon as I select the form, or the control the Icon disappears, but other painting stays (ie grading background).
Does anyone know why it doesn't seem to repaint the icon?
Many thanks.
EDIT:
I've just removed the "Using(){}" part of the code and changed it to:
Icon oIcon = _DropDownCustom;
Rectangle RectangleIcon = new Rectangle((DropDownRectangle.X + ((DropDownRectangle.Width / 2) - (oIcon.Width / 2))),
    (DropDownRectangle.Y + (((DropDownRectangle.Height / 2) - (oIcon.Height / 2)) + 1)),
    oIcon.Width,
    oIcon.Height);
graphics.DrawIcon(oIcon, RectangleIcon);

This seems to work as expected so I'm guessing it's something to do with using and disposing - Still trying to understand the displosing part - could you please explain why this is happening? I'm guessing my "oIcon" is basically just referencing my custom Icon variable rather than "by value" (I'm from a VB background).

A: The "using" block around your Icon resource will signal to the GC that the memory at that location is no longer needed and it will clean it up. So, after the first time it gets drawn the Icon will no longer be valid (unless you load it and dispose it every time you draw it).
You should probably either:

*

*Handle the close event of the control and dispose of the resources there.

*Implement the Disposable pattern on your user control to clean up resources (like your Icon) when your control is no longer needed.


text:
Q: How to save DataGridView multiple row data in to MySQL database in c# I have multiple row data in a single column. I need to save all data in to a MySQL DB. But it's only saving selected rows data only in DataGridView.
Below is my sample code.
private void button1_Click(object sender, EventArgs e)
{
    string price = dataGridView1[3, dataGridView1.CurrentCell.RowIndex].Value.ToString();

    string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price +"');";

    MySqlConnection myConn = new MySqlConnection(MySQLConn);
    MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
    MySqlDataReader myReader;
    try
    {
        myConn.Open();
        myReader = MySQLcmd.ExecuteReader();
        while (myReader.Read())
        {

        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Appreciate any help
Thank you!

A: One way is to use Foreach loop to get all rows value one by one in DataGridView and then insert them.
foreach (DataGridViewRow row in dataGridView1.Rows)
{
    string constring = "Connection String";
    using (MySqlConnection con = new MySqlConnection(constring))
    {
        using (MySqlCommand cmd = new MySqlCommand("INSERT INTO db1.table1 (price) VALUES (@price", con))
        {
            cmd.Parameters.AddWithValue("@price", row.Cells["ColumnName"].Value);
            con.Open();
            cmd.ExecuteNonQuery();
            con.Close();
        }
    }
}

A: If you want to save all rows from your Gridview then loop through it and pick up the column value to save.
Also if you want to save/update to the database, you should use ExecuteNonQuery. Finally, dispose of the objects you're creating and the reason for using.
using (MySqlConnection myConn = new MySqlConnection(MySQLConn))
{
    myConn.Open();

    MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
    MySqlParameter priceParameter = new MySqlParameter("@price");
    MySQLcmd.Parameters.Add(priceParameter);

    foreach (DataGridViewRow row in dataGridView1.Rows)
    {
       var price = row.Cells["PRICE_COLUMN_NAME"].Value;

       MySQLcmd.Parameters["@price"].Value = price;

       MySQLcmd.ExecuteNonQuery();
     }
}

A: Dear mbharanidharan88 and user3501749, Thanks for quick support.
With your sup I fond a new code.
Below is my full working code (for me).
private void button1_Click(object sender, EventArgs e)
    {
       try
        {
            string MySQLConn = "datasource=localhost;port=3306;username=root;password=root;";
            MySqlConnection myConn = new MySqlConnection(MySQLConn);
            myConn.Open();

            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
                string price = dataGridView1.Rows[i].Cells[3].Value.ToString();
                string Query = "INSERT INTO db1.table1 (price) VALUES ('"+ price + "');";
                MySqlCommand MySQLcmd = new MySqlCommand(Query, myConn);
                MySQLcmd.ExecuteNonQuery();

            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

If anything wrong let me know


text:
Q: How to move contents of one ArrayList to another? Is there a way to move the entire contents of an ArrayList to another instance of ArrayList in O(1)?
I.e.: only the reference to the backing array is passed from one instance to the other (elements are not copied one by one).
For example:
ArrayList<String> a = new ArrayList<>(Arrays.asList("A", "B", "C"));
ArrayList<String> b = new ArrayList<>();
a.moveContentsTo(b);
// 'a' is now empty, while 'b' contains everything that 'a' did before and 'a != b'
// It is desired that the 'moveContentsTo' method is O(1)

Even better, is there an ArrayList#swapContents(ArrayList) method?

Further explanation and use-case:
Further explanation 1: the references of 'a' and 'b' must not be exchanged. I am not looking for tmp = a; a = b; b = tmp; type of solutions.
Further explanation 2: The operation must be ~O(1) in time.
The use-case: This is useful when an object wants to encapsulate a list constructed outside:
public class A {
    private ArrayList<String> items = new ArrayList<>();

    /**
     * This method takes the sole ownership of the contents. Whoever
     * passed the list from the outside will not be able to modify
     * contents of 'this.items' from outside the class.
     */
    public AnImmutableObject(ArrayList<String> items) {
        if (items != null) {
            items.moveContentsTo(this.items);
        }
    }

    /**
     * Other collections that do not provide the 'move' functionality
     * must be copied. If we just stored the reference to 'items' we
     * would break encapsulation as whoever called the constructor
     * still have write capabilities to the collection.
     */
    public A(Collection<String> items) {
        if (items != null) {
            this.items.addAll(items);
        }
    }

    public List<String> getItems() {
        return Collections.unmodifiableList(items);
    }
}

Notice that we want to avoid making a copy (to increase speed and decrease memory usage). The crucial bit is that the callee must lose the ability to modify the (now encapsulated) ArrayList.

A: This should do it:
ArrayList<String> a = new ArrayList<>(Arrays.asList("A", "B", "C"));
ArrayList<String> b = a;
a = new ArrayList<>();

Conceptually speaking, a is now empty and b contains what a contained before. There was a single assignment and no copying of data, which is about the fastest you can do it. Does that satisfy your requirement, or do you actually want a to still reference the same array except that the given array should now be empty?
Update
I don't believe that in C++ the time complexity for the move operation is O(1) either. It's also prudent to point out that "because classes in Java use reference semantics, there are never any implicit copies of objects in those languages. The problem move semantics solve does not and has never existed in Java." (see the answer by FredOverflow: C++ Rvalue references and move semantics)

Is there a way to move the entire contents of an ArrayList to another ArrayList so that only the reference to the backing array is passed from one to the other (i.e., so that elements are not copied one by one).

Given the above statement, then if you copy something from array a to array b in Java, both arrays will reference the same data. All that you do with move semantics in C++ is that you save the temporary object which needs to be created in order to make such a copy:
X foo();
X x;
// perhaps use x in various ways
x = foo();

The last one does:
destructs the resource held by x,
clones the resource from the temporary returned by foo,
destructs the temporary and thereby releases its resource.

Move semantics does:
swap resource pointers (handles) between x and the temporary,
temporary's destructor destruct x's original resource.

You save one destruct, but only in C++... the above problem does not exist in Java! See this article for more details on move semantics: http://thbecker.net/articles/rvalue_references/section_02.html

A: @Lirik answer is greate +1. However, if you are looking for a real ArrayList#swapContents(ArrayList), here is how you can do it:
public static void swapContents(ArrayList<String> listA, ArrayList<String> listB)
{
    List<String> temp = new ArrayList<String>(listA);
    listA.clear();
    listA.addAll(listB);
    listB.clear();
    listB.addAll(temp);
}

A: AFAIK, it's very not Java-like to keep track of "ownership" of references (at least on the programmer's side) which is why I doubt that you'll find the std::move()-like functionality that you want. It just isn't very commonly needed in Java.
I guess C++ needs to keep track of object ownership explicitly because there is no garbage collection.
I think that your best bet is to create a defensive copy in your constructor and save space by relying on copy constructors of immutable objects:
public class AnImmutableObject {

    private final List<String> items;

    /**
     * Creates a new immutable object with the given list of items.
     * Always deep copy from an outside source, because we can't know if the
     * calling code will modify that collection later.
     */
    public AnImmutableObject(Collection<String> items) {
        // It's a constructor. We know items needs to be set.
        // We are creating a new array list, using its constructor which deep
        // copies the collection, and immediately wrapping it to make it truly
        // immutable. We are guaranteed that no one will hold a reference to the
        // mutable view of the new ArrayList.
        this.items = Collections.unmodifiableList(new ArrayList<String>(items));
    }

    /**
     * Creates a new immutable object with the same items as another.
     * Copying the reference here is completely safe because we
     * enforce the immutability of the items array.
     */
    public AnImmutableObject(AnImmutableObject source) {
        items = source.items;
    }

    public List<String> getItems() {
        return items;
    }
}

At this point, you can "pass the arrays around" (really share them) in O(1) between your own immutable objects:
ImmutableObject a = new ImmutableObject(Arrays.asList("A", "B", "C")); // O(n)
ImmutableObject b = new ImmutableObject(a); // O(1)

Hopefully, something like this can suit your purposes.
Another route you could go is use Guava's ImmutableList. Since these are immutable, you can safely copy the reference to the ImmutableList in a constructor.
The main approach is about making it safe for you to copy references to the lists rather than taking ownership over them.


text:
Q: Index for finding an element in a JSON array I have a table that looks like this:
CREATE TABLE tracks (id SERIAL, artists JSON);

INSERT INTO tracks (id, artists)
  VALUES (1, '[{"name": "blink-182"}]');

INSERT INTO tracks (id, artists)
  VALUES (2, '[{"name": "The Dirty Heads"}, {"name": "Louis Richards"}]');

There's several other columns that aren't relevant to this question. There's a reason to have them stored as JSON.
What I'm trying to do is lookup a track that has a specific artist name (exact match).
I'm using this query:
SELECT * FROM tracks
  WHERE 'ARTIST NAME' IN
    (SELECT value->>'name' FROM json_array_elements(artists))

for example
SELECT * FROM tracks
  WHERE 'The Dirty Heads' IN
    (SELECT value->>'name' FROM json_array_elements(artists))

However, this does a full table scan, and it isn't very fast. I tried creating a GIN index using a function names_as_array(artists), and used 'ARTIST NAME' = ANY names_as_array(artists), however the index isn't used and the query is actually significantly slower.

A: jsonb in Postgres 9.4+
The binary JSON data type jsonb largely improves index options. You can now have a GIN index on a jsonb array directly:
CREATE TABLE tracks (id serial, artists jsonb);  -- !
CREATE INDEX tracks_artists_gin_idx ON tracks USING gin (artists);

No need for a function to convert the array. This would support a query:
SELECT * FROM tracks WHERE artists @> '[{"name": "The Dirty Heads"}]';

@> being the jsonb "contains" operator, which can use the GIN index. (Not for json, only jsonb!)
Or you use the  more specialized, non-default GIN operator class jsonb_path_ops for the index:
CREATE INDEX tracks_artists_gin_idx ON tracks
USING  gin (artists jsonb_path_ops);  -- !

Same query.
Currently jsonb_path_ops only supports the @> operator. But it's typically much smaller and faster. There are more index options, details in the manual.

If the column artists only holds names as displayed in the example, it would be more efficient to store just the values as JSON text primitives and the redundant key can be the column name.
Note the difference between JSON objects and primitive types:

*

*Using indexes in json array in PostgreSQL
CREATE TABLE tracks (id serial, artistnames jsonb);
INSERT INTO tracks  VALUES (2, '["The Dirty Heads", "Louis Richards"]');

CREATE INDEX tracks_artistnames_gin_idx ON tracks USING gin (artistnames);
Query:
SELECT * FROM tracks WHERE artistnames ? 'The Dirty Heads';

? does not work for object values, just keys and array elements.
Or:
CREATE INDEX tracks_artistnames_gin_idx ON tracks
USING  gin (artistnames jsonb_path_ops);

Query:
SELECT * FROM tracks WHERE artistnames @> '"The Dirty Heads"'::jsonb;

More efficient if names are highly duplicative.
json in Postgres 9.3+
This should work with an IMMUTABLE function:
CREATE OR REPLACE FUNCTION json2arr(_j json, _key text)
  RETURNS text[] LANGUAGE sql IMMUTABLE AS
'SELECT ARRAY(SELECT elem->>_key FROM json_array_elements(_j) elem)';

Create this functional index:
CREATE INDEX tracks_artists_gin_idx ON tracks
USING  gin (json2arr(artists, 'name'));

And use a query like this. The expression in the WHERE clause has to match the one in the index:
SELECT * FROM tracks
WHERE  '{"The Dirty Heads"}'::text[] <@ (json2arr(artists, 'name'));

Updated with feedback in comments. We need to use array operators to support the GIN index.
The "is contained by" operator <@ in this case.
Notes on function volatility
You can declare your function IMMUTABLE even if json_array_elements() isn't wasn't.
Most JSON functions used to be only STABLE, not IMMUTABLE. There was a discussion on the hackers list to change that. Most are IMMUTABLE now. Check with:
SELECT p.proname, p.provolatile
FROM   pg_proc p
JOIN   pg_namespace n ON n.oid = p.pronamespace
WHERE  n.nspname = 'pg_catalog'
AND    p.proname ~~* '%json%';

Functional indexes only work with IMMUTABLE functions.


text:
Q: "Smart" page breaking for boxed content I am trying to load content from a central .tex file, then display it.
%%%%%%%%%%%%%%%
% central.tex %
%%%%%%%%%%%%%%%
\saveContent{A}{this is content "A"}
\saveContent{B}{this is content "B"}
\saveContent{C}{this is content "C"}
\saveContent{D}{this is content "D"}
% \vdots

.
%%%%%%%%%%%%%%%%
% document.tex %
%%%%%%%%%%%%%%%%
\documentclass{article}
\input{central.tex}

\useContent{A}
\useContent{B}
\useContent{C}

\begin{document}
  \displayUsableContent
\end{document}

The particular use case is that this allows me to write problem sets and exams using a question bank, editing only the top few lines of the document. I am sure there are many ways to do this.
Different content blocks have different sizes. Let's say that A takes up 0.5 (vertical) pages, B takes up 1.0 page, C takes up 1.5 pages, and D takes up 0.5 pages. I would like them to display as
+---+  +---+  +---+  +---+
| A |  | B |  | C |  | C |
|   |  | B |  | C |  | D | % (breaking D onto its own page would be acceptable)
|(1)|  |(2)|  |(3)|  |(4)|
+---+  +---+  +---+  +---+

I have tried wrapping the content in minipage, which cuts off the last 0.5 pages of C:
+---+  +---+  +---+  +---+
| A |  | B |  | C |  | D |
|   |  | B |  | C |  |   | % where is my C :(
|(1)|  |(2)|  |(3)|  |(4)|
+---+  +---+  +---+  +---+

I have tried wrapping the content in list, which doesn't respect trying to keep content together where possible:
+---+  +---+  +---+  +---+
| A |  | B |  | C |  | D |
| B |  | C |  | C |  |   | % B is broken but doesn't need to be :(
|(1)|  |(2)|  |(3)|  |(4)|
+---+  +---+  +---+  +---+

Is there a way to have LaTeX automatically break pages in this way? The rough rule is, If additional content cannot fit on the same page as previous content, put it on a new page; create page breaks in content if necessary.

A: I'm not sure about how to apply this solution but I think it can work. It consists in using tcolorboxes to include the problems in main document. In this case it's possible to control how much vertical space is used by a box. By default it's its natural height but you can use options like feight fill to use all available space in every page. It's also possible to use option heigth fixed for option in breakable boxes to decide if last fragment uses a complete page or only its natural height. Here you have some examples:
\documentclass{article}
\usepackage[most]{tcolorbox}
\usepackage{lipsum}

\tcbset{enhanced, breakable, height fixed for=all}

\begin{document}
\begin{tcolorbox}[height fill, title=Problem A]
\lipsum[1]
\end{tcolorbox}
\begin{tcolorbox}[height fill, title=Problem B]
\lipsum[1-3]
\end{tcolorbox}
\begin{tcolorbox}[title=Problem C]
\lipsum[1-5]
\end{tcolorbox}
\begin{tcolorbox}[height fixed for=none, title=Problem D]
\lipsum[1-5]
\end{tcolorbox}
\begin{tcolorbox}[height fill, title=Problem E]
\lipsum[1]
\end{tcolorbox}
\end{document}

Note: option blanker will suppress all frames and colors but keep vertical space.

A: Presuming the content is free to undergo page breaks (not boxed), just put
\filbreak

between content items


text:
Q: google maps export driving directions to kml file - java geogoogle Sorry at first for my poor grammar.
I am writing a program in Java using geogoogle (Google Geocoder Java API) http://geo-google.sourceforge.net/
I need from two specific points to get the walking directions between these points and also these info to be exported in a KML file.
Do you know how can I do it from Java? Is there an API that I can use? Perhaps making a call from the java program to google and handle the result - but how can it be done?
Thanks in advance.
PS. Google gives this functionality as i saw here http://www.gringod.com/2008/02/26/save-google-maps-driving-directions/ but I need all these to be called from Java.

A: I suspect that the geogoogle utility is already making requests to google that specify the KML output format, since it's easier to parse in java than JSON (the default). The trouble is that geogoogle isn't exposing the raw KML response to you.
If I were you, I'd stop using the geogoogle utility altogether, and make the requests to the geocoder yourself. It's really not difficult, you just send simple HTTP GET requests (see the documentation here), and you should be easily able to capture the raw KML responses and stick them wherever you like.


text:
Q: Hitting open sets Let $(\Omega,\mathscr F,(\mathscr F_t)_{t\geq 0},\mathsf P)$ be a complete filtered probability space and $X = (X_t)_{t\geq 0}$ be a cadlag stochastic process with value in a Polish space $E$. Is it true that for any closed subset $A$ of $E$ the first hitting time
$$
\tau = \inf\{t\geq 0:X_t\in A\}
$$
is a stopping time, i.e. $\{\tau\leq t\}\in \mathscr F_t$ for all $t\geq 0$; and what if $A$ is an open set.
As an example, we can consider $X$ with values in $\mathbb R$. It holds that the first hitting time of a closed half-line
$$
\tau = \inf\{t\geq 0:X_t\in[K,\infty)\}
$$
is a stopping time. Can we apply the following argument:

Let $\tau = \inf\{t\geq 0:X_t\in (K,\infty)\}$ then
  $$
\{\tau\leq t\} = \bigcup\limits_{n=1}^\infty\{\tau_n\leq t\}\in \mathscr F_t
$$
  where $\tau_n = \inf\{t\geq 0:X_t\in[K+1/n,\infty)\}$ and hence $\{\tau_n\leq t\}\in \mathscr F_t$.

A: The measurability of hitting times is a subtle and complex problem,
i.e., a pain in the neck. Of course, the raw $\sigma$-fields are pretty
much hopeless, even if the process has continuous paths and $A$ is open.
(Take two sample paths that start on the boundary of $A$; one stays put
while the other immediately heads into $A$. If $\tau_A$ were a stopping time,
 then $1[\tau_A=0]$ should be a function of the initial position only.)
It is often assumed that the filtration is complete and right continuous,
then things work out better. In this case, for open $A$ and $t>0$ we have
$$\{\tau_A<t\}=\cup_{r\in Q_t} \{X_r\in A\},$$
where $Q_t$ is the set of rational numbers in $[0,t)$. This, and the right-continuity
of the fields shows that $\tau_A$ is a stopping time.
For general Borel sets, I suggest reading The measurability of hitting times by Richard Bass,
Electron. Comm. Probab. 15 (2010) 99-105; 16 (2011) 189-191 for an elementary (but not easy)
exposition of quite general results about hitting times. Note that even
Prof. Bass made a subtle error, later corrected.  The paper and correction
 are number 130 on his home page:
http://bass.math.uconn.edu/biblio.html


text:
Q: align position of different symbols in legend R plots I have a plot using the map function in R.  I added a legend with a symbol, line and a box for three different variables, but the three symbols are not aligned.  The box is to the left of the other two symbols.  Does anyone know how I can get all three aligned.
   library(maps)
library(mapdata)

map("worldHires","USA",xlim=c(-75.5,-71),ylim=c( 36.5 ,42),col="gray90",fill=T)
box ()

legend(x="topleft", legend = c("2015 MAB Stations", "Scallop Access Areas",
      "2015 Survey Domain with NMFS Strata"),cex=.7,bg="white",lwd=c(NA,NA,1),
      pch=c(4,NA,NA),col=c("black" ,NA,"black"),fill=c("white","gray99",NA),border=c(NA,"black",NA),
      x.intersp=0.8)

I have tried changing x.intersp, y.intersp, xjust, and adj with no luck.
Thanks


text:
Q: Import and Export using a complex name with ES2015 Using node unit, I want to translate from ES5 the name of the test suite.
So I had in parser_test.js
exports['Awesome Parser Test'] = {
  setUp: function(done) {
    done();
  },
   ....
}

And now I have in parser_test.es6
export default {
  setUp: function(done) {
    done();
  },
   ....
}

Then in another file named index.es6
import parserTest from './parser_test';

export {
    parserTest
}

Node unit displays the suite name as parserTest which is OK, but I would prefer something like Awesome Parser Test

A: You can't have spaces in the import name. It's just a variable which is assigned the export of the file. You can, however, call it what ever you want. Eg:
import awesomeParserTest from './parser_test';
Or
import Awesome_Parser_Test from './parser_test';


text:
Q: Memory leak while setListener Memory leak in below example.
1.SpeedHelper.java:
public class SpeedHelper {

    interface Listener {
        void OnSelected(String entry);
    }
    static Listener sListener;

    static void setListener(Listener listener) {
        sListener = listener;
    }
    static Listener getListener() {
        return sListener;
    }
    static void clearListener() {
        sListener = null;
    }
}

2.CallSpeed.java
public class CallSpeed {

    protected void speed() {
        SpeedHelper.Listener litener = SpeedHelper.getListener();
        if (litener != null) {
            litener.OnSelected("mEntry");
        }
    }
}

3.MainActivity.java
public class MainActivity extends Activity {

    private CallSpeed callspeed;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SpeedHelper.setListener(mCallSpeedListener);
        callspeed = new CallSpeed();
        callspeed.speed();
    }
    private SpeedHelper.Listener mCallSpeedListener = new SpeedHelper.Listener() {

        @Override
        public void OnSelected(String entry) {
            Toast.makeText(getApplicationContext(), entry, Toast.LENGTH_SHORT).show();
        }
    };
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        SpeedHelper.clearListener();
    }
}

How to avoid Memory leak for "sListener"?

A: You can try to use static WeakReferences<Listener> sListener for variable definition in your  SpeedHelper class and change your getter and setter methods to:
static void setListener(Listener listener) {
    sListener = new WeakReference(listener);
}
static Listener getListener() {
    return sListener.get();
}

A: Your problem lies in the following non-static enclosed anonymous class in association with the static field sListener:
private SpeedHelper.Listener mCallSpeedListener = new SpeedHelper.Listener() {

        @Override
        public void OnSelected(String entry) {
            Toast.makeText(getApplicationContext(), entry, Toast.LENGTH_SHORT).show();
        }
    };

Because this is a non-static enclosed class, it contains a reference to its outer class, MainActivity.  This hidden reference blocks the release of the MainActivity class by the GC because the object mCallSpeedListener - which contains the hidden reference - get stored in the static field sListener with the instruction SpeedHelper.setListener(mCallSpeedListener);.  Therefore, the MainActivity object is never collected, its onDestroy function is never called and everything remains in memory; out of reach of the GC.  Using static fields is a door wide open to memory leaks and the presence of hidden references in enclosed classes (anonymous or not) amplifies this problem.
In your case, you will have to either remove the static field sListener or change the anonymous class to an ordinary class; one without the hidden reference to its outer MainActivity class or make a direct call to clearListener in another callback of the activity when it is terminated.


text:
Q: Is there tool to convert cobol file into csv or json I have a COBOL file and COBOL copybook. I'm not sure if these files are corrupted or not and I need to convert this data into CSV or JSON.
This is sample of the copybook, I'm not sure if this valid copybook or not.
000040* LTOT-TABRU        :INTEREST CODES TABLE  CULCOLATED*
000050*  ORGANIZATION     :INDEXED                         *
000060*  RECORD KEY       :CLE-TRUT                        *
000070******************************************************
000090*  CLE-TRUT         :INTEREST CODE                   *
000100*  LIB-TRUT         :NAME                            *
000120*  MONT-TRUT        :RATE CODE                       *
000150******************************************************
000160 FD  TOT-TABRU
000170     LABEL RECORDS ARE  STANDARD
000180     BLOCK CONTAINS 5  RECORDS
000190     RECORD CONTAINS 95 CHARACTERS.
000200 01  ENRE-TRUT.
000220     02 CLE-TRUT     PIC XXX.
000230     02 LIB-TRUT     PIC X(20).
           02 RATE-ITEM OCCURS 12 TIMES.
000240        03 MONT-TRUT PIC X(6).
              03 MONT-TRUT9 REDEFINES MONT-TRUT PIC 99V9999.

Is there a tool to convert this copybook and data file into readable format?

A: Have a look at the Record-Editor, it should be able to display the file (note there is a Cobol tab on the File Open screen).
The RecordEditor can generate scripts for

*

*Cobol To Csv

*Cobol to JSON

*Cobol to Xml


text:
Q: Notification generation issue in Android GCM I'm having the following two problems:
First Problem:
I have to register two customers who are using the same device, so they have the same Registration Id.
When I send an offer from the server side to both of these customers, the notification being displayed should depend on the logged in customer.
For example (see image):

In my application I have a customer login form. In this form, if user gnanavel logs in, the app has to receive his offers alone, and not the other's offers.
Similarly, if the user jeya logs in, the app has to receive her offers alone, and not the other's offers.
Currently the app is receiving both offers.
EDIT:
I have created login status field in my database.if my customer logs in the device means received the notification for his offers alone.i didn't get other's offers.its working well.
i have checked the condition while click the offer button:
 $getregid = mysqli_query($con,"select * from pim_customers where customer_id='$customer_id' and gcm_regid='$regId' and loginstatus='Y'");

i wrote these condition means my first problem is solved.but raised another problem.
The other problem is.,
When admin person enters some offer, the customer has to receive the notification on the device only when logged in the customer. Otherwise, the notification shouldn't be received. This part is working well.
The problem is, when my customer is logged out for a long time, and during that time the admin person entered more offers.
If the customer logs in the app after 2 days, he should receive all the pending messages. How can I get the pending messages?
admin side enters offers that time the customer logged out means loginstatus is 'N' in database.so how can execute these condition and receive the notification.
 $getregid = mysqli_query($con,"select * from pim_customers where customer_id='$customer_id' and gcm_regid='$regId' and loginstatus='Y'");

This is my server side code executed when clicking the offer button :
if (isset($_GET["regId"]) && isset($_GET["customer_id"]) && isset($_GET["message"])) {
  $regId = $_GET["regId"];
  $message = $_GET["message"];
  $customer_id = $_GET["customer_id"];
  include_once './GCM.php';
  $getregid = mysqli_query($con,"select * from pim_customers where customer_id='$customer_id' and gcm_regid='$regId' and loginstatus='Y'");
  $count1=mysqli_num_rows($getregid);
  while($row = mysqli_fetch_array($getregid))
  {
    $id=$row['customer_id'];
  }
  if (mysqli_num_rows($getregid) > 0) {
    $query = mysqli_query($con,"select count(offer) as count from pim_productdeal where customer_id='$id' and offer!=''");
    $count = mysqli_fetch_array($query);
    $msg = $count['count'];
    $gcm = new GCM();
    $registatoin_ids = array($regId);
    $message = array("price" => $msg." "."The offers received");
    $result = $gcm->send_notification($registatoin_ids, $customer_id, $message);
    echo $result;
  }
}

This is my Android side code:
public class GCMIntentService extends GCMBaseIntentService {

  private static final String TAG = "GCMIntentService";
  String regId;

  public GCMIntentService() {
    super(SENDER_ID);
  }

  @Override
  protected void onRegistered(Context context, String registrationId) {
    ServerUtilities.register(context, RegisterActivity.first_name, RegisterActivity.last_name, RegisterActivity.email, RegisterActivity.password, registrationId);
  }

  @Override
  protected void onUnregistered(Context context, String registrationId) {
    Log.i(TAG, "Device unregistered");
    displayMessage(context, getString(R.string.gcm_unregistered));
    ServerUtilities.unregister(context, registrationId);
  }

  @Override
  protected void onMessage(Context context, Intent intent) {
    Log.i(TAG, "Received message");
    GCMRegistrar.checkDevice(this);
    GCMRegistrar.checkManifest(this);
    regId = GCMRegistrar.getRegistrationId(this);
    String message = intent.getExtras().getString("price");
    displayMessage(context, message);
    if(Constants.response != null) {
      generateNotification(context,message);
    }
  }

  @Override
  protected void onDeletedMessages(Context context, int total) {
    Log.i(TAG, "Received deleted messages notification");
    String message = getString(R.string.gcm_deleted, total);
    displayMessage(context, message);
    // notifies user
    generateNotification(context,message);
  }

  @Override
  public void onError(Context context, String errorId) {
    Log.i(TAG, "Received error: " + errorId);
    displayMessage(context, getString(R.string.gcm_error, errorId));
  }

  @Override
  protected boolean onRecoverableError(Context context, String errorId) {
    // log message
    Log.i(TAG, "Received recoverable error: " + errorId);
    displayMessage(context, getString(R.string.gcm_recoverable_error,
            errorId));
    return super.onRecoverableError(context, errorId);
  }

  private static void generateNotification(Context context,String message) {
    int icon = R.drawable.icon;
    long when = System.currentTimeMillis();
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new Notification(icon, message, when);

    String title = context.getString(R.string.app_name);

    Intent notificationIntent = new Intent(context, MyDealProducts.class);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
            Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent intent =
            PendingIntent.getActivity(context, 0, notificationIntent, 0);
    notification.setLatestEventInfo(context, title, message, intent);
    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.defaults |= Notification.DEFAULT_SOUND;
    notification.defaults |= Notification.DEFAULT_VIBRATE;
    notificationManager.notify(0, notification);
  }
}

A: I edited your question to make it easier to understand. I hope that I didn't change your meaning. If I did, I apologize and ask you to correct me.
Now for my answer:

*

*Your server should be aware which user is currently logged in to which device. You should maintain in your server a table of logged in users, and for each logged in user it will hold the identifier of the device in which he/she is logged in. In order to do that you have to send a request to your server each time a user logs in or logs out. The request should contain the user id and the device id. For the device id you can either use the Registration ID or use some other ID that your server generates (it might be better to generate an ID in your server that would be shorter than the registration ID and therefore more efficient to use. You'll have to maintain a table that maps the registration ID to the device ID).

*When the admin creates a new offer and assigns it to a user, you will send a GCM notification to the app only if the user is logged in. Therefore, in your example of two users using the same device, if one of them is logged in, you will send only a single notification to that device for the logged in user. If none of them is logged in, you won't send any notifications. You will store the new offers in your DB and wait until one of them logs in.

*When a GCM message arrives to the device, you should make should that it is addressed to the current logged in user, since it's possible that one user logged out after the message was sent but another user logged in before it arrived to the device. For that purpose, your GCM message should include the user identifier as an additional field. If a message arrives to the device with a user ID that doesn't match the current logged in user, you discard that message and don't display a notification.

*When a user logs in, the server will receive a request (see #1). In the response of this request the server should return to the device all the offers that the user has in the server's DB.

*As for messages that were sent while the device was inactive for a long period of time - when the device becomes active again, old messages might be sent to it from GCM (if they haven't been discarded by GCM yet). If these messages don't belong to the current logged in user, you discard them (see #3). If they belong to the current logged in user, you should display them.

*I don't know PHP, but from my limited understanding of your server's code, it seems that you send to the device a GCM message that contains the number of offers the user has. You should probably use the same collapse_key for all messages you send. This way, if multiple messages were sent by your server while the device was offline, only one of them will be sent to the device when it becomes active again. You don't need to get all the pending messages if all they contain is the number of available offers.

A: You don't have to set time_to_live when sending message from your server. According to the docs default time-to-live is 4 weeks
Also make sure you don't unregister the device on user logout.

A: When you send a push notification from the server add a Notification_id field to it. Now use local database (SQLite) in your mobile to manage the notification ids which have been displayed to the user.
You need to implement a call to your web server for getting the current list of all notifications when the app starts. So that the notifications ids from the server can be matched with the local notification ids. Then you can fetch the details for those particular notifications whose id is not in your database.


text:
Q: How to use in ObjectiveC project C++ files I have a reqular objective C project. I import 10 C++ files into my project. All this files take "are communicating" with each other. If I have a look at File1.h, this file can manage all the operations in other class.
So, the question is How to include reference to File1.h and to call functions from it.
For example: [File1Class getAudioData];
If I include it by #include "File1.h", I will get a error "Class is unknown element"
P.S. I want to import aurioTouch2 sample code to my project and to call functions from theire C++ code.

A: You Can simply open both the projects in Xcode and drag and drop the files you need from the aurioTouch2 application. Make sure the files are actually copied by selecting the check mark that you get after you drop the files in your xcode project. After this, you will be able to use those files/classes. Consider using ".mm" as the extension of the implementation file in which you want to use the c++ files/classes. You may also use ".mm" as extension for your appdelegate implementation file in case you get c++ related errors.