text:
Q: Did eastern PKUFFT algorithm beat FFTW3 (Fastest FFT on the west) 20 fold? I wonder if PKUFFT is Chinese algorithm/library and is it really better than FFTW, MKL?
Edit: I will elaborate. My personal programmers interest is in fast parallel algorithms like FFTW3, which was my favorite until I stumbled upon chinese claim of superior run with PKUFFT. It is on google, if you search for FFTW3, Intel MKL, GPU and things. I don't know anything about this library, but I would be very interested to learn.
I can guess PKU stands for Peking Univ. There is nothing on web except presentation and mentioning of some commonly available hardware (GPU, infiniband, etc.). Everything, including compilers was available for years. The improvement of 2000% is significant. The news are 1 year old. But no details about algorithm itself.
It will be interesting to know if there is genuine discovery in algebra, or just technical effect with unfair advantage of knowing specific platform better than competing teams.

A: It looks like the benefit comes from a better use of underlying architecture (and the improvement is in the 20-25x range). They figured out a better way to, in general, take advantage of parallel GPU/CPU architectures, reducing the overhead for the parallelized algorithm.
This is not an improvement in the underlying algorithm for FFT. This is an improvement in the general application of heavy math algorithms to many-core/multi-core architectures.
The technique continues to improve, with innovative optimizations. See http://www.springer.com/us/book/9783642164040 for more info


text:
Q: best practice to pass object between a grid and edit page in Angular 8+ so i have a data grid with a typical edit button. a very typical scenario where this a create-edit-account component that will also be used to edit and existing component.
so when i click edit on a grid i navigate to create-edit-account component to use it for edit purposes as well.
upon clicking edit i navigate like this
 edit(account: BankAccount) {
this.router.navigateByUrl('/create-edit-account/' + account.id);
 }

but at the time i clicked edit i have a populated account object i want to pass it to the create-edit-account component.
Question 1 what is the best practice in passing object while using parameterized routes in Angular 8+
Question 2 how we tell a component that it is being used for edit or add. i learned that if i pass "0" in the route's id param we can consider it is being used as "new" . but is there a better approach ?
i also have an ngrx store implemented . so  Question 3 would you recommend using an action dispatch with something called "account-updating" and passing in the object as an action param and subscribing it in the create-edit-account component and later dispatching "account-updated" action?

A: We should be utilizing power of ngrx where its actually required. I mean where there is sharing of data being used my multiple components at same time in single view. Those kind of scenarios.
Your particular case is simple
Create a service, before navigation set this data in a property in that service, and in on init of your create-edit component get that data. In this data, you can set where creating account or editing account flag in same data object.
I you want it to retain data on refresh use localStorage or sessionStorage as per scenario.

A: Q1: you can use resolvers, they can fetch the data and pass it together with ActivatedRoute.
Q2: You should have an independent url for the edit mode, then the component can detect its state and switch between show / edit, also users can share desired page to show or to edit the component.
As an option you can have internal state in the component and a button that switches it to be show / edit. But in this case users always have to click the button.
Q3: For the thing you describe you should use ngrx effects. Then an effects listens to update request and performs it. Once the request has been finished it dispatches an action to set the updated entity in the store.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I display the content of React Quill without the html markup? I managed to get my Quill working, but now I wanted to make a nice splitscreen as we have on this forum but one thing I haven't been able to figure out is how to convert the input of Quill to nice text on the preview side.
I'm able to display the text but it still has all the html tags which of course I don't want.
So this is my Quill setup so far:

export default class AddSpark extends Component {
  constructor(props) {
    super(props);

    this.onChange = this.onChange.bind(this);

    this.state ={
      content: '',
    };
  }

  onChange(html) {
    this.setState ({ content: html });
      console.log(html)
    }

  render() {
    return (

      <Col xs={12} md={6}>
        <form ref={(input) => this.sparkForm = input} onSubmit={(e) => this.createSpark(e)}>

            <ControlLabel>Select your city</ControlLabel>
            <select id="formControlsCity" placeholder="Choose your city" onChange={this.onChange} className="form-control" onClick={ moreOptions } ref={(input) => this.city = input}>
              <option value="select">Choose your city</option>
              <option value="Beijing">Beijing</option>
              <option value="Shanghai">Shanghai</option>
              <option value="Chengdu & Chongqing">Chengdu & Chongqing</option>
            </select>

            <ControlLabel>Select your person</ControlLabel>
            <select id="formControlsPerson" placeholder="Choose your person" className="form-control" ref={(input) => this.person = input}>
              <option value="select">First select your city</option>
            </select>

            <ControlLabel>Select your location</ControlLabel>
            <select id="formControlsLocation" placeholder="Choose your location" className="form-control" ref={(input) => this.location = input}>
              <option value="select">First select your city</option>
            </select>

            <ControlLabel>Title</ControlLabel>
            <input type="text" label="Title" placeholder="Enter your title" className="form-control" ref={(input) => this.title = input}/>

            <ControlLabel>Content</ControlLabel>

                <ReactQuill
                  ref='editor'
                  onChange={this.onChange}
                />

          <Button type="submit">Submit</Button>
        </form>
      </Col>
      <Col xs={12} md={6}>

Preview

        {this.state.content}
      </Col>

  )}
}

At the moment I get this:

Any help is highly appreciated!

A: You need html-react-parser
import Parser from 'html-react-parser';

...     // in your render
<ReactQuill
    ...
    value={code}
    onChange={this.previewCode}
/>
...
{Parser(code)}

A: i used it like this in React.js..
To display quil content in a div i use class "ql-editor" because through this our div can use the quil default classes...works..
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";

const ReactMarkdown = require("react-markdown/with-html"); //for displaying html

function editorContent() {

        <ReactMarkdown escapeHtml={false} source={quilGeneratedHtml} />

}

A: The simplest way is to use the same react-quill component with editing disabled. This method doesn't need you to install any extra package. You can do it by passing a prop readOnly whose value is set to true (By default it is false)
Here is the code for the component which you can use to preview side:
<ReactQuill
   value={this.state.content}
   readOnly={true}
   theme={"bubble"}
/>

This is how it will look like:

Note: ReactQuill comes with two inbuilt themes (bubble and snow).
Here is how it looks in the snow theme. It has a toolbar at the top:

And here is how it looks in bubble theme.

You should use the "bubble" theme by passing the string "bubble" in the theme prop to display your editor content. This is because it does not have a toolbar at the top like the "snow" theme.
In order to use the bubble theme, you'll also have to import a CSS stylesheet for this specific theme as follow:*
import 'react-quill/dist/quill.bubble.css'

A: After doing some research I was able to find the answer:
To display the content of Quill in the preview section without the html tags I used this code:

A: onChange(content, delta, source, editor) {
  const text = editor.getText(content);
  this.setState ({ content: text });
  console.log(text)
}

A: Here's the docs link: https://github.com/zenoamaro/react-quill#the-unprivileged-editor
simple to implement and getText out of quill editor
// define function to get text,
// here inpText is defined in your constructor, or any global variable
onChangeText = () => {
    const editor = this.reactQuillRef.getEditor();
    const unprivilegedEditor = this.reactQuillRef.makeUnprivilegedEditor(editor);
    // You may now use the unprivilegedEditor proxy methods
    this.inpText = unprivilegedEditor.getText();
        console.log("unprivilegedEditor.getText()", unprivilegedEditor.getText());
    }

    // on submit, you can set state with that text binded in this.inpText
    this.setState({text: this.inputText})
}

// define react quill component
<ReactQuill value={this.state.text} onChange={this.onChangeText} ref={(el) => { this.reactQuillRef = el }} />

Good Luck...

A: Using 'html-react-parser' worked for me

A: Save the html output from quill editor. Then render it as an innerHTML on a div. Give class="ql-editor" to the div and the html will be formatted as we see it in the editor. No need to instantiate editor context. Just import quill's css file.
Vue example:
import '@vueup/vue-quill/dist/vue-quill.snow.css';

A: To preview HTML in your web page in REACT then there are 2 options you have,

*

*using dependency html-react-parser
Follow below steps,
Step1:
Install dependency using below command,
npm i html-react-parser
If you are using yarn then use below command,
yarn add html-react-parser
Step 2:
const parse = require('html-react-parser');
parse(`<div>${this.state.content}</div>`);

*Use below code to set the editor contents using below code,

 Using **dangerouslySetInnerHTML**, but this I will not recommend.
2> WE can try using a npm package for react such as
**html-react-parser**. Try it out, as its easy to use.


text:
Q: Contain content of 50% width horiz divs to an overall wrapper width (1200px) I want to achieve an increasingly popular design - two 50% width divs aligned horizontally (.tile), but their content across both divs restricted to an overall max width (equal to the page wrapper for the rest of the site e.g. 1200px). I have them floated left to achieve horizontal alignment, each with contrasting colours. Picture a centered 'overlay' wrapper across the 2 divs. The code below hopefully explains my setup:
CSS
.full-width-row {
    width: 100%; // 100% of entire page so child divs bg color will stretch
    padding: 0;
    margin: 0;
    overflow: hidden;
    height: auto;
    position: relative;
}
.tile {
    width: 50%;
    float: left;
    height: 100%;
    margin-bottom: -99999px;
    padding-bottom: 99999px // hack to fill height of parent
}
.tile-content {
    padding: 5%;
}
.left {
    background: #FFC15E;
}
.right {
    background: #3E7F72;
}

HTML

                    //CONTENT LEFT

                    //CONTENT RIGHT

The parent here (.full-width-row) is 100% of the whole window, so the bg colours of the 2 child divs will stretch the whole page. It's the content inside these children that I want to behave within a maximum, defined width (equal to 1200px). Has anyone built a similar layout or has any suggestions on how to achieve this?
I guess the right-hand side div will never be a problem as it will always be in the 1200px wrapper space, but the left hand will keep moving left on bigger screens.

A: I am not completly sure what you want, but if it's about centering the outer container, you can simply apply margin: 0 auto to it. i did that in the snippet below and added max-width: 500px to make it visible immediately inside the snippet window (you can of course set that to 1200px).
Note: The centering with margin: 0 auto only works if the element has a position setting, which was the case in your example.)

html, body {
margin: 0;
}
.full-width-row {
  width: 100%; // 100% of entire page so child divs bg color will stretch
  padding: 0;
  margin: 0;
  overflow: hidden;
  height: auto;
  position: relative;
  max-width: 500px;
  margin: 0 auto;
}

.tile {
  width: 50%;
  float: left;
  height: 100%;
  margin-bottom: -99999px;
  padding-bottom: 99999px;
  background: #ddd;
}

.tile-content {
  padding: 5%;
}

.left {
  background: #FFC15E;
}

.right {
  background: #3E7F72;
}

      //CONTENT LEFT

      //CONTENT RIGHT

A: This was a tricky one to explain but thanks for everyone's attempts. My solution was after all fairly straight forward. To the left hand side content class I also added a new class 'restrict'
.restrict {
    max-width: 600px;
    float: right;
}

