text:
Q: Integrate a React Modal in a non-react website So I'm trying to build a modal in react and integrate it into a non-react website. I understand that I might need to export the app as a UMD and include it as an  embed script into the host website.
But how do I interact with the modal within the host website i.e open a modal when a button is clicked and close the modal when a button is clicked within the modal.

A: Solution
It's unclear what you're trying to do, have react in just some place in an existing website ?
You could just render you react app into a div and have it live there.
const element =
Hello, world
;
ReactDOM.render(element, document.getElementById('root'));

Even though if you plan on doing it this way, vue might be better suited.
Alternative

*

*React would be a bit overkill for such a use case, where vue is suited perfectly for it.

*Otherwise, I'd advise switching the whole web app to react. Depending on what technology it is made with currently, it might not be too difficult!


text:
Q: The Projection of a Vector onto a Plane I want to find the orthogonal projection of the vector $\vec y$ onto a plane.
I have $\vec y = (1, -1, 2)$ and a plane that goes through the points
\begin{align*}u_1 = (1, 0, 0) \\ u_2 = (1, 1, 1) \\ u_3 = (0, 0, 1)
\end{align*}
I started by finding the equation for the plane by calculating: $\vec{PQ} = u_2 - u_1$ and $\vec{PR} = u_3 - u_1$.
I then took the cross product between $\vec{PQ}$ and $\vec{PR}$ and got $(1, -1, 1)$. I used the cross product as coefficients $a, b, c$ in the equation:
$$a(x - x_0) + b(y-y_0) + c(z-z_0) = 0$$
With this I got the plane equation to become $x - y + z = 1$.
Building on this, I went on to calculate the point where the vector $\vec y$ intersects the plane. I used $(0, 0, 0)$ as a starting point and $(1, -1, 2)$ as the endpoint.
$$r(t) = \{x_0, y_0, z_0\} + t\{x_1-x_0, y_1-y_0, z_1-z_0\} = (t, -t, 2t)$$
I inserted these parameters into the plane equation and got $t = 1/4$.
So the vector intersects the plane in $(1/4, -1/4, 1/2)$.
Now my task is to find the projection of the vector y onto the plane. My idea was to use the point of intersection together with the cross product to find a vector that is perpendicular to the plane. By using the point of intersection as the starting point and the cross product as the endpoint.
I could subtract y with this perpendicular vector and get the endpoint for the projection of y onto the plane, while also here using the point of intersection as the starting point.
Howevever, the resulting projection is not correct. Apparently, both the starting point and the end point has to be calculated differently.
I also tried using the Gram-Schmidt process to transform the base vectors $u_1$, $u_2$, $u_3$ into an ortogonal base. With this I tried to use the equation  $$\vec y' = \frac{\vec y·u_1}{u_1·u_1}\cdot u_1 + \frac{\vec y·u_2}{u_2·u_2}\cdot u_2 + \frac{\vec y·u_3}{u_3·u_3}\cdot u_3$$ to find the projection but a bit surprisingly arrived back at the original vector y when doing this.
Tremendously grateful for any tips.
Image of my problem:

A: It looks like you've corrected the fundamental conceptual error that you were making in trying to find where $\vec y$ (really the line segment from the origin to $\vec y$) intersects the plane. That line of attack is suspect since there's no a priori reason to believe that this intersection even exists.
However, once you've found an equation for the plane, the orthogonal projection of $\vec y$ onto this plane can be computed directly: it's simply the foot of the perpendicular from $\vec y$ to the plane. A simple way to compute this point is to substitute $\vec y+t\vec n$, where $\vec n$ is normal to the plane, into the equation of the plane, and then solve for $t$: $$(1+t)-(-1-t)+(2+t)-1 = 3t+3 = 0,$$ so $t=-1$ and the orthogonal projection of $\vec y$ onto the plane is $(0,0,1)$.
You can instead compute the projection without finding an implicit Cartesian equation for the plane or even computing its normal by using the fact that the orthogonal projection of $\vec y$ onto the plane is the nearest point on the plane to $\vec y$. The plane can be parameterized by the affine combination $$\vec r(\alpha,\beta)=\alpha u_1+\beta u_2+(1-\alpha-\beta)u_3 = (\alpha+\beta,\beta,1-\alpha).$$ Minimizing the distance between $\vec y$ and $\vec r$ is equivalent to minimizing the square of the distance, namely $$(\alpha+\beta-1)^2+(\beta+1)^2+(1-\alpha-2)^2 = 2\alpha^2+2\alpha\beta+2\beta^2+3=\frac12(\alpha-\beta)^2+\frac32(\alpha+\beta)^2+3,$$ from which it's obvious that the minimum is attained when $\alpha=\beta=0$, i.e., that the closest point to $\vec y$ is $(0,0,1)$.

A: I think some confusion might have come from the way Mathematica creates a 2D plane out of the two given points.
By using that a vector that passes through a plane (y) can be broken down into the sum of a vector (normal) orthogonal to the plane (n) and a vector that runs parallell to the plane and is a projection (x).
y = n + x
(1, -1, 2) = (1, -1, 1) + (a, b, c)
Projection = Vektor - VektorNormal
Projection = (0, 0, 1)
I used this and calculated where the VektorNormal intersects the plane and used that as the starting point for the projection.
It seems reasonable that it could work and it looks like it might do the trick.
Although far from as elegant as Haris Gusic's calculations.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Equivalent of URL parsing PCRE regex for .NET There's a PCRE regex for extracting URLs posted here: http://daringfireball.net/2009/11/liberal_regex_for_matching_urls
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/)))

What would need to be changed to make it compatible with regex in .NET?

