text:
Q: Minimal Exim router which simply adds custom header I answered this question with my current solution, but as I said I'm not 100% happy with it. That solution to the question 'How to add a custom header to all outgoing mail' involved adding the headers_add parameter into the existing Smarthost transport. However, I can see updates or reconfiguration reverting my edit at some point without me knowing.
I had hoped to create a minimal router which would run early on in the chain and just add the required header - this header can be added to all mail, whether it ends up being for local or remote delivery. But I couldn't find any example of a router which runs, adds the header then passes all messages on to the next router in the chain. I created this, which seems to work, but I'm very new to Exim and would be grateful if anyone can point out flaws or a better way to achieve the desired outcome. The router is /etc/exim4/conf.d/router/01_exim4-config_dev_header:
dev_header:
    debug_print = "R: dev_header for $local_part@$domain"
    driver = redirect
    headers_add = "X-Test-Dev-Header: true"
    data = $local_part@$domain
    self = pass

A: You don't need a router to do this. It is much more easier (and, in my opinion, cleaner) to have a statement in the acl_smtp_data ACL, which does nothing but adds the header, like this:
warn add_header = X-Test-Dev-Header: true

See "Adding header lines in ACLs" for more info.
How to enable this rule
I'm assuming you have the "split" configuration.

*

*Look for a file named main/0000-localmacros or similar. If it doesn't exist, create it.

*The file should contain a line like this:
CHECK_DATA_LOCAL_ACL_FILE=/etc/exim4/some/file

If it doesn't, add this line. The filename can be anything.

*Write the line above into the /etc/exim4/some/file file (the warn add_header... one).

*Reconfigure exim. On Debian this is done by running the dpkg-reconfigure exim4-config command.

After this, every mail should contain the header you specified.