This pushed the left side against a 'barrier of 600px from center (half the page wrapper), whilst keeping the colour of the parent 50% div to stretch the whole page. Ironically now that I've seen it I think I might just center both content div's anyway


text:
Q: JPA / JPQL: find root elements of a unidirectional tree JPA / JPQL: find root elements of a unidirectional tree.
I need some help to write a named query for the following problem.
I have the following (simplified) definition of an entity (TNode) and can save/read it via JPA.
The entity is unidirectional, so childs don't know the parent!
Now I try to write a named query to get all root elements.
I use JPA 2.0 (Hibernate) and found some hints in the internet, that unidirectional links are supported.
A simple JUnit (4) is also attached, to create two trees and save it into the db. I removed all the asserts.
If I run the Junit, the table looks as expected:
ID  NAME    CHILDS_ID
1   A1  (null)
2   A11 1
3   B1  (null)
4   B11 3

I added @JoinColumn to have the self reference in the same table. And the with simple SQL the problem
would be easy (WHERE childs_id = null). But how must I write this in JPQL?
Thanks for the answers.
Uwe
@Entity
@Table(name = "TNode")
@NamedQueries({ @NamedQuery(name = "getRootNodes", query = "FROM TNode tnode ......."), })
public class TNode implements JPAObject {
    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @OneToMany(cascade = { CascadeType.REFRESH, CascadeType.MERGE, CascadeType.REMOVE })
    @JoinColumn
    private Set<TNode> childs = new HashSet<TNode>();

    // JPA only
    private TNode() {
    }

    public TNode(String name) {
    this.name = name;
    }

    public void add(TNode tNode) {
    childs.add(tNode);
    }

    @Override
    public Integer getId() {
    return id;
    }

    @Override
    public String getName() {
    return name;
    }
}

Here the simplified Junit
@RunWith(Arquillian.class)
public class TNodeTest {
    @Deployment
    public static Archive<?> createTestArchive() {
    //@formatter:off
    Archive<?> archive = ShrinkWrap.create(WebArchive.class, "test.war")
        .addPackages(true, DummyInterfaceForTest.class.getPackage())
        .addAsLibraries(FindMavenArtifact.find("com.thoughtworks.xstream:xstream:1.4.2"))
        .addAsLibraries(FindMavenArtifact.find("xmlpull:xmlpull:1.1.3.1"))
        .addAsResource("META-INF/persistence.xml", "META-INF/persistence.xml")
        .addAsResource("import.sql", "import.sql")
        .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml");
    //@formatter:on
    System.out.println(archive.toString(true));
    return archive;
    }

    @Inject
    @DAO.DAOType(type = DAO.MODE.STATELESS)
    private DAO<JPAObject> dao;

    @Test
    public void testMutipleRoots() throws Exception {
    TNode root;

    root = new TNode("A1");
    root.add(new TNode("A11"));

    dao.saveOrUpdate(root);

    root = new TNode("B1");
    root.add(new TNode("B11"));

    dao.saveOrUpdate(root);
    }
}

A: I found a solution by myself after reading a little bit about JPQL.
The (Sub-) Query solves the problem:
query = "SELECT node FROM TNode node WHERE node.id NOT IN (SELECT DISTINCT child.id FROM TNode node, IN(node.childs) child)"), })


text:
Q: Unable to createand append divs and spans dynamically I'm writing a HTML code that has a div say y and this is in my HTML body and there is a button. when user clicks on this button, I want to do the below.

*

*Create another div (with class as smallBar)

*Inside this div, I want to create 3 spans.

*Add this(total smallBar) content to div y.

Here is my current code.
HTML

<input type="button" onclick="createDiv()" value="click me" />

JS
function createDiv() {
  var div = document.createElement("div");
  div.className = "smallBar";
  var span1 = document.createElement("span");
  span1.className = "span1";
  var span2 = document.createElement("span");
  span2.setAttribute("class", "span1");
  var span3 = document.createElement("span");
  span3.setAttribute("class", "span1");

  div.appendChild(span1);
  div.appendChild(span2);
  div.appendChild(span3);

  document.getElementById("y").innerHTML = div;
}

here when I click on the button, Instead of creating a div it is giving me message as [object HTMLDivElement]. please let me know where am I going wrong and how can I fix this.
Here is my fiddle https://jsfiddle.net/d9hg0vkk/
Thanks

A: You are using innerHTML instead you need to use appendChild()

function createDiv() {
  var div = document.createElement("div");
  div.className = "smallBar";
  var span1 = document.createElement("span");
  span1.className = "span1";
  span1.innerHTML="Spam1";
  var span2 = document.createElement("span");
  span2.setAttribute("class", "span2");
  span2.innerHTML="Span2";
  var span3 = document.createElement("span");
  span3.setAttribute("class", "span3");
  span3.innerHTML="Span3";

  div.appendChild(span1);
  div.appendChild(span2);
  div.appendChild(span3);

  document.getElementById("y").appendChild(div);
}

<input type="button" onclick="createDiv()" value="click me" />

P.S- InnerHTML gives/sets a String, representing the HTML content of an element. When you do document.getElementById("y").innerHTML = div, it takes it as a String and not as a Object and thus you see [object HTMLDivElement] in the div. Instead you can do it with innerHTML like this document.getElementById("y").innerHTML = div.outerHTML;
Read More about innerHTML

A: Should be
  document.getElementById("y").innerHTML = div.innerHTML;

You are assigning div element directly. Where as you should get it's innerHTML
https://jsfiddle.net/d9hg0vkk/2/
Once you click the button and inspect element and see. You see span's inside of your target div.

function createDiv() {
  var div = document.createElement("div");
  div.className = "smallBar";
  var span1 = document.createElement("span");
  span1.className = "span1";
  span1.textContent= "span1"
  var span2 = document.createElement("span");
  span2.setAttribute("class", "span1");
  span2.textContent= "span2"
  var span3 = document.createElement("span");
  span3.setAttribute("class", "span1");
  span3.textContent= "span3"

  div.appendChild(span1);
  div.appendChild(span2);
  div.appendChild(span3);

  document.getElementById("y").innerHTML = div.innerHTML;
}

<input type="button" onclick="createDiv()" value="click me" />

Or if you want to append whole div, you can try using appendChild as others pointed
document.getElementById("y").appendChild(div);

A: If you want to use innerHTML and not appendChild which appends the div every time you click on the button, you have to use
document.getElementById("y").innerHTML = div.outerHTML;

instead of
document.getElementById("y").innerHTML = div;

Because 'div' is HTMLDivElement Object and innerHTML accepts only string. By using outerHTML you retain the 'smallBar' Div as well. if you use
 document.getElementById("y").innerHTML = div.innerHTML;

you'll see only 3 spans inside div 'y' and not 'smallBar' Div.

A: Another option to Sanchits .appendChild() is .insertAdjacentElement()

function createDiv() {
  var div = document.createElement("div");
  div.className = "smallBar";
  div.textContent = "div";
  var span1 = document.createElement("span");
  span1.className = "span1";
  span1.textContent = "span1";
  var span2 = document.createElement("span");
  span2.setAttribute("class", "span1");
  span2.textContent = "span2";
  var span3 = document.createElement("span");
  span3.setAttribute("class", "span1");
  span3.textContent = "span3";

  div.appendChild(span1);
  div.appendChild(span2);
  div.appendChild(span3);

  document.getElementById("y").insertAdjacentElement("beforeend", div);
}

<input type="button" onclick="createDiv()" value="click me" />

A: Are you trying like this?
document.getElementById("y").innerHTML = "
ABC
";

Link: https://jsfiddle.net/d9hg0vkk/1/


text:
Q: iPhone and Android - Appcelerator Titanium complex view with labels stacking We need to design a page like this with a tap on the blue username redirecting to the users page. How is this possible in Ti. The data is dynamic from the webservices and the text may increase also..
Any help is appreciated
http://i.stack.imgur.com/iBzBx.png

A: cannot be done without a lot of crazy calculations to determine the length of the name field.
i would suggest change the UI if you want to use appcelerator

A: you're first try should be to set the label.height='auto'. the second way would be to calculate the height
var charsPerLine = 20; //depends on font-properties
var tmp = Math.round(text.length/charsPerLine);
label.height = tmp;

hope it helps a little bit


text:
Q: Plot a Floquet solution to Mathieu equation In wikipedia https://en.wikipedia.org/wiki/Mathieu_function#Floquet_solution
I want to know how the Floquet solution is plotted.
One way I am thinking is to write Floquet solution in terms of the elemental solutions: Mathieu sin and cos, so that I can call these two functions built in software like Mathmatica. But I don't How to write Floquet solution in terms of Mathieu sin and cos.

A: I'm not quite sure what's going on in that plot.  The basics of the Floquet solution are this.  You start off with the first order differential equation system for the fundamental matrix
$$
\phi'(t) = A(t) \phi(t), \ \phi(0) = I
$$
where in this case
$$A(t) = \pmatrix{ 0 & 1\cr -a + 2 q \cos(2t) & 0\cr} $$
which is periodic with period $\pi$.
In this case that fundamental matrix is
$$ \phi(t) = \pmatrix{ C(a,q,t) & S(a,q,t)\cr C'(a,q,t) & S'(a,q,t)\cr} $$
where $C$ and $S$ are the Mathieu cosine and sine functions, $C'$ and $S'$ their derivatives with respect to $t$.
Now we let $B$ be a matrix such that $e^{\pi B} = \phi(\pi)$.  In this case
we can take $$ B = \pmatrix{ i & .100721974647390\cr 0.0983648541461455 & i\cr}$$
Floquet says that the matrix function $P(t) = \phi(t) e^{-tB}$ is periodic.
If $v$ is an eigenvctor of $B$ for eigenvalue $\lambda$, then $w(t) = \phi(t) v$ is a solution of $w'(t) = A(t) w(t)$ with $w(\pi) = e^{\pi \lambda} v = e^{\pi \lambda} w(0)$.  In our case $B$ has real eigenvectors
$$ \eqalign{\pmatrix{0.711280416113229\cr 0.702908365047530} &\ \text{for eigenvalue}\ 0.0995364372755138 + i\cr
\pmatrix{0.711280416113229\cr -0.702908365047530} &\ \text{for eigenvalue}\ -0.0995364372755138 + i\cr}$$
The plots of the first entry of $w(t)$ (corresponding to solutions of the Mathieu equation) for these eigenvectors look like this (the first one in red, the second in green):

The first describes a solution that, after one period ($t=\pi$) has changed sign (because of the imaginary part $i$ in the eigenvalue) and grown in amplitude by a factor $e^{0.0995364372755138 \pi} = 1.36711535556321$.
The second also changes sign, but has decreased in amplitude: in fact it is the time-reversal of the first.


