text:
Q: Should we use useCallback in every function handler in React Functional Components let's say we have the components like this
const Example = () => {
  const [counter, setCounter] = useState(0);

  const increment = () => setCounter(counter => counter + 1);
  return (

      <Button onClick={increment} />

{counter}

  );
}

When I passed the onClick handler as an arrow function, my eslint throw a warning:
error    JSX props should not use arrow functions        react/jsx-no-bind

As I read from an answer from this post: https://stackoverflow.com/questions/36677733/why-shouldnt-jsx-props-use-arrow-functions-or-bind#:~:text=Why%20you%20shouldn't%20use,previous%20function%20is%20garbage%20collected.
The short answer is because arrow function is recreated every time, which will hurt the performance.
One solution proposed from this post is to wrapped in a useCallback hook, with empty array. And when I change to this, the eslint warning really disappear.
const Example = () => {
  const [counter, setCounter] = useState(0);

  const increment = useCallback(() => setCounter(counter => counter + 1), []);

  return (

      <Button onClick={increment} />

{counter}

  );
}

However, there is also another opinion saying that overusing useCallback will eventually slowdown the performance due to the overheads of useCallback. One example is here: https://kentcdodds.com/blog/usememo-and-usecallback
This is making me really confused? So for Functional Components, when dealing with inline function handler, should I just write the arrow function (ignore the eslint) or always wrap it in a useCallback ???

A:
The short answer is because arrow function is recreated every time, which will hurt the performance.

This is a common misconception. The arrow function is recreated every time either way (although with useCallback subsequent ones may be thrown away immediately). What useCallback does is make it possible for the child component you use the callback on to not re-render if it's memoized.
Let's look at the misconception first. Consider the useCallback call:
const increment = useCallback(() => setCounter(counter => counter + 1), []);

That's executed like this:

*

*Evaluate the first argument, () => setCounter(counter => counter + 1), creating a function

*Evaluate the second argument, [], creating an array

*Call useCallback with those two arguments, get back a function
Compare with what you have if you don't use useCallback:
const increment = () => setCounter(counter => counter + 1);

That's much simpler: Create the function. It doesn't then have to do #2 and #3 above.
Let's move on to what useCallback actually does that's useful. Let's look at where the callback is used:
<Button onClick={increment} />

Now, suppose Button is memoized with React.memo or similar. If increment changes every time your component renders, then Button has to re-render every time your component changes; it can't be reused between renders. But if increment is stable between renders (because you used useCallback with an empty array), the memoized result of calling Button can be reused, it doesn't have to be called again.
Here's an example:

const { useState, useCallback } = React;

const Button = React.memo(function Button({onClick, children}) {
    console.log("Button called");
    return <button onClick={onClick}>{children}</button>;
});

function ComponentA() {
    console.log("ComponentA called");
    const [count, setCount] = useState(0);
    // Note: Safe to use the closed-over `count` here if `count `updates are
    // triggered by clicks or similar events that definitely render, since
    // the `count` that `increment` closes over won't be stale.
    const increment = () => setCount(count + 1);
    return (

            {count}
            <Button onClick={increment}>+</Button>

    );
}

function ComponentB() {
    console.log("ComponentB called");
    const [count, setCount] = useState(0);
    // Note: Can't use `count` in `increment`, need the callback form because
    // the `count` the first `increment` closes over *will* be slate after
    // the next render
    const increment = useCallback(
        () => setCount(count => count + 1),
        []
    );
    return (

            {count}
            <Button onClick={increment}>+</Button>

    );
}

ReactDOM.render(

        A:
        <ComponentA />
        B:
        <ComponentB />

,
    document.getElementById("root")
);

Note that clicking the button in ComponentA always calls Button again, but clicking the button in ComponentB doesn't.
When do you want to do that? That's largely up to you, but it probably makes sense when your component's state will change frequently in ways that don't affect the contents of increment and thus don't affect Button and if Button has to do significant work when rendered. Button probably doesn't, but other child components may.
For instance, the useCallback in my previous example is probably pointless if you use count as the text of the button, since that means Button has to re-render regardless:

const { useState, useCallback } = React;

const Button = React.memo(function Button({onClick, children}) {
    console.log("Button called");
    return <button onClick={onClick}>{children}</button>;
});

function ComponentA() {
    console.log("ComponentA called");
    const [count, setCount] = useState(0);
    // Note: Safe to use the closed-over `count` here if `count `updates are
    // triggered by clicks or similar events that definitely render, since
    // the `count` that `increment` closes over won't be stale.
    const increment = () => setCount(count + 1);
    return (

            <Button onClick={increment}>{count}</Button>

    );
}

function ComponentB() {
    console.log("ComponentB called");
    const [count, setCount] = useState(0);
    // Note: Can't use `count` in `increment`, need the callback form because
    // the `count` the first `increment` closes over *will* be slate after
    // the next render
    const increment = useCallback(
        () => setCount(count => count + 1),
        []
    );
    return (

            <Button onClick={increment}>{count}</Button>

    );
}

ReactDOM.render(

        A:
        <ComponentA />
        B:
        <ComponentB />

,
    document.getElementById("root")
);

Also note that useCallback isn't free, it impacts the code in the callback. Look at the code in the callbacks in ComponentA and ComponentB in the examples. ComponentA (which doesn't use useCallback) can use the value of count that it closes over (within limits!), () => setCount(count + 1). But the one in ComponentB always has to use the callback form of the setter, () => setCount(count => count + 1). That's because if you keep using the first increment you create, the count it closes over will be stale — you'd see the count go to 1, but never further.

A final note: If you're re-rendering a component so often that creating and throwing away the various functions you're passing to useCallback or useMemo may be causing too much memory churn (a rare situation), you can avoid it by using a ref. Let's look at updating ComponentB to using a ref instead of useCallback:
const incrementRef = useRef(null);
if (!incrementRef.current /* || yourDependenciesForItChange*/) {
    // Note: Can't use `count` in `increment`, need the callback form because
    // the `count` the first `increment` closes over *will* be slate after
    // the next render
    incrementRef.current = () => setCount(count => count + 1);
}
const increment = incrementRef.current;