text:
Q: Studying non-linear PDEs with manifolds I'm sorry if this is an inappropriate forum to ask this question on, for I fear it is pretty undergraduate-level one :) I was contemplating on the study of non-linear PDEs. Is it possible to reduce a non-linear PDE on $\mathbb{R}^n$ to a distribution or a 'good' PDE on a smooth manifold? It seems to me like a natural step, but I don't know anything about it yet :(

A: The question is vague (Denis is right) but it does make some sense. When looking at explicit solutions of nonlinear PDEs one frequently encounters singularities that remind of projections from some higher dimensional manifold (e.g. in Burger's equation). But I think the OP does not have a clear picture. Locally, working 'on' a manifold instead than on $R^n$ is essentially like changing coordinates in the equation. So usually you do not resolve nonlinearities, you just modify the coefficients of the equation.
On the other hand, if you consider equations with values into a manifold, then sometimes a very difficult nonlinear term reveals to be a very simple geometric object, 'linear' in some sense. This does not happen by chance; your equation must have some geometric meaning. Best examples are harmonic maps (elliptic) and wave maps (hyperbolic).
Some years ago, Serge Alinhac tried to develop a whole theory of 'geometric blow up': singularities in the solution which can be resolved by choosing an appropriate coordinate sistem in the target space. But I guess the results where not too satisfying since he abandoned the effort.

redpajama_set_name: RedPajamaStackExchange


text:
Q: unix shell programming if statement condtion setting I'm trying to set filename upper to lower and lower to upper i dont know how to use "and" operation in shell programming.
if [ $temp == "[a-z]" ]
if (( (($temp >= 'a')) && (($temp <= 'z')) ))
if [[ (($temp >= 'a')) && (($temp <= 'z')) ]]

I tried these three if statement but no one worked well. What should i do

A: if [ "$temp" \> 'a' ] && [ "$temp" \< 'z' ] || [ "$temp" = 'a' ] || [ "$temp" = 'z' ]  ; then
  echo 'true 1'
fi

if [ "$temp" \> 'a' -a "$temp" \< 'z' -o "$temp" = 'a' -o "$temp" = 'z' ]  ; then
  echo 'true 2'
fi

A: You are comparing a string (filename) with a character.
When you just want to change the case of the filename, you can use:
file="FileWithUpAndDowns"

    echo "Tr gives ${file}" | tr '[[:lower:]]' '[[:upper:]]'
    # or use typeset
    typeset -u  upperfile
    typeset -l  lowerfile
    upperfile="${file}"
    lowerfile="${file}"
    echo "Low=${lowerfile}"
    echo "Up=${upperfile}"

A: bash glob patterns understand POSIX character classes, so to test for a lower case character:
if [[ $temp == [[:lower:]] ]]; then ...

The key is to leave the right-hand side unquoted to have the shell treat it like a pattern. If it's quoted, it will be considered a literal string. Note this behaviour is only for the [[ double bracket ]] form.
However, as you say you want to swap case, this is straightforward:
swapped=$( tr '[:lower:][:upper:]' '[:upper:][:lower:]' <<<"$str" )


text:
Q: Remove class from td when the same class is clicked on I have a bunch of 's that have the class clickable
How can I remove the class clickable to no longer make them clickable? Here's what I have but it doesn't remove the class:
    $('td.clickable').click(function(){
        $(this).removeClass('clickable');
});

A: The code you have will certainly remove the class, however it doesn't remove the click event.
I'd suggest modifying your click event to use event delegation, like so:
$('table').on("click", ".clickable", function(){
    $(this).removeClass('clickable');
});

Example: https://jsfiddle.net/c6eda0kj/

Why event delegation is important:
Doing something like $('.clickable').click( ... ) creates a listener for every instance of clickable. If there are 100 .clickable td's, that's 100 listeners that you've just created. Regardless of whether or not you remove the class from those 100 elements, the event is already attached. In order to remove the event, you'll have to use unbind or off.
If you instead put the listener on the table as I have above, you have just one single event. When that event fires (the click of the table), it checks to see if the clicked element matches the specified selector. By removing the class, it will then no longer trigger the event - no need for unbinding of any sort.

A: When you select the element, it adds the event. When the event is not removed because you remove the class. You have two options. Remove the click event. Other option is event delegation.
$('td.clickable').click(function(){
    $(this).removeClass('clickable').off("click");
});

or
$("table").on("click", 'td.clickable', function(){
    $(this).removeClass('clickable');
});

A: As @isherwood mentioned use off() instead of unbind()
here's an example:

$('.clickable').click(function(){
  console.log($(this).text());
  $(this).off();
});

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    Germany

    Centro comercial Moctezuma
    Francisco Chang
    Mexico


text:
Q: How do I silence the delayed_job output in test? I am using delayed_job for background tasks such as system e-mails and different timed events.  I use Delayed::Worker.new.work_off to work off the events in my RSpec tests, but then the test out put gets littered with sh*t like:
[Worker(host:ch.local pid:24307)] RPM Monitoring DJ worker host:ch.local pid:24307
[Worker(host:ch.local pid:24307)] acquired lock on ListingJob
[Worker(host:ch.local pid:24307)] ListingJob completed after 0.0655

I get that the output is helpful for debugging, but is there a way to silence it?  I would much rather enable it when a test fails to debug, rather than always have it on.
Thanks.

A: Try this:
worker = Delayed::Worker.new(:max_priority => nil,
                             :min_priority => nil,
                             :quiet => true
                            )
worker.work_off

By telling the worker to be quiet it should clean up the spam...


text:
Q: unexpected recursion in restler call (node/js) I want to get a URI, parse it, and then get another URI based on the parsed data.  Using restler, I thought I could do the parsing and the second get call from the .on('complete',...)  function of the first get call.  It doesn't seem to work as I expect.  To investigate, I coded up the following, which is a very simplified version of how my code is structured. It never exits until I hit Ctrl-C.
var sys = require('util');
var rest = require('restler');

function UriCall( uri, handler ) {
    rest.get(uri).on('complete', function(result) {
        if (result instanceof Error) {
            sys.puts('Error: ' + result.message);
        }
        else {
            if (handler) { handler( result ); }
            else { sys.puts('No handler provided.'); }
        }
    });
}

var uri = "http://www.google.com";

UriCall(uri, function(result) {
   sys.print("@");
   UriCall(uri, function(result) {
      sys.print(".");
   });
});

Output:
$node resttest.js

@@.@..@...@....@.....@......@.......@........@ [deleted error messages] .........@..........@...........@............@.............@..............@...............@................@.................@..................@...................@....................@.....................@......................@.......................@........................@.........................@..........................@...........................@............................@.............................@..............................@...............................@................................@.................................@..................................@...................................  ^C

From the output above it looks like something is getting stacked up with each call and it just gets deeper and deeper.  I'm a C/C++ guy who is just getting started with js/node/restler. Why doesn't the program simply call UriCall twice and then exit?
(BTW: The errors messages start with "(node) warning: possible EventEmitter memory leak detected 11 listeners added. Use emitter.setMaxListeners() to increase limit." and then included some trace.  The error message doesn't surprise me given what appears to be happening.)

A: When you attach the event listeners to the 'complete' event, they don't go away after the event happens (they will run again with the same callback method you put in originally when any 'complete' is detected). Every successful call to your uri will trigger this event. So you are basically stacking up function calls on the 'complete' event, and the recursive call in the first callback adds more each time the original event is triggered. Does that make sense?
I suggest using .once instead of .on, as was suggested here (Multiple responses on node.js restler call).  Or unbind the event upon success.


text:
Q: How do I get New & Returning Visitors as Standard Metrics in SiteCatalyst I am wondering if there is a way to get New Visitors and Returning Visitors as a Site Catalyst Metrics. I understand you can get the same results using segments but I am looking for a "column-able" metrics for example - you can add "Unique Visitors" or any other Calculated Metrics to any report. I am wondering if there is a way to create a prop/evar or events to do the above?
Example firing an event if the visitor is visiting the site 2nd time? or creating a calculated metrics?

A: With the latest release of Adobe Analytics in June 2015 you can now add segments to metrics in the new calculated metric builder with out changing your javascript. Here is how you would do it.

*

*Create a segment for New Visitors (Visit Num = 1)

*Create a segment for Returning Visitors (Visit Num >1)

*Create the new Visitors metric in the metric builder by adding new visitors to the unique visitors metrics

*Do the same for returning visitors

Once you have done this you can use it just like any other metric.

A: Assuming the visitor retention reportsOne way you can achieve this is by using the visit number plugin or something similar: Visit Num Plugin
Using that, you can use whatever logic within your plugin section you need to set events:
var visNum = s.getVisitNum();
if(visNum === 1){
    //set event for first timer
}else{
    //set event for repeat visitor
}


text:
Q: Is there an easy way to make anything draggable in Silverlight XAML? My target is an entire listbox clipped in a canvas, but I guess there should be something that can work for all controls?
How to make a control draggable and even attached x or y constraints?

A: You would have to cycle thru all the child controls and add handlers to mouse events.
Within those events you control the drag and the bounds.


text:
Q: TinyTest against onUse DB Assuming they aren't, is there some way to make meteor test-packages ./ use the same DB as meteor? I'd like to add some package tests that rely on user data.

A: Just like meteor run, meteor test-packages takes into account the MONGO_URL setting.
Thus,
MONGO_URL=mongodb://127.0.0.1:27017/mydb meteor test packages ./

will use the specified database.


text:
Q: Out of memory or dimension too large for Octave's index type (reading xlsx file) I tried to read from an excel .xlsx file containing 3000 rows and about 800 columns using Octave xlsread (using Octave GNU package) on Windows. The file contains very large integers. The highest is 10^32. The total size of the excel file is 17732KB. The .xlsx file I am trying to read is here: https://drive.google.com/file/d/0B9_0IQ9zpJH2SzVKTHVqSW5qN0U/view?usp=sharing
This is the error I have:
error: out of memory or dimension too large for Octave's index type
error: called from
    __OCT_spsh_open__ at line 95 column 11
    xlsopen at line 314 column 30
    xlsread at line 197 column 11
    getExcelData at line 5 column 18
    start at line 18 column 6

When I debugged xlsopen does not return any value (so it couldn't read). I was wondering whether there is a way to solve this problem? Or is there a better way to read large excel data using Octave? Or is there a way to increase Octave's memory.
EDIT: I tried reading with 200 rows instead of 3000 rows and apparently it worked. But the problem is still I want to read and process all 3000 rows. Sometimes when I try to process 200 rows, the error is still printed out at various part of the application:
error: out of memory or dimension too large for Octave's index type


text:
Q: I am trying to run unittest using python. But, when I try to run the below code, I get error even though I have handled the exception import unittest
import math

class Circle:
    def __init__(self, radius):
        self.radius = radius
        # Define the initialization method below
        try:
            if not isinstance(radius, (int, float)):
                raise TypeError
        except TypeError:
            print("radius must be a number")
        try:
            if radius in range(0, 1001):
                raise ValueError
        except ValueError:
            print("radius must be between 0 and 1000 inclusive")

    def area(self):
        return round(math.pi * self.radius ** 2, 2)

    def circumference(self):
        return round(2 * math.pi * self.radius)

class TestCircleCreation(unittest.TestCase):
    def test_creating_circle_with_numeric_radius(self):
        # Define a circle 'c1' with radius 2.5 and check if
        # the value of c1.radius equal to 2.5 or not
        c1 = Circle(2.5)
        self.assertEqual(2.5, c1.radius)

    def test_creating_circle_with_negative_radius(self):
        # Try Defining a circle 'c' with radius -2.5 and see
        # if it raises a ValueError with the message
        # "radius must be between 0 and 1000 inclusive"
        c2 = Circle(-2.5)
        self.assertRaises(ValueError, c2)

    def test_creating_circle_with_greaterthan_radius(self):
        # Try Defining a circle 'c' with radius 1000.1 and see
        # if it raises a ValueError with the message
        # "radius must be between 0 and 1000 inclusive"
        c3 = Circle(1000.1)
        self.assertRaises(ValueError, c3)

    def test_creating_circle_with_nonnumeric_radius(self):
        # Try Defining a circle 'c' with radius 'hello' and see
        # if it raises a TypeError with the message
        # "radius must be a number"
        c4 = Circle("hello")
        self.assertRaises(TypeError, c4)

A: assertRaises expects a function for it's second parameter. You're passing a Circle object though, which it's attempting to call as a function; which is causing that error.
I think you meant something like:
self.assertRaises(ValueError, lambda: Circle(-2.5))

Then make a similar change to the other cases.
This wraps the call to the Circle constructor in a lambda function so assertRaises can call the constructor as needed.

This will still fail as you're using a try to catch the ValueError and TypeErrors that assertRaises is looking for. If you want the exceptions to be thrown, don't catch them internally.


text:
Q: Formatter in VsCode for React When I save or format my React code with Ctrl + Shift + F the code below, is formatted in a strange way.
How can I solve this?
Default code:
import logo from './logo.svg';
import './App.css';

function App() {
  return (

          Edit src/App.js and save to reload.

          Hello CodeCademy

  );
}

export default App;

After formatting the code:
import logo from './logo.svg';
import './App.css';

function App() {
    return ( <
        div className = "App" >
        <
        header className = "App-header" >
        <
        img src = { logo }
        className = "App-logo"
        alt = "logo" / >
        <
        p >
        Edit  src / App.js  and save to reload. <
        /p> <
        a className = "App-link"
        href = "https://reactjs.org"
        target = "_blank"
        rel = "noopener noreferrer" >
        Hello CodeCademy <
        /a> <
        /header> <
        /div>
    );
}

export default App;

I tried to install another formatter and go to my settings to remove my "html" "twig" extension in emmet.

A: Follow these steps:

*

*CTRL + SHIFT + P

*Format Document (in pop-up bar)

*Select Format Document

*Select Configure Default Formatter...

*Select Prettier - Code formatter
To enable Format On Save

*

*CTRL + SHIFT + P

*Preferences Open Settings (UI) (in pop-up bar)

*Type Format On Save

*Enable Format On Save if it is not checked

Done!

A: Download the Prettier extension for VSCode. Follow this article.

A: I have had the same issue, even thus I have installed the Prettier extension. It shows later that I have had another extension called JS-CSS-HTML Formatter. I uninstalled JS-CSS-HTML Formatter and kept Prettier, and all problem was solved.
This issue is mentioned here as well.


text:
Q: Husky pre-commit doesn't fire in create-react app I installed husky to automatically format my code as CRA docs say. When I try to commit files, pre-commit actions just don't fire and non-formatted files are committed. What can I do with that?
I didn't do anything connected with Prettier or Husky that is not written in CRA docs: only installed prettier, husky, and lint-staged and added some code in package.json. Also I saw some similar questions there, but the answers are mostly connected with Node and Git versions and it's not my case.
Node version: v14.17.5
Git version: 2.32.0.windows.2
package.json:
{
  "name": "ts-react-course",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.4.0",
    "@types/node": "^16.11.19",
    "@types/react": "^17.0.38",
    "@types/react-dom": "^17.0.11",
    "axios": "^0.24.0",
    "husky": "^7.0.4",
    "lint-staged": "^12.1.7",
    "prettier": "^2.5.1",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-router-dom": "^6.2.1",
    "react-scripts": "5.0.0",
    "types": "^0.1.1",
    "typescript": "^4.5.4",
    "web-vitals": "^2.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "prepare": "husky install"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "husky": {
    "hooks": {
      "pre-commit": "lint-staged"
    }
  },
  "lint-staged": {
    "src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
      "prettier --write"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

A: Husky's API has dropped conventional JS configuration support and create-react-app's documentation is outdated as it shows the old way of configuring it. When you installed Husky with npm install husky you installed the latest Husky version and not the old version.
Proposed solution
npx husky install
npm set-script prepare "husky install"
npx husky add .husky/pre-commit "npx lint-staged"

Here's the associated GitHub issue in create-react-app repository in case you like to stay up-to-date with the fix: https://github.com/facebook/create-react-app/issues/11568


text:
Q: Changing tense in reported questions In a book published by Merriam-Webster, the direct question When is she seeing them again? has been changed to a reported question as following:
He asked when she would be seeing them again.
My question is, why has the present continuous in the direct question been changed to would be + verb/ing in the reported question?

A: Good question. The answer is that when reporting a question, it isn't necessary to report the exact verb tense as the original. You've probably been taught to perfectly back-shift every tense, which is the right way to teach students at first, but the only real requirement in reporting someone's speech is that the meaning stays consistent from the original to the reported speech.
It's like if someone tells you a story, and you tell someone else, you're unlikely to preserve the sentences or even paragraphs, let alone the precise verb tenses.
With your example sentences, the book expects the reader to already understand that
"When is she seeing them again?" is functionally equivalent to "When will she be seeing them again?", so I'm guessing (hoping?) this is not a book aimed at ESL students exposed to reported speech for the first time.
The reported form of "When will she be seeing them again?" is "He asked when she would be seeing them again."
All meaning is preserved.

A: That looks like present continuous, but it is equivalent to "When will she see them
again."
Here is a discussion of "future with present progressive"
Lawless English


text:
Q: Taxonomy image in Drupal 7 I've set up taxonomy in Drupal 7 called Colours. I've added some terms (red, blue etc) and added a colour image to each term.
In a content type I have added a term reference field, so my client can choose colours (the colours in which that product is available).
In Views, rather than listing the taxonomy terms on the node page, I would like instead to output the image associated with the taxonomy term.
Any ideas on how to do this? I've tried endless "output this field as" in Views but just can't get it to work. The only way I've actually got it to work is to upload images when adding content, but that's not ideal obviously.

A: In Drupal 7 you have to add the taxonomy under "relationships". Then the taxonomy images will appear as fields in the view.

A: I had the same issue, all I did was adding a new field called "image" to the taxonomy and inside the view I just called that field. its working well.

A: Your best bet is to create a View Template, and in the template you can look at the value in that field and load the appropriate image in its place.
Here's a guide on doing this in Views 2: http://www.group42.ca/theming_views_2_the_basics
Couldn't find one for Views 3


text:
Q: Multiple Select Menus in Discordjs with Subvalues? I want to have a discord select menu that, given a selection, returns another select menu with a different response. I understand that the code is running through itself again and that it's recognizing the second selection as the first. Any ideas on how to fix that? Yes, I know the values are the same for the selections. I kind of want that.
Code:
const row1 = new MessageActionRow()
  .addComponents(
    new MessageSelectMenu()
    .setCustomId("dummy1")
    .setPlaceholder("Pick something")
    .addOptions({
        label: "One",
        value: "One"
      },
      {
        label: "Two",
        value: "Two"
      }
    )
  );

const row2 = new MessageActionRow()
  .addComponents(
    new MessageSelectMenu()
    .setCustomId("dummy2")
    .setPlaceholder("Pick something")
    .addOptions({
        label: "One",
        value: "One"
      },
      {
        label: "Two",
        value: "Two"
      }
    )
  );

const row3 = new MessageActionRow()
  .addComponents(
    new MessageSelectMenu()
    .setCustomId("dummy3")
    .setPlaceholder("Pick something")
    .addOptions({
        label: "One",
        value: "One"
      },

      {
        label: "Two",
        value: "Two"
      }
    )
  );

await message.channel.send({
  content: "Pick an option",
  components: [row1]
});

const collector1 = message.channel.createMessageComponentCollector();
collector1.on("collect", async(collection1) => {
  collvalue1 = collection1.values[0];
  if (collvalue1 === "One") {
    await message.channel.send("You chose correctly")
  };
  if (collvalue1 === "Two") {
    await message.channel.send("You chose wrong. Try again.");
    await message.channel.send({
      content: "One more time",
      components: [row2]
    });
  };
  const collector2 = message.channel.createMessageComponentCollector();
  collector2.on("collect", async(collection2) => {
    collvalue2 = collection2.values[0];
    if (collvalue2 === "One") {
      await message.channel.send({
        content: "Bruh",
        components: [row3]
      })
    };
    if (collvalue2 === "Two") {
      await message.channel.send({
        content: "Yo",
        components: [row3]
      })
    };
  });
  collection1.deferUpdate();
});


text:
Q: Collision, Rotation and Kinetic Energy I'm new to this community and I think you can help me! I studying Rolling at college and I'm struggling with this question:

Figure shows a cube of mass m sliding without friction at speed $v_0$. It
  undergoes a perfectly elastic collision with the bottom tip of a rod
  of length d and mass M = 2m. The rod is pivoted about a frictionless
  axle through its center, and initially it hangs straight down and is
  at rest. What is the cube's velocity - both speed and direction -
  after the collision?

I tried this:
From kinetic energy conservation:
$$
\frac{mv_0^2}{2} = \frac{mv^2}{2} + \frac{I\omega^2}{2}
$$
$$
I = \frac{Md^2}{12} = \frac{2md^2}{12} =  \frac{md^2}{6}
$$
$$
\frac{mv_0^2}{2} = \frac{mv^2}{2} + \frac{md^2\omega^2}{12}
$$
$$
v_0^2 = v^2 + \frac{d^2\omega^2}{6} \implies (1)
$$
From angular momentum conservation:
$$
\frac{mvd}{2} = I\omega
$$
$$
\frac{mv_0d}{2} = \frac{md^2\omega}{6}
$$
$$
v_0 = \frac{d\omega}{3}
$$
$$
d^2\omega^2 = 9v_0^2 \implies (2)
$$
Substituting (2) into (1):
$$
v^2 = v_0^2 - \frac{3v_0²}{2}
$$
$$
v^2 = -\frac{v_0^2}{2}
$$
But this is a wrong answer, the correct answer is:
$$
v = \frac{v_0}{5}
$$
Could you help me? Thanks in advance!
PS: this is question 86 is from
UPDATE
Especial thanks to @ssj3892414 to point the right direction! I'll put here the correct equation.
From angular momentum:
$$
\frac{mv_0d}{2} = \frac{mvd}{2} + I\omega
$$
$$
\frac{mv_0d}{2} = \frac{mvd}{2} + \frac{md^2\omega}{6}
$$
$$
v_0 = v + \frac{d\omega}{3}
$$
$$
d\omega = 3(v_0 - v)
$$
$$
d^2\omega^2 = 9(v_0^2 - 2vv_0 + v^2)
$$
$$
\frac{d^2\omega^2}{6} = \frac{3(v_0^2 - 2vv_0 + v^2)}{2} \implies (2)
$$
Substituting (2) into (1):
$$
v_0^2 = v^2 + \frac{3}{2}v_0^2 - 3vv_0 + \frac{3}{2}v^2
$$
manipulating this equation gives:
$$
5v^2 - 6vv_0 + v_0² = 0 \implies (v - v_0)(5v - v_0) = 0
$$
So, answers $v = v_0$ and $v_0 = 5v$, which the second one is the right answer!

Knight, Randall Dewey. Physics for scientists and engineers: a
  strategic approach. 3rd ed. Vol. I. Boston: Pearson, 2013, p. 353. Print.

A: The angular momentum conservation equation is wrong. You haven't taken into account the angular momentum of the block after collision.


text:
Q: How to keep same parameters after reloading page/view I currently have a select tag dropdown of a few options and I want to have the page reload with the same option selected when the user selects an option.
So far, I have the following code:
<select name="blah" id="blahblah" onchange="document.location.reload()">
This will reload the page when an option is selected but how would I go about having the page reload with the same parameters/ option selected?


text:
Q: PS get-content high memory usage - Is there a more efficient way to filter a file? I am using get-content to read a largish file (252 MB), but when I use get-content to read it, the powershell process proceeds to consume almost 10 GB of memory. Is this normal behavior?
The array has just shy of 6 million items. It doesn't seem to be remotely in line with the amount of memory being used.
Maybe I'm just going about this the wrong way entirely.
I want to write the line that matches a string and the subsequent line to a new text file.
$mytext = get-content $inpath
$search = "*tacos*"
$myindex = 0..($mytext.count - 1) | Where {$mytext[$_] -like $search}
$outtext = @()
foreach ($i in $myindex){
    $outtext = $outtext + $mytext[$i] + $mytext[$i+1]
    }
$outtext | out-file -filepath $outpath

Performance Testing Results
I took a performance sample for different scripts based on different answers here.
My original script
(highly sensitive to the number of lines that get written out)

*

*10k lines - 1.8s

*100k lines - 38s

*100k lines - 21s (when search string occurs rarely)

*5000k lines - Too long to measure (aborted after several hours)

Select-String with no Get-Content (adapted from whatever)
Select-String -path $inpath -pattern $search -Context 0,1 -SimpleMatch | Out-File $outpath

*

*10k lines - 1.2s

*100k lines -  4s

*1000k lines - 107s
Note processing speed only grows by a factor of ~4 for a 10x increase in input. The more data you try to process at once, the better this solution becomes relative to the others.
Eliminating the array resize (from Mathias)

*

*10k lines - 2.0s

*100k lines - 25s

*1000k lines - 1533s (using 1.7GB memory, the same as running gc outside of the script on 1000k lines)

Using the pipeline (from Chris Dent)

*

*100k lines - 26s

A:
process proceeds to consume almost 10 GB of memory. [...] The array has just shy of 6 million items. It doesn't seem to be remotely in line with the amount of memory being used.

Get-Content against a file of 6 million lines results in 6 million string objects - and allocating a string object is not just allocating memory for the characters themselves but also an object header and additional overhead.
That would only account for about 5-10% of what you're seeing though - the real problem is this construct:
$outtext = @() # this
foreach ($i in $myindex){
    $outtext = $outtext + $mytext[$i] + $mytext[$i+1] # and this
}

Every time you re-assign the values of the array like that, the underlying array has to be resized, causing .NET to copy the contents to a new array.
Change it to:
$outtext = foreach ($i in $myindex){
    $mytext[$i],$mytext[$i+1]
}

A: The pipeline is your friend. There's no advantage to be gained from your indexing process other than making it take longer and add more into memory.
This gets the line you're searching for, plus the one line of context you need (from the example). Nothing is loaded into memory except the items that match your search plus that one line.
$getNext = $false
$outtext = Get-Content $inPath | ForEach-Object {
    if ($_ -like $search) {
        $_
        $getNext = $true
    }
    elseif ($getNext) { #reads the following line on next iteration
        $_
        $getNext = $false
    }
}

A: Another option is Select-String:
$search = "tacos"
Get-Content $inpath | Select-String $search -Context 0,1 | Out-File $OutputFile -Append

However, this will produce slightly changed output:
match
following line

will turn into
> match
  following line

if you want the exact lines from the file:
Get-Content $inpath | Select-String $search -Context 0,1 | foreach {$_.Line | Out-File $OutputFile -Append ; $_.Context.Postcontext |  Out-File $OutputFile -Append}

Btw: Get-Content gets kinda slow once files get really big. Once that happens it might be better to do:
$TMPVar = Get-Content $inpath -Readcount 0
$TMPVar | Select-String....

This will make Get-Content read the entire file at once instead of line by line which is much faster but needs a bit more memory than piping it directly into the next cmdlets.


text:
Q: Renewing AWS AssumeRoleRequest on expiry I have the following for assuming role credentials for my lambda client:
    AWSSecurityTokenServiceClient stsClient = new AWSSecurityTokenServiceClient(credentials);
    AssumeRoleRequest assumeRequest = new AssumeRoleRequest()
            .withRoleArn(config.getAssumeLambdaARN())
            .withDurationSeconds(3600)
            .withRoleSessionName("AssumeRoleTest");

    AssumeRoleResult assumeResult = stsClient.assumeRole(assumeRequest);
    BasicSessionCredentials temporaryCredentials =
            new BasicSessionCredentials(
                    assumeResult.getCredentials().getAccessKeyId(),
                    assumeResult.getCredentials().getSecretAccessKey(),
                    assumeResult.getCredentials().getSessionToken());
    AWSLambdaClientBuilder lambdaClientBuilder = AWSLambdaClientBuilder.standard();
    lambdaClientBuilder.setCredentials(new AWSStaticCredentialsProvider(temporaryCredentials));
    lambdaClientBuilder.setRegion(config.getAwsRegion());

    lambdaClient = lambdaClientBuilder.build();

AssumeRoleRequest is going to expire after 1hr. How do I automatically create another assumeRequest and re-create the lambdaClient when the request is expired?


text:
Q: d3js removing a transition of an element I have a SVG image (alpha) where I want to show some control options group on mouseover and hide them on mouse out.
Let's say I have the  image alpha in x=100, y=100. I have a predefined tooltip classed group in my svg with the style 'visibility':'hidden'.
I change the style to visible and I set its x,y coordinates to alpha.attr('x')-20 , alpha.attr('y')-20 . So that it comes in the left corner of the image. But when I mouseout from the image the group hides itself, to overcome that issue I gave a delay with the setTimeOut() function. But when I mouse over to the control group it changes it style to hidden because of the delay.
I tried using the d3.transition but I couldn't figure out how to remove it once I hover the control group.
I do not know how to overcome the issue and achieve my requirement. can anyone help me?
d3.select('#svg')
    .append('g')
    .attr('id', 'playground')
    .append('image')
    .attr('class', 'tooltip')
    .attr('width', 20)
    .attr('height', 20)
    .attr('x', 0)
    .attr('y', 0)
    .attr('xlink:href', base_url + '/assets/svg/api_lbs_color.svg')
    .style('visibility', 'hidden')
    .on('mouseover', function () {
        d3.select(this).style('visibility','visible');
    })
    .on('mouseout', function () {
        d3.select(this).style('visibility','hidden');

    });

playGround
            .append('image')
            .attr('width', 32)
            .attr('height', 32)
            .attr('x', d3.mouse(this)[0])
            .attr('y', d3.mouse(this)[1])
            .attr('xlink:href', curr.attr('xlink:href'))
            .on("mouseover", function(d) {  // the mouseover event
                console.log('mouse over playgrround operator');

                var curr = d3.select(this);

                d3.select('.tooltip')
                    .attr('x', curr.attr('x') - 20)
                    .attr('y', curr.attr('y') - 20)
                    .style('visibility', 'visible')
                ;

            })
            .on('mouseout', function () {

                setTimeout(function () {
                    d3.select('.tooltip')
                        .style('visibility', 'hidden')

                }, 1000);

            })
        ;

A: I don't exactly understand the functionality you want but I think I've had a similar problem in the past. You should be using the mouseenter and mouseexit events instead of mouseover and mouseout, that will allow the tooltip to stay visible while the cursor is inside the image element.


text:
Q: How can I make the legend horizontal in the euler plot in R? I'm having difficulty styling this euler plot. One of my main issues is that I'd like the legend to be on the bottom, but display the variables horizontally. They look strange stacked vertically.
If anyone also knows how to adjust the margins, add a border around the whole plot, and add a subtitle, I'm stumped on those things too. I've already tried par(mar) and that didn't have any effect.
fit1 <- euler(c("Day 1" = 69, "Day 2" = 109, "Day 3" = 152,
                "Day 1&Day 2" = 11, "Day 1&Day 3" = 18, "Day 2&Day 3" = 28,
                "Day 1&Day 2&Day 3" = 2))

col <- c("#66D2D6", "#FBC740", "#E56997")

plot(fit1,
     quantities = TRUE,
     fills = list(fill = col, alpha = 0.8),
     edges = "black",
     main = list(label = "test", cex = 0.9),
     legend = list(side = "bottom"))

A: The plot method for euler objects uses grid::grid.legend() to plot the legend.  You can specify any of grid.legend's arguments in the legend argument to plot (which really calls plot.euler).  To get a horizontal legend, use
plot(fit1,
     quantities = TRUE,
     fills = list(fill = col, alpha = 0.8),
     edges = "black",
     main = list(label = "test", cex = 0.9),
     legend = list(side = "bottom", nrow = 1, ncol = 3))


text:
Q: How to append a row of a CSV as a string (and not individual lists) to a list I have a .csv file with one column (approx 5k rows). I want to convert all this into a list that looks like this:
key_list = ['key_1','key_2','key_3'...]

The 'key_1', 'key_2' etc are individual rows within my csv file.
To do this, I am using the csv module. My code does:
import csv

key_list = []

with open('key_list.csv','r') as file:
    reader = csv.reader(file, delimiter = ',')

    for row in reader:
        key_list.append(row)

However this creates the following output when I go to print(key_list):
[['key_1'],['key_2']]

When I then go to use this in my code, by looping through the list, I am trying to save key_list[0] = 'key_1' as a string, but my code is outputting ['key_1'] as a list and failing.
What do I need to change so I can get a list that looks like:
key_list = ['key_1','key_2','key_3'...]

Thank you

A: You can unpack the first column from the row:
key_list = [key for key, in reader]

A: You can also do in one line with map:
import csv
key_list = list(map(lambda row: row[0], csv.reader(open('key_list.csv'))))
print(key_list)

Or list comprehension:
import csv
key_list = [row[0] for row in csv.reader(open('key_list.csv'))]
print(key_list)

A: When you read the CSV file, each row is going to be treated as a list. so changing each list to a string will give you the key_list = ['key_1','key_2','key_3'...] as key_1, key_2, ... as a string.
Try this one,
import csv

key_list = []

with open('snakes_count_10.csv','r') as file:
    reader = csv.reader(file, delimiter = ',')

    for row in reader:
        key_list.append(', '.join(row))

print(key_list)


text:
Q: Busca com REGEX no VI Tenho uma regex que é válida conforme o teste do site https://regex101.com/ , porem no vi ela não funciona:
2017\/04\/26 12:24:(.*)(89418644)

Seguem um exemplo que esta REGEX deveria casar:
INFO| 2017/04/26 12:24:15.019 | [OrderEntryAvailableOutgoingFlowListPopulator] 89418644 OK
Acredito que seja alguma regra de sintaxe para utilização de grupos na busca do vi, mas ainda não consegui identificar.

A: Ao realizar um pesquisa no vi ele não interpreta direto que o que você esta usando é uma REGEX, de tal forma que o que ele pesquisa na verdade é um String.
Assim você deve usar a mesma lógoca quando de passa um String para REGEX, e é necessário escapar os caracteres especiais.
2017\/04\/26 12:24:\(.*\)\(89418644\)
Adendo
Se você esta apenas pesquisando você poderia simplesmente remover os grupos :
2017\/04\/26 12:24:.*89418644
Caso voce esteja trabalhando com replace a um modificador que auxilia nisso \v :
:%s/\v2017\/04\/26 12:24:(.*)(89418644)/REPLACE/
Fonte Vim Regex Capture Groups


text:
Q: How do I squelch "fatal: The upstream branch of your current branch does not match the name of your current branch"? There is a related question on SO dealing with how to change the parameters of the push command to avoid this message:
fatal: The upstream branch of your current branch does not match the name of your current branch
I'm interested in how to squelch the message itself, without changing the names of my local/remote branches or using fancy push commands.
Suppose I have a local branch tracking a remote branch of a different name:
user@home:~ git branch -vv
branch-name abcd1234 [remote/origin/branch-name] last commit message

Now I want to be able to push my commited changes by simply typing git push. When I do this, I get the following message:

fatal: The upstream branch of your current branch does not match
the name of your current branch.  To push to the upstream branch
on the remote, use

    git push origin HEAD:remote/origin/branch-name

To push to the branch of the same name on the remote, use

    git push origin branch-name

How do I force git to automatically push to the upstream branch even if the names don't match? I'm using git 1.9.1

A: Newer Git (v 1.9 or newer)
git config --global push.default upstream

Older Git
git config --global push.default tracking

Git 2.3 still accepts tracking as a synonym for upstream
Just do that once and whenever you "git push" it will push your current branch to its configured upstream.
This also sets it in your global config, which might be shadowed by a different setting in your repository config.


text:
Q: GMSMapView clear doesn't clear memory I have a GMSMapView in my app. The app with an open map screen takes 150 mb in memory.
At some point I add a lot of polygons. After that the application takes 230 mb.
After calling the method [GMSMapView clear] all polygons disappear, but app still takes 230 mb in memory.
Pointers to Polygons are not stored anywhere else.
How to make the map clear the memory an why it does not happen after calling 'clear' method?

A: Well, this is pain in a**... I not found the official docs.
My solution:
Swift 3.0
1) Do not use Storyboard, create mapView in code:
@IBOutlet weak fileprivate var mapViewContainer: UIView!

weak fileprivate var mapView: GMSMapView? {
    didSet {
        //you can config and customise your map here
        self.configureMapView()
    }
}

//If you use clustering
fileprivate var clusterManager: ClusterManager?
fileprivate var clusterRenderer: ClusterRenderer?

2) Create viewController configure function & call it before viewDidLoad:
func configure() {
    mapView = GMSMapView()
    mapView?.delegate = self
}

3) Layout & add mapView to your UI:
override func viewDidLoad() {
    super.viewDidLoad()

    if let mapView = mapView {
        mapViewContainer.addSubview(mapView)
        //Create constraints as you wish
        mapView.fillView()
        mapViewContainer.layoutSubviews()
    }
}

4) Now create function:
func releaseMemory() {

    if
        let mapView = mapView,
        let clusterManager = clusterManager {

        clusterManager.clearItems()
        mapView.clear()
        mapView.delegate = nil
        mapView.removeFromSuperview()

    }

    clusterManager = nil
    clusterRenderer = nil
    mapView = nil
}

You call it in ViewDidDisappear, or call delegate...
releaseMemory() function clear memory, not so smart, but it works.

A: You might try storing the polygon objects somewhere and then call polygon.map = nil on all of them, delete the polygon references and then call the map view clear


text:
Q: Parsing html tag link with Powershell I want to copy the content of the first tag (the link) to the next 2 tags:
<link rel="canonical" href="https://website.com/en/america.html" />

to
<meta property="og:url" content="https:/something-better/rosrr.html"/>

"@id": "https://distrinct.com/stiintess-pomei.html"

Output:
<link rel="canonical" href="https://website.com/en/america.html" />

<meta property="og:url" content="https://website.com/en/america.html"/>

"@id": "https://website.com/en/america.html"

I really don't know why my Powershell code is not working as I want:
$sourcedir = "C:\Folder1\"
$resultsdir = "C:\Folder1\"

Get-ChildItem -Path $sourcedir -Filter *.html | ForEach-Object {
    $content = Get-Content -Path $_.FullName -Raw
    $replaceValue = (Select-String -InputObject $content -Pattern '(?<=<link rel="canonical" href=").+(?=" />)').Matches.Value
    $content = $content -replace '(<meta property="og:url" content=").+("/>)',$replaceValue
    $content = $content -replace '("@id": ").+(")',$replaceValue
    Set-Content -Path $resultsdir\$($_.name) $content
}

This is what I get, instead of the Output I want:

A: I figured it out. To make a parsing in Powershell, with regex, must use the same "start" and the same "stop". And you have to pay attention to the regex formula:
$sourcedir = "C:\Folder1\"
$resultsdir = "C:\Folder1\"

Get-ChildItem -Path $sourcedir -Filter *.html | ForEach-Object {
    $content = Get-Content -Path $_.FullName -Raw
    $replaceValue = (Select-String -InputObject $content -Pattern '(?<=<link rel="canonical" href=").*(")').Matches.Value
    $content = $content -replace '(?<=<meta property="og:url" content=").*(")',$replaceValue
    $content = $content -replace '(?<="@id": ").*(")',$replaceValue
    Set-Content -Path $resultsdir\$($_.name) $content
}


text:
Q: Setting large images in UIScrollView I want to put images in UIScrollView. However, the problem is that when I try to put an image larger than UIScrollView, UIScrollView shows the upper part of images. I would like the scrollview to show the bottom part of the image. Right now, I have the following code:
let imgBot1 = UIImage(named:"Img1.jpg");
let imgBot2 = UIImage(named:"Img4.jpg");
let imgBot3 = UIImage(named:"Img5.jpg");

//Adding UIImage in UIImageView
let imgView1 = UIImageView(image:imgBot1)
let imgView2 = UIImageView(image:imgBot2)
let imgView3 = UIImageView(image:imgBot3)

//creating UIScrollView
let scrView2 = UIScrollView()

scrView2.frame = CGRectMake(0, self.view.frame.height/2,
self.view.frame.width, self.view.frame.height)

//content size of the scrollview
scrView2.contentSize = CGSizeMake(self.view.frame.width*3, self.view.frame.height)

//Size and place of UIImageView
imgView1.frame = CGRectMake(0, 0, self.view.frame.width, self.view.frame.height)
imgView2.frame = CGRectMake(width, 0, self.view.frame.width, self.view.frame.height)
imgView3.frame = CGRectMake(width*2, 0, self.view.frame.width, self.view.frame.height)

//adding the scrollview to the view
self.view.addSubview(scrView2)

scrView2.addSubview(imgView1)
scrView2.addSubview(imgView2)
scrView2.addSubview(imgView3)

scrView2.pagingEnabled = true

//Initial location of the scrollview
scrView2.contentOffset = CGPointMake(0, 0);

I would like to know how I can make the scrollview to show the bottom part of the image, and not the top part. Will you help me out?

A: I made this code, hope it will work for you. I used the storyboard, made a scrollView, added an imageView and added constrains to the image view to stick to the edges (don't know it that's necessary).
imageView = UIImage(named: "image")
scrollView.contentOffset = CGPoint(x: 0, y: image.image!.size.height)


text:
Q: Customizing Community with html header I am customizing community (VF + tabs) and whenever I add html header in the community, default user options on right hand side are not longer available.
Is there a way to use html header with all user options like My settings, logout still available?
Thanks


text:
Q: mc (midnight commander) view (F3) strange behavior when there is a "." in the filename It seems to ignore newline characters in "parsed" view. In raw view everything is fine. Same thing happens in nano "justified" mode.
a) parsed text file