text:
Q: NHIbernate refreshing a collection I know this has been asked, but I can not solve this problem.
Lets say you have an nhibernate object that has a collection.
Problem is, if some object in the collection is updated in the database by a different user (i manually modifiy the database fot testing purposes), I can't seem to find a way to make nhibernate refresh the collection value.
I hace tried refresh, evict, Loading againg... Only closing the session and creating a new one works. But I find this solution problematic and, how hard can it be to tell nhibernate "dude, refresh the items in the collection"?
But anyhow I can't get it working.
Thanks a lot

A: This isn't actually supposed to work, that's why it doesn't.
NHibernate uses the a session level cache by default, to optimise reads and track modifications.
It sounds like you're not using a correct unit of work around your data access as your sessions should be scoped down and used only when you need them.
If this is part of a web app, it's recommended you follow a "session-per-request" approach.
If you really wanted this to work, you could probably evict entity and it's children from the session, forcing a re-fetch, but this is nasty and I'd really not advise it.

A: Having gone to the trouble of trying to evict, and even considered opening and closing sessions. It sounds as though there is enough headspace in your code to consider doing a filtered get, i.e. get all items of the collection type where the parent id is that of your parent object. You might have to extend your repository or dao, depending on how you are working with NH, but as others have said, it is hard to be more specific without an example. Main point is that you get the child objects in a query for that type, filtered by the parent id.
This would be a fresh get, so you'd get any new or altered objects that were created by some other process, and then you could set that collection as the collection in your parent object. NH should get over this when you try to save as it can make assumptions about your objects and save or update as appropriate. This could be of use to you if there is likely to be some time lag between getting the parent object and saving it again.
Problem with this approach is that a sort of merge type operation is required. You may want to add any new objects that were created in process so that you don't loose your changes when the collection is updated. Hope this helps, give us some more info if you're still stuck.

A: You should implement the IDispose interface in you SessionFactory Class.
Just like this:
public class YouSessionFactory : INHibernateSessionFactory, IDisposable
{
    private ISessionFactory _sessionFactory;

    //codes for initial _sessionFactory, for configuration,mapping or something else.
    //balalalalalala
    //....

    public ISessionFactory BuildSessionFactory()
    {
        return _sessionFactory;
    }

    public void Dispose()
    {
        if (!_sessionFactory.IsClosed || _sessionFactory != null)
        {
            _sessionFactory.Close();
            _sessionFactory.Dispose();
        }
    }
}


text:
Q: Ajax calls vs. server side calls I am building a twitter feed widget for Wordpress, and one of the issues I have to deal with is Twitter's rate limits (150 tweets per hour per account). I have noticed that when i'm fetching the tweets using server-side calls (e.g. file_get_contents()) the limit is reached very quickly, especially on a shared host. I've tried to fetch the tweets using client-side calls with jQuery's getJSON function, and the rate limit took a lot longer to reach.

*

*What is the reason for this difference between client-side and
server-side calls when it comes to Twitter rate limits?

*Which method would be preferable for this case?

Update
I should note that the tweets are being cached to avoid hitting the rate limits, but that does not help when the calls are made from a shared host.

A: When you use server-side calls, all the calls are coming from the same IP; all the users are sharing the same 150 tweat/hour quota.
When you use client-side calls, they calls come from different IPs for each client. Each client gets 150 tweats per hour, so all the clients combined can get a much larger volume.


text:
Q: Importing a JSON feed from an external source in Javascript I'd like to load a JSON feed from an external source using Javascript; what's the best method? I've been working a lot in PHP where it would be easy to do so with file_get_contents or cURL. Is there a related function or process in Javascript?

A: jQuery to get some JSON data might look like this:
$.getJSON("http://pathtodata.js", function(json){
  alert(json.dot.notation);
});

A source is specified along with a callback function. Read up on jQuery JSON documentation:
http://api.jquery.com/jQuery.getJSON/

A: Javascript XMLHTTPRequest has same-domain origin policy so you will be restricted to only loading data from URLs from the same domain that your script was loaded from. JSONP is one way to get around this. Another way is to use a proxy script on your domain, which in turns performs its own HTTP calls for you. For more information on JSONP check out this article:
http://www.ibm.com/developerworks/library/wa-aj-jsonp1/


text:
Q: Release an object in a non-ARC project, object is declared in an ARC library Well I am working on a non-ARC project, but use Philipp Kyeck's socketio library which is written using ARC. I am using the method explained in this tutorial merge non-ARC project and ARC library.
In my ViewController file I am initializing the socket using
 SockIO *chatSockIO = [[SocketIO alloc] initWithDelegate:self];

and when I need to disconnect, I call
[chatSockIO disconnect];

which results socketIODidDisconnect delegate method to fire.
- (void) socketIODidDisconnect:(SocketIO *)socket{
   [chatSockIO release]; ==> is this call needed?
}

Now my question is about the line [chatSockIO release]. Should we need to release an object which itself is defined in ARC mode, but is used in a non-ARC project?
Now when I tried the release, I got an exception saying
-[SocketIO retain]: message sent to deallocated instance 0x6fec370

but when I commented out that line, I am getting a memory leak and dealloc in my library object not getting called at all
Bounty Time!!
Forget the library I mentioned, crash in my code and leaks.. What is the usual practice when using an object defined using ARC method, in a non-ARC project. Should I only alloc it, or should I alloc and release it after use?
EDIT:Some more info.
I run zombie instrument on the crash, and this is what it had to say.. It shows the call to alloc and release functions.
#   Address     Category    Event Type  RefCt   Timestamp       Size    Responsible Library     Responsible Caller
0   0x72d5da0   SocketIO    Malloc      1       00:09.700.274   64      MyProject           -[MyViewController sendRequestForSocketIOPush]
1   0x72d5da0   SocketIO    Retain      2       00:09.700.317   0       MyProject           -[SocketIO initWithDelegate:]
2   0x72d5da0   SocketIO    Release     1       00:09.700.320   0       MyProject           -[SocketIO initWithDelegate:]
3   0x72d5da0   SocketIO    Retain      2       00:09.700.440   0       Foundation          -[NSURLConnectionInternal initWithInfo:]
4   0x72d5da0   SocketIO    Retain      3       00:10.413.717   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
5   0x72d5da0   SocketIO    Release     2       00:10.413.761   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
6   0x72d5da0   SocketIO    Retain      3       00:10.413.797   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
7   0x72d5da0   SocketIO    Release     2       00:10.413.811   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
8   0x72d5da0   SocketIO    Retain      3       00:10.413.816   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
9   0x72d5da0   SocketIO    Release     2       00:10.415.087   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
10  0x72d5da0   SocketIO    Retain      3       00:10.415.214   0       Foundation          -[NSURLConnectionInternal _withConnectionAndDelegate:onlyActive:]
11  0x72d5da0   SocketIO    Release     2       00:10.415.216   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
12  0x72d5da0   SocketIO    Release     1       00:10.415.275   0       Foundation          -[NSURLConnectionInternalConnection invokeForDelegate:]
13  0x72d5da0   SocketIO    Retain      2       00:10.969.432   0       GraphicsServices    GSEventRunModal
14  0x72d5da0   SocketIO    Release     1       00:10.969.433   0       GraphicsServices    GSEventRunModal
15  0x72d5da0   SocketIO    Retain      2       00:10.969.434   0       GraphicsServices    GSEventRunModal
16  0x72d5da0   SocketIO    Release     1       00:10.969.456   0       GraphicsServices    GSEventRunModal
17  0x72d5da0   SocketIO    Retain      2       00:10.969.459   0       GraphicsServices    GSEventRunModal
18  0x72d5da0   SocketIO    Retain      3       00:10.969.488   0       Foundation          -[NSCFTimer initWithFireDate:interval:target:selector:userInfo:repeats:]
19  0x72d5da0   SocketIO    Release     2       00:10.976.115   0       MyProject           -[SocketIO setTimeout]
20  0x72d5da0   SocketIO    Retain      3       00:10.976.125   0       Foundation          -[NSCFTimer initWithFireDate:interval:target:selector:userInfo:repeats:]
21  0x72d5da0   SocketIO    Release     2       00:10.976.161   0       GraphicsServices    GSEventRunModal
22  0x72d5da0   SocketIO    Retain      3       00:13.935.328   0       GraphicsServices    GSEventRunModal
23  0x72d5da0   SocketIO    Release     2       00:13.935.373   0       MyProject           -[SocketIO setTimeout]
24  0x72d5da0   SocketIO    Retain      3       00:13.935.399   0       Foundation          -[NSCFTimer initWithFireDate:interval:target:selector:userInfo:repeats:]
25  0x72d5da0   SocketIO    Release     2       00:13.935.685   0       MyProject           -[SocketIO onDisconnect]
26  0x72d5da0   SocketIO    Release     1       00:13.935.705   0       MyProject           -[MyViewController socketIODidDisconnect:]
27  0x72d5da0   SocketIO    Release     0       00:13.935.716   0       GraphicsServices    GSEventRunModal
28  0x72d5da0   SocketIO    Zombie      -1      00:13.936.298   0       GraphicsServices    GSEventRunModal

A: To answer your question:
If you use an ARC-managed object from non-ARC code, you use it just as you would use a non-ARC object: If you create or retain it, you have to release or autorelease it.
Regarding your issue:
In on of your comments you mentioned that you tried to fix the problem with initializing like this
self.chatSockIO = [[[SocketIO alloc] initWithDelegate:self] autorelease];

and in socketIODidDisconnect
self.chatSockIO = nil;

That should work fine, provided that the chatSockIO property has retain semantics, and that only one SocketIO object is used at a time.
The Zombie output gives a hint on what's going wrong:

*

*In the second to last line, you release the object, the retain count drops to 0, and the object is deallocated. That is what you would expect.

*In the last line however, it is tried to retain the object from the run loop. You know it's a retain because of the exception you get without NSZombie.

*That means although you are done with the object, it still receives calls from somewhere. This is unexpected.

It could be either something in your code, or an error in one of the libraries you are using. Just a hunch: In SocketIO.m replace these lines in -onDisconnect
if (_webSocket != nil) {
    [_webSocket close];
}

with
if (_webSocket != nil) {
    [_webSocket close];
    _webSocket.delegate = nil;
}

A: This may not solve your problem, but in any case its usually a TERRIBLE idea to release an object in a delegate call - it may get dealloc'd while still doing work, and particularly if the object is under ARC, may not have a dealloc method.
So convert your close delegate call to this:
- (void) socketIODidDisconnect:(SocketIO *)socket
{
   chatSockIO.delegate = nil; // don't want any more messages
   dispatch_async(dispatch_get_main_gueue(), ^{ self.chatSockIO = nil; }); // typed in text editor
   // your question - is the release needed? Well, under virtually every scenario yes, but I don't know this framework
}

Whether this fixes your problem or not, you should be doing the release in this manner - on the main thread AFTER the delegate has returned. If you look at your code, you should do EXACTLY with this ARC class as you would with a normal class. The interoperability is excellent, I used several NON-ARC projects in my ARC app, and others have successfully done the reverse.