A: Looking at in Regexbuddy now. So far, the only issue is the [:punct:] - doesn't look like .NET supports POSIX character classes.
EDIT - double clicking on the offender gave me this:
\b(([\w-]+://?|www[.])[^\s()<>]+(?:\([\w\d]+\)|([^\p{P}\s]|/)))


text:
Q: Windows Forms in VB Updating Two tables I am creating a form in VB to enter customer sales invoices and need to update two tables i.e. InvoiceHeader and InoviceDetails.  The Invoice details can have more than one line for one Invoice header. I was wondering if there is any thing like Access subforms or how can I update both tables through an SQL statement.

A: You need a few more details, but generally you could create a view of the tables in SQL and update through the view.
Or just write a procedure, in the SQL designer get the select statement showing what you want with both tables (You know inner outer Join) Then change it to update.


text:
Q: Reverse transform by rearrainging terms I have a simple affine transform equation:
$$ x' = a + bx + cy \\ y' = d + ex + fy $$
I found some code that states that through a rearrangement of terms you can find the following reversed transformation:
$$ x = (f(x' - a) - cy' + dc) / (bf - ce) \\ y = (e(x' - a) - by' + db) / (ce - bf) $$
I have tested it and seen that it works, but how was it derived?

A: The transform is $$\begin{bmatrix}
b & c \\
e & f \\
\end{bmatrix}\begin{bmatrix}
x \\
y \\
\end{bmatrix}+\begin{bmatrix}
a \\
d \\
\end{bmatrix}=\begin{bmatrix}
x' \\
y' \\
\end{bmatrix}$$
Hence
$$\begin{bmatrix}
x \\
y \\
\end{bmatrix}=\begin{bmatrix}
b &c \\
e &f \\
\end{bmatrix}^{-1}\begin{bmatrix}
x'-a \\
y'-d \\
\end{bmatrix}$$
Where $$\begin{bmatrix}
b &c \\
e &f \\
\end{bmatrix}^{-1}={1\over bf-ce}\begin{bmatrix}
f &-c \\
-e &b \\
\end{bmatrix}$$


text:
Q: Reading Events from CSV in Esper I'm trying to read a couple of events from a CSV using the CSVInputAdapter but I can't achieve it, here is what I'm trying:
First I've followed the first steps of the documentation http://esper.espertech.com/release-7.1.0/esper-reference/html_single/index.html#gettingstarted
I've defined the Person event like this:
public class PersonEvent {
    private String name;
    private int age;

    public PersonEvent() {
        this.name = "NONE";
        this.age = -1;
    }

    public PersonEvent(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

Then instantiate the service, add the event type and create a statement and a listener so everytime a PersonEvent is received it prints the name and the age of the person:
EPServiceProvider engine = EPServiceProviderManager.getDefaultProvider();
engine.getEPAdministrator().getConfiguration().addEventType(PersonEvent.class);
String epl = "select name, age from PersonEvent";
EPStatement statement = engine.getEPAdministrator().createEPL(epl);

statement.addListener((newData, oldData) -> {
            String name = (String) newData[0].get("name");
            int age = (int) newData[0].get("age");
            System.out.println(String.format("Name: %s, Age: %d", name, age));
        });

I tested it sending a simple event and it works
engine.getEPRuntime().sendEvent(new PersonEvent("Peter", 10));

This is the output
Name: Peter, Age: 10

The problem comes when I try to read the events from a CSV file, my CSV looks like this:
name,age
John,3
Anne,4

This is how I read the file:
    AdapterInputSource source = new AdapterInputSource(new File("/path/input.csv"));
    (new CSVInputAdapter(engine, source, "PersonEvent")).start();

And this is the output I receive:
Name: Peter, Age: 10
Name: NONE, Age: -1
Name: NONE, Age: -1

As you can see, I receive the information of Peter, processed by sending a simple event, and two lines of the CSV, which is OK, but without data. Could you help me if there is something that I am doing wrong? Thank you very much.

A: It might be because the class doesn't have setters?
It might be because the JVM does not have any defined order for methods on Java classes. The first property may actually be 'age' and not 'name. Try providing a field order too. Debug level logging may also help you.


text:
Q: Cordova 10 unable to post ajax to http url I'm trying to send json data to an http url without success (I tried to send same data to an other https with success).
I have this settings:
config.xml
<access origin="*" />
<allow-intent href="http://*/*" />
<allow-intent href="https://*/*" />

AndroidManifest.xml
android:usesCleartextTraffic="true"

HTML Header
<meta http-equiv="Content-Security-Policy" content="default-src *; style-src * 'unsafe-inline'; script-src * 'unsafe-inline' 'unsafe-eval'; img-src * data: 'unsafe-inline'; connect-src * 'unsafe-inline'; frame-src *;">
<meta http-equiv="Content-Security-Policy" content="default-src * gap://ready file:; style-src 'self' 'unsafe-inline' *; script-src 'self' 'unsafe-inline' 'unsafe-eval' *">

<script>
  $.ajax({
    type: "GET",
    url: url,
    dataType: "jsonp",
    jsonp: 'callback',
    crossDomain: true,
    async: true,
    data: {
      id: results.rows.item(i).id,
      bolla: results.rows.item(i).bolla,
      anno: results.rows.item(i).anno,
      magazzino: results.rows.item(i).magazzino,
      articolo: results.rows.item(i).articolo,
      quantita: results.rows.item(i).quantita,
      term: terminale
    },
    success: function (data) {
      console.log(data)
    },
    error: function (xhr, textStatus, err) {
      alert("readyState: " + xhr.readyState);
      alert("responseText: " + xhr.responseText);
      alert("status: " + xhr.status);
      alert("text status: " + textStatus);
      alert("error: " + err);
    }
  });
</script>

If I use json it returns devicereadystate=0 and error if I use jsonp it returns devicereadystate=4 and error 404 (the url is correct if I paste to a browser it works)

A: I believe this is because with cordova-android 10.0.x, the webview is now acting as a https page and you can't load/send to non secure origins while using https.
From the cordova docs

By default, the WebViewAssetLoader is enabled and allows apps to serve
their content from a 'proper' origin. This will makes routing work
easily for frameworks like Angular.
With no additional configurations, the app content is served from
https://localhost/. You can configure the hostname by setting the
preference option hostname.

   <preference name="hostname" value="localhost" />

The scheme, https, is not configurable by nature.


text:
Q: When I bootstrap Modal from CDHtmlView Class or CHTmlDialog, the scroll bar does not disappear. Why? When I bootstrap Modal from CDHtmlView Class or CHTmlDialog, the scroll bar does not disappear.

I am using the Windows IE Framework to control external web pages using CDHtmlView Class or CDHtmlDialog.
Of course, "\ Microsoft \ Internet Explorer \ Main \ FeatureControl \ FEATURE_BROWSER_EMULATION" is set to the latest (11001)
IE11 and Chrome browser will work normally. Do you know why?
How do I fix it?

    <colgroup>
      <col />
      <col />
      <col style="width: 50px;" />
    </colgroup>

        group
        odd
        delete

        hint message

// HTML onClick
<button onclick="sch_dept_modal_popup();" class="btn btn-sm btn-outline-info">add</button>

function sch_dept_modal_popup() {
  loadSearchDept('addDept');
}

// modal Call
function loadSearchDept(returnFunc) {
  if (!returnFunc || typeof (returnFunc) == "undefined" || returnFunc == "")
    return;
    var func = encodeURIComponent(btoa(returnFunc));
    var url = StringFormat("/util/search/dept?func={0}", func);
    $("#searchDept").load(url, function(response, status, xhr) {
        if (status == "error") {
            alert("get search_dept_modal error");
        }
        else
            $('#search_dept_modal').modal({
                backdrop : 'static',
                keyboard : false
            });
    });
}

When the Modal window appears, the scroll bar at the back should not come forward.


text:
Q: What would happen in the final days of the universe? I would like to know the stages of how the universe would end and what would happen and what the possible scenarios are.
I understand that eventually all the stars would burn out and that would introduce a big freeze that would make it harder to sustain life. Forgive me if this is incorrect as I do not have any expertise in this area, I would appreciate any information on this.

A: Adams & Laughlin wrote a great book about this, called "The five ages of the universe". It follows the history of the universe from the big bang to more than $10^{100}$ years. So the "final days" become rather longer. The book assumes the universe will continue to expand forever and follows the future of matter and energy. Up until around $10^{14}$ years (10,000 times longer than current the age of universe!) the universe is dominated by stars and other matter, as well as black holes. After that, protons that have not yet fallen into black holes will eventually decay. Later still (between $10^{40}$ and $10^{100}$ years) black holes will evaporate, and eventually we end up with an extremely dilute soup of electrons, positrons and photons that slowly drift further and further apart. The distance between any two particles will be far greater than the size of the current observable universe.
The book is a bit dated now as it did not take into account the existence of Dark Energy. Depending on what happens to Dark Energy in the future, the sequence may speed up or down. In the extreme case, Dark Energy may even tear matter apart.


text:
Q: Azure api management clone API I have an instance of Azure API management and it`s working all right with one domain. My question is what is the best way to make this API available for multiple environments?
For example my Urls are:

*

*http://dev.api.com

*http://api.com

*api.us.com

*api.hk.com

The four domain have the same web API running on them, they are just different servers.
Do I create one API management instance for each one?
Or do I create one instance in just one API management for each one?
Maybe there is an efficient way to do this and I`m missing out.
Have a nice day.
Best Regards,

A: I was needing this urgently so the way I did was importing and exporting the API. So basically I configured on the first server with all parameters I`d like, after this I went to the API page and exported to wadl and imported again changing the "Web API URL suffix" and "Web service URL".
The only cons I found is when I need to change the documentation or API definition, I need to change in four different API's.
I`ll send this feedback to Microsoft and see their response.
Have a nice day.

A: So the URLs you listed above are the backend services running Web API. If you use a single APIM instance then they will share the domain you set for that instance and can be delineated using suffixes - e.g. .azure-api.net/devapi, .azure-api.net/usapi, .azure-api.net/hkapi, etc. - the suffix names are under your control. Does that work / is it what you need?

A: Although an old question, I was searching for a similar answer, so I thought I'd add the solution I used here.
You can approach this by using the policies. In order to solve you first need to be able to differentiate which backend each user should be sent to (I used the products to do this, you might want to investigate using policies to do this part).
Once you have the products on the single API, you can then use the 'Set backend service' to forward on each request to the correct environment for the user.
To edit the policies you can navigate to the page on the API management portal. Select the products and api that you wish to configure and then select configure policy. Insert the 'Set backend service' into the 'inbound' policy and insert the backend.
<set-backend-service base-url="https://example.co.uk"/>

This Microsoft page has some useful information on policies for redirecting https://azure.microsoft.com/en-gb/blog/policy-expressions-in-azure-api-management/


text:
Q: jsGrid Jquery not loading data This code shows grid definition when run in browser. It also prints to console so I can see array of data is there.  Not showing in grid though, just grid headers.
Any ideas?
<!DOCTYPE html>

    <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
    <link type="text/css" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />

A: You can achieve this functionality by using loadData method inside of grid-controller.
SEE DEMO

$("#jsGrid").jsGrid({
  width: "100%",
  height: "auto",

  autoload: true,
  paging: true,
  pageSize: 10,
  pageButtonCount: 5,
  pageIndex: 1,

  controller: {
    loadData: function(filter) {
      return $.ajax({
        url: "//restcountries.eu/rest/v2/all",//you can put your url here.
        dataType: "json"
      });
    }
  },
  fields: [{
      name: 'alpha2Code',
      title: 'Code',
      width: 50
    },{
      name: "name",
      title:'Full Name',
      width: 50
    }
  ]
});

<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jsgrid/1.5.3/jsgrid-theme.min.css" />

A: Can you give a snippet of your actual data?
Your paging and pageLoading are true, so your data has to be of the form:
{
  "data": [ { ..first item ...}, { ..second item..}, ...],
  "itemsCount": n
}

itemsCount is the total number of records of your data. This is to allow jsGrid to compute the total number of pages.
See http://js-grid.com/docs/#loaddatafilter-promisedataresult


text:
Q: Soap UI to Exchange I am trying to connect SOAP UI to our Exchange server but i keep getting an error in SOAP UI of
Error loading [https://<<our exchange server>>/ews/Services.wsdl]: org.apache.xmlbeans.XmlException: org.apache.xmlbeans.XmlException: error: Unexpected element: STRING

I am using this as our endpoint which i have been reading that it is this and not the WSDL URL.
https://<<Our Exchange Server>>/ems/exchange.asmx

Anyone know what might be going on here?

A: Not sure if this is a typo in your code or just your comment, but the EWSUrl should be https://mail.contoso.com/EWS/Exchange.asmx, not /ems/.


text:
Q: Fixed div in y position but not in x position depending on other div I have a sidebar and navbar fixed, and I would like to know if it's possible to adapt the x position of the sidebar depending on the width of each articles.
HTML :

CSS :
div#sidebar{
    width: 200px;
    height: 100%;
    position: fixed;
    margin-top: 50px;
    float: left;
}

A: How about set sidebar inside article?
jsfiddle
HTML:

article

sidevar

CSS :
#article
{
    margin-left: 30px;
    background: white;
    width: 200px;
    height: 300px;

}

#sidebar
{
    position: fixed;

    top: 0px;
    width: 30px;
    height: 100%;
    background: blue;
    color: white;
}


text:
Q: Chrome Extension - ContextMenu listener not working after few minutes I'm trying to create a Chrome Extension which can dynamically create ContextMenu based on storage info. Each created menu has its owned key and will do some actions then send message to Content.js to show info box on page if it is clicked.
The menu will be updated if user select some options in Options page. The Options.js will send out a message to background.js, background.js update the storage then refresh menu.
The menu behavior works fine after extension was loaded. But no longer work after few minutes. If I open a console of service worker then it can stay longer, but it eventually no response when i click menu button. Further more, if i trigger the menu updating from Option page, the button back to live. But still failed after few minutes.
I made some research and found out seems background.js will be terminated very soon after it was loaded. So i doubt that cause this issue. But how com the added menu listener not working after that? The listener should already be added, isn't it?
Background.js

function eventListener(message, sender, sendResponse) {
  if (message.event === "updateMenu") {
    updateMenu();
    sendResponse({ result: "update menu completed" });
  }
}

function updateMenu() {
  chrome.storage.local.get("currencyMappings", function (result) {
    prepareContextMenuBySetting(result.currencyMappings);
  });
}

function prepareContextMenuBySetting(mappings) {
  chrome.contextMenus.removeAll();
  chrome.contextMenus.create(
    { id: "rootMenu", title: "%s", contexts: ["selection"] },
    function () {
      if (chrome.extension.lastError) {
        console.log("Got expected error: " + chrome.extension.lastError.message);
      }
    });
  mappings.forEach(map => {
    currencies = map.split("|");
    chrome.contextMenus.create(
      { id: `${currencies[0]}to${currencies[1]}`, title: `${currencies[0]} => ${currencies[1]}`, type: "normal", parentId: "rootMenu", contexts: ["selection"] });
  })

  chrome.contextMenus.onClicked.addListener(
    (info, tab) => {
      let rate = null;
      rateKey = info.menuItemId.split("to");
      makeExchange(rateKey, info)
    }
  );

}

Update:
Log will display when the function is working. But there was no any log in console when the button action is not working. Event both Server Worker and page console.

A: I figure out the possible reason. According to https://developer.chrome.com/docs/extensions/mv2/background_pages/#listeners
adding listener in listener function may not working.
The root cause is that the backgound.js will be terminated in short time. Only keep the root listener. After backgound.js is terminated, the listener in my menu button not working anymore.
Further  more, the background.js actually back to live if the root listener get called.
Ex.
chrome.runtime.onMessage.addListener(eventListener);

i added a console.log() at the top of background.js and monitor the console. After the Service Worker display unavailable, which means the backgroud.js is shut down, then I fire a message to background.js. The console.log() will be triggerd.
The solution of my issue is moving adding listener of menu to root level.
chrome.contextMenus.onClicked.addListener(
  (info, tab) => {
    console.log("item clicked");
    let rateKey = info.menuItemId.split("to");
    makeExchange(rateKey, info)
  }
);

Then once background.js is wake up, the button listener will be set.


text:
Q: Make extraParams in proxy bindable - a solution with 2 overrides extraParams config of a proxy is NOT bindable. The only standard way to bind data to a stores request is via filters. It might seem that extraParams is bindable since the first value is used. It only works one time, any changes to the bound value after that are not registered.
Using remote filters is a solution :
vehicleliststore: {
    model: 'packagename.model.Vehicle',
    proxy: {
        type: 'ajax',
        url: Ext.getResourcePath('php/overview/vehicle.php', null, 'packagename'),
        reader: AIIC.Global.defaultProxyReader,
    },
    autoLoad: true,
    remoteFilter: true,
    filters:[{
        property: 'personid',
        value: '{personId}'
    }],
}

This works fine until you want to use the remote filter to realy filter something.
To overcome this problem, make the extraParams bindable by writing 2 overrides. One for the store and one for the ajax proxy. The config loadonextraparamschange is optional.
Ext.define('overrides.data.proxy.Ajax', {
    override: 'Ext.data.proxy.Ajax',

    mixins :
    {
        observable : 'Ext.mixin.Observable'
    },

    constructor : function(config){
        // do all the constructor stuff of the parent..
        this.callParent(arguments);
        // now do the extended version constructor stuff...
        this.mixins.observable.constructor.call(this, config);
    },

    updateExtraParams : function(newValue, oldValue){
        // when keys change, fire event 'keyupdates'
        //console.log('updateExtraParams');
        this.fireEvent('extraparamsupdated', oldValue, newValue);
    },

});

And the override for the store...
Ext.define('overrides.data.Store', {
    override: 'Ext.data.Store',

    mixins :
    {
        observable : 'Ext.mixin.Observable'
    },
    config: {
        loadonextraparamschange : true,
    },

    constructor : function(config){
        var me = this;

        me.callParent(arguments);
        me.initConfig(config);
        // listen to proxy event 'keyupdated' and then do reload
        me.getProxy().on('extraparamsupdated', this.onExtraParams , me);
    },

    onExtraParams: function(extraParams){
        if( this.getLoadonextraparamschange() )  this.reload();

    }
});


text:
Q: Rails 3 validate_with throws ArgumentError: wrong number of arguments could anybody explain me why this code
class MyValidator < ActiveModel::Validator
  def validate
    # nothing here for now
  end
end

class MyModel < ActiveRecord::Base
  validates_with MyValidator
end

throws this exception (when I try to create a model object):
ArgumentError: wrong number of arguments (1 for 0)
/data/rubydev/kalpana/gems/activesupport-3.0.3/lib/active_support/callbacks.rb:314:in `validate'
/data/rubydev/kalpana/gems/activesupport-3.0.3/lib/active_support/callbacks.rb:314:in `send'

I used the tutorial for this one. It should work.

A: Your #validate method needs to accept one parameter (the model it's validating).
http://api.rubyonrails.org/classes/ActiveModel/Validator.html


text:
Q: Example for llvm::CloneBasicBlock I am trying to find an example code which uses llvm::CloneBasicBlock, but can't find it. I am having problems with PHI nodes and problem with instruction domination. So I'll appreciate any good example code which teach how to use llvm::CloneBasicBlock properly.

A: What's wrong with looking in the LLVM source itself? CloneBasicBlock is used in a number of places. The simplest is probably llvm::CloneFunctionInto; it should probably be enough to demonstrate how to correctly use the function (in terms of what arguments to pass, etc.)
A more interesting example is in llvm::LoopUnroll, which also has to deal with references from PHI nodes.


text:
Q: NV.D3 Cannot read property 'length' of undefined I'm trying to build a simple bar chart using based on reading in CSV data.  Right now I'm just including the data in my script.  When I try to run it, I get this error:
Uncaught TypeError: Cannot read property 'length' of undefined

Here's the script:
var data;

function showChart() {
  var theCsv =
    "name,value\n" +
    "Foo,43\n" +
    "bar,76\n" +
    "foo2,88\n" +
    "bar2,59\n";
  var csvString;
  var content = [{
    key: "totals",
    values: []
  }];

  var input = d3.csv.parse(theCsv, function(d) {
    return {
      name: d.name,
      value: d.value
    };
  });

nv.addGraph(function() {
    var chart = nv.models.discreteBarChart()
      .x(function(d) {
        return d.name
      })
      .y(function(d) {
        return d.value
      })
      /*.showvalues(true)*/

    d3.select('#chart svg')
      .datum(input)
      .transition(1000)
      .call(chart)

    nv.utils.windowResize(chart.update);
    return chart;

  });

  fileDisplayArea.innerText = csvString
}

As far as I can tell from debugging, the error is occuring on the .call(chart) line, but I have no clue what the problem is.  I've found a couple of links talking about the version of D3, but I've tried several different ones, and I'm still getting the error.
Here's a JSFiddle.

A: Looks like you need to wrap your data into another object like so:
var input = d3.csv.parse(theCsv, function(d) {
    return {
      name: d.name,
      value: d.value
    };
  });

// get it into the form required by `nvd3`
input = [{ key: "Some Key", values: input }]

Here's an updated fiddle with the one extra line above added.
I couldn't find any documentation on why, but that seems to be the pattern used (based on this example on the site).


text:
Q: netty pipeline order for outbound message I am using Netty v4.1.9final and trying to send a message from client to server. I tried setting up the channel client initializer with the handler as follows on the client side:
final Bootstrap bootstrap = BootstrapGenerator.generate();
bootstrap.handler(new XmlClientInitializer());

XMLClientInitializer
public class XmlClientInitializer extends ChannelInitializer<SocketChannel> {

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        final ChannelPipeline pipeline = ch.pipeline();

        pipeline.addLast("fileEncoder", new FileEncoder());
        pipeline.addLast("handler", new XmlSenderHandler());
    }
}

FileEncoder
public class FileEncoder extends MessageToByteEncoder<String> {

XmlSenderHandler
public class XmlSenderHandler extends ChannelOutboundHandlerAdapter {

    private static final Logger log = LogManager.getLogger(XmlSenderHandler.class.getName());
    private static ChannelHandlerContext ctx;

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) {
        log.info("attempting to write messages to server {}", msg.toString());
        ctx.write(msg, promise);
    }

    @Override
    @SuppressWarnings("FutureReturnValueIgnored")
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
    }
}

Even though the FileEncoder is defined first in the pipeline, it gets called after the xml handler (which is not what I am seeking).  Is this because the FileEncoder is extending MessageToByteEncoder or am I configuring the channel incorrectly?

A: No, the pipeline is configured correctly. The point is that the inbound event is processed from the first handler to the last, and the outbound event is processed from the last handler to the first one.
ChannelPipeline doc


text:
Q: not getting any results!! is there an error with the pdo code? The code is not giving any result can you help me ?
$f_name = $_POST['first_name'];
$l_name = $_POST['last_name'];
$e_mail = $_POST['email'];
$sql = "INSERT INTO
            informations(first name, last name,email ,email)
        VALUES($f_name,$l_name,$e_mail)";

 /*$result = pdo::query($sql);
if(!$result)*/
    $result = $sql->fetch(PDO::FETCH_ASSOC);
if(!$result)
{
    //something went wrong, display the error
    echo 'Something went wrong while registering. Please try again later.';
    //echo mysql_error(); //debugging purposes, uncomment when needed
}
else
{
    echo 'Successfully registered. You can now sign in and start posting! :-)';
}

A: You currently aren't using PDO propertly, you're fetching results with an insert query, and you aren't making the most of parameter binding.
Try this:
// make sure $db is initialized as a new PDO object
// use :param placeholders for binding
$sql = "INSERT INTO informations(first name, last name, email) VALUES(:first, :last, :email)";

// prepare query
$query = $db->prepare($sql);

// set up parameter binding replacements
$binding = array(
    ':first' => $f_name,
    ':last' => $l_name,
    ':email' => $e_mail // strange variable name splitting...
);

// execute the query (returns boolean true or false)
$query_results = $query->execute($binding);

// process result message
if($query_results) {
    echo 'Success';
} else {
    echo 'Something went wrong! Error: ' . $query->errorInfo();
}

For reference:

*

*PDO::execute() manual

*PDO introduction tutorial

*Another PDO tutorial


text:
Q: specific homotopy groups of $\textrm{Gr}(n,m)$ --- $\pi_0$, $\pi_n$, $\pi_m$, $\pi_{n+m}$ Given a real Grassmanians
$$\textrm{Gr}(n,m)=O(n+m)/O(n)\times O(m)$$
could we determine the following specific homotopy groups:
$$\pi_0\textrm{Gr}(n,m)=?$$
$$\pi_n\textrm{Gr}(n,m)=?$$
$$\pi_m\textrm{Gr}(n,m)=?$$
$$\pi_{n+m}\textrm{Gr}(n,m)=?$$
You can provide partial answers. No need to be complete if some of the answers are too harsh. We can boil down the answer by writing in terms of homotopy groups of $O(n+m)$, $O(n)$, $ O(m)$.
We take $n,m \geq 1$.


text:
Q: Pandas mutliIndex sort by group I would like to keep values the same order (descending), but I am unable to group by index level 0 the following frame. The block with code 0512 should come together keeping descending order by code.
code   product                                        count
0510  あたたか新潟こしひかり 5kg                 1
0511  キッコ−マン 味わいリッチ減塩しょうゆ 450ml       1
      7プレミアム 国産果汁使用ゆずぽん酢 200ml        1
0512  キリン 生茶 525ml                    1
      キリンレモン 450ml                    1
      コカ・コーラ い・ろ・は・す もも 555ML         1
      サントリー なっちゃん オレンジ 425ml          1
      サントリー プレミアムボス ブラック 490ml        2
      サントリー 天然水南アルプス 2L ケース           1
      サントリー 天然水南アルプス 2L ペット           1
      サントリー 朝摘みオレンジ&天然水 540ml         1
      大塚 ポカリスエット 900ML ペット            1
      森永 inゼリー エネルギーレモン 180g          1
      綾鷹 525MLペット                     2
      7プレミアム パイナップルサイダー 500ml         1
      7プレミアム フルーツオ・レ 500ml            1
      GAクラフトマン ダークモカ 440ml            1
      UCC 職人の珈琲 無糖 930ML ペット          1
0513  アサヒ オフ 500ml×6                  1
      キリン 本麒麟 500ml                   1
      万上 濃厚熟成本みりん 1L                  1
      東村山純米酒 720ml                    1
0514  ブルボン プチポテトコンソメ味 45g             1
      ロッテ ガーナローストミルク 50g              1
      ロッテ グリーンガム 9枚                   1

My code
data = df.groupby(['code','product']).size().reset_index(name='counts').set_index(['code','product'])
data1 = data.sort_values(by=['counts','code'], ascending=False).groupby(['product','code']).sum()

EDIT:
I could see that the second groupby put the code together but mess up the descending order of count per code as we can see for 0512.

A: You should pass a list to the ascending argument in the second line, like this:
data1 = data.sort_values(by=['counts','code'], ascending=[False,False]).groupby(['product','code']).sum()

Otherwise, it would take the default value which is True for "code" column.


text:
Q: setText() for custom Dialog box causing app to crash I have started developing in android. I am trying to do a word game, at the end I should be displaying the players result in a dialog box. I have a textView in the layout and when trying to use setText() the app crashes. Otherwise the custom dialog gets displayed. Need help.
@Override
   public void onClick(View v) {
    switch (v.getId()){
        case R.id.butt_submit:
            puzzword.validateAnswer();
            puzzword.resetStrings();
            init();
            if(count==10){
                showScore();
                count=0;
               // finish();
            }
            break;
        case R.id.butt_share:
            break;
    }
   }

public void showScore(){
    Dialog d = new Dialog(this);
    d.setContentView(R.layout.dialog1_layout);
    d.setTitle("Your Score");
    TextView correctAns = (TextView) findViewById(R.id.correctAns);
    correctAns.setText("Correct Answers");
    d.show();
}

Layout file for the custom dialog box is here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent"
android:background="@color/back_color">

<TextView
    android:id="@+id/correctAns"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textColor="@color/text_color"
    android:textSize="25dp"
    />
<TextView
    android:id="@+id/wrongAns"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/correctAns"
    android:layout_marginTop="30dp"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:textColor="@color/text_color"
    android:textStyle="bold"
    android:textSize="25dp"
    />

</RelativeLayout>

A: The issue is that you are trying to get the view from the activity content view and not from the dialog view hirarchy.
Instead of :
TextView correctAns = (TextView) findViewById(R.id.correctAns);

Write:
TextView correctAns = (TextView) dialog.findViewById(R.id.correctAns);

A: Try this:
TextView correctAns = (TextView)  dialog.findViewById(R.id.correctAns);


text:
Q: Error in Dijkstra's shortest path algorithm implementation (using C++ STL) I have tried to implement Dijkstra's algorithm in C++ using std::priority_queue.The function "dijsktra"  will take input as 2 nodes, the source vertex and the destination vertex. However, I am getting incorrect answers every time. Kindly help me out and tell me where I have erred. My code-
#include <iostream>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <stdio.h>
#include <vector>
#include <numeric>
#include <set>
#include <map>
#include <queue>
#define inf 9999999
using namespace std;

map <int,int> vis;
vector <vector <pair <int,int> > > adj(100);
vector <int> dist(100);

void dijkstra(int u,int t)
{
    priority_queue <pair <int,int> > q;
    int b,w,i;
    q.push({0,u});
    vis[u]=1;

    while(!q.empty())
    {
        u = q.top().second; q.pop();

        if(!vis[u])
        {
            vis[u]=1;
            for(i=0;i<adj[u].size();i++)
            {
                b = adj[u][i].first; w = adj[u][i].second;
                if(dist[b]>dist[u]+w)
                {
                    dist[b] = dist[u] + w;
                    q.push({-dist[b],b});
                }
            }
        }
    }

    cout << dist[t];
}

int main()
{
    int i,j,k,n,m,x,y,w,t;

    cin >> n >> m;
    for(i=0;i<m;i++)
    {
        cin >> x >> y >> w;
        adj[x].push_back({y,w});
        adj[y].push_back({x,w});
    }

    cin >> t;

    for(i=1;i<=n;i++)
    {
        dist[i]=inf;
    }

    dijkstra(1,t);
}

A: Mistake:
Your code is not working due to vis[u] = 1 which never lets you enter the for loop.
Actually there is no need of having a visited array in Dijkstra algorithm (atleast for this case). But using visited array here will decrease the time complexity and when there are negative edges it will be tricky, so be careful there.
#include <iostream>
#include <vector>
#include <queue>
#define inf 9999999

std::vector <std::vector <std::pair <int,int> > > adj(100);
std::vector <int> dist(100);

void dijkstra(int u,int t)
{
    std::priority_queue <std::pair<int, int>> q;
    int b, w, i;

    q.push({0, u});
    while(!q.empty()) {
        u = q.top().second;
        q.pop();
        for(i = 0; i < adj[u].size(); i++) {
            b = adj[u][i].first; w = adj[u][i].second;
            if(dist[b] > dist[u] + w) {
                dist[b] = dist[u] + w;
                q.push({-dist[b], b});
            }
        }
    }

    std::cout << dist[t];
}

int main()
{
    int i, n, m, x, y, w, t;

    std::cin >> n >> m;
    for(i = 0;i < m; i++) {
        std::cin >> x >> y >> w;
        adj[x].push_back({y, w});
        adj[y].push_back({x, w});
    }

    std::cin >> t;

    for(i = 0; i < n; i++) {
        dist[i] = inf;
    }

    // making the source distance to 0
    dist[0] = 0;

    dijkstra(0,t);
}

A: The problem is vis[u]=1; just after q.push({0,u});.
Due to that, the check if(!vis[u]) cannot be passed and no nodes will be processed.
You should do dist[u]=0; instead of that.


text:
Q: Running a Python model I've been given a piece of code which is a physical model (filename 'agnsim.py') and some instructions to run it which I'm confused by.
The instructions say that I should import the code using
import agnsim as agn

and then to run the model with
ed = agn.Wilp(dens=3., incr=0.2, drac=2.0)

The argument above in Wilp will configure the run.
My question is, how do I actually run this?  Do I create a separate .py file that contains these two lines of code?
I've only ever run simple python programs before using e.g. >>>python file.py

A: You should literally just open up the python console and type those two lines in.
$python
import agnsim as agn
ed = agn.Wilp(dens=3., incr=0.2, drac=2.0)

Make sure that agnsim.py is located at the same folder level from which you start python. E.g. If you're in "My Documents" and "agnsim.py" is in my documents, you should cd to "My Documents" and then start python there (from the command line).


text:
Q: Disable warnings in TypeScript for generated code I use OpenApiTool/OpenApi-Generator-CLI to generate code for models and services based on API. When I start my Angular 9 application then in the console I see warnings for generated files:

WARNING In file.name.ts is part of the TypeScript compilation, but it
is unused. Add only entry points to the 'files' or 'include' properties
in your tsconfig

All genarated files are placed in ~/src/app/api-client
How to configure tsconfig.json file to disable such warnings for this path?


text:
Q: Different text scaling factors for different displays? I just purchased a new laptop, which has a much higher DPI than my prior one did; in fact, its resolution (in a 14" form) is roughly the same as that of my 23" second monitor.
I'd like the text on each display to be roughly equivalent.  Adjusting the window-manager-wide text scaling factor (via e.g. gnome-tweak-tool) yields either too-small text on the laptop screen, or too large text on the second monitor.
Is there any way to have different text scaling apply to different displays?  I suspect not, but I would very much like to avoid replacing my current (perfectly good) external monitor just to compensate for the DPI increase in the laptop.

A: There are workarounds: you can, for example, adjust dpi for the most dense screen, and use xrandr to downscale other screens (to keep it crisp). See my answer for a relative question:
Is it possible to have two different DPI configurations for two different screens?
PS: sorry, the topic is a duplicate, but I do not know how mark it as duplicate - so just give a link for existing one.


text:
Q: Should I install Microsoft Security Essentials on Windows 8 Developer Preview?  Does Windows 8 Developer Preview come pre-installed with anti-virus software?
I'm testing Windows 8 on my laptop and it's running great; I just want to make sure it's secure.
Should I install Microsoft Security Essentials on Windows 8 Developer Preview?

A: Windows 8 Developer Preview comes with the old Windows Defender, not as good as MSE, I installed MSE on my W8 install.
.

A: Windows 8 Developer Preview comes with the new MSE which is renamed to the old name Windows Defender. Under the Action center's virus section, it says Windows Defender is the provider. If you look at the name of the executable file of the Windows Defender in task manager, it says MsMpEng.exe, same as Security Essentials.
There is no need to install the old MSE on the developer preview for virus protection.

A: I installed Avast AV without any problems ...

A: Microsoft have issued a KB which puts a hard block on the installation of MSE on the Windows 8 Consumer Preview. Link.
This would suggest that it conflicts with the built-in Windows Defender, and that MSE is redundant.


text:
Q: Emulating Old Tektronix Coded Probes I've got an older Tektronix 2430 100MHz oscilloscope. The older probes are "coded" and according to the manual are supposed to automatically select the proper scale based on the probe type. My last original probe just broke, so I ordered some inexpensive generic replacements. These have a 1x/10x switch on them to select the attenuation built into the probe. Obviously, the 'scope doesn't know anything about the generic probes and always defaults to 1x mode.
Thus, when trying to use the 400mV P-P 1 MHz square wave for calibration it shows up on the display as 40mV P-P (10% of actual value).
Normally, there is an attenuation setting on the 'scope itself to get the scaling right for display, but this this one is either automatic-only or there is a really cryptic setting that I can't find... Sure, I could always do the 1:10 conversion in my head, but it would be more fun to build something that fakes the 'scope out.
Question: Does anybody know how this "coding" works so I can fake it out and make the 'scope think that the probe is a 10x probe all of the time?
Images below for your reference. Thanks for your help!
Connection on 'scope:

Genuine Tek probe (P6131)

Generic replacement probe

A: According to the manual of my Tek 465B scope, the coupling ring is connected through a resistor to the base of a transistor that controls the illumination of the 1X and 10X LED indicators.  A typical probe (P6105) has an 11k resistor connected between the coupling pin on the probe body and ground. Thus when the probe is connected to the scope BNC connector, the transistor is connected to ground through this resistor.  This changes its state which then turns off the 1X indicator and turns on the 10X indicator. If you could take the Tek probe BNC (with the coupling pin) and substitute it for the generic probe BNC, you might be able to make the probe sensing work.

A: I experienced the following on my 2425A scope for the probe coding, with Rp being the resistance between the coupling ring and ground:
Rp               scaling
------------------------
>10k5            x1
8k5 < Rp < 10k5  x10
5k5 < Rp < 8k5   x100
0k5 < Rp < 5k5   x1000

Confirmed on a 2445

A: If I recall correctly, the pin on the coupling ring shown in your picture of the Tek probe grounds the insulated ring around the connector on the scope to indicate that the probe is set to 10 X.  If your probe is sufficiently intact, you could check this with an ohmmeter...
I don't think you could easily make a generic probe switch the indication to match the probe setting, but with a little ingenuity you may be able to make the generic probe force the scope to always indicate the 10X scale.  If you don't mind making a small mod to the scope, you could add switches to the scope to change the scale indication, by grounding (or not) the sensing ring.


text:
Q: deleting certain lines in ms word 2007 I would like to delete certain lines from my word document using a VBA macro. Basically the (block of) text to be deleted (and replaced by "***") follows a certain pattern (below).
Bottom of Form
perma-link

Top of Form
save
Bottom of Form
[+] ....
[–] ....
Top of Form

"...." represents text that changes every block, but for sure the line starts with "[+]" or "[-]".
Please suggest a suitable macro
EDIT: In the screenshot, I would like to keep the text in yellow and delete the rest. (in the actual file, the text isn't in yellow)
PS-FYI, I tried using the example looping a find and delete row macro (for line by line deletion) but i get a runtime error 5941 with debugging option highlighting the line "selection.row.delete" in the macro.
What does this mean?

A: Assuming that the example list is a list of paragraphs beginnings the following code should do the trick. What you have to do is to place all 'paragraphs starting' into array arrRemove as I did for the test. If any of the mark is a special marks (see this link for additional information) you need to add \ in front of it as I did for [+] and [-]. Hope this is what you are looking for.
Sub Macro2()

    Dim arrRemove As Variant
        arrRemove = Array("Bottom of Form", "perma -link", "Top of Form", _
                    "\[+\]", "\[\-\]", "Donec", "In")

    Dim i!
    For i = 0 To UBound(arrRemove)
        Activedocument.Range(0,0).select

        Selection.Find.ClearFormatting
        With Selection.Find
            .Text = arrRemove(i) & "*^13"
            .Replacement.Text = ""  'replace with nothing

            .Forward = True
            .Wrap = wdFindContinue
            .MatchCase = False
            .MatchWildcards = True
        End With
        Selection.Find.Execute Replace:=wdReplaceAll

    Next i

End Sub

The above macro will remove all yellow paragraph in the following document.


text:
Q: How to pass output of grep to sed with tail -f command I am trying to filter out certain lines in a log file using the tail -f |grep command:
tail -f /path/to/file.log |grep error

This works fine and I get a nice stream of errors only from the log.
The output of this has the entire date string at the beginning of each line eg. 07-Apr-2021
I want to filter out the first 11 characters of each line (07-Apr-2021)
So I have tried the following:
tail -f /path/to/file.log |sed 's/...........//'

This works fine as well and removes the first 11 characters of each line.
So, I then tried the grep and sed together so I would get only error massages without the date at the beginning:
tail -f /path/to/file.log |grep error |sed 's/...........//'

I get no output from this. I also tried:
tail -f /path/to/file.log |sed 's/...........//' |grep error

Same again - no output. I don't get any errors I just get a blinking cursor with no output.
Obviously I am doing something wrong, any help would be appreciated.

A: Trying to fix OP's attempt here. Please try following. Couldn't test it because samples were not attached; should work though.
tail -f /path/to/file.log | grep --line-buffered "error" | sed -E 's/^.{11}//'

From man grep:

--line-buffered
Use line buffering on output.

Also I have fixed your sed's substitution here, you need not mention 11 dots here you could handle that with regex like I shown above.

2nd solution: Within single awk you could do following.
tail -f Input_file | awk '/error/{sub(/^.{11}/,"");print;fflush()}'

A: Thanks for the answers, I have found that the reason I wasn't getting an output is that I needed to use --line-buffered for the grep (thanks ravindersingh13). In regards to the sed command this is what I ended up using and worked:
tail -f /path/to/file.log | grep --line-buffered "error" | sed -r 's/{11}//'

This removes the first 11 characters of the grep output.

A: Getting rid of the useless grep might also be an option, and arguably more elegant.
tail -f /path/to/file.log |
sed -n '/error/s/...........//p'


text:
Q: "./sbt/sbt assembly" errors "Not a valid command: assembly" for Apache Spark project I'm having trouble with installing Apache Spark on Ubuntu 13.04. Im using spark-0.8.1-incubating, and both ./sbt/sbt update and ./sbt/sbt compile work fine. However, when I do a ./sbt/sbt assembly I get the following error:
[info] Set current project to default-289e76 (in build  file:/node-insights/server/lib/spark-0.8.1-incubating/sbt/)
[error] Not a valid command: assembly
[error] Not a valid project ID: assembly
[error] Not a valid configuration: assembly
[error] Not a valid key: assembly
[error] assembly
[error]

I googled for stuff related to this but couldn't find anything useful. Any guidance would be much appreciated.

A: The current project set to default-289e76 message suggests that sbt was called from outside of the Spark sources directory:
$  /tmp  ./spark-0.8.1-incubating/sbt/sbt assembly
[info] Loading global plugins from /Users/joshrosen/.dotfiles/.sbt/plugins/project
[info] Loading global plugins from /Users/joshrosen/.dotfiles/.sbt/plugins
[info] Set current project to default-d0f036 (in build file:/private/tmp/)
[error] Not a valid command: assembly
[error] Not a valid project ID: assembly
[error] Not a valid configuration: assembly
[error] Not a valid key: assembly
[error] assembly
[error]         ^

Running ./sbt/sbt assembly works fine from the spark-0.8.1-incubating directory (note the log output showing that the current project was set correctly):
$  spark-0.8.1-incubating  sbt/sbt assembly
[info] Loading global plugins from /Users/joshrosen/.dotfiles/.sbt/plugins/project
[info] Loading global plugins from /Users/joshrosen/.dotfiles/.sbt/plugins
[info] Loading project definition from /private/tmp/spark-0.8.1-incubating/project/project
[info] Loading project definition from /private/tmp/spark-0.8.1-incubating/project
[info] Set current project to root (in build file:/private/tmp/spark-0.8.1-incubating/)
...

A: You typed "abt" twice, but shouldn't that be "sbt"? Apache Spark has its own copy of sbt, so make sure you're running Spark's version to pick up the "assembly" plugin among other customizations.
To run the Spark installation of sbt, go to the Spark directory and run ./sbt/sbt assembly .


text:
Q: Generate orthogonal (lower) upper-triangular matrices Problem
I am trying to numerically verify the fact that "the orthogonal lower (upper) triangular matrix has to be diagonal". However, I have difficulty finding general matrices that satisfies both orthogonality and triangularity since brute force search is of no hope.
Instead, I am wondering if I could manually specify such matrices. More formally, find matrices $\mathbf{A}=[\mathbf{v}_1,\mathbf{v}_2, \cdots, \mathbf{v}_n]$ such that
$$
\begin{cases}
\mathbf{v}_i^T\mathbf{v}_j=0, i\neq j\\
\mathbf{v}_i^T\mathbf{v}_j=1, i=j\\
\mathbf{v}_i[i-k]=0, i\geq 2,k=1,2\cdots,(k-1)
\end{cases}
$$


text:
Q: Need hint: Prove that $r = a (\sin t) + b (\cos t)$ is a circle, where $ab \neq 0$ "Show that the polar equation $r = a \sin(t) + b \cos(t)$, where $ab \neq 0$, represents a circle, and find its center and radius."
I don't need the answer - I just need a hint to nudge me on. I've tried to tackle it by investigating tangents, completing squares, force-fitting into the formula of a circle, etc., but I can't seem to arrive at the indisputable conclusion that it must be a circle.
This is not homework, by the way. It comes from a Calculus textbook that I am studying on my own. I understand you have no reason to believe me, but if I were taking a real course, I'd bring this to my TA.

A: Multiply either side by $r$, use $r^2=x^2+y^2, r\sin t=y,r\cos t=x$
But we don't need $ab\ne 0$
If $a=0,r=b\cos t\implies r^2=b r\cos t\implies x^2+y^2-bx=0$
$\implies (x-\frac b 2)^2+y^2=(\frac b 2)^2$ is a circle.
If both $a,b$ are $0, r=0\implies x^2+y^2=0$ which is point-circle.

A: Hint: Use the relations $\sin{t} = \frac{y}{r}$, $\cos{t} = \frac{x}{r}$ and $r = \sqrt{x^2 + y^2}$ to find a cartesian equation for the circle.

A: Hint 1:
Compute $x$ and $y$:
$$
\begin{array}{lll}
x&=r\cos(t)&=a\sin(t)\cos(t)+b\cos^2(t)&=\frac{a}{2}\sin(2t)+\frac{b}{2}(1+\cos(2t))\\
y&=r\sin(t)&=a\sin^2(t)+b\sin(t)\cos(t)&=\frac{a}{2}(1-\cos(2t))+\frac{b}{2}\sin(2t)
\end{array}
$$
Hint 2:
Therefore, if we set $(b,a)=\sqrt{a^2+b^2}(\cos(\theta),\sin(\theta))$, we get
$$
(x,y)=\tfrac12(b,a)+\tfrac12\sqrt{a^2+b^2}\;(\cos(2t-\theta),\sin(2t-\theta))
$$
Answer: (mouse over to view)

Thus, the curve is a circle of radius $\frac12\sqrt{a^2+b^2}$ centered at $\frac12(b,a)$.


text:
Q: How do i compare the dates read from csv file, such that I will only count those post with that month? I am currently stumped in filtering out the dates that I have retrieved from 2 CSV file via opencsv. I wish to filter out the dates by month such that I could count the number of posts of each month and display it via javaFX line chart. E.g. y-axis would be number of post, x-axis would be the month.
So far, as per my codes below, it just prints out a list of "is it not comparing". So far I have manage to convert the date to string format such that it would print out just the month, Feb, Jan, Dec, etc...
Format of the dates in csv files are:
csv file 1: Feb 14, 2020, 8:03 pm

csv file 2: 2020-01-20T16:34:57+0800

CODE
int febCounter = 0;
int janCounter = 0;
int decCounter = 0;
String pattern = "MMM";
SimpleDateFormat sdf = new SimpleDateFormat(pattern);

try (Reader reader = Files.newBufferedReader(Paths.get("file_path"));
            CSVReader csvReader = new CSVReader(reader);){
    String [] nextRecord;
    while((nextRecord = csvReader.readNext()) != null) {
        String retrievedate = nextRecord[2];
        Date date = sdf.parse(retrievedate);
        String strDate = sdf.format(date);
        if(strDate.equals("Feb")) {
            febCounter++;
        }
        else {
            System.out.println("it is not comparing");
        }
        System.out.println(febCounter);
    }
} catch(IOException e) {
    System.out.print("File can't be found");
}

EXPECTED OUTPUT
Feburary: 50

January: 20

December: 10

Current OUTPUT
it is not comparing
it is not comparing
it is not comparing
it is not comparing

so on....
UPDATE
So I am able to fix my error, I needed to format the retrieved date twice, once is to format the date such that I would only have the month, second format is to convert the date into a string, such that "strDate.equals("Feb")" will work.

A: Can you add a real example of the content of files?
You have two csv files, each one has a different date format.
lets strat with the first one, if you have "Feb 14, 2020, 8:03 pm" then the nextRecord variable will be :
[
    0 => "Feb 14",
    1 => "2020",
    2 => "8:03 pm",
]

And you have to test if nextRecord[0].startWith("Feb") and not equal.

A: You need to read the value from the CSV file and use logic similar to the one given to get the value of month counters. For the purpose of the demo, I have put some dates in an array.
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.TextStyle;
import java.util.List;
import java.util.Locale;

public class Main {
    public static void main(String[] args) {
        List<String> monthList = List.of("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov",
                "Dec");
        int[] months = new int[12];
        String[] dateStrs = { "Feb 14, 2020, 8:03 pm", "Jan 20, 2020, 9:03 am", "Mar 6, 2020, 2:03 pm",
                "Feb 15, 2020, 11:03 am", "Jul 18, 2020, 4:03 am", "Jan 21, 2020, 5:03 pm", "Mar 11, 2020, 6:03 pm" };
        for (String dateStr : dateStrs) {
            months[monthList.indexOf(LocalDate.parse(dateStr, DateTimeFormatter.ofPattern("MMM d, yyyy, h:mm a"))
                    .getMonth().getDisplayName(TextStyle.SHORT, Locale.US))]++;
        }
        for (int i = 0; i < months.length; i++) {
            System.out.println(monthList.get(i) + ":" + months[i]);
        }

        //Similarly apply the following format for the second CSV file
        // DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ssXX")
        // String[] dateStr2 = {"2020-01-20T16:34:57+0800",...};
    }
}

Output:
Jan:2
Feb:2
Mar:2
Apr:0
May:0
Jun:0
Jul:1
Aug:0
Sep:0
Oct:0
Nov:0
Dec:0

I hope, this is enough hint for you to complete your task. Feel free to comment in case of any issue.


text:
Q: Ignore arrow key input on rich:scrollableDataTable I have a rich:scrollableDataTable on my JSF page. If I click a row, then hit the down arrow key to scroll the page, it instead changes the selection in the table. I don't want this to happen, for a number of reasons. Is there some way I can turn that off, or just eat that keypress outright?

A: If you can replace the rich:scrollableDataTable with an rich:extendableDataTable you will be able to capture the onkeypress event.
<rich:rich:extendableDataTable ... onclick="Event.stop(event);" .../>

Or you can filter out only the up/down arrow keys with further js.


text:
Q: Subscribe non-exposed NodeJS Application to SNS On my current architecture, I have a NodeJS application that posts a message on SQS, which triggers a lambda function that (finally) puts the result on MongoDB. While the lambda is running, the NodeJS app pools MongoDB until the status field changes to SUCCESS or FAILED.
I would like to change this architecture to be event-driven rather than relying on pooling. To achieve that I considered changing both the NodeJS app to subscribe to a SNS topic and the Lambda function to post the result to that topic.
However, I faced a challenge when attempting to subscribe to the SNS topic. The subscribe method demands an Endpoint to confirm the subscription, and the NodeJS in question is not exposed (it's not an API). So how could the subscription be confirmed?
I understand that AWS might want to avoid spams by implementing subscription confirmation for SMS and Email, but on this case, the subscriber is a simple application...
Is there any way to subscribe tot he topic without exposing the NodeJS application? Or SNS is not the appropriate solution here?
I have used RabbitMQ for this on the past, but I would rather not deploy an instance and instead leverage a platform-as-a-service type of product.


text:
Q: Prevent EditText from scrolling to cursor Is it possible to keep EditText scrolled all the way to the left, instead of following the cursor while typing?
EditText is set to WRAP_CONTENT and text is longer than the view.
I have tried posting a scrollTo(0, 0) in afterTextChanged, but it only works when gravity is left (text disappears if gravity is right or center).
Also, the scrolling (jump) is noticeable after each keystroke.
What would be a proper way to achieve this?
Update:
I managed to determine the first character of the longest line in TextView and post bringPointIntoView(x) in onPreDrawListener but the jump is still noticeable.


text:
Q: Using .NET's HttpWebRequest to download a multitude of files in a row I have an application that needs to download several files in a row in succession (sometimes a few thousand).  However, what ends up happening when several files need to be downloaded is I get an exception with an inner exception of type SocketException and the error code 10048 (WSAEADDRINUSE).  I did some digging and basically it's because the server has run out of sockets (and they are all waiting for 240s or so before they become available again) - not coincidentally it starts happening around the 1024 file range.  I would expect that the HttpWebRequest/ServicePointManager would be reusing my connection, but apparently it is not (and the files are https, so that may be part of it).  I never saw this problem in the C++ code that this was ported from (but that doesn't mean it didn't ever happen - I'd be surprised if it was, though).
I am properly closing the WebRequest object and the HttpWebRequest object has KeepAlive set to true by default.  Next my intent is to fiddle around with ServicePointManager.SetTcpKeepAlive().  However, I can't see how more people haven't run into this problem.
Has anyone else run into the problem, and if so, what did you do to get around it?  Currently I have a retry scheme that detects this error and waits it out, but that doesn't seem like the right thing to do.
Here's some basic code to verify what I'm doing (just in case I'm missing closing something):
WebRequest webRequest = WebRequest.Create(uri);
webRequest.Method = "GET";
webRequest.Credentials = new NetworkCredential(username, password);

WebResponse webResponse = webRequest.GetResponse();
try
{
    using(Stream stream = webResponse.GetResponseStream())
    {
        // read the stream
    }
}
finally
{
    webResponse.Close()
}

A: What kind of application is this? You mentioned that the server is running out of ports, but then you mentioned HttpWebRequest. Are you running this code in a webservice or ASP.NET page, which is trying to then download multiple files for the same incoming request from the client?
What kind of authentication is the page using? If it is using NTLM authentication, then the connections cannot be shared if the credentials being used are different for each request.
What I would suggest is to group your request per credential. So, for eg, all requests using username "John" would be grouped. You can specify the "ConnectionGroupName" property on the service point, so the system will try to reuse connections for the same credential and server.
If that also doesnt work, you will need to do one or more of the following:
1) Throttle your requests.
2) Increase the wildcard port range.
3) Use the BindIPConnectionCallback on ServicePoint to make it bind to a non-wildcard port (i.e a port in the range 1024-16384)

A: More digging seems to point to it possibly being due to authentication and the UnsafeAuthenticatedConnectionSharing property might alleviate this.  However, I'm not sure that's the best thing, either.


text:
Q: List view difference in python I am working on python project for my python course project so I need to get number from users so enter image description here
here is my test codes but the output is like that
enter image description here
I want to store my input data like this one [2] not like this ['2'] what can I do for solve this.
Thanks for help.

A: Try the below:
yinp = int(input('enter your number'))

Explanation: By default python will take the inputs as string, you need to convert it to required type. In this case you need to convert into integer, int() is helpful for you.

A: by declaring new variable as input and without declaring what type it is, python will adress the variable as string.
you will need to convert your variable:
yinp= int(input("enter your number")

A: That's because the program doesn't know that you meant for "2" to be a number, you have to cast it into a number aka int, or a float.
You can do this like that (assuming there is only one input number):
ydata.append(float(yinp))

Also learn how to paste code into Stackoverflow


text:
Q: Element in the absolute Galois group of the rationals Usually when people talk on the absolute Galois group Gℚ of ℚ they have in mind two elements they can describe explicitly, namely the identity and complex conjugation (clearly, everything is up to conjugation), although the cardinality of the group is uncountable.
Can you describe other elements of Gℚ?

A: Leila Schneps claims that one cannot write down any other element.
See her paper in The Grothendieck theory of dessins d'enfants. Papers from the Conference on Dessins d'Enfant held in Luminy, April 19--24, 1993. Edited by Leila Schneps. London Mathematical Society Lecture Note Series, 200. Cambridge University Press, Cambridge, 1994. I think that http://www.aimath.org/WWN/motivesdessins/schneps1.pdf is more or less the same.

A: It is a theorem of Artin that the only non-trivial element in $\mathrm{Gal}(\overline{\mathbf{Q}}/\mathbf{Q})$ (up to conjugation) of finite order is complex conjugation. This explains Leila Schneps' remark. There is a related theorem of Artin and Schreier that says that if a field $F$ has a finite non-trivial absolute Galois group, then $F$ has characteristic zero and $\overline{F} = F(\sqrt{-1})$.

A: See the last of this extended answer.  I'm going to part company with everyone else and say that you can describe other elements of $\text{Gal}(\mathbb{Q})$.  In other words, I claim that you can identity a specific element of $\text{Gal}(\mathbb{Q})$ in a wide range of ways, together with an algorithm to compute the values of that element as a function on $\mathbb{Q}$.  You can use either a synthetic model of $\overline{\mathbb{Q}}$, or its model as a subfield of $\mathbb{C}$.  Although this is all doable, what's not so clear is whether these explicit elements are interesting.
The other two parts of the answer raise interesting issues, but they are moot for the original question.

This is not exactly the question, but it is related.  To begin with, it is difficult to "explicitly" describe $\overline{\mathbb{Q}}$ except as a subfield of $\mathbb{C}$.  I found a paper, Algebraic consequences of the axiom of determinacy (in English translation of the title) that establishes that $\mathbb{C}$ does not have any automorphisms other than complex conjugation in ZF plus the axiom of determinacy (AD).  So you need some part of the axiom of choice (AC) for this related question.
As for the smaller field $\overline{\mathbb{Q}}$, the Wikipedia page for the fundamental theorem of algebra suggests that you might not even be able to construct it in the first place without the axiom of countable choice.  (I say "suggests" because I'm not entirely sure that that is a theorem.  Note that AC and AD both imply countable choice even though they are enemy axioms.)    Any construction with countable choice isn't truly "explicit".  On the other hand, if you allow countable choice, then I suspect that you can build $\overline{\mathbb{Q}}$ synthetically by induction rather than as a subfield of $\mathbb{C}$, and that you can build many automorphisms of it as you go along.
So the questions for logicians is whether there is a universe over ZF in which $\overline{\mathbb{Q}}$ does not exist, or a universe in which it does exist but has no automorphisms.

I got email about this from Kevin Buzzard that made me look again at the paper referenced by Wikipedia, A weak countable choice principle by Bridges, Richman, and Schuster.  According to this paper, life is pretty strange without countable choice.  You want to make the real numbers as the metric completion of the rationals.  However, there is a difference between general Cauchy sequences and what they called "modulated" sequences, which are sequences of rationals with a promised rate of convergence.  They cite a result of Ruitenberg that the modulated complex numbers are algebraically closed in ZF.  Hence $\mathbb{Q}$ has an algebraic closure in ZF.
But it still seems possible that without countable choice, algebraic closures of $\mathbb{Q}$ need not be unique up to isomorphism, and that the complex analysis model of $\overline{\mathbb{Q}}$ might not have automorphisms other than complex conjugation.

A better and hopefully final technical answer:  As mentioned, $\overline{\mathbb{Q}}$ exists explicitly (in just ZF) as a subfield of $\mathbb{C}$.  You can also construct it synthetically as follows:  Consider the monic Galois polynomials over $\mathbb{Z}$.  These are the polynomials such that the Galois group acts freely transitively on the roots; equivalently the splitting field is obtained by adjoining just one root.  The Galois polynomials can be written in a finite notation and enumerated.  Beginning with $\mathbb{Q}$, formally adjoin a root of $p_n(x)$, the $n$th monic Galois polynomial, for each $n$ in turn.  If $p_n(x)$ factors over the field constructed so far, the factors can also be expressed in a finite notation; take the first irreducible factor.  The result is an explicit, synthetically constructed $\overline{\mathbb{Q}}$.
For comparison, let $\widetilde{\mathbb{Q}}$ be the algebraic closure of $\mathbb{Q}$ in $\mathbb{C}$.  Each element of it is computable:  Its digits can be generated by an algorithm, even with an explicit bound on its running time.  As we build $\overline{\mathbb{Q}}$, we can also build an isomorphism between $\widetilde{\mathbb{Q}}$.  We can do this by sending the formal root of $p_n(x)$ to its first root in $\mathbb{C}$, using some convenient ordering on $\mathbb{C}$.  Or we could just as well have used its last root, its second root if it has one, etc.  Composing these many different isomorphisms between $\overline{\mathbb{Q}}$ and $\widetilde{\mathbb{Q}}$ gives you many field automorphisms.

A: I don't know of any other elements, but I just want to point out that it's hard to really explicitly describe "elements of $\text{Gal}~\bar{\mathbb{Q}}/\mathbb{Q}$"; see e.g. this answer for a much clearer explanation than I could provide.

A: This is an analogous to the complex conjugation:
Let K be a local field, i.e. a finite extension of ℚp, for some p. Then its Galois group GK is finitely presented (See "Cohomology of number fields" of Jürgen Neukirch, Alexander Schmidt, and Kay Wingberg). Then its generators are in a sense explicit elements of Gℚ.

A: Dear "FC"
Could you please give me a precise reference which I can find a proof of "Artin theorem" which is, up to conjugation non-trivial element of finite order in absolute Galois group of Q, is complex conjugation. I could not find it in the paper you have shared. you wrote "This explains Leila Schneps' remark" which is not clear where you mean.


text:
Q: Similarities Between Trees I am working on a problem of Clustering of Results of Keyword Search on Graph. The results are in the form of Tree and I need to cluster those threes in group based on their similarities. Every node of the tree has two keys, one is the table name in the SQL database(semantic form) and second is the actual values of a record of that table(label).
I have used Zhang and Shasha, Klein, Demaine and RTED algorithms to find the Tree Edit Distance between the trees based on these two keys. All algorithms use no of deletion/insertion/relabel operation need to modify the trees to make them look same.
**I want some more matrices of to check the similarities between two trees e.g. Number of Nodes, average fan outs and more so that I can take a weighted average of these matrices to reach on a very good similarity matrix which takes into account both the semantic form of the tree (structure) and information contained in the tree(Labels at the node).
Can you please suggest me some way out or some literature which can be of some help?**
Can anyone suggest me some good paper

A: Even if you had the (pseudo-)distances between each pair of possible trees, this is actually not what you're after. You actually want to do unsupervised learning (clustering) in which you combine structure learning with parameter learning. The types of data structures you want to perform inference on are trees. To postulate "some metric space" for your clustering method, you introduce something that is not really necessary. To find the proper distance measure is a very difficult problem. I'll point in different directions in the following paragraphs and hope they can help you on your way.
The following is not the only way to represent this problem... You can see your problem as Bayesian inference over all possible trees with all possible values at the tree nodes. You probably would have some prior knowledge on what kind of trees are more likely than others and/or what kind of values are more likely than others. The Bayesian approach would allow you to define priors for both.
One article you might like to read is "Learning with Mixtures of Trees" by Meila and Jordan, 2000 (pdf). It explains that it is possible to use a decomposable prior: the tree structure has a different prior from the values/parameters (this of course means that there is some assumption of independence at play here).
I know you were hinting at heuristics such as the average fan-out etc., but you might find it worthwhile to check out these new applications of Bayesian inference. Note, for example that within nonparametric Bayesian method it is also feasible to reason about infinite trees, as done e.g. by Hutter, 2004 (pdf)!


text:
Q: what blog template/software is used Does anyone know what "blog template/software" is used in the blog http://laforge.gnumonks.org/weblog/?

A: It looks like Blosxom http://blosxom.sourceforge.net (based on the call to try and load pb_blosxom.gif)


text:
Q: Increment static variable value in XSLT 2.0 In my XSLT 2.0 file, I have to define a  static variable say counter and will be using this variable under a for-each() loop. I need to increment this static variable value by 10.
Says for each look, this variable value should be in incremented by 10,20,30,40.
Internally I will be assigning this variable to one of target schema element.
Can someone please hep or help me redirecting to relevant post.

A: It is not possible to increment a variable within a xsl:for-each loop, because xsl:for-each is not a loop1.
You could, however, use the position() function to increase a static variable incrementally, e.g.:
$staticVariable + 10 * position()

--
[1] Except: http://www.saxonica.com/documentation/index.html#!extensions/instructions/assign


text:
Q: BigQuery REGEXP_REPLACE I have a query that is defined as;
var query = " SELECT " +
            "REGEXP_REPLACE(TRIM(destination_value), r'[^\d]+', '') " +
            "FROM table1";
console.log(query,'query');
bigquery.query(query, function(err, rows) {
            if (err === null) {
                return resolve(rows);
            }else{
                return reject(err);
            }
            });

When I print the query it's returning
SELECT REGEXP_REPLACE(TRIM(destination_value), r'[d]+', '') FROM `table1`;

Why the special characters from my query is not there when I console it? Is there something I am doing wrong?
Thanks in advance.

A: You need to double escape the backslash in the regex metacharacter \d, because the first backslash will be consumed by JavaScript.  Try the following:
var query = "SELECT " +
            "REGEXP_REPLACE(TRIM(destination_value), r'[\^\\d]+', '') " +
            "FROM table1";

I would not expect that ^ would also need to be escaped, but I have done so since it seems this character is also causing a problem.  You can verify in the demo below that the query prints correctly.
Demo


text:
Q: Amazon Selling Partner API in Ruby returns MissingAuthenticationToken I've been having a heck of a time trying to access the new Amazon SP-API with the Ruby gem amz_sp_api
I've followed all the directions on creating an IAM user as well as getting what I believe are the correct tokens.. But I continue to get the following error:
"message": "Access to requested resource is denied.",
"code": "MissingAuthenticationToken"

This is the code I'm using:
require 'amz_sp_api'
require 'product-pricing-api-model'
require 'fulfillment-outbound-api-model'
require 'byebug'
require 'aws-sdk-core'

  AmzSpApi.configure do |config|
    config.refresh_token = 'long string'
    config.client_id = 'amzn1.application-oa2-client.123'
    config.client_secret = 'secret'
    config.credentials_provider = Aws::STS::Client.new(
        region: AmzSpApi::SpConfiguration::AWS_REGION_MAP['na'],
        access_key_id: 'key',
        secret_access_key: 'secret_key'
      ).assume_role(role_arn: 'arn:aws:iam::123:role/SellerAPIRole', role_session_name: SecureRandom.uuid)

    config.timeout = 20 # seconds
    config.debugging = true
  end

api_instance = AmzSpApi::FulfillmentOutboundApiModel::FbaOutboundApi.new
marketplace_id = 'ATVPDKIKX0DER'

begin
  result = api_instance.get_features(marketplace_id)
  pp result
rescue AmzSpApi::FulfillmentOutboundApiModel::ApiError => e
  puts "Exception when calling FbaOutboundApi->get_features: #{e}"
end

And I get in return
Exception when calling FbaOutboundApi->get_features: Error message: the server returns an error
HTTP status code: 403
Response headers: {"Date"=>"Wed, 12 May 2021 19:23:39 GMT", "Content-Type"=>"application/json", "Content-Length"=>"135", "Connection"=>"keep-alive", "x-amzn-RequestId"=>"123", "x-amzn-ErrorType"=>"MissingAuthenticationTokenException", "x-amz-apigw-id"=>"something"}
Response body: {
  "errors": [
    {
      "message": "Access to requested resource is denied.",
     "code": "MissingAuthenticationToken"
    }
  ]
}

Anyone else seeing this issue? I've gone through the extensive onboarding process of setting up a IAM user and all that mess.

A: this is because you need to pass the client to the api like this AmzSpApi::FulfillmentOutboundApiModel::FbaOutboundApi.new(AmzSpApi::SpApiClient.new) as per https://github.com/ericcj/amz_sp_api#getting-started


text:
Q: Ground state in $k$-space convert back to real space - spinless non-interacting fermionic system Say, you have the following spinless non-interacting fermionic (1D) Hamiltonian:
$$\hat H = -t \displaystyle \sum_{\langle i,j\rangle} (\hat c_i^+ \hat c_j + \hat c_j^+ \hat c_i)$$
Diagonalizing it (by going to k-space with Fourier) gives you:
$\hat H = -t\displaystyle \sum_{k} \epsilon_k c_k^+ c_k$, with $k = \frac{2\pi m}{N}$, $m$ is an integer, and $N$ total number of particles
The ground state for a fixed number of Fermions (satisfying Pauli exclusion principle) is:
$$|\psi^k_{GS}\rangle = \left(\displaystyle\prod_{|k|\leq k_F}c_k^+\right)|0\rangle = c_{k_F}^+\dotsc_1^+c_0^+|0, 0, 0, \dots, 0\rangle $$
Now, if we want to convert it back to real space (just to see how it looks like), we use the following Fourier transform:
$$c_k^+ = \frac{1}{\sqrt{N}} \sum_j e^{ikj}c_j^+ \qquad\text{and}\qquad c_j^+ = \frac{1}{\sqrt{N}} \sum_k e^{-ikj}c_k^+$$
$$|\psi^k_{GS}\rangle = \left(\frac{1}{\sqrt{N}} \sum_j e^{ik_{N-1}j}c_j^+\right)\dots\left(\frac{1}{\sqrt{N}} \sum_l e^{ik_1l}c_l^+\right)\left(\frac{1}{\sqrt{N}} \sum_m e^{ik_0m}c_m^+\right)|0, 0, 0,\dots, 0\rangle $$
How can we simplify this state?

A: *

*Relabeling in a systematic way ($j, l, m\rightarrow j_1, j_2, j_3...$):
$$
|\psi_{GS}^{k_F}\rangle = \left(\frac{1}{\sqrt{N}}\sum_{j_{N-1}}e^{ik_{N-1}j_{N-1}}c_{j_{N-1}}^\dagger\right)...\left(\frac{1}{\sqrt{N}}\sum_{j_{0}}e^{ik_{0}j_{0}}c_{j_{0}}^\dagger\right)|0,0,...,0\rangle
$$

*Moving all the exponents into one

*Using the fact that one cannot create two electrons on the same site.

Remark however that there are already problems with notation - first of all, the ground state wave function label - why $k$? Secondly, the number of the factors in the product should be determined by by $k_F$, not by the total number of sites, $N$.


text:
Q: Read Json file with Scala/Spark I am trying to read a json, example:
{
  "id1": {
    "a": "7",
    "b": "3",
    "c": "10",
    "d": "10",
    "e": "15",
    "f": "11",
    "g": "2",
    "h": "7",
    "i": "5",
    "j": "14"
  },
  "id2": {
    "a": "3",
    "b": "7",
    "c": "12",
    "d": "4",
    "e": "10",
    "f": "4",
    "g": "13",
    "h": "4",
    "i": "1",
    "j": "13"
  },
  "id3": {
    "a": "10",
    "b": "6",
    "c": "1",
    "d": "1",
    "e": "13",
    "f": "12",
    "g": "9",
    "h": "6",
    "i": "7",
    "j": "4"
  }
}

when I process it with spark.read.json ("file.json") it returns a single record with this format:
+-----------------------------------+---------------------------------------+---------------------------------+
|id1                                |id2                                    |id3                              |
+-----------------------------------+---------------------------------------+---------------------------------+
|{7, 3, 10, 10, 15, 11, 2, 7, 5, 14}|{322539, 7, 12, 4, 10, 4, 13, 4, 1, 13}|{10, 6, 1, 1, 13, 12, 9, 6, 7, 4}|
+-----------------------------------+---------------------------------------+---------------------------------+

I would like the result to be something like this when processing the file:
+-----+------+------+------+------+------+------+------+------+------+-------+
| id  | col1 | col2 | col3 | col4 | col5 | col6 | col7 | col8 | col9 | col10 |
+-----+------+------+------+------+------+------+------+------+------+-------+
| id1 |  7   |  3   |  10  |  10  |  15  |  11  |  2   |  7   |  5   |  14   |
+-----+------+------+------+------+------+------+------+------+------+-------+
| id2 |  3   |  7   |  12  |  4   |  10  |  4   |  13  |  4   |  1   |  13   |
+-----+------+------+------+------+------+------+------+------+------+-------+
| id3 |  10  |  6   |  1   |  1   |  13  |  12  |  9   |  6   |  7   |  4    |
+-----+------+------+------+------+------+------+------+------+------+-------+

some simple and fast way?
thanks

A: Are you able to modify your input JSON file ? If so, making it an array of JS Objects would do the job with spark.read.json() :
[
    {
      "id": "id1",
      "a": "7",
      "b": "3",
      "c": "10",
      "d": "10",
      "e": "15",
      "f": "11",
      "g": "2",
      "h": "7",
      "i": "5",
      "j": "14"
    },
    ...
]


text:
Q: how to handle text and image input together in neural network algorithm I am working on neural network machine learning algorithm . i wanted to know input data formats applicable in NN feature list. is there possibility to handle text & image together as a input in CNN or using any other machine learning algorithm. how will i make sense of output.

A: Yes, it is possible to handle text and image data together.
The feature vectors created using each text data-point or image data-point can be combined together and used in parallel as a new big feature vector.
After vectorization of text data, there is not much difference between the pixel vectors and the text vectors.
Specifically in case of CNN, for the final model, a combined neural network can be created that has a convolutional branch one on side while the vectorized words branch on the other side.

Image Credits: This image from Christopher Bonnett's article
For more details, please refer to above mentioned article. It has explained how e-commerce products can be classified into various category hierarchies using both image and text data.


text:
Q: React & Reselect selector claims state is the same after update I am implementing Reselect in my project and have a little confusion on how to properly use it. After following multiple tutorials and articles about how to use reselect, I have used same patterns and still somethings dont work as expected.
My selector:
const getBaseInfo = (state) => state.Info;
const getResources = (state) => state.Resources;

export const ASelector = createSelector(
  [getBaseInfo, getResources],
  (items, resources) => {
    let result = {};
    for(const item in items) {
      console.log(item);
      result[item] = _.pick(items[item], ['Title', 'Type', 'Beginning', 'minAmount', 'Address'])
    }
    for(const item in resources) {
      console.log(item);
      result[item] = {...result[item], firstImage: resources[item].firstImage}
    }
    return result;
  }
);

mapStateToProps component:
function mapStateToProps(state) {
  console.log(state);
  return {
    gridInfo: ASelector(state)
  }
}

Now at first my initial state is:
state = { Info: {}, Resources: {} }

My Reducer:
const Info = ArrayToDictionary.Info(action.payload.data.Info);
  const Resources = ArrayToDictionary.Resources(action.payload.data.Info);
  let resourcesKeys = Object.keys(Resources);
  let infoKeys = Object.keys(Info);
  let temp = { ...state };
  let newInfo;

  for (let item of infoKeys) {
    newInfo = {
      Title: Info[item].Title,
      Type: Info[item].Type,
      BeginningOfInvesting: Info[item].BeginningOfInvesting,
      DateOfEstablishment: Info[item].DateOfEstablishment,
      pricePerUnit: Info[item].PricePerUnit,
      minUnits: Info[item].MinUnits,
      publicAmount: Info[item].PublicAmount,
      minInvestmentAmount: Info[item].MinInvestmentAmount,
      EinNumber: Info[item].EinNumber,
      Address: Info[item].Address,
      Status: Info[item].Status,
      Lat: Info[item].Lat,
      Lng: Info[item].Lng,
      CurrencySymbol: Info[item].CurrencySymbol,
      Publicity: Info[item].Publicity
    }
    temp.Info[item] = { ...temp.Info[item], ...newInfo }
  }
  for (let item of resourcesKeys) {
    temp.Resources[item] = { ...temp.Resources[item], ...Resources[item] }
  }
  return temp;

As a component renders with the initial state, I have an action pulling data from api and saving it accordingly into the state inside reducers.
Now my state is changed, but after debugging a little into reselects code, I found in the comparison function that the old and new states are the same.
Suddenly my "old" state became already populated with the newState data and it of course failing the comparison as they became the same.
Is there anything wrong with my selectors?
I have really tried to use it as the documentation states, but still cant understand how to solve my little issue.
Thank you very much for reading and helping!

A: It looks like the temp.Info[item] and temp.Resources[item] lines are mutating the existing state.  You've made a shallow copy of the top level, but aren't correctly copying the second level.  See the Immutable Update Patterns page in the Redux docs for an explanation of why this is an issue and what to do instead.
You might want to try using the immer library to simplify your immutable update logic.  Also, our new redux-starter-kit library uses Immer internally.


text:
Q: Generate file of given size For test purposes I'd like to get file of given size filled with random data.
So I have two questions:

*

*How to efficiently generate file of given size in Android?

*

*is RandomAccessFile sufficient method? (see Create file with given size in Java)

*How to efficiently fill the file with random data ?

*

*What is the best source (ideally compatible back to v7) of random bytes?

*Is it necessary, because the file would contain data previously written in allocated harddisk space?

A: You just create the file and fill it with the size you want. You don't 'set the size'. If you create a file and put 1 kilobytes of stuff into it the file will be 1 kilobyte (*slightly larger actually).
So just create a file, and use whatever file write routine to output bytes which you can create with (byte)(random()*510 - 255) in a loop for however many bytes large you want the file to be. Since this is java and you may want to use print to output to the file, you have to use (char)(Math.random()*510 - 255) otherwise it will print the string "65" instead of "A"


text:
Q: Why when click on download link there are continuation packets when the save dialog is open (before click on start save) my machine is Ubuntu.
When i click on some download link i see continuation packets, why is that ? why there are continuation packets before i start download the file

A: What do you mean by fluent? Are you talking about the continuation packets? Your browser sends those to keep the connection to the web server from timing out before you decide what to do with the Save window. If those packets were not sent, then the web server might give up waiting before you had a chance to tell your browser what to do with the file.


text:
Q: Objective C: How to check object type without a lot of if statements I am trying to set my text string to a URL. The following code works, but I feel like I can refactor it to make it look neater.
NSString *text = @"";

id json = [NSJSONSerialization JSONObjectWithData:[data dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

if ([json isKindOfClass:[NSDictionary class]]) {

   id data = json[@"data"];

    if ([data isKindOfClass:[NSDictionary class]]) {
       id value = data[@"value"];

       if ([value isKindOfClass:[NSArray class]]) {
            id url = [value valueForKey:@"url"];

          if ([url isKindOfClass:[NSString class]]) {
             text  = url;
         }
       }
     }
   }

So far it has the whole "mountain of doom" going on and I want to know how can I check if the object type is correct without using so many if statements. Any tips or suggestions are appreciated.
Edit: This is the lite version of my code, but the concept is the same.

A: In my opinion, there are 2 ways to make it look neater and ignore if-else-nesting-hell.

*

*Using return.
NSString *text = @"";

id json = [NSJSONSerialization JSONObjectWithData:[data dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];

if (![json isKindOfClass:[NSDictionary class]]) {
  return;
}
id data = json[@"data"];

if (![data isKindOfClass:[NSDictionary class]]) {
  return;
}
id value = data[@"value"];

if (![value isKindOfClass:[NSArray class]]) {
  return;
}
id url = [value valueForKey:@"url"];

if (![url isKindOfClass:[NSString class]]) {
  return;
}
text  = url;

*Create a generic method which checks kind of class and return a safe value
- (id)safeValueFromObject:(id)object forKey:(NSString *)key class:(Class)valueClass {
  if (![object respondsToSelector:@selector(valueForKey:)]) {
    return [[valueClass alloc] init];
  }

  id result = [object valueForKey:key];
  return [result isKindOfClass:valueClass] ? result : [[valueClass alloc] init];
}

Use
NSString *text = @"";

id json = [NSJSONSerialization JSONObjectWithData:[data dataUsingEncoding:NSUTF8StringEncoding] options:0 error:nil];
id data = [self safeValueFromObject:json forKey:@"data" class:NSDictionary.class];
id value = [self safeValueFromObject:data forKey:@"value" class:NSArray.class];
id url = [self safeValueFromObject:value forKey:@"url" class:NSString.class];
text  = url;


text:
Q: How do Vectors and Matrices work into computer graphics, such as Matrix Rotations? I have been trying to wrap my head around how my Linear and Vector Algerbra knowledge fits in with Computer Graphics. Particulary in the language C#
The knowledge I mean is:
Points
Vectors
Matrices
Matrix multiplaction - Rotations, Skews, etc..
Heres my goal: Create a simple box, and apply a rotation, translation, and skew to it via matrix multiplication. Afterwards, start messing around with the camera. I wish to do this all myself, only using the functions that actually take in the data and draw it. I wish to create all the logical stuff inbetween.
Heres what i've got so far:
My custom Vector3 class, which holds
-an X, Y, and Z variable (floats)
-Several static matrices (as 2x2 2d float arrays?) that hold ZERO and TRANSLATION matrices (for 2x2 and 3x3)
-Methods
 1. Rotate(float inAngle) - Creates a rotation matrix and multiplies the xyz by it.
 2. Translate(inx,iny,inz) - Adds the ins to the member variables
 3. etc...
When complete, i translate the vector back into a C# Vector3 class and pass it to a drawing class, such as DrawPrimitiveShapes which would draw Lines.
The box class is like this:
4 Vector3's, UpperLeftX, UpperRightX, LowerLeftX, LowerRightX
a Draw class which uses the 4 points to then render lines to each one
My confusion comes at this:
How do I rotate this box? Am I on the right track by using 4 vector3's for the box?
Do I just rotate all four vector3's by the angle and be done with it? How does a texture get rotated if it's got all this texture data in the middle?

A: The way I learned is by using the upper level built in Xna methods and using 'Reflector' to see inside those methods to see how they work.
To rotate the box, each of the four vertices needs to be transformed from where they were to: a number of degrees about a particular axis.
In Xna 2d the axis is always the Z axis and that axis always runs through the worlds origin, the top left corner of the screen in xna.
So to rotate your four rectangle vertices in xna, you would do something like this:
foreach(Vector2 vert in vertices)
{
   vert = Vector2.Transform(vert, Matrix.CreateRotationZ(someRadians));
}

This gets the vertices to rotate (orbit) the top left corner of the screen.
In order to have the box rotate in place, you would first move the box to the top left corner of the screen , rotate it a bit, then move it back. All this happens in a single frame so all the user sees is the rectangle rotating in place. There are many ways to do that in code but here is my favorite:
// assumes you know the center of the rectangle's x & y as a Vector2 'center'
foreach(Vector2 vert in vertices)
    {
       vert = Vector2.Transform(vert - center, Matrix.CreateRotationZ(someRadians)) + center;
    }

Now if you were to reflect the "Matrix.CreateRotationZ" method, or the "Vector2.Transform" method, you would see the lines of code MS used to make that work. By working through them, you can learn the math behind more efficiently without so much trial and error.


text:
Q: about the independence of the angle at $\infty$ of the Schwarz-Christoffel integral In Stein's complex analysis, he said about the integral $$S(z)=\int_{0}^{z} \frac{d\zeta}{(\zeta-A_1)^{b_1}\cdot\cdot\cdot(\zeta-A_n)^{b_n}}$$(the Schwarz-Christoffel integral) where $A_1<A_2<\cdot\cdot\cdot<A_n$ are n distince points on the real axis arranged in increasing order. And if $\Sigma_{k=1}^{n}b_k>1$, then Cauchy's theorem implies $\lim_{r\to\infty}S(re^{i\theta})$ exists and is independent of the angle $\theta$, $0<\theta<\pi$.
Can anyone tell me why this integral is independent of $\theta$? He seems to have used Cauchy's theorem on a simply connected set which is any integral of a same holomorphic function on the set from 2 points would be the same regardless of the path between the two points. But I don't understand how it is used here. Thanks

A: You can compare two different angles $\theta_1,\theta_2$ in the following way:  Cauchy's theorem shows that
$S(re^{i\theta_2}) = S(re^{i\theta_1}) + \int_\gamma f(z) dz$
where $f(z)$ is the Schwarz-Christoffel integrand and $\gamma$ is a semi-circular arc of radius $r$ from $re^{i\theta_1}$ to $re^{i\theta_2}$. If you now do the usual arclength integral estimate you can show as $r$ tends to $\infty$, the two values become arbitrarily close.