text:
Q: Java Corrupt JPEG data ... sending image Client-Server-Client My error when sending an image Client-Server-Client is "Corrupt JPEG data: 4350674 extraneous bytes before marker 0xd9" What I can change? Here is my code :
SERVER
 InputStream is = klienciRemoteScreen[1].getInputStream();
 OutputStream os = klienciRemoteScreen[0].getOutputStream();

                  byte[] bytesize = new byte[4];
                  is.read(bytesize);
                  int size = ByteBuffer.wrap(bytesize).asIntBuffer().get();
                  byte [] image= new byte [size];
                  byte[]bufferimage = new byte [1];
                  os.write(bytesize);
                  os.flush();
                  int count;
                  while((count = is.read(image)) > 0)
                  {
                     os.write(image);
                     os.flush();
                   }
                     os.close();

CLIENT sending image to server
OutputStream os = noguiklient.sockRemoteScreen.getOutputStream();

Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    Rectangle rectangle = new Rectangle(dim);
    Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(rectangle);

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

ImageIO.write(image, "jpg", byteArrayOutputStream);

byte[] size =
ByteBuffer.allocate(4).putInt(byteArrayOutputStream.size()).array();
int sizeas = ByteBuffer.wrap(size).asIntBuffer().get();

        os.write(size);
        os.write(byteArrayOutputStream.toByteArray());
        os.close();

CLIENT Receiving from server
JFrame okno = new JFrame();
    okno.setSize(1300, 1000);
    okno.setTitle(" Remote screen");
    okno.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    JPanel panel = new JPanel();
    panel.setSize(1300,1000);
    panel.setLayout(null);
    okno.add(panel);
    okno.setVisible(true);

    InputStream is = Klient.sockRemoteScreen.getInputStream();
    File photo = new File ("photo") ;
    FileOutputStream fos = new FileOutputStream(photo);

    byte[] buffer = new byte[4];
    is.read(buffer);
    int size = ByteBuffer.wrap(buffer).asIntBuffer().get();
    byte[] image = new byte [size];

    int count;
    int i =0 ;
    while((count = is.read(image)) > 0)
    {
        fos.write(image);
        fos.flush();

    }

       ImageIcon screen = new ImageIcon("photo");
       Image imagefinal = screen.getImage();
       imagefinal =
       imagefinal.getScaledInstance(okno.getWidth(),okno.getHeight(), Image.SCALE_SMOOTH);

       BufferedImage(width,height,BufferedImage.TYPE_INT_ARGB);
          Graphics graphics = panel.getGraphics();
while(true)
{
          graphics.drawImage(imagefinal, 0, 0, panel.getWidth(), panel.getHeight(), panel);
}

Example of this bad Image
When I try to send with ImageIO everything is fine but I want to try with bytes and there is a problem.
Thank you :)


text:
Q: Prisma query engine not found on mac M1 I'm having an issue with running Prisma in my project. Running npx prisma generate works, but then running my app I get:
/Users/user/Desktop/project/node_modules/@prisma/client/runtime/index.js:36466
4:29:05 PM web.1 |        throw new PrismaClientInitializationError(errorText, this.config.clientVersion);
4:29:05 PM web.1 |              ^
4:29:05 PM web.1 |  PrismaClientInitializationError: Query engine library for current platform "darwin" could not be found.
4:29:05 PM web.1 |  You incorrectly pinned it to darwin
4:29:05 PM web.1 |  This probably happens, because you built Prisma Client on a different platform.
4:29:05 PM web.1 |  (Prisma Client looked in "/Users/user/Desktop/project/node_modules/@prisma/client/runtime/libquery_engine-darwin.dylib.node")

I've noticed that the libquery_engine-darwin.dylib.node file actually exists as libquery_engine-darwin-arm64.dylib.node. My schema.prisma file includes:
generator client {
  provider       = "prisma-client-js"
  bindaryTargets = ["native", "darwin"]
}

I can't seem to figure out how to generate the right query engine binary with darwin and not darwin-arm64, or have the clientVersion look for the latter.
Here's npx prisma -v:
prisma                  : 3.7.0
@prisma/client          : 3.7.0
Current platform        : darwin-arm64
Query Engine (Node-API) : libquery-engine 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/libquery_engine-darwin-arm64.dylib.node)
Migration Engine        : migration-engine-cli 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/migration-engine-darwin-arm64)
Introspection Engine    : introspection-core 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/introspection-engine-darwin-arm64)
Format Binary           : prisma-fmt 8746e055198f517658c08a0c426c7eec87f5a85f (at node_modules/@prisma/engines/prisma-fmt-darwin-arm64)
Default Engines Hash    : 8746e055198f517658c08a0c426c7eec87f5a85f
Studio                  : 0.445.0

I'm running on a new M1 iMac. Any help would be so so appreciated, thanks!

A: I had bindaryTargets. Should be binaryTargets. LMAO

A: For me mac M2, its work with darwin-arm64
generator client {
  provider      = "prisma-client-js"
  binaryTargets = ["native", "darwin-arm64"]
}