b) same file in raw mode

c) vi with :set list

d) same file in parsed mode when the name is changed to "tt"

Can anyone explain this?

A: The problem is not the ., but the .1 . This extension is used for man pages - and so the viewer tries to interpret this as a man page.
Edit: this is controlled by the file /etc/mc/mc.ext - you'll find a
# Manual page
regex/(([^0-9]|^[^\.]*)\.([1-9][A-Za-z]*|[ln])|\.man)$
        Open=/usr/lib/mc/ext.d/text.sh open man %var{PAGER:more}
        View=%view{ascii,nroff} /usr/lib/mc/ext.d/text.sh view man %var{PAGER:more}

Entry.


text:
Q: How can I mirror my phone to Ubuntu? I have a Nexus 6 phone. I have a smaller PC with Ubuntu 15.04 connected to my TV. How can I stream my phones screen to the Ubuntu machine, with Airplay like behavior? My phone has Chromecast client built in, but Miracast is not supported afaik. I dont have a Chromecast stick.
Is there a Chromecast/similar server available on Ubuntu?


text:
Q: unable to install awscli using pip on dind 18.09.6-dind due to cython dependency I saw a strange issue just most of yesterday where while running a simple jenkins build that uses pod template with container docker:18.09.6-dind (alpine linux) the build would fail while trying to install awscli using pip. Here is the sample code:-