A: In my experience I wouldn't mix ARC and non-ARC expect small small chunks of code. I wasted way to much time to try to find leaks and crash bugs.
If you can't convert your program to ARC, consider using the non-ARC version of sockIO: https://github.com/pkyeck/socket.IO-objc/tree/non-arc
That will probably save you a lot of headaches.

A: I had felt similar issues. I solved this by setting @property(nonatomic, retain)  over the class. In your case it should be,
in .h
  @property(nonatomic, retain) SockIO *socketIO;

in .m
   @synthesize socketIO;
   chatSockIO = [[SocketIO alloc] initWithDelegate:self];

And you wont get crash your App again !

A: ARC and non ARC objects mix fine. Classes that are implemented using ARC can safely be used from non-ARC code. Whenever there's an ownership error the problem is probably in your code.
Without seeing code it's not possible to find the error but it's probably some simple over-release.
Look at all the places in MyProject where the Instruments trace shows a Release event, like -[SocketIO setTimeout], -[SocketIO onDisconnect] and -[MyViewController socketIODidDisconnect:]. Check if there are improper ownership transfers, like assigning an instance variable handled by a retain property or similar.

A: I am currently working on a project that I did something similar and the way I solved it was to switch the non-ARC project to ARC. Xcode transfers everything over for you and for me solved all my memory leaks and other issues.
To change over to ARC you need to:
1. Click Edit->Refactor->Convert to Objective-C ARC
2. Click your projects target and in the drop down, select the files you want to convert to ARC
3. Click Check once you have selected the right files
4. Click next and wait until conversion is done.
5. Click the "Update" button to update your code.
6. Review your code
Hope that helps. It helped me


text:
Q: 'CoreWebView2NavigationCompletedEventArgs' does not contain a constructor that takes 1 arguments I'm new to C# and the WebView2 control, and I'm trying to make something happen when a webpage inside the control finishes loading.
webView.NavigationCompleted += new CoreWebView2NavigationCompletedEventArgs(WebView_NavigationCompleted);
The code above throws a CS1729 error. What is the correct way to implement what I'm trying to accomplish? Any help appreciated!

A: Check out the WebView2 C# sample apps. It has a C# example of just what you're trying to do.
Registering the event handler
            control.NavigationCompleted += WebView_NavigationCompleted;

The event handler
        void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
        {
            // ...
        }

See also Navigation Events documentation.


text:
Q: Files won't save unless force is applied I'm currently working on my Thesis in LaTex and have successfully used TexStudio (2.11.2) and MiKTeX (2.9.6069-x64) for two years now. Since a couple of days TexStudio always needs to be forced to save the File by holding down STRG+S for 3-4 seconds and when I compile my file any changes since that last forced save are not included but an older version of the Code is compiled.
I also noticed that everytime I compile the code a new copy of my .tex-file with an obscure file-ending is created (Base File is "Thesis.tex"; new Files are e.g. "Thesis.tex.if2720", "Thesis.tex.JC2720" et cetera).
Cutting almost all text from the file won't change anything, updating packages and completely wiping MiKTeX and TexStudio didn't help. Neither cutting  TexWorks does not suffer from the same problem.
Additional Information: The Files are saved inside a Dropbox-folder and I am using Windows File History for backup.
Has anyone encountered this issue before?


text:
Q: Fail to fetch POST info I'm learning backend node/express. In this block of code I'm trying to send some data to backend but i get Uncaught (in promise) TypeError: Failed to fetch. Thank you.
Backend:
    const path = require("path")
const express =require("express")
const cors = require('cors')
const app = express()

const publicPath = path.join(__dirname, "..","client", 'dist')
const publicPath2 = path.join(__dirname, "..","client", 'public')
const port = process.env.PORT || 3000

app.use(express.urlencoded({extended: true}))
app.use(express.json())
app.use(cors())
app.use(express.static(publicPath))
app.use(express.static(publicPath2))

app.use(express.urlencoded)

app.get("*", (req,res) => {
    res.sendFile(path.join(publicPath, 'index.html'))
})

//edit

app.post('/api', (req, res) => {
console.log('I got a req')
console.log(req.body)
const data = req.body
res.json({
    status:'success',
    cart:data.cart
})

})
app.listen(port, () => {
    console.log('server is up')
})

frontEnd
const submitAuthor = async () => {
        const result = await fetch('/api', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(cart)
        })
        const data= await result.json()
        console.log(data)
      }

Edited the response part.

A: Your browser knows how to send only GET requests, unless you specify somehow that you need another method (like using a form). So if you just try to access that endpoint through the url, a GET request will be sent by the browser, not a POST one


text:
Q: Return Bool from Mongoose virtual In MEAN stack project, I want to find if there are likes for a comment or not. "Comment" is the acutal comment schema and "CommentReaction" schema stores details of users who liked the comment. Using below code, I'm able to get the count of number of likes for a comment. In my Angular code, I'm checking if count is more than 0 or not and its working good.
commentSchema.virtual('likes', {
  ref: 'CommentReaction',
  localField: '_id',
  foreignField: 'commentId',
  count: true
});

But I am expecting the REST API to return true or false accordingly. How can I modify my above code to return true or false only?

A: You could define another virtual and check the count for members there:
commentSchema.virtual('hasLikes', {
    foreignField: 'likes', // must match the previous virtual
}).get(function () {
    return this.likes > 0;
});

Make sure to enable the virtual options for toJSON/toObject:
commentSchema.set('toObject', { virtuals: true });
commentSchema.set('toJSON', { virtuals: true });

and finally correctly populate the query:
const res = await Comment.find({}).populate('likes').populate('hasLikes').exec();
console.log(res);


text:
Q: Flex Mobile persist view data I built a simple hello world app to check out the Flash Builder 4.5 mobile capabilities.
Here's how it works:
The Default View asks for name in an textinput and has a continue button
When you click the continue button it pushes a new view in the viewNavigator which just displays "Hello " + name in a label.
When you click anywhere in this view, it pops a view (i.e. itself) from the viewNavigator, to go back to the default view
I see only 1 issue with this:
When I get back to the default view, it is in its initial state, i.e. the textInput is blank. It seems as if the viewNavigator created a new view of the default view's class and pushed this, instead of just removing the top view and displaying the previous one.
I see this being especially problematic for programs which display data in a grid and you can click the data to view the detail...when you get back, the grid will be empty.
Any ideas or gotchas to solve this?
EDIT:
Project name: HelloWorld
Code below:
HelloWorldDefaultView.mxml
protected function button1_clickHandler(event:MouseEvent):void {
    navigator.pushView(HiView, tName.text);
}

HiView.mxml
protected function view1_clickHandler(event:MouseEvent):void {
    navigator.popView();
}

protected function view1_creationCompleteHandler(event:FlexEvent):void {
    lblHello.text="Hello " + data;
}

Screenshots

Initial screen

Screen 2

Clicking on screen 2 gets us back to initial screen. Notice the blank textInput

A: That's the way it is supposed to work for mobile applications.
Check out this article: Flex 4.5 (Hero) – Persistant Data in MobileApplication
As they write:

Each time a View is removed from the display list (via popView() or pushView()) its instance is destroyed, but its data model is stored in memory.
In order to save session state for a View, you must modify the data property. This property will be requested when destroying the current instance of the View class. And the data property value will be assigned back to a newly created instance of the same View class when navigating back to that view.

A: Have you tried to set destructionPolicy="never" and then
protected function button1_clickHandler(event:MouseEvent):void {
    data = tName.text;
    navigator.pushView(HiView, tName.text);
}

to store the data in current View's data - before changing to another one?


text:
Q: Zariski topology closure of image of a homomorphism Just started dealing with Zariski's topology on specta, and encountered the following question:

$R,S$ commutative rings with unit and $\phi:R\rightarrow S$ homomorphism. Prove that the induced map $\psi:\operatorname{Spec(S)}\rightarrow\operatorname{Spec(R)}$ is continuous and $\text{Cl}(Im(\psi))=V(\text{ker}(\phi))$.

So I proved continuity: Assume $V(I)\subseteq\operatorname{Spec(R)}$ is some closed set, so:
$\psi^{-1}(V(I))=\{p\in\operatorname{Spec(S)}:\psi(p)\in V(I)\}=\{p\in\operatorname{Spec(S)}:I\subseteq \psi(p)\}=\{p\in\operatorname{Spec(S)}:\psi^{-1}(I)\subseteq p\}=V(\psi^{-1}(I))$ which is closed in $\operatorname{Spec(S)}$. So this proves continuity.
The part I'm having trouble with is the second part. I know that for $X\subseteq\operatorname{Spec(S)}, \text{Cl}(X)=V(\bigcap_{P\in X}P)$, but I'm not able to prove that $\text{ker}(\phi)=\bigcap_{P\in Im(\psi)}P$.
Any help would be appreciated.

A: $\text{ker}(\phi)=\bigcap_{P\in Im(\psi)}P$ is not true in general but you can still prove that $V\left(\text{ker}(\phi)\right)=V(\bigcap_{P\in Im(\psi)}P)$.
Note that $Im(\psi)=\{ \phi^{-1}(Q) : Q\in \operatorname{Spec(S)} \}$ so $$V\left(\bigcap_{P\in Im(\psi)}P\right) = V\left(\bigcap_{Q\in \operatorname{Spec(S)}}\phi^{-1}(Q) \right) = V\left( \phi^{-1} \left(\bigcap_{Q\in \operatorname{Spec(S)}} Q \right) \right) =V\left( \phi^{-1}(\operatorname{Nil(S)}) \right)$$
where $\operatorname{Nil(S)}$ is the nilradical of $S$.
Now we can show that $V\left( \phi^{-1}(\operatorname{Nil(S)}) \right)=V\left(\text{ker}(\phi)\right)$. One inclusion is immediate: $V\left( \phi^{-1}(\operatorname{Nil(S)}) \right)\subseteq V\left(\text{ker}(\phi)\right)$ since $\text{ker}(\phi) \subseteq \phi^{-1}(\operatorname{Nil(S)})$.
For the other inclusion, let $P\in V\left(\text{ker}(\phi)\right)$ and we want to show that $\phi^{-1}(\operatorname{Nil(S)}) \subseteq P$. In fact, take an element $x\in \phi^{-1}(\operatorname{Nil(S)})$ then $\phi(x^n)=0$, which implies that $x^n\in \text{ker}(\phi) \in P$, hence, $x\in P$.


text:
Q: Webclient download file with size zero when downloading more than once I have a weird problem and I can't find why it happen, I wrote a function to download a file from a given link, when I invoke the function once it works fine. but if I invoke it twice or more (on the same link), it downloads a file with size 0.
Here my code:
Uri uri = new Uri("http://www.orimi.com/pdf-test.pdf");
string outPath = @"D:\tttt\pdf-test.pdf";
for (int i = 0; i < 1; i++)
{
     using (WebClient webClient = new WebClient())
     {
         WebProxy wp = new WebProxy($"http://192.168.xxx.xxx:8002/", true);
         webClient.Proxy = wp;
         webClient.OpenRead(uri);
         webClient.DownloadFileAsync(uri, outPath);
     }
        Console.WriteLine("Success!");
}
Console.ReadKey();