A: I downgraded my node to v14 from v16, which worked for me. I didn't have to set the binaryTarget property.
generator client {
  provider = "prisma-client-js"
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I count the number of times a word is repeated in an array? I'm trying to remove duplicates from my array and display the number of times that a particular word shows up in the array. I've seen ways to handle this, but I tried the ones I've found, and they're not working. When I enter text such as "this this is a test test," it will return a final sorted list of:
1 - is
1 - a
2 - this
2 - test
Though I will eventually be reversing the order of the array, so that the highest numbers are first in the list, this result is perfect! But, if I change the text up a bit, to something like "this is a test test this," the order goes completely out of whack, as shown here:
1 - this
1 - is
1 - a
1 - this
2 - test
As you can see, 'test' shows 2x, which is great, but 'this' shows up twice in the list with only a number '1'. It only compiles duplicates that are in succession. How do I prevent this?
Here is my code:
<!DOCTYPE html>

Click the button to display the array values after the split.

<button onclick="analyze()">Analyze</button>

A: Here is a possible solution using for and Array.prototype.forEach():

var str = "One Two Three One One Three Two One Two Three",
    arr = str.split(' '),
    res = {},
    nb = 0;

for (var i = 0; i < arr.length; i++) {
  nb = 0;
  arr.forEach(function (item) {
    if (item === arr[i]) {
      nb++;
    }
  });
  if (!res[arr[i]]) {
    res[arr[i]] = nb;
  }
}

console.log(res);

A: Try using an object to store the counts for each word:

    var str = "this is a test test this";
    var words = str.split(" ");
    var wordsWithCount = {};

    for (var i = 0; i < words.length; i++) {
        var word = words[i];
        if (word in wordsWithCount) {
            wordsWithCount[word]++;
        } else {
            wordsWithCount[word] = 1;
        }
    }

    console.log("WORD COUNTS");

    for (word in wordsWithCount) {
        console.log(word + " - " + wordsWithCount[word]);
    }

    var sortable = [];
    for (var word in wordsWithCount) {
        sortable.push([word, wordsWithCount[word]]);
    }

    sortable.sort(function(a, b) {
        return b[1] - a[1];
    });

    console.log("SORTED WORD COUNTS");

    for (var i = 0; i < sortable.length; i++) {
        var word = sortable[i][0];
        console.log(word + " - " + wordsWithCount[word]);
    }

A: I do believe GSerg is correct about this being a duplicate, but to help you understand the logic of what's happening in your code, here's what your code is actually doing, in words:
First you're taking your string this is a test test this and splitting it into an array: words = [this,is,a,test,test,this]
On each iteration of the loop, you're comparing the current word to the previous word. If the current word is the same word as the previous word, you increase your counter. If the current word is not the same as your previous word, you're adding the previous word to the end of the wordsWithCount array.
This goes well until you get to the second this in your array. This is because when you compare this to test and find that they're not the same word. You then start a whole new counter for the second this. With this new counter, you also add to the end of the wordsWithCount array instead of adding to the existing counter for this.
To prevent this, you could use a key-value structure instead of a normal array:
for (var i = 0; i < words.length; i++) {
    if(wordsWithCount[words[i]] == undefined) {
        wordsWithCount[words[i]] = 1;
    } else {
        wordsWithCount[words[i]]++;
    }
}

Which will give you this structure:
wordsWithCount: {
    'this': 2,
    'is': 1,
    'a': 1,
    'test': 2
}

And you can loop through the structure as well to create the formatted list you had mentioned:
var formattedWordsWithCount = [];
for (var word in wordsWithCount) {
    formattedWordsWithCount.push(wordsWithCount[word] + " - " + word);
}

A: Here is a solution that will ignore case and punctuation.
function sanitizeWord(word) {
  let result;
  const re = /(\w+)/g.exec(word.toLowerCase().trim());
  if(re) {
    result = re[1];
  }
  return result;
}

function analyze(str) {
  let result = {};
  str.split(" ").forEach((word) => {
    word = sanitizeWord(word);
    if(word) {
      if (result.hasOwnProperty(word)) {
        result[word] = result[word] + 1;
      } else {
        result[word] = 1;
      }
    }
  });
  return result;
}

console.log(analyze("This, . is a test! test this this"));


text:
Q: Is it possible to inject XML comments into a WCF service response I have a WCF service. I would like to include some XML comments in the message returned by the service. (to help developers debug situations, where the defined contract does not expose enough information to be helpful) The comments will vary per execution.
I cannot change the contract as it is provided by my client.
I am aware of message inspectors, and the ability to decorate the contract methods, and therefore manipulate the response directly, but I don't see how I could pass the per-execution custom information to the inspector to add it into the response.

A:
how I could pass the per-execution custom information to the inspector

You do this by extending the InstanceContext. See my answer to How to find out whether current method is flagged with IsOneWay for an example of using a custom context to pass information from an IOperationInvoker to the service. Start with the line of code that says:
OneWayContext.Current.IsOneWay = this.isOneWay;

You can change the code in that answer to pass information from the service to an inspector.
The best general reference on the topic is Carlos Figueira's blog: IExtension and IExtensibleObject


text:
Q: webpage screenshot using wkhtmltoimage is not able to render HTML5 & utf8 in Amazon VPC ubuntu 12.04.4 Scenario:
I am trying to take the screenshot of the new web application created by the user using a background process. I am using wkhtmltoimage with Xvfb.
Issue:
Well the screenshot process is working perfectly fine but the issue is utf8 & HTML5 video in my case are not working only in server (Amazon VPC) but working in my local machine
My first guess for UTF8 issue was to add the UTF8 local language support i.e. en_IN.UTF8 but this did not do the trick.
When I saw the issue with HTML5 video, I tried serching for default browser or rendering engine xvfb uses. I wasn't lucky there but found wkhtmltoimage uses QtWebkit rendering engine.
Tried check out difference in installed packages between my local (Ubuntu 13.04) & server ubuntu 12.04. I almost found all packages related to QtWebkit same.
Possible Solution:
I am guessing the issue may be of the Browser/Rendering Engine which is invoked while taking the screen shot.
Here is the code:
xvfb-run --server-args="-screen 0, 1024x680x24" wkhtmltoimage --use-xserver -f png --quality 94 --javascript-delay 2000 --disable-smart-width --zoom 0.8 --encoding "utf-8" --enable-plugins --width 650 --height 600 http://google.com new.png

Few online Documentation I referred:
wkhtmltoimage doc1
wkhtmltoimage doc2
I am adding the images which are created both in local and server. Well local one has all the details I am looking for.
Local Machine Screenshot:

Amazon VPC Server Screenshot:

Please guide me on this. I am stuck with this from past 20 hours.
Regards,
Hbksagar
P.S: I started using xvfb because of the following errors while using wkhtmltoimage only such as:

*

*QWidget: Cannot create a QWidget when no GUI is being used

*QPixmap: Cannot create a QPixmap when no GUI is being used

with reference to This Article

A: Ensure that the font-related packages are the same at both machines and that you have fontconfig configured similarly. Using the latest 0.12.1 binaries is also recommended.

A: Please for UTF issue please try to install
yum install "@Chinese Support"

This will work for the groups below:
Arabic
Armenian
Bengali
Burmese
Chinese
Ethiopic
Georgian
Greek
Gujarati
Hebrew
Japanese
Kannada
Khmer
Korean
Lao
Malayalam
Oriya
Russian
Tamil
Telugu
Thai

It works for me.


text:
Q: How to get child form's element?   form: ControlGroup
  childForm1: ControlGroup
  childForm2: ControlGroup
  childForm3: ControlGroup

  constructor(fb: FormBuilder) {
    this.form = fb.group({
      name: [''],
      childForm1: fb.group({
        child1: [''],
        child2: ['']
      }),
      childForm2: fb.group({
        child3: [''],
        child4: ['']
      }),
      childForm3: fb.group({
        child5: [''],
        child6: ['']
      })
    });
  }

I can get name by two ways:
  console.log(this.form.find('name'));
  console.log(this.form.controls['name']);

But I cannot use similar way to get child1.
I know a way:
for (name in this.childForm1.controls) {
    if (name === "child1") {
        console.log(this.childForm1.controls[name]);
    }
}

But this still uses childForm1 in the code.
Is it possible using only form and child1 to get it? Thanks

A: You could try this to get the child controls of child1:
var child1Controls = this.form.controls.childForm1.controls;

As a matter of fact, the group method returns a ControlGroup element:

*

*https://angular.io/docs/ts/latest/api/common/ControlGroup-class.html

A: I realized this is nested objects problem. So I created a simplified question, and got an answer from @dave.
But in this case you cannot use typeof to decide whether is is Control or ControlGroup, I got answer from @thierry-templier. So you need change a little bit of the code.
So he final working version:
getControl(controlName:string, controls:Object): AbstractControl {
    for (let i in controls) {
        if (controls.hasOwnProperty(i)) {
            if (i === controlName) {
                return controls[i];
            } else if (controls[i] instanceof ControlGroup) {
                let control:AbstractControl = this.getControl(controlName, controls[i].controls);
                if (typeof(control) !== "undefined") {
                    return control;
                }
            }
        }
    }
}

To use it
let control = this.getControl(this.controlName, this.form.controls);


text:
Q: What is $( \partial u / \partial x )^2$ equal to? Is it equal to $\partial ^2 u / \partial x ^2$?
I am trying to figure that out. I don't think it's the case, but I am just trying to make sure.

A: $( \partial u / \partial x )^2$ is the derivative squared, while $\partial ^2 u / \partial x ^2$ is the second derivative (that's the notation for 2nd derivative).

A: As others have mentioned, they are not the same.
$$
( \partial u / \partial x )^2 = ( \partial u / \partial x )( \partial u / \partial x )
$$
while
$$
\partial^2 u / \partial x^2 = \partial  / \partial x(\partial u / \partial x).
$$
To show an example. If $u = f(x,y) = x^2y$, then
$$
( \partial u / \partial x )^2 = (2xy)^2
$$
and
$$
\partial^2 u / \partial x^2 = \partial  / \partial x (2xy) = 2y.
$$

A: No, it is just the number $\partial u/\partial x$ multiplied by itself.
There's no simpler way of writing that, as long as you don't know how $u$ is a function of $x$.

A: It's not.
Let $f =  \partial u / \partial x $.
Then, $( \partial u / \partial x )^2 = f^2 $ (assuming $f$ returns a number) and $\partial f / \partial x = \partial ^2 u / \partial x ^2$.


text:
Q: File path in jsp Im new to Java and JSP. Pls help me in resolving this problem.
I have two files Page1.jsp and Page2.jsp under WebContent/web/jsp directory. When I click a hyperlink (using a href tag) in Page1.jsp, it should navigate to Page2.jsp.
Here is the code below written in Page1.jsp:
Navigate to Page2 here

I used below path also:
Navigate to Page2 here

Both the times, I am getting the error "The requested resource (/Sample/web/jsp/Page2.jsp) is not available".
'Sample' is my project  name specified in web.xml. And I am using Tomcat 6.0 server.
Please help me on this.

A: Do not include folder name if both these .jsp files are lies in the same folder.
e.g.
Navigate to Page2 here

A: To navigate to Page2.jsp can be done like this .
<a href="<%=request.getContextPath() %>/web/jsp/Page2.jsp">here


text:
Q: PDF of function of random variable in multidimensional case proof I read the wiki page on PDF and I got stuck at the proof of relation between pdf $g$ of a function $\textbf{y}$ and pdf $f$ of its random variables $\textbf{x}$:
$$g({\bf{y}}) = f({H^{ - 1}}({\bf{y}}))\left| {\det\left[ {{{\left. {\frac{{d{H^{ - 1}}({\bf{z}})}}{{d{\bf{z}}}}} \right|}_{{\bf{z}} = {\bf{y}}}}} \right]} \right|,$$
where $\textbf{y} = H (\textbf{x})$, $f$ - pdf for $\bf{x}$
This is proved  from the equation
$$\left|g(\textbf{y})\,d\textbf{y}\right|=\left|f(\textbf{x})\,d\textbf{x}\right|.$$
Since the probability is always positive we can rewrite it like
$$g(\textbf{y})\left|\,d\textbf{y}\right|=f(\textbf{x})\left|\,d\textbf{x}\right|.$$
Now we have two numbers that can be expanded as follows:
$$\left|\,d\textbf{y}\right| =  \sqrt{{dy_1}^2 + \cdots + {dy_n}^2}$$
$$\left|\,d\textbf{x}\right| =  \sqrt{{dx_1}^2 + \cdots + {dx_n}^2}$$
Let's divide it
$\frac{\left|\,d\textbf{x}\right|}{\left|\,d\textbf{y}\right|} = \sqrt{\frac{{dx_1}^2 + \cdots + {dx_n}^2}{{dy_1}^2 + \cdots + {dy_n}^2}}$.
So how can we from this stage get to the $\frac{\left|\,d\textbf{x}\right|}{\left|\,d\textbf{y}\right|}=\left|\frac{d\textbf{x}}{d\textbf{y}}\right|$?
UPD:This step is easy when $\dim(\textbf{x}) = \dim(\textbf{y})$:
$$\frac{{\left| {{\mkern 1mu} d{\bf{x}}} \right|}}{{\left| {{\mkern 1mu} d{\bf{y}}} \right|}} = \frac{{\sqrt {d{{\bf{x}}^T}d{\bf{x}}} }}{{\sqrt {d{{\bf{y}}^T}d{\bf{y}}} }} = \sqrt {\frac{{d{{\bf{x}}^T}d{\bf{x}}}}{{d{{\bf{y}}^T}d{\bf{y}}}}}  = \sqrt {\frac{{d{{\bf{x}}^T}}}{{d{{\bf{y}}^T}}}\frac{{d{\bf{x}}}}{{d{\bf{y}}}}}  = \sqrt {{{\left( {\frac{{d{\bf{x}}}}{{d{\bf{y}}}}} \right)}^T}\frac{{d{\bf{x}}}}{{d{\bf{y}}}}}  = \left| {\frac{{d{\bf{x}}}}{{d{\bf{y}}}}} \right|$$
But what to do if the dimensions equality is not the case?
And how to show then that $\left| {\frac{{d{\bf{x}}}}{{d{\bf{y}}}}} \right| = {\rm{ }}\left| {\det\left( {\frac{{d{\bf{x}}}}{{d{\bf{y}}}}} \right)} \right|$?

A: See the answer to the 1st question in comment of @kimchi-lover
The answer to the 2nd question:
For 2D case the coordiantes transformation is
[\begin{array}{*{20}{l}}
{d{\bf{y_1}} = J({x_1},{x_2})d{{\bf{x}}_{\bf{1}}} = \left( {\frac{{d{y_1}}}{{d{x_1}}}d{x_1},\frac{{d{y_2}}}{{d{x_1}}}d{x_1},0} \right)}\\
{d\textbf{y}_2 = J({x_1},{x_2})d{{\bf{x}}_{\bf{2}}} = \left( {\frac{{d{y_1}}}{{d{x_2}}}d{x_2},\frac{{d{y_2}}}{{d{x_2}}}d{x_2},0} \right)},
\end{array}
where
${d\bf{x}_1} = (dx_1,0)$, ${d\bf{x}_2} = (0, dx_2)$, ${d\bf{y}_1} = (dy_1,0)$ and ${d\bf{y}_2} = (0, dy_2)$.
Then cross-product of $$d\textbf{y}_1 \times d\textbf{y}_2 = \left\langle {0,0,\left| {\begin{array}{*{20}{c}}
{\frac{{d{y_1}}}{{d{x_1}}}}&{\frac{{d{y_1}}}{{d{x_2}}}}\\
{\frac{{d{y_2}}}{{d{x_1}}}}&{\frac{{d{y_2}}}{{d{x_2}}}}
\end{array}} \right|} \right\rangle d{x_1}d{x_2} $$
Then the area in new coordinate system is
$$dA = \left| \left| d\textbf{y}_1 \times d\textbf{y}_2 \right| \right| = \left| {\frac{{d{y_1}}}{{d{x_1}}}\frac{{d{y_2}}}{{d{x_2}}} - \frac{{d{y_1}}}{{d{x_2}}}\frac{{d{y_2}}}{{d{x_1}}}} \right|d{x_1}d{x_2} $$
and finally
$$dA = \left| d\textbf{y} \right| = \left| {\frac{{\partial ({y_1},{y_2})}}{{\partial ({x_1},{x_2})}}} \right|d{x_1}d{x_2} = \left| {\frac{{\partial ({y_1},{y_2})}}{{\partial ({x_1},{x_2})}}} \right|\left| {d\textbf{x}} \right|$$ and
$$\left| {\frac{{d\textbf{y}}}{{d\textbf{x}}}} \right| = \left| {\frac{{\partial ({y_1},{y_2})}}{{\partial ({x_1},{x_2})}}} \right| = \left| {\det \left[ {\frac{{d\textbf{y}}}{{d\textbf{x}}}} \right]} \right|$$
Note: I've mistaken $\textbf{y}$ for $\textbf{x}$, but the idea should be clear anyway
UPD: What to do if $\left| \left| d\textbf{y}_1 \times d\textbf{y}_2 \right| \right| \neq  \left| d\textbf{y} \right|$? Are the last 2 equations valid?


text:
Q: In Rails Test changes to objects not reflecting in Database? I have a Rails 3 application, in which I am trying to write a test-case? When the test case loads, I can see that it is creating the objects corresponding to the fixtures in the database. However, if I change the object within the test case or create another object they do not reflect in the database. Further, if I find the newly created object that is happening correctly.
What is happening here? Also, how can I get the changes to reflect in the database?

A: In your test_helper.rb, the use_transactional_fixtures option is probably set to true. This means that every test is wrapped in a database transaction. A transaction (in MySQL InnoDB) has to be persisted with a "COMMIT". The rails testing framework just doesn't do that so your database is in a fresh state after each test. As a consequence, your changes are rolled back.
Changes within a transaction can only be seen by the database connection that started it, from the outside (in your case the rails db command) they won't show up.
I hope, this helps.


text:
Q: Performance issue persisting/Updating large list of objects using JPA I have one-many unidirectional mapping in 3 entities.
class A {
    List<B> listB ;

    // getter setters
}

class B {
    List<C> listC:

    //getter Setter
}

class C {
  //fields
}

Both the listB and listC having large no of objects. When I am persisting object A it persist B and C also.
only issue I am facing is performance. I am thinking about iterating over listB and persist in batch.
Is there any other option to persist large list ?

A: I assume you are using hibernate as JPA provider. Fine-tune your entity manager using options from:
    org.hibernate.cfg.AvailableSettings
"search" using "batch" keyword, it may help.
Performance is a tricky topic - all depends on a business logic that you are implementing.


text:
Q: Transactional and object mutation Lets say I have an object retrieved from db, and updated
@Transactional
public void update(Long id) {
    User user = dao.get(id);
    user.setName("XXX");
    dao.save(user);
}

Meanwhile, the same record is being updated from outside of hibernate/JPA; lets say plain SQL.
UPDATE USER SET NAME="YYY" WHERE ID=1

What will happen?


text:
Q: C# desktop chart draw complete takes long time I am creating C# chart using button click.
    void myButton_Click(object sender, RoutedEventArgs e)
    {
       DrawChart();
       MessageBox.Show("Draw complated");
    }

    private void DrawChart()
    {
        for (int i = 0; i < 30000; i++)
        {
            Series series = this.chart1.Series.Add(seriesArray[i]);
            series.Points.Add(pointsArray[i]);
        }
    }

I have about 30000 points. So when I click the button, the message box shows immediately, but the graphic is drawn after 5-10 seconds. The users gets the message box before but there is no chart on chart area about 10 seconds.
How can I solve this problem?

A: Try using Chart event.
public partial class Form1 : Form
    {
        private int _pointsCount;

        public Form1()
        {
            InitializeComponent();
        }

        private void Draw()
        {
            _pointsCount = 300000;
            var range = Enumerable.Range(0, _pointsCount);
            Series series = new Series();

            foreach (var i in range)
            {
                series.Points.Add(new DataPoint(0, i));
            }

            chart1.PostPaint += OnDrawingFinished;
            chart1.Series.Add(series);
        }

        private void OnDrawingFinished(object sender, ChartPaintEventArgs e)
        {
            var chart = (Chart)sender;
            var points = chart.Series.SelectMany(x => x.Points).Count();

            if (points < _pointsCount) return;

            MessageBox.Show("Done!");
            chart1.PostPaint -= OnDrawingFinished;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            Draw();
        }
    }

Wokrs here for me for first try. Its not so elegant way but still works.


text:
Q: Cortar Nombre substr() Tengo los siguiente nombre  guardados con apellido+nombre en un base de datos GONZALEZ PEREZ JUAN GABRIEL en un informe solo quiero mostrar los nombres de ellos. Para Juan seria asi
JUAN GABRIEL
Como lo podria realizar usando el substr()?

A: Al leer este comentario tuyo:

En la DB guardo los nombres y apellidos en una pura variable GONZALEZ
  PEREZ JUAN GABRIEL de esta forma.

Debo decir que la solución a esta pregunta es una sola: rediseñar urgentemente tu modelo de datos. El error es ese, porque no puedes usar una sola columna para guardar todo junto el nombre y el apellido.
La dificultad que estás teniendo ahora para querer separar ambos datos es fruto de no haberlos separado al diseñar la base de datos. Es imposible crear un algoritmo o función que te diferencie nombre y apellido en tal diseño, porque:

*

*es imposible saber cuántos palabras tienen todos los nombres y apellidos que van a estar guardados en la base de datos.

*porque hay nombres que parecen apellidos y apellidos que parecen nombres

*porque es imposible saber donde termina el nombre y empieza el apellido

*porque ...

*porque ...

Más adelante habrá otras complicaciones... quiero ver la cara que vas a poner cuando te pidan una lista organizada por el primer apellido, o por el segundo apellido... OMG!!! ¡Y la tabla tiene 10 millones de registros! ¿Cómo hago para normalizarla ahora?  ¿Cómo voy a saber en datos como estos donde termina el nombre y comienza el apellido: José Martín Pérez y José Martín Pérez  ... resulta que en el primero su nombre es José Martín, pero en el segundo su nombre es José y sus apellidos son Martín Perez... Normalizar cuando hay varios miles de registros ya va a ser complicado.
O cuando te pidan una lista con los apellidos que empiecen con la letra B... O cualquier otra cosa que puede ser necesaria en un futuro.

Solución
Rediseñar los datos para normalizarlos, creando una o dos columnas para el nombre, y una o dos columnas para los apellidos, según el caso.

*

*nombre

*primer_apellido

*segundo_apellido  --opcional

A: Si lo quieres hacer con substr() para este caso especifico seria asi:
$nombre = substr('GONZALEZ PEREZ JUAN GABRIEL', 16, 12);

Pero los numeros cambiarian para cada nombre.  Quizas sea mejor en tu caso con explode asi:
$nombres = explode(" ", "GONZALEX PEREZ JUAN GABRIEL");
$nombre = $nombres[2] . " " . $nombres[3];

Por supuesto esto solo funciona si tienes dos apellidos y dos nombres.  Si los nombres no siguen ese formato, tendrias que agregar mas logica.


text:
Q: Creating a dictionary from two iterables and consuming both of them Suppose I have two lists and I want to make a dictionary from them. Like:
>>> l = [1, 2, 3, 4, 5]
>>> x = ['a', 'b', 'c']
>>> dict(zip(l, x))
{1: 'a', 2: 'b', 3: 'c'}

This works as I'd want it to and since the lists are not of equal length, the elements 4 and 5 are left out and there is no corresponding value for them. That is as expected.
But what if I want a value, say None for the keys in l? I'd want the output to be:
{1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}
One of the solutions I thought was to iterate over both, compare their lengths and append None where required. I have a solution that works also, but I was wondering whether it can be done in a much easier and shorter way perhaps?

A: Use
dict(itertools.izip_longest(l, x))
# {1: 'a', 2: 'b', 3: 'c', 4: None, 5: None}


text:
Q: How to get Firebase target by PHP? I'm building an PHP website. I want to push notification to client(who login to my website) so I use Firebase Cloud Messaging.
I already registered Firebase app and write a function to send message
public function sendMessage($data, $target)
{
    //FCM api URL
    $url = 'https://fcm.googleapis.com/fcm/send';
    //api_key available in Firebase Console -> Project Settings -> CLOUD MESSAGING -> Server key
    $server_key = 'MY SERVER KEY';

    $fields = array();
    $fields['data'] = $data;
    if (is_array($target)) {
        $fields['registration_ids'] = $target;
    } else {
        $fields['to'] = $target;
    }
    //header with content_type api key
    $headers = array(
        'Content-Type:application/json',
        'Authorization:key=' . $server_key
    );

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields));
    $result = curl_exec($ch);
    if ($result === FALSE) {
        die('FCM Send Error: ' . curl_error($ch));
    }
    curl_close($ch);
    return $result;
}

But I don't know how to get $target to let Firebase send message to.

Now I want when user register/login on my website, I will request token from Firebase and save it to my DB.
Because when I want send message to that user, I need provide target(token) for Firebase. Anyone please help me?

A: At first, client should have application that uses your firebase project.
Then you can sand message to it application, and you have 2 ways to do it:

*

*You have to acquire his registration token

*His app on smartphone should be registered in some topic, ex. "general".


text:
Q: Boundary of a topological manifold invariant? Let $M=(X,\tau)$ be a topological manifold with boundary.
One can proof that the interior $Int(M)$ and boundary $\partial M$ of the manifold are distinct sets.
I was wondering if someone knows a good reference to cite the proof (Lee only presents this proof as an exercise)?
Thanks

A: Assuming $n$ is the dimension of $M$, you can do this with the following homology computations:

*

*$x \in \text{Int}(M)$ if and only if $H_n(M,M-x;\mathbb{Z}) \approx \mathbb{Z}$,

*$x \in \partial M$ if and only if $H_n(M,M-x;\mathbb{Z}) \approx 0$.
The first is a piece of the standard inductive method for proving $H_n(S^n;\mathbb{Z})=\mathbb{Z}$, as seen for example in Section 2.1 of Hatcher.
The second is on the level of an elementary direct application that combines the excision theorem, the long exact sequence of relative homology, and homotopy invariance of homology. Excision is used to make the left hand side isomorphic to $H_n(H^n, H^n - O;\mathbb{Z})$ where $H^n$ denotes the closed upper half space $\{(x_1,…,x_n) \in \mathbb{R}^n \, | \, x_n \ge 0\}$ and $O$ is the origin.


text:
Q: In a Typescript declaration, how to have one value dependent to the type of another? I have the following code:
type ValidationResult = 'OK' | 'MISSING_FIELDS' | 'DUPLICATED_FIELD';

type ValidationResultOkDetails = null;
type ValidationResultMissingFieldsDetails = [string];
type ValidationResultDuplicatedField = string;

type Validation = {
  result: ValidationResult,
  details: any
}

Is there a way in Typescript to tell the compiler that when the field result of Validation is 'OK', details is of type ValidationResultOkDetails, when it is 'MISSING_FIELDS', details should be ValidationResultMissingFieldsDetails and so on?

A: type Validation = {
  result: 'OK',
  details: ValidationResultOkDetails
} | {
  result: 'MISSING_FIELDS',
  details: ValidationResultMissingFieldsDetails
};

This is a bit messy, but it's the nicest way I know of to solve the problem. Others may know more.

A: Given that OK has no data, here is how I would do it (with example for usage / checking).
The compiler "knows" how to narrow down to whichever type based on the signal value in result.
I've declared the individual types separately, but they could be just done inline with the Validation declaration if desired (keep them separate if you need to refer to any of them explicitly).
type ValidationResult = 'OK' | 'MISSING_FIELDS' | 'DUPLICATED_FIELD';

type ValidationResultOkDetails = null;
type ValidationResultMissingFieldsDetails = [string];
type ValidationResultDuplicatedField = string;

type ValidationOK = {
    result: 'OK',
}

type validationMissing = {
    result: 'MISSING_FIELDS',
    details: ValidationResultMissingFieldsDetails,
}

type validationDuplicated = {
    result: 'DUPLICATED_FIELD',
    details: ValidationResultDuplicatedField,
}

type Validation = ValidationOK | validationMissing | validationDuplicated;

const ok: Validation = {
    result: 'OK',
}

const missing: Validation = {
    result: 'MISSING_FIELDS',
    details: ['x'],
}

const duplicated: Validation = {
    result: 'DUPLICATED_FIELD',
    details: 'hello',
}

function handle(v: Validation) {
    if (v.result === 'OK') {
        // no details
    } else if (v.result === 'MISSING_FIELDS') {
        // [string]
        const m = v.details[0];
    } else if (v.result === 'DUPLICATED_FIELD') {
        // string
        const d = v.details;
    }
}

TypeScript Playground


text:
Q: infinite series question involving sigma how to find out the sum of infinite series question
$$\displaystyle\mathop{\sum^{\infty}\sum^{\infty}\sum^{\infty}}_{i=0\ j=0\ k=0\ i\neq j\neq k}\frac{1}{3^i}\cdot \frac{1}{3^j}\cdot \frac{1}{3^k}$$
the answer in the book is given to be $\displaystyle \frac{81}{208}$.

A: Fist we will calculate the sum without any restriction. So  $$\displaystyle\mathop{\sum^{\infty}\sum^{\infty}\sum^{\infty}}_{i=0\ j=0\ k=0\ }\frac{1}{3^i}\cdot \frac{1}{3^j}\cdot \frac{1}{3^k} = \sum^{\infty}_{i=0}\left(\frac{1}{3^i}\right)^3 = \left(\frac{1}{1-\frac{1}{3}}\right)^3 = \frac{27}{8}.$$
Now for the first sum we have to remove all the cases when $i=j=k$ and also remove
all the cases when any $2$ of them equal but not equal to other variable (say $i=j\neq k$)
$\bullet\; $ If $i=j=k\;,$ Then $$\displaystyle\mathop{\sum^{\infty}\sum^{\infty}\sum^{\infty}}_{i=0\ j=0\ k=0}\frac{1}{3^i}\cdot \frac{1}{3^j}\cdot \frac{1}{3^k} = \sum^{\infty}_{i=0}\frac{1}{3^{3i}} = \frac{1}{1-\frac{1}{27}} = \frac{27}{26}.$$
$\bullet\; $ If $i=j\neq k\;,$ Then $$\displaystyle\mathop{\sum^{\infty}\sum^{\infty}\sum^{\infty}}_{i=0\ j=0\ k=0}\frac{1}{3^i}\cdot \frac{1}{3^j}\cdot \frac{1}{3^k} = \left(\sum^{\infty}_{i=0}\frac{1}{3^{2i}}\right)\cdot \left(\sum^{\infty}_{k=0\;\; k\neq i}\frac{1}{3^{2i}}\right)$$
So we get $$= \left(\sum^{\infty}_{i=0}\frac{1}{3^{2i}}\right)\cdot \left[\frac{3}{2}-\frac{1}{3^{i}}\right] = \frac{3}{2}\cdot \frac{9}{8}-\frac{27}{26} = \frac{135}{8\times 26}$$
So there are three type of such pair in second Case, So we will multiply second case by $3$
So Required Sum is $$ = \frac{27}{8}-\frac{27}{26}-3\times \frac{135}{8\times 26} = \frac{81}{208}$$


text:
Q: Arena queue multiple condition problem 3 stations there are trucks and 3 cleaning stations numbered 1 2 and 3 there are these rule about queues:
1-If there is an empty station trucks go there
2-If there are more than 1 empty station trucks choose the highest numbered station (3,2,1)
3-If all stations are busy trucks chooses the station with the lowest queue if the queues are equal trucks chooses the lowest numbered station (1,2,3)
Can you explain which modules to use and how to construct this model please thanks my best regards...


text:
Q: Post inside fpdf ... help Is this possible?
$pdf->setSourceFile**('Write(0, "h.pfd")')**; --- it gives this error: FPDF error: Cannot open Write(0, "h.pfd") !
Is there any way to integrate a write inside fpdf?
I just want Post inside setSourceFile() fpdi...
any ideas?
--correction ')

A: already tried? $pdf->setSourceFile('Write(0, "h.pfd")');


text:
Q: MySQL partitioning or NoSQL like AWS DynamoDB? Business logic:
My application crawls a lot(hundreds or sometimes thousands) of webpages every few hours and stores all the links(i.e. all anchor tags) on that webpage in a MySQL database table say links. This table is growing very big day by day (already around 20 million records as of now).
Technical:
I have a unique index combined on [webpage_id, link] in the links table. Also, I have a column crawl_count in the same table.
Now whenever I crawl a webpage, I already know webpage_id (the foreign key to webpages table) and I get links in that webpage (i.e. array of link) which I just do an insert or update query without worrying about what is already in the table.
INSERT INTO ........ ON DUPLICATE KEY UPDATE crawl_count=crawl_count+1

Problem:
The table grows big every day & I want to optimize the table for performance. Options I considered are,

*

*Partitioning: Partition table by domains. All webpages belong to a particular domain. For example: Webpage https://www.amazon.in/gp/goldbox?ref_=nav_topnav_deals belong to the domain https://www.amazon.in/

*NoSQL like DynamoDB. I have other tables of application in MySQL DB which I do not want to migrate to DynamoDB unless it's absolutely required. Also I have considered change in application logic (eg: change the structure of webpages table to something like

{webpage: "http://example.com/new-brands", links: [link1, link2, link3]}

and migrate this table to DynamoDB so I don't have a links table. But again, there is a limit for every record in DynamoDB(400kb). What if it exceeds this limit?
I have read pros & cons of using either of the approach. As far my understanding goes, DynamoDB doesn't seem to be a good fit for my situation. But still wanted to post this question so I can make a good decision for this scenario.

A: PARTITION BY domain -- No.  There won't be any performance gain.  Anyway, you will find that one domain dominates the table, and a zillion domains show up only once.  (I'm speaking from experience.)
The only concept of an "array" is a separate table.  It would have, in your case, webpage_id and link as a 2-column PRIMARY KEY (which is 'unique').
Normalize.  This is to avoid having lots of copies of each domain and each link.  This saves some space.
I assume you have two categories of links -- the ones for pages you have scanned, and the ones for pages waiting to scan.  And probably the two sets are similar in size.  I don't understand the purpose of `crawl count, but it adds to the cost.
I may be able to advise further if I could see the queries -- both inserting and selecting.  Also, how big are the tables (GB) and what is the value of innodb_buffer_pool_size?  Putting these together, we can discuss likely points if sluggishness.
Also the slowlog would help.
Are you dealing with non-ascii urls?  Urls too long to index?  Do you split urls into domain + path?  Do you strip off "#..."?  And "?..."?