apk add curl
apk add py-pip
pip install --user awscli

The error was :-

apk add py-pip
(1/11) Installing libbz2 (1.0.6-r7)
(2/11) Installing expat (2.2.8-r0)
(3/11) Installing libffi (3.2.1-r6)
(4/11) Installing gdbm (1.13-r1)
(5/11) Installing ncurses-terminfo-base (6.1_p20190518-r2)
(6/11) Installing ncurses-libs (6.1_p20190518-r2)
(7/11) Installing readline (8.0.0-r0)
(8/11) Installing sqlite-libs (3.28.0-r3)
(9/11) Installing python2 (2.7.18-r0)
(10/11) Installing py-setuptools (40.8.0-r1)
(11/11) Installing py2-pip (18.1-r0)
Executing busybox-1.30.1-r2.trigger
OK: 74 MiB in 54 packages
[Pipeline] withAwsCli
Executing sh script inside container dind of pod pod-custom-w741q
Executing command: "pip" "--version"
exit
pip 18.1 from /usr/lib/python2.7/site-packages/pip (python 2.7)
Executing sh script inside container dind of pod pod-custom-w741q
Executing command: "pip" "show" "awscli"
exit
ERROR: [withAwsCli] Command 'pip show awscli' returned the code 1
Executing sh script inside container dind of pod pod-custom-w741q
Executing command: "pip" "install" "--user" "awscli"
exit
Collecting awscli
  Downloading https://files.pythonhosted.org/packages/d9/d3/1b76aa71fea8438f82a991ad94443d343836848f8b8c0dc413ed987745f8/awscli-1.19.51-py2.py3-none-any.whl (3.6MB)