This works only for one iteration
but if I'm changing to for loop with two or more iteration the downloaded file will be with size zero


text:
Q: How to get current displayed date range in full calendar jquery I have implemented fullcalendar in my application. I am facing a problem for getting current displayed date range.
I want to get currently displayed date range in full calendar.
Please suggest me a proper solution.
For example please take a look on this image

In this I want to get "20 Sept" and "26 Sept".

A: $('#mycalendar').fullCalendar('getView').start.format('DD MMM');
$('#mycalendar').fullCalendar('getView').end.format('DD MMM');

A: In version 5.5.1 , you have to use

var view = calendarObj.view; // calendarObj is the reference to the fullcalendar
var start = view.activeStart;
var end = view.activeEnd;

start and end variables are Date.

A: Try this.
Add this function and call this. It will help you.
  function GetCalendarDateRange() {
        var calendar = $('#calendar').fullCalendar('getCalendar');
        var view = calendar.view;
        var start = view.start._d;
        var end = view.end._d;
        var dates = { start: start, end: end };
        return dates;
    }

A: In version 4.0, $().fullCalendar('next') no longer exists. You can use calender.next(), where calender is an instance of the object.
For example, to capture the start date:
    calender.view.activeStart.
See the documentation for more information: https://fullcalendar.io/docs/upgrading-from-v3

A: I don't have enough reputation but user2682863 answer is the best in my opinion.
This way you use their API instead of using jquery to retrieve it from the frontend.
By accessing the View object (https://fullcalendar.io/docs/view-object) you can get the current range like so (in Vue).
var calendarApi = this.$refs.calendar.getApi();
this.dates = calendarApi.state.dateProfile.currentRange;

A: I know this has been answered already but none of the above methods worked for me in v5 so will post what did. After a rather frustrating search through the docs I came across this page. Using datesSet you can get start and end dates as well as the full view.
https://fullcalendar.io/docs/datesSet
If you add in a handler on init then this fires whenever the user changes the date via the buttons which is what I needed:
  document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var calendar = new FullCalendar.Calendar(calendarEl, {
      initialView: 'dayGridMonth',
            dateClick: function (info) {
                alert('clicked ' + info.dateStr);
            },
            datesSet: function (dateInfo) {
                var start = dateInfo.start;
                var end = dateInfo.end;
                var startStr = dateInfo.startStr;
                var endStr = dateInfo.endStr;
                var timeZone = dateInfo.timeZone;
                var view = dateInfo.view;
            }
    });
    calendar.render();
  });

A: I found the current date range by accessing calendar.state.dateProfile.currentRange
where calendar is
calendar = new FullCalendar.Calendar(calendarEl}

A: I'm using FullCalendar 5.8.0 with React. I found the following to work for me:

*

*Create a ref and pass it into FullCalendar.
const calendarRef = React.createRef()
...
FullCalendar ref={calendarRef} ...

*In my function where I need the know the visible date range:
let calendarApi = calendarRef.current.getApi()
let dates = calendarApi.currentDataManager.state.dateProfile.activeRange


text:
Q: iCheck jQuery blocks custom script I used "iCheck jQuery" to modificate the style of the checkbox. But when i add a  iCheck script - my onlick metod stops working. Why it happening?
<input id="my_cb"  type="checkbox" value="yes_n" onclick="hide_row_metod()"/>
    <script>
    $(document).ready(function(){
      $('#my_cb').iCheck({
        checkboxClass: 'icheckbox_square-blue',
        radioClass: 'iradio_square-blue',
        increaseArea: '20%' // optional
      });
    });
    </script>

My script:
<script>
   function hide_row_metod() {
     if(document.getElementById('my_cb').checked){
        document.getElementById('row1').style.display = "none";
     }else{
            document.getElementById('row1').style.display = "inline";
          }
     }
</script>

A: iCheck registers custom events you can listen for. I put up a working example on jsbin, the main difference is this:
$("#my_cb").on("ifChanged", hide_row_metod);

There are two events: ifChecked and ifUnchecked. If you want to catch all changes to your checkbox, you need to either listen for both or simply listen for ifChanged. This will work to toggle the row, as you are testing for checked in your hide_row_metod.
In my example, I use a block element div#row1, so it will render differently (inline) after checking and unchecking.
Also: you got a typo in your method name (missing h).

A: I know it's been some time since this question has been asked. I've made a script to capture onclick attribute from each radio / checkbox and attach it to its corresponding iCheck / iRadio. Just remember to run it AFTER iCheck has been applied. Set a timeout or run it after iCheck's implementation:
$("[class*='icheckbox'],[class*='iradio']").each(function(){
  $(this).find("ins").attr("onclick", $(this).find("input").attr("onclick"));
});

A: It is probably overridden by the iCheck script. Try using only jQuery:
$('#my_cb').on('click', function() {
    $('#row1').css('display', this.checked ? 'none' : 'inline');
});


text:
Q: Nuxt run code clientside within server-side execution In nuxt, if I know the code running is in server-side context, is there a way to specify that some code should run once the client is rendered?
For example:
if (process.server) {
   // we know we are server-side
   // run the following line of code client-side:
   window.doSomething();
}

I know that as a workaround I could put this code in mounted, but is there any way to specify to run client-side within any context?
For example, like a setTimeout, or some callback like (pseudo-code) onClientSide( () => {} )


text:
Q: Does django csrf token must be unique on every request? I have a question about Django CsrfViewMiddleware mechanism.
I know, that Django:

*

*Set new csrftoken cookie on every request.

*Check, than X-CSRFToken header value (or hidden input "csrfmiddlewaretoken") must be equals to csrftoken cookie.

But Django doesn't check whether token has been used already (example from CsrfViewMiddleware):
if not constant_time_compare(request_csrf_token, csrf_token):
            return self._reject(request, REASON_BAD_TOKEN)

So I can POST multiple requests with the same token (I tested it on my server).
Is it standart behavior, or I have incorrect Django setup?
Thanks.

A: CSRF tokens are not consumed.
To elaborate on Germano's comment, the reasoning behind it is simple:
Multiple browser windows / tabs and REST
Essentially, Django would have to create (and persist, and, in distributed 'cloud' deployment, synchronize) new CSRF tokens for every single page that has been rendered in the past. Essentially, this would easily lead to Denial of Service attacks, where you cannot assume any sensible expiration for the CSRFs.


text:
Q: how to place value of xpath in to html img tag The following code gets me the appropriate string, but I don't know how to put the value in to an html img tag:
<xsl:value-of select="MT[@N = 'tag']/@V" />

I've tried this:
<img src="<xsl:value-of select="MT[@N = 'tag']/@V" />

and several variations.
Thanks.

A: Use an Attribute Value Template (AVT)


text:
Q: ASP .net validations For validation in ASP.Net which one is better validation controls or JavaScript coding

A: Javascript validations can be easily overridden by potential hackers, they are just for user comfort (not requiring to postback). You should always do a server-side validation.
Validation controls take care of this automatically (provide client and server-side validations), so it's better to use them unless you do server validations on your own.

A: For WebForms I would suggest to use the Validator controls provided by Microsoft. The Validator controls by Microsoft validate the controls on the client side as well as on the server side.


text:
Q: Python JSON and Unicode Update :
I found the answer here : Python UnicodeDecodeError - Am I misunderstanding encode?
I needed to explicitly decode my incoming file into Unicode when I read it. Because it had characters that were neither acceptable ascii nor unicode. So the encode was failing when it hit these characters.
Original Question
So, I know there's something I'm just not getting here.
I have an array of unicode strings, some of which contain non-Ascii characters.
I want to encode that as json with
json.dumps(myList)

It throws an error
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb4 in position 13: ordinal not in range(128)

How am I supposed to do this? I've tried setting the ensure_ascii parameter to both True and False, but neither fixes this problem.
I know I'm passing unicode strings to json.dumps. I understand that a json string is meant to be unicode. Why isn't it just sorting this out for me?
What am I doing wrong?
Update : Don Question sensibly suggests I provide a stack-trace. Here it is. :
Traceback (most recent call last):
  File "importFiles.py", line 69, in <module>
    x = u"%s" % conv
  File "importFiles.py", line 62, in __str__
    return self.page.__str__()
  File "importFiles.py", line 37, in __str__
    return json.dumps(self.page(),ensure_ascii=False)
  File "/usr/lib/python2.7/json/__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "/usr/lib/python2.7/json/encoder.py", line 204, in encode
    return ''.join(chunks)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xb4 in position 17: ordinal not in range(128)

Note it's python 2.7, and the error is still occurring with ensure_ascii=False
Update 2 : Andrew Walker's useful link (in comments) leads me to think I can coerce my data into a convenient byte format before trying to json.encode it by doing something like :
data.encode("ascii","ignore")

Unfortunately that is throwing the same error.

A: Try adding the argument: ensure_ascii = False. Also especially if asking unicode-related issues it's very helpful to add a longer (complete) traceback and stating which python-version you are using.
Citing the python-documentation: of version 2.6.7 :

"If ensure_ascii is False (default: True), then some chunks written to
  fp may be unicode instances, subject to normal Python str to unicode
  coercion rules. Unless fp.write() explicitly understands unicode (as
  in codecs.getwriter()) this is likely to cause an error."

So this proposal may cause new problems, but it fixed a similar problem i had. I fed the resulting unicode-String into a StringIO-object and wrrote this to a file.
Because of python 2.7 and sys.getdefaultencoding set to ascii the implicit conversion through the ''.join(chunks) statement of the json-standard-library will blow up if chunks is not ascii-encoded! You must ensure that any contained strings are converted to an ascii-compatible representation before-hand! You may try utf-8 encoded strings, but unicode-strings won't work if i'm not mistaken.


text:
Q: How to check arrays for equality between multiple values? So I'm trying to build a tic-tac-toe game that involves the user playing against a the computer. I would like these arrays to check for a winning sequence of blocks that will indicate someone has won the game. I'm wondering if this method of checking different parts of an array and comparing them for equality is valid?
function winner() {
    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'X' || blocks[0, 3, 6].value == 'X' || blocks[2, 5, 8].value == 'X' || blocks[6, 7, 8].value == 'X' || blocks[2, 4, 6].value == 'X' || blocks[0, 4, 8].value == 'X') {
            alert('Player X Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }
    };

    var blocks = document.getElementsByClassName('block');
    for (var i = 0; i < blocks.length; i++) {
        if (blocks[0, 1, 2].value == 'O' || blocks[0, 3, 6].value == 'O' || blocks[2, 5, 8].value == 'O' || blocks[6, 7, 8].value == 'O' || blocks[2, 4, 6].value == 'O' || blocks[0, 4, 8].value == 'O') {
            alert('Player O Wins!!');
            blocks.classList.toggle('block');
            player === 1;
        }

    }
}

Also, is this a viable way to dictate whose turn it is? I had a little success with this class switching mechanism to determine which blocks have been chosen in the beginning but can't seem to make it work now.
This is the code for changing turns and class switching so far but I'm sure there's a better way:
var player === 1