text:
Q: Solving for the height of water in a sphere of radius $r$ being filled at a constant rate. I'm attempting to find a function that will output a value for the height $h$ (which can also be represented as $y$) of water in a sphere of radius $r$ being filled at a constant rate.
For finding the volume of a sphere until a certain point ($h$) I have chosen to use integration and add the areas of all spheres up until that certain point to do so, we will use the formula $\pi r^2$ and modify it into $\pi r_y^2$ where $r_y$ is the radius of the circular slice of our sphere at height $y$. To do this accurately, we use integration to add an infinite amount of circles to form a sphere. That equation looks like so:
$$
V=\int_{-r}^h\pi r_y^2 \,dx
$$
The work I've done so far has been broken into 2 major parts:
1.) Finding $r_y^2$
To find $r_y^2$, I've rearranged the equation of a circle to solve for $y$ and give a singular value, making it into a usable function for finding the radius of a circle at any given x coordinate between $-r$ and $r$:
$$
x^2+y^2=r^2
$$
$$
y^2=r^2-x^2
$$
$$
y=\pm\sqrt{r^2-x^2}
$$
We only care about the absolute value to give us the value of $r$ so that last equation becomes:
$$
f(x)=\sqrt{r^2-x^2}
$$
Which gives the shape:$y=\sqrt{r^2-x^2}$ on Desmos.com">
Now that we have a function for finding $r_y^2$ (although the equation is in terms of $x$ the equation will work nonetheless which will be demonstrated soon) we are good to move on to step 2.
2.) Solving for height $h$
We can use our equation for volume $V$ which adds the areas of all circles under a point $y=h$ in that sphere and plug in our new function for finding the radius of a circle at a different height in our sphere:
$$
V=\int_{-r}^h\pi r_y^2 \,dx
$$
$$
V=\int_{-r}^h\pi f(x)^2 \,dx
$$
$$
V=\int_{-r}^h\pi \sqrt{r^2 - x^2}^2 \,dx
$$
$$
V=\int_{-r}^h\pi(r^2 - x^2) \,dx
$$
Before going any further, to make sure that this equation is correct in finding the volume of a sphere of radius $r$, we will use $h=r$ and solve to see if we get the volume of a sphere equation $\frac{4}3 \pi r^2$:
$$
V = \int_{-r}^r\pi(r^2 - x^2) \,dx
$$
$$
=\pi\left(\int_{-r}^hr^2 - x^2 \,dx\right)
$$
$$
=\pi\left(\int_{-r}^hr^2 \,dx - \int_{-r}^rx^2 \,dx \right)
$$
$$
=\pi\left([r^2 x]_{-r}^r - [\frac{1}3 x^3]_{-r}^r \right)
$$
$$
=\pi\left(r^2 [x]_{-r}^r - \frac{1}3 [x^3]_{-r}^r \right)
$$
$$
=\pi\left(r^2 [r - (-r)] - \frac{1}3 [r^3 - (-r)^3] \right)
$$
$$
=\pi\left(r^2 [r + r] - \frac{1}3 [r^3 + r^3] \right)
$$
$$
=\pi\left(2r^3 - \frac{2r^3}3 \right)
$$
$$
=\pi\left(\frac{6r^3}3 - \frac{2r^3}3 \right)
$$
$$
=\pi\left(\frac{4r^3}3 \right)
$$
$$
=\pi \cdot \frac{4}3 \cdot r^3
$$
$$
V = \frac{4}3 \pi r^3
$$
Now that we know this equation is effective at finding the volume of a sphere, we will attempt to solve for $h=h$ rather than $h=r$. We will take it from the 5$^{th}$ equation onwards though as all of the steps for finding the indefinite integral are the same until there:
$$
V = \pi\left(r^2 [x]_{-r}^h - \frac{1}3 [x^3]_{-r}^h \right)
$$
$$
V = \pi\left(r^2 [h - (-r)] - \frac{1}3 [h^3 - (-r^3)] \right)
$$
$$
V = \pi\left(r^2 [h + r] - \frac{1}3 [h^3 + r^3] \right)
$$
$$
V = \pi\left(hr^2 + r^3 - \left(\frac{h^3}3 + \frac{r^3}3 \right) \right)
$$
$$
V = \pi\left(hr^2 + r^3 - \frac{h^3}3 - \frac{r^3}3 \right)
$$
$$
\frac{V}\pi = hr^2 + r^3 - \frac{h^3}3 - \frac{r^3}3
$$
$$
\frac{V}\pi - r^3 + \frac{r^3}3 = hr^2 - \frac{h^3}3
$$
$$
\frac{V}\pi - r^3 + \frac{r^3}3 = 3hr^2 - h^3
$$
$$
h(3r^2 - h^2) = \frac{V}\pi - r^3 + \frac{r^3}3
$$
$$
h(3r^2 - h^2) = \frac{3V}{3\pi} - \frac{3r^3\pi}{3\pi} + \frac{r^3\pi}{3\pi}
$$
$$
h(3r^2 - h^2) = \frac{3V - 3r^3\pi + r^3\pi}{3\pi}
$$
$$
h(3r^2 - h^2) = \frac{3V - 2r^3\pi}{3\pi}
$$
This is as far as I've gotten. I've attempted going further by making a quadratic equation in the form $ax^2 + bx + c = 0$ where $x$ is replaced with $r$ and I solve for $r$ to place that equation back in, but that lead to the equation $0 = 0$, which means I did it right, it's just not what I'm looking for. I also realised later that it's required for $r$ to be in the equation for finding $h$ so to get rid of it would defeat the purpose of this equation. Assuming $V$ and $r$ are known variables which will be plugged in, how do you solve the equation we came up with in terms of $h$?
$$
h(3r^2 - h^2) = \frac{3V - 2r^3\pi}{3\pi}
$$
P.S. I have put it into Wolfram Alpha and it gave me some extremely complicated answers. Here's the link to the answer. If the link isn't working, type this into Wolfram Alpha and click "=": "h(3r^(2) - h^(2)) = (3V - 2r^(2)pi)/pi solve h".