Collecting botocore==1.20.51 (from awscli)
  Downloading https://files.pythonhosted.org/packages/3c/1d/7a3741f17a10cc599bb3728351992b10094328ee07b8a129250ba2039642/botocore-1.20.51-py2.py3-none-any.whl (7.4MB)
Collecting colorama<0.4.4,>=0.2.5 (from awscli)
  Downloading https://files.pythonhosted.org/packages/c9/dc/45cdef1b4d119eb96316b3117e6d5708a08029992b2fee2c143c7a0a5cc5/colorama-0.4.3-py2.py3-none-any.whl
Collecting PyYAML<5.5,>=3.10 (from awscli)
  Downloading https://files.pythonhosted.org/packages/a0/a4/d63f2d7597e1a4b55aa3b4d6c5b029991d3b824b5bd331af8d4ab1ed687d/PyYAML-5.4.1.tar.gz (175kB)
  Installing build dependencies: started
  Installing build dependencies: finished with status 'error'
  Complete output from command /usr/bin/python2 -m pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-mT9r0n --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel Cython:
  Collecting setuptools
    Downloading https://files.pythonhosted.org/packages/e1/b7/182161210a13158cd3ccc41ee19aadef54496b74f2817cc147006ec932b4/setuptools-44.1.1-py2.py3-none-any.whl (583kB)
  Collecting wheel
    Downloading https://files.pythonhosted.org/packages/65/63/39d04c74222770ed1589c0eaba06c05891801219272420b40311cd60c880/wheel-0.36.2-py2.py3-none-any.whl
  Collecting Cython
    Downloading https://files.pythonhosted.org/packages/d9/cd/0d2d90b27219c07f68f1c25bcc7b02dd27639d2180add9d4b73e70945869/Cython-0.29.23.tar.gz (2.1MB)
  Installing collected packages: setuptools, wheel, Cython
    Running setup.py install for Cython: started
      Running setup.py install for Cython: finished with status 'error'
      Complete output from command /usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-72Od1r/Cython/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-Qfbz7l/install-record.txt --single-version-externally-managed --prefix /tmp/pip-build-env-mT9r0n --compile:
      Unable to find pgen, not compiling formal grammar.
      running install
      running build
      running build_py
      creating build
      creating build/lib.linux-x86_64-2.7
      copying cython.py -> build/lib.linux-x86_64-2.7
      creating build/lib.linux-x86_64-2.7/Cython
      copying Cython/TestUtils.py -> build/lib.linux-x86_64-2.7/Cython
      copying Cython/Utils.py -> build/lib.linux-x86_64-2.7/Cython
      copying Cython/CodeWriter.py -> build/lib.linux-x86_64-2.7/Cython
      copying Cython/Debugging.py -> build/lib.linux-x86_64-2.7/Cython
      copying Cython/StringIOTree.py -> build/lib.linux-x86_64-2.7/Cython
      copying Cython/__init__.py -> build/lib.linux-x86_64-2.7/Cython
      copying Cython/Coverage.py -> build/lib.linux-x86_64-2.7/Cython
      copying Cython/Shadow.py -> build/lib.linux-x86_64-2.7/Cython
      creating build/lib.linux-x86_64-2.7/Cython/Build
      copying Cython/Build/Dependencies.py -> build/lib.linux-x86_64-2.7/Cython/Build
      copying Cython/Build/__init__.py -> build/lib.linux-x86_64-2.7/Cython/Build
      copying Cython/Build/Distutils.py -> build/lib.linux-x86_64-2.7/Cython/Build
      copying Cython/Build/Inline.py -> build/lib.linux-x86_64-2.7/Cython/Build
      copying Cython/Build/BuildExecutable.py -> build/lib.linux-x86_64-2.7/Cython/Build
      copying Cython/Build/Cythonize.py -> build/lib.linux-x86_64-2.7/Cython/Build
      copying Cython/Build/IpythonMagic.py -> build/lib.linux-x86_64-2.7/Cython/Build
      creating build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/FlowControl.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Code.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/MemoryView.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Pipeline.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/AnalysedTreeTransforms.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/CythonScope.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/TypeSlots.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Errors.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/FusedNode.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/PyrexTypes.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/AutoDocTransforms.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/UtilityCode.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/StringEncoding.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Version.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/CmdLine.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/UtilNodes.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/ParseTreeTransforms.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Visitor.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/TypeInference.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/__init__.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Options.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/DebugFlags.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Scanning.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/ExprNodes.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Interpreter.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Builtin.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Annotate.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Symtab.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Optimize.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Parsing.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Naming.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/ModuleNode.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/TreeFragment.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Nodes.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Future.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/TreePath.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Main.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/CodeGeneration.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Buffer.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Pythran.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      copying Cython/Compiler/Lexicon.py -> build/lib.linux-x86_64-2.7/Cython/Compiler
      creating build/lib.linux-x86_64-2.7/Cython/Runtime
      copying Cython/Runtime/__init__.py -> build/lib.linux-x86_64-2.7/Cython/Runtime
      creating build/lib.linux-x86_64-2.7/Cython/Distutils
      copying Cython/Distutils/old_build_ext.py -> build/lib.linux-x86_64-2.7/Cython/Distutils
      copying Cython/Distutils/__init__.py -> build/lib.linux-x86_64-2.7/Cython/Distutils
      copying Cython/Distutils/build_ext.py -> build/lib.linux-x86_64-2.7/Cython/Distutils
      copying Cython/Distutils/extension.py -> build/lib.linux-x86_64-2.7/Cython/Distutils
      creating build/lib.linux-x86_64-2.7/Cython/Debugger
      copying Cython/Debugger/DebugWriter.py -> build/lib.linux-x86_64-2.7/Cython/Debugger
      copying Cython/Debugger/libpython.py -> build/lib.linux-x86_64-2.7/Cython/Debugger
      copying Cython/Debugger/__init__.py -> build/lib.linux-x86_64-2.7/Cython/Debugger
      copying Cython/Debugger/Cygdb.py -> build/lib.linux-x86_64-2.7/Cython/Debugger
      copying Cython/Debugger/libcython.py -> build/lib.linux-x86_64-2.7/Cython/Debugger
      creating build/lib.linux-x86_64-2.7/Cython/Debugger/Tests
......................................
......................................
      running build_ext
      building 'Cython.Plex.Scanners' extension
      creating build/temp.linux-x86_64-2.7
      creating build/temp.linux-x86_64-2.7/tmp
      creating build/temp.linux-x86_64-2.7/tmp/pip-install-72Od1r
      creating build/temp.linux-x86_64-2.7/tmp/pip-install-72Od1r/Cython
      creating build/temp.linux-x86_64-2.7/tmp/pip-install-72Od1r/Cython/Cython
      creating build/temp.linux-x86_64-2.7/tmp/pip-install-72Od1r/Cython/Cython/Plex
      gcc -fno-strict-aliasing -Os -fomit-frame-pointer -g -DNDEBUG -Os -fomit-frame-pointer -g -DTHREAD_STACK_SIZE=0x100000 -fPIC -I/usr/include/python2.7 -c /tmp/pip-install-72Od1r/Cython/Cython/Plex/Scanners.c -o build/temp.linux-x86_64-2.7/tmp/pip-install-72Od1r/Cython/Cython/Plex/Scanners.o
      unable to execute 'gcc': No such file or directory
      error: command 'gcc' failed with exit status 1

      ----------------------------------------
  Command "/usr/bin/python2 -u -c "import setuptools, tokenize;__file__='/tmp/pip-install-72Od1r/Cython/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-record-Qfbz7l/install-record.txt --single-version-externally-managed --prefix /tmp/pip-build-env-mT9r0n --compile" failed with error code 1 in /tmp/pip-install-72Od1r/Cython/

  ----------------------------------------
Command "/usr/bin/python2 -m pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-mT9r0n --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- setuptools wheel Cython" failed with error code 1 in None

It always worked fine until yesterday and also works fine now on same dind OS. I have no clue why was it trying to set up dependency cython just yesterday. I see a new version of cython was released yesterday
https://pypi.org/search/?q=cython
Not sure if that played any role
I am not that familiar with how pip works when it tries to install something so would like to understand why it was looking for cython all of a sudden while its the same pip version 18.1 on that dind OS and trying to fetch latest awscli which happened to be released just yesterday 1.19.51 as per
https://github.com/aws/aws-cli/releases
Also yesterday same thing worked just fine all throughout on docker:18.06.1-ce-dind or other dind versions. So something specific to docker:18.09.6-dind and combination of pip 18.1 and awscli 1.19.51.
kindly help me figure out what could have been the issue here.

A: Found out the root cause which is
https://github.com/aws/aws-cli/issues/6096