var blocks = document.getElementsByClassName('block');

function turn() {
    if (player === 1) {
        player -= 1;
        winner();
        var buttons = document.getElementsByTagName("button");
        console.log(buttons.length);
        for (var i = 0; i < buttons.length; i++) {
            buttons[i].addEventListener("click", function(e) {
                var number = (this.getAttribute('name'));
                var chosenblock = document.getElementsByName(number)[0];
                chosenblock.classList.toggle('chosen');
                chosenblock.value = 'X';
                // console.log('click!');
            });
        }
    } else {
        player += 1;
        winner();
        var computer;
        computer = function() {
                var computerchoice = Math.floor(Math.random() * (9) + 1);

                function compselected(number) {
                    //How to make number equal to the id of the selected block?
                    var chosenblock = document.getElementsByName(number)[0];
                    chosenblock.classlist.toggle('picked');
                }

Any advice is appreciated thanks guys! Here's the fiddle if that helps.


text:
Q: CAT on same file from multiple thread fails     XML_OUTPUT=${WORK_DIR}/xml.txt
    errCode=`cat ${XML_OUTPUT} | grep ERR_CODES | cut -d "=" -f2`
    accesslog_filterMap=`cat ${XML_OUTPUT} | grep ACCESS_LOG_FM_VALUE | cut -d "=" -f2`
    sec_filterMap=`cat ${XML_OUTPUT} | grep SECURITY_FM_VALUE | cut -d "=" -f2`
    instrumentation_filterMap=`cat ${XML_OUTPUT} | grep INSTRUMENTATION_FM_VALUE | cut -d "=" -f2`
    serverhealthcheck_filterMap=`cat ${XML_OUTPUT} | grep SERVER_HEALTH_CHECK_FM_VALUE | cut -d "=" -f2`

xml.txt content
ERR_CODES=400 401 403 404 408 413 414 500 505 java.lang.Throwable
INSTRUMENTATION_FM_VALUE=TRUE
ACCESS_LOG_FM_VALUE=TRUE
SECURITY_FM_VALUE=TRUE
SERVER_HEALTH_CHECK_FM_VALUE=TRUE

When i run this script from multiple threads its not gives always the same result. Sometimes it(cat) returns empty String . How to handle this for multi thread environment ?


text:
Q: Angular js binding strings without quotes So i have this project where I want to bind string to
 tags from highlight.js with angular.js but I don't know how to bind it without quotes.
This is the code:


text:
Q: AuraEnabled Method Causes Internal Server Error for non-Admin Profile I have an Aura Enabled method in my class that accepts a Case record and a list of a related object records and inserts both of them. The code works fine when I'm logged in as the admin, but the actual user profile that will be leveraging it receives an Internal Server Error when calling the method.
The user profile is a Community user (Customer Community Plus license) and I am testing with the Community in Preview.
I've verified that:

*

*The profile has full CRUD access on Case

*The profile has full CRUD access on Subject__c

*The profile has all field level security visibility needed for fields on Case and Subject__c

*The profile has access to the Apex class

Are there any other areas I should be looking? These are new records to be inserted so I do not think sharing should be a part of the issue.
My class looks like this:
public with sharing CaseWithSubjectServive {

    @AuraEnabled
    public static Id createCaseWithSubjects(Case newCase, List<Subject__c> subjects) {
        System.debug('Entered method'); //this will not get hit
        try {
            insert newCase;
            insert subjects;
        } catch(Exception e) {
            throw new AuraHandledException(e.getMessage());
        }
    }

}

My component HTML:
<template>

    <lightning-record-edit-form if:true={caseRecordTypeId} object-api-name="Case" record-type-id={caseRecordTypeId} onsubmit={handleSubmit} density="comfy">
        <lightning-messages></lightning-messages>

Create a Case

                <lightning-input-field required field-name="Company_Name__c"></lightning-input-field>

Associated Individuals/Companies

        <c-associated-individuals-companies-list></c-associated-individuals-companies-list>

                <lightning-button
                    class="slds-m-top_small"
                    type="submit"
                    name="save"
                    label={label.submit}>
                </lightning-button>

    </lightning-record-edit-form>

        <lightning-spinner alternative-text="Saving..." style="position: fixed;"></lightning-spinner>

</template>

My component JS:
import { LightningElement, track, wire } from 'lwc';
import createCaseWithSubjects from '@salesforce/apex/CaseWithSubjectServive .createCaseWithSubjects';
import { getObjectInfo } from 'lightning/uiObjectInfoApi';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import { NavigationMixin } from 'lightning/navigation';
import CASE_OBJECT from '@salesforce/schema/Case';

// custom labels
import submit from '@salesforce/label/c.Submit';

export default class CaseWithSubjects extends NavigationMixin(LightningElement) {
    label = {
        submit,
    };
    caseRecordTypeId;

    showSpinner;

    @wire(getObjectInfo, { objectApiName: CASE_OBJECT })
    objectInfo({error, data}) {
        if(data) {
            const recordTypes = data.recordTypeInfos;
            this.caseRecordTypeId = Object.keys(recordTypes).find(
                t => recordTypes[t].name === 'Request Form'
            );
        } else if(error) {
            console.error(error);
        }
    }

    get caseRecordTypeId() {
        return this.caseRecordTypeId;
    }

    toggleSpinner() {
        this.showSpinner = !this.showSpinner;
    }

    handleSubmit(event) {
        event.preventDefault();

        const newCase = event.detail.fields;
        newCase.RecordTypeId = this.caseRecordTypeId;

        const individuals = this.template.querySelector('c-associated-individuals-companies-list').getIndividuals();
        const companies = this.template.querySelector('c-associated-individuals-companies-list').getCompanies();

        if(!this.hasValidCompanies(companies) && !this.hasValidIndividuals(companies)) {
            this.fireErrorToast('Please fill in all required fields on your Subjects');
            return;
        }

        const allAssociated = [...individuals, ...companies];

        this.toggleSpinner();

        createCaseWithSubjects ({
            newCase: newCase,
            subjects: allAssociated
        })
        .then(caseId => {
            this.toggleSpinner();
            this[NavigationMixin.Navigate]({
                type: 'standard__recordPage',
                attributes: {
                    recordId: caseId,
                    objectApiName: 'Case',
                    actionName: 'view',
                }
            });
        })
        .catch(error => {
            //INTERNAL SERVER ERROR HITS CATCH
            this.toggleSpinner();
            console.error(error);
            this.fireErrorToast(error.body.message);
        });

    }

    fireErrorToast(msg) {
        const evt = new ShowToastEvent({
            title: 'Error',
            message: msg,
            variant: 'error',
        });
        this.dispatchEvent(evt);
    }

    hasValidIndividuals(individuals) {
        const invalidIndividuals = individuals.filter(v => {
            if(!v.First_Name__c || !v.Last_Name__c) {
                return v;
            }
        });

        return (invalidIndividuals.length === 0);
    }

    hasValidCompanies(companies) {
        const invalidCompanies = companies.filter(v => {
            if(!v.Company_Name__c) {
                return v;
            }
        });

        return (invalidCompanies.length === 0);
    }

}

A: One way to figure whats the actual error is by handling the AuraEnabled exception . This would reveal why it is failing and will not give a GACK.
public with sharing CaseWithSubjectServive {

  @AuraEnabled
  public static Id createCaseWithSubjects(Case newCase, List<Subject__c> subjects) {
    try {
       System.debug('Entered method'); //this will not get hit
       insert newCase;
       insert subjects;
    } catch(ex) {
        throw new AuraHandledException(ex.getMessage());
    }

  }
}

A: Try these two:

*

*Can you please remove public with sharing to public without sharing
in apex class.

*Add some console.logs in Java script and check Line by Line why its
failing (trace it).

A: I figured it out. The Subject__c object had a Deployment Status of "In Development". Once I changed it to "Deployed" everything worked.


text:
Q: How to set/unset environmental variables just before to run my program in Code Blocks I am using Code::Blocks fortran project fork, svn 11210 sdk version 1.32.0
I was previously using an older Code::Blocks version, so the options I saved are now conflicting with this new version, but I do not know how to change them.
When I run my program from within Code::Blocks (I press the button "Build and run"), the following text appears tin the log window:
Checking for existence: /home/me/fortran_projects/project/bin/Debug/Prevision
Executing: gnome-terminal --hide-menubar  -t Prevision --maximize -x  /usr/local/apps/global/codeblocks_fortran/1.5/cb_console_runner LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.:/home/me/fortran_projects/cdi/installed/include:/usr/lib64 /home/me/fortran_projects/project/bin/Debug/Prevision /home/me/Documentos/calc_config.conf (in /home/me/project)

You can see the string

LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.:/home/me/fortran_projects/cdi/installed/include:/usr/lib64

inserted just before the calling to the program. It seems that I inserted it when I used the previous version of Code::Blocks. I also used an older version of gfortran, whose libraries where palced in /usr/lib64. I now use a newer version of gfortran, whose libraries are placed in another directory. So, this piece of command line, is conflicting.
I have checkd the following options but the conflicting string is not there:

*

*Settings->Environment->General settings->Terminal to launch console programs

*Settings->Environment->General settings->Environment variables

*Settings->Global variables
I really do not know where to find it.

A: The offending path ("/usr/lib64") was in the project's "Build options ..." panel, in the settings common to Debug and Release, under "Search directories" and under "Linker".
I have deleted it and now everything goes ok.


text:
Q: Why does my C# client, POSTing to my WCF REST service, return (400) Bad Request? I'm trying to send a POST request to a simple WCF service I wrote, but I keep getting a 400 Bad Request. I'm trying to send JSON data to the service. Can anyone spot what I'm doing wrong? :-)
This is my service interface:
public interface Itestservice
{
    [OperationContract]
    [WebInvoke(
        Method = "POST",
        UriTemplate = "/create",
        RequestFormat = WebMessageFormat.Json,
        ResponseFormat = WebMessageFormat.Json)]
    String Create(TestData testData);
}

The implementation:
public class testservice: Itestservice
{
    public String Create(TestData testData)
    {
        return "Hello, your test data is " + testData.SomeData;
    }
}

The DataContract:
[DataContract]
public class TestData
{
    [DataMember]
    public String SomeData { get; set; }
}

And finally my client code:
private static void TestCreatePost()
{
    Console.WriteLine("testservice.svc/create POST:");
    Console.WriteLine("-----------------------");

    Uri address = new Uri("http://localhost:" + PORT + "/testweb/testservice.svc/create");

    // Create the web request
    HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;

    // Set type to POST
    request.Method = "POST";
    request.ContentType = "application/x-www-form-urlencoded";
    //request.ContentType = "text/x-json";

    // Create the data we want to send
    string data = "{\"SomeData\":\"someTestData\"}";

    // Create a byte array of the data we want to send
    byte[] byteData = UTF8Encoding.UTF8.GetBytes(data);

    // Set the content length in the request headers
    request.ContentLength = byteData.Length;

    // Write data
    using (Stream postStream = request.GetRequestStream())
    {
        postStream.Write(byteData, 0, byteData.Length);
    }

    // Get response
    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
    {
        // Get the response stream
        StreamReader reader = new StreamReader(response.GetResponseStream());

        // Console application output
        Console.WriteLine(reader.ReadToEnd());
    }

    Console.WriteLine();
    Console.WriteLine();
}

Can anyone think of what I might be doing wrong? As you can see in the C# client I've tried both application/x-www-form-urlencoded and text/x-json for ContentType, thinking that might have something to do with it, but it doesn't seem to. I've tried a GET version of this same service and it works fine, and returns a JSON version of TestData with no problem. But for POST, well, I'm pretty stuck at the moment on this :-(

A: Have you tried "application/json" instead of "text/x-json".  According to this Stack Overflow question application/json is the only valid json media type.

A: The only problem here is the ContentType.
try ( recommended )
request.ContentType = "application/json; charset=utf-8";

or ( this will work too )
request.ContentType = "text/json; charset=utf-8";

Both of above solve the problem. However, the first one is recommended, for details of JSON-RPC 1.1 Specification check out http://json-rpc.org

A: Try:
[OperationContract]
[WebInvoke(
  Method = "POST",
  UriTemplate = "/create",
  RequestFormat = WebMessageFormat.Json,
  ResponseFormat = WebMessageFormat.Json,
  /* non-wrapped */ BodyStyle = WebMessageBodyStyle.Bare )]
String Create(TestData testData);


text:
Q: Segemented Control Navigation Controller I was wondering how you use segmented control in a navigation controller. I want it so that on one of the screens, when they click the segmented control, they can flip between 2 other pages (hence 3 all together).
When I try doing this in a navigation controller, they either don't have any navigation bars (once a segue is made from each view controller to each of the other 2 (6 in total)), or if I connect them in series then they all have back buttons.
How would I achieve the segmented control effect to flip between 3 pages in a navigation controller, each with the same back button (i.e. it goes back to the same page), without running into any of the problems mentioned above?
Thanks in advance. Any help is much appreciated.


text:
Q: Specify URL instead of IP:port in network endpoints for applications behind reverse proxy We are using GCP external HTTPS load balancer, architecture is shown in the diagram below. The primary use of LB is redirecting users to static error site (hosted on Cloud Storage bucket) in case CE instance is down, Traefik crashes on CE, Docker crashes on CE, etc.
We have 4 backend services defined on load balancer:

*

*static-error-page backend bucket

*blog-backend-service, gallery-backend-service and shop-backend-service zonal network endpoint groups

Then, we defined host and path rules so that:

*

*https://blog.company.com -> blog-backend-service

*https://gallery.company.com -> gallery-backend-service

*https://shop.company.com -> shop-backend-service

*All unmatched (default) -> static-error-page
Each zonal network endpoint group (blog-backend-service, gallery-backend-service and shop-backend-service) has just 1 endpoint defined: 192.168.171:443 (192.168.171.3 is internal IP of CE instance).
However, since my websites are served behind reverse proxy (Traefik), specifying IP:port combination in network endpoint is useless because they all have the same IP:port. I would like to specify URL instead of IP:port in network endpoint (that way network endpoint would also show correct health status if website is down, it always reports healthy now, even if application is down).
Is it possible to specify URL instead of IP:port in network endpoint? If not, what are my alternatives?

A: Instead of using treafik, you can use Google API Gateway which was meant to do that job, while you can still use the load balancer behind it.


text:
Q: disabled button gets enabled on toggling between tabs and pages I am trying to disable a button on certain condition. I tried to use data-ng-class but when I change the tabs or switch between pages the buttons are getting activated intermittently. Would like to understand how can I achieve this feature.
<button type="button" class="btn btn-success"  href="" data-ng-click="saveValueSellerBid(false);" data-ng-class="{disabled: currentQuote.acceptPricingSellerDisabled}">
                                    <svg class="icon icon-checkmark"><title>Accept value seller offer</title><use xlink:href="#icon-checkmark"></use></svg>

        </button>

A: Try this attribute instead:
ng-disabled="currentQuote.acceptPricingSellerDisabled"


text:
Q: Punctuation in a sentence "from A or B to C and even D" Is there a need for punctuation in the following sentence: "Response time has reduced from weeks or days to hours and even minutes in some cases."
More generally, how should one use punctuation in a family of sentences:
" ..... from A or B to C and even D ....."?

A: Technically no punctuation is necessary, but it might be helpful to add a few commas and parentheses:

Response time has reduced, from weeks or days, to hours (and even minutes in some cases).

A: How about separating the from ideas from the to ideas. Then treat the add-on idea with long dashes. (I've grown to love the long dashes, revealed to me by an editor long ago...)
As in, "Response time has reduced from weeks or days, to hours — and even minutes — in some cases."
In the second sub query, " ... from A or B to C and even D ...", it would follow as "...from A or B, to C — and even D."
The sense of each ends with "to hours" or "to C" as the capper of the idea, then an afterthought chimes in, hence the long dash.

A: I agree with Buzz Mega that an "em" dash might help.  In addition, it may allow you to remove the last "and" to make the last, and presumably the most important, clause stronger.

Response time has reduced from weeks or days to hours—even minutes in some cases.

The punctuation depends on what part of the sentence you want to place the emphasis.

A: I'm not always correct, so correct me if I am wrong. I think the correct punctuation would be "Response time has reduced from weeks and days to hours and even minutes on occasion."
Very good question.

A: I think it depends on whether you pause or not when you say the sentence because essentially a comma is used to indicate a pause.


text:
Q: Pull to Refresh UWP - Grid view? Could someone please advise me on the "correct" way of implementing Pull to refresh on UWP?

Below are some examples I've found however I'm not sure which one is using the best approach:

*

*Microsoft sample which is for a ListView - This works however it is specific to the ListView Control

*AmazingPullToRefresh is a NuGet package that also works however it is somewhat limited in terms of styling

*PullToRefreshUWP_WindowsComposition is another example however it works differently to the other two as it does not use an extension class

Any advice is much appreciated

A: There is no standard answer for this question, basically, there are two points we need to implement:

*

*Get the offset changes when user pull something on the control

*Generate some indicator to notify user

Both XamlPullToRefresh and PullToRefreshUWP_WindowsComposition use the new Windows Composition API: Windows.UI.Composition namespace
Ref Windows.UI.Composition Overview

The API is a powerful supplement to existing frameworks such as XAML
  to give developers of UWP applications a familiar C# surface to add to
  their application. These APIs can also be used to create DX style
  framework-less applications.

Please notice that this API works only on Windows 10.

While AmazingPullToRefresh uses Manipulation API and implement all things by calculating offset changes. A similar implementation can be found here

If you want to implement a cool pull-to-refresh control, I would recommend using the Windows.UI.Composition API. You can get start from here

A: The functionality of pulling to refresh is not used by microsoft.
Reloading a page / data is something we have still in our mind from thinking apps like a website.
Why not have a synced database and alway update your UI with the data which got changed in your local db? For eg. see firebase.google.com
If you want to implement this feature anyway there is not really a way to go.
I have used the PullToRefresh.UWP library from NuGet. For a tutorial see:
codeproject.com
With some tweaking it works but sometimes when I lift my finger of the screen after pulling down the bar won't go up again.
So the answer is: Sorry, but nobody can give you an answer on how to do this the "correct" way. But is there a correct way anywhere? Like almost always in programming. It depends on the case you will use it.
Hope this will help you.


text:
Q: How to Query in a web map for distance between 2 points I am new to web mapping and am looking out for a solution to my issue.
I have been working on creating a Web Map for Paying guest location from my workplace and am looking to find the distance to each PG locations. However I am not sure how to do this? Can anybody help?
I am using GeoServer, Postgresql and Leaflet.
To do the query is there any plugins available or do I have to write a Javascript code?

A: There is a whole slew of measurement plugins available for Leaflet.  Leaflet-MeasureControl and leaflet_measure both appear to have potential for your use-case.  Alternatively, it would be very simple to implement your own point to point measurement using trigonometry.  If the distances are short (10s of km), then you would not need the Haversine formula (though that too is an option for greater accuracy - do a search on this site for more info).
I also notice that you are using Postgresql and Geoserver. Yet another option is for you send the coordinates back to either Postgresql (through your web-server backend) or, even easier still, to Geoserver as a REST request and write a simple SQL query that will return the distance using ST_Distance.  This would be a lot simpler than trying to implement the Haversine formula (so long as you remember to cast your coordinates as Geography types).  Geoserver would then return the distance as  JSON.


text:
Q: How to test the method that makes http request? I am writing tests in Laravel.
However, I am in trouble because I do not know how to test.
There is a method to make an http request as shown below.
How would you typically test this method?
Should I use a URL or mock that is actually accessible?
PHP 7.4.6
Laravel 7.0
<?php

namespace App\Model;

use Illuminate\Support\Facades\Http;
use Exception;

class Hoge
{
    public function getText(string $url, ?string $user, ?string $password, string $ua): bool
    {
        $header = ["User-Agent" => $ua];
        $httpObject = $user && $password ? Http::withBasicAuth($user, $password)->withHeaders($header) : Http::withHeaders($header);

        try {
            $response = $httpObject->get($url);
            if ($response->ok()) {
                return $response->body();
            }
        } catch (Exception $e) {
            return false;
        }

        return false;
    }
}

A: To create a new test case, you can use the make:test Artisan command:
php artisan make:test HogeTest

Then you can create your HogeTest, considering your headers are correct
<?php

namespace Tests\Feature;

use Tests\TestCase;

class HogeTest extends TestCase
{
    public function hogeExample()
    {
        $header = ["User-Agent" => $ua];
        $response = $this->withHeaders([
            $header,
        ])->json('POST', $url, ['username' => $user, 'password' => $password]);

        $response->assertStatus(200);
      // you can even dump response
      $response->dump();
    }
}

This is a simple example how you can use modify it as per your need.
See more in laravel docs

A: Functionality that reaches out to other systems can be slow and make tests brittle. Nevertheless, you want to be sure that your getText method works as expected. I would do the following:

*

*Create a set of integration tests just for your getText method. These tests make actual http requests to a server to verify the expected behaviors. The web server don't have to be an external system. You could use php's built in webserver to provide test urls. You can find an article here that guides you in that direction.

*For every other functionality that uses the getText method, I'd mock that method to keep the tests fast.

A: I prefer Postman for web server / API testing. https://www.postman.com/downloads/


text:
Q: Reading and multiplying sorted matrix I've got a problem concerning a few operations on two sorted matrices of size NxN.
Namely, the matrices are sorted in a way that every single row and every single column is sorted in an ascending order. My task is first to read two matrices and then to multiply them which should produce another sorted square matrix. In this result matrix I've got to make a search for an element, but the problem is with time complexity limitation which is O(n^2(lgn)), whereas typical multiplying algorithm is around O(n^3).
How can I look for elements simultaneously counting dynamically proper values? Could anyone help me to sort out this problem?  I've been struggling with it for a week or so and I still don't see a good solution for it.
I'll really appreciate any help from You!
Best regards!

A: Searching an element in a sorted matrix can be done in O(N) time.
1. Start from lower left corner of the matrix A[N-1][0] (i = N-1, j = 0).
2. If element is > A[i][j], go right (increment j).
3. If element is < A[i][j], go above (decrement i).
4. If element is == A[i][j], Stop with success.
5. If i < 0 or j == N, Stop with failure.

Now you want to search for an element in a matrix that is a product of two sorted matrices.
IMO It can be done in O(N^2) time overall!
Simply apply the above searching algorithm and calculate the matrix elements on the fly. Calculating each element takes O(N) time because you multiply a row with a column. Hence overall complexity of the algorithm shall be O(N^2).


text:
Q: How to identify the distribution when its moments are specified? I was reading my course notes and I came across this statement:

If we are given a set of moments, we can identify the distribution that they came from.

My question is: how do we identify the distribution when its moments are specified?

A: This is in no way a trivial question. So I will do my best in answering and filling the gap left by the previous comments. EDIT: I've had to remove links as I don't have the reputation to post them, please just search in google what is written.
It is firstly worth stating that the comment in your course notes

If we are given a set of moments, we can identify the distribution that they came from.

Is either implicitly assuming some rather strict conditions, or just plain wrong. In general it is not possible from a set of moments to determine a probability distribution.
Under certain extra conditions this is possible, a good discussion can be found
https://mathoverflow.net/questions/3525/when-are-probability-distributions-completely-determined-by-their-moments and
Do moments define distributions?
in the case of where you assume a parametric form of the probability distributions one can use the method of moments
(search method of moments wikipedia)
to determine the parameters of the distribution, this can be extended to semi-parametric and non-parametric distributions (where the number of parameters is allowed to grow with the data). Maybe this is what your course meant? However these methods are very restrictive and are very quickly either over or under-determined. I.e you either need more moments than you have, or you need to throw away valuable moment information.
One thing I have not seen on math stackexchange, maybe because this tends to be in the realm of Physicists and not Mathematicians, is the method of maximum entropy with moment constraints. Essentially the idea is, given a set of moments and no extra information, what is the best guess I can have for a probability distribution?
The answer is to maximize the functional
$S = \int p(x)\log p(x) dx - \sum_{i}\lambda_{i}[\int p(x)x^{i} - \alpha_{i}]$
For example, if we had a mean and variance constraint this would become
$S = \int p(x)\log p(x) dx - \alpha[\int p(x) - 1] - \beta[\int p(x)x - <x>] - \gamma[\int p(x)x^{2} - <x>^{2} - \sigma^{2}]$
Which when maximized gives us the normal distribution. Great references include the wikipedia article (search principle of maximum entropy wikipedia) and Jaynes where do we stand on Maximum entropy (where do we stand on maximum entropy jaynes on google), which is an absolute must read
My own research, unifies quantum field theory with statistical mechanics under the umbrella of independence in statistics. Furthermore the method works well in Machine learning for large matrix approximations. (Search Diego Granziol arxiv).

A: I'm about 6 years late, but I was trying to get a quick answer to this and thought others might benefit.
As another physicist answering, this is a well-known problem encountered in statistical field theory, particularly with regards to the Replica trick. There, you're trying to determine P(x) given that you know $\mathbb{E}_{x \sim P}[x^n]$ for integer N
The short answer can be found on page 214 of Kardar's Statistical Physics of Fields:

This [only knowing integer-valued moments $\mathbb{E}_{x \sim P}[x^n]$ for n integer] is one of the difficulties associated with the problem of deducing a probability distribution $P(x)$ from the knowledge of its moments $\mathbb{E}_{x \sim P}[x^n]$. There is in fact a rigorous theorem that the probability distribution cannot be uniquely inferred if its nth moment increases faster than n! [N.I. Akhlezer, The Classical Moment Problem (Oliver and Boyd, London, (1965)]


text:
Q: Controller to controller redirect in rails using AJAX I currently call a controller in rails that returns some HTML output like so
$(".certificate_request").click(function() {
    $(".request_holder").load("/generate_cert", function(){
        $(this).show();
    });

In my generate_cert controller, I want to then redirect to another controller, which also returns some html
The first bit works fine, so I added the redirect, and that (obviously) didn't work. After some research I also tried
render :js => "window.location = '/validate_cert'"

at the end of the controller but all this does is load 'window.location = '/validate_cert'' into my HTML and doesn't load the html.erb file related to the first call either
Am i going about this wrong, or is there a good way to do it?


text:
Q: AngularJS controller for a tab I have three tabs in my page. I'm using tabset and tab according to Angular Bootstrap Docs.
I set a controller for the
 which has the tabsetas

  <tabset  class="panel-body">
    <tab heading="Tab 1"> </tab>
    <tab heading="Tab 2"> </tab>
    <tab heading="Tab 3"> </tab>
  </tabset>

The corresponding page is
But, when I try to add another controller for my 2nd tab as

  <tabset  class="panel-body">
    <tab heading="Tab 1"> </tab>
    <tab heading="Tab 2" ng-controller="Tab2> </tab>
    <tab heading="Tab 3"> </tab>
  </tabset>

I now find that the heading is not displayed and I can no longer click the Tab2.
Why is that? How to get back the same functionality?
Is this the right way to add another controller in an existing controller?
My app.js :
var myApp = angular.module('myApp',['ui.bootstrap']);

myApp.controller('Tabs', function ($scope) {

});

myApp.controller('Tab2', function ($scope) {

});

A: I think there are at least three ways you could organize your controller code:

*

*Everything in one TabController

*Custom directive for each tab

*Add your tab logic to the tab callback function.

Please have a look at the demo below or here at jsfiddle.
It's the ui-bootstrap example code with the above mentioned points added.

angular.module('demoApp', ['ui.bootstrap'])
    .controller('TabsDemoCtrl', TabsController)
    .directive('sepecialTab', SpecialTab);

function TabsController($scope, $window) {
    $scope.tabs = [{
        title: 'Dynamic Title 1',
        content: 'Dynamic content 1'
    }, {
        title: 'Dynamic Title 2',
        content: 'Dynamic content 2',
        disabled: true
    }];

    $scope.alertMe = function () {
        setTimeout(function () {
            $window.alert('You\'ve selected the alert tab!');
        });
    };

    $scope.thirdTabCallback = function () {
        $scope.test = 'I\'m the third tab callback';

        $scope.clickme = function () {
            $window.alert('third tab only function');
        };
    };
}

function SpecialTab() {
    return {
        restrict: 'A',
        controller: function ($scope) {
            console.log('Special tab ctrl, runs on start.');
            $scope.hello = 'hello from special tab controller';
        }
    }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>

Select a tab by setting active binding to true:

        <button class="btn btn-default btn-sm" ng-click="tabs[0].active = true">Select second tab</button>
        <button class="btn btn-default btn-sm" ng-click="tabs[1].active = true">Select third tab</button>

        <button class="btn btn-default btn-sm" ng-click="tabs[1].disabled = ! tabs[1].disabled">Enable / Disable third tab</button>

    <tabset>
        <tab heading="Static title">Static content</tab>
        <tab heading="Static title 2" sepecial-tab="">Static content2 {{hello}}</tab>
        <tab heading="Static title 3" select="thirdTabCallback()">Static content3 {{test}}
            <button ng-click="clickme()">click me</button>
        </tab>
        <tab ng-repeat="tab in tabs" heading="{{tab.title}}" active="tab.active" disable="tab.disabled">{{tab.content}}</tab>
        <tab select="alertMe()">
            <tab-heading>  Alert!</tab-heading>I've got an HTML heading, and a select callback. Pretty cool!</tab>
    </tabset>

A: Here a custom directive to use in tabs, so I can use custom controllers for each tab.

angular.module('myModule', ['ui.bootstrap'])
  .directive('tabController', function() {
    return {
      restrict: 'A',
      controller: '@',
      name: 'tabController',
    }
  })
  .controller('MyCustomController', function() {
    var vm = this;
    vm.title = "Hey, I am The first controller";
  })
  .controller('MyCustomController2', function() {
    var vm = this;
    vm.title = "Hey, I am the second controller!";
  });

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

  <uib-tabset type="tabs">
    <uib-tab tab-controller="MyCustomController as ctrl">
      <uib-tab-heading>

      </uib-tab-heading>

    </uib-tab>
    <uib-tab tab-controller="MyCustomController2 as ctrl2">
      <uib-tab-heading>

      </uib-tab-heading>

    </uib-tab>

  </uib-tabset>


text:
Q: Cannot set property 'className' of null at setThemeFromCookie I am coding in WordPress to make a button to toggle body class from light-mode to dark-mode. i was experimenting with trying to add a cookie so that the preference is remembered for the browser. But i receive a error Cannot set property className of null at setThemeFromCookie.
moreover clicking the button gives another error (index):486 Uncaught TypeError: Cannot read property 'className' of null at togglePageContentLightDark
My url is https://milyin.com
you can see the button in blue color located in footer
JS follows
 function togglePageContentLightDark() {
      var body = document.getElementById('body')
      var currentClass = body.className
      var newClass = body.className == 'dark-mode' ? 'light-mode' : 'dark-mode'
      body.className = newClass

  document.cookie = 'theme=' + (newClass == 'light-mode' ? 'light' : 'dark')
  console.log('Cookies are now: ' + document.cookie)
}

function isDarkThemeSelected() {
  return document.cookie.match(/theme=dark/i) != null
}

function setThemeFromCookie() {
  var body = document.getElementById('body')
  body.className = isDarkThemeSelected() ? 'dark-mode' : 'light-mode'
}

(function() {
  setThemeFromCookie()
})();

HTML for button
<button type="button" name="dark_light" onclick="togglePageContentLightDark()" title="Toggle dark/light mode"></button>

i am fairly new to Java script and this code was taken from internet only. Please help me debug this code.

A: Using JQuery Simplifies the whole thing, using JS Cookie
$(document).ready(function(){

    // Check cookie and set theme
    if(Cookies.get('theme')) {

        $('body').removeClass('light-mode dark-mode').addClass( Cookies.get('theme') );

    };

    //Switch theme and create the cookie...

    $("#theme-toggler").click(function(){

         if ($('body').hasClass( 'light-mode')){
            $('body').removeClass('light-mode').addClass('dark-mode');
            Cookies.set('theme', 'dark-mode');

         }else  {
            $('body').removeClass('dark-mode').addClass('light-mode');
            Cookies.set('theme', 'light-mode');
         }

     });

});

Add id to button.
<button id="theme-toggler" type="button" name="dark_light"  title="Toggle dark/light mode"></button>

Also add this script
<script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

A: var body = document.getElementById('body') is your problem.  The document's body is not an id, it's a tag.  Use var body = document.querySelector('body');