text:
Q: POST Request not returning array from API - ngresource I'm trying to learn AngularJS and i am currently on the ngresource part.
What i'm trying to do is to POST request the API to get it to return me a array with information in the console log after a button click.

/*---------Service----------*/

app.factory('getTableGridDataService', function ($resource) {
    return $resource('API-URL-ADRESS', {}, { 'save': { method: 'POST' } })
});

/*---------Controller--------*/

    $scope.fillRealTable = function () {
        alert('Getting Data...');
        var arrayBody = {};
        var query = getTableGridDataService.save({}, arrayBody);
        query.$promise.then(function (data) {
            var loggItemList = data;
            alert('Done!');
            $scope.loggItems = loggItemList
            console.log($scope.loggItems);
            alert('Console Log Displayed!')
        })
    }
<!--BUTTON-->

    <button type="button" class="btn btn-default pull-right" style="margin-top:20px;" ng-click="fillRealTable()">Console Log Result</button>

So what i get in the console log is the Structure of the Array but nothing in it..
I know you have to pass like a body with it or something, but i couldn't find out how that is done the correct way, or maybe i found it but i couldn't understand what they where telling me haha :P
Anyways..The console.log result i get is something like this:

Hope you understand... sorry for the inconvenience if any.
Thanks in advance!


text:
Q: Appropriate clustering algorithm with mixed data types I have a customer data set with several features. These features have mostly different meanings e.g.

*

*(Currency / Money) Customer monthly spend in $

*(Count) Quantity of service x customer has active with us

*(Count) Quantity of service y that customer has with us

*(Boolean) Is customer a premium services customer

*(Boolean) Is customer some other kind of customer boolean

*(Time) Customer tenure in months

*(Time but entirely different meaning) Average time in a month spent using our call center

I had built a script using simple KMeans only because I've used it before and it's simple to understand.
Then, a post I came across told me to scale my data, that makes sense. But then I did some more research and found that KMeans is not ideal for clustering on binary fields. I have some binary fields, but not all my data are binary. The example features above pretty much cover the nature of the features that I have in my data set.
Can I still use Kmeans for clustering?
Are there some more appropriate algorithms to cluster data of this nature?
Edit:
On the topic of scaling, I was reading this SO post. From the accepted answer:

... and it is not appropriate to scale a discrete or categorical
  variable.

Should I scale some of my features and not others? Is this a standard practice? So with the example features above I would scale Customer monthly spend, the two count variables (integers) and the two time features since they are expressed as integers of whole months. Then, I would just leave the booleans, which are just dummied categoricals?

A: Clustering is an inexact science at the best of times, so there is no definitively correct way of doing this. On the question of scaling your features, considering the following:
You have two features, A and B. A is continuous, and you scale it so that its standard deviation and variance are 1. B is binary/boolean, and you don't scale.
Your cluster centroids along the B axis, will take a value between 0 and 1. In the most extreme case, a centroid could be at exactly 0 or 1. Thus the "most different" any given data point can be from any given centroid is 1, and this would contribute 1 to the Euclidean distance of this point from that cluster.
What about feature A? If a data point is a distance of 1 away from a centroid along the A-axis, it is exactly one variance away. Is this fair? Is a difference of one-sigma comparable with two readings of a binary variable being unequal ? It's hard to say and perhaps problem specific. What is likely true, is that you should scale your continuous data, otherwise, you could find that the variance is 0.001 or 1000 and then if you replayed my argument, it would start to sound silly.
In terms of whether to use KMeans, it's rather unprincipled to do so, and the results can be hard to interpret, but the algorithm itself is simple to understand and performs well, so there's no harm in using it. It's worth conducting sense checks of your results to see if you're getting anything sensible. One check would be to plot distributions of features in each cluster and see whether they separate and generally get less wide. Are the variances of each feature lower within clusters than globally (and much less so than if you took random samples of features with the same size as each cluster) ?
Your data has low enough dimensionality that you might also want to try using (H)DBSCAN as well as k-means and run some of the same sense checks I described.
If you want something more powerful, albeit no more principled, and with the benefit of being visualisable, you could try reducing the dimensionality of your data using t-SNE, UMAP or an Autoencoder and then using (H)DBSCAN. This will have the benefit that your data will go from being discrete along some axes, to looking close to continuous in your lower dimensional space. This will make clustering algorithms like k-means and DBSCAN more suitable. Also, you can plot the data in 2d and see whether the clustering is doing anything sensible.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Failing to install ruby-runtime due to null pointer exception I'm trying to install the ruby-runtime (0.12) plugin for Jenkins, but getting the following error:
ruby-runtime
 Failure -
java.lang.NullPointerException
    at java.lang.Class.isAssignableFrom(Native Method)
    at org.jenkinsci.jruby.JavaProxyConverter.canConvert(JavaProxyConverter.java:43)
    at com.thoughtworks.xstream.core.DefaultConverterLookup.registerConverter(DefaultConverterLookup.java:74)
    at com.thoughtworks.xstream.XStream$2.registerConverter(XStream.java:502)
    at com.thoughtworks.xstream.XStream.registerConverter(XStream.java:1422)
    at com.thoughtworks.xstream.XStream.registerConverter(XStream.java:1417)
    at org.jenkinsci.jruby.JRubyXStream.register(JRubyXStream.java:26)
    at ruby.RubyRuntimePlugin.initRubyXStreams(RubyRuntimePlugin.java:44)
    at ruby.RubyRuntimePlugin.start(RubyRuntimePlugin.java:28)
    at hudson.ClassicPluginStrategy.startPlugin(ClassicPluginStrategy.java:539)
    at hudson.ClassicPluginStrategy.load(ClassicPluginStrategy.java:528)
Caused: java.io.IOException: Failed to initialize
    at hudson.ClassicPluginStrategy.load(ClassicPluginStrategy.java:531)
    at hudson.PluginManager.dynamicLoad(PluginManager.java:872)
Caused: java.io.IOException: Failed to install ruby-runtime plugin
    at hudson.PluginManager.dynamicLoad(PluginManager.java:881)
    at hudson.PluginManager.dynamicLoad(PluginManager.java:820)
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1889)
Caused: java.io.IOException: Failed to dynamically deploy this plugin
    at hudson.model.UpdateCenter$InstallationJob._run(UpdateCenter.java:1893)
    at hudson.model.UpdateCenter$DownloadJob.run(UpdateCenter.java:1651)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.AtmostOneThreadExecutor$Worker.run(AtmostOneThreadExecutor.java:110)
    at java.lang.Thread.run(Thread.java:748)

I've found some questions on similar issues, however none of them seem to address this specific issue. Would greatly appreciate any assistance or where to go towards in terms of troubleshooting.


text:
Q: Confusion about the Evaluation of an Integral. I have a confusion about the following question:

Question. $\rho:\mathbb{R} \to \mathbb{R}$ be a continuous function such that $\rho(x) \ge 0 ~\forall ~x \in \mathbb{R}$, and $\rho(x)=0$ if $|x|\ge 1$ and $$\int_{-\infty}^{\infty}\rho(t)dt=1$$
  Let $f:\mathbb{R}\to\mathbb{R}$ be a continuous function. Evaluate $$\lim_{\epsilon \to 0}\frac{1}{\epsilon}\int_{-\infty}^{\infty}\rho(\frac{x}{\epsilon})~f(x) dx$$

My Solution. The last integral in the question reduces to :
$$
\lim_{\epsilon \to 0}\frac{1}{\epsilon}\int_{-1}^{1}\rho(\frac{x}{\epsilon})~f(x)dx
$$
Now we substitute $x/\epsilon=t$ in the last integral so that we have:
$\lim_{\epsilon \to 0}\frac{1}{\epsilon}\int_{-1}^{1}\rho(\frac{x}{\epsilon})~f(x)dx  = \lim_{\epsilon \to 0}\int_{-1/ \epsilon}^{1/ \epsilon}\rho(t)~f(\epsilon t)dt
 $
Is this right?...First, I cannot understand where the continuity of $\rho$ has been used. Is it even necessary?
Second, Is the interchanging of limit and integral permissible here? or does it require something more for this interchanging?
I'm not sure how to answer these question here...Please help me to understand what is going on here....!! Thank you so much.

A: First point to be noted: integral with respect to $t$ is from $-\frac 1 \epsilon$ to $-\frac 1 \epsilon$ but since $\rho $ is supported by $[-1,1]$ this does not cause any problem Secondly you have to justify interchnage of limit and integral. Consider $\int_1^{1} \rho (t)f(\epsilon t)\, dt -f(0)$ which you can write as  $\int_1^{1} \rho (t)[f(\epsilon t)-f(0)]\, dt$. Given $\eta >0$ we can find $r$ such that $|f(\epsilon t)-f(0)|<\eta $ if $\epsilon <r$ (because $|\epsilon t | \leq \epsilon)$ Now can you complete the proof?

A: In order to legitimize the interchange of limit and integral, consider the difference
$$\left|\int_{-1/\epsilon}^{1/\epsilon}\rho(t)~f(\epsilon t)dt-f(0)\right|=\left|\int_{-1}^{1}\rho(t)~(f(\epsilon t)-f(0)) dt\right|\leq \int_{-1}^{1}\rho(t)~\left|f(\epsilon t)-f(0)\right| dt$$
where $\epsilon\leq 1$.
Now, by the continuity of $f$ at $0$, for all $n>0$ there is $r>0$ such that $|f(x)-f(0)|<1/n$ for all $|x|<r$. Hence, for $|\epsilon|<r$, then $|\epsilon t|<r$ and
$$\left|\int_{-1}^{1}\rho(t)~f(\epsilon t)dt-f(0)\right|\leq \int_{-1}^{1}\rho(t)(1/n) dt=\frac{1}{n}$$
which goes to $0$ as $n\to+\infty$.


text:
Q: Finitely many ideals of given norm in rings of integers I'm trying to prove that there are only finitely many ideals of any given norm in the ring of integers $\mathcal{O}_k$ over a numberfield $K$.
I know there are "standard proofs" (e.g. How many elements in a number field of a given norm?), but I'm just wondering would a induction proof on the norm be valid:
(i) True for $n=1$.
(ii) For $n=k+1$, if $n$ is prime then it's either rammified, inert or split in $K$ which would mean there are 1, 0 or 2 ideals of norm $n$ respectively. If $n$ is composite then it can be factored into prime ideals of smaller norms (since $\mathcal{O}_k$ is a Dedekind domain), where there are only finite ideals of smaller norm, hence it follows by induction.
Thanks.

A: Your argument is more or less correct. Be careful, however - there could be a lot more than two prime ideals above a given prime (but there is a finite number). Also, induction is really awkward and not necessary here.
A much cleaner proof is just to use unique factorization directly: an arbitrary ideal of $\mathcal O_K$ can be written as $\wp_1^{r_1}\cdots\wp_t^{r_t}$, and the norm of this is $p_1^{r_1f_1}\cdots p_t^{r_1f_t}$. If you require that this equals $n$ for some $n$, then there are finitely many possibilities for $t$, for the $\wp$'s, and for the $r$'s.