text:
Q: Troubleshooting SQL Server Strange Timeout I have a fairly generic select query. When I select the top 1245 results of a particular result set, it runs in under a second, as expected. However, if I run it for 1246, it runs continuously as if on an infinite loop. I've checked the formatting of rows 1245 and 1246, the data for which appears completely fine. I can also run the same query on a separate group of users numbering over 2300, which again, runs almost instantly, which makes me think it's not in relation to memory issues.
As a quick example of the query formatting:
SELECT TOP 1246 a.id,
(SELECT TOP 1 col_1 FROM table_1 t INNER JOIN table_2 c ON t.id=c.id WHERE t.id=a.id) AS [columnAlias]
FROM table_3 a

Open to any ideas on troubleshooting.
If I can provide anything else that might help, just ask.

A: The difference in performance is probably due to changes in the execution plan.  You might want to check that statistics are up-to-date.
Second, your query really makes no sense, because the subquery has no relationship to the outer query.  So, you might as well accept that you are going to get a single value and move it to the from clause:
SELECT TOP 1246 a.id, col_1 AS [columnAlias]
FROM table_3 a CROSS JOIN
     (SELECT TOP 1 col_1 FROM table_1 t INNER JOIN table_2 c ON t.id=c.id);

Finally, if you have some other intention with your query, you should ask another question.  If you revise your question, you may invalidate this answer which draws downvotes.

A: "Running continuously on an infinite loop" when you get to a specific record makes me suspicious that you are encountering a deadlocking situation. There isn't anything obvious in what you posted that would cause it, so I'd suspect there is a context where this is running, e.g. it's part of a several step transaction, that could be the cause.


text:
Q: How to use switch operator and best way to iterate string and detect symbols How to implement this logic with switch operator instead of large if/else?
   type token =
  | DOT
  | OPEN_BRACKET
  | SYMBOL;

let dot_code = ".".[0] |> Char.code;
let open_bracket_code = "{".[0] |> Char.code;

let char_to_token symbol :token => {
  let code = Char.code symbol;
  let c =
    if (code === dot_code) {
      DOT
    } else if (code === open_bracket_code) {
      OPEN_BRACKET
    } else {
      SYMBOL
    };
  c
};

String.iter
  (
    fun symbol => {
      let c = char_to_token symbol;
      switch c {
      | DOT => print_string " DOT "
      | OPEN_BRACKET => print_string " OPEN_BRACKET "
      | SYMBOL => print_char symbol
      }
    }
  )
  "a.s {";