A: Cardano is not the best way to go here. Try the trigonometric solution. Your equation is already depressed, so you can ignore that part. Your equation has $$p = -3r^2\\q = \frac{3V - 2r^3\pi}{3\pi}$$$p < 0$, so the solutions will involve real numbers only.


text:
Q: Exclude headers when importing Google Spreadsheet content with Roo I created a rake task to import users from a Google Sheet. Therefore I am using the gem 'Roo'. Everything works so far but I can't seem to get it working without importing the first row (headers).
This is my code:
require 'roo'

namespace :import do
  desc "Import users from Google Sheet"
  task users: :environment do

    @counter = 0
    url = 'https://docs.google.com/spreadsheets/d/{mycode}/export?format=xlsx'
    xlsx = Roo::Spreadsheet.open(url, extension: :xlsx, headers: true)
    xlsx.each do |row|
        n = User.where(name:row[0]).first
        user = User.find_or_create_by(id: n)
        user.update(
                     name:row[0],
                     country_id:row[6]
                   )
        user.save!
        puts user.name
        @counter += 1
      end
     puts "Imported #{@counter} lines."
    end
end

A: Your code says headers: true when you are opening the sheet. Have you tried turning it to false? Or are you saying it does not work when it's set to false?
Also, you are using .each rather differently than the example in the documentation. The doc shows a hash with keys derived from the headers. You are using [n] array notation. Does that work?
EDIT:
Try using .each in a way that's more similar to what the documentation says:
xlsx.each(name: 'Name', country_id: 'Country ID') do |row|
  n = User.where(name: row[:name]).first
  ...