text:
Q: How do I retrieve state from a different file in React There are 3 files below: Toggle.jsx, PersistentState.jsx, and Particles.jsx
A site that I am building has a theme toggle. When that toggle is pressed, the page switches between dark mode and light mode. I use a custom hook (PersistentState.jsx) to store state so that the theme of the page persists through page reloads (useState() does not persist so that is why I use a custom hook).
This is how I setup usePersistentState:
const [isDark, setIsDark] = usePersistentState('theme', true);

isDark is changed depending on if the toggle is checked or not. setIsDark is changed in the toggle's onChange event.
I am trying to access the value isDark in a different file, Particles.jsx. I am unsure of how to gain access to it since I cant just import it. This is what I need help with.

Files
Toggle.jsx
import React, { Component, useEffect } from "react";
import { usePersistentState } from './../hooks';

const Theme = () => {
    const [isDark, setIsDark] = usePersistentState('theme', true); // default to dark mode

    useEffect(() => {
        isDark ? document.documentElement.classList.add('other') : document.documentElement.classList.remove('other')
    });

    return (

                <input id="toggle" name="toggle" type="checkbox" checked={isDark} onChange={event => setIsDark(event.target.checked)} />

    )
}

class Toggle extends Component {
    render() {
        return (
            <Theme />
        );
    }
}

export default Toggle;

PersistentState.jsx
import React from 'react';

export default function usePersistentState(key, defaultValue) {
    const [state, setState] = React.useState(() => {
        const persistentState = localStorage.getItem(key);
        return persistentState ? JSON.parse(persistentState) : defaultValue;
    });
    React.useEffect(() => {
        window.localStorage.setItem(key, JSON.stringify(state));
    }, [state, key]);
    return [state, setState];
}

Particles.jsx
import React, { Component, useState } from 'react';
import { Particles as ReactParticles } from 'react-particles-js';

const PARAMS = () => {
    const [isdark, setIsDark] = useState(0) <- this does not work, how should I go about retrieving the value of isDark from Toggle.jsx
    console.log(isdark, setIsDark)

    return ({
        "particles": {
            "number": {
                "value": 60,
            },
            "color": {
                "value": `${isDark ? : ...}` <- where I need to use the value of isDark
            },
            ...
}

class Particles extends Component {
    render() {
        return (

                <ReactParticles width='100vw' height="100vh" params={PARAMS()} />

        )
    }
}

export default Particles;

A: Because your hook is not a singleton, whenever you call the custom hook the state does not persist - meaning you get new values every time.
Therefore you need to make your hook a singleton. The easiest way is to use a library like reusable and call it a day.
But if you think about it, you can make a singleton with a Context API:
// Wrap your application components
<ThemeContext.Provider value={{ isDark, setIsDark }}>...</ThemeContext.Provider>

// Change the hook implementation to use context
export default function usePersistentState(key, defaultValue) {
    const {isDark, setDark} = useContext(ThemeContext);

    React.useEffect(() => {
        ...
    }, [...]);
    return [isDark, setDark];
}


text:
Q: Serialize JSON array from a web request I am making what should be a very simple JSON request from a script task from SSIS. The URL return is very large, 20 million characters.
The first URL return line looks like this:
[{"brandId":"9","season":"SG","year":"2003","bomNumber":"00011111","costId":"00001","bomCCNumber":"0000008","firstCost":1.01,"landedFactor":1.234,"elc":9.876,"market":"MA","channel":"CH","destinationCountry":"DC"},...

I've run the URL return through a parser and verified that it is well-formed.
Here is my code.
[DataContract]
public class CostingNegotiated
{

    [DataMember(Name = "brandId")]
    public string brandId { get; set; }

    [DataMember(Name = "season")]
    public string season { get; set; }

    [DataMember(Name = "year")]
    public string year { get; set; }

    [DataMember(Name = "bomNumber")]
    public string bomNumber { get; set; }

    [DataMember(Name = "costId")]
    public string CostID { get; set; }

    [DataMember(Name = "bomCCNumber")]
    public string bomCCNumber { get; set; }

    [DataMember(Name = "firstCost")]
    public string firstCost { get; set; }
    [DataMember(Name = "landedFactor")]
    public double landedFactor { get; set; }

    [DataMember(Name = "elc")]
    public double elc { get; set; }

    [DataMember(Name = "market")]
    public string market { get; set; }

    [DataMember(Name = "channel")]
    public string channel { get; set; }

    [DataMember(Name = "destinationCountry")]
    public string destinationCountry { get; set; }

}

[DataContract]
public class RootObject
{
    [DataMember(Name = "CostingNegotiatedList")]
    public List<CostingNegotiated> CostingNegotiatedList { get; set; }
}

private RootObject GetWebServiceResult(string wUrl)
{

    HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);
    httpWReq.Method = "GET";
    httpWReq.ContentType = "application/json";
    httpWReq.Timeout = 300000;
    HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
    RootObject jsonResponse = null;

    try
    {
        //Get the stream of JSON
        Stream responseStream = httpWResp.GetResponseStream();

        //Deserialize the JSON stream
        using (StreamReader reader = new StreamReader(responseStream))
        {
            string r = reader.ReadToEnd();

            //Deserialize our JSON
            DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(RootObject));
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(r));
            jsonResponse = (RootObject)sr.ReadObject(ms);
        }
    }
    //Output JSON parsing error
    catch (Exception e)
    {
        FailComponent(e.ToString());
    }
    return jsonResponse;

}

I've verified that the string variable r has the JSON string. When I get to this line:
jsonResponse = (RootObject)sr.ReadObject(ms);

The jsonResponse has a RootObject, but the CostingNegotiatedList list variable is NULL. What do I need to do to get this list to populate?

A: I figured it out. My JSON doesn't have a header element, it's just a straight list, so I don't need my RootObject variable. I changed my code to refer to a list of my objects:
private List GetWebServiceResult(string wUrl)
{
HttpWebRequest httpWReq = (HttpWebRequest)WebRequest.Create(wUrl);
httpWReq.Method = "GET";
httpWReq.ContentType = "application/json";
httpWReq.Timeout = 300000;
HttpWebResponse httpWResp = (HttpWebResponse)httpWReq.GetResponse();
List<CostingNegotiated> jsonResponse = null;

try
{
    //Get the stream of JSON
    Stream responseStream = httpWResp.GetResponseStream();

    //Deserialize the JSON stream
    using (StreamReader reader = new StreamReader(responseStream))
    {
        string r = reader.ReadToEnd();

        //Deserialize our JSON
        DataContractJsonSerializer sr = new DataContractJsonSerializer(typeof(List<CostingNegotiated>));
        MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(r));
        jsonResponse = (List<CostingNegotiated>)sr.ReadObject(ms);
    }
}
//Output JSON parsing error
catch (Exception e)
{
    FailComponent(e.ToString());
}
return jsonResponse;


text:
Q: How to add custom properties dynamicly to a JMS Provider using Jython of Websphere V7 I would like to know how to add dynamicly custom properties to a JMS Provider with Jython script of Websphere V7. Can anyone provide an example script?
With dynamicly I mean no direct address with file path because it has to run on different machines. *.xml files are in different locations and profiles.
Here an example how the JMS provider is beeing created. You can use it to write the command to add the custom properties for this JMS Provider.
try:
 jmsProvider=AdminConfig.getid("/JMSProvider:MQProvider1/")
 if jmsProvider == "":
    name = ["name", "MQProvider1"]
    extICF = ["externalInitialContextFactory", "org.apache.activemq.jndi.ActiveMQWASInitialContextFactory" ]
    extPURL = ["externalProviderURL", "tcp://server:1234"]
    jmspAttrs = [name, extICF, extPURL]
    AdminConfig.create("JMSProvider", node, jmspAttrs)
    AdminConfig.save()

except:
    print '[ERROR] Task: #1'
    print sys.exc_type, sys.exc_value

A: I discovered my own how to add custom properties for JMS in Websphere V7:
try:
    jmsProvider=AdminConfig.getid("/JMSProvider:MQProvider1/")
    props = AdminConfig.create('J2EEResourcePropertySet', jmsProvider, [])
    AdminConfig.create('J2EEResourceProperty', props, '[[name "name1"] [value "value1"]]')
    AdminConfig.create('J2EEResourceProperty', props, '[[name "name2"] [value "value2"]]')
    AdminConfig.save()
except:
    print '[ERROR] Task: #2'
    print sys.exc_type, sys.exc_value


text:
Q: Jquery when keypress in input need autocomplete English letter on number I would like to replace letters into numbers as they're typed inside an <input type="text"> box.
Currently I use this code:
function Auto(str)
{
  var search = new Array(
    "q","w","e","r","t","y","u","i","o","p"
  );
  var replace = new Array(
    "1","2","3","4","5","6","7","8","9","0"
  );
  return str.replace(search, replace);
}

// me need make find in find_str but i dont know how...
$("#find").on('keypress',function(){
  find_str = $("#find").val();
  alert (Auto(find_str));
});

Tell me please how make find letter in find_str and how to write this code?
P.S.: alert() only for test.

A: replace doesn't do arrays. There are a couple of alternatives, like multiple replacements, but transliteration seems good:
var map = {q: '1', w: '2', e: '3', r: '4', t: '5', y: '6', u: '7', i: '8', o: '9', p: '0'};
var r = '';

for(var i = 0; i < str.length; i++) {
    r += map[str.charAt(i)] || str.charAt(i);
}

return r;

Also note that you're probably going to run into some focus problems, which are really annoying for users, so avoid things like this if at all possible.

A: replace takes a regular expression (or a string that will be converted to a regex) as the first argument and a string to replace matches or a function to compute replacements.
Therefore, you'd use this:
var map = {q:'1', w:'2', e:'3', r:'4', t:'5', y:'6', u:'7', i:'8', o:'9', p:'0'};
var keys = "[";
for (var key in map)
    keys += key.replace(/[\]-]/, "\\$&");
keys += "]";
var regex = new RegExp(keys, "g") // /[qwertyuiop]/g

function auto(str) {
    return str.replace(regex, function(match) {
         return map[match]; // the respective number
    });
}
$("#find").on('keyup', function(){
    alert( auto( this.value ));
});

If you really need to use arrays, of course you can do that, too.
var search =  ["q","w","e","r","t","y","u","i","o","p"],
    replace = ["1","2","3","4","5","6","7","8","9","0"];
var map = {};
for (var i=0; i<search.length && i<replace.length; i++)
    map[ search[i] ] = replace[i];
var regex = new RegExp("["+search.join("").replace(/[\]-]/g, "\\$&")+"]", "g");