Or what is the best way to iterate string and detect symbols like . and { ?

A: First, instead of ".".[0] |> Char.code, try '.' |> Char.code. Reason/OCaml has character literals. In this case, since it's a single pipe, Char.code '.' is encouraged.
Second, I'd personally use a switch in char_to_token too:
let char_to_token symbol :token =>
  switch symbol {
  | '.' => DOT
  | '{' => OPEN_BRACKET
  | _ => SYMBOL
  };

Which obviates the need for the above let dot_code = ... in the first place. The benefit of using switch, as you might have guessed, is that it's more efficient. See the compiled-to-js code here. Same thing happens for native compilation.
The rest looks good! Btw since you've told me (in discord) that you've just started Reason, I'd say this is pretty simple and keep it this way! When you get more proficient, I sense that you might want a real parser here or try GADT (http://mads-hartmann.com/ocaml/2015/01/05/gadt-ocaml.html).


text:
Q: globalize2 with xml/json support I'm implementing a distributed application, server with rails and mobile clients in objective c (iPhone). To enable internationalization, I use the rails plugin 'globalize2' by joshmh.
However, it turned out that this plugin does not translate attributes when calling to_xml or to_json on an ActiveRecord. Does anyone know of a workaround / patch? Do you have any ideas how to fix this, where to alter globalize2?
Using:
Rails 2.3.5
globalize2: commit from 2010-01-11

A: With Globalize2 (and with model_translations as well) translated attribute in a model is not a real attribute but is a method. Thus and so when you execute to_json method you can use :methods, as Joris suggested, but in a simpler way:
class Post < ActiveRecord::Base
  attr_accessible :title, :text
  translates :title, :text
end

class PostsController < ApplicationController
  def index
    @posts = Post.all
    respond_to do |format|
        format.html
        format.json { render :json => { :posts => @posts.to_json(:only => :id, :methods => :title) }}
        format.js
    end
  end
end

Here I would like to receive only post id and title in json response. For additional information see to_json (Serialization) in Rails API.

A: I found this fork on github: http://github.com/leword/globalize2
But it looks like it is based on an older version.
I was looking for this myself, but solved my problem using the :methods option:
If you want to translate one attribute in @item, you can use:
class Item < ActiveRecord::Base
  translates :name
  def t_name
    self.name
  end
end

And in your controller:
render :text => @item.to_xml(:methods => [ :t_name ])

If your api path is something like /en/api/item.xml, you should get the english translation in the t_name attribute
For a belongs_to relation:
belongs_to :category
def category_name
  self.category.name
end

And in your controller:
render :text => @item.to_xml(:methods => [ :category_name ])

Your use case is probably different. Above is a workaround that works for me.


text:
Q: Return only the Hours and Minutes part of the timestamp from Firestore - React Native I am trying to return the Hours and Minutes part from a timestamp. I can currently return the time but it is returning the seconds as well, which I would like to trim from the time.
<Text style={{ fontWeight: "300" }}>{data.endtime.toDate().toLocaleTimeString('en-GB')}</Text>

I am using moment.js and have tried setting the format in the state as "HH:mm"

A: This solution is a quick-and-dirty way to solve your problem, but maybe look into something else more elegant. This is essentially cutting off the last 3 character from the string
<Text style={{ fontWeight: "300" }}>{data.endtime.toDate().toLocaleTimeString('en-GB').substring(0, 5)}</Text>


text:
Q: How to insert records from multiple rows in a table into single rows (group my ID) in other table? I have a table with records  as:
ID  |NAME   |FULLNAME
ID1 |John   |John S
ID1 |Tom    |Tom S
ID2 |Tin    |Tin J
ID2 |Jim    |Jim B
ID2 |Kethy  |Kethy T
ID3 |Neo    |Neo L

I want to create a new table and insert the records as below :
ID  |NAME1  |FULLNAME1  |NAME2  |FULLNAME2  |NAME3         |FULLNAME3
ID1 |John   |John S     |Tom    |Tom S
ID2 |Tin    |Tin J      |Jim    |Jim B      |Kethy         |Kethy T
ID3 |Neo    |Neo L

The structure of the new table is fixed with 7 columns in total.

A: Try the following statement:
CREATE TABLE new_table AS
SELECT name1.id
     , name1.name AS name1
     , name1.fullname AS fullname1
     , name2.name AS name2
     , name2.fullname AS fullname2
     , name3.name AS name3
     , name3.fullname AS fullname3
  FROM ( SELECT *
           FROM ( SELECT id, name, fullname
                       , rank() over ( partition by id order by fullname asc) as rank
                    FROM old_table )
          WHERE rank = 1) name1
     , ( SELECT *
           FROM ( SELECT id, name, fullname
                       , rank() over ( partition by id order by fullname asc) as rank
                    FROM old_table )
          WHERE rank = 2) name2
     , ( SELECT *
           FROM ( SELECT id, name, fullname
                       , rank() over ( partition by id order by fullname asc) as rank
                    FROM old_table )
          WHERE rank = 3) name3
 WHERE name1.id = name2.id (+)
   AND name1.id = name3.id (+)
 ORDER BY name1.id ASC;

There may be some ways to optimize it somehow but it seems to produce the result you're looking for.

A: if your database version is 11g or higher you can use the pivot function , which can transfer rows into columns.
examples here : http://www.dba-oracle.com/t_pivot_examples.htm
to determine what is your database version : How can I confirm a database is Oracle & what version it is using SQL?
select * from v$version;


text:
Q: Conditional fusion of two arrays I have two arrays:
$array1 = ['a', 'b', 'c'];
$array2 = ['d', 'e', 'f'];

Please tell me how to get to the output I received:
$array3 = [
    'a-d',
    'a-e',
    'a-f',
    'b-d',
    'b-e',
    'b-f',
    'c-d',
    'c-e',
    'c-f',
];

A: Sounds like homework but you could do the following
$array3 = [];
foreach($array2 as $value) {
    foreach($array1 as $index) {
       $array3[] = $index . '-' . $value;
    }
}

But this is pretty simple PHP, you should really take a course or read a book/tutorial.


text:
Q: How can I convert a mp4 file to webm using java only? I am trying to convert a file from mp4 to webm. I am trying to use the JAVE wrapper of FFmpeg. I am getting the error.
Here is my code:
private String ConvertVideo(URL url) {
    File target =null;
    MultimediaObject multimediaObject = new MultimediaObject(url);
    try {
        target = File.createTempFile("target", ".webm");

    } catch (IOException e1) {
        e1.printStackTrace();
    }
    AudioAttributes audio = new AudioAttributes();
    audio.setCodec(AudioAttributes.DIRECT_STREAM_COPY);
    audio.setBitRate(new Integer(128000));
    audio.setSamplingRate(new Integer(44100));
    audio.setChannels(new Integer(2));
    VideoAttributes video = new VideoAttributes();
    video.setBitRate(new Integer(160000));
    video.setFrameRate(new Integer(15));
    video.setCodec("libvpx-vp9");
    video.setCodec(VideoAttributes.DIRECT_STREAM_COPY);
    EncodingAttributes attrs = new EncodingAttributes();
    attrs.setFormat("webm");
    attrs.setAudioAttributes(audio);
    attrs.setVideoAttributes(video);

    try {
          Encoder encoder = new Encoder();
          encoder.encode(multimediaObject, target, attrs);
        } catch (Exception e) {
           e.printStackTrace();
        }

    return "success";
}

I am getting the below error:
2022-Jun-13 11:12:55 AM [qtp1914526580-175] ERROR ws.schild.jave.Encoder - Process exit code: 1  to target2636257785060285182.webm
ws.schild.jave.EncoderException: Exit code of ffmpeg encoding run is 1

What am I doing wrong here. Is there any other way around it? I want to do it only using java.

A: I have sorted it out. Here is my final working code. Just removed the line video.setCodec(VideoAttributes.DIRECT_STREAM_COPY); and also changed the line audio.setCodec(AudioAttributes.DIRECT_STREAM_COPY);  to audio.setCodec("libvorbis");
private String convertVideo(URL url) {
        File target =null;
        MultimediaObject multimediaObject = new MultimediaObject(url);

        try {
            target = File.createTempFile("target", ".webm");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        AudioAttributes audio = new AudioAttributes();
        audio.setCodec("libvorbis");
        audio.setBitRate(new Integer(128000));
        audio.setSamplingRate(new Integer(44100));
        audio.setChannels(new Integer(2));
        VideoAttributes video = new VideoAttributes();
        video.setBitRate(new Integer(160000));
        video.setFrameRate(new Integer(20));
        video.setCodec("libvpx-vp9");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("webm");
        attrs.setAudioAttributes(audio);
        attrs.setVideoAttributes(video);

        try {
              Encoder encoder = new Encoder();
              encoder.encode(multimediaObject, target, attrs);
            } catch (Exception e) {
               e.printStackTrace();
            }
        return "success";
    }


text:
Q: Strange issue reading from a CSV I am trying to write a program that will allow the user to search for any element on the periodic table by searching using name, atomic number, or symbol. Currently the name and atomic number work fine, but when I tried to copy and paste the code for the symbol, it's suddenly not working. Even hard coding in a cout << "Hello World!"; will not display. Any tips?
#include <iostream>
#include <string>
#include <fstream>
#include <vector>
#include <sstream>

using namespace std;

std::vector<std::string> readAtomicNumber(std::string file_name,std::string search_term);
std::vector<std::string> readName(std::string file_name,std::string search_term);
std::vector<std::string> readSymbol(std::string file_name,std::string search_term);

int main()
{

    int searchchoice;
    int AtomicNumber;
    string Name;
    string Symbol;
    string term;

    cout << "How will you be searching?\nYou may search using;\n1 = Element Name\n2 = Element Symbol\n3 = Atomic Number\n4 = Show me the entire Periodic Table.\n\n";
    cin  >> searchchoice;

    if(searchchoice == 4)
    {
        //something here to cout the entire periodic table
    }
    else if(searchchoice == 3)
    {
        cout << "\n\nWhat is the Atomic Number of the Element you are searching for?\n";
        cin >> term;
    }
    else if(searchchoice == 2)
    {
        cout << "\n\nWhat is the Symbol of the Element you are searching for?\n";            // going to need something to return
        cin >> term;                                                                         // "that is not a name/atomic number etc"
    }                                                                                // incase of a false input
    else if(searchchoice == 1)
    {
        cout << "\n\nWhat is the Name of the Element you are searching for?\n";
        cin >> term;
    }
    else
    {
        cout << "\n\nError. Please re-run the program, and input 1, 2, or 3.\n";
        return 0;
    }

    if(searchchoice == 3)
    {
        std::vector<std::string> data = readAtomicNumber("PeriodicTableupdated",term);                  //atomic number
    }
    else if(searchchoice == 2)
    {
        std::vector<std::string> data = readSymbol("PeriodicTableupdated",term);                         //symbol
    }
    else if(searchchoice == 1)
    {
        std::vector<std::string> data = readName("PeriodicTableupdated",term);                           //name
    }

return 0;
}

std::vector<std::string> readAtomicNumber(std::string file_name,std::string search_term)            //READ ATOMIC NUMBER
{
    std::vector<std::string> record;

    std::ifstream file;
    file.open(file_name);

    bool found_record = false;

    std::string field_one; //atomic number
    std::string field_two; // name
    std::string field_three; // symbol
    std::string field_four;

    while(getline(file,field_one,',') && !found_record)
    {
        getline(file,field_two,',');
        getline(file,field_three,',');
        getline(file,field_four,'\n');
        if(field_one == search_term)
        {
            found_record = true;
            record.push_back(field_one);
            record.push_back(field_two);
            record.push_back(field_three);
            record.push_back(field_four);
        }
    }

        std::cout << "\nThat Element is: " << record[1] << "\nAtomic Number:\tName:\t\tSymbol:\t\tAtomic Mass:\n" << record[0] << "\t\t" << record[1] << "\t" << record[2] << "\t\t" << record[3];
    return record;
}

std::vector<std::string> readName(std::string file_name,std::string search_term)            // READ NAME
{
    std::vector<std::string> record;

    std::ifstream file;
    file.open(file_name);

    bool found_record = false;

    std::string field_one; //atomic number
    std::string field_two; // name
    std::string field_three; // symbol
    std::string field_four;

    while(getline(file,field_two,',') && !found_record)
    {
        getline(file,field_one,',');
        getline(file,field_three,',');
        getline(file,field_four,'\n');
        if(field_one == search_term)
        {
            found_record = true;
            record.push_back(field_one);
            record.push_back(field_two);
            record.push_back(field_three);
            record.push_back(field_four);
        }
    }

        std::cout << "\nThat Element is: " << record[0] << "\nAtomic Number:\t\tName:\t\tSymbol:\t\tAtomic Mass:\n" << record[1] << "\t\t\t" << record[0] << "\t" << record[2] << "\t\t" << record[3];
    return record;
}

std::vector<std::string> readSymbol(std::string file_name,std::string search_term)            // READ SYMBOL
{
    std::vector<std::string> record;

    std::ifstream file;
    file.open(file_name);

    bool found_record = false;

    std::string field_one; //atomic number
    std::string field_two; // name
    std::string field_three; // symbol
    std::string field_four;

    while(getline(file,field_three,',') && !found_record)
    {
        getline(file,field_one,',');
        getline(file,field_two,',');
        getline(file,field_four,'\n');
        if(field_three == search_term)
        {
            found_record = true;
            record.push_back(field_one);
            record.push_back(field_two);
            record.push_back(field_three);
            record.push_back(field_four);
        }
    }

        std::cout << "\nThat Element is: " << record[2] << "\nAtomic Number:\t\tName:\t\tSymbol:\t\tAtomic Mass:\n" << record[0] << "\t\t\t" << record[1] << "\t" << record[2] << "\t\t" << record[3];
    return record;
}

The Periodic Table csv I'm using has 118 elements, so I will just include the first 10 elements for this purpose.
AtomicNumber,Element,Symbol,AtomicMass
1,Hydrogen,H,1.007
2,Helium,He,4.002
3,Lithium,Li,6.941
4,Beryllium,Be,9.012
5,Boron,B,10.811
6,Carbon,C,12.011
7,Nitrogen,N,14.007
8,Oxygen,O,15.999
9,Fluorine,F,18.998
10,Neon,Ne,20.18

A: I highly recommend not using parallel arrays, but using vectors of structs that model the data (record).  Let's define a record as the data on one text line, less the separator characters.
struct Element
{
    unsigned int atomic_number;
    std::string  name;
    std::string  symbol;
    double       atomic_mass;
    friend std::istream& operator>>(std::istream& input, Element& e);
};

std::istream& operator>>(std::istream& input, Element& e)
{
    std::string text_record;
    std::getline(input, text_record);
    std::istringstream text_stream(text_record);
    text_stream >> e.atomic_number;
    char comma;
    text_stream >> comma;
    std::getline(text_stream, e.name, ',');
    std::getline(text_stream, e.symbol, ',');
    text_stream >> e.atomic_mass;
    return input;
};

The above code models the Element and overloads operator>> to read an Element.
Your data input could look like this:
std::vector<Element> database;
Element e;
//... open file.
while (file >> e)
{
    database.push_back(e);  // Append to database;
}

You can then search the database by brute force.
Edit 1:  Index tables
An index table is a table that is sorted by a key member and contains links or offsets to the database.  This will allow you to search by keys without having to resort the database.
We're going to need an index table, that compares by name:
std::map<string, unsigned int> index_by_name;

Here's the modification to the input:
unsigned int db_index = 0;
while (file >> e)
{
    database.push_back(e);
    index_by_name[e.name] = db_index;
    ++db_index;
}

So, to search the database for Sodium, you would do:
unsigned int sodium_index = index_by_name.at("Sodium");
Element sodium_element = database.at(sodium_index);

Without index tables, you would have to either do a linear search, or sort the database then do a binary search (or other search based on a sorted contents).

A: std::vector<std::string> readSymbol(std::string file_name, std::string search_term)            // READ SYMBOL
{
    std::vector<std::string> record;

    std::ifstream file;
    file.open(file_name);

    bool found_record = false;

    std::string field_one; //atomic number
    std::string field_two; // name
    std::string field_three; // symbol
    std::string field_four;

    while (getline(file, field_three, ',') && !found_record)
    {
        getline(file, field_one, ',');
        getline(file, field_two, ',');
        getline(file, field_four, '\n');
        if (field_three == search_term)
        {
            found_record = true;
            record.push_back(field_one);
            record.push_back(field_two);
            record.push_back(field_three);
            record.push_back(field_four);
        }
    }

    std::cout << "\nThat Element is: " << record[2] << "\nAtomic Number:\t\tName:\t\tSymbol:\t\tAtomic Mass:\n" << record[0] << "\t\t\t" << record[1] << "\t" << record[2] << "\t\t" << record[3];
    return record;
}

in this part you literally assign the first string until , to field_three.
but that first string is actually line number since the structure of your file is:
lineNumber , Name, Symbol, Mass

so comparison of (field_three == search_term) is actually a comparison between lineNumber and Symbol which is not logical.
when you debug you will see variables better.
i will drop a screenshot below.


text:
Q: Process started with ProcessBuilder stop supplying data I need to run a unix program from java running on windows. The unix program takes a file name as first parameter, processes the file, and returns the processed file on stdout.
The following works perfectly from CMD console:
wsl.exe /home/user/process /mnt/c/Users/user/input

It prints out the stdout and stderr into console; or I can redirect stdout into a new file which will weigh 1.2MB.
I want to do the same thing from Java. The following code is the most simplified version
ProcessBuilder toCsv = new ProcessBuilder("wsl.exe", "/home/user/process", "/mnt/c/Users/user/input");
Process proc = toCsv.start();
try (InputStream is = proc.getInputStream()){
 for(int i=0; is.read() != -1; i++) {
   System.out.println(i);
 }
}

This always stalls on byte number 380927. Debugger shows that it stalls on FileInputStream.read

*

*I've tried using redirects to send stdout to a file

*I tried reading only stderr

*I tried reading on a different thread with waitFor on main

*I tried reading on a different thread without mainFor on main

*I tried reading without Thread.sleep instead of waitFor

*I tried passing "/bin/bash", "-c", exec+" "+execFile to ProcessBuilder

*I tried using Runtime.exec instead of ProcessBuilder

*I tried "/bin/bash", "-c", "while :; do echo 1; done". This actually broke the 380k byte limit, and went infinitely, like expected.

What's going on, and how do I fix it?
P.S. the source for the unix executable is here, but I don't think it's very useful, since it works from CMD

A: I found the answer as I was typing. Apparently, you MUST take care of both STDERR and STDOUT streams somehow, they don't just disappear. If you only read one of them and ignore the other, eventually the ignored one's buffer will get too big and block until it gets emptied.
so adding the following code solved it
new Thread( () -> {
     try (InputStream es = csvBuilder.getErrorStream() ){
            IOUtils.skip(es, Long.MAX_VALUE);
     } catch (IOException e) {
            throw new RuntimeException(e);
     }
}).start();


text:
Q: about using Van Kampen theorem Please see the following link:
https://math.stackexchange.com/a/1190643/287172
I saw this question and have understood the answer but, I think in this answer we must prove  $ \pi_{1}( Y \cap X_{n+1})= 0 $. Why don't we need this?
Thanks for your help.

A: That is because by Van Kampen's theorem $\pi_1(Y \cup X_{n+1})$ is a quotient of the free product $\pi_1(Y)*\pi_1(X_{n+1})$ which is trivial since $$\pi_1(X_{n+1})=\pi_{1}(Y)=0\ .$$


text:
Q: IE8 What is tiggering beforeunload event I have an issue that is only a problem in IE8, go figure.
I have a anchor tag with an onclick attribute
Click Me

and then foo is declared elsewhere:

After foo is called, my onbeforeunload handler is being executed, and I have no idea why.
I have had other instances, if the foo function does not return false, it triggers the beforeunload event in IE, but even with this function returning false, it still hits my onbeforeunload handler and I can't figure out why.
Is there any way to find out what is triggering it. I have viewed the event object inside my onbeforeunload handler, but it doesn't not seem to give me and relevant info.
Any Ideas?

A: Change it to
Click Me

or
Click Me

A: There's also this thread over at microsoft "answers": http://answers.microsoft.com/en-us/ie/forum/ie8-windows_other/ie8-fires-onbeforeunload-when-clicking-a/0ac8cd9b-7483-4e16-b7c4-346df1f1499a
:)

A: I had this issue as well on some anchor tags that were being rendered by CK Editor.  Fixed by attaching a click event to a DIV that surrounded the anchor tags in question and stopped events from propagating to the window:
$('div.cke_form_fix').on('click', function(e){
    e.stopPropagation();
});


text:
Q: is there a way of scrolling the mkmapview in swift automatically? In my Storyboard in Swift app I have a UIViewController with MKMapView stretched to each edge of the screen. It was enough for me to import a MapKit, then I set up the delegate:
class MyClass: MKMapViewDelegate {

    @IBOutlet weak var mapView: MKMapView!

    override func viewDidLoad(){
        super.viewDidLoad()

        mapView.delegate = self
    }
}

and then, when I ran the app, I saw the map nicely centered above my country.
I want to implement a feature, that works like this:
when user opens this view, he sees the map, but centered on a place next to my home country, then the map could scroll automatically to center to my home country. Is that even achievable?
For example, if I lived in the US and opened the map, I would see the Pacific Ocean and then the map would scroll to show me the US territory.

A: Of course it's possible. MKMapView has the method setRegion(_:animated:).
You could set the map region to a spot in the pacific, wait a few seconds (using a timer or dispatch_after) and then call setRegion(_:animated:) to move the map to be centered over your current location.


text:
Q: MySQL 8.0 Performance on large datasets I have a simple schema bellow with multiple entries and I would like to speed up the queries. I have included indexes but they didn't had a major impact on performance but I don't have experience in handling big data in mysql. It is running on a local MySQL 8.0 server on a Windows 10 with 16GB RAM.
  DROP TABLE IF EXISTS `drugs`;
    /*!40101 SET @saved_cs_client     = @@character_set_client */;
    /*!50503 SET character_set_client = utf8mb4 */;
    CREATE TABLE `drugs` (
      `drug_id` int NOT NULL,
      `ATC` varchar(15) NOT NULL,
      PRIMARY KEY (`drug_id`),
      UNIQUE KEY `drug_id_UNIQUE` (`drug_id`),
      KEY `drug_ATC` (`ATC`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    /*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `events`
--

DROP TABLE IF EXISTS `events`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `events` (
  `event_id` int NOT NULL,
  `Meddra` varchar(10) NOT NULL,
  PRIMARY KEY (`event_id`),
  UNIQUE KEY `event_id_UNIQUE` (`event_id`,`Meddra`),
  KEY `event_Meddra` (`Meddra`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `reports`
--

DROP TABLE IF EXISTS `reports`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `reports` (
  `report_id` int NOT NULL,
  `reportDate` date NOT NULL,
  PRIMARY KEY (`report_id`),
  UNIQUE KEY `report_id_UNIQUE` (`report_id`),
  KEY `reportDateIndex` (`reportDate`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `reports_drugs`
--

DROP TABLE IF EXISTS `reports_drugs`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `reports_drugs` (
  `id` int NOT NULL AUTO_INCREMENT,
  `report_id_FK` int NOT NULL,
  `drug_id_FK` int NOT NULL,
  `type` int NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  KEY `report_id_fk_idx` (`report_id_FK`),
  KEY `report_id_fk_idx1` (`drug_id_FK`) /*!80000 INVISIBLE */,
  CONSTRAINT `drug_report_id_fk` FOREIGN KEY (`drug_id_FK`) REFERENCES `drugs` (`drug_id`),
  CONSTRAINT `report_drug_id_fk` FOREIGN KEY (`report_id_FK`) REFERENCES `reports` (`report_id`)
) ENGINE=InnoDB AUTO_INCREMENT=143260638 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Table structure for table `reports_events`
--

DROP TABLE IF EXISTS `reports_events`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `reports_events` (
  `id` int NOT NULL AUTO_INCREMENT,
  `report_id_FK` int NOT NULL,
  `events_id_FK` int NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `id_UNIQUE` (`id`),
  KEY `report_event_id_fk_idx` (`report_id_FK`),
  KEY `event_report_id_fk_idx` (`events_id_FK`),
  CONSTRAINT `event_report_id_fk` FOREIGN KEY (`events_id_FK`) REFERENCES `events` (`event_id`),
  CONSTRAINT `report_event_id_fk` FOREIGN KEY (`report_id_FK`) REFERENCES `reports` (`report_id`)
) ENGINE=InnoDB AUTO_INCREMENT=143258062 DEFAULT CHARSET=utf8;

My artificial data consists of 30.000.000 entries at the reports table. Each report has a median value of drugs and events of 5, meaning that the reports_drugs and reports_events tables have roughly 150.000.000 entries each.
Two of the queries that are being used and their response time.
SELECT report_id,reportDate,Meddra FROM events
INNER JOIN reports_events ON events.event_id=reports_events.events_id_FK
INNER JOIN reports ON reports_events.report_id_FK=reports.report_id
WHERE Meddra=11125127;

0.36 sec duration / 37.625 sec fetch
SELECT report_id,reportDate,Meddra,ATC,type FROM events
INNER JOIN reports_events ON events.event_id=reports_events.events_id_FK
INNER JOIN reports ON reports_events.report_id_FK=reports.report_id
INNER JOIN reports_drugs ON reports.report_id=reports_drugs.report_id_FK
INNER JOIN drugs ON reports_drugs.drug_id_FK=drugs.drug_id
WHERE Meddra=11125127 AND ATC="ACNKMFRRMVST";

80.296 sec duration / 0 sec fetch
Both of those experience a bottleneck during the 'executing' phase

Query
Status
Duration
Source_function
Source_file
Source_line

1st Query

'executing'
'37.614281'
'SELECT_LEX_UNIT::ExecuteIterat'
'sql_union.cc'

2nd Query

'executing'
'80.293151'
'SELECT_LEX_UNIT::ExecuteIterat'
'sql_union.cc'

Are those times to be expected with such a large dataset or the performance can be increased somehow?

A: Please qualify all columns it makes it easier for us to help you:
SELECT  r.report_id, r.reportDate, e.Meddra
    FROM  events AS e
    INNER JOIN  reports_events AS e AS re  ON e.event_id=re.events_id_FK
    INNER JOIN  reports AS r  ON re.report_id_FK=r.report_id
    WHERE  e.Meddra=11125127;

SELECT  r.report_id, r.reportDate, e.Meddra, d.ATC, rd.type
    FROM  events AS e
    INNER JOIN  reports_events AS e AS re  ON e.event_id = re.events_id_FK
    INNER JOIN  reports AS r  ON re.report_id_FK=r.report_id
    INNER JOIN  reports_drugs AS d AS rd  ON r.report_id = rd.report_id_FK
    INNER JOIN  drugs AS d  ON rd.drug_id_FK = d.drug_id
    WHERE  e.Meddra = 11125127
      AND  d.ATC = "ACNKMFRRMVST";

I assume there are other columns in the tables?
Your UNIQUE keys are redundant and should be Dropped.  (A PRIMARY KEY is a UNIQUE key.)
Many-to-many tables should be indexed in a better way.  See discussion here:  http://mysql.rjweb.org/doc.php/index_cookbook_mysql#many_to_many_mapping_table
That, alone, may solve the performance questions.
The second query will step through the 5 tables in one of these ways:
e -> re -> r -> rd -> d
         --OR--
d -> rd -> r -> re -> e

The link provides the optimal indexes to allow either to work optimally (namely composite indexes, or the equivalent by knowing how InnoDB handles the PK).
And, since there is a test on e.Meddra and e.DTC, the Optimizer will make a semi-intellengent choice of which to start with.


text:
Q: PHP String Search Okay so I'm struggling more than I should with this.  I've been to the blogs and I don't see what I'm doing wrong.  I have a large string of text that is getting returned from a server.  This text is XML.  I have a contactId tag in the returned xml.  I'm using php which I'm still kinda new to.  I'm using the strpos function to try and find the location of the start and end tag in the xml.  I know that it is in there so that isn't the problem.  However when I echo out the result to the call of that function I get nothing instead of the position like I would expect.  My code is below and help would be greatly appreciated.  Thanks.
$contactIdStart = strpos($result, '<contactId>');
$contactIdEnd = strpos($result, '</contactId>');
echo $contactIdStart;
echo "*";
echo $contactIdEnd;

if ($contactIdStart === false)
    echo "bah";
else
    echo "humbug";

Nevermind everyone.  I'm dumb.  strpos is case sensitive I guess.

A: strpos() is case sensitive. Use stripos()for case insensitive search, or fix the capitalisation (ContactId instead of contactId).


text:
Q: Why might I be getting a 500 Error when using Python Requests, but not using cURL I am trying to work on a basic implementation of the Synchroteam API using python's requests. I was able to establish a connection using cURL as a proof of concept and get all the data I wanted, but using requests I am able to get into the site with my credentials, but all I get is:
500
text/html; charset=utf-8
https://apis.synchroteam.com/Api/v1/user/list

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title>Error</title>
</head>
<body>
    <h2>
        An error occurred while processing your request.
    </h2>
</body>
</html>

Process finished with exit code 0

When using curl with this line everything returns the correct info:
curl -u domain:APIKEY -H "Accept: application/json" -H "Content-Type: application/json" https://apis.synchroteam.com/Api/v1/user/List

My small bit of python code is this:
import requests

apiurl = 'https://apis.synchroteam.com/Api/v1/user/list'
login = ("domain", "APIKEY")
headers = {'Content-Type': 'application/json'}

def run():
    r = requests.get(apiurl, auth=login, headers=headers)

    print r.status_code
    print r.headers['Content-type']
    print r.url
    print r.text

run()

All of the Synchroteam documentation has examples in PHP, but I can't see any reason why i wouldn't be able to use python.
The docs are here: http://api.synchroteam.com/rest.php
Any insight would be great, I really hope its just something small I'm missing.
Thank you.

A: This is the Python code I generate using Postman. I'm sure it will help you!
import requests

url = "https://apis.synchroteam.com/Api/v1/User/list"

payload = "{\n    \"status\":\"1\"\n}"
headers = {
'content-type': "application/json",
'accept': "application/json",
'authorization': "Basic ZGVtbzoxMjEyOThucDIwMDM=",
'cache-control': "no-cache",
'postman-token': "1a3839b6-db5b-0c07-be1a-2816f491476c"
}

response = requests.request("GET", url, data=payload, headers=headers)

print(response.text)

Just change the Auth!
Nick