end

The strings 'Name' and 'Country ID' are just examples; they should be the text of whatever column headers have the name and country_id information.

A: There is a way to skip the headers, it is using the method: each_row_streaming(offset: 1).
It will return an array with rows skipping the header, so you have to get the value using .value method. In documentation specify it for Excelx::Cell objects, but it works for Roo::Spreadsheet objects too.
The documentation example:
xlsx.each_row_streaming(offset: 1) do |row| # Will exclude first (inevitably header) row
  puts row.inspect # Array of Excelx::Cell objects
end


text:
Q: Why was Locke led to the Pearl Station? I don't know if anyone discusses Lost anymore, but my question is this: Locke with Boone and later with Eko are led by dreams to the plane above the Pearl Station.
What was Locke meant to find there? Note that in the second season he was led there after finding the Swan. Who is responsible for the dreams? The man in black?

A: I don't think the discovery of the plane was for Locke's benefit so much as it was to sow the seeds of conflict between him and the other survivors:
(SO MANY SPOILERS AHEAD)

*

*The drugs inside the plane (nearly?) led to Charlie relapsing (conflict with Charlie)

*Eko was deeply affected by discovering his brother's body, and spent a bunch of time building a church in his memory (conflict with Eko)

*Climbing into the plane killed Boone (conflict with Jack -- this leads to Locke finally telling the rest of the survivors about the Hatch)

You made it more clear that you're asking why was Locke pushed to find the Pearl, but I think it's pretty much the same explanation: The discovery of the Pearl station led to a pretty basic argument over whether pushing the button was "real" or not (and flipped Locke away from being the Man of Faith for a while). This conflict with Eko led to their showdown and the use of the fail-safe.


text:
Q: What does "no new ground being broken" mean? In Spider Man: No Way Home (2021), Happy startled Peter Parker, who speaking to MJ on phone:

Happy: Wrap it up. You both like each other. We get it. Hang up.
There's no new ground being broken. I need my eight hours.

What does "no new ground being broken" mean?

A: "Breaking new ground":

To advance, innovate, or pioneer (something).

In other words, nothing is advancing in their relationship from their phone call. They're just at a lovey-dovey equilibrium.


text:
Q: Python. If value on column 1 (row X) = value from column 2 (row Y), print row Y of column 3 I have a .csv file, df, with 3 columns (C1, C2 and C3). All columns are of the same length (aprox. 600000 rows) and have unique values. Values in C1, which represent SNPs (single nucleotide polymorphisms) are ordered according to their location on chromosomes. C2 has the same values as C1 but they are disordered. Values in C2 are coupled to corresponding values (chromosome locations) in the same row on C3. What I want to do is to couple the chromosomal locations on C3 to the values in C1 keeping the column order of C1. In other words, generate another column with chromosome locations for the ordered SNPs on C1. So far, I tried to create a dictionary with keys from C2 and values from C3 and then using a for loop to match values on C1 and print the ordered chromosome positions, but I get C3. I understand why I get that but I don't manage to get what I want.
Any suggestion/help would be welcome. I am new into programming.
import csv

from collections import OrderedDict # to save keys order

import sys
sys.stdout = open("output1.csv", "w")

# C1= rows[0], C2= rows[1], C3= rows[2]
with open('df1.csv', 'rU') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    next(reader) #skip header
    d = OrderedDict((rows[1], rows[2]) for rows in reader)

for rows in reader:
    if rows[0] in d:
        print rows[2]

Input example:
C1            C2          C3
12082473    2980300     785989
11240776    4245756     799463
2980300     12082473    740857
2905036     2341354     918573
4245756     3748597     888659
3748597     11240776    765269
2341354     2905036     792480
2465126     2465126     947034

Desired output:
   C1         C4
12082473    740857
11240776    765269
2980300     785989
2905036     792480
4245756     799463
3748597     888659
2341354     918573
2465126     947034

A: I am not entirely sure I understand what you are trying to do.
I think your error is from using the generator expression d = OrderedDict((rows[0], rows[3]) for rows in reader1) and then referring to it after the file has been closed at the end of the with block.
You might try something along these lines:
import csv
from collections import OrderedDict

d=OrderedDict()
with open('df1.csv', 'rU') as csv1, open('df2.csv', 'rU') as csv2:
    reader1 = csv.reader(csv1, delimiter=',')
    reader2 = csv.reader(csv2, delimiter=',')
    next(reader1) #skip header
    next(reader2) #skip header
    for row in reader1:
        d[row[0]]=row[3]
 #   d = OrderedDict(("a", "b") for rows in reader1)
    for row in reader2:
        if row[0] in d:
            print d[row[0]]

I do not see any reason you need an OrderedDict since this is just a mapping between row[0] and row[3] as written. You are not using the order currently.


text:
Q: cast to pointer from integer of different size [-Wint-to-pointer-cast] Well, I have to revive a question that was answered here before.  I've made some changes for other reasons and now I have a problem again.  Here is the relevant details:
volatile char RxBuffer1[NEMA_BUFFER_LENGTH];
uint32_t NEMA_TypeStart;
char NEMA_Type[10];
uint32_t len;
...

memcpy(NEMA_Type,(const char*)RxBuffer1[NEMA_TypeStart], len);

With the cast I get the error shown in the subject line.  Without the cast I get:

passing argument 2 of 'memcpy' makes pointer from integer without a
  cast

Note the same thing happens if I use strncpy instead.  So I'm stumped.  I thought I understood that memcpy uses void*.  What am I doing wrong?

A: You need to pass addresses to memcpy. I would assume you want:
memcpy(NEMA_Type,(const char*) &RxBuffer1[NEMA_TypeStart], len);

A: Its been awhile, but I think you need to say this instead...
memcpy(NEMA_Type, &RxBuffer1[NEMA_TypeStart], len);

You could also say...
memcpy(NEMA_Type, RxBuffer1 + NEMA_TypeStart, len);


text:
Q: Information not pushing to FireBase Realtime Database correctly I have a simple form requesting couple questions from the user. I am attempting to connect my FireBase account so the realtime database can get updated when the user presses the submit button. However, the database is not receiving any information. I have attached the code.
The problem is somewhere in the HTML or JavaScript. I have inserted random alerts to see if they would work, and I get them to come up. I removed some of the "dataLink.push" commands, due to my FireBase only containing 2 values (name, value). I am a beginner with FireBase.

var config = {
    apiKey: "AIzaSyCdqgGdZH8bWSMiHEM7ZoeWSNfZ04uA3Y8",
    authDomain: "errandboi-f1cf5.firebaseapp.com",
    databaseURL: "https://errandboi-f1cf5.firebaseio.com",
    storageBucket: "errandboi-f1cf5.appspot.com",
  };
  firebase.initializeApp(config);
// Creates a variable called databaseLink that links to our database.
  var databaseLink = new Firebase('https://errandboi-f1cf5.firebaseio.com/');
  // Create javascript variables that link our previous HTML IDs.  Remember, we can't use regular HTML inside a script tag, so we need to use JQuery to reference any previous HTML.  A $ means we are using JQuery
  var messageField = $('#task');
  var nameField = $('#name');
  var contactField = $('#contact');
  var locationField = $('#location');
  var miscField = $('#misc');
  var messageList = $('#example-messages'); // DELETE MAYBE?????
  //alert(messageField);
  // If the enter key is pressed, push the values in the text boxes to our database.
  function push(){
    alert("yo");
    messageField.keypress(function (e) {
    if (e.keyCode == 13) {                            //13 is the enter key's keycode
      alert("yo");
      if (messageField.val() == ""){                  //Ensure that an activity was entered.
        alert("Please let us know how we can help!");
      }else{
        //push data to firebase and then clear the text box
        databaseLink.push({name:nameField.val(), value:messageField.val()});
        messageField.val('');
      }
    }
  }
  });//end of keypress function
<DOCTYPE! html>

<meta charset="UTF-8">

<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">

<link href="style.css" rel="stylesheet" />
<title>ErrandBoi!</title>

ErrandBoi

Your Helping Hand in Every Situation

Ever have an emergency while you are in class? Life has got you all tied up but your tasks won't do themselves? Well, you are at the right place for help. Let ErrandBoi take the stress off your shoulders while you can do what really matters. Simply, fill out the form below with any* task that you may need help with and one of our drivers will help you out as soon as possible!

<form method="POST">
<fieldset>
<legend>1 Your Information</legend>
<input type="text" name="field1" id="name" placeholder="Your Name *">
<input type="email" name="field2" id="contact"placeholder="Contact Information (Email, Phone Number, etc.) *">

<input type="location" name="field2" id="location" placeholder="Your Location (i.e. McNutt, Hodge Hall, exact address, etc.)*">
<input type="text" name="field3" id="misc" placeholder="Miscellaneous Information That May Be Important"></textarea>
Urgency:
<select id="job" name="field4">
<optgroup label="Urgency level: just for us to prioritize properly">
  <option value="Not Urgent">Low (ETA: Up to an hour)</option>
  <option value="reading">Normal (ETA: Up to 45 mins)</option>
  <option value="boxing">Critical (ETA: ASAP!)</option>
</optgroup>
</select>
</fieldset>
<fieldset>
<legend>2Task that needs completion</legend>
<input type="text" name="field3" id="task" placeholder="Let Us Know How We Can Help!*"></input>
</fieldset>
<input type="submit" value="Apply" onClick = "push()"/>
</form>

A: You are trying to mix Firebase v2 and Firebase v3. In order to make it work you should:
1) Import the right Firebase sdk (and remove the old one from your code)

2) Get a reference to the firebase database
var databaseLink = firebase.database().ref();

NOTE: Firebase has been updated recently, the new documentation is at firebase.google.com (not firebase.com)
Hope it helps ;)