text: Q: Multiple controllers with one route I have a controller which I want to deprecate but the deprecation can't be sudden. I will create a new controller and slowly migrate users from old controller to new controller. I don't want to change the routes, basically same route should be able to direct to old controller or new controller depending on a flag. Currently I am thinking of using redirect_to to give the control to the new controller from the old one. I want to figure out the cleanest possible way to do this. Any suggestions are welcome.


text:
Q: nodejs job server (multiple purpose) I'm fairly new and just getting to know node.js (background as PHP developer). I've seen some nodeJs examples and the video on nodejs website.
Currently I'm running a video site and in the background a lot of tasks have to be executed. Currently this is done by cronjobs that call php scripts. The downsite of this approach is when an other process is started when the previous is still working you get a high load on the servers etc.
The jobs that needs to be done on the server are the following:

*

*Scrape feeds from websites and insert them in mysql database

*Fetch data from websites (scraping) (upon request)

*Generate data for reporting. These are mostly mysql queries that need to be executed.

Tasks that need to be done in the future

*

*Log video views (when a user visits a video page) (this will also be logged to mysql)

*Log visitors in general

*Show ads based on searched video

I want to be able to call an url so that a job can be queued and also be able to schedule jobs by time or they can run constantly.
I don't know if node.js is the path to follow that's why I'm asking it here. What are the advantages of doing this in node? The downsites?
What are the pro's here with node.js?
Thanks for the response!

A: While traditionally used for web/network tasks (web servers, IRC chat servers, etc.), Node.js shines when you give it any kind of IO bound (as opposed to CPU bound) task, since it uses completely asynchronous IO (that is, all IO happens outside of the main event loop). For example, Node can easily hold open many sockets, waiting for data on each, or stream data to and from files very efficiently.
It really sounds like you're just looking for a job queue; a popular one is Resque, and though it's written for Ruby, there are versions for PHP, Node.js, and more. There are also job queues built specifically for PHP; if you want to stick to PHP, a Google search for "PHP job queue" make take you far.
Now, one advantage to using Node.js is, again, its ability to handle a lot of IO very easily. Of course I'm just guessing, but based on your requirements, it could be a good tool for the job:

*

*Scrape data/feeds from websites - mostly waiting on network IO

*Insert data into MySQL - mostly waiting on network IO

*Reporting - again, Node is good at MySQL queries, but probably not so good at analyzing data

*Call a URL to schedule a job - Node's built-in HTTP handling and excellent web libraries make this a cinch

So it's entirely possible you may want to experiment with Node for these tasks. If you do, take a look at Resque for Node or another job system like Kue. It's also not very hard to build your own, if you don't need something complicated--Redis is a good tool for this.
There are a few reasons you might not want to use Node. If you're not familiar with JavaScript and evented and continuation-passing style programming, Node.js may have a bit of a learning curve, as you have to force yourself to stop thinking synchronously. Furthermore, if you do have a lot of heavy non-IO tasks in your program, such as analyzing data, Node will not excel as those calculations will block the main event loop and keep Node from handling callbacks, etc. for your asynchronous IO. Finally, if you have a lot of logic already in PHP or another language, it may be easier and/or quicker to find a solution in your language of choice.

A: I second the above answers. You don't necessarily need a full-service job queue, however: you can use flow-control modules like async to run tasks in parallel or series, as fast as they'll go or with controlled concurrency.
Node.js has many powerful scraping/parsing tools. This post mentions a few; I just heard about Trumpet recently; there are probably dozens of options. Node.js has a Stream module in core and Request makes HTTP interactions extremely easy.
For timed tasks, the simplest approach is a basic setTimeout/setInterval. Or you could write the scraper as a script that's called on cron. Or have it triggered on some event using the EventEmitter module in core. etc...

A: Uncontrolled amount of node js parallel jobs may lay down your server. You will need to control processes or in better way put them in queue for each task
For this needs and if you know php I suggest to use gearman and add jobs by needs or by small php scripts


text:
Q: Aggregating firm specific data on an industry level based on SIC codes I have ~250,000 rows of firm-specific annual data(2000-2019) with and industry SIC code for each firm. The aim is to sum the value in each variable column for every individual SIC code based on the year. The data looks like this for the first couple of rows:
>head(compustat)
  gvkey datadate fyear indfmt consol popsrc datafmt curcd      at   capx     ceq emp      ni     revt xrd costat  sic
1  1004 20000531  1999   INDL      C      D     STD   USD 740.998 22.344 339.515 2.9  35.163 1024.333  NA      A 5080
2  1004 20010531  2000   INDL      C      D     STD   USD 701.854 13.134 340.212 2.5  18.531  874.255  NA      A 5080
3  1004 20020531  2001   INDL      C      D     STD   USD 710.199 12.112 310.235 2.2 -58.939  638.721  NA      A 5080
4  1004 20030531  2002   INDL      C      D     STD   USD 686.621  9.930 294.988 2.1 -12.410  606.337  NA      A 5080

For the columns "at", "capx", "ceq", "emp", "ni", "revt", "xrd" I want the total sum for all firms with identical SIC codes for each year. So my output would be the total value of all variables within the same industry SIC, for every year between 2000 and 2019.
Could someone help me achieve this?
Thanks,

A: Try this tidyverse solution. You can follow as strategy selecting the desired variables, set a group_by() and then use summarise_all() to compute the total sum. Your shared data is small but it should work with your larger data. Here the code:
library(tidyverse)
#Code
df %>%
  #Filter years
  filter(fyear>=2000 & fyear<=2019) %>%
  #Select variables
  select(sic,fyear,at,capx,ceq,emp,ni,revt,xrd) %>%
  #Group by sic and year
  group_by(sic,fyear) %>%
  #Compute total
  summarise_all(sum,na.rm=T)

Output:
# A tibble: 3 x 9
# Groups:   sic [1]
    sic fyear    at  capx   ceq   emp    ni  revt   xrd
  <int> <int> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <int>
1  5080  2000  702. 13.1   340.   2.5  18.5  874.     0
2  5080  2001  710. 12.1   310.   2.2 -58.9  639.     0
3  5080  2002  687.  9.93  295.   2.1 -12.4  606.     0

Some data used:
#Data
df <- structure(list(gvkey = c(1004L, 1004L, 1004L, 1004L), datadate = c(20000531L,
20010531L, 20020531L, 20030531L), fyear = 1999:2002, indfmt = c("INDL",
"INDL", "INDL", "INDL"), consol = c("C", "C", "C", "C"), popsrc = c("D",
"D", "D", "D"), datafmt = c("STD", "STD", "STD", "STD"), curcd = c("USD",
"USD", "USD", "USD"), at = c(740.998, 701.854, 710.199, 686.621
), capx = c(22.344, 13.134, 12.112, 9.93), ceq = c(339.515, 340.212,
310.235, 294.988), emp = c(2.9, 2.5, 2.2, 2.1), ni = c(35.163,
18.531, -58.939, -12.41), revt = c(1024.333, 874.255, 638.721,
606.337), xrd = c(NA, NA, NA, NA), costat = c("A", "A", "A",
"A"), sic = c(5080L, 5080L, 5080L, 5080L)), class = "data.frame", row.names = c("1",
"2", "3", "4"))