That only creates the increment function once (in that example, since we don't have any dependencies), it doesn't create and throw away functions like using useCallback does. It works because the initial value of the ref is null, and then the first time the component function is called, we see that it's null, create the function, and put it on the ref. So increment is only created once.
That example does recreate the function we pass setCount every time increment is called. It's possible to avoid that, too:
const incrementRef = useRef(null);
if (!incrementRef.current) {
    // Note: Can't use `count` in `increment`, need the callback form because
    // the `count` the first `increment` closes over *will* be slate after
    // the next render
    const incrementCallback = count => count + 1;
    incrementRef.current = () => setCount(incrementCallback);
}
const increment = incrementRef.current;

const { useState, useRef } = React;

const Button = React.memo(function Button({onClick, children}) {
    console.log("Button called");
    return <button onClick={onClick}>{children}</button>;
});

function ComponentA() {
    console.log("ComponentA called");
    const [count, setCount] = useState(0);
    // Note: Safe to use the closed-over `count` here if `count `updates are
    // triggered by clicks or similar events that definitely render, since
    // the `count` that `increment` closes over won't be stale.
    const increment = () => setCount(count + 1);
    return (

            {count}
            <Button onClick={increment}>+</Button>

    );
}

function ComponentB() {
    console.log("ComponentB called");
    const [count, setCount] = useState(0);
    const incrementRef = useRef(null);
    if (!incrementRef.current) {
        // Note: Can't use `count` in `increment`, need the callback form because
        // the `count` the first `increment` closes over *will* be slate after
        // the next render
        const incrementCallback = count => count + 1;
        incrementRef.current = () => setCount(incrementCallback);
    }
    const increment = incrementRef.current;
    return (

            {count}
            <Button onClick={increment}>+</Button>

    );
}

ReactDOM.render(

        A:
        <ComponentA />
        B:
        <ComponentB />

,
    document.getElementById("root")
);

That's really going to 11 in terms of avoiding unnecessary function creation. :-)
It's a rare component that needs even that first level of optimization, much less the second level; but when/if you do, that's how you do it.


text:
Q: What the best way to check if an Android application is in foreground? I have an application that uses AsyncTasks to make REST calls to a server. Whenever the AsyncTask is finished, it either: shows an error dialog/calls the next activity (if the application is in foreground) or does nothing (application is in background).
I do this to avoid having an activity poping out after the application is sent to background.
I've seen some implementations:

*

*check android application is in foreground or not?

*Determining the current foreground application from a background task or service
Currently i'm using another, even simpler:

*

*onResume of each activity I set a global variable as FOREGROUND

*onPause of each activity I set a global variable as BACKGROUND

Which would you recommend?
PS
I am aware of the best practice of REST calls as described in this video https://www.youtube.com/watch?v=xHXn3Kg2IQE&list=PL73AA672847DC7B35 and in my specific case this approach seems more appropriate.

A: private boolean isAppForground() {

        ActivityManager mActivityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> l = mActivityManager
                .getRunningAppProcesses();
        Iterator<RunningAppProcessInfo> i = l.iterator();
        while (i.hasNext()) {
            RunningAppProcessInfo info = i.next();

            if (info.uid == getApplicationInfo().uid && info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND)
                {
                    return true;
               }
           }
        return false;
    }

A: I ended up having a static variable that every Activity sets to true on onResume and to false on onPause.
Added these methods on an Activity that all other activities extend:
    public abstract class AbstractActivity extends Activity
    {

     private static boolean isInForeground = false;

     @Override
      protected void onResume()
     {
        super.onResume();
        isInForeground = true;
    }

    @Override
    protected void onPause()
    {
        super.onPause();
        isInForeground  = false;
    }

 }

To understand why it works: Activity side-by-side lifecycle
This will give me the information if MY APP is on foreground or background.
But still Shailendra Rajawat is the more standard option... because this has some weaknesses:

*

*It only works to know if MY OWN app is in foreground or background

*It doesn't work if you have transparent activities. Because the lifecycle will not be the same, the onPause/onStop won't be called when a transparent activity is started.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any way to detect two kinds of objects from an image or video using two seperate trained weight files in **YoloV5**? I had trained a weight file to detect an object and another weight file to detect another specific object using yolov5. If i want to detect both objects in a single images, can i ,like, use both weight files together? Or is there a way to combine the both trained files into a single one, without training the datasets again together?

A: Actually, no. There is no way to aggregate models, trained to detect different objects into one. You can sequentially detect objects by first and second model. Proper approach is to train model again with two classes.


text:
Q: Codeigniter multiple controllers I'm creating a todo list with registration. I named my default controller main and use it to register/login, on localhost the index page looks like http://localhost/todo/main/  however, after logging in I don't want to show localhost/main/todolist  but rather localhost/todolist  do I have to create a new controller for that? Is it practical to use multiple controllers in CI?
My routes.php now is
$route['default_controller'] = 'main';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;

A: <?php

  public function login_validation(){
    $this->load->library('form_validation');

    $this->form_validation->set_rules('email','Email','required|trim|callback_validate_credentials');
    $this->form_validation->set_rules('password','Password','required|md5|trim');

    /*******************************
     Little modification so that i'll come in this block if form has everything right in it
    **********************************/
    if($this->form_validation->run() !== FALSE){

     /******************
      Also you should now check these user inputs against DB values to make sure if this user exists. you may use e.g
      ***************/
       $result = $this->db->get_where('table_name',array('table_colum',$this->input->post('form_field_name')))->row();
     if($result)
     {
        $data = array(
            'username'=>$this->input->post('username'),
            'email'=>$this->input->post('email'),
            'is_logged_in'=> 1
            );
        $this->session->set_userdata($data);

        // This should be the new controller where you want to take
        // your user but by passing its ravelent data, you can do it like

         redirect('lists',$data);
       //create new controller and put that name here for 'lists'
    } else {
        $this->load->view('login');
    }

}


text:
Q: Typeset book for children I am working (writing and typesetting) on a book for children. I have used the memoir class. The book looks good for an adult audience. But I had ideas of making it more interesting for the children.
More specifically, how about adding little thumbnails to the table of contents page? These will be tiny images placed randomly and rotated randomly.
Or a different pattern border around each page? Like bright colored zigzag pattern for one page and may be, colored crayon strips on another?
With my limited experience and expertise in latex, I could not crack this one.
Any ideas/ suggestions/ solutions?


text:
Q: How to create india map chart using Hightcharts? I want to generate reports in Graph. Suppose I want to see my sales in all over india. I want to see in india map chart. So I would be able to see this state sales is this much and so on. I have generated bar chart, pie chart and line chart using Hight Charts. But now I want to generate map chart. But I am not getting how to go through it.

A: HighCharts has some pre-alpha proof of concepts on doing heat maps (or choropleth). See this post here. It is not in main released version.
Now, you could use any number of other JS libraries to do this. There are essentially 3 steps:

*

*Get mapping data as SVG (or some other format). These are the
shapefiles used to draw the outlines of the geographic features you
want.

*In these mapping shapefiles there is an ID associated that is
unique to it. Now assign your data values to this ID/area.

*Using D3, raphael, etc draw the shapefiles and link the data. If you have large amounts of cash laying around you can give it to ESRI to purchase ESRI ArcGIS.


text:
Q: Grab first two sentences (untill second dot) of a text string with jQuery? I have this HTML (as an example - Texts can vary in length):

Stockholm is a city in Sweden. Moscow is a city in Russia. Here is Berlin, it's the capital of Germany.

I want to grab the first two sentences of this text and extract them, using JavaScript/jQuery. Further more I also want to extract the rest of the text and put this into its own element.
So basically i want to end up with the following:

Stockholm is a city in Sweden. Moscow is a city in Russia.

and

Here is Berlin, it's the capital of Germany.

So far I am only able to get the first sentence of the text using the following:
var addy = jQuery('#myDiv > p').html();
var introText = addy.slice(0, addy.indexOf("."));

This puts out: "Stockholm is a city in Sweden" - Without the dot aswell. I would also like to have this included.
As stated in the intro, the texts are dynamic and vary in length.
How can I achieve the above?
Thanks in advance!

A: One option is:
$('#myDiv > p').each(function() {
   var ss = this.textContent.split('.');
   var f = ss.slice(0, 2).join('.');
   var s = ss.slice(2).join('.');

   $(this).text(f);
   $('
').text(s).insertAfter(this);
})

http://jsfiddle.net/0xh5ku4f/

A: You can use a function to get the second index at which there is a dot, and then split the string at that index:

let str = "
Stockholm is a city in Sweden. Moscow is a city in Russia. Here is Berlin, it's the capital of Germany.
"

let index = nthIndex(str, ". ", 2);

let parts = [str.substring(0, index+1)+"
" ,"
"+str.substring(index+2)]

console.log(parts)

function nthIndex(str, pat, n){
    var L= str.length, i= -1;
    while(n-- && i++<L){
        i= str.indexOf(pat, i);
        if (i < 0) break;
    }
    return i;
}


text:
Q: In VB with classic ASP will local variable hides the Global declaration if variable names are similar I am working on classic ASP and I have declared a variable abc as Global variable and I also declare another variable within the scope of function the same variable abc in vb will local variable hides the Global declaration?
Following is the way i declared local variable:
Sub TestFunction()
  dim abc
  abc = GetItem()
End Sub

A: Short answer is
<%
dim test
test = "hello"

sub tryme
  response.write test & " - 1
"
  dim test
  response.write test & " - 2
"
  test = "hello2"
  response.write test & " - 3
"
end sub

  response.write test & " - 0
"
call tryme
  response.write test & " - 4
"
%>

output:
hello - 0
- 1
- 2
hello2 - 3
hello - 4

A: The answer is yes, take this example;
'Global Scope
Dim abc
abc = 1

Call Response.Write(Test1() & "
") 'Will output 2
Call Response.Write(Test2() & "
") 'Will output 1

'Change global variable value.
abc = 2

'Local variable abc will not be affected by the global variable value change.
Call Response.Write(Test1() & "
") 'Will output 2
Call Response.Write(Test2() & "
") 'Will output 3

Function Test1()
  'Local Scope
  Dim abc
  abc = 2
  Test1 = abc
End Function

Function Test2()
  Test2 = abc
End Function

Output will be;
2
1
2
3

Any locally declared variable that matches the name of a global variable will take precedent. They are in no way connected and changing the local variable abc will never affect the value of global variable abc.

Useful links

*

*MSDN - Using Variables and Constants


text:
Q: Visual Studio 2019 Solutions Explorer Blank and Not Showing Files Stored on Network In a nutshell my computer had to be re-imaged and after reinstall when I open Visual Studio 2019 I no longer see the network folders where we stored our working files.  I can access the individual files through the file menu but I was hoping to see the "tree map" in solutions like I had before. Strangely, when I open files in the main folder nothing happens in solution explorer.  When I open files from a subfolder then solution explorer will "populate".
I hope this explanation makes some sense as I am faenter image description hereirly new to this and trying to restore the setup like I had before the imaging was done.


text:
Q: Can anyone help me on where i can start on trying to draw a graph like this in latex? I played around with tikz-network package but I can't seem to find a way to replace edges with dots and the positioning is a bit weird as well

\usepackage{tikz-network}
\begin{tikzpicture}
\Vertex[x=7,y=-12,label=$v_0$]{A}\Vertex[x=8.5,y=-10]{B}\Vertex[x=8.8,y=-8]{C}\Vertex[x=7,y=-6]{D}\Vertex[x=4,y=-10]{E}
\Edge[bend=-20,label=$0^{s_0}$,position=below](A)(B)
\Edge[bend=-10,label=$1^{s_1}$,position=right](B)(C)
\Edge[bend=-10,label=$2^{s_2}$,position=top](C)(D)
\Edge[bend=-45,label=$\dots$,position=left](D)(E)
\Edge[bend=-45,label=$(d-1)^{s_{d-1}}$,position=left](E)(A)
\Vertex[x=3,y=-15]{B1}\Vertex[x=3,y=-17]{C1}\Vertex[x=4.5,y=-19]{D1}\Vertex[x=7.5,y=-16]{E1}
\Edge[bend=-20,label=$0^{s_0}$,position=below](A)(B1)
\Edge[bend=-5,label=$1^{s_1}$,position=right](B1)(C1)
\Edge[bend=-19,label=$2^{s_2}$,position=top](C1)(D1)
\Edge[bend=-25,label=$\dots$,position=left](D1)(E1)
\Edge[bend=-25,label=$(d-1)^{s_{d-1}}$,position=left](E1)(A)
\Vertex[x=9,y=-13.5]{B2}\Vertex[x=12,y=-13.8]{C2}\Vertex[x=14.5,y=-12.5]{D2}\Vertex[x=13.5,y=-11]{E2}
\Edge[bend=-20](A)(B2)
\Edge[bend=-5,label=\text{Loop m},position=below](B2)(C2)
\Edge[bend=-19](C2)(D2)
\Edge[bend=-25](D2)(E2)
\Edge[bend=-25](E2)(A)
\end{tikzpicture}

\end{document}

A: \documentclass[border=1cm]{standalone}
\usepackage{tikz-network}

\begin{document}
\begin{tikzpicture}
    \Vertex[x=7,y=-12,label=$v_0$]{A}\Vertex[x=8.5,y=-10]{B}\Vertex[x=8.8,y=-8]{C}\Vertex[x=7,y=-6]{D}\Vertex[x=4,y=-10]{E}
    \Edge[bend=-20,label=$0^{s_0}$,position=below](A)(B)
    \Edge[bend=-10,label=$1^{s_1}$,position=right](B)(C)
    \Edge[bend=-10,label=$2^{s_2}$,position=top](C)(D)
    \Edge[style=dashed,bend=-45,label=$\dots$,position=left](D)(E)
    \Edge[bend=-45,label=$(d-1)^{s_{d-1}}$,position=left](E)(A)
    \Vertex[x=3,y=-15]{B1}\Vertex[x=3,y=-17]{C1}\Vertex[x=4.5,y=-19]{D1}\Vertex[x=7.5,y=-16]{E1}
    \Edge[bend=-20,label=$0^{s_0}$,position=below](A)(B1)
    \Edge[bend=-5,label=$1^{s_1}$,position=right](B1)(C1)
    \Edge[bend=-19,label=$2^{s_2}$,position=top](C1)(D1)
    \Edge[style=dashed,bend=-25,label=$\dots$,position=left](D1)(E1)
    \Edge[bend=-25,label=$(d-1)^{s_{d-1}}$,position=left](E1)(A)
    \Vertex[x=9,y=-13.5]{B2}\Vertex[x=12,y=-13.8]{C2}\Vertex[x=14.5,y=-12.5]{D2}\Vertex[x=13.5,y=-11]{E2}
    \Edge[bend=-20](A)(B2)
    \Edge[bend=-5,label=\text{Loop m},position=below](B2)(C2)
    \Edge[bend=-19](C2)(D2)
    \Edge[bend=-25](D2)(E2)
    \Edge[bend=-25](E2)(A)
\end{tikzpicture}

\end{document}


text:
Q: How to make the printing output starts from right to left? I'm pretty new in programming and I making a decimal to binary converter. I need help to make the print output starts from right to left (reversed).(Sorry if my code is messy)
int main()
{
    int num, form;

    printf("Decimal to Binary\n\n");
    printf("        Value          : ");
    scanf("%d", &num);
    printf("        Expected Format (Type 2 for binary): ");
    scanf("%d", &form);
    if (form == 2)
        printf("        %d base 10 is ", num);
    if (form == 2)
        do {
            if (num % 2 == 0) {
                printf("0");
                num = num / 2;
            }
            else {
                printf("1");
                num = num / 2;
            }
        } while (num > 0);
    else
        printf("Invalid input!");

    return 0;
}

If I input the value to 25,I expected the output will be "11001", but the actual output is "10011"

A: Some recursion.. It's looks much more better, for my opinion
#include <stdio.h>

void rec(int num)
{
    if (num==0) return;
    rec(num>>1);
    printf("%d", num%2);
}

int main()
{
  int n;

  printf("Enter an integer in decimal number system\n");
  scanf("%d", &n);
  printf("%d in binary number system is: ", n);

  rec(n);

  printf("\n");
  return 0;
}

A: One possibility would be recursion as Jean-Francois Fabre said. Since you mentioned you are a beginner, recursions are sometimes hard to understand at the beginning, so another possibility that I didn't find in his link would be something like this
#include <stdio.h>

int main()
{
  int n, c, k;

  printf("Enter an integer in decimal number system\n");
  scanf("%d", &n);

  printf("%d in binary number system is:\n", n);

  for (c = 8; c >= 0; c--)
  {
    k = n >> c;

    if (k & 1)
      printf("1");
    else
      printf("0");
  }

  printf("\n");

  return 0;
}

You can use c to specify the length of your output, or calculate in advance to have a perfect output.


text:
Q: Django Application I have finished coding a Django App. In that app I have created two models in order to record some project information. Also I am showing project locations with markers on a map (OpenStreetMap) by using leaflet.js.
I will use this app only by starting an offline server like "python manage.py runserver". I am using "Firefox" to display the django app.
I really wonder if somehow the information that I keep in my django models or the markers on the OpenStreetMap is somehow reachable by others via on Firefox or leaflet.
Thank you very much in advance.

A: If you are in the same wi-fi network you can run python manage.py runserver 0.0.0.0:8000 and then your application will be visible for everybody by typing http://your-pc-up:8000
If you want to make it public you have to buy domain (or register free domain) and put it in your vpc / free hosting. There are plenty of tutorial out there which show how to host an application.
This tutorial is really easy and straight forward: http://michal.karzynski.pl/blog/2013/06/09/django-nginx-gunicorn-virtualenv-supervisor/

A: You can use ngrok service which gives you domain such as https://c2757c5f.ngrok.io and other users can visit it by accessing this url. In addition, this url can be visited from anywhere!
See more details by visiting here
If you want other users can visit you website from you local server, then you can run manage.py runserver 0.0.0.0:8000. Your app is visible to other users on same network by accessing this http://your-ip:8000/
You could know you ip by using ifconfig command on linux or ubuntu


text:
Q: ConcurrentDictionary.GetOrAdd when valueFactory has side-effects I'm trying to offload work from my database server by introducing a cache layer for some very central functions that insert a value to a table in the database and retrieves the id. This is in a multi-threaded environment.
My first approach was:
public class Cache {
      private Dictionary<string, Int64> i;

      public void Init() { /* init i with values from DB */ }

      public Int64 Get(string value)
         lock(i) {
            Int64 id;
            if (cache.i.TryGetValue(value, out id))
                return id;

            id = /* Insert to DB and retrieve ID */
            cache.i[value] = id;
            return id;
      }
 }

This helped. However the threads still wait a lot for each other. I'd like to reduce this waiting time. My first thought was to use ConcurrentDictionary.GetOrAdd(key, valueFactory). This would not work because valueFactory could be called more than once.
I've wound up at this approach:
public class Cache
{
    private ConcurrentDictionary<string, Int64> i;

    public void Init() { /* init i with values from DB */ }

    public Int64 Get(string value)
    {
        Int64 id;
        if (i.TryGetValue(value, out id))
            return id;

        lock (i)
        {
            if (i.TryGetValue(value, out id))
                return id;

            id = /* Insert to DB and retrieve ID */
            i.TryAdd(value, id);
            return id;
        }
    }

Is there a better way of doing this? Is this even thread-safe?

A: What you're trying to do is lazily create an object that needs to be created no more than once and then accessed by any number of threads once created.  Lazy is designed for exactly this:
public class Cache
{
    private ConcurrentDictionary<string, Lazy<long>> i;

    public void Init() { /* init i with values from DB */ }

    public Int64 Get(string value)
    {
        return i.GetOrAdd(value, new Lazy<long>(() =>
            CreateDatabaseRecordAndGetId()))
            .Value;
    }

    private long CreateDatabaseRecordAndGetId()
    {
        throw new NotImplementedException();
    }
}

A: Just FYI, in Servy's example you get an instance of Lazy created for every call to GetOrAdd. Now, the magic of Lazy still happens, and you only get one call to your Func that creates your instance. But maybe the extra instantiations of Lazy in the above example explain the memory increase you saw when you tried it.
If you create a "double" lambda, you don't get multiple instantiations of Lazy.
E.g. paste this into a console app and compare the implementation with and without the x => new Lazy... below:
public static class LazyEvaluationTesting
{
    private static readonly ConcurrentDictionary<int, CustomLazy<CacheableItem>>
        cacheableItemCache = new ConcurrentDictionary<int, CustomLazy<CacheableItem>>();

    private static CacheableItem RetrieveCacheableItem(int itemId)
    {
        Console.WriteLine("--RETRIEVE called\t ItemId [{0}] ThreadId [{1}]", itemId, Thread.CurrentThread.ManagedThreadId);
        return new CacheableItem
        {
            ItemId = itemId
        };
    }

    private static void GetCacheableItem(int itemId)
    {
        Console.WriteLine("GET called\t ItemId [{0}] ThreadId [{1}]", itemId, Thread.CurrentThread.ManagedThreadId);

        CacheableItem cacheableItem = cacheableItemCache
            .GetOrAdd(itemId,
                x => new CustomLazy<CacheableItem>(
                    () => RetrieveCacheableItem(itemId)
                )
            ).Value;

        //CacheableItem cacheableItem2 = cacheableItemCache
        //  .GetOrAdd(itemId,
        //      new CustomLazy<CacheableItem>(
        //          () => RetrieveCacheableItem(itemId)
        //      )
        //  ).Value;
    }

    public static void TestLazyEvaluation()
    {
        int[] itemIds = { 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5 };
        ParallelOptions options = new ParallelOptions
        {
            MaxDegreeOfParallelism = 75
        };

        Parallel.ForEach(itemIds, options, itemId =>
        {
            GetCacheableItem(itemId);
            GetCacheableItem(itemId);
            GetCacheableItem(itemId);
            GetCacheableItem(itemId);
            GetCacheableItem(itemId);
        });
    }

    private class CustomLazy<T> : Lazy<T> where T : class
    {
        public CustomLazy(Func<T> valueFactory)
            : base(valueFactory)
        {
            Console.WriteLine("-Lazy Constructor called  ThreadId [{0}]", Thread.CurrentThread.ManagedThreadId);
        }
    }

    private class CacheableItem
    {
        public int ItemId { get; set; }
    }
}

Source: Reed Copsey's Blog


text:
Q: How to Create a dropdown Button with see more option and on click toggle should not happen in react js? I want to add see more option to fetch data
import React, { useState } from 'react';
import { Dropdown, DropdownToggle, DropdownMenu, DropdownItem } from 'reactstrap';

const Example = (props) => {
  const [dropdownOpen, setDropdownOpen] = useState(false);

  const toggle = () => setDropdownOpen(prevState => !prevState);

  return (
    <Dropdown isOpen={dropdownOpen} toggle={toggle}>
      <DropdownToggle caret>
        Dropdown
        </DropdownToggle>
      <DropdownMenu>
        <DropdownItem header>Header</DropdownItem>
        <DropdownItem>Some Action</DropdownItem>
        <DropdownItem>Some Action</DropdownItem>
        <DropdownItem onClick={(e) => {this.showAllData(e)} }>See Action</DropdownItem>
      </DropdownMenu>
    </Dropdown>
  );
}

export default Example;

I Just want to fetch more data on click of dropdown item without closing dropdown, can anyone give to solution to figure out this.

A: just keep toggle={false} for dropdown item
<DropdownItem toggle={false} onClick={(e) => {this.showAllData(e)} }>See Action</DropdownItem>


text:
Q: Connect GIATA hotel mapping with postman I am trying to use GIATA multi-codes for hotels mapping but they have HTTP Basic authentification when i type url like this https://multicodes.giatamedia.com/webservice/rest/1.0/properties/country/US  pop up appears to write my username and password but how to work with that using api request with postman for example
I tried adding username:password@url but still doesn't work with me

A: In each tab to make a request, you have an "Authorization" tab. Normally, a page protected by an .htpasswd is only a basic authentication.
Have you tried in the "Authorization" tab to choose the type "Basic Auth" and put your username and password in it?

A: You have to build a username as follows:
The user name for authentication consists of the name of the user (usually the first part of the email address before "@") + | (Pipe) + the company name.
Thus access is granted using:
User name
testUser|testCompany

Password
testPw

For example: user|company.com


text:
Q: Using WYSIWYG In custom meta boxes So I've created a few meta boxes using the wp_editor, all are exactly as the following:
add_action( 'add_meta_boxes', 'business_facts_metabox' );
function business_facts_metabox()
    {
        add_meta_box('business_facts', 'Business Facts', 'business_facts_output', 'page', 'normal', 'high');
    }

function business_facts_output( $post )
    {
    //so, dont ned to use esc_attr in front of get_post_meta
    $business_facts_value=  get_post_meta($_GET['post'], 'business_facts' , true ) ;
    wp_editor( htmlspecialchars_decode($business_facts_value), 'business-facts', $settings = array('textarea_name'=>'business-facts') );
    }

function save_business_facts( $post_id )
{
    if (!empty($_POST['business-facts']))
        {
        $data=htmlspecialchars($_POST['business-facts']);
        update_post_meta($post_id, 'business_facts', $data );
        }
}
add_action( 'save_post', 'save_business_facts' );

Unfortunately, when I output what is saved, it outputs everything, so it doesn't show bolds, instead if I were to output a bold word, it would output word, instead of word. I need it to output properly with styling and html working properly.
Is this possible using custom metaboxes? if so, what do I need to edit in my code?

A: So I figured this out almost immediately after posting this question (duh)
function business_facts_output( $post )
    {
    //so, dont ned to use esc_attr in front of get_post_meta
    $business_facts_value=  get_post_meta($_GET['post'], 'business_facts' , true ) ;
    wp_editor( htmlspecialchars_decode($business_facts_value), 'business-facts', $settings = array('textarea_name'=>'business-facts') );
}

Basically this bit here, where it says htmlspecialchars_decode($business_facts_value) needs to be changed. the htmlspecialchars_decode() function isn't needed here, instead I just needed the $business_facts_value


text:
Q: Xinu boot in VM I want to learn something about OS and networking with Xinu. I downloaded the source code from the xinu-os repo on github (up to 4d489eead3a49170f69041b959bd5a1bd8dff92d) and compiled xinu.boot and xinu.elf myself. To really get down to it, I wanted to do some modify-and-test. So my goal (and also the goal of this question) was to boot xinu in VBox.
To explain things a bit, I know that on the Xinu Page, there is a Versions of Xinu for a VM along with instructions item under the Code Available For Download section, which includes a VBox version (I will refer to it as the VBox version below). The reason I do not want to use that version is that it does not include as many features as in the code in github. I also know that there is a boot.xinu-os.org project in github, which advertises to be able to boot xinu in a javascript PC emulator. The reason I do not want to use that is because there seems to be some limitations, and I thought there could be more problems than the conventional way (maybe not). So I thought I could compile my own binaries with the code from the xinu-os repo, and easily ran them in a similar way as the VBox version in VBox, but I seemed to be wrong.
The VBox version from the Xinu page is using pxe and grub to boot. What I did was the following:

*

*I cloned from the xinu-os repo.

*I followed the Multiboot Specification#OS-image-format, and added the required header to the end of _start, to make the binary multiboot-compliant:
/* /xinu/loader/platforms/x86/start.S
 * ...
 * #define     MULTIBOOT_HEADER_MAGIC  0x1BADB002
 * #define     MULTIBOOT_HEADER_FLAGS  0x00000003
 * _start:
 * ...
 */
jmp     startup

/* Enable multiboot support */
.align  4
.long   MULTIBOOT_HEADER_MAGIC
.long   MULTIBOOT_HEADER_FLAGS
.long   -(MULTIBOOT_HEADER_MAGIC + MULTIBOOT_HEADER_FLAGS)

*I built my Xinu.boot and Xinu.elf out of the modified code.

*I set up minicom as instructed, and successfully booted the VBox version.

*I examined the Xinu.boot used in the VBox version, and found that it was an 32bit elf for i386, but the Xinu.boot I built with the Makefile was made from objcopy, while the Xinu.elf was an elf. So I renamed Xinu.elf I built to Xinu.boot, and substituted it for that in the VBox version.

*Then I tried to boot with the same files except the Xinu.boot, in the same environment.

*It failed, and grub gave me the grub commandline. I also tried using a debug version. It failed too, but before it showed the grub commandline, it displayed a message "Unknown command: r(0, 1)".

So my major question is what is the fundamental difference between my Xinu.boot and that in the VBox version that prevents mine from pxe booting? Can anyone shed some light on it?
It took me a lot of readings and experiments to get there. My goal is still to run the Xinu I built myself, modify and test it. It does not need to be boot with pxe, but I hope I can run it in VBox rather than on some real hardware. My other questions are:

*

*Is there any alternative (and easier) way to run xinu in VBox or a virtual machine?

*How is the grub shipped in the VBox version configured to find Xinu.boot to boot? Because I tried to search for xinu in the files, but got nothing.

*What does the message "Unknown command: r(0, 1)" mean, and is it grub or xinu emitted it?

*How should I debug such a system? I tried to insert some kprintf in the start.S, but got nowhere. I also tried to gdb Xinu.elf, but it gave me a segmentation fault after running a few instructions. And why it cannot be debugged in gdb? (I am a newbie to assembly. So please explain.)

*Is there any reliable Xinu community or mailing-list for this kind of questions?

I know my questions may be special and complex, and I am so awkward to express them in English. Any help will be greatly appreciated! Thanks in advance!

A: After quite a lot of reading, now I can successfully run the github version xinu in QEMU. This is how I did it:

*

*The github version xinu has little to change to be run in QEMU. Adding the multiboot header as described in my question is required.

*After making, run with xinu with:
qemu-system-i386 -kernel xinu.elf

*When QEMU runs, it will stop at a screen showing "Booting from ROM...". Then press CTRL-ALT-3, there will you find it!

Booting with QEMU, you skip grub, together with any issues grub causes.
QEMU also makes it convenient for debugging. If you run xinu with:
qemu-system-i386 -s -S -kernel xinu.elf

QEMU will start and pause before any instruction is run (check the QEMU manual for more details about the parameters). Then, you can start gdb and attach to it by:
gdb xinu.elf

And after gdb starts, issue:
target remote localhost:1234

You will attach gdb onto the QEMU process running xinu. You can do whatever you normally do with gdb, such as setting breakpoints, displaying registers, or disassembling, etc. When all is done, issue c (continue) to kick off.
You may find that you cannot display the CRx registers with gdb. You can do that with QEMU directly. Press CTRL-ALT-2 in the QEMU window, you will be put into a console, where you can issue:
info registers

And you will get all registers including the CRx ones. There are more commands can be issued in that console. help will give you more info about them.


text:
Q: Non-Invasive High Power DC current measurement For one of my projects I need to measure if there is a DC current going trough the thick power cable. The current is DC, and my method of measurement has to be non-invasive.
The current going trough the cable will be anywhere from 1A to 50A. Also the measurements don't have to be precise (at all), I just need to know if there is current being drawn (flowing trough cable) or not.
I've found several solutions using current shunts, hall effect sensors but all of them have some upsides and downsides.
I was wondering if someone could suggest a cheap/simple solution for Non-Invasive high power DC current measurement?

A: If you have access to both ends of the cable, then the voltage drop across the cable is easy to measure.
I have been known to use a the screen of an RF co-axial cable as a heavy current conductor (some cables are built with a lot of copper in the screen), and use the inner to sense the voltage at the far end. This gives a nicely screened differential voltage at this end to measure. An op-amp used as a comparator to sense the mV can be very inexpensive.
An improved Hall sensor method would be to use a pair of Hall sensors, one attached to each side of the cable, facing in opposite directions. This way, the magnetic field due to the current would add, and any external fields would cancel, yeilding a much better signal to interference ratio.

A: Since the current is DC and you're not allowed to connect directly to anything (what I interpret you mean by "non-invasive"), a Hall effect sensor is the obvious option.  The current will make a circular magnetic field around the cable, which the Hall effect sensor detects.
You could make some mechanical contraption based on the principle of a compass needle, but I'd go with the Hall effect sensor.

A: Is measuring voltage invasive?
If you monitor the output voltage the cable resistance will act as a current shunt and indicate the current from a stable power supply.
If the power supply dips with current, it's internal resistance or ESR would have to be included with the cable (both wires) to determine if current is flowing.
Otherwise measuring the voltage difference of each end for + or - will indicate actual voltage drop but a filter cap may be needed for noise.
Testability should always be an up-front design requirement and not an afterthought, FWIW.

A: You can try an experimental approach. Can you wrap a non-ferromagnetic ring around the cable? The magnetic field produced by the cable will be contained within this ring, which will become an annular magnet. If you create a little slit on the surface of this ring, the magnetic field will leak and will loop over the slit. By pouring magnetic particles on the slit, some will stick to it. If there is current, there is magnetic field. If it is strong enough, it might do the trick.

A: Many smartphones and tables have a built-in magnetometer.  I remember seeing a few applications that use them to measure the magnetic field (for example, this one).  You could use one of them to measure the magnetic field generated by the DC current.  I don't know the sensitivity of this method but it should be more than enough to measure the magnetic field generated by currents in the range you want.
Or, if you are using a microcontroller, there are some cheap breakout boards with magnetometer chips.


text:
Q: Unit testing communication between siblings in Angular 2 How does someone test communication between 2 sibling components in Angular 2? I don't seem to find any viable resource online.
app.component.html
<comp1 #a></comp1>
<comp2 [x]="a.get()"></comp2>

where get() is a function within the comp1 component whose value I'm passing to one of the class variables of component comp2. How can I test this efficiently?
app.component is the parent component of comp1 and comp2 and encloses them.

A: The snippet you've mentioned gives a partial idea. But I think you want to test if changes in one component's data affects the other component's data.
it('should xx', async(() => {
    const fixture = TestBed.createComponent(ParentComponent);
    fixture.detectChanges();

    const child1 = fixture.debugElement.queryAll(By.directive(ChildComponent1))[0];
    const but = child1.queryAll(By.css('#some_element'))[0].nativeElement; // change data in child1
    fixture.detectChanges(); // detect changes

    const child2 = fixture.debugElement.queryAll(By.directive(ChildComponent2))[0];
    const child2info = child2.queryAll(By.css('some_element'))[1].nativeElement.innerHTML;
    expect(child2info).toBe('some_data'); // check if reflected in child2
  }));

So, basically you use By.directive() to fetch the DOM elements for a child component. Once you've done that, you need to edit the DOM using nativeElement.
After editing, use By.directive() again to fetch the DOM elements for the second child component and then further check its DOM for data changes.
Note:
For changing the data in ChildComponent1, do something like but.value = "something" (if its an <input> box) and then create an Event before you call detectChanges().


text:
Q: Regular elements in reductive monoids Let $M$ be a reductive linear algebraic monoid with a zero and with unit group $G$ of rank $r$. Fix a maximal torus $T$ in $G$. Then, $M$ can be embedded into a space of matrices $M_n$ for some $n$.

*

*$x \in M$ is regular if its centralizer in $G$ is as small as possible, i.e. $\mathrm{dim} C_G(x) = r.$

*$x \in M$ is semisimple if it is $G$-conjugate to an element in $\overline{T}$. If one embeds $M$ into $M_n(k)$, then $x$ would be a diagonalizable matrix.

*$x \in M$ is (quasi)-unipotent if $ue$ is unipotent in $H(e)$, the unit group of $eMe$ for some idempotent $e$. If one embeds $M$ into $M_n$, then $x$ would be a matrix whose only eigenvalues are 0 and 1.
My question is how much of the theory of regular elements in algebraic groups carry over? In particular,

*

*If $x$ is regular semi-simple, is it contained in $|W|$ many Borel submonoids $\overline{B}$, i.e. closure of Borel subgroups $B$ in $M$?

*If $x$ is regular unipotent, is it contained in a unique Borel submonoid $\overline{B}$?

*If $x$ is regular, is it contained in finitely many Borel submonoids?

My general feeling is "yes" to all of these but I'm not so sure of the proofs and I'm interested to hear whatever references are out there on this topic.


text:
Q: Change Ubuntu 1604 IO scheduler on AWS? I am using a VM from AWS, Ubuntu 1604.
The tricky thing is that I am not able to change the block device's IO scheduler in this way:
root@ip-10-0-96-236:/home/ubuntu# cat /sys/block/xvdb/queue/scheduler
none
root@ip-10-0-96-236:/home/ubuntu# echo noop > /sys/block/xvdb/queue/scheduler
root@ip-10-0-96-236:/home/ubuntu# cat /sys/block/xvdb/queue/scheduler
none
root@ip-10-0-96-236:/home/ubuntu# echo xxx > /sys/block/xvdb/queue/scheduler
root@ip-10-0-96-236:/home/ubuntu# cat /sys/block/xvdb/queue/scheduler
none
root@ip-10-0-96-236:/home/ubuntu#

As you see, I can echo anything to the scheduler file but it did not take effect.
What's the right way for me to change the IO scheduler here? Thanks!

A: Is /sys/block/xvdb/ the right device? (I'd think it should be /dev/sdX )
Usually, to change your io scheduler permanently edit
/etc/default/grub

add
elevator=noop

to
GRUB_CMDLINE_LINUX

and run
update-grub

then reboot.


text:
Q: Kendo TreeList Data Binding I am unable to get my Kendo TreeList to bind to my data.
Model
public class Test
    {
        public int EmployeeId { get; set; }
        public string Name { get; set; }
        public string ReportsTo { get; set; }
    }

Controller
[HttpPost]
    public JsonResult GetAllTest([DataSourceRequest] DataSourceRequest request)
    {
        var result = GetTest().ToTreeDataSourceResult(request,
                //e => e.EmployeeId,
                e => e.Name,
                e => e.ReportsTo,
                e => e);
        return Json(result, JsonRequestBehavior.AllowGet);
    }

    public IEnumerable<Models.InvoiceModels.Test> GetTest()
    {
        var invoiceList = new List<Models.InvoiceModels.Test>();
        var invoice0 = new Models.InvoiceModels.Test();

        invoice0.EmployeeId = 1;
        invoice0.Name = "K S";
        invoice0.ReportsTo = null;

        invoiceList.Add(invoice0);

        var invoice1 = new Models.InvoiceModels.Test();

        invoice1.EmployeeId = 2;
        invoice1.Name = "O G";
        //invoice1.ReportsTo = 1;
        invoice1.ReportsTo = "K S";

        invoiceList.Add(invoice1);

        var invoice2 = new Models.InvoiceModels.Test();

        invoice2.EmployeeId = 3;
        invoice2.Name = "T N";
        //invoice2.ReportsTo = 1;
        invoice2.ReportsTo = "K S";

        invoiceList.Add(invoice2);

        var invoice3 = new Models.InvoiceModels.Test();

        invoice3.EmployeeId = 4;
        invoice3.Name = "E L";
        //invoice3.ReportsTo = 1;
        invoice3.ReportsTo = "K S";

        invoiceList.Add(invoice3);

        var invoice4 = new Models.InvoiceModels.Test();

        invoice4.EmployeeId = 5;
        invoice4.Name = "T C";
        //invoice4.ReportsTo = 4;
        invoice4.ReportsTo = "E L";

        invoiceList.Add(invoice4);

        var invoice6 = new Models.InvoiceModels.Test();

        invoice6.EmployeeId = 6;
        invoice6.Name = "J B";
        //invoice6.ReportsTo = 4;
        invoice6.ReportsTo = "E L";

        invoiceList.Add(invoice6);

        return invoiceList;
    }

View
@{Html.Kendo().TreeList<COOP_MVC_Test.Models.InvoiceModels.Test>()
            .Name("treelist")
            .Columns(columns =>
            {
                columns.Add().Field(p => p.Name).Title("Name").Width("150px");
                columns.Add().Field(p => p.EmployeeId).Title("ID").Width("50px");
            }
        )
        .Filterable()
        .Sortable()
        .HtmlAttributes(new { style = "height: 700px; width: 99.8%" })
        .DataSource(DataSource => DataSource
            .Read(read => read.Action("GetAllTest", "Home"))
            .ServerOperation(false)
            .Model(model =>
            {
                model.Id(p => p.Name);
                model.ParentId(p => p.ReportsTo);
                //model.Field(p => p.Name);
                //model.Field(p => p.ReportsTo);
            }
            )
        )
        .Height(650)
        .Render();
    }

Data that is passed
{"Data":[
        {"EmployeeId":1,"Name":"K S","ReportsTo":null}
        ,{"EmployeeId":2,"Name":"O G","ReportsTo":"K S"}
        ,{"EmployeeId":3,"Name":"T N","ReportsTo":"K S"}
        ,{"EmployeeId":4,"Name":"E L","ReportsTo":"K S"}
        ,{"EmployeeId":5,"Name":"T C","ReportsTo":"E L"}
        ,{"EmployeeId":6,"Name":"J B","ReportsTo":"E L"}
    ] "AggregateResults":{} ,"Errors":null}

This works when I used EmployeeId which was a INT datatype. But when I changed Name to the parent ID and ReportsTo to string type it it returns "No Records to be display".
Am I missing something? Can't seem to figure it out for the life of me.


text:
Q: Restructuring Grouped Data in R I have this data in the following format:
my_data = structure(list(name = c("john", "john", "john", "john", "john",
"alex", "alex", "alex", "alex", "alex", "tim", "tim", "tim",
"tim", "tim", "jason", "jason", "jason", "jason", "jason", "peter",
"peter", "peter", "peter", "peter", "nancy", "nancy", "nancy",
"nancy", "sarah", "sarah", "sarah", "sarah", "luke", "luke",
"luke", "luke", "steve", "steve", "steve", "steve", "matt", "matt",
"matt", "mark", "mark", "mark", "jim", "jim", "jim", "derek",
"derek", "lucy", "lucy", "anne", "kevin", "dave"), year = c(2010,
2011, 2013, 2014, 2019, 2010, 2011, 2012, 2013, 2014, 2008, 2010,
2014, 2018, 2019, 2005, 2006, 2009, 2010, 2011, 2012, 2013, 2014,
2015, 2016, 2009, 2010, 2011, 2013, 2014, 2015, 2019, 2020, 2007,
2008, 2009, 2010, 2009, 2015, 2016, 2016, 2010, 2011, 2012, 2009,
2015, 2016, 2020, 2021, 2022, 2010, 2011, 2012, 2013, 2005, 2012,
2011), grade = c("PASS", "PASS", "PASS", "FAIL", "FAIL", "FAIL",
"PASS", "FAIL", "FAIL", "PASS", "PASS", "PASS", "PASS", "PASS",
"PASS", "PASS", "FAIL", "FAIL", "FAIL", "PASS", "FAIL", "PASS",
"FAIL", "FAIL", "PASS", "FAIL", "FAIL", "PASS", "FAIL", "PASS",
"FAIL", "PASS", "FAIL", "PASS", "PASS", "FAIL", "FAIL", "PASS",
"PASS", "PASS", "PASS", "PASS", "PASS", "FAIL", "PASS", "PASS",
"PASS", "PASS", "FAIL", "PASS", "PASS", "FAIL", "FAIL", "FAIL",
"PASS", "PASS", "FAIL")), row.names = c(NA, -57L), class = "data.frame")

This data shows for each student:

*

*The year they were enrolled in school

*If they passed or failed for that year

In this dataset, students have been attended school for different periods of time. Sometimes, students take a leave of absence and then return to the school.
I would like to make a "Sankey Diagram" (e.g. https://d2mvzyuse3lwjc.cloudfront.net/doc/en/UserGuide/images/Sankey_Diagrams/Sankey_Diagrams_01.png?v=83374) that looks at the academic history of the different students in such a way:

I found this link in R that shows how to do something similar : https://rpubs.com/techanswers88/sankey-with-own-data-in-ggplot
But I am not sure as to how I can restructure the data to make such a diagram.
Can someone please suggest how I can restructure this data so that I can make this diagram? Possibly in plotly? https://plotly.com/r/sankey-diagram/
Thank you!

A: You could first transform your data to wide based on each year using pivot_wider. After transforming the data back to wide using make_long and the tricky part is to replace the NA values with a previous value in the data to prevent it from plotting NA's in your graph. Here is a reproducible example:
library(ggplot2)
library(ggsankey)
library(dplyr)
library(tidyr)

# Transform data to wide based on year
my_data_wide <- my_data %>%
  group_by(year) %>%
  mutate(row = row_number()) %>%
  pivot_wider(names_from = year, values_from = grade) %>%
  select(-row) %>%
  select(sort(names(.)))

# Transform data back to long format and replace na's
df <- my_data_wide %>% make_long(`2005`:`2022`) %>% filter(!if_all(c(node, next_node), is.na)) %>%
  rowwise() %>%
  mutate(node = ifelse(is.na(node), next_node, node),
         next_node = ifelse(is.na(next_node), node, next_node))

# Plot
ggplot(df, aes(x = x, next_x = next_x, node = node, next_node = next_node, fill = factor(node), label = node)) +
  geom_sankey(flow.alpha = 0.5, node.color = "black", show.legend = FALSE) +
  geom_sankey_label(size = 2, color = "black", fill= "white", hjust = 0.5) +
  theme_bw() +
  theme(legend.position = "none") +
  theme(axis.title = element_blank(), axis.text.y = element_blank(), axis.ticks = element_blank(), panel.grid = element_blank())

Created on 2022-10-29 with reprex v2.0.2

A: You could use calculate next grade for every student and use ggsankey:
library(dplyr)
library(ggsankey)
library(ggplot2)

sankey_data <- my_data %>% arrange(name,year) %>%
                group_by(name) %>%
                mutate(next_year=lead(year),
                       next_grade=lead(grade)) %>%
                ungroup

ggplot(sankey_data, aes(x = year,
               next_x = next_year,
               node = grade,
               next_node = next_grade,
               fill = factor(grade))) +
  geom_sankey()


text:
Q: Angular ng-model on label ignored I work with an Angular 1.5.5 application. I want to display a value (selectedRol.activities[0]) in a form. The value shows, the ng-show works also but the ng-model is ignored. Adding the attribute value="{{selectedRol.activities[0]}}" makes no difference.
I expect the output to be
Algemeen Leiding en Coördinatie
irData.Werkzaamheid1 = Algemeen Leiding en Coördinatie
but I get
Algemeen Leiding en Coördinatie
irData.Werkzaamheid1 =
                     <label
                            ng-show="selectedRol.activities.length === 1"
                            ng-model="irData.Werkzaamheid1"
                            ng-bind="selectedRol.activities[0]">
                    </label>
                    irData.Werkzaamheid1 = {{irData.Werkzaamheid1}}

A: You cannot use ng-model in label element. Ng-model is used for inputs.
Instead, use ng-bind:
<label ng-show="selectedRol.activities.length === 1"
ng-bind="irData.Werkzaamheid1">
</label>

or as expression:
<label ng-show="selectedRol.activities.length === 1">
{{irData.Werkzaamheid1}}
</label>

Working plunker: Plunker


text:
Q: Hadoop streaming Python Mapper and reducer error message print. Is that possible? Hello everyone and thank you for your time first.
I am working on a Hadoop streaming job with a python mapper and reducer.
Therefore my command looks like
yarn jar /where/hadoop-version/blahblah/hadoop-streaming.jar. -files mapper.py,reducer.py  -mapper mapper.py -reducer reducer.py -input input.txt -output output
However, Hadoop streaming doesn't give me a helpful error message when my python code has a problem. For example, if I have any typo in my mapper.py or if my for loop is out of the range of the list. Hadoop just gives me back a java error that I cannot understand.
Is there any technique that shows a python error message?
Thank you!


text:
Q: Ember data 2.0 access relationship from template I'm having trouble accessing a relationship inside the ember templates

*

*Ember & Ember Data 2.0.0

*ActiveModelAdaptar - via plugin

Ember Store in console, shows that the current item has a relationship that is already computed, but I can't access it from template

Grouped Item Model
export default DS.Model.extend({
  group:          DS.belongsTo('group', { async :  false }),
  groupable_id:   DS.attr('number'),
  groupable_type: DS.attr('string'),
});

Group Model
export default DS.Model.extend({
    code:          DS.attr('string'),
    name:          DS.attr('string'),
    description:   DS.attr('string'),
    adyuz_site_id: DS.attr('number'),
    extra:         DS.attr(),
    display_as:    DS.attr(),
    items:         DS.hasMany('groupedItem', { async: false, inverse: 'group' }),
});

JSON

Index Route model
  model: function(){
    var self = this;

    return Ember.RSVP.Promise.all([
      this.store.query('groupedItem', { group_code: 'HOME', position : 1 }),
      this.store.query('groupedItem', { group_code: 'HOME', position : 2 }),
    ]);
  },

Index template
{#each model as |section|}}
  {{#each section.content as |item|}}
    {{item}} | {{item.group.id}}
  {{/each}}
{{/each}}

Any suggestions, migration deprecations?


text:
Q: asyn foreach in jQuery What I want is to run a code in asynchronous mode to get a faster response (multi-thread).
I have an array like "sources" with feeds and what I want is to get data from each one.
I've thought something like this :
$.each(sources, function(key, val) {
    JSON CALL OF EACH SOURCE
}

and then group all the results in an array and show them. The problem is that I want the json calls in asynchronous mode due to some of them take some time.
How could I do the 'each' in async mode with jQuery ??

A: Using deferred objects:
// get an array of jqXHR objects - the AJAX calls will
// run in parallel, subject to browser limits on the number
// of concurrent connections to each host
var defs = $.map(sources, function() {
    return $.ajax({ url: this });
});

// when they're all done, invoke this callback
$.when.apply($, defs).done(function() {
    // "arguments" array will contain the result of each AJAX call
    ...
});

To alter the AJAX function so that only the data argument is returned, you can use .pipe():
var defs = $.map(sources, function() {
    return $.ajax({ url: this }).pipe(function(data, text, jqxhr) {
        return data;  // filtered result
    });
});


text:
Q: Angular - Ng Multiselect if statement I can't seem to figure out how to change different booleans when I select an item out of the NG Multiselect dropdown list.
in my app.component.ts
ngOnInit() {
  this.dropdownList = [
    { item_id: 1, item_text: 'option 1' },
    { item_id: 2, item_text: 'option 2'},
    { item_id: 3, item_text: 'option 3'},
    { item_id: 4, item_text: 'etc' },
    { item_id: 5, item_text: 'etc' }
  ];
  this.dropdownSettings = {
    singleSelection: false,
    idField: 'item_id',
    textField: 'item_text',
    selectAllText: 'Selecteer allemaal',
    unSelectAllText: 'Verwijder selectie',
    itemsShowLimit: 3,
    allowSearchFilter: true
  };
}
onItemSelect(item: any) {
  console.log(item);
}
onSelectAll(items: any) {
  console.log(items);
}
}

Above code works fine. When I select an item it gets logged in the console
What I am aiming to achieve is when item_id 1 is checked, set a boolean to true.
Something like this (but does not work):
onItemSelect(item: any) {
if(this.dropdownList.idField == 1) {
  this.option1boolean = true
}
if (this.dropdownList.idField == 2) {
  this.option2boolean = true
}
}

Thanks in advance

A: use item.item_id in place of this.dropdownList.idField
public onItemSelect(item: any) {
  if (item.item_id === 1) {
    this.option1boolean = true;
  }
  if (item.item_id === 2) {
    this.option2boolean = true;
  }
}


text:
Q: cakephp delete casade with sub-categories Using cake 2.x I have 3 tables (I've shortened the names for this example removing the plural/singular cakephp conventions):

*

*Main (has many Sub1)

*Sub1 (belongs to main, hasmany Sub2)

*Sub2 (belongs to sub1)

When I delete a category from Main, all of its dependent sub1/sub2 items are properly deleted using $this->Main->delete($id, true) call.
However I'm not sure how to delete an item from Sub1 and remove all it's sub2 properties. The controller needs to manipulate all three levels of the tables.  I tried:
$this->loadModel('Sub1');
$res = $this->Sub1->delete($id, true);

But it is not picking up the model bindings to Sub2 and deleting them.  What is the proper convention for doing this kind of thing in cake and/or what am I doing wrong?

A: There's two things I'd suggest checking:
1) check that dependent is set true for BOTH associations, that is, the $hasMany in Main, and the $hasMany in Sub1
2) check that 'exclusive' is NOT set to true in either of those associations. From the cookbook:

When exclusive is set to true, recursive model deletion does the delete with a deleteAll() call, instead of deleting each entity separately. This greatly improves performance, but may not be ideal for all circumstances.

If dependent is true, and exclusive is false, for both associations, then Cake should delete your associations recursively, as you can see from the source code.
Lastly, a couple of small tips to keep in mind, though they are unrelated to your current problem:
a)
In the code snippet you gave from your controller, you don't need to load the Sub1 model. It's already available. So you can call:
$res = $this->Main->Sub1->delete($id, true);

b) No need to pass in true as the second param in your delete method, because it's default value is already true. See http://book.cakephp.org/2.0/en/models/deleting-data.html
c) I obviously don't know what the specific differences are between your main, sub1 and sub2 models. But if they're essentially the same thing and you're just wanting to keep track of hierarchy, you should look into the Tree Behaviour


text:
Q: duply fails on all command with, assert filecount == len(self.files_changed) AssertionError No matter which command I try on this duply profile it always errors out.
duply database status
duply database bkp
duply database purge

They all return a trace similar to the following
Start duply v1.11.3, time is 2017-11-30 12:20:12.
Using profile '/etc/duply/database'.
Using installed duplicity version 0.7.12, python 2.7.5, gpg 2.0.22 (Home: ~/.gnupg), awk 'GNU Awk 4.0.2', grep 'grep (GNU grep) 2.20', bash '4.2.46(1)-release (x86_64-redhat-linux-gnu)'.
Checking TEMP_DIR '/srv/mysql/logs/duply_backup/duply_tmp' is a folder and writable (OK)
Test - En/Decryption skipped. (GPG disabled)

--- Start running command PURGE at 12:20:12.397 ---
Using archive dir: /srv/mysql/logs/duply_backup/duply_cache/duply_database
Using backup name: duply_database
Import of duplicity.backends.acdclibackend Succeeded
Import of duplicity.backends.azurebackend Succeeded
Import of duplicity.backends.b2backend Succeeded
Import of duplicity.backends.botobackend Succeeded
Import of duplicity.backends.cfbackend Succeeded
Import of duplicity.backends.copycombackend Succeeded
Import of duplicity.backends.dpbxbackend Failed: No module named dropbox
Import of duplicity.backends.gdocsbackend Succeeded
Import of duplicity.backends.giobackend Succeeded
Import of duplicity.backends.hsibackend Succeeded
Import of duplicity.backends.hubicbackend Succeeded
Import of duplicity.backends.imapbackend Succeeded
Import of duplicity.backends.lftpbackend Succeeded
Import of duplicity.backends.localbackend Succeeded
Import of duplicity.backends.mediafirebackend Succeeded
Import of duplicity.backends.megabackend Succeeded
Import of duplicity.backends.multibackend Succeeded
Import of duplicity.backends.ncftpbackend Succeeded
Import of duplicity.backends.onedrivebackend Succeeded
Import of duplicity.backends.par2backend Succeeded
Import of duplicity.backends.pydrivebackend Succeeded
Import of duplicity.backends.rsyncbackend Succeeded
Import of duplicity.backends.ssh_paramiko_backend Succeeded
Import of duplicity.backends.ssh_pexpect_backend Succeeded
Import of duplicity.backends.swiftbackend Succeeded
Import of duplicity.backends.sxbackend Succeeded
Import of duplicity.backends.tahoebackend Succeeded
Import of duplicity.backends.webdavbackend Succeeded
Main action: remove-old
================================================================================
duplicity 0.7.12 (March 21, 2017)
Args: /bin/duplicity remove-older-than 8W --archive-dir /srv/mysql/logs/duply_backup/duply_cache --name duply_database --no-encryption --verbosity 5 --full-if-older-than 4W --volsize 50 --include-filelist /etc/duply/database/include --exclude-filelist /etc/duply/database/exclude --rsync-options --rsh="ssh -oBatchMode=yes -i /root/.ssh/duplicity_scp.dsa" --copy-links rsync://root@10.21.230.69:22//backup-lun/duplicity//eventlogdb-core-01/database
Linux eventlogdb-core-01.ecnza.net 3.10.0-514.6.1.el7.x86_64 #1 SMP Wed Jan 18 13:06:36 UTC 2017 x86_64 x86_64
/bin/python2 2.7.5 (default, Nov  6 2016, 00:28:07)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)]
================================================================================
Reading results of 'rsync -e 'ssh -p 22 -oBatchMode=yes ' --rsh="ssh -oBatchMode=yes -i /root/.ssh/duplicity_scp.dsa" root@10.21.230.69:/backup-lun/duplicity//eventlogdb-core-01/database/'
Local and Remote metadata are synchronized, no sync needed.
Reading results of 'rsync -e 'ssh -p 22 -oBatchMode=yes ' --rsh="ssh -oBatchMode=yes -i /root/.ssh/duplicity_scp.dsa" root@10.21.230.69:/backup-lun/duplicity//eventlogdb-core-01/database/'
Processing local manifest /srv/mysql/logs/duply_backup/duply_cache/duply_database/duplicity-full.20171010T231503Z.manifest.part (634880)
Using temporary directory /srv/mysql/logs/duply_backup/duply_tmp/duplicity-k1XfbU-tempdir
Traceback (most recent call last):
  File "/bin/duplicity", line 1546, in <module>
    with_tempdir(main)
  File "/bin/duplicity", line 1540, in with_tempdir
    fn()
  File "/bin/duplicity", line 1391, in main
    do_backup(action)
  File "/bin/duplicity", line 1416, in do_backup
    globals.archive_dir).set_values()
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 710, in set_values
    self.get_backup_chains(partials + backend_filename_list)
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 836, in get_backup_chains
    add_to_sets(f)
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 830, in add_to_sets
    if new_set.add_filename(filename):
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 101, in add_filename
    self.set_manifest(filename)
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 148, in set_manifest
    self.set_files_changed()
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 128, in set_files_changed
    mf = self.get_manifest()
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 250, in get_manifest
    return self.get_local_manifest()
  File "/usr/lib64/python2.7/site-packages/duplicity/collections.py", line 224, in get_local_manifest
    return manifest.Manifest().from_string(manifest_buffer)
  File "/usr/lib64/python2.7/site-packages/duplicity/manifest.py", line 208, in from_string
    assert filecount == len(self.files_changed)
AssertionError

12:20:14.362 Task 'PURGE' failed with exit code '30'.
--- Finished state FAILED 'code 30' at 12:20:14.362 - Runtime 00:00:01.964 ---

A: This comment helped me to resolve this
"Remove the last corrupt backup"
All the .part files are incomplete backups
ll /srv/mysql/logs/duply_backup/duply_cache/duply_database/*.part

Remove the incomplete backups. If you want to be more conservative the output does tell you which files were causing problems.
Processing local manifest /srv/mysql/logs/duply_backup/duply_cache/duply_database/duplicity-full.20171010T231503Z.manifest.part

Other wise you can just clean up all the *.parts
rm /srv/mysql/logs/duply_backup/duply_cache/duply_database/*.part

It works correctly after removing those files. Those are all incomplete backups and should be cleaned up any way.


text:
Q: /StartupItem/ Error, How to resolved the issue? I'm using Macbook Pro late 2011 and I'm getting this error in my startup.
I've already performed Repair Disk Permission in my Utilities;
I've also upgraded from Lion to Mountain Lion (10.8.3) but non of the solutions repaired it. I don't want to install fresh Mountain Lion and re-install again, it would be a tedious solution. Any idea how can this be resolved?
Errors Screenshot:

A: Looks like you need to reinstall VirtualBox.

A: Since you can not start in normal mode you need to start up in

Safe mode

.
Then you can reinstall or delete the problem applications.
While in Safe mode look in to the Console for more information on start up problems.


text:
Q: VS2017 Issue with typescript compiler options path not being supported by MS build I already found that MSBuild for VS2017 does not currently support paths in the tsconfig.json according to the docs. But, I was hoping someone might have a workaround for it.
tsconfig.json
{
  "compilerOptions": {
    "baseUrl": "./src",
    "paths": {
      "@example/utils/*": ["app/utils/*"],
      "@example/pipes/*": ["app/pipes/*"]
    }
  }
}

A:
VS2017 Issue with typescript compiler options path not being supported by MS build

If you want specify the compiler options paths by MSBuild properties, I am afraid you can not do that.
As we know, compiler options can be specified using MSBuild properties within an MSBuild project, but some options are only allowed in tsconfig.json, and not through command-line switches and compiler option paths is also not supported by in MSBuild:

So it seems we could not specify the compiler options paths by MSBuild at this moment.


text:
Q: MAC Jupyter Notebook add Graphviz to Path, Graphviz ExecutableNotFound: How to add Graphviz to path? I am having problems running graphviz in Jupyter notebook.
I am using the conda environment and have installed graphviz using brew and Conda.
I ran the command which dot to see where graphviz's path is and got this back
/anaconda3/bin/dot

I have edited my path file so that it looks like this
/anaconda3/bin/
/usr/local/bin/
/usr/bin
/bin
/usr/sbin
/sbin

However I still end up getting the errors
FileNotFoundError: [Errno 2] No such file or directory: 'dot': 'dot'

During handling of the above exception, another exception occurred:

ExecutableNotFound: failed to execute ['dot', '-Tsvg'], make sure the Graphviz executables are on your systems' PATH

I know I am doing something wrong, but am unsure how to get this too work.
I am trying to run this code in Jupyter Notebook but am getting the above errors, the strange things is that graphviz works in the command line, but not in Jupyter notebook.
class Tree:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

from lolviz import *

root = Tree(100)
treeviz(root)

If anyone knows how to solve this it would be greatly appreciated.
Please let me know if you need any more information.
Thank you for your time.

A: Try installing graphviz via homebrew instead (rather than pip from anaconda) as mentioned in this issue. Try uninstalling it and reinstalling with homebrew. You should see
$ which dot
/usr/local/bin/dot

rather than the anaconda path you currently see.

A: I've installed Graphviz via Anaconda but a function calling dot caused the same error. Adding /opt/anaconda3/bin to my path did not help either. Following Elias' answer, I just copied dot to my /usr/local/bin and removed /opt/anaconda3/bin from my path. It works now!


text:
Q: Elasticsearch How to retrieve the maximum id How to retrieve the maximum id for one type index effectively?

A: You want to get the top _id for a type?
{
  "fields": [
    "_id"
  ],
  "query": {
    "match_all": {}
  },
  "sort": {
    "_id": "desc"
  },
  "size": 1
}

A: I tested this query on 1.4.2.  It should work with any mapping, because you are just sorting over the built in ElasticSearch ID.  If you are using your own id field it may or may not work depending on your mapping.  Try this and let me know how it works.
assuming your type is called fruit:
{
  'filter': {
    'type' : {
      'value' : 'fruit'
    }
  },
  'sort': {
    '_id': {
      'order': 'desc'
    }
  },
  'size': 1
}

A: You can also use Max Aggregation (since 1.3) to get the maximum value of a given field in a document.
curl localhost:9200/myindex/mytype/_search -d
  '{
    "aggs" : {
      "max_id" : {
        "max" : {
          "field" : "id"
        }
      }
    },
    "size":0
  }'

Will return:
{
  "took":7,
  "timed_out":false,
  "_shards": {
    "total":6,
    "successful":6,
    "failed":0
  },
  "hits": {
    "total":22,
    "max_score":0.0,
    "hits": []
  },
  "aggregations": {
    "max_id": {
      "value": 27.0
    }
  }
}

In my case the maximum id is 27.

A: {
  "fields": [
    "_uid"
  ],
  "query": {
    "match_all": {}
  },
"size": 1,
"sort": [ { "_uid" : { "order" : "desc"} } ]
}


text:
Q: Split string before the number out of text with mix number and string in Javascript I have some string like this
"ABC17" , "ABCDE16", "AB17a",  "ABCDER10b"

I want to split the string that goes in front of the number out so the result is like
"17" , "16", "17a", "10b"

I also want to ask if my string has some special characters at the end such as
"ABC17)" , "ABCDE16", "AB17a]",  "ABCDER10b"

I want to split the string that goes in front of the number out and remove the ) or ] so the result is like
"17" , "16", "17a", "10b"

Is there a way to do this?
I have tried
string.split(/(\d+)/)[1]

but this only takes all of the letters out of the string. I only want to take the letter in front of the number out and keep the number and letter after the number, such as 10b.

A: in a list you should be able to do this

var x = ["ABC17" , "ABCDE16", "AB17a",  "ABCDER10b"]
x.forEach(y=>{console.log(y.replace(/^\D*/, ''))})


text:
Q: array with constant size (global vs stack) When I tried this code it works:
const int i = 5;
int main() {
    int arry[i];
}

Even though this didn't work:
const int i = 5;
int arry[i];
int main() {

}

I have read all posts here about arrays with constant sizes, but I can't understand why when declaring arry in main it works.

A: The issue here is that const in C doesn't result in a true constant.
When you write const int i = 5 what you have is a read-only variable and not a constant. In C99 an array dimensioned with i is a variable length array (VLA). VLAs are only available for stack allocated variables, hence the compilation error you see.
If you need an array with global scope you should switch to a macro.
#define ARRAY_SIZE 5
int arry[ARRAY_SIZE];

This is valid because 5 is a literal which is a true constant.
In fact, even for an array of automatic storage (i.e. stack allocated local variable) you should avoid a VLA since they incur a runtime overhead.

A: Version 2 is simply not valid C, since i is a read-only variable rather than a true compile-time constant. If you wanted to make it work, you could use malloc and free (or a #define for the size).
Version 1 uses a variable-length array, which is standard feature of C99. gcc supports this syntax in pre-C99 code as an extension. If you compiled your code as C90 and turned on -pedantic, you'd get a warning that ISO C90 forbids variable length array 'arry'.


text:
Q: Как ООП влияет на скорость и объем используемой памяти при работе с большими объемами данных? Допустим, мне нужно оперировать данными о некоторых объектах (о центре масс, плотности, скорости и прочих параметрах). Не используя ООП я могу описать объект с помощью структуры, потом создать большой массив структур и перелопачивать его в процессе работы. Используя ООП я описываю класс объекта, создаю вектор таких классов и работаю с каждым экземпляром класса через его методы.
Насколько второй способ будет более затратен по ресурсам, если объектов очень много. Объясните пожалуйста.

A: Обработчик, выполняющий манипуляции с данными структуры в обоих случаях идентичный:
struct foo {
    int a;
    int b;
};

// в свободную функцию явно передается указатель на экземпляр структуры
void do_something(foo* thiz) {
    thiz->a = thiz->b * 2;
}

struct bar {
    int a;
    int b;

    // в функцию-член неявно передается указатель на экземпляр структуры (this)
    void do_something(/* bar* this */) {
        this->a = this->b * 2;
    }
};

В случае с отдельной функцией вы явно передаете указатель на структуру, в случае функции-члена - это сделает компилятор. Таким образом здесь принципиальной разницы нет в быстродействии.
Единственные накладные расходы при хранении объекта (не важно структуры или класса) - это несколько байтов на экземпляр, в случае, если используются виртуальные методы (указатель на vtab).
Что касается использования массива или вектора (std::vector) для хранения данных, то вектор, никоим образом не замедляет доступ к элементам (если специально не использовать доступ с проверкой на выход за границы массива -  std::vector::at).

A: Всё всегда зависит от контекста/ситуации. Если то что ТС называет "объектом" не имеет собственного "поведения" или "внутренних процессов" или "событий" (а просто как "блок данных") и предполагается иметь массив этих "объектов", то описывать классом нет смысла, будет лучше записью.В иных условиях вполне может оказаться эффективнее сделать класс и иметь массив ссылок. Так что однозначного ответа быть не может. Если бы он был - вещь которая "хуже" просто бы давно исчезла.

A: Операции с выделением, перевыделением памяти достаточно медленные и поэтому для оптимизации их лучше избегать.
 На мой взгляд грамотнее выделить память под массив записей (структур) и передавать ссылку на запись (структуру) в объект для обработки. Это тоже будет ООП. Смысл создавать 1000 экземпляров объектов я не вижу.
Все на самом деле просто тестируется.. Достаточно создать прототип объекта и выделить память под 1 миллион объектов и посмотреть продолжительность их создания и объем выделенной памяти. Тесты будут красноречивее любой теории. Возможно, компиляторы очень круто все сами оптимизируют, возможно, этого  не случится. На саму математику вызов из метода или процедуры думаю значительно не повлияет.

A: Если учесть что у каждого объекта есть указатель this, а также указатель на имя класса и указатель на список всех функций класса то в остальном расходы по сравнению со структурой минимальны, самый простой способ это просмотреть это сделать дезасемблирование и увидеть получившийся код, так же можно указать оптимизацию по данным, а не по скорости для компилятора.

A: В данном случае Вам надо обдумать требуемые алгоритмы и исходя из этого выбирать между несколькими массивами и массивом структур/классов. Основные потери скорости будут не от самого ООП, а от организации данных в памяти и соответственно кэширования данных в процессе работы. Например, для вычисления средней скорости лучше использовать раздельные массивы для данных, а для вычисления энергии тела по массе-скорости-температуре - массивы структур

A: ООП никак не влияет на скорость и объем используемой памяти.


text:
Q: Laravel 8: attach() does not seem to be working I want to add a new role for each user who has registered a new account. So at RegisterController.php, I added this:
protected function create(array $data)
    {
        return User::create([
            'name' => $data['name'],
            'email' => $data['email'],
            'password' => Hash::make($data['password']),
        ]);

        $role = Role::where('name', 'manual user')->first();

        $user->roles()->attach($role->id);

        return $user;
    }

And I have already the row named manual user at roles table:

But now the problem, whenever I try to register a new user, it does not attach $role->id to the pivot table role_user table !!
Note that I have added these relationships also:
User.php:
public function roles()
    {
        return $this->belongsToMany(Role::class);
    }

Role.php:
public function users()
    {
        return $this->belongsToMany(User::class);
    }

And the migration of role_user table goes like this:
public function up()
    {
        Schema::create('role_user', function (Blueprint $table) {
            $table->unsignedBigInteger('user_id');
            $table->unsignedBigInteger('role_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
            $table->timestamps();
        });
    }

So what is going wrong here? How can I fix this issue ?
I would really appreciate any idea or suggestion from you guys...
Thanks in advance.

A: You are saying return User::create([ at first line of method, while using $user variable for attaching. Change it to $user = User::create([


text:
Q: MySQL Join 4 tables returning only 1 row Sorry for my bad English, I have requirement to get data from mysql 4 table but it only return 1 row.
table 1
col_2 in tabl 1 contain numeric data as reference from Table 2 col_2
+----+-------+---------+
| id | col_1 | col_2   |
+----+-------+---------+
| 1  |   A   |  4      |
| 2  |   B   |  5      |
| 3  |   C   |  6      |
+----+-------+---------+

table 2
+----+-------+---------+
| id | col_1 | col_2   |
+----+-------+---------+
| 1  |   A   |  4      |
| 2  |   B   |  5      |
| 3  |   C   |  6      |
| 4  |   C   |  7      |
| 5  |   C   |  8      |
+----+-------+---------+

table 3
Table 3 col_1 has numeric value of table 1 id but most of theme will be the same id,
and col_2 has numeric value of id from table 4
+----+-------+---------+
| id | col_1 | col_2   |
+----+-------+---------+
| 1  |   1   |  1      |
| 2  |   1   |  2      |
| 3  |   1   |  3      |
| 4  |   2   |  4      |
| 5  |   2   |  5      |
| 6  |   4   |  8      |
| 7  |   4   |  1      |
| 8  |   5   |  2      |
| 9  |   5   |  5      |
| 10 |   5   |  8      |
| 11 |   5   |  9      |
| 12 |   5   |  10     |
+----+-------+---------+

table 4
+----+-------+
| id | col_1 |
+----+-------+
| 1  |   A   |
| 2  |   B   |
| 3  |   C   |
+----+-------+

the query I run to get data.
SELECT
    t1.id,
    t1.col_1,
    t2.col_1 as result_0,
    GROUP_CONCAT(t4.col_1) as result
FROM
    table_1 AS t1
LEFT JOIN table_2 AS t2
    ON t2.col_2 = t1.col_2
LEFT JOIN table_3 AS t3
    ON t3.col_1 = t1.id
LEFT JOIN table_4 AS t4
    ON t4.id = t3.col_2
WHERE t1.col_2 > 1
ORDER BY t1.id DESC

as you can see table 3 has deferent id from table 1 and table 4,
both table has value so I want query to return me as bellow. it means I want the value from table 4 to be separated by comma.
+----+-----------+-----------+-----------+
| id | result_1  | result_2  | result_3  |
+----+-----------+-----------+-----------+
| 1  |   A       |    A      |    A,B,C  |
| 2  |   B       |    B      |    A,B    |
| 3  |   C       |    C      |    C,B    |
+----+-----------+-----------+-----------+

UPDATE:
as requested here is the fiddle of query.
SQL Fiddle http://sqlfiddle.com/#!9/3af0af/1
thanks

A: Based on the fiddle you posted
All you have to do is change your query to :-
SELECT
    t1.id,
    t1.name,
    t2.role as result_0,
    GROUP_CONCAT(t4.ct) as result
FROM
    table_one AS t1
LEFT JOIN table_tow AS t2
    ON t2.level = t1.level
 JOIN table_three AS t3                       //CHANGED LEFT JOIN TO JOIN
    ON t3.vid = t1.id
LEFT JOIN table_four AS t4
    ON t4.id = t3.cid
WHERE t1.level > 1
group by t1.id ORDER BY t1.id ASC            //ADDED group by t1.id AND CHANGED ORDER BY t1.id DESC TO ORDER BY t1.id ASC


text:
Q: Getting 'Not Found' page in polymer app I'm very new to Polymer. i read this official polymer documentation and downloaded a code sample and ran it using polyserve without modifying the code.I  followed instructions given in polymer-project website. I installed every required components but after running polyserve command, it shows a page with 'Not found' text. Please help me.
I've installed npm 3.3.6,node v5.0.0.,gulp 3.9.0 and bower 1.7.7. All the commands are running fine without any error. I can't understand what exactly is going wrong.Am i missing something?
Polyserve output

A: Start server and try: http://localhost:8080/components/icon-toggle/demo/
Your folder structure should look like this:
[folder-path]/polymer-first-elements
README.md
bower.json
bower_components
demo -> contents: icon-toggle-demo.html & index.html
icon-toggle-finished
icon-toggle.html

A: You don't say what URL you are trying to access in the browser, but the sample code doesn't have any index.html file at its root, so accessing it there will fail.
There is an index.html in the demo directory, so you might have to add that to the url to access it.

A: Make sure the default port used by polyserve (3000) is not busy,you can use polyserve -p 8000 to try other port

A: I found I needed to add the following line to the <head> element of /demo/index.html:
<link rel="import" href="/bower_components/polymer/polymer.html">

Then view http://localhost:8080/demo (note the trailing "demo").


text:
Q: What does it mean to speak of was and when?
We passed upon the stair
We spoke of was and when
Although I wasn't
there He said I was his friend

The above is the lyrics of the song "The Man Who Sold the World" of David Bowie. What does "speaking of was and when" mean?

A:
We spoke of was and when

This is not an idiom. It is a phrase invented by the songwriter. In general you will not learn normal spoken or written English by studying the lyrics of songs. They may be poetic, they may even be nonsense. They are rarely normal spoken or written English.
In this particular case we can assume that the people were talking about things that happened in the past (what was) and the times at which those events occurred (when).


text:
Q: OpenCV OTSU threshold removing text When I do an OTSU threshold on this image it always takes erodes away the same text every time no matter the lighting conditions.
Here is how I am calling the method:
threshold(outImg_gray(boxRoi), outImg_binarized(boxRoi), 0, 255, CV_THRESH_BINARY_INV|CV_THRESH_OTSU);

When given this image:

I get this image:

As you can see the bottom text removes part of the text at the bottom and it always removes part of this text.
How can I avoid this from happening?

A: Add a border to the image before processing (use copyMakeBorder), and remove it after processing.


text:
Q: How to tell STDIN to stop reading? So I am studying Build Awesome Command-Line Applications in Ruby. On page 81, we're supposed to use STDIN to enter more than one task into a project.
 File.open(global_options[:filename], 'a+') do |todo_file|
  if task_names.empty?
    puts "Reading new tasks from stdin..."
    task_names = STDIN.readlines.map {|a| a.chomp}
  end
  tasks = 0
  task_names.each do |task|
    todo_file.puts [task, Time.now].join(', ')
    tasks+=1
  end
  if tasks == 0
    raise "You must provide tasks on the command-line or standard input"
  end
end

The usual way to enter tasks into a project it's like this $todo new "Rake leaves but with the code above we can to what's in the example below.
It does work. But how do I tell STDIN to stop listening? The example on how to use it is this...
$ todo new
Rake leaves
Take out trash
Clean garage
Put away dishes
^D

What does the ^D represent?

A: It's an end-of-file character. You can type this literally on Unix systems with Ctrl+D or on Windows with Ctrl+Z. The traditional way of displaying the Ctrl modifier is with a ^ prefix, e.g., ^D.
Be aware that this closes standard input entirely. If you want to read more data after entering these lines, you'll need to check the input itself for a different delimiter—for instance, an empty line.

A: You can close STDIN by pressing Ctrl-d on Unix-like systems or Ctrl-z on Windows.

What does the ^6 represent?

Are you sure it says ^6 and not ^d? If so, that's probably a typo.


text: Q: Is there a way to convert nested LESS to un-nested SCSS? I am transfering a lot of LESS files from an my old way of developing in Wordpress to Sage 9, and the linter is going crazy. So I would love a way to convert nested LESS to un-nested SCSS that the linter will allow.


text:
Q: Informatica character sequence I am trying to create character sequence like AAA, AAB, AAC, AAD,....,BAA, BAB, BAC,.... and So on in a flat file using Informatica. I have the formula to create the charater sequence.
Here I need to have sequence numbers generated in informatica. But I dont have any source file or database to have this source.
Is there any method in Informatica to create sequence using Sequence Generater when there is no source records to read?

A: This is bit tricky as Informatica will do row by row processing and your mapping won't initialize until you give source rows through input(File or DB). So for generating sequence of n length by Informatica trnasformations you need n rows in input.
Another soltion to this is to use Dummy Source(i.e. Source with one row) and you can pass the loop parameters from this source and then use Java transfornmation and Java code to generate this sequence.

A: There is no way to generate rows without a source in a mapping.
When I need to do that I use one of these methods :

*

*Generating a file with as many lines as I need, with the seq command under Unix. It could also be used as a direct pipeline source without creating the file.

*Getting lines from a database

For example Oracle can generate as many lines as you want with a hierarchical query :
SELECT LEVEL just_a_column
FROM dual
CONNECT BY LEVEL <= 26*26*26

DB2 can do that with a recursive query :
WITH DUMMY(ID) AS (
    SELECT 1 FROM SYSIBM.SYSDUMMY1
    UNION ALL
    SELECT ID + 1 FROM DUMMY WHERE ID < 26*26*26
)
SELECT ID FROM DUMMY

A: You can generate rows using Java transformation. But even to use that , you need a source. I suggest you to use the formula in the Java transform and a dummy source to a database with a select getdate() statement so that a record is returned to call the Java transform. You can then generate the sequence as well in Java transform or connect sequence generator to output of Java transform to number them.

A: We have an option to create a sequence number even it is not available in the source.

*

*Create a Sequence generator transformation. You will be getting NEXTVAL and CURRVAL.

*In a property tab you will be having an option the create a sequence numbers.

*

*Start values - the value from which it should start

*Increment by - increment value

*End value - the value in which it should end

*Current value - your current value

*Cycle - In case you require in cyclic

*No.of cached values

*Reset

*Tracing level

*Connect the NEXTVAL to your target column.


text:
Q: Getting different image arrays after doing the same operation in Image Sharpening I am trying to sharpen an image by applying unsharp masking, where you subtract your image with the Gaussian blurred image and then add the difference back to the image.
Here is the code which I ran:
 img = cv2.imread('redhat.jpg')
 gauss = cv2.GaussianBlur(img,(7,7),0)
 diff = img - gauss
 sharp = img + diff
 cv2_imshow(img)
 cv2_imshow(sharp)

original image:

sharp:

Instead of above code, if I run:
 img = cv2.imread('redhat.jpg')
 gauss = cv2.GaussianBlur(img,(7,7),0)
 sharp = cv2.addWeighted(img, 2, gauss, -1, 0)
 cv2_imshow(img)
 cv2_imshow(sharp)

then I am getting the correct sharp image:

Can someone explain to me why I got weird results in the first code? Per my understanding both the pieces of code are doing the same mathematical operations.

A: In diff = img - gauss, the subtraction produces negative values, but the two inputs are of type uint8, so the result of the operation is coerced to that same type, which cannot hold negative values.
You'd have to convert one of the images to a signed type for this to work. For example:
gauss = cv2.GaussianBlur(img,(7,7),0)
diff = img.astype(np.int_) - gauss
sharp = np.clip(img + diff, 0, 255).astype(np.uint8)

Using cv2.addWeighted() is more efficient.

A: I believe the difference is caused by over/underflow in
diff = img - gauss
If the source images have both 8-bit unsigned integer depth, the diff will have the same depth as well, which can cause underflow in the subtraction operation.
In contrast, addWeighted(), performs the operation in double precision, and perform saturation cast to the destination type after the operation (see documentation). That effectively reduces the likelihood of over/underflow, and cast will automatically trim the values to the supported range of the destination scalar type.
If you still want to use the first approach, either convert the images to floating point depth, or use big enough signed integers. After the operation, you may need to perform saturation cast to the destination depth.