text:
Q: Помогите с конструкцией require | ДЗ Дали дз ,а я не совсем понимаю что от меня хотят(
Сам сам вопрос
Используя константы и обслуживающие их функции, добейтесь от конструкции require поведения require_once. Иными словами, при многократном включении, код во включаемом файле должен выполниться только ОДИН раз.

A:     function test() {
        if (!defined('TEST')) {
            define('TEST', true);
            require 'test.php';
        } else {
            die('Повторное подключение невозможно!');
        }
    }

    test();
    test(); // Повторное подключение невозможно!

A: Проверьте, определена ли константа. Если нет - определите и выполните код:
<?php
// single.php
if (!defined("FILE_REQUIRED")) {
    define("FILE_REQUIRED", "FILE_REQUIRED");
    echo 'hi';
}

// index.php
<?php
require 'single.php';
require 'single.php';


text:
Q: Meaning of "pax count" I want to know what is pax count regarding to hotel search.
 I want deep meaning of pax count.

A: pax is short for passenger. It's mostly used in the context of transportation, not for hotels, though.


text:
Q: When and how was wheeled transport introduced to Middle-Earth? In The Lord of the Rings, wheeled transport is common. Gandalf has a cart, travelling dwarven merchants have them, Gondor had many, the siege engines of Mordor obviously use wheels to get around, and the first mention I remember is that this was the signature of the Wainriders. (Eastern people who attacked Gondor in the second millennium TA).
But I think no carts are ever mentioned in the context of Aman or Beleriand. Everybody just gets around on horse or foot. (Or wings, wolves, hounds and unclothed ainuic flight).
Who invented the wheel in Middle-Earth?
My guesses:

*

*The dwarves: They did invent things, did long distance trade in Beleriand, and built roads. Perhaps there is confirmation in some narrative of the Fall of Doriath?

*Melkor: He invented many things, and obviously could use it for transporting loot and siege equipment.

*Numenoreans: They also invented things, and would found them useful on their island. Perhaps there is some reference in the Wife of the Mariner.

*Easterlings: The chariots of the Wainriders where a nasty surprise to the Dunedain.

A: Probably during the First Age
The passage from Unfinished Tales quoted in chepner's answer makes clear that wheeled vehicles, while rare, existed in Númenor "in the early centuries". This puts the invention of the wheel at no later than the early centuries of the Second Age.

In Númenor all journeyed from place to place on horseback;
  ...
  Therefore the roads of Númenor were for the most part unpaved, made and tended for riding, since coaches and carriages were little used in the earlier centuries, and heavy cargoes were borne by sea. The chief and most ancient road, suitable for wheels, ran from the greatest port, Rómenna in the east, to the royal city of Armenelos ...
Unfinished Tales Part Two, Chapter I: A Description of the Island of Númenor
Page 164 (Houghton Mifflin Harcourt; 2012 Kindle Edition)

I have not been able to find any earlier reference to wheels, but I think we can we can infer that they were invented earlier. The passage quoted from Unfinished Tales makes clear that the Númenóreans had little need for the wheel when they first moved to Númenor so they would have little incentive to invent it.
If the Númenóreans already knew about the wheel when they moved to Númenor, they must have acquired that knowledge in Middle-earth during the First Age. That suggests that the wheel was invented in the First Age. I can find no reference to wheels or wheeled transport in the First Age. So while I think the wheel was likely invented in the First Age, I can't say exactly when or who invented it (although my money would be on the dwarves).
As "the early centuries" is quite vague, I looked for a quote that gave a more more precise date. The best I could find is also in Unfinished Tales; it has a more precise date (between 873 and 892 of the Second Age), but refers to water wheels (presumably for water mills). In our world, the wheel was usually used for transport before water wheels were developed, and it seems reasonable to assume the same applied in Númenor.

All things were made for their service: hills are for quarries, rivers to furnish water or to turn wheels, trees for boards ...
Unfinished Tales Part Two, Chapter II: Aldarion and Erendis
Page 199 (Houghton Mifflin Harcourt; 2012 Kindle Edition)

The quote is from a letter to Ancalimë written by her mother some time before Ancalimë was named heir to the throne in 892 at the age of 19 (so between 873 and 892).
Conclusion
Water wheels were in use in Númenor by some time between 873 and 892 of the Second Age. The invention of the wheel was no later than "the early centuries of the Second Age", and probably some time in the First Age.

A: There is a passage in "A Description of Númenor" in Unfinished Tales that refers explicitly to wheels (though this only gives a no-later-than answer to "When?" without addressing "Who?"):

Therefore the roads of Númenor were for the most part unpaved, made and tended for riding, since coaches and carriages were little used in the earlier centuries, and heavy cargoes were borne by sea. The chief and most ancient road, suitable for wheels, ran from the greatest port, Rómenna in the east [...]

Wild speculation, but if it is true that no wheeled vehicles were used in Beleriand, one might interpret this passage from the beginning of the Akallabêth

Eönwë came among [the Edain] and taught them

to include the wheel.

However, it is difficult to imagine exactly how a civilization the size implied for the Noldor in Exile to function without the use of wheeled transport. Most significantly: who was supplying Nargothrond with food, and how?


text:
Q: Why can't I edit formatting after a VBA process has set it? I have some code to set formatting for a sheet (see below).
But once the formatting has been set, users can't then change it after the fact.
The formatting is applied as part of a business process to standardise look and feel and make it ready for reporting, but during the reporting review, reviewers may change content and practice is to highlight the cell yellow (or make font red) to indicate where they have made a change.
It seems that they can now do neither, because my code set cell colour and font colour.
Any ideas on how to make this editable again, after the code has executed?
Thanks
Sub FormatCCO()

'Turn off pop-up alerts which are caused by having moved many WIP sheets over with the same dropdown list names
    Application.DisplayAlerts = False

'Turn off screen updating for smoother look and feel
    Application.ScreenUpdating = False

'Delete the sheet "CCO Formatted" if it exists
    On Error Resume Next
    ActiveWorkbook.Worksheets("CCO Formatted").Delete
    On Error GoTo 0

'Create a copy of the Combined sheet and rename it CCO Formatted, placing it in 2nd tab position
    Sheets("Combined").Select
    Sheets("Combined").Copy Before:=Sheets(2)
    Sheets("Combined (2)").Select
    Sheets("Combined (2)").Name = "CCO Formatted"

'Delete all columns not required for CCO reporting (including last rows with the Peoplesoft Tiers
    Sheets("CCO Formatted").Range("A:A, F:F, O:O, P:P, S:U, W:Y, AC:AC, AH:AJ, AL:AT, AY:BF").EntireColumn.Delete

'Move status to Column E (after Allegation but before Date Opened)
    Columns("i:i").Select
    Selection.Cut
    Columns("e:e").Select
    Selection.Insert Shift:=xlToRight

'Format rows 2:350 - remove cell colouring, turn text to verdana 9pt black
    Rows("2:350").Select
    With Selection.Interior
        .Pattern = xlNone
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    With Selection.font
        .Name = "Verdana"
        .Size = 9
        .bold = False
        .ColorIndex = xlAutomatic
        .TintAndShade = 0
    End With

' Centre (horizontally and vertically) all columns, then only left align Allegation (c), Key Factors (i) Investigation status (j). Autofit height
Range("a:aa").HorizontalAlignment = xlCenter
Range("a:aa").VerticalAlignment = xlCenter
Rows("2:350").AutoFit
Range("C:C,I:I,J:J").HorizontalAlignment = xlLeft

'Re-bold header row and Days Open column
    Rows("1:1").Select
    Selection.font.bold = True
    Columns("H:H").Select
    Selection.font.bold = True

'Sort by [Date Opened]
    If Not ActiveSheet.AutoFilterMode Then
        ActiveSheet.Range("A1").AutoFilter
    End If

    ActiveWorkbook.Worksheets("CCO Formatted").AutoFilter.Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("CCO Formatted").AutoFilter.Sort.SortFields.Add Key _
        :=Range("f1:f350"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
        :=xlSortNormal
    With ActiveWorkbook.Worksheets("CCO Formatted").AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

'Apply conditional formatting to [Raised Profile] Cases
    Range("A2:G350,I2:AA350").Select
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$r2=""Yes"""
        Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = RGB(255, 220, 185)
    End With
     With Selection.FormatConditions(1).font
        .ColorIndex = xlAutomatic
        .TintAndShade = 0
    End With

    Selection.FormatConditions(1).StopIfTrue = False

'Apply conditional formatting to cases where [Status] is 'Closed'
    Range("A2:G350,I2:AA350").Select
    Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
        "=$E2=""CLOSED"""
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1).Interior
        .PatternColorIndex = xlAutomatic
        .Color = RGB(153, 204, 255)
        .TintAndShade = 0
    End With
     With Selection.FormatConditions(1).font
        .ColorIndex = xlAutomatic
        .TintAndShade = 0
    End With

    Selection.FormatConditions(1).StopIfTrue = False

'Break external links (from migrating from WIP backups)
Call BreakExternalLinks

' Reset borders from A1 across to the last row and column
Dim lngLstCol As Long, lngLstRow As Long

    lngLstRow = ActiveSheet.UsedRange.Rows.Count
    lngLstCol = ActiveSheet.UsedRange.Columns.Count

    For Each rngCell In Range(Range("a1"), Cells(lngLstRow, lngLstCol))
        If rngCell.Value > "" Then
            rngCell.Select 'Select cells
            With Selection.Borders
                .LineStyle = xlContinuous
                .Weight = xlThin
                .ColorIndex = xlAutomatic
            End With
        End If
    Next

'Return cursor to cell A1
Application.GoTo Reference:=Range("a1"), Scroll:=True

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub


text:
Q: aggregate in new columns using pandas I have the following pandas dataframe:
    time  mes   mech
0   1     50    A
1   2     15    A
2   3     16    A
3   1     17    B
4   2     49    B
5   3     62    B

I would like to aggregate it by time and then have the renamed columns for each mech, like so:
    time  mes_A mes_B
0   1     50    17
1   2     15    49
2   3     16    62

what's the best way to do this?

A: out = (df.pivot('time', 'mech', 'mes')
         .add_prefix('mech_')
         .reset_index())
out.columns.name = None
print(out)

Output:
   time  mech_A  mech_B
0     1      50      17
1     2      15      49
2     3      16      62

A: You can do it like this:
df = pd.DataFrame({"time": [1, 2, 3, 1, 2, 3], "mes": [50, 15, 16, 17, 49, 62], "mech": ["A", "A", "A", "B", "B", "B"]})

def agg_mech(row):
    return {f"mech_{v}": v for v in row}

df2 = df.groupby("time").agg({"mes": "first", "mech": agg_mech})
df2 = df2.merge(df2.mech.apply(pd.Series), left_index=True, right_index=True).drop(columns=["mech"])


text:
Q: conditional jumps -- comparing c code to assembly I am trying to compare a c function code to the equivalent of the assembly and kind of confused on the conditional jumps

I looked up jl instruction and it says jump if < but the answer to the question was >= Can someone explain why is that?

A: To my understanding, the condition is inverted, but the logic is the same; the C source defines

if the condition is satisfied, execute the following block

whereas the assembly source defines

if the condition is violated, skip the following block

which means that the flow of execution will be the same in both implementations.

A: In essence, what this assembly is doing, is executing your condition as you set it, but using negative logic.
Your condition says:

If a is smaller then b, return x. Otherwise, return y.

What the assembly code says (simplified):

Move y into the buffer for returning. Move b into a different buffer.
  If a is bigger then b, jump ahead to the return step. Then y is
  returned. If a is not bigger then b, continue in the program. The next
  step assigns x to the return buffer. The step after that returns as
  normal.

The outcome is the same, but the process is slightly different.

A: the assembly does, line by line (code not included, because you posted it as image):
foo:
    return_value (eax) = y; // !!!
    temporary_edx = b;      // x86 can't compare memory with memory, so "b" goes to register
    set_flags_by(a-b);      // cmp does subtraction and discards result, except flags
    "jump less to return"   // so when a < b => return y (see first line)
    return_value (eax) = x;
    return

so to make that C code do the same thing, you need:
if (a >= b) { return x; } else { return y; }

BTW, see how easy it is to flip:
if (a < b) { return y; } else { return x; }

So there's no point to translate jl into "less" into C, you have to track down each branch, what really happens, and find for each branch of calculation the correct C-side calculation, and then "create" the condition in C to get the same calculation on both sides, so this task is not about "translating" the assembly, but about deciphering the asm logic + rewriting it back in C. Looks like you sort of completely missed the point and expected you can get away with some simple "match pattern" translation, while you have to work it out fully.


text:
Q: How to extract JAD file from COD file? I provided a JAR file and a JAD file to the Blackberry's RAPC compiler. It produced a COD file. The JAD file constains business logic related properties (in opposition to classics properties like MIDlet-Name, etc) that I am trying to extract.
Assuming one only has access to the COD file, is there a way to extract the JAD file from this COD file ?
PS: I don't have access to the JAD given to the RAPC. Hence the question :)
PS2: Links/turotials/samples about how to create a JAD file for Blackberry don't answer the question.
Thanks

A: You can make your own JAD manually or do this by using "BlackBerry Desktop Manager":
http://www.ehow.com/how_7846156_create-jad-cod-alx.html
And here is a sample for JAD:
Manifest-Version: 1.0
RIM-COD-Module-Name: YourProjectName
RIM-COD-Module-Dependencies: net_rim_cldc,net_rim_pdap,net_rim_bbapi_invoke
MIDlet-Jar-Size: 133911__your_JAR_size_in_byte
MIDlet-1: ,img/icon.png,
RIM-COD-Creation-Time: 1319628844__maybe_unneccessary
MIDlet-Jar-URL: YourProjectName.jar
RIM-COD-URL: YourProjectName.cod
RIM-COD-Size: 45832__your_COD_size_in_byte
MicroEdition-Configuration: CLDC-1.1
MIDlet-Version: 1.0.0
MIDlet-Name: YourProjectName
MIDlet-Vendor: BlackBerry Developer
MicroEdition-Profile: MIDP-2.0
RIM-MIDlet-Flags-1: 0

A: No.
(filling up to 30 characters)


text:
Q: Strange behavior with NVIDIA CUDA 4.1 RC2 and Parallel NSight 2.1 I am having a strange problem debugging my CUDA code in Nsight 2.1.  I have two global functions that get called from my main.cu like so:
dim3 block(threadsPerBlock);
dim3 grid(numBlocks);
InitPhotons<<<grid,block>>>(devicerun,sources[i],1);
cudaThreadSynchronize();
MC<<<grid,block>>>(devicerun,sources[i],1);

I can hit breakpoints in InitPhotons successfully, and single step through that function.  However, I can only hit the first breakpoint I set in MC.  If I attempt to single step through the function (F10 in VS), the debugger behaves as if I had used the continue command (F5) and no longer hits breakpoints.
Has anyone else encountered this issue?  Does anyone have any ideas for a solution?
I am using Parallel NSight 2.1 with CUDA 4.1 RC2 in Visual Studio 2010 Pro.  I am compiling with the -G0 flag, and optimization is disabled.
Edit: The problem seems to be with the default size of Code patching memory.  I changed the Code patching memory factor from 2 to 4, and everything works fine (Nsight->Options->CUDA->Code patching memory factor).

A: I'm a member of the Parallel Nsight team at NVIDIA. Unfortunately, this sounds like it could be a bug.
Is there any chance we could take a look at your project? Please contact me via email by filing a bug for the issue here: http://developer.nvidia.com/rdp/bugs/parallel-nsight-bug-reporting
I'll take a look at it ASAP.
Thanks!


text:
Q: JdbcTemplate IN Clause for String elements Am using NamedParameterJdbcTemplate for where Clause elements and one of them seems to be List<String>.  JdbcTemplate replaces them ?,?,?...(list size) but for a IN clause with List<String> it has to be '?','?'....
Is there a way around this?

A: There a few other similar questions out there which might have helpful answers for you:
How to execute IN() SQL queries with Spring's JDBCTemplate effectivly?
To make this style of query work on my end, I have to switch from plain old JDBCTemplate to NamedParameterJdbcTemplate.
Here is some example code:
String query = "select * from table where columnName in (:listOfValues)";
List<String> nameRecordIDs = new ArrayList<String>();
// ...
// add values to collection, then
// ...
Map namedParameters = Collections.singletonMap("listOfValues", nameRecordIDs);
namedparameterJdbcTemplate.query(query, namedParameters,new MyMapper());


text:
Q: JSON object is valid and populated, but has no methods and it's data cannot be accessed (react) I am working with an API that returns a JSON object of the following format:
{
  "Home": {
    "Office": [
      { ... },
      { ... },
    ]
  }
}

*

*I retrieve the data from the API, which returns a result just like many other endpoints.

*I cannot access its properties - object['Home'] is undefined

*It has NO methods - Object.getOwnPropertyNames(obj).filter(item => typeof obj[item] === 'function') returns an empty array

*.keys(), .map(), .values() etc are all undefined

This is the only JSON object that has this issue - no matter how I alter it, this endpoint seems to be broken.
In the API, I build this object as follows:
    var map = {};
    result.forEach(device => {
        if (!map[device.facility]) map[device.facility] = {};
        if (!map[device.facility][device.room]) map[device.facility][device.room] = [];
        map[device.facility][device.room].push(device);
    });

The response looks valid
Also:

*

*The JSON object is valid

*JSON.stringify has no issues with it

*Even calling JSON.parse on the result of JSON.stringify gives the same broken object

So how can a valid json object have no methods and no accessible properties? I know I am missing something stupid here

A: Turns out I have to use Object.keys( x ) and not x.keys()

A: You will have to parse the JSON you are getting as a response from the API.
Then you can get the value either by using object.Home or object["Home"]
reference - https://mkyong.com/javascript/how-to-access-json-object-in-javascript/


text:
Q: Single quotes is not displayed in output while concatenating strings along with single quotes in excel I have strings in each column as like below

I used concatenate formula in excel as below
=A1&+B1&+C1&+D1&+E1&+F1&+G1&+H1&+I1&+J1&+K1&+L1

Output of the above formula is below

But the expected output is below

Please help. I need single single quotes between the string 143001000100317520150311600030104200003000000O using excel formula.

A: If you are using columns E1 and G1 for single quotes, set the value of the cell to ="'" (equals double quote single quote double quote) instead of just typing a single quote in the cell.


text:
Q: Should careers early adopters get upgraded to the lifetime membership? When careers was originally released, when there were no employers around and it wasn't even complete, there was a "promotional" deal for early adopters. Stack Overflow friends jumped in out of their trust and love to SO. Careers pricing has changed significantly since then. However, instead of going up, it has practically went down. This, of course, contradicts what has been promised:

Fair warning, the price absolutely will go up in 2010. So if you think you might need to file your CV — that is, make it searchable by hiring managers — any time in the next year, consider jumping on this offer before January 1.

This looks quite unfair to SO's true friends, the early adopters. Considering the fact that there's a loophole (taking advantage of the 90-day money back guarantee and refiling with the new pricing), I think it makes sense to promote the original accounts to the new lifetime offer.

A: Of course not. Those of us who jumped onto the bandwagon were taking a risk. We knew the risk was there and we took it. That's the price of being at the head of the pack.
Or are you one of those people who waited in line for a day to buy a $600 iPhone and then whined when they lowered the price? You either wait for the Blu-Ray to win, or you jump in and buy an HD-DVD player and suck it up when it loses the battle.
Learn to live with the risky choices you've made, or don't make them in the first place.

A:
I think we should have the option to pay the difference to upgrade to lifetime

You can of course do this -- if you'd like to upgrade to lifetime and apply your $29 toward that, just email us -- careers@stackoverflow.com

A: I disagree.
However, for those of us who took advantage of this deal up front, I think we should have the option to pay the difference to upgrade to lifetime, or refund the difference to reduce the period to only 1 year (after the initial sign-up).
I think this

Fair warning, the price absolutely will go up in 2010. So if you think you might need to file your CV — that is, make it searchable by hiring managers — any time in the next year, consider jumping on this offer before January 1.

was posted with the best of intentions, but it's hard to argue that it didn't skew their up-front business results.

A: I thought about this quite a bit when it was announced, but ultimately decided that I still got a good deal, and they gave me exactly what they promised I'd get for $29.
So no, of course not.
Your remedies include demanding a refund, and sulking.
But sulking because you got what you paid for is in rather poor form.

A: I agree. I joined early and paid $25 to file my CV under the premise that I may want to use it at some point in the next 3 years.
I assume that when I actually do file, it will only be for a brief period while I search for a job. If I had waited, that would now only cost me $19.
I'm not really annoyed, I like that I'm supporting SO anyway, and $25 isn't exactly a lot, and I'm not going to start demanding a refund or anything, but as I've paid over the odds, lifetime membership would be nice ;)


text:
Q: Spring security - Restricting Authenticated User redirection to Login After login, when login url is accessed with out logging out, login page is shown, but I do not want the login Page, instead remain on the same page even when login url is accessed from address bar.
Following is my security configuration:
<form-login login-page="/loginform.do" authentication-failure-url =     "/loginform.do?error=1" default-target-url="/dashBoard.do" always-use-default-    target="false" />

One solution I come across is to redirect page, if the role is not 'ROLE_ANONYMOUS'
<sec:authorize ifNotGranted="ROLE_ANONYMOUS">
  <% response.sendRedirect("/mainpage.jsp"); %>
</sec:authorize>

But can a similar configuration be done in security configuration file ?

A: I solved this with an HandlerInterceptor because I dont know a build in solution.
import org.springframework.web.util.UrlPathHelper;
...

public class PreventLoginPageForLoggedInUserInterceptor extends HandlerInterceptorAdapter {

    private UrlPathHelper urlPathHelper = new UrlPathHelper();

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler)
                   throws Exception {

         if (urlPathHelper.getLookupPathForRequest(request).startsWith("/login"))
             && isAuthenticated()) {

            sendRedirect(request, response);
            return false;
        } else {
            return true;
        }
    }

     private void sendRedirect(HttpServletRequest request,
                               HttpServletResponse response) {
         response.setStatus(HttpStatus.TEMPORARY_REDIRECT.value());
         response.setHeader("Location", response.encodeRedirectURL(request.getContextPath() + "/"));
    }

    private boolean isAuthenticated() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return (authentication != null)
               && (!authentication instanceof AnonymousAuthenticationToken)
               && authentication.isAuthenticated()
    }

}