A: You can use dplyr library to achieve this:
Considering you have a dataframe dw like this:
dw <- read.table(header=T, text='
gvkey datadate fyear indfmt consol popsrc datafmt curcd      at   capx     ceq emp      ni     revt xrd costat  sic
1004 20000531  1999   INDL      C      D     STD   USD 740.998 22.344 339.515 2.9  35.163 1024.333  NA      A 5080
1004 20010531  2000   INDL      C      D     STD   USD 701.854 13.134 340.212 2.5  18.531  874.255  NA      A 5080
1004 20020531  2001   INDL      C      D     STD   USD 710.199 12.112 310.235 2.2 -58.939  638.721  NA      A 5080
1004 20010531  2000   INDL      C      D     STD   USD 701.854 13.134 340.212 2.5  18.531  874.255  NA      A 5080
1004 20020531  2008   INDL      C      D     STD   USD 710.199 12.112 310.235 2.2 -58.939  638.721  NA      A 5080
1004 20030531  2002   INDL      C      D     STD   USD 686.621  9.930 294.988 2.1 -12.410  606.337  NA      A 5080
1004 20030531  2002   INDL      C      D     STD   USD 686.621  9.930 294.988 2.1 -12.410  606.337  NA      A 5080
')

The following code can group it by sic and fyear and then select the rows where fyear is greater than 2000.
library(dplyr)
df = as.data.frame(dw %>% group_by(sic, fyear) %>% summarise(capx=sum(capx), ceq=sum(ceq),emp=sum(emp), ni=sum(ni), revt=sum(revt), xrd=sum(xrd)))
df = df[df$fyear >=2000, ]
print(df)

The final output looks this:
   sic fyear   capx     ceq emp      ni     revt xrd
  5080  2000 26.268 680.424 5.0  37.062 1748.510  NA
  5080  2001 12.112 310.235 2.2 -58.939  638.721  NA
  5080  2002 19.860 589.976 4.2 -24.820 1212.674  NA
  5080  2008 12.112 310.235 2.2 -58.939  638.721  NA


text:
Q: Validating signature trust with gpg? We would like to use gpg signatures to verify some aspects of our
system configuration management tools.  Additionally, we would like to
use a "trust" model where individual sysadmin keys are signed with a
master signing key, and then our systems trust that master key (and
use the "web of trust" to validate signatures by our sysadmins).
This gives us a lot of flexibility, such as the ability to easily
revoke the trust on a key when someone leaves, but we've run into a
problem.  While the gpg command will tell you if a key is
untrusted, it doesn't appear to return an exit code indicating this
fact.  For example:
# gpg -v < foo.asc
Version: GnuPG v1.4.11 (GNU/Linux)
gpg: armor header:
gpg: original file name=''
this is a test
gpg: Signature made Fri 22 Jul 2011 11:34:02 AM EDT using RSA key ID ABCD00B0
gpg: using PGP trust model
gpg: Good signature from "Testing Key <someone@example.com>"
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: ABCD 1234 0527 9D0C 3C4A  CAFE BABE DEAD BEEF 00B0
gpg: binary signature, digest algorithm SHA1

The part we care about is this:
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.

The exit code returned by gpg in this case is 0, despite the trust
failure:
# echo $?
0

How do we get gpg to fail in the event that something is signed with
an untrusted signature?
I've seen some suggestions that the gpgv command will return a proper exit code, but unfortunately gpgv doesn't know how to fetch keys from keyservers.  I guess we can parse the status output (using --status-fd) from gpg, but is there a better way?

A: This is what ended up with:
#!/bin/sh

tmpfile=$(mktemp gpgverifyXXXXXX)
trap "rm -f $tmpfile" EXIT

gpg --status-fd 3 --verify "$@" 3> $tmpfile || exit 1
egrep -q '^\[GNUPG:] TRUST_(ULTIMATE|FULLY)' $tmpfile

This looks for the trust information that gpg outputs on --status-fd.  The script exits with an error in the presence of an untrusted signature (or invalid/no signature):
$ sh checksig sample.sh.bad
gpg: Signature made Mon 24 Jun 2013 11:42:58 AM EDT using RSA key ID DCD5C569
gpg: Good signature from "Test User <testuser@example.com>"
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: 6FCD 3CF0 8BBC AD50 662E  5070 E33E D53C DCD5 C569
$ echo $?
1

The script exits with no error in the presence of a valid, trusted signature:
$ sh checksig sample.sh.good
gpg: Signature made Mon 24 Jun 2013 11:38:49 AM EDT using RSA key ID 5C2864A8
gpg: Good signature from "Lars Kellogg-Stedman <...>"
$ echo $?
0

A: So let me try to split the issue:
First issue seems that the key your are testing against is untrusted.
gpg -v < test.txt.asc
gpg: armor header: Version: GnuPG v1.4.11 (GNU/Linux)
gpg: original file name='test.txt'
this is a test
gpg: Signature made Thu 11 Aug 2011 09:09:35 PM EST using RSA key ID FE1B770E
gpg: using PGP trust model
gpg: Good signature from "John Doe <jdoe@noemail.com>"
gpg: WARNING: This key is not certified with a trusted signature!
gpg:          There is no indication that the signature belongs to the owner.
Primary key fingerprint: 5DD8 216D ADB1 51E8 4326  3ACA 1DED BB72 FE1B 770E
gpg: binary signature, digest algorithm SHA1

I assumed this is intentional... but before we get to how to fix, let me suggest you use gpgv instead of gpg -v? You will se why in a minute:
$ gpgv < test.txt.asc
gpgv: keyblock resource `/user/.gnupg/trustedkeys.gpg': file open error
gpgv: Signature made Thu 11 Aug 2011 09:09:35 PM EST using RSA key ID FE1B770E
gpgv: Can't check signature: public key not found

$ echo $?
2

No key, no trust... No we import the key into trustedkeys.gpg
$ gpg --no-default-keyring --keyring trustedkeys.gpg --import jdoe_pub.gpg
gpg: keyring `/user/.gnupg/trustedkeys.gpg' created
gpg: key FE1B770E: public key "John Doe <jdoe@noemail.com>" imported
gpg: Total number processed: 1
gpg:               imported: 1  (RSA: 1)
$ gpgv < test.txt.asc
gpgv: Signature made Thu 11 Aug 2011 09:09:35 PM EST using RSA key ID FE1B770E
gpgv: Good signature from "John Doe <jdoe@noemail.com>"

$ echo $?
0

Hope it helps

A: Two options come to mind (other than parsing the output).
A quick and dirty way would be to run both gpg and gpgv. The first run of gpg would ensure the key was fetched from the keyserver, and then gpgv will give you the return code you want.
A more elegant, controlled way (though it would involve more work) would be to use the gpgme library to verify the signature. It is a C library, though there are wrappers for Perl, PHP, Python and Ruby. (The Python one is quite low level, while the Ruby one has some higher level abstractions, not sure about Perl or PHP).
The GPGME library appears to talk to keyservers when I've used it, though you'd want to confirm that. I've written a bit of code that uses the ruby gpgme library (search for verify and verified_ok? for code that verifies a signature, and for sig_output_lines for some code that works out whether a signature is trusted).

A: What about migrating your system configuration to a tool like Puppet or Chef?
While a non-trivial amount of work, Chef (I have not used Puppet) you must create user accounts (and pub/private keys are generated).  While this doesn't prevent people from modifying the files local on the server, chef-client runs periodically, and will overwrite their changes on the next run.  (Periodic recurring runs occurs by default.)


text:
Q: Sencha touch 2.0 beta profiles does not work i am a beginner in sencha touch, i am trying to run a demo application using sencha touch profiles this is the code
<!-- index.html-->
<!DOCTYPE html>
<html>
    <head>
       <title>MOIC Touch</title>
       <link rel="stylesheet" href="touch/resources/css/sencha-touch.css" type="text/css">
       <script type="text/javascript" src="touch/sencha-touch-all-debug.js"></script>
       <script type="text/javascript" src="app.js"></script>
    </head>
    <body></body>
</html>

//app.js
Ext.require([
     'MOICTouch.profile.Tablet']);
Ext.application({
    name: 'MOICTouch',
    profiles: ['Tablet']
});

//app/profile/Tablet.js
Ext.define('MOICTouch.profile.Tablet', {
      extend: 'Ext.app.Profile',

      config: {
         name: 'Tablet',
         views: ['Main']
      },

      isActive: function() {
         return Ext.os.is.Tablet;
      }
 });

when i run index.html i got the following error in browser console
Uncaught Error: Ext.Loader is not enabled, so dependencies cannot be resolved dynamically. Missing required class: MOICTouch.profile.Tablet

can anyone help me,
thanks in advance

A: As you mentioned, you should enable Ext.Loader using the following code:
Ext.Loader.setConfig({ enabled: true });

However, this only happens because you are including sencha-touch-all-debug.js. The file includes the whole framework, so it presumes you do not need to use the Loader.
In development, you should use sencha-touch-debug.js. This will enable Ext.Loader by default, and will actually dynamically load each of the classes you require in the framework - instead of loading the whole framework up front.
There is more information about the different builds, and how to build your application for production over on the Sencha Touch API Docs - http://docs.sencha.com/touch/2-0/#!/guide/building


text:
Q: Add AnimationDrawable (PNG Sequence) to Canvas? I have started venturing into a bit of Canvas stuff and managed to add some statis PNG files to it.
Now I'd like to load in a PNG sequence, which I believe is an AnimationDrawable (rather then Bitmap)
I have written the XML file for the animation but then I am stumped.
I cannot find any examples of people adding PNG sequences to a Canvas object.

A: here is sample:
public class MainActivity extends Activity {

    private static final int FRAME_DELAY = 200; // in ms

    private ArrayList<Bitmap> mBitmaps;
    private final AtomicInteger mBitmapIndex = new AtomicInteger();
    private View mView;
    private Thread mThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // load resources
        mBitmaps = new ArrayList<Bitmap>();
        for(int resId : new int[]{
                // resource ids here
                R.drawable.ic_launcher,
                R.drawable.ddms_128,
                R.drawable.ddms_icon
                }){
            mBitmaps.add(BitmapFactory.decodeResource(getResources(), resId));
        }

        // create View and implement 'draw'
        ViewGroup root = (ViewGroup) findViewById(R.id.root);
        root.addView(mView = new View(this){
            @Override
            public void draw(Canvas canvas) {
                canvas.drawBitmap(mBitmaps.get(Math.abs(mBitmapIndex.get() % mBitmaps.size())), 10, 10, null);
                super.draw(canvas);
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();

        mThread = new Thread(){
            @Override
            public void run() {
                // wait and invalidate view until interrupted
                while(true){
                    try {
                        Thread.sleep(FRAME_DELAY);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        break; // get out if interrupted
                    }
                    mBitmapIndex.incrementAndGet();
                    mView.postInvalidate();
                }
            }
        };

        mThread.start();
    }

    @Override
    protected void onStop() {
        mThread.interrupt();
        super.onStop();
    }
}

activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/root"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

</RelativeLayout>

A: Canvas allows to draw line/shapes/bitmaps.
You managed to draw one bitmap.
Animation is just drawing one bitmap from bunch of them.
Canvas does nothing with drawables.
The logic neither related to Canvas nor to drawables.

A: Draw the first frame, then use a Handler to post delayed Message that when handled moves to the next frame and calls invalidate().
What you need to do is:
Step #1. Override VisualizerView.verifyDrawable(Drawable who)
@Override
protected boolean verifyDrawable(Drawable who) {
    return true;
}

Step #2. Modify MainActivity.addAnimationRenderer()
private void addAnimationRenderer() {
    final AnimationDrawable anim = (AnimationDrawable) getResources().getDrawable(R.drawable.png1);

    AnimationRenderer animRenderer = new AnimationRenderer(anim);
    mVisualizerView.addRenderer(animRenderer);

    anim.setCallback(mVisualizerView);
    mVisualizerView.post(new Runnable() {
        @Override
        public void run() {
            anim.start();
        }
    });
}

Step #3. Modify AnimationRenderer: delete
mBitmap.setCallback(null);
mBitmap.start();


text:
Q: Is it a drive path or another? Check with Regex I would like to check whether it is a drive path or a "pol" path.
For this I have already written a small code, unfortunately, I always return true.
The regex expression may be incorrect \W?\w{1}:{1}[/]{1}. How do I do it right?The path names can always be different and do not have to agree with the pole path.
Thank you in advance.

public bool isPolPath(string path)
{
     bool isPolPath= true;
     // Pol-Path:       /Buy/Toy/Special/Clue
     // drive-Path:     Q:\Buy/Special/Clue

     Regex myRegex = new Regex(@"\W?\w{1}:{1}[/]{1}", RegexOptions.IgnoreCase);
     Match matchSuccess = myRegex.Match(path);
     if (matchSuccess.Success)
         isPolPath= false;

     return isPolPath;
}

A: You don't need regexes to achieve this. Use System.IO.Path.GetPathRoot. It returns X:\ (where X is the actual drive letter) if the given path contains drive letter and an empty string or slash otherwise.
new List<string> {
    @"/Buy/Toy/Special/Clue",
    @"q:\Buy/Special/Clue",
    @"Buy",
    @"/",
    @"\",
    @"q:",
    @"q:/",
    @"q:\",
    //@"",    // This throws an exception saying path is illegal
}.ForEach(
    p => Console.WriteLine(Path.GetPathRoot(p))
);

/* This code outputs:
  \
  q:\

  \
  \
  q:
  q:\
  q:\
*/

Therefore your check may look like this:
isPolPath = Path.GetPathRoot(path).Length < 2;

If you wish to make your code more foolproof and protect from exception when an empty string is passed, you need to decide if an empty (or null) string is a pol-path or drive path. Depending on the decision the check would be either
sPolPath = string.IsNullOrEmpty(path) || Path.GetPathRoot(path).Length < 2;

or
if (string.IsNullOrEmpty(path))
    sPolPath = false;
else
    sPolPath = Path.GetPathRoot(path).Length < 2;


text:
Q: Where to get ruby-asana documentation I am new to Ruby and trying to learn how to use the Asana API. I have installed ruby-asana and am using Notepad++. I am having issues figuring out how to do things. I read that ruby-asana is a wrapper for Asana API and I see a few code snippets. Is there a help file somewhere that documents the classes, methods, etc?

A: Yes! You can find these docs here: http://www.rubydoc.info/github/Asana/ruby-asana/master Note the menu on the left, which expands to provide reference docs on classes/methods.


text:
Q: Google Charts Does not render for a scatter plot with multiple colors I am plotting up data in Google Charts and continue to have trouble rendering my HTML. I could sure use a second pair of eyes to check if there is anything obviously wrong with the code below.  The data has three columns, each of which is meant to be plotted a different color.

A: Call to arrayToDataTable() is wrong. Instead of
var data = google.visualization.arrayToDataTable()({
        [['x','Virg','Set','Versi'],
        [1.0,null,null,1.0],
        [2.0,null,2.0,null],
        [3.0,3.0,null,null]]

});

you have to use
var data = google.visualization.arrayToDataTable([
        ['x','Virg','Set','Versi'],
        [1.0,null,null,1.0],
        [2.0,null,2.0,null],
        [3.0,3.0,null,null]
]);

Instead of an object of array you have to provide an array of arrays. And unnecessary () deleted.
**Update: ** example at jsbin.


text:
Q: T4 code generation: access types in current project Using T4 code generation, is it possible to access the types defined in the current project?
For example, if I have an interface and I want to delegate its implementation to another class, i.e.
interface IDoSomething {
    public void do_something();
}

class DoSomethingImpl : IDoSomething {
    public void do_something() {
        // implementation...
    }
}

class SomeClass : IDoSomething {
    IDoSomething m_doSomething = new DoSomethingImpl();

    // forward calls to impl object
    public void do_something() {
        m_doSomething.do_something();
    }
}

I would like to automate the call-forwarding in SomeClass with code generation; is this possible?

A: While this doesnt solve the locking problems (although ive heard that VS2010 does), you could try copy the dll to a temp location and just use that copied assembly..
<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".txt" #>
<#@ import namespace="System.Reflection" #>
<#@ import namespace="System.IO" #>
<#
var newFileName = System.IO.Path.GetTempFileName();
System.IO.File.Copy(@"C:\Development\CustomAssembly.dll",newFileName,true);

var assembly = Assembly.LoadFrom(newFileName);
var type = assembly.GetType("CustomAssembly.DummyClass");
#>
<#=newFileName#>
<#=type#>


text:
Q: Finding the shape and scale of a gamma distribution given home range pasted below is supplemental material from an article. After finding home range values, the authors say, "gamma(13,10) covers this nicely". How did the authors find 13 and 10?
# Moldenhauer and Regelski (1996) state that home range size typically
# ranges from 0.08-0.65 ha, which equates to a radius of
sqrt(0.08/pi*10000) # 15.96 m or
sqrt(0.65/pi*10000) # 45.49 m

# Since parulas were detected by song, let's be safe
# and add a minimum and maximum
# distance at which they could be heard, 50 and 250 m, based upon
# Simons et al. (2009).
# So now we have an area between
(15.96+50)^2*pi / 10000  # 1.37 ha, and
(45.49+250)^2*pi / 10000 # 27.4 ha

# We note that this is a very large range.

# Following Royle et. al (2011), and assuming a
# chi-squared distribution with 2 degrees of freedom,
# the range of sigma is given by
sqrt(1.37*10000/pi)/sqrt(5.99)   # 27 m
sqrt(27.4*10000/pi)/sqrt(5.99)   # 120 m

# In our grid spacing, 1 unit = 50m, so our we want a prior with most
# of the density between:
27/50  # 0.54
121/50 # 2.42

# Gamma(13, 10) covers this nicely
qgamma(c(0.001, 0.5, 0.999), 13, 10)

plot(function(x) dgamma(x, 13, 10), 0, 5, xlim=c(0, 3), ylim=c(0, 1.5))**

A: Honestly, I think the answer to this may just be a bunch of hand waving.  If I were to choose a gamma prior and had some intuition about the range I would find the median value and make it the mean of the gamma distribution. So for this example I would do something like:
# Find median of range (which is 1.48)
gamma_med <- median(seq(0.54, 2.42, length.out = 1e6))

The gamma distribution has two parameters, gamma(a,b). The first moment, or the mean, can be calculated easily because it is just a/b.  Therefore, if we want our mean to be 1.48 we just need to choose a shape (a) and scale(b) whose ratio equals 1.48.  The simplest one would be gamma(14.8, 10), but we could increase or decrease our variance by changing those parameters (variance of gamma = a/(b^2)).
Here is how different the two priors are, you can see how gamma(13,10) is more precise.  At the end of the day though it really comes down to what you feel is defensible in what you want your priors to be (or preferably you should use multiple priors to see how they influence your posterior).


text:
Q: Ruby on Rails 4 - form not updating additional field I have recipe and ingredient model which have association set as
Recipe has_many :ingredients
accepts_nested_attributes_for :ingredients, :reject_if => :all_blank, :allow_destroy => true

Ingredient belongs_to :recipe

and strong parameter defined in recipes_controller
def recipe_params
  params.require(:recipe).permit(:title, :image, :serving, :prep, :cook, :steps, ingredients_attributes: [:id, :name, :_destroy])
end

and the submitted form sends the following parameters
Request

Parameters:

{"utf8"=>"✓",
 "_method"=>"patch",
 "authenticity_token"=>"zT+9YEIh6ZNxO3wrV8ajj8NyVaTfPDel171hasWk2DA=",
 "recipe"=>{"title"=>"Recipe with image",
 "serving"=>"3",
 "prep"=>"10 min ",
 "cook"=>"19 min"},
 "ingredient"=>{"name"=>["Chicken", "Beef"]},
 "commit"=>"Update Recipe",
 "id"=>"4"}

The problem is that the additional ingredient Beef does not get persisted in the database.
I wonder if I also have to pass in ingredient_id hash as defined in recipe_params or I need some kind of reference in the parameter for the association with recipe.
This additional field was generated with script and I don't think this value gets lost after form is submitted as it shows in the request parameters.
I would appreciate your input.

A: You use fields_for when create form in view?
you post contain ingredient, but should be contained ingredients_attributes
Follow http://railscasts.com/episodes/196-nested-model-form-part-1


text:
Q: how to use tax_query to apply both terms or one if one is empty I'm having trouble with getting tax_query to act as a filter for posts. What I would like is to have it so it will display cpt's that have the terms of county and status but also work if terms are not provided for status or county. So have the posts show if it has the term of "Adams" county in the County taxonomy and the the term of "Locked" in the Status taxonomy. But it needs to also work if a County is not provided, just a status and vice-versa.
Here is my code:
    <?php
    $args = array(
        'post_type' => 'property',
        'posts_per_page' => 5000,
        'tax_query' => array(
            'relation' => 'AND',
            array(
            'taxonomy' => 'Status',
            'field' => 'slug',
            'terms' => explode( ',', $st_term_final_string    )
            ),
            array(
            'taxonomy' => 'County',
            'field' => 'slug',
            'terms' =>  explode( ',', $il_term_final_string )
            )
        )
    );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
        the_title();
        echo '
';
        echo get_the_post_thumbnail();
        the_content();
        echo '
';
    endwhile;
    ?>

Any hints to put me in the right direction?
Thanks in advance

A: Change your code with the following:
$args = array(
  'post_type' => 'property',
  'posts_per_page' => 5000,
);

$statuses = explode( ',', $st_term_final_string);
$terms = explode( ',', $il_term_final_string );

if ( $statuses || $terms ) {
  $args['tax_query'] = array();
  if ( $statuses ) {
    $args['tax_query'][] = array(
      'taxonomy' => 'Status',
      'field' => 'slug',
      'terms' => $statuses
    );
  }

  if ( $terms ) {
   $args['tax_query'][] = array(
     'taxonomy' => 'County',
     'field' => 'slug',
     'terms' => $terms
    );
  }

  if ( $statuses && $terms ) $args['tax_query']['relation'] = 'AND';

  $loop = new WP_Query( $args );

  // do your stuff here

} else {

  // You have no statuses nor county, I don't know what you want to do in this case

}

Hope it helps.


text:
Q: How to get previous candles data in indicator? I'm writing an indicator that needs to read the previous 32 candles ohlc data to make a forecast.
How can I get the previous 32 candles ohlc data in TradingView > PineScript Editor > Indicator ?

A: ´[]´ in pinescript is called History Referencing Operator. You can use that operator to access historical values.
You can create 32 variables if your algorithm really needs those 32 individual values, or you can create a function and run a for loop.
Below code shows both examples for n=5.
//@version=4
study("My Script")

src = input(title="Source", type=input.source, defval=close)

src_1 = src[1]
src_2 = src[2]
src_3 = src[3]
src_4 = src[4]
src_5 = src[5]

avg_of_indv = avg(src_1, src_2, src_3, src_4, src_5)

get_average(avg_src, avg_len) =>
    ret_val = 0.0
    for i = 1 to avg_len
        ret_val := ret_val + avg_src[i]
    ret_val/avg_len

avg_of_func = get_average(src, 5)

plot(series=avg_of_indv, title="avg_of_indv", color=color.red, linewidth=2)
plot(series=avg_of_func, title="avg_of_func", color=color.green, linewidth=2)

If you look at the plots, both will be the same.
Also, there are highest() and lowest() functions available in pinescript. Those functions return highest/lowest value for a given number of bars back.


text:
Q: Regular expression Pattern matching java I need to have a Regex for the string:
Created ID @DBDOYEF has problems
The word @DBDOYEF may contain a-z,A-Z,0-9 and all special characters like
~!#$%^&*()_+{}:"<>?,./\.

Please help me to create a pattern for this word. I used
Created ID \\b[A-Z][0-9][\\//+-@#$%^~&*!():]+\\b has problems

for this, but it fails for many cases.

A: Your problems are

*

*\b only matches between a "word character" (letter/digit/underscore) and a non-word character (or start/end of string). You therefore need a different method to determine that your match has ended. Since you already have spaces before and after your identifier, you already have such a method and can remove the \bs.

*- is a metacharacter in a character class and needs to be placed at the start or end of the character class so it isn't interpreted as a range token (as in A-Z).

*Your identifier starts with a @, but that isn't part of [A-Z], so that can't match. You probably want to (optionally) start the match with @.

*Apparently the identifier doesn't require a number in position 2 and does allow letters after position 1, so you should combine the three character classes into two (assuming that the first letter needs to be a letter or digit).

That gives you
Created ID @?[A-Z0-9][-A-Z0-9\\/+@#$%^~&*!():]+ has problems

If IDs like -(X@Q) are also valid, you can simplify that to
Created ID [-A-Z0-9\\/+@#$%^~&*!():]+ has problems

A:
it may or may not start with @. some times it starts with : or A-Z or a-z or 0-9

You were trying [A-Z][0-9][\\//+-@#$%^~&*!():]+, which requires 1 letter, followed by 1 digit, followed by any punctuation. Instead, use the same character class for all allowed characters.
Regex
Created ID [@A-Za-z0-9~!#$%^&*()_+\-{}:\"<>?,./]+

*

*[@A-Za-z0-9~!#$%^&*()_+\-{}:\"<>?,./]+ Matches any of the characters in the character class any times.

regex101 demo


text:
Q: Webpage fails in responsiveness in smaller resolutions (only due to text overflow) I have:

*

*webpage

*CSS

*JS

*responsinator
When I open the webpage in desktop resolutions, resizing doesn't mess up the page, but when it comes to mobile browsers (as you can see in the responsinator) with much smaller dimensions (width & height below 500px) there is this problem that text overflows if I decrease the font using @ media queries, it's too small to read. So I used a combination of font-size-reduction, increasing text-container-size and overflow:scroll to the container. but still the text-container is becoming too small in height to be inside the div#block2.
And I have to use a lot of @media queries to a lot of max-widths as messing up occurs at several window.width ranges. So is it normal to use huge number of @media queries or I have to do a drastic change in my code.
So generally what front end developers do to see the responsiveness in smaller devices where block-wrappers and banners behave perfectly as we orchestrate them to be but text and content like images are the main issue.
I am asking for help in both in general and solution specific to this webpage. I have fair bit of knowledge on Jquery, CSS @media queries.

A: The problem I see with your code is you have max-height set on your text-wrapper.  That's what causes the scrollbar to appear.  In my opinion, when it comes to text responsiveness on mobile, you have to allow for the text to wrap the way it wants to naturally wrap.  Which usually means letting the paragraph get really tall and thin.  It's just kind of something you have to design for when it comes to small screens.
You can use media queries at the major break points; 768, 640, and 480, to reduce text size and padding but like you said it gets hard to read at a certain point.  I wouldn't drop the font-size below 14px to be on the safe side.
I hope that helps out.


text:
Q: Выборка лет из бд MS SQL Есть таблица, в которой есть поля Date (datetime) и Money (float).
Записей около 15 миллионов.
Т.е. за несколько лет, хранится информация по продажам товаров на каждый день.
Необходимо представить отчёт по сумме продаж по годам.
То, что у меня получилось:
SELECT      t.[Year],
            SUM(t.Money)
FROM        (
                SELECT  DATEPART(YEAR, mss.Date) AS [Year],
                        mss.Money
                FROM    Sales AS mss
            ) t
GROUP BY    t.[Year]
ORDER BY    t.[Year]

НО, данный запрос отрабатывает примерно за 3-4 секунды, есть возможность ускорить это время?


text:
Q: Selecting names from table I need to list names of professor and courses that teach by professor from the list of tables schemas
PROFESSOR : ID, NAME, DEPARTMENT_ID, , SALARY
DEPARTMENT : ID , NAME
COURSE: ID, NAME, DEPARTMENT_ID, CREDITS
SCHEDULE: PROFESSOR_ID, COURSE_ID, SEMESTER, YEAR
The output should be
Brandon Matthews Clinical Biochemistry
Brandon Matthews Clinical Neuroscience
Daniel Hicks Clinical Biochemistry
Emily Lee Clinical Biochemistry
Emily Lee clinical Neuroscience
Emily Lee Earth Science
Theresa Peterson Earth Science
Theresa Peterson Geography
Theresa Peterson Materials Science and Metallurgy
Theresa Peterson Pure Mathematics and Mathematical Statistics

The code that I tried
SELECT
    p.NAME,
    c.NAME
FROM COURSE c, SCHEDULE s, PROFESSOR p
WHERE p.ID = s.PROFESSOR_ID AND s.COURSE_ID = c.ID
ORDER BY  p.NAME;

This is not printing the correct output.

A: Use standard joins! Then it is easy to add more tables.
This is you current code:
select p.name, c.name
from course c, schedule s, professor p
where p.id = s.professor_id and s.course_id = c.id
order by  p.name

This translates as:
select p.name as professor_name, c.name as course_name
from schedule s
inner join course    c on c.id = s.course_id
inner join professor p on p.id = s.professor_id
order by p.name

Note that I also aliased the columns in the resultset, to avoid the ambiguity caused by identical names.
From there on, you can add more tables if needed (department comes to mind), or implement some filtering on the where clause (maybe you want course of this year only?).

A: You will need to incorporate the Department table in your query as well and join on the IDs. Then, you can also select the department name as well.
Something like the following should work:
SELECT p.name, d.name, c.name
FROM Course c, Schedule s, Professor p, Department d
WHERE p.id = s.professor_id AND s.course_id = c.id AND d.id = c.department_id
ORDER BY p.name;

A: You should also use the information on the Department table
SELECT
    p.NAME,
    d.NAME,
    c.NAME
FROM
    PROFESSOR p,
    DEPARTMENT d,
    COURSE c,
    SCHEDULE s
WHERE
    p.ID = s.PROFESSOR_ID AND
    d.ID = c.DEPARTMENT_ID AND
    c.ID = s.COURSE_ID
ORDER BY p.NAME;


text:
Q: I am confused by a solution about the time complexity of fibonacc long fib(int n)
{
    if (n <= 1)
        return 1;
    else
        return fib(n - 1) + fib(n - 2);
}

Although I've seen a lot of different solutions,some of them do not make sense to me.
Like this one which is a very popular solution(I paste the whole content to here and thanks for your patience as it will take some time)

Let's start by assuming that T(n-2) ≈ T(n-1). Don't worry about why just yet – this will become apparent shortly.
Substituting the value of T(n-1) = T(n-2) into our relation T(n), we get:
T(n) = T(n-1) + T(n-1) + 1 = 2T(n-1) + 1
By doing this, we have reduced T(n) into a much simpler recurrence.  As a result, we can now solve for T(n) using backward substitution.
To do this, we first substitute T(n-1) into the right-hand side of our recurrence. Since T(n-1) = 2T(n-2) + 1, we get:
T(n) = 2[2T(n-2) + 1] + 1 = 4T(n-2) + 3
Next, we can substitute in T(n-2) = 2T(n-3) + 1:
T(n) = 2[2[2T(n-3) + 1] + 1] + 1 = 8T(n-3) + 7
And once more for T(n-3) = 2T(n-4) + 1:
T(n) = 2[2[2[2T(n-4) + 1]+ 1] + 1] + 1 = 16T(n-4) + 15
We can see a pattern starting to emerge here, so let's attempt to form a general solution for T(n). It appears to stand that:
T(n) = 2kT(n–k) + (2k-1)
For any positive integer k. We can prove this equation holds through simple induction – for brevity's sake, we'll skip this process.
Finally, we can find k and, thereby, solve T(n), by substituting in T(0) = 1.
For T(0), we can see that n – k = 0. Rearranging, we get k = n. Now, substituting in our values for T(0) and k, we get:
T(n) = 2nT(0) + (2n-1) = 2n + 2n – 1 = O(2n)

My question is why it can substitute n with 0. In my opinion, the program will be terminated when n reaches 1 as T(n-2) has been replaced with T(n-1). Hence, it's no possible to get the value of n as 0.

A: Added a simple cout statement .
Consider the call f(2)
long fib(2)
{
    std::cout<<n<<"\n";
    if (2 <= 1)
        return 1;
    else{

        return fib(1) + fib(0); --- >     here there are two calls  > fib(1)  will return 1 and secod will be fib(0) which prints 0
    }

}

the output for f(2)

2
1
0

Moreover as Note :
return fib(n - 1) + fib(n - 2);

The statement above doesn't guarantee you the order of evaluation  so for f(2) there is no order whether f(1) will be called first of f(0) will be.


text:
Q: How can I append the results of additional queries to an SSRS report? I am generating an SSRS report whose results are displayed like so:

I need to append similar query results (same exact query, one different parameter value) to the right of this data, so that one additional result set of data (from a 2nd query) would look something like this (but with different data, of course - this is just copied-and-pasted to show what's needed):

How can I add multiple of these similar-but-distinct result sets so that they can be read from left to right as shown above?

A: Solution: COLUMN GROUPING
If I have understood your question correctly, you are expecting to show those 3 columns repeatedly for different set of values. All you need to do is put those 3 columns in a group (Column Group) and Group by on whatever "Field/Parameter" you want to it repeat. Let me know how it goes!!

A: Based on what is written here, this is how I accomplished this:
I created a new report based on the existing one, and then added a Subreport and then dragged the existing (original) report onto it (I dragged "VariancePricebyProduct_Facelift.rdl" onto the subreport in "VariancePricebyProduct_Facelift_WithSubreports.rdl"). Then I selected the context menu item "Subreport Properties" and added a parameter ("Unit"), providing it with a "hard-coded/baked-in" value ("CHOPHOUSE") different from the one to be provided by the user for the main report.
Then, since I want to keep the same date values from the existing report, I added two more parameters to the subreport and set them to use the same values for the date range as those used there in the main report by selecting the "formula" ("fx") button and 2-clicking the appropriate parameter to be used as the passed-in (tramp) value:

That works. Just to make it plainer, here is how it looks at design time:

The mess at the top is "VariancePricebyProduct_Facelift.rdl"; the bit below is a Textbox/Label for the subreport and then the subreport itself.
And here is how the data looks where the original/base report finishes and the subreport begins:


text:
Q: ManagedObjectModel inits to nil Just creating a new iPhone application with CoreData. My application builds without any warnings or errors and has my .xcdatamodeld in it as well which has no errors or warnings.
For some reason my managedObjectModel won't initialise and I can't work out why.
- (NSManagedObjectModel *)managedObjectModel {
 if (__managedObjectModel) {
     return __managedObjectModel;
}

 NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"BAK" withExtension:@"momd"];
 __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
 return __managedObjectModel;
}

The modelURL resolves correctly and points to my compiled data model but the managedObjectModel stays at nil after its alloc line. There is no output into the console either. What can cause this or what am I missing?
The __managedObjectModel is declared as follows:
.h
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
.m
@synthesize managedObjectModel = __managedObjectModel;

Thanks for your help.

A: My bet is you changed the model somehow, most likely the name ("BAK" to something else or something else to "BAK").
That initialization of the NSManagedObjectModel is really simple.  If it has been initialized and exists, return it, otherwise initialize the ManagedObjectModel using the name you provided ("BAK").
The only other explanation is that somehow, someway, the Core Data model didn't get initialized in the main bundle location, but somewhere else.


text:
Q: 1>main.obj : error LNK2001: unresolved external symbol _D3D10CreateDeviceAndSwapChain@32 having trouble getting my directx going I get the following error
1>Linking...
1>main.obj : error LNK2001: unresolved external symbol _D3D10CreateDeviceAndSwapChain@32
1>C:\Users\numerical25\Desktop\Intro ToDirectX\msdnTutorials\tutorial0\tutorial\Debug\tutorial.exe : fatal error LNK1120: 1 unresolved externals

below is my code
// include the basic windows header file
#include <windows.h>
#include <windowsx.h>
#include <d3d10.h>

ID3D10Device* g_pd3dDevice;
IDXGISwapChain* g_pSwapChain;

// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd,
                         UINT message,
                         WPARAM wParam,
                         LPARAM lParam);
bool InitDirect3D(HWND);

// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance,
                   HINSTANCE hPrevInstance,
                   LPSTR lpCmdLine,
                   int nCmdShow)
{
    // the handle for the window, filled by a function
    HWND hWnd;
    // this struct holds information for the window class
    WNDCLASSEX wc;

    // clear out the window class for use
    ZeroMemory(&wc, sizeof(WNDCLASSEX));

    // fill in the struct with the needed information
    wc.cbSize = sizeof(WNDCLASSEX);
    wc.style = CS_HREDRAW | CS_VREDRAW;
    wc.lpfnWndProc = WindowProc;
    wc.hInstance = hInstance;
    wc.hCursor = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
    wc.lpszClassName = L"WindowClass1";

    // register the window class
    RegisterClassEx(&wc);

    // create the window and use the result as the handle
    hWnd = CreateWindowEx(NULL,
                          L"WindowClass1",    // name of the window class
                          L"Our First Windowed Program",   // title of the window
                          WS_OVERLAPPEDWINDOW,    // window style
                          300,    // x-position of the window
                          300,    // y-position of the window
                          640,    // width of the window
                          480,    // height of the window
                          NULL,    // we have no parent window, NULL
                          NULL,    // we aren't using menus, NULL
                          hInstance,    // application handle
                          NULL);    // used with multiple windows, NULL

    // display the window on the screen
    ShowWindow(hWnd, nCmdShow);

    // enter the main loop:

    // this struct holds Windows event messages
    MSG msg;
    bool finished = InitDirect3D(hWnd);

    // Enter the infinite message loop
    while(TRUE)
    {
        // Check to see if any messages are waiting in the queue
        while(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
        {
            // Translate the message and dispatch it to WindowProc()
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }

        // If the message is WM_QUIT, exit the while loop
        if(msg.message == WM_QUIT)
            break;

        // Run game code here
        // ...
        // ...
    };
}

// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    // sort through and find what code to run for the message given
    switch(message)
    {
        // this message is read when the window is closed
        case WM_DESTROY:
            {
                // close the application entirely
                PostQuitMessage(0);
                return 0;
            } break;
    }

    // Handle any messages the switch statement didn't
    return DefWindowProc (hWnd, message, wParam, lParam);
}

bool InitDirect3D(HWND g_hWnd)
{
    DXGI_SWAP_CHAIN_DESC sd;
    ZeroMemory( &sd, sizeof(sd) );
    sd.BufferCount = 1;
    sd.BufferDesc.Width = 640;
    sd.BufferDesc.Height = 480;
    sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
    sd.BufferDesc.RefreshRate.Numerator = 60;
    sd.BufferDesc.RefreshRate.Denominator = 1;
    sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
    sd.OutputWindow = g_hWnd;
    sd.SampleDesc.Count = 1;
    sd.SampleDesc.Quality = 0;
    sd.Windowed = TRUE;

    if( FAILED( D3D10CreateDeviceAndSwapChain( NULL, D3D10_DRIVER_TYPE_REFERENCE, NULL,
                     0, D3D10_SDK_VERSION, &sd, &g_pSwapChain, &g_pd3dDevice ) ) )
    {
        return FALSE;
    }

    return TRUE;
}

A: You need to link your application with d3d10.lib. In Visual Studio you can configure this in the project settings in Linker / Input / Additional Dependencies.


text:
Q: Using JQuery to show/hide div based on month and date range I'm new to learning JQuery and I am trying to write a script that will only display text inside a div after May 1 and before June 1. This needs to ignore the year and only show the dive between these limits. Here is what I've been experimenting with:
 <script type="text/javascript">
    var today = new Date();
    //month begins with 0

     if ((today.getMonth() > 04 && today.getDate() > 01) || (today.getMonth() < 05 && today.getDate() < 01)){
        $('#cellOne').show();
      }
       else {
      $('#cellOne').hide();
    }
    </script>

Since today is not between these limits, I believe the div should be hidden, but I can't get it to work. Can anyone put me on the right path here? It is possible I have a logic error as I'm not very experience with JavaScript and JQuery. Much obliged.
For this particular situation, calculating the day of the year is not an ideal solution, mostly because when I hand the website back over to daily administrators they will not understand how to update the code.

A: Here is the answer I came up with, following the lead of @Alex
It seems to work and thought it might be useful to someone else.
$(document).ready(() => {
    // MM - DD - YYYY
  function getDayFromDate(dateString) {
    var now = new Date(dateString);
    var start = new Date(now.getFullYear(), 0, 0);
    var diff = now - start;
    var oneDay = 1000 * 60 * 60 * 24;
    return Math.floor(diff / oneDay);
  }

  let cutoffLow = getDayFromDate("05/01");
  let cutoffHigh = getDayFromDate("06/01");
  let now = getDayFromDate(new Date());

  if(now > cutoffLow && now < cutoffHigh) {
    document.querySelector('#cellOne').style.display = "";
  }
  else{
         document.querySelector('#cellOne').style.display = "none";
}
});


text:
Q: Generating DDL and DML statements from existing tables in MS Access 2016 I have created database using MS Access 2016. I was thinking that it will easy to generate DDL and DML statements after that like it is in other tools such as MySQL and MS SQL Server but unfortunately this is not the case.
I have tried using DBWscript but that is not built for Access 2016 yet.
Please suggest something.


text:
Q: fuse.js as a dependency in an aurelia app I've been trying, without success, to add fuse.js as a dependency to my aurelia-based app.
The app was initialized with the au tool, and uses TypeScript as the main language.
In aurelia_project/aurelia.json, I've tried adding the dependency in the following formats, under build.bundles[vendor-bundle].dependencies:
"fuse.js"

{
  "name": "fuse.js",
  "path": "../node_modules/fuse.js/dist/fuse"
}

{
  "name": "fuse.js",
  "path": "../node_modules/fuse.js/dist/",
  "main": "fuse"
}

Neither has given me the library available at runtime (always undefined when imported by import * as Fuse from 'fuse.js';, and the two first have given me errors when building.
How can I add fuse.js as a dependency to an aurelia app?

A: I use fuse.js in my app as a value converter, my structure is webpack and dotnet core,

*

*npm install fuse.js --save

*add fuse.js in my vendor part of webpack.config.vendor file

*npm install @types/fuse

*I created a value converter like :
import { FuseOptions } from 'fuse.js';
import * as Fuse from 'fuse.js';

export class FuseValueConverter {

toView(value: Array<any>, options: FuseOptions, criteria: string) {
   console.log(value);

   if (!options || !criteria)
       return value || [];

   const fuse = new Fuse(value, options);

   return fuse.search(criteria);
   }
}

and then I caleed it in my view models just like any other value converter in Aurelia

A: Is it not that aurelia does not use extension (.js in your case) when importing?
Your json file is also incorrectly formatted.


text:
Q: Mercurial and Git custom SSH key location Exists there any way to define for each cloned repo the path of which SSH key pair it should use?

A: Yes, you need to define a ~/.ssh/config file, in which you can declare different ssh names, with a custom full path name for the public/private key to use.
Host AHostName -- name you will use for the ssh address
User gituser
Hostname SSH IP address
Port 1234 -- use this if you need custom ports
IdentityFile "path to your private ssh key"

From there, the ssh url of the repo can be:
AHostName:myrepo

See also:

*

*"git + assembla + multiple ssh keys/multiple computers"

*"How to work on personal GitHub repo from office computer whose SSH key is already added to a work related GitHub account?"


text:
Q: How to convert String having key=value pairs to Json myString =  {AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00};
I want to convert it to the following string.
{"AcquirerName": "abc", "AcquiringBankCode": 0.2, "ApprovalCode": 0};

How can I do it in java?

A: You can use Gson to convert the key-value String to Object and convert it into JSON. For Eg,
Add the following dependency:
<dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.8.5</version>
    </dependency>

Your Model:
class MyModel {
    String AcquirerName;
    double AcquiringBankCode;
    int ApprovalCode;
//getter //setter //constructor
}

Verify:
public static void main(String[] args) {

        // Impl
        Gson gson = new Gson();
        String myString = "{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00}";
        MyModel myModel = gson.fromJson(myString, MyModel.class);
        String json = gson.toJson(myModel, MyModel.class);
        System.out.println(json);
    }

O/P: {"AcquirerName":"abc","AcquiringBankCode":0.2,"ApprovalCode":0}
Hope it helps :)

A: You can JSONObject.. see below example
JSONObject main = new JSONObject();
main.put("Command", "CreateNewUser");
JSONObject user = new JSONObject();
user.put("FirstName", "John");
user.put("LastName", "Reese");
main.put("User", user);

For Json Data:
{
    "User": {
        "FirstName": "John",
        "LastName": "Reese"
    },
    "Command": "CreateNewUser"
}


text:
Q: Draw a rectangle around a string of words using pytesseract Here is my image:

I can recognize the words:

I need to check if there is a line with specific text in the image and highlight this line with a rectangle.
For example. I check if there is "times, it was the worst". And then I expect to see:

How can I achieve this?
My code:
import cv2 as cv
from pytesseract import pytesseract, Output
unchanged_image = cv.imread("i1Abv.png", cv.IMREAD_UNCHANGED)
initial_image = cv.imread("i1Abv.png", 0)
cv.imshow('', initial_image)
cv.waitKey(0)

ret, image = cv.threshold(initial_image, 100, 255, cv.THRESH_BINARY)

cv.imshow('', image)
cv.waitKey(0)

results = pytesseract.image_to_data(image, output_type=Output.DICT, config="--psm 6")
for i in range(0, len(results["text"])):
    # extract the bounding box coordinates of the text region from
    # the current result
    x = results["left"][i]
    y = results["top"][i]
    w = results["width"][i]
    h = results["height"][i]
    # extract the OCR text itself along with the confidence of the
    # text localization
    text = results["text"][i]
    conf = float(results["conf"][i])

    # filter out weak confidence text localizations
    if conf > 10:

        # strip out non-ASCII text, so we can draw the text on the image
        # using OpenCV, then draw a bounding box around the text along
        # with the text itself
        cv.rectangle(unchanged_image, (x, y), (x + w, y + h), (0, 255, 0), 2)
        cv.putText(img=unchanged_image, text=text, org=(x, y), fontFace=cv.FONT_HERSHEY_COMPLEX,
                   fontScale=0.3, color=(36, 0, 255), thickness=1)

cv.imshow('', unchanged_image)
cv.waitKey(0)

A: pytesseract.image_to_data provides line_num for each recognized text block. You can group all the recognitions by line_num and then concatenate words into a text line. Also you need to find a bounding box that includes all the text boxes of each word (you can get them using left, top, width, height). You can find it with cv2.boundingRect
Results:

Code:
import cv2
import numpy as np
import pytesseract

original_image = cv2.imread("text_line.png")
gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
target_text = "times, it was the worst"

df = pytesseract.image_to_data(gray, lang="eng", config="--psm 6", output_type=pytesseract.Output.DATAFRAME)

# group recognized words by lines
for line_num, words_per_line in df.groupby("line_num"):
    # filter out words with a low confidence
    words_per_line = words_per_line[words_per_line["conf"] >= 5]
    if not len(words_per_line):
        continue

    words = words_per_line["text"].values
    line = " ".join(words)
    print(f"{line_num} '{line}'")

    if target_text in line:
        print("Found a line with specified text")
        word_boxes = []
        for left, top, width, height in words_per_line[["left", "top", "width", "height"]].values:
            word_boxes.append((left, top))
            word_boxes.append((left + width, top + height))

        x, y, w, h = cv2.boundingRect(np.array(word_boxes))
        cv2.rectangle(original_image, (x, y), (x + w, y + h), color=(255, 0, 255), thickness=3)

cv2.imwrite("out.jpg", original_image)


text:
Q: Not unique table alias set @carer_fname = 'Carername';
set @carer_sname = 'Carersname';
select concat_ws(' ', C.child_fname, C.child_sname) as 'Child Name'
,C.child_carer
,A.activity_name, A.activity_day
from Child C, Activity A
inner join Child C on CA.child_id = C.child_id
inner join Activity A on CA.activity_id = A.activity_id
order by child_sname

Response is: Error Code: 1066. Not unique table/alias: 'C'
Not exactly sure why C not unique comes up
Thank you for your help!

A: @Dravenzo you are using multiple instances of the table Child and giving it the alias of C both times:
set @carer_fname = 'Carername';
set @carer_sname = 'Carersname';
select concat_ws(' ', C.child_fname, C.child_sname) as 'Child Name'
,C.child_carer
,A.activity_name, A.activity_day
from -->Child C<--, Activity A -- first instance of aliasing Child as C
inner join -->Child C<-- on CA.child_id = C.child_id -- second instance of aliasing Child as C
inner join Activity A on CA.activity_id = A.activity_id
order by child_sname

It's not really clear what you are trying to do with this query because in your FROM clause you are listing both tables Child and Activity and then using JOIN statements in a confusing manner. Also, you are referring to an alias of CA but you aren't stating which table should be aliased as CA.
This is only a guess at what you want to do with your query because of the confusing aspects of what you have listed, but try something like this:
set @carer_fname = 'Carername';
set @carer_sname = 'Carersname';
select concat_ws(' ', C.child_fname, C.child_sname) as 'Child Name',
    C.child_carer,
    A.activity_name,
    A.activity_day
from Child C
inner join Activity A on A.activity_id = C.activity_id
order by C.child_sname

I suggest reading up on MySQL joins in the official documentation here or googling MySQL JOINS tutorial, there are loads of tutorials out there.


text:
Q: Why Isn't There A Git Clone Specific Commit Option? In light of a recent question on SO, I am wondering why isn't there an option in git clone such that the HEAD pointer of the newly created branch will point to a specified commit? In say question above, OP is trying to provide instructions on the specific commit his users should clone.
Note that this question is not about How To Clone To A Particular Version using reset; but about why isn't there?

A: Cloning a repo is a different operation than checkout.  You don't "clone a specific commit".  For convenience you can clone and then checkout a particular pre-existing branch at the same time, since that is what most people want.  If that doesn't meet your needs (no branch for the particular SHA you want) just use or alias some form of
git clone -n <some repo> && cd <some repo> && git checkout SHA

A: If your specific commit is referenced by a branch, you can do a:
git clone -b yourBranch /url/of/the/repo

The cloned repo will be directly at the commit referenced by that branch.

A: As the other answers say, this is typically not much of an issue, but they don't say why you can't clone a specific commit. The answer is security.
If you accidentally push confidential information, and then force-push a fixed history, the commits with the confidential information will still be stored on the server, until the server's Git's garbage collector finds it is no longer needed. If the hash is known (it might for example be available in logs), a malicious user might request the specific commit that shouldn't have been pushed, even if you were able to verify that when you force-pushed the fixed history, nobody had fetched those commits yet.
Making sure you can only clone from refs makes sure that only "reachable" commits will be sent to the clients.

A: Two answers so far (at the time I wrote this, now there are more) are correct in what they say, but don't really answer the "why" question.  Of course, the "why" question is really hard to answer, except by the authors of the various bits of Git (and even then, what if two frequent Git contributors gave two different answers?).
Still, considering Git's "philosophy" as it were, in general, the various transfer protocols work by naming a reference.  If they provide an SHA-1, it's the SHA-1 of that reference.  For someone who does not already have direct (e.g., command-line) access to the repository, none1 of the built in commands allow one to refer to commits by ID.  The closest thing I can find to a reason for this—and it is actually a good reason2—is this bit in the git upload-archive documentation:

SECURITY
In order to protect the privacy of objects that have been removed from
  history but may not yet have been pruned, git-upload-archive avoids
  serving archives for commits and trees that are not reachable from the
  repository's refs. However, because calculating object reachability is
  computationally expensive, git-upload-archive implements a stricter but
  easier-to-check set of rules ...

However, it goes on to say:

If the config option uploadArchive.allowUnreachable is true, these
  rules are ignored, and clients may use arbitrary sha1 expressions. This
  is useful if you do not care about the privacy of unreachable objects,
  or if your object database is already publicly available for access via
  non-smart-http.

which is particularly interesting since git clone gets all reachable objects in the first place, after which your local clone could trivially check out a commit by SHA-1 ID (and create a local branch name pointing to that ID if desired, or just leave your clone in "detached HEAD" mode).
Given these two cross-currents, I think the real answer to "why", at this point, is "nobody cares enough to add it". :-)  The privacy argument is valid, but there is no reason that git clone could not check out a commit by ID after cloning, just as it can be told to check out some branch other than master3 with git clone -b ....  The only drawback to allowing -b sha1 is that Git cannot check up front (before the cloning process begins) whether sha1 will be received.  It can check reference names, since those are transferred (along with their branch tips or other SHA-1 values) up front, so git clone -b nonexistentbranch ssh://... terminates quickly and does not create the copy:
fatal: Remote branch nonexistentbranch not found in upstream origin
fatal: The remote end hung up unexpectedly

If -b allowed an ID, you'd get the whole clone, then it would have to tell you: "oh gosh, sorry, can't check out that ID, I'll leave you on master instead" or whatever.  (Which is more or less what happens now with a busted submodule.)

1While git upload-archive now enforces this "privacy" rule, this was not always the case (it was introduced in version 1.7.8.1); and many (most?) git-web servers, including the one distributed with Git itself, allow viewing by arbitrary ID.  This is probably why allowUnreachable was added to upload-archive a few years after the "only by ref name" code was added (but note that releases of Git after 1.7.8 and before 2.0.0 have no way to loosen the rules).  Hence, while the "security" idea is valid, there was a period (pre 1.7.8.1) when it was not enforced.
2There are numerous ways to "leak" ostensibly private data out of a Git repository.  A new file, Documentation/transfer-data-leaks, is about to appear in Git 2.11.1, while Git 2.11.0 added some internal features (see commit 722ff7f87 among others) to immediately drop objects pushed but not accepted.  Such objects are eventually garbage-collected, but that leaves them exposed for the duration.
3Actually, by default git clone makes a local check-out of the branch it thinks goes with the remote's HEAD reference.  Usually that's master anyway, though.


text:
Q: Access to *.doc was denied | Libreoffice 5.4.5.1 I am using Ubuntu 17.10 as my daily driver. I have created a separate partition like home for storage /data of ext4 type.
Today, i updated my system  using apt dist-upgrade. It also updated  libreoffice after updating libreoffice, i am unable to access all my documents from /data partition only and start getting the below error

Note:- I am able to access documents from home directory.
When i am trying to create new document using libreoffice getting below error

A: I first recommended a temporary Workaround: Copy your file to $HOME.
However, it's probably better to solve the problem like is described in the answer to my own question:
Libreoffice 5.4.5.1 gets access denied on NFS mounted filesystem

A: Issue is fixed finally after latest update.


text:
Q: $\lim_{a\rightarrow 0} \int_0^1 \frac{1}{1+a\sin(x)} \, \mathrm{d}x$ Am I allowed to change limit and integral here? How can I solve this integral?
$$\lim_{a\rightarrow 0} \int_0^1 \frac{1}{1+a\sin(x)} \, \mathrm{d}x$$

A: For $x\in[0,1]$ and $|a|<1/2$,
\begin{align*}
\left|\dfrac{1}{1+a\sin x}\right|\leq\dfrac{1}{1-(1/2)\sin(1)}
\end{align*}
and
\begin{align*}
\int_{0}^{1}\dfrac{1}{1-(1/2)\sin 1}dx<\infty,
\end{align*}
so it goes through by Lebesgue Dominated Convergence Theorem.


text:
Q: Filling field according to value of another field with ArcPy? I am very ill at ease with Python. I am working on ArcGIS 10.3. I am working on a table in a gdb.
I want to fill an empty field of this table with an expression (words) according to the value of a second field in the same table.
In my case, if my second field contain the word "roadway", I want to fill the empty field cells councerned by this expression "route à deux chaussées".
I know that accents are not good in programming but I need to fill my field with (french...).
My script is below:
import arcpy

fc = "D:/TESTS_TOP25/POUR_SDC/ROUTIER_TRAITEMENT/DONNEES.gdb"

#field'sname
field1 = "NATURE"
field2 = "symbology"

cursor = arcpy.UpdateCursor(fc)
for row in cursor:
    if field1 == "roadway"
        field2 == "route à deux chaussée"
    cursor.updateRow(row)

A: This should do it, using the feature class "UneFC" inside DONNEES.gdb, and using the newer arcpy.da.UpdateCursor().
# -*- coding: utf-8 -*- # Should handle the French characters.

import arcpy

fc = "D:\\TESTS_TOP25\\POUR_SDC\\ROUTIER_TRAITEMENT\\DONNEES.gdb\\UneFC"

fields = ("NATURE", "symbology")

with arcpy.da.UpdateCursor(fc, fields) as cursor:
    for row in cursor:
        if row[0] == "roadway": # if NATURE is "roadway"...
            row[1] = "route à deux chaussée" # Voila votre traduction ;)
        cursor.updateRow(row)


text:
Q: Magento : Change Stock Availability From Dropdown to Text I want to change Stock Availability of product in backend, from drop down to text area to add custom text for product. My version is Magento 1.9.2.

A: I made an attribute called "customstock"
Then in public_html/app/design/frontend/base/default/template/catalog/product/view/type/default,phtml
I changed the code to
<?php if ($_product->isAvailable()): ?>

<?php echo $this->__('Availability:') ?> <?php echo $this->__('In stock') ?>

    <?php else: ?>

<?php echo $this->__('Availability:') ?> <?php echo $_product->getData('customstock'); ?>

    <?php endif; ?>