text:
Q: Elegant way to find min/max in a table (vector of vectors, 2D array) using STL algorithm(s) Let us assume we have a vector of vectors and wish to find a minimum (or maximum) values (no need to know their position in the table). What would be an elegant way to accomplish this?
The obvious solution, included below, is to run std::min_element per each row in a loop. But may be it is possible to do it with a single statement without loop using, may be, lambda functions?
Note, there is a similar question on SO already, but it is actually not quite about what I am asking here.
Update: Ideal solution would be using STL only, but, failing that, it would be interesting to see other options.
#include <algorithm>
#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<double> > test_array=
         {
          {1., 2., 3., 4.},
          {7., 4., 6., 8.},
          {5., -1., 3., 1}
         };
    double min_val(test_array[0][0]);
    double max_val(test_array[0][0]);
    for(auto& row : test_array)
    {
        min_val = std::min(min_val, *std::min_element(row.begin(), row.end()));
        max_val = std::max(max_val, *std::max_element(row.begin(), row.end()));
    }

    cout << "Minimum = " << min_val << std::endl;
    cout << "Maximum = " << max_val << std::endl;
    return 0;
}

A: With range-v3, you might have a flatten view with ranges::view::join:
std::vector<std::vector<double> > test_array =
{
    {1., 2., 3., 4.},
    {7., 4., 6., 8.},
    {5., -1., 3., 1}
};
auto flatten_view = test_array | ranges::view::join;
const auto p = std::minmax_element(begin(flatten_view), end(flatten_view));
std::cout << "Minimum = " << *p.first << std::endl;
std::cout << "Maximum = " << *p.second << std::endl;

Demo

A: There are multiple options, e.g., the following one uses std::accumulate that returns pair of numbers containing minimum and maximum elements, respectively:
auto res = std::accumulate(a.begin(), a.end(), std::make_pair(a[0][0], a[0][0]),
    [](const auto& current, const auto& v) {
        auto minmax = std::minmax_element(v.begin(), v.end());
        return std::make_pair(std::min(current.first, *minmax.first),
                              std::max(current.second, *minmax.second));
    });

Live demo: https://wandbox.org/permlink/IwMWioewJBg7C67l


text:
Q: Beanstalkd tube missing Integrated Pheanstalk library in my web app. Created three tubes for three type of jobs.
Created a beanstalkd web console also to see the job status.
All are working fine.
The issue is, today when I checked the console, one of the tubes is missing. I restarted beanstalkd and it appeared and started working again. Why did this happen?

A:
Tubes are created on demand whenever they are referenced. If a tube is empty
  (that is, it contains no ready, delayed, or buried jobs) and no client refers
  to it, it will be deleted.  -- https://github.com/beanstalkd/beanstalkd/blob/master/doc/protocol.txt

The tube will be re-created as soon as a new job is put into it. Normally you would watch all of the tube(s) that a particular worker can deal with, and a reserve would return the next job from any of the watched tubes based on the specified ordering, or first-come-first-served, as appropriate.


text:
Q: How make Google Play Store like view in HTML? I am working on a website where I display some resources that have been uploaded by some admin users in the form of a google play store view.
It looks like something below:

I need to make a CSS view of this resource and then repopulate the same view for all the resources.
This is what I have implemented till now:

        a.img-list {
            list-style-type: none;
            margin: 0;
            padding: 0;
            text-align: center;
        }
    ul.img-list li {
        display: inline-block;
        height: 150px;
        margin: 0 1em 1em 0;
        position: relative;
        width: 150px;
    }

    .imgWrap:hover .imgDescription {
        visibility: visible;
        opacity: 1;
    }

    span.text-content span {
        display: table-cell;
        text-align: center;
        vertical-align: middle;
    }

    span.text-content {
        background: rgba(0,0,0,0.5);
        color: white;
        cursor: pointer;
        display: table;
        height: 150px;
        left: 0;
        position: absolute;
        top: 0;
        width: 150px;
        opacity: 0;
        -webkit-transition: opacity 500ms;
        -moz-transition: opacity 500ms;
        -o-transition: opacity 500ms;
        transition: opacity 500ms;
    }

    ul.img-list li:hover span.text-content {
        opacity: 1;
    }
</style>

for displaying my resources.

A: Try this code

.box{width: 180px;background: #fff;box-shadow: 0 4px 5px 0 rgba(0,0,0,0.14),0 1px 10px 0 rgba(0,0,0,0.12),0 2px 4px -1px rgba(0,0,0,0.3);margin: 10px;font-family: Arial,sans-serif;}
.box img{width: 100%;}
.box .content{padding: 10px;}
.box p{margin: 7px 0;}
.box .title{color: #333;font-size: 18px;}
.box .price{color: #ed3b3b;float:right;}
.box .author{font-size: 16px;}
.box .desc{font-style: italic;font-size: 14px;color: #616161;}

    The time machine

      H.G Wells
      $226.80

  Popular with time machine readers

Demo here https://jsfiddle.net/tsebautr/


text:
Q: Reverse geocode for given lat long gives incomplete address results for iOS app when compared to the GET api In my iOS app I am trying to get address details for lat long (18.557121460659193, 73.793425261974335). I am making use of following code to get address details.
func reverseGeoCode() {
    let gmsCoder = GMSGeocoder()
    gmsCoder.reverseGeocodeCoordinate(CLLocationCoordinate2DMake(18.557121460659193, 73.793425261974335), completionHandler: { (response, error) in
        if let address = response?.firstResult() {
            let lines = address.lines! as [String]

            let completeAddress = lines.joined(separator: " ")
            print(completeAddress)
            print(response?.results())
        }
    })
}

In response, I receive an object of GMSReverseGeocodeResponse which contains results as an array of GMSAddress objects.
the result array contains 7 objects and the first address component received is as shown below
some : 7 elements
- 0 : GMSAddress {
coordinate: (18.557121, 73.793425)
lines: S.No.3, Baner Road, Riviresa Society, Baner, Pune, Maharashtra 411045
thoroughfare: S.No.3 Baner Road
subLocality: Riviresa Society
locality: Pune
administrativeArea: Maharashtra
postalCode: 411045
country: India
}

However this is not the detailed address result that is received.
When i try to get the location address details using the GET api
http://maps.googleapis.com/maps/api/geocode/json?latlng=18.557121460659193,73.793425261974335&sensor=true
I get the result array count as 10. Also the first address details are something like this
{
"results" : [
  {
     "address_components" : [
        {
           "long_name" : "Omkar Building",
           "short_name" : "Omkar Building",
           "types" : [ "premise" ]
        },
        {
           "long_name" : "Baner Road",
           "short_name" : "Baner Rd",
           "types" : [ "route" ]
        },
        {
           "long_name" : "Baner",
           "short_name" : "Baner",
           "types" : [ "political", "sublocality", "sublocality_level_1" ]
        },
        {
           "long_name" : "Pune",
           "short_name" : "Pune",
           "types" : [ "locality", "political" ]
        },
        {
           "long_name" : "Pune",
           "short_name" : "Pune",
           "types" : [ "administrative_area_level_2", "political" ]
        },
        {
           "long_name" : "Maharashtra",
           "short_name" : "MH",
           "types" : [ "administrative_area_level_1", "political" ]
        },
        {
           "long_name" : "India",
           "short_name" : "IN",
           "types" : [ "country", "political" ]
        },
        {
           "long_name" : "411045",
           "short_name" : "411045",
           "types" : [ "postal_code" ]
        }
     ],
     "formatted_address" : "Omkar Building, Baner Rd, Baner, Pune, Maharashtra 411045, India",
     "geometry" : {
        "bounds" : {
           "northeast" : {
              "lat" : 18.5572967,
              "lng" : 73.79350599999999
           },
           "southwest" : {
              "lat" : 18.5570646,
              "lng" : 73.79327309999999
           }
        },
        "location" : {
           "lat" : 18.5571293,
           "lng" : 73.793358
        },
        "location_type" : "ROOFTOP",
        "viewport" : {
           "northeast" : {
              "lat" : 18.5585296302915,
              "lng" : 73.7947385302915
           },
           "southwest" : {
              "lat" : 18.5558316697085,
              "lng" : 73.79204056970849
           }
        }
     },
     "place_id" : "ChIJD2Vxati-wjsRROyg_2yMD50",
     "types" : [ "premise" ]
  },

The first address component shown here is the accurate address which should also be shown when i try to get details using reversegeocode api in iOS application.
I have also implemented reverse geocoding in an Android app and the Android app shows the address details like the first address component of the GET api.
Can anyone please help me in determining why am I receiving incomplete address components array when compared to the GET api and the Android app. Any help on this will be much appreciated.
Environment -
iOS version: iOS 11.1
Google Maps SDK for iOS version: 2.4.0


text:
Q: Powershell script not recognizing my function I have a powershell script that parses a file and send an email if it detects a certain pattern. I have the email code setup inside a function, and it all works fine when I run it from the ISE, but I used PS2EXE to be able to run the script as a service but it does not recognize the function "email". my code looks similar to this
#Do things |
foreach{
    email($_)
}

function email($text){
    #email $text
}

When I convert it to exe and run it I get this error:
The term 'email' is not recognized as teh name of a cmdlet, function, script file,
or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.

A: When it comes to the Function-Calls, PowerShell is fairly different from other programming-languages in the following ways:

*

*When passing the arguments to a function, parentheses are NOT allowed (and will raise a parse error if Set-StrictMode is set to -version 2.0 or above/Latest), however, Parenthesised arguments must be used to call a method, which can either be a .NET method or a user defined method (defined within a Class - in PS 5.0 or above).

*Parameters are space-separated and not comma separated.

*Be careful in where you define the function. As PowerShell sequentially processes line-by-line in top-down order, hence the function must be defied before that function is called:
    Function func($para1){
          #do something
    }
    func "arg1"  #function-call

In Windows PowerShell ISE (or Visual Studio Code) if a function-call appears   to be working even though the function-definition is defined below the function-call, (beware) this is because it's cached in memory from a previous execution(s), which too will fail as soon as you update the function-definition.

A: Powershell processes in order (top-down) so the function definition needs to be before the function call:
function email($text){
    #email $text
}

#Do things |
foreach{
    email($_)
}

It probably works fine in the ISE because you have the function definition in memory still from a prior run or test.


text:
Q: Empty statemachine base? hello I recently started using Resource editor and I have a question:I 'm trying to create a simple project just for test purposes in Resource Editor:nothing special just a Label with a hello world, but when I push "create Netbeans project" while all the projects(JavaSE,MIDP ,RIM) are created none of them are running. In normal JaVA I just get a black screen and in MIDP emulator I get a message saying "This application runs in the background".
My StateMachineBase code is this
public class StateMachineBase {
    public StateMachineBase(String s) {}
}

And My StateMachine code is this:
public StateMachine(String resFile) {
    super(resFile);
    // do not modify, write code in initVars and initialize class members there,
    // the constructor might be invoked too late due to race conditions that might occur
}

/**
 * this method should be used to initialize variables instead of
 * the constructor/class scope to avoid race conditions
 */
protected void initVars() {
}

So I'm guessing my prgramm obviously won't do anything since there is no code. What am I doing wrong? From my understanding StateMachineBase should have all the boiler code.I'm using Netbeans 6.9.1 ,Lwuit latest version  and JavaME SDK 3.0 and Nokia S60 SDK.
Thank you.

A: Well I shall answer my own post. Randomly I found out that if you save the res file and reopen it then it works fine. This was confirmed by Shai Almog in his blog saying that this is a bug that will be fixed in the next release.
Shai's answer to my post


text:
Q: How to insert a value in a fixed positon of pytorch I have a PyTorch tensor
x = [[1,2,3,4,5]]

Now I want to add a value to a fixed position of the tensor x, for example, I want to add 11 in position 3 then the x will be
x= [[1,2,3,11,4,5]]

How can I perform this operation in Pytorch?

A: Dynamically extending arrays to arbitrary sizes along the non-singleton dimensions, such as the ones you mentioned, are unsupported in PyTorch mainly because the memory is pre-allocated during tensor construction and set to fixed size depending on the data type. The only way to grow non-singleton dimension size is to create a new (empty/zero) tensor with the target shape and insert values at the desired position(s), while also copying values.
In [24]: z = torch.zeros(1, 6)
In [27]: t
Out[27]: tensor([[1, 2, 3, 4, 5]])

In [30]: z[:, :3] = t[:, :3]
In [33]: z[:, -2:] = t[:, -2:]
In [36]: z[z == 0] = 11

In [37]: z
Out[37]: tensor([[ 1.,  2.,  3., 11.,  4.,  5.]])

However, if you'd have instead wanted to expand the tensor along the singleton dimension, then that's easy to achieve using tensor.expand(new_shape). In the below example, we expand the tensor t to length 3 along the 0th dimension, which is originally a singleton dimension.
# make a copy for in-place modification since `expand()` returns a view
In [64]: t_expd = t.expand(3, -1).clone()

In [65]: t_expd
Out[65]:
tensor([[1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5],
        [1, 2, 3, 4, 5]])

# modify 2nd and 3rd rows
In [66]: t_expd[1:, ...] = 23

In [67]: t_expd
Out[67]:
tensor([[ 1,  2,  3,  4,  5],
        [23, 23, 23, 23, 23],
        [23, 23, 23, 23, 23]])