text:
Q: How to fix "Cannot read property 'setState' of undefined" in React My app retrieve data from Firebase Realtime database and trying to load it in 'state' but get error 'Cannot read property setState of undefined'.
I tried to add bind in constructor but it doesn't work
import React from 'react';

import { View } from '@vkontakte/vkui';

import * as firebase from "firebase/app";
import {config} from './dbinit' // import firebase config
import "firebase/database";

import Home from './panels/Home';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.setState = this.setState.bind(this);
        this.state = {
            activePanel: 'home',
            db: null,
            loading: true,
        };
        console.log("init");
    }

    componentDidMount = () => {
        let ref = firebase
         .initializeApp(config)
         .database()
         .ref();

        ref.once("value").then(function onSuccess(res) {
            console.log("success", res.val())

            this.setState({db: res.val(), loading: false})
            // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'

        });
    }

    go = (e) => {
        this.setState({activePanel: e.currentTarget.dataset.to})
    };

    render() {
        const { loading, db } = this.state;
        return loading ? (

loading...

        ) : (
            <View activePanel={this.state.activePanel}>

loaded

            </View>

        );
    }
}

export default App;

I expect correct work of setState but actual have error Cannot read property 'setState' of undefined'

A: You lost context here since anon. function used:
    ref.once("value").then(function onSuccess(res) {
        console.log("success", res.val())

        this.setState({db: res.val(), loading: false})
        // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'

    });

Use arrow function lilke this:
ref.once("value").then((res) => {
    console.log("success", res.val())

    this.setState({db: res.val(), loading: false})
    // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'

});

A: From your use of arrow functions I see your Babel configuration is able to handle the newer (to be released) ES feature of class fields, so it may be worth it to get rid of your constructor altogether.
class App extends React.Component {
    state = {
        activePanel: 'home',
        db: null,
        loading: true,
    };

    componentDidMount = () => {
    ....

This doesn't answer the question, but thought I'd mention it :)
Viktor's answer mentions that your 'this' context got lost from not using an arrow function, which is correct.

A: The reason is that because you are using regular  functions which bind the this keyword dynamically based on the callee and not based on lexical scope... since this code is running in strict mode ( because it is in a class ) the this keyword is resolved as undefined.
if you wish to preserve context you either have to bind the function or use arrow functions ( which bind the this keyword based on the lexical scope)
convert this
ref.once("value").then(function onSuccess(res) {
        console.log("success", res.val())

        this.setState({db: res.val(), loading: false})
        // ERROR GOES HERE 'Unhandled Rejection (TypeError): Cannot read property 'setState' of undefined'

});

to this
ref.once("value").then(res => this.setState({db: res.val(), loading: false}));


text:
Q: How to bounce emails TO a particular email address We use Google Apps and on most domains, have a catchall address.
Over the years though, various email addresses of ours have ended up on various sold email databases/lists and they receive different types of spam on a regular basis - in fact, it isn't necessarily spam, but just cold calling via email.
In many cases, we know that the only way the some of the email addresses were obtained were through purchasing email lists, which we are very much against in business.
I am wondering if there is any way to bounce only emails to specific email addresses so that we can still keep our catchall running.
Anyone know if this is possible, either within Google Apps or with a third party app?

A: Yes, you can keep your catch-all running and bounce only emails sent to a specific email address. Follow these steps:

*

*Sign in to gmail

*Go to Settings (gear icon) -> Manage this domain

*From the admin console, click Apps

*Select Default routing

*Click ADD SETTING

Pop-up window has 3 settings:

*

*The recipient email address you want to disable

*Choose: Reject message

*Choose: Perform this action on non-recognized and recognized addresses

Then press SAVE and you are done.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are the ways in which semiconductor-grade neon is critical for manufacturing? This is a question about material use specifically in semiconductor manufacturing.
CNN's Ukraine halts half of world's neon output for chips, clouding outlook begins:

Ukraine's two leading suppliers of neon, which produce about half the world's supply of the key ingredient for making chips, have halted their operations as Moscow has sharpened its attack on the country, threatening to raise prices and aggravate the semiconductor shortage.
Some 45%-54% of the world's semiconductor grade neon, critical for the lasers used to make chips, comes from two Ukrainian companies, Ingas and Cryoin, according to Reuters calculations based on figures from the companies and market research firm Techcet. Global neon consumption for chip production reached about 540 metric tons last year, Techcet estimates.

and later says:

Before the invasion, Ingas produced 15,000 to 20,000 cubic meters of neon per month for customers in Taiwan, Korea, China, the United States and Germany, with about 75% going to the chip industry, Nikolay Avdzhy, the company's chief commercial officer, said in an email to Reuters.

The CNN article mentions lasers, and it certainly can't be HeNe lasers (e.g. as used in interferometric nano-positioning stages) because they are sealed and long-lived and no where near consumable on this scale.
Is neon perhaps used in large volumes in KrF or ArF excimer lasers for DUV lithography? Or perhaps is it really used in reactive ion etching instead and they've got it wrong? Helium is often used in etch gas chemistries as both a buffer and a way to limit and control the plasma temperature, but I'd never heard of neon being used.
Question: What are the ways in which semiconductor-grade neon is critical for manufacturing?

A: Neon is used the buffer gas in most excimer lasers. Both KrF and ArF excimer lasers contain roughly 98-99% neon, with the balance being the actual krypton or argon (and of course fluorine).
Due to its nature as a carrier gas, it doesn't just need to be any old neon gas, it must be extremely pure 'semiconductor grade' neon, which very few companies are able to produce.  The purification process is long and complicated and there is not a lot of demand from other industries.  There is a small demand from the medical industry, but it is minor compared to the semiconductor industry.
It is worth emphasizing that Ukraine didn't produce 50% of the global neon supply, but rather 50% of the global semiconductor grade neon.  As stated earlier, purifying neon to this grade is not easy and and the few companies that can do it will require the better part of a year to increase their production capacity to pick up the slack.
It is also worth noting that the gas in excimer lasers is a consumable.  In fact, something called 'gas lifetime' is one of the primary performance metrics for an excimer laser.  Commercial ArF excimer lasers typically achieve only 1,000,000 shots before requiring that the gas be purged completely and refilled with a fresh mix of mostly neon with a little bit of  argon and fluorine of course.
The gas is not actually consumed, but each shot dislodges a small amount of impurities from various sources like the electrodes, and these impurities are quite opaque to 193nm light.  Eventually, the concentration of impurities grows too high and the laser will require too high of a voltage to achieve the needed dose to the wafer, and at that point, the gas is simply purged and replaced.  Purifying the used gas would be the same challenge and difficulty as purifying the raw neon in the first place, so little is solved by reusing the gas.  In fact, it might even be recycled, but the purifying process would be made no easier or cheaper for it.


text:
Q: Comparing equality of two columns and the sum total of another column using PARTITION BY I'm new to sql and I am developing a table on snowflake to give status to each id in an already existing table if the sum of colA equals zero where colB and colC have equal values and I want to partition by colC and colB. If when partitioned by colC and colB, colB equals colC and sum of colA equals zero, the status should be true else false. Here, in the table below, is a demonstration. How can I be able to achieve this.

id
ColA
ColB
ColC
status

id1
-10
AbC
o056
True

id2
8
Kdg
AbC
True

id3
2
fdg
AC2
False

id4
2
fdg
AbC
True

I tried this
SELECT array_agg(id) OVER (PARTITION BY ColB, ColC) AS matched_id,
    CASE WHEN ColB = ColC AND SUM(amount) = 0 OVER (PARTITION BY ColB, ColC) THEN True ELSE False
    END AS status

but it didn't work


text:
Q: nodejs child_process.spawnSync or child_process.spawn wrapped in yieldable generator which returns output since a while i am trying to reach something that doesn't work out for me so far.
With nodejs, i like to run a interactive sh-command and work with the sh-command output after the command has exited. i like to write a yieldable generator-function that wraps the running of the interactive shell command and returns the output of the shell command.
Approach 1: shelljs

*

*shelljs

*I had some success with shelljs, but at some point it wont run further.

*Question 1: is it possible to get shelljs to the point where i can inherit stdio and make the shelljs function yieldable?

Approach 2: child_process.spawnSync

*

*child_process.spawnSync

*at last i discovered child_process.spawnSync and was happy that, at least i can run interactive sh-commands without problems with options: { stdio: 'inherit' }

*but i haven't found out how to get back the output of child_process.spawnSync.

*Question 2: How to wrap spawnSync into a generator function that returns the child_process's output?

Approach 3: co-child-process

*

*i also tried co-child-process.

*it seems to run, but not interactive with stdio. there is a issue regarding this, i dont really understand.

*Question 3: could someone explain me/ post a example how co-child-process will work with stdio inherit.

Approach 4: promisify child_process.spawn() with bluebird

*

*i opened an issue on bluebird if child_process.spawn() is promisifiable

So my question at all. Can someone post me an example of how to run a interactive shell command that can be wrapped in a yieldable generator function that returns the output of the shell command? i am open for new approaches.
I created a npm module which is available on github where you can fork it and contribute.
thx in advance.

A: I found the following which works on v5.4.1 . In the docs NodeJS Child Process it mentions the option encoding which has a default of 'buffer'. If you set this option to 'utf8', then instead of a buffer you get a string back with the results. You can get a string back from spawnSync because it is synchronous and blocks execution until the command completes. Here's a working example of a script which does an 'ls -l /usr' command and gets the output as a string object:
#!/usr/bin/env node

var cp = require('child_process');

var ls = cp.spawnSync('ls', ['-l', '/usr'], { encoding : 'utf8' });
// uncomment the following if you want to see everything returned by the spawnSync command
// console.log('ls: ' , ls);
console.log('stdout here: \n' + ls.stdout);

When you run it you get the following:
stdout here:
total 68
drwxr-xr-x   2 root root 36864 Jan 20 11:47 bin
drwxr-xr-x   2 root root  4096 Apr 10  2014 games
drwxr-xr-x  34 root root  4096 Jan 20 11:47 include
drwxr-xr-x  60 root root  4096 Jan 20 11:47 lib
drwxr-xr-x  10 root root  4096 Jan  4 20:54 local
drwxr-xr-x   2 root root  4096 Jan  6 01:30 sbin
drwxr-xr-x 110 root root  4096 Jan 20 11:47 share
drwxr-xr-x   6 root root  4096 Jan  6 00:34 src

The docs tell you what you can get back on the object in addition to stdout . If you want to see all the properties on the return object, uncomment the console.log (Warning: there's a LOT of stuff :) ).


text:
Q: Unexpected inaccessible base (first derived class) The following code gives the error: 'B' is an inaccessible base of 'D'.
Why does this happen? The constructor of B is public which means it should be inherited by class D even though the inheritance is protected / private.
Can someone tell me a workaround as well? Except of course making the inheritance public.
#include <iostream>
#include <typeinfo>
using namespace std;
class B
{ int i;
   public:
   B() { i=1; }
  int get_i() { return i; }
};
class D: private B
{ int j;
  public:
   D() { j=2; }
  int get_j() {return j; }
 };
 int main()
 {
 B *p= new D;
 return 0;
 }

Thank you!

A: Your example could be narrowed to
D * p_d{nullptr};
B * p_b{p_d};

Casting to private base class is prohibited outside of derived class and derived class's friends scope. Error has nothing to do with constructor (which will work as expected).
You may also want to check some workarounds.


text:
Q: How does Magento model distinguish column names in its get/set Model methods? Let's say I have a Model associated to a table with a column called title. I understand that I can do a $model->setTitle("Hello"); to set a value to this field. I can probably do the same for reading like so ``$model->getTitle();`.
An example would be:
$blogpost = Mage::getModel('weblog/blogpost');
    $blogpost->setTitle('Code Post!');
    $blogpost->setPost('This post was created from code!');
    $blogpost->save();

However, what if the column name was title_name? I could do it with $this->getTitleName() and it worked.
So, I was thinking, if I could use getTitleName() for a column called title_name, then what if I had another column called titleName in the database? How is Magento going to decide between titleName and title_name? How is Magento going to know which column I am referring to?

A: That's a very specific case so let me clear that up for you.
The magic getters/setters are just wrappers for getData/setData methods.
So in your case:

*

*title_name can be retrieved by using getData('title_name')

*titleName can be retrieved by using getData('titleName')
However, if you call getTitleName() it will automatically retrieve the title_name column.
Here's why.
Those magic getters/setters are defined in the Varien_Object class as well as two other magic methods has and uns:
public function __call($method, $args)
{
    switch (substr($method, 0, 3)) {
        case 'get' :
            //Varien_Profiler::start('GETTER: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            $data = $this->getData($key, isset($args[0]) ? $args[0] : null);
            //Varien_Profiler::stop('GETTER: '.get_class($this).'::'.$method);
            return $data;

        case 'set' :
            //Varien_Profiler::start('SETTER: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            $result = $this->setData($key, isset($args[0]) ? $args[0] : null);
            //Varien_Profiler::stop('SETTER: '.get_class($this).'::'.$method);
            return $result;

        case 'uns' :
            //Varien_Profiler::start('UNS: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            $result = $this->unsetData($key);
            //Varien_Profiler::stop('UNS: '.get_class($this).'::'.$method);
            return $result;

        case 'has' :
            //Varien_Profiler::start('HAS: '.get_class($this).'::'.$method);
            $key = $this->_underscore(substr($method,3));
            //Varien_Profiler::stop('HAS: '.get_class($this).'::'.$method);
            return isset($this->_data[$key]);
    }
    throw new Varien_Exception("Invalid method ".get_class($this)."::".$method."(".print_r($args,1).")");
}

As you can see the _underscore() method is called on the attribute of the method called.
protected function _underscore($name)
{
    if (isset(self::$_underscoreCache[$name])) {
        return self::$_underscoreCache[$name];
    }
    #Varien_Profiler::start('underscore');
    $result = strtolower(preg_replace('/(.)([A-Z])/', "$1_$2", $name));
    #Varien_Profiler::stop('underscore');
    self::$_underscoreCache[$name] = $result;
    return $result;
}

So in your case, the code that runs would be:
strtolower(preg_replace('/(.)([A-Z])/', "$1_$2", "TitleName"))

Which returns title_name
So getTitleName() will always get you this column and thus the only way to get titleName is by calling getData('titleName')

A: Convention is to use lower_snake_case for columns and CamelCase in the getters and setters. Best follow these conventions to not run into weird problems.
It's possible to use getData($columName) and setData($columnName, $value) to access arbitrary column names but I highly recommend following the convention.
(it's also possible to access title_name with getTitle_name() but don't do everything that is possible just because you can. This is not the intended usage!)


text:
Q: Inequality for a non-decreasing function Let $f:[0,+\infty] \rightarrow R^+$ be non-decreasing with $$\int_{2r}^{4r} f(t) dt \leq C \int_{r}^{2r} f(t) dt \qquad \forall r \geq 0$$
To prove $f(2r)\leq C' f(r) \qquad \forall r\geq 0$
$\\$
Don't know from where to start. Maybe to use Lebesgue differentiation theorem and write $$f(2r)=\lim_{\epsilon \rightarrow 0} \frac{1}{2\epsilon} \int_{2r-\epsilon}^{2r+\epsilon} f(t) dt$$

A: Use the fact that $f$ is non-decreasing. In particular $f(2r)\le f(t)$ for $t\in(2r,4r)$ and $f(t)\le f(r)$ for $t\in(r/2,r)$, so $$2r\,f(2r)=\int_{2r}^{4r}f(2r)\le\int_{2r}^{4r}f(t)
\le C\int_r^{2r}f(t)\le C^2\int_{r/2}^rf(t)\le C^2\int_{r/2}^rf(r)=\frac{C^2r}{2}f(r).$$Divide by $2r$.


text:
Q: How to match a power amplifier and a loudspeaker array? I am trying to use a power amplifier that is available to me to actuate an array of loudspeakers. The array has a total number of 30 loudspeakers (ways of connection can vary).
And I would like to know how I should connect the loudspeaker array to the amplifier to make sure there's enough power for the array and also not overload the array. Below are some parameters of the amplifier and the loudspeaker. Do you think serial connection in this case will be fine?
If possible, would you please show the chain of thought to reach the conclusion? So will help me when I want to change the no. of loudspeakers in the future.
Power amplifier:

*

*Power output capacity: 75 VA into a 3 ohm resistive load

*Input impedance: 15 kohm

*Output impedance: 0.04 ohm: [10Hz-5kHz], 0.08 ohm: [5kHz-20kHz]

*Max output current: 5A or 1.8A rms according to selected value

*Max output voltage: 15 V RMS

Loudspeaker

*

*Input power: 2W (rated), 3W (max)

*impedance: 8 ohm

Array
The array will be composed of the loudspeaker above with a total number of 30.

A:
Power output capacity: 75 VA into a 3 ohm resistive load

So your power amplifier can deliver the highest power into a 3 ohms load.
If you would connect all speakers in series you would get 30 x 8 ohms = 240 ohms, then the maximum power to the speakers is limited by the voltage that the amplifier can make. This is about 15 V, into 240 ohms that means P = U^2 / R = 15^2 / 240 = 0.94 Watt which is not much.
If you would connect all speakers in parallel you would get 8 ohms / 30  = 0.27 ohms, then the maximum power to the speakers is limited by the current that the amplifier can deliver. This is about 5 A, into 0.27 ohms that means P = I^2 * R = 5^2 * 0.27 = 6.8 Watt which is more than the 0.94 Watt but still not much. Also, this quite low impedance of 0.27 ohms is bound to cause problems, the amplifier simply might not like it.
Your best bet is to combine series and parallel to get close to 3 ohms. My guess is that 4 Ohms would be good enough as well and somewhat easier as two 8 ohm speakers in parallel equals 4 ohms. Then use series and parallel again to add more speakers but keep a total of 4 ohms, like so:

simulate this circuit – Schematic created using CircuitLab
There are 8 speakers, between the top and bottom there's 4 ohms.
You can combine 4 of these in series and parallel and then you'd need 32 speakers.
If you must have 30 speakers maybe you can use 5 x 6 = 30 meaning make sets of 5 speakers in series, connect 6 of those sets in parallel, that would result in a total of 8 ohm * 5 / 6 = 6.7 ohms.

A: Your speakers are rated at 2W and 8Ω, which means that they can take a maximum of \$\sqrt{P\cdot R} = \sqrt{2 \cdot 8} = 4\$ VRMS.
The amplifier produces up to 15 VRMS, so you need to connect the speakers in strings of 4 in series across the amplifier terminals in order to make sure that the speakers are not overdriven. You can put any number of such strings in parallel.
Each string consumes 15 V/32 Ω = 0.47 ARMS, so you can have up to 5 A/.47 A = 10 strings before you overload that particular amplifier.

A: Another approach is to match impedances for maximum power transfer out without overdriving all your speakers.
If MPT impedance is 3 Ohm load  ( due to thermal IC limits) and you have 30 x Zo=8 Ohm loads,  that would wish to arrange as a 3 Ohm load, then you have several options.
For an array of xSyP where x is the qty in a series string and y is the qty of parallel strings;
\$Z_{equiv.}=3<= \dfrac{x}{y} \cdot Zo\$ where x*y=30 and Zo=8
Solve this :
4S10P=3.2 Ohms which is > 3 Ohms and gives you closest to MPT with  a 75VA source gives you 75VA/30 = 2.5 VA per speaker   below its MAX limit of 3W peak and rated limit of 2Wrms.


text:
Q: How to get YouTube Video ID from PlaylistID? how do I get ID of a youtube video that is part of a playlist
example a link like this:
https://www.youtube.com/watch?v=kXYiU_JCYtU&list=PL87FA01F68C540290
this is the gdata
http://gdata.youtube.com/feeds/api/playlists/PL87FA01F68C540290?v=2&alt=jsonc&max-results=50
THIS IS MY CODE
public class Episodi extends Activity implements OnClickListener {

ImageView mainThumb;
TextView mainTitle;
TextView mainTime;
LinearLayout videos;
ArrayList<String> links;
URL jsonURL;

/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.episodi);

    new ParseVideoDataTask().execute();
    mainThumb = (ImageView) findViewById(R.id.mainThumb);
    mainTitle = (TextView) findViewById(R.id.mainTitle);
    mainTime = (TextView) findViewById(R.id.mainTime);
    videos = (LinearLayout) findViewById(R.id.videos);

}

public class ParseVideoDataTask extends AsyncTask<String, String, String> {
    int count = 0;

    @Override
    protected String doInBackground(String... params) {
        URL jsonURL = null;
        URLConnection jc;
        links = new ArrayList<String>();
        try {

                jsonURL = new URL("http://gdata.youtube.com/feeds/api/playlists/" +
                "PL87FA01F68C540290" +
                "?v=2&alt=jsonc&max-results=50");

             jc = jsonURL.openConnection();
             InputStream is = jc.getInputStream();
             String jsonTxt = IOUtils.toString(is);
             JSONObject jj = new JSONObject(jsonTxt);
             JSONObject jdata = jj.getJSONObject("data");
             JSONArray aitems = jdata.getJSONArray("items");
             for (int i=0;i<aitems.length();i++) {
                 JSONObject item = aitems.getJSONObject(i);
                 JSONObject video = item.getJSONObject("video");
                 String title = video.getString("title");
                 JSONObject player = video.getJSONObject("player");
                 String link = player.getString("default");
                 String length = video.getString("duration");
                 JSONObject thumbnail = video.getJSONObject("thumbnail");
                 String thumbnailUrl = thumbnail.getString("hqDefault");
                 String[] deets = new String[4];
                 deets[0] = title;
                 deets[1] = thumbnailUrl;
                 deets[2] = length;
                 links.add(link);
                 publishProgress(deets);
             }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(final String... deets) {
        count++;
        if (count == 1) {
            Picasso.with(getBaseContext()).load(deets[1]).into(mainThumb);
            mainTitle.setText(deets[0]);
            mainTime.setText(formatLength(deets[2]));
            mainThumb.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent i = new Intent(Episodi.this,Video.class);
                    //I want to insert .putExtra here for the VIDEO ID (example. kXYiU_JCYtU)
                    startActivity(i);
                }
            });
        } else {
            LayoutInflater layoutInflater = (LayoutInflater)Episodi.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View video = layoutInflater.inflate(R.layout.videothumb, null);
            ImageView thumb = (ImageView) video.findViewById(R.id.thumb);
            TextView title = (TextView) video.findViewById(R.id.title);
            TextView time = (TextView) video.findViewById(R.id.time);
            Picasso.with(getBaseContext()).load(deets[1]).into(thumb);
            title.setText(deets[0]);
            time.setText(formatLength(deets[2]));
            video.setPadding(20, 20, 20, 20);
            videos.addView(video);
            video.setId(count-1);
            video.setOnClickListener(new OnClickListener() {

                public void onClick(View v) {
                    Intent i = new Intent(Episodi.this,Video.class);
                    //I want to insert .putExtra here for the VIDEO ID (example. kXYiU_JCYtU)
                    startActivity(i);
                }
            });
        }
    }
}

private CharSequence formatLength(String secs) {
    int secsIn = Integer.parseInt(secs);
    int hours = secsIn / 3600,
            remainder = secsIn % 3600,
            minutes = remainder / 60,
            seconds = remainder % 60;

            return ((minutes < 10 ? "0" : "") + minutes
            + ":" + (seconds< 10 ? "0" : "") + seconds );
}

public void onDestroy() {
    super.onDestroy();
    for (int i=0;i<videos.getChildCount();i++) {
        View v = videos.getChildAt(i);
        if (v instanceof ImageView) {
            ImageView iv = (ImageView) v;
            ((BitmapDrawable)iv.getDrawable()).getBitmap().recycle();
        }
    }
}

}

A: As I can see here you have JSON formated string as a response.
There are many JSON APIs, you can use provided in Android. Just make JSONObject and get the data you are interested in.
JSONObject playlist = new JSONObject(response);
// list items
JSONArray items = playlist.getJSONObject("data").getJSONArray("items");
// traverse items array and get video url
for(int i=0; i<items.length(); i++) {
    JSONObject item = items.getJSONObject(i);
    // video url
    String videoURL = item.getJSONObject("video").getJSONObject("player").getString("default");
}

You need to wrap all this in try-catch block.
EDIT
As I understood you need to parse the strings you have in the list links.
for(String link : links) {
    String id = link.split("&")[0].split("v=")[1];
    // do what you need with the link
}


text:
Q: Opening Large CSV files? I have a file that I need to import to a MS-SQL Database but I am not able to open it because my computer only has 4 Gigs of RAM.. I normally use a CSV splitter to make large files smaller but it is not working for this file (155 Gigs)
Can anyone tell me a way to deal with this file for importing into the database (besides buying a new computer with better hardware)
Thank you

A: In this case I would suggest to use either SSIS (if possible) or simpler a small PowerShell script. You can find working scripts here and here.
Both PowerShell scripts will iterate over a few rows and import them before they unload them from the memory and take the next ones. In the last link, you can just specify the variable $batchsize which will load the data in defined blocks.

A: A streaming CSV splitter would be a lot more efficient because it processes the file in chunks (of bytes) instead of trying load the entire file into memory before processing it.  node-csv does that but you will need to install node.js in order to use it.
https://github.com/voodootikigod/node-csv
https://nodejs.org/

A: If your file is just simple comma separated values (doesn't have columns that have commas and therefore double quotes around them), you can also use BCP to load the data. It's quite simple to use if the file doesn't have anything special in it.
For more complex cases SSIS is probably the better solution. When importing something this big, make sure you set -b option so that the whole file isn't a one batch and depending on your file contents you want to use -c (ascii) or -w (unicode)


text:
Q: How to create a custom-element "resize" mixin for Polymer 2? I'm trying to upgrade a Polymer 1.8 component to Polymer 2.
As explained in the documentation, behaviors are replaces by class mixin, but I'm not really confident with theses. After some search, about how to replace the iron-resizable-behavior, I'm not able to find how to build it.
Is there someone to show me where I can find some documentation on it or/and explain how can I design mixins to react on events?
Thanks

A: Hybrid Behavior
In the 2.0-preview branch of <iron-resizable-behavior>, Polymer.IronResizableBehavior is a hybrid behavior (i.e., defined as an object instead of a class mixin). Polymer 2 provides Polymer.mixinBehaviors() to merge one or more hybrid mixins with a class.
Usage:
class NEW_CLASSNAME extends Polymer.mixinBehaviors(HYBRID_MIXINS_ARRAY, SUPERCLASSNAME) { ... }

Example:
class MyView1 extends Polymer.mixinBehaviors([Polymer.IronResizableBehavior], Polymer.Element) {
  static get is() { return 'my-view1'; }

  connectedCallback() {
    super.connectedCallback();
    this.addEventListener('iron-resize', this._logResizeEvent);
  }

  disconnectedCallback() {
    super.disconnectedCallback();
    this.removeEventListener('iron-resize', this._logResizeEvent);
  }

  _logResizeEvent(e) {
    console.debug('resize', e);
  }
}

window.customElements.define(MyView1.is, MyView1);

Behavior-Class Mixin
You could create a behavior-class mixin like this:
const MyMixin = (superclass) => class extends superclass {
  foo() {
    console.log('foo from MyMixin');
  }
};

Then, you'd use it in your Polymer element like this:
class MyView1 extends MyMixin(Polmer.Element) {
  onClick() {
    this.foo(); // <-- from MyMixin
  }
}

Hybrid Behavior + Behavior-Class Mixin
You could use hybrid behaviors and behavior-class mixins together like this:
class MyView1 extends Polymer.mixinBehaviors([Polymer.IronResizableBehavior], MyMixin(Polmer.Element)) {
  onClick() {
    this.foo();                               // <-- from MyMixin
    console.log(this._interestedResizables);  // <-- from Polymer.IronResizableBehavior
  }
}

A: As per documentation, you only need to do the following:
Change:
class MyElement extends Polymer.Element {
  // Implementation
}

To:
class MyElement extends Polymer.IronResizableBehavior(Polymer.Element) {
  // Implementation
}

Does this work for you?


text:
Q: SQL programming for Calculating Failure Rate +------+------+
|DealId|Failcode|
+------+------+
|1     |A     |
+------+------+
|2     |A     |
+------+------+
|2     |A     |
+------+------+
|1     |B     |
+------+------+
|2     |B     |
+------+------+
|1     |A     |
+------+------+
|1     |A     |
+------+------+

I would like to select the DealId that occurs more than once with the different Failcode And their failurerate
The output should be something like:
+------+------+-----+
|DealId|Fail  |count|
+------+------+-----+
|1     |A     |3    |
+------+------+-----+
|1     |B     |1    |
+------+------+-----+
|2     |A     |2    |
+------+------+-----+
|2     |B     |1    |
+------+------+-----+

A: use aggregation and group by
select DealId,Fail,count(*) as cnt
from tablename
group by DealId,Fail
having count(*) > 1;

A: You can use WHERE EXIST like following to check DealId that occurs more than once with the different Failcode .
To show the count, you can simply use GROUP BY dealid,failcode
SELECT T1.dealid,
       T1.failcode Fail,
       Count(*)    AS CT
FROM   YourTableName T1
WHERE  EXISTS (SELECT 1
               FROM   YourTableName T2
               WHERE  T2.dealid = T1.dealid
                      AND T2.failcode <> T1.failcode)
GROUP  BY T1.dealid,
          T1.failcode

Note: Replace YourTableName with actual table name.

A:
I would like to select the DealId that occurs more than once with the different Failcode And their failurerate

I interpret this as saying that you want more than one type of failure rate.  Your sample data doesn't provide any example of deal ids that are filtered out by the first condition.  But the answer to this question appears to be:
select dealid, fail, cnt
from (select DealId, Fail, count(*) as cnt,
             count(*) over (partition by DealId) as cnt_fails
      from tablename
      group by DealId, Fail
     ) t
having cnt_fails > 1;


text:
Q: Limit of time derivative in linear parabolic equation $M^n$ , $n\ge 1$ , is a compact n-dimensional manifold without boundary. $F_0: M^n\rightarrow \mathbb R^{n+1}$ is smoothly immersion with nonnegative mean curvature. Deform $F(x,t)$ by
$$
\partial_t F(x,t)  = \Delta_g  F+ F  \\
F(\cdot , 0)=F_0~~~~~~~~
$$
$\Delta_g$ is Laplace-Beltrami operator. If the solution exist for all $t\ge0$. Then, how to show
$
\partial_t F \rightarrow 0
$
as $t\rightarrow \infty$ ?
This question is origin from Huisken's Asymptotic behavior for singularities of the mean curvature flow. In fact, Huisken want to prove the limit of $F$ is a sphere. First , he proves the limit manifold $F_\infty(M^n)$ satisfies
$$
H=\langle F, \nu\rangle
$$
$H$ is the mean curvature , $\nu$ is normal vector, $\langle \cdot,\cdot \rangle$ is  Euclid  inner.  For proving this, he needs a monotonicity formula. In my view , the monotonicity formula is not easy to think. And obviously, there is a intuitional way. If we have $\partial _t F \rightarrow 0$, because $\Delta_g F=-H\nu$, we can easily get $H=\langle F, \nu\rangle$  in the limit manifold. Maybe, this is too strong, just $\langle \partial _t F ,\nu \rangle \rightarrow 0$ is enough.


text:
Q: QuickTime Plug-In 7.7.2 (in Firefox) QuickTime Plug-In 7.7.2 (in FireFox) shows up in my Applications 32 times.  It seems to me that I shouldn't need but one application and the other 31 are just hogging space.  Is this true?  If so, how do I remove all those QuickTime applications?
Thank you


text:
Q: Is there a more efficient way to do this algorithm? To the best of my knowledge, this algorithm will search correctly and turn out true when it needs too. In class we are talking about Big O analysis so this assignment is to show how the recursive search is faster than an iterative search. The point is to search for a number such that A[i] = i (find an index that is the same as the number stored at the index). This algorithm versus an iterative one only varies by about 100 nanoseconds, but sometimes the iterative one is faster. I set up the vector in main using the rand() function. I run the two algorithms a million times and record the times. The question I am asking is, is this algorithm as efficient as possible or is there a better way to do it?
bool recursiveSearch(vector<int> &myList, int beginning, int end)
{
    int mid = (beginning + end) / 2;

    if (myList[beginning] == beginning) //check if the vector at "beginning" is
    {                                      //equal to the value of "beginning"
        return true;
    }

    else if (beginning == end) //when this is true, the recursive loop ends.
    {                          //when passed into the method: end = size - 1
        return false;
    }

    else
    {
        return (recursiveSearch(myList, beginning, mid) || recursiveSearch(myList, mid + 1, end));
    }

}

Edit: The list is pre-ordered before being passed in and a check is done in main to make sure that beginning and the end both exist

A: One possible "improvement" would be to not copy the vector in each recursion by passing a reference:
bool recursiveSearch(const vector<int>& myList, int beginning, int end)

A: Unless you know something special about the ordering of the data, there is absolutely no advantage to performing a partitioned search like this.
Indeed, your code is actually [trying] to do a linear search, so it is actually implementing a simple for loop with the cost of a lot of stack and overhead.
Note that there is a weirdness in your code: If the first element doesn't match, you will call recursiveSearch(myList, beginning /*=0*/, mid). Since we already know that element 0 doesn't match, you're going to subdivide again, but only after re-testing the element.
So given a vector of 6 elements that has no matches, you're going to call:

recursiveSearch(myList, 0, 6);
  -> < recursiveSearch(myList, 0, 3) || recursiveSearch(myList, 4, 6); >
  -> < recursiveSearch(myList, 0, 1) || recursiveSearch(2, 3) > < recursiveSearch(myList, 4, 5); || recursiveSearch(myList, 5, 6); >
  -> < recursiveSearch(myList, 0, 0) || recursiveSearch(myList, 1, 1) > < recursiveSearch(myList, 2, 2) || recursiveSearch(myList, 3, 3) > ...

In the end, you're failing on a given index because you reached the condition where begin and end were both that value, that seems an expensive way of eliminating each node, and the end-result is not a partitioned search, it a simple linear search, you just use a lot of stack-depth to get there.
So, a simpler and faster way to do this would be:
for (size_t i = beginning; i < end; ++i) {
    if (myList[i] != i)
        continue;
    return i;
}

Since we're trying to optimize here, it's worth pointing out that MSVC, GCC and Clang all assume that if expresses the likely case, so I'm optimizing here for the degenerate case where we have a large vector with no or late matches. In the case where we get lucky and we find a result early, then we're willing to pay the cost of a potential branch miss because we're leaving. I realize that the branch cache will soon figure this out for us, but again - optimizing ;-P
As others have pointed out, you could also benefit from not passing the vector by value (forcing a copy)
const std::vector<int>& myList

A: An obvious "improvement" would be to run threads on all the remaining cores.  Simply divvy up the vector into number of cores - 1 pieces and use a condition variable to signal the main thread when found.

A: If you need to find an element in an unsorted array such that A[i] == i, then the only way to do it is to go through every element until you find one.
The simplest way to do this is like so:
bool find_index_matching_value(const std::vector<int>& v)
{
    for (int i=0; i < v.size(); i++) {
        if (v[i] == i)
            return true;
    }
    return false; // no such element
}

This is O(n), and you're not going to be able to do any better than that algorithmically. So we have to turn our attention to micro-optimisations.
In general, I would be quite astonished if on modern machines, your recursive solution is faster in general than the simple solution above. While the compiler will (possibly) be able to remove the extra function call overhead (effectively turning your recursive solution into an iterative one), running through the array in order (as above) allows for optimal use of the cache, whereas, for large arrays, your partitioned search will not.


text:
Q: Using astropy to generate solar eclipse conditions based on my location This is a question for the astronomy-minded folks on here.
I am an amateur astrophotographer looking to develop a personal script to aid my photography of next year's total solar eclipse. I am developing a Python script to automate my photography, so that I may enjoy the eclipse with my own eyes while my DSLR clicks away. Here's the script I've developed so far. The script uses digicamcontrol to control the camera.
Right now in the script I have just develop automation based on the partial phase of the eclipse (first contact, C1) and the timing of the eclipse in UTC (as well as my own PC). But a thought occurred to me: What if I can't connect to the internet and get the exact timing of the solar eclipse based on my location? I'd like to be able to generate those times. Is there a more efficient method to utilize astropy for this task? Thanks in advance.
import digiCamControlPython as dccp
import time
from datetime import datetime
from astropy.time import Time

local_time = Time.now()

utc_time_now = local_time.utc

def PartialEclipse(start_time:str, end_time:str):
    camera = dccp.Camera()
    camera.setIso(100)
    camera.setShutterspeed("1/50")
    camera.setFolder(r"C:\Users\My_Name\Pictures\digiCamControl")

    # Set the target capture time in astropy time format
    partial_eclipse_start = Time(start_time, format='isot')
    partial_eclipse_end = Time(end_time, format='isot')

    # Wait until the capture time
    while utc_time_now < partial_eclipse_start:
        time.sleep(1)

    # Start capturing images
    while utc_time_now < partial_eclipse_end:
        camera.capture()
        time.sleep(30)  # Capture an image every 30 seconds

PartialEclipse("2024-04-08T17:12:13", "2024-04-08T18:29:24") #times of partial eclipse start and T-15s before totality

EDIT: In the event anyone ever looks at this question, I did make some progress on this.
import numpy as np
import astropy.units as u
from astropy.coordinates import solar_system_ephemeris, AltAz, EarthLocation, SkyCoord
from astropy.coordinates import get_body, get_moon, get_sun
from astropy.time import Time

myLocation = EarthLocation(lat=26*u.deg, lon=-80*u.deg, height=0*u.m)

# set the time step (how often to check for a solar eclipse in seconds)
time_step = 3600 # 1 hour

# set the number of days to check for a solar eclipse
num_days = 365

# set the start and end times to check for a solar eclipse
start_time = Time.now()
end_time = start_time + num_days * u.day

# initialize a list to store the times of a solar eclipse
eclipse_times = []

# loop over the desired time range, checking for a solar eclipse every time_step seconds
with solar_system_ephemeris.set('jpl'):
  for t in np.arange(start_time.unix, end_time.unix, time_step):
    time = Time(t, format='unix')
    moon = get_body('moon', time, myLocation)
    sun = get_body('sun', time, myLocation)
    sun_coord = SkyCoord(sun.ra, sun.dec, sun.distance, frame='icrs')
    moon_coord = SkyCoord(moon.ra, moon.dec, moon.distance, frame='icrs')

    # check if the angular separation between the moon and sun is close to zero
    angular_separation = moon_coord.separation(sun_coord)
    if angular_separation < 0.6 * u.deg: #elongation where the partial eclipse begins
      eclipse_times.append(time)

# print the times of the next solar eclipse
if len(eclipse_times) > 0:
  print("The next solar eclipse is at: ", eclipse_times[0].iso)
else:
  print("No solar eclipses found in the specified time range.")

A: I think your approach is really good! If you want to increase the accuracy of your start time prediction without using a lot more computational power, you can use scipy.optimize.root_scalar to refine the start time you found.
In my solution below, I've defined a function called distance_contact() whose root represents the start of the eclipse. This function is zero if the Sun and Moon are barely touching, positive if they are separated, and negative if they are overlapping. Then I define a grid of times with a timestep of 1 hour similar to your code, and pass it into this function to search for eclipses. It then finds the first time where distance_contanct is negative and uses that time and the timestep before as the search space for scipy.optimize.root_scalar.
Also, instead of using 0.6 * u.deg as the separation distance for an eclipse to occur, I've calculated the angular radius of the Sun and Moon for the time argument to distance_contact to make the prediction as accurate as possible.
import numpy as np
import scipy.optimize
import astropy.units as u
import astropy.time
import astropy.constants
import astropy.coordinates

def distance_contact(
        location: astropy.coordinates.EarthLocation,
        time: astropy.time.Time,
        eclipse_type: str,
) -> u.Quantity:

    radius_sun = astropy.constants.R_sun
    radius_moon = 1737.4 * u.km

    coordinate_sun = astropy.coordinates.get_sun(time)
    coordinate_moon = astropy.coordinates.get_moon(time)

    frame_local = astropy.coordinates.AltAz(obstime=time, location=location)

    alt_az_sun = coordinate_sun.transform_to(frame_local)
    alt_az_moon = coordinate_moon.transform_to(frame_local)

    angular_radius_sun = np.arctan2(radius_sun, alt_az_sun.distance).to(u.deg)
    angular_radius_moon = np.arctan2(radius_moon, alt_az_moon.distance).to(u.deg)

    if eclipse_type == 'total':
        separation_max = angular_radius_moon - angular_radius_sun
    elif eclipse_type == 'partial':
        separation_max = angular_radius_moon + angular_radius_sun
    else:
        raise ValueError("Unknown eclipse type")

    return (alt_az_moon.separation(alt_az_sun).deg * u.deg) - separation_max

def calc_time_start(
        location: astropy.coordinates.EarthLocation,
        time_search_start: astropy.time.Time,
        time_search_stop: astropy.time.Time,
        eclipse_type: str = 'partial'
) -> astropy.time.Time:

    astropy.coordinates.solar_system_ephemeris.set("de430")

    # If we're only looking for a partial eclipse, we can accept a coarser search grid
    if eclipse_type == "partial":
        step = 1 * u.hr
    elif eclipse_type == "total":
        step = 1 * u.min
    else:
        raise ValueError("Unknown eclipse type")

    # Define a grid of times to search for eclipses
    time = astropy.time.Time(np.arange(time_search_start, time_search_stop, step=step))

    # Find the times that are during an eclipse
    mask_eclipse = distance_contact(location=location, time=time, eclipse_type=eclipse_type) < 0

    # Find the index of the first time that an eclipse is occuring
    index_start = np.argmax(mask_eclipse)

    # Search around that time to find when the eclipse actually starts
    time_eclipse_start = scipy.optimize.root_scalar(
        f=lambda t: distance_contact(location, astropy.time.Time(t, format="unix"), eclipse_type=eclipse_type).value,
        bracket=[time[index_start - 1].unix, time[index_start].unix],
    ).root
    time_eclipse_start = astropy.time.Time(time_eclipse_start, format="unix")

    return time_eclipse_start

def test_calc_time_start():

    location = astropy.coordinates.EarthLocation(lat=26 * u.deg, lon=-80 * u.deg, height=0 * u.m)
    eclipse_type = 'partial'
    time_start = calc_time_start(
        location=location,
        time_search_start=astropy.time.Time.now(),
        time_search_stop=astropy.time.Time.now() + 0.9 * u.yr,
        eclipse_type=eclipse_type,
    )
    print(time_start.isot)

which outputs:
2023-10-14T15:57:38.068


text:
Q: Tap Event for Pin Annotation Callout View What method should I use to handle if the Pin Annotation's view gets clicked?
I am able to get the disclosure button hooked up to this:
myPinAnnotationView.canShowCallout = YES

- (void)mapView:(MKMapView *)mapView annotationView:(MKAnnotationView *)view calloutAccessoryControlTapped:(UIControl *)control

How do I get the Callout View to trigger a tap event?

A: *

*Implement extension MKMapViewDelegate

*Implement method func mapView(_ mapView: MKMapView, didSelect view: MKAnnotationView)

*Put whatever functionality you need/desire within that method


text:
Q: How to transform list of dictionaries with jagged arrays to a DataFrame Fairly new to Pandas.  I'm trying to get a json data set which looks like this
data = [
    {'id':1, 'colors':['red', 'blue']},
    {'id':2, 'colors':['red', 'blue', 'green']},
    {'id':3, 'colors':['orange', 'blue', 'orange']},
]

into a Pandas DataFrame which looks like this
import pandas as pd
df = pd.DataFrame({'id':[1,2,3],
                  'blue':[1,1,1],
                  'green':[0,1,0],
                  'orange':[0,0,2],
                  'red':[1,1,0]})
df
     blue  green  id  orange  red
0     1      0   1       0    1
1     1      1   2       0    1
2     1      0   3       2    0

Where the columns are 'id' and the unique colors and the rows are the ids and the count of each color in each original dictionary.  How do I do this?

A: Figured it out.
df = [DataFrame(e) for e in data]
df = pd.concat(df)
df = df.pivot_table(index=['id'], columns=['colors'], aggfunc=len).fillna(0)
df

   blue  green  id  orange  red
0     1      0   1       0    1
1     1      1   2       0    1
2     1      0   3       2    0

A: >>> ids = [item['id'] for item in data]
>>> col = [item['colors'] for item in data]

>>> ids = np.repeat(ids, list(map(len, col)))
>>> col = [a for item in col for a in item]

>>> df = DataFrame({'ids':ids, 'colors':col})
>>> df
   colors  id
0     red   1
1    blue   1
2     red   2
3    blue   2
4   green   2
5  orange   3
6    blue   3
7  orange   3
>>> df.groupby(['id', 'colors']).size().unstack().fillna(0)
colors  blue  green  orange  red
id
1          1      0       0    1
2          1      1       0    1
3          1      0       2    0

you may call .reset_index at the end, to have id as a column instead of index.

A: I would first get the list of all unique colors using set().union() on the colors lists and then create the new dictionary using collections.defaultdict. Example -
In [10]: data = [
   ....:     {'id':1, 'colors':['red', 'blue']},
   ....:     {'id':2, 'colors':['red', 'blue', 'green']},
   ....:     {'id':3, 'colors':['orange', 'blue', 'orange']},
   ....: ]

In [11]:

In [11]: from collections import defaultdict

In [24]: colorlist = list(set().union(*colorlist))

In [25]: colorlist
Out[25]: ['orange', 'blue', 'red', 'green']

In [26]: newd = defaultdict(list)

In [30]: for x in data:
   ....:     xid = x['id']
   ....:     newd['id'].append(xid)
   ....:     for elem in colorlist:
   ....:         if elem in x['colors']:
   ....:             newd[elem].append(xid)
   ....:         else:
   ....:             newd[elem].append(0)
   ....:

In [31]: newd
Out[31]: defaultdict(<class 'list'>, {'id': [1, 2, 3], 'orange': [0, 0, 3], 'blue': [1, 2, 3], 'red': [1, 2, 0], 'green': [0, 2, 0]})

In [32]: df = pd.DataFrame(newd)

In [33]: df
Out[33]:
   blue  green  id  orange  red
0     1      0   1       0    1
1     2      2   2       0    2
2     3      0   3       3    0

A: You can make use of list comprehension and dicts, for a faster alternative
In [2494]: pd.DataFrame(dict(zip(r['colors']+['id'], [1]*len(r['colors'])+[r['id']]))
                        for r in data).fillna(0)
Out[2494]:
   blue  green  id  orange  red
0     1    0.0   1     0.0  1.0
1     1    1.0   2     0.0  1.0
2     1    0.0   3     1.0  0.0

Timings
In [2492]: %timeit pd.DataFrame(dict(zip(r['colors']+['id'], [1]*len(r['colors'])+[r['id']])) for r in data).fillna(0)
1000 loops, best of 3: 863 µs per loop

In [2493]: %timeit pd.concat([pd.DataFrame(e) for e in data]).pivot_table(index=['id'], columns=['colors'], aggfunc=len).fillna(0)
100 loops, best of 3: 7.79 ms per loop

Details
In [2495]: [dict(zip(r['colors']+['id'], [1]*len(r['colors'])+[r['id']])) for r in data]
Out[2495]:
[{'blue': 1, 'id': 1, 'red': 1},
 {'blue': 1, 'green': 1, 'id': 2, 'red': 1},
 {'blue': 1, 'id': 3, 'orange': 1}]

A: If using pandas 0.25 and up, explode is a convenience method
df = (pd.DataFrame(data)
        .assign(v=1)
        .explode('colors')
        .groupby(['id', 'colors']).sum()
        .unstack(1, fill_value=0)
        .reset_index(col_level=1)
      )

df.columns = df.columns.droplevel(0)


text:
Q: Suggestion Needed on using GSM to sip gateway with freeswitch in C# I am considering using 2N® VoiceBlue Lite with Freeswitch to serve as a GSM to sip gateway that will route gsm calls to fs server for an IVR system to be built with C# anybody who has tested this or anybody with any suggestions or opinion?

A: What does your IVR system need to achieve? If it's routing call then you can do this fairly easily with the freeswitch dialplans.
Anything more complicated might require a programming language. I've used LUA in FS and this works very well. LUA is integrated well and there's a lot of help on the web for how to program FS using LUA.
2N VoiceBlueLite looks like a standard GSM gateway and calls can be sent from the 2N in SIP to FS. DTMF is handled by 2N with RFC2833 so this won't cause a problem on freeswitch.
You might find that you are getting double digits on Freeswitch - this sometimes happens with SIP so best practice is to explicitly state that you're using RFC2833 at the beginning of your inbound dialplan.


text:
Q: postgraphile - how to enable many to many relation field I have Uploads table.
Uploads has many-to-many relation with Parties table.
the junction table is Uploads_Parties, it contains: upload_id & party_id as fields.
how can i make postgraphile to consider these relation in the schema generation ?
attempts:

*

*many-to-many plugin - https://github.com/graphile-contrib/pg-many-to-many. after adding the plugin no effect was taking place.

*smart tags plugin - https://www.graphile.org/postgraphile/make-pg-smart-tags-plugin/ - i tried adding foreign key relation between the Uploads.upload_id -> Uploads_Parties.upload_id, but then postgraphile throw an error.

Server init code
const SmartTagsPlugin = makePgSmartTagsFromFilePlugin(
  resolve(__dirname, '../../postgraphile.tags.jsonc'),
);
...
appendPlugins: [
        SmartTagsPlugin,
        PgManyToManyPlugin]
...

tags.jsonc
"config": {
    "class": {
      "upload_service.upload": {
        "tags": {
          "foreignKey": [
            "(id) references upload_service.uploads_parties (upload_id)|@fieldName uploadDataSet"
          ]
        }
      }
    }
  }

A: the solution was the tags.jsonc, only pointing the fk the other way around:
uploads.upload_id <- uploads_parties.upload_id.
"config": {
    "class": {
      "upload_service.uploads_parties": {
        "tags": {
          "foreignKey": [
            "(upload_id) references upload_service.uploads (id)|@fieldName fileUpload"
          ]
        }
      }
    }
  }

i also have these plugins:
    pgSimplifyInflector,
    postgraphilePluginConnectionFilter,
    pgOrderByRelatedPlugin,
    pgAggregatesPlugin,


text:
Q: Angular Blank page - Random issue Some  of my customers, got blank page when they enter to my site.
My site based on angular application.
I try many things to restore this "blank page" error, for getting the console errors, but with no success.
I try open the site in different browsers.
Open multiple requests same time.
Windows / Mac.
This is my app.js file
    var siteApp = angular.module('siteApp', ['ui.router', 'ngSanitize', 'ngAnimate',
'datatables','datatables.buttons','ngCookies']);
    siteApp.config(function ($stateProvider, $urlRouterProvider,$httpProvider) {
        $urlRouterProvider.otherwise("/index");
        $httpProvider.defaults.headers.common['X-CSRF-Token'] = $('meta[name=csrf-token]').attr('content');
      $stateProvider
          .state('app', {
              url: "/?:site_id",
              templateUrl: "/controls/angular/templates/partial/app.html",
              abstract: true
          })
          .state('app.popup', {
          }).....
    });
    siteApp.run(['$rootScope','$cookies','$state','$location','$window',
        function(
            $rootScope,$cookies, $state, $location,$window) {
            $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
                var log_route = $cookies.get("hash_route");
                if(log_route && log_route.length){
                    var date = new Date();
                    date.setTime(date.getTime()+(-2*24*60*60*1000));
                    var expires = "; expires="+date.toGMTString();
                    document.cookie = "hash_route" + "=" + undefined + "; " + expires+"; path=/";
                    $location.url(log_route);
                    return null;
                }
            });
            $rootScope.$on('$stateChangeSuccess', function () {
                try {  if (!$window.ga) {
                    } else {
                        //$window.ga('send', 'pageview', { page: $location.path() });
                    }
                } catch (x) {}
            });
        }
    ]);

I look for ideas for diagnose or restore this issue, or thing for debugging and getting the data error from customers.


text:
Q: Render/edit MS Office docs in browser with SharePoint or WOPI I have a Rails application I want to do CRUD operation on user's documents online but I want to render MS Office (OpenXML-based) docs in the browser. I have heard about WOPI/SharePoint. How can  I integrate it with my web app?

A: What you're looking for is indeed called WOPI. To be precise, you want to integrate Office Online Server (WOPI client) with your application (WOPI host). This is how SharePoint's integration works as well (SharePoint plays the role of a WOPI host here).
You need to implement the following flow:

Translated to your app - your Rails app will generate URLs pointing to the WOPI client and providing it with information about the MS Office files, authentication information, etc. Then, the WOPI client reaches for those files to your Rails app which will also need to implement the REST endpoints defined by MS-WOPI protocol (mainly CheckFileInfo, GetFile, and PutFile actions).

A: If you just want to provide view for the documents, that are publicily available, you could use office live viewer, or google docs viewer. You need to basically provide an URL to your document to those services.
I have found this site that has demos for online viewers currently available, you could check it out: https://xtai-umd.github.io/docs-viewer-demo/
SharePoint also has something called WopiFrame.aspx page (or WopiFrame2.aspx), that allows you to show documents like the site above, but with authentication. Please note that this will work only for the documents that are stored in the SharePoint (in the particular SharePoint where you use that WopiFrame.aspx, that is).
If you are developing SPFx web part, this is the way to go I think. Since in this case both are running in the context of SharePoint site, you don't really need to think much about security, it's all taken care of.
I mean, implementing your own WOPI server is not easy at all, and in addition to that you'll need Office Web Apps server, either installed on-premise in your organization, or the Microsoft's online one. To be able to use Microsoft's one you need to be a member of Cloud Storage program, as far as I know.
I would not recommend implementing custom WOPI server unless it is really needed for whatever reason (in my case, it was quite specific security requirements)


text:
Q: How to make a service for iphone? I want to create a service for the iPhone which will run in the background.
I can't find any help anywhere and I dont know if its possible or not.

A: iOS doesn't allow developer to create background services like in Android.
Check the belwo SO post that clearly state Only some of the Apple apps are allowed to do this
Running application in background

A: what kind of service are you programming ?
Because Apple allows certain kinds of background tasks.
More info at http://developer.apple.com/library/ios/#documentation/iphone/conceptual/iphoneosprogrammingguide/BackgroundExecution/BackgroundExecution.html


text:
Q: Double integral in cartesian coordinate instead of (R,Theta)
my previous question (Integral of Intensity function in python)

you can see the diffraction model in image below:

I want to calculate integral of intensity in each pixel (square), so I can't use R and Theta as variable. How can I do this in X-Y coordinate.
Our function:

instead of sin(theta) we can use:
sintheta= (np.sqrt((x)**2 + (y)**2)/(np.sqrt((x)**2 + (y)**2 + d**2)))

Other constants:
lamb=550*10**(-9)
k=2.0*np.pi/lamb
a=5.5*2.54*10**(-2)
d=2.8

when you plot function, the result is something like this:(The image above is a view from top)

the method in previous topic:
calculate integrate of function in (0.0, dist) and after that * (2*np.pix) which x = ka*np.sin(theta), But now I want integrate in each pixel. which the previous method doesn't work, because this is X-Y coordinate , not polar.

A: Actually, the integration in Cartesian coordinates is rather straightforward. Now that you have the intensity function, you have to express the radius r by coordinates x and y. A trivial thing which you have actually done in your question.
So, the function to be integrated (without some constants) is:
from scipy import special as sp

# Fraunhofer intensity function (spherical aperture)
def f(x,y):
    r = np.sqrt(x**2 + y**2)
    return (sp.j1(r)/r)**2

Or by using the fact that 2 J1(x)/x = J0(x) + J2(x) [thanks, Jaime!]:
def f(x,y):
    r = np.sqrt(x**2 + y**2)
    return (sp.j0(r) + sp.jn(2,r))**2

This form is better in the sense that it does not have a singularity anywhere.
Now, I do not use any constant factors. You may add them if you want, but I find it easier to normalize with the integration result over infinite area. Otherwise it is too easy to just forget some constant (I do, usually).
The integration can be carried out with scipy.integrate.nquad. It accepts a multi-dimensional function to integrate. So, in this case:
import scipy.integrate

integral = scipy.integrate.nquad(f, ([-d/2, d/2], [-d/2, d/2]))[0]

However, as your function is very clearly symmetric, you might consider integrating over one quadrant only and then multiply by four:
4. * scipy.integrate.nquad(f, ([0, d/2], [0, d/2]))[0]

By using these the full intensity is:
>>> 4. * scipy.integrate.nquad(f, [[0,inf],[0,inf]])[0]
12.565472446489999

(Which looks very much like 4 pi, BTW.) Of course, you can also use the polar coordinates to calculate the full value, as the function has circular symmetry (as outlined in Integral of Intensity function in python). The different values are due to different scaling (2 pi omitted in the polar integration, 2 because I am using the sum form of the bessel functions here).
For example for a square area from -1..1 on both directions the normalized (divided by the above full power value) power over the square area is:
>>> 4*scipy.integrate.nquad(f, [[0,1],[0,1]])[0] / 12.565472446489999
0.27011854108867

So, approximately 27 % of the incoming light shines onto the square photodetector.

When it comes to your constants, it seems that something (at least units) is missing. My guess:

*

*wavelength: 550 nm

*circular aperture diameter: 0.0055" = 0.14 mm

*distance from the aperture to the sensor: 2.8 mm

*square sensor size 5.4 um x 5.4 um

The last one I just guessed from the image. As the sensor size is very much smaller than the distance, sin(ϴ) is very close to y/d, where d is distance and y displacement from the optical axis. By using these numbers x = ka sin(ϴ) = kay / d ≈ 1.54. For that number the intensity integral gives approximately 0.52 (or 52 %).
If you are comparing this to some experimental value, remember that there are numerous error sources. The image on the image plane is a fourier transform of the aperture. If there are small imperfections in the aperture edge, they may change the resulting spot. Airy rings are seldom as beautiful as astronomers think...
Just for fun:


text:
Q: VBA: Delete row if value is in list, looping through list I have two tables. One table is called DRData (Blad3), other table is CheckData (Blad2). EANCODE is Column J for DRData, and Column A for Checkdata.
I want to check whether CheckData.EANCODE is present in DRData.EANCODE. If so; delete that row from CheckData.
I tried several things, but no success yet. The code I have written now is as follows:
Sub FindEAN()
Dim i As Long
Dim x As Long

x = 1 'Start on first row

EANtoFind = Blad2.Range("A" & x).Value

For i = 1 To 99999    '

    If Blad3.Cells(i, 1).Value = EANtoFind Then
    Blad2.Range("A" & x).EntireRow.Delete
    Else: x = x + 1
    End If

Next i
End Sub

When the EANCODE is not present, I want to hop over a row to check that code. I want to end with a list in CheckData where all the EANCODE values that are not in DRData are shown.
With the code above, only the first row is getting deleted and now I'm stuck how to get this to loop. Including the x+1 to get to the next row.

A: First you have to clarify that your problem is a little bit complicated. You have to pay attention to indexes when deleting rows
To do that, you have to point the the maximal number of line to optimize your loop
A simple way to do that, is to use predefined search function, and edit your code a little bit.
My favorite is Application.match(), which takes 3 parameters :

*

*Value to look for

*Array where you look (in our case the column J of Blad3 or position 10)

*0 : exact match

For more details, see the documentation
https://learn.microsoft.com/fr-fr/office/vba/api/excel.worksheetfunction.match
An example of code which works is like the following
Sub FindEAN()

Dim x As Long

x = 1 'Start on first row

maxline = Blad2.Range("A" & Rows.count).End(xlUp).row

While x <= maxline    '
    EANtoFind = Blad2.Range("A" & x).Value
    If Not IsError(Application.Match(EANtoFind, Blad3.Columns(10), 0)) Then
        Blad2.Range("A" & x).EntireRow.Delete
        maxline = maxline - 1
    Else
        x = x + 1
    End If
Wend

End Sub


text:
Q: R combining two vectors into one Let's say I have two vectors
a <- c(NA,"Jan","Feb",NA)
b <- c("Mar",NA,NA,"Apr")

How should I combine a and b so that I can get something like this
ab <- c("Mar", "Jan", "Feb", "Apr")

Remember that here NA is different from "NA".

A: We can use pmax
pmax(a,b, na.rm=TRUE)
#[1] "Mar" "Jan" "Feb" "Apr"

Or use ifelse
ifelse(is.na(a), b, a)
#[1] "Mar" "Jan" "Feb" "Apr"


text:
Q: Directive to ignore compilation of an element I wanna write a directive called ng-ignore to prevent the HTML compiler from processing an element and it's children.
I've been practicing writing directives, but a bit confused about this one.

I want something like this:
angular.module("myMod", [])
.directive("ngIgnore", function()
{
    var dirDefObj = {
        // What should I write here to have compiler ignore this element?
    };
    return dirDefObj;
});

to be used like this:

    This div must be ignored by Angular's compiler.

Need help and pointers for writing it. Thanks.

A: Angular already has this built in ngNonBindable

Normal: {{1 + 2}}

Ignored: {{1 + 2}}

Normal: 3
Ignored: {{1 + 2}}
Plunker


text:
Q: My mouse icon is messed on my computer My mouse cursor has decided to randomly display what appears to be half an 'X' whenever the resize window cursor is displayed. I have circled it in red in this image. It is driving me nuts! I am always misclicking because of it. It is cross application. I see it in everything from Chrome to a report editor.
Oddly, I took a screenshot with 'cursors on.' But the artifact is not included! So I had to take a picture with my phone.
Windows 7 64. Relatively new install (three months old or so). Any ideas how to fix/remove it?

A: I found that by uninstalling Synaptics mouse software for my laptop's touchpad via Add/Remove programs fixed the issue. I am very happy.

A: I've got the same issue on my laptop, also featured with Synaptics, and solved it by rotating my monitor sideways and rotating it back - or the other way around, since I use it rotated by default, which might explain the issue, according to Stuart → check this thread.


text:
Q: How to disable row group expand functionality on one row? After a lot of searches in SO without any particular solution, I am compelled to ask this question.
What I want is to hide a row group icon on a single group row. Like in the below picture I have a group row that has only one record, which is already shown in the top row. I want to hide that collapse icon on that single record. Only collapse/expand icon shown when group rows are more than one.
For reference see AG-Grid Master-Detail Section, here they specify which rows to expand. Same functionality I needed here.

I'm using the below versions of AG-Grid Angular (v9)
"@ag-grid-community/core": "^25.3.0",
"@ag-grid-enterprise/row-grouping": "^26.0.0",
"@ag-grid-enterprise/server-side-row-model": "^25.3.0",
"ag-grid-angular": "^25.3.0",
"ag-grid-community": "^25.3.0",

Here is my code:
this.rowModelType = 'serverSide';
this.serverSideStoreType = 'partial';
this.cacheBlockSize = 20;
this.gridOptions = {
  rowData: this.loanlist,
  columnDefs: this.generateColumns(),
  getNodeChildDetails: function(rowItem) {
    if (rowItem.orderCount > 1) {
      return {
        expanded: true
      }
    } else {
      return null;
    }
  }
}

The issue is the getNodeChildDetails is not accessible. Browser console showing me the below warning and my above code is not working.

A: This is simple to achieve using a cellRendererSelector on the autoGroupColumnDef. You can specify whether to show the default agGroupCellRenderer or simply return another renderer (or, just return null):
    this.autoGroupColumnDef = {
      cellRendererSelector: (params) => {
        if (params.value == 'United States') {
          return null;
        } else {
          return {
            component: 'agGroupCellRenderer',
          };
        }
      },
    };

In the example below, we are disabling the row group expand functionality on the United States row.
See this implemented in the following plunkr.

A: The solution isn't that hard - but could be tough, agreed (one day faced with the same case)
So - the answer is custom cell renderer.
It would look a little bit different (separate column for collapse\expande action) - but you would get all control of it.
Custom rendeder component for this action would look like :
template: `
    <em
        [ngClass]="{'icon-arrow-down':params.node.expanded, 'icon-arrow-right': !params.node.expanded}"
        *ngIf="yourFunctionHere()"
        (click)="toggleClick()">
    </em>`,

export class MasterDetailActionComponent implements ICellRendererAngularComp {
    private params: any;

    agInit(params: any): void {
        this.params = params;
    }

    public toggleClick(): void {
        this.params.node.setExpanded(!this.params.node.expanded);
    }

    public yourFunctionHere(): boolean {
        // so here you are able to access grid api via params.api
        // but anyway params.node - would give you everything related to row also
    }

    refresh(): boolean {
       return false;
    }
}

in [ngClass] - you are able to handle the visual part (icons) - modify\customize
and don't forget to add this component in the gridOptions:
frameworkComponents: {
    'masterDetailActionCellRenderer': MasterDetailActionComponent,
}

and include this column in your columnDef:
columnDefs: [
    headerName: "",
    width: 75,
    field: "expand",
    cellRenderer: "masterDetailActionCellRenderer",
    filter: false,
    resizable: true,
    suppressMenu: true,
    sortable: false,
    suppressMovable: false,
    lockVisible: true,
    getQuickFilterText: (params) => { return '' }
]


text:
Q: How to graph individual Summary metric instances in Prometheus? I'm using Prometheus' Summary metric to collect the latency of an API call.  Instead of making an actual API call, I'm simply calling Thread.sleep(1000) to simulate a 1 second api-call latency value -- this makes the Summary hold a value of .01 (for 1 second of latency).  But if, for example, I invoke Thread.sleep(1000) twice in the same minute, the Summary metric ends up with a value of .02 (for 2 seconds of latency), instead of two individual instances of .01 latency that just happened to occur within the same minute. My problem is the Prometheus query. The Prometheus query I am currently using is: rate(my_custom_summary_sum[1m]).
What should my Prometheus query be, such that I can see the latency of each individual Thread.sleep(1000) invocation.  As of right now, the Summary metric collects and displays the total latency sum per minute.  How can I display the latency of each individual call to Thread.sleep(1000) (i.e. the API request)?
private static final Summary mySummary = Summary.build()
                                        .name("my_custom_summary")
                                        .help("This is a custom summary that keeps track of latency")
                                        .register();

Summary.Timer requestTimer = mySummary.startTimer(); //starting timer for mySummary 'Summary' metric
        Thread.sleep(1000); //sleep for one second
        requestTimer.observeDuration(); //record the time elapsed

This is the graph that results from this query:
Prometheus graph

A: Prometheus is a metrics-based monitoring system, it cares about overall performance and behaviour - not individual requests.
What you are looking for is a logs-based system, such as Graylog or the ELK stack.


text:
Q: appendbytes with mp4 Hi I have a flash as3 player that is playing flv files using appendbytes.
I have searched the web for many hours on how to stream a mp4 using appendbytes.
Does anyone have a solution for this?
Just using Netstream is not an option as we need progressive download seeking.

A: The best thing I've found is using the SoundLoaderContext, and setting the first argument to be whatever time you want to spend buffering.
I've researched the "loadCompressedDataFromByteArray" and "loadPCMFromByteArray " methods in the Sound class, but the solution would be to buffer a certain amount of sound and then load it.
Found this sample code:
import flash.media.Sound;
import flash.media.SoundLoaderContext;
import flash.net.URLRequest;

var s:Sound = new Sound();
var req:URLRequest = new URLRequest("trackName.mp4");
var context:SoundLoaderContext = new SoundLoaderContext(8000, true);
s.load(req, context);
s.play();


text:
Q: How To Convert HTTPS POST to HTTP POST I have an existing web application hosted in Tomcat which is listening for a HTTP POST.
However for security reasons requests to the web application have to be transported across the network as HTTPS.
I cannot change the web application.
So I want to receive a HTTPS POST, decrypt it and pass it on to the web application as a HTTP POST.
I also need to pass back to the sender response codes etc.
I have been told that I can do this using Apache configured as a "reverse proxy".
But I am not an expert at Apache or Tomcat and before I investigate this option I wanted to be sure I was going down the right path.
i.e.
Schematic
So to the Remote Server application everything looks like it happens over HTTPS.
And to my local Tomcat web application everything looks like it happens over HTTP.
Is this doable and correct ?
Do I need to use Apache or could I do it all in Tomcat ?
Is this what is called "url rewriting" ?
This is more than just "redirection" ?
Thanks,
Brett


text:
Q: Compiling a main document with many TikZ subfiles efficiently What would be the most efficient way to compile a document of the article class with many TikZ subfiles?
In the main document, I have added \usepackage{standalone} and then \includestandalone for the individual subfiles.

*

*Would it be better to add the options subpreambles = true, sort =
true, and trim all the TikZ preambles from the main document?

*Or should I not use those options and keep all the TikZ preambles
in both the main .tex file and the subfiles?
Which method would speed up compiling?  If neither of these methods are truly efficient, what should I do instead?
As it stands now, my document is around 60 pages but it takes a few minutes to compile.  I have over 30 .eps figures and over 30 TikZ subfiles.  Besides the TikZ code, everything else is pretty standard LaTeX.
The document class for the subfiles is standalone with the option convert = false.
One of the other problems that slows down compilation is the fact that every standalone picture is compiled when the main document is compiled.  However, there may have been nothing change with 95% of the pictures.
Main example doc:
\documentclass{article}
\usepackage{standalone}
\usepackage{tikz}
\usepackage{float}
\begin{document}
text here
\begin{figure}[H]
  \centering
  \includestandalone{test}
\end{figure}
text here
\end{document}

test example doc
\documentclass[convert = false, tikz]{standalone}
\begin{document}
\begin{tikzpicture}
  \draw (0, 0) circle[radius = .35cm];
\end{tikzpicture}
\end{document}

A: I use the suggestion in zeroth's discussion.
The discussion is for pdflatex.
However, I use xelatex, and I only test the methods by texlive on Linux x64 system.
here is my way to make it works for xelatex compiler:

*

*In the document preamble after \usepackage{tikz}:
\usepackage{tikz}
  \usetikzlibrary{external}
  \tikzexternalize[figure list=false,prefix=tikz/]
    % make tikz externalize and store in directory "tikz"
  \tikzset{external/system call={xelatex \tikzexternalcheckshellescape
    -halt-on-error -interaction=batchmode -jobname "\image" "\texsource"}}
    % to let xelatex work

and use the command xelatex -shell-escape xxxxxxx.tex to compile the picture externalized. (Till now the normal xelatex xxxxxxx.tex command would return errors)

*Once all independent pdf files compiled, normal xelatex xxxxxxx.tex should works as usual.
It's not perfect way to do tikz figure externalized because the options here cannot recognize whether the externalized pdf files are identical to new tikz figure.


text:
Q: How to change the text on ARcore Sample - Solar System I'm trying to add / change the text on the Solar System Augmented Reality sample from ARcore. For example Earth to No. 3 Earth, but I could not find anywhere to do this.
I tried changing the name in Earth.sfb in the Assets folder, but it doesn't work.
model: {
    attributes: [
        'Position',
        'TexCoord',
        'Orientation',
    ],
    collision: {},
    file: 'sampledata/models/Earth/Earth.gltf',
    name: 'No.3-The Earth',
    recenter: true,
    scale: 0.5


text:
Q: Why are private fields private to the type, not the instance? In C# (and many other languages) it's perfectly legitimate to access private fields of other instances of the same type. For example:
public class Foo
{
    private bool aBool;

    public void DoBar(Foo anotherFoo)
    {
        if (anotherFoo.aBool) ...
    }
}

As the C# specification (sections 3.5.1, 3.5.2) states access to private fields is on a type, not an instance. I've been discussing this with a colleague and we're trying to come up with a reason why it works like this (rather than restricting access to the same instance).
The best argument we could come up with is for equality checks where the class may want to access private fields to determine equality with another instance. Are there any other reasons? Or some golden reason that absolutely means it must work like this or something would be completely impossible?

A: First of all, what would happen to private static members? Can they only be accessed by static methods? You certainly wouldn't want that, because then you wouldn't be able to access your consts.
As to your explicit question, consider the case of a StringBuilder, which is implemented as a linked list of instances of itself:
public class StringBuilder
{
    private string chunk;
    private StringBuilder nextChunk;
}

If you can't access the private members of other instances of your own class, you have to implement ToString like this:
public override string ToString()
{
    return chunk + nextChunk.ToString();
}

This will work, but it's O(n^2) -- not very efficient. In fact, that probably defeats the whole purpose of having a StringBuilder class in the first place. If you can access the private members of other instances of your own class, you can implement ToString by creating a string of the proper length and then doing an unsafe copy of each chunk to its appropriate place in the string:
public override string ToString()
{
    string ret = string.FastAllocateString(Length);
    StringBuilder next = this;

    unsafe
    {
        fixed (char *dest = ret)
            while (next != null)
            {
                fixed (char *src = next.chunk)
                    string.wstrcpy(dest, src, next.chunk.Length);
                next = next.nextChunk;
            }
    }
    return ret;
}

This implementation is O(n), which makes it very fast, and is only possible if you have access to private members of other instances of your class.

A: I think one reason it works this way is because access modifiers work at compile time. As such, determining whether or not a given object is also the current object isn't easy to do. For example, consider this code:
public class Foo
{
    private int bar;

    public void Baz(Foo other)
    {
        other.bar = 2;
    }

    public void Boo()
    {
        Baz(this);
    }
}

Can the compiler necessarily figure out that other is actually this? Not in all cases. One could argue that this just shouldn't compile then, but that means we have a code path where a private instance member of the correct instance isn't accessible, which I think is even worse.
Only requiring type-level rather than object-level visibility ensures that the problem is tractable, as well as making a situation that seems like it should work actually work.
EDIT: Danilel Hilgarth's point that this reasoning is backwards does have merit. Language designers can create the language they want, and compiler writers must conform to it. That being said, language designers do have some incentive to make it easier for compiler writers to do their job. (Though in this case, it's easy enough to argue that private  members could then only be accessed via this (either implicitly or explicitly)).
However, I believe that makes the issue more confusing than it needs to be. Most users (myself included) would find it unneccessarily limiting if the above code didn't work: after all, that's my data I'm trying to access! Why should I have to go through this?
In short, I think I may have overstated the case for it being "difficult" for the compiler. What I really meant to get across is that above situation seems like one that the designers would like to have work.

A: Because the purpose of the kind of encapsulation used in C# and similar languages* is to lower mutual dependence of different pieces of code (classes in C# and Java), not different objects in memory.
For example, if you write code in one class that uses some fields in another class, then these classes are very tightly coupled. However, if you are dealing with code in which you have two objects of the same class, then there is no extra dependency. A class always depends on itself.
However, all this theory about encapsulation fails as soon as someone creates properties (or get/set pairs in Java) and exposes all the fields directly, which makes classes as coupled as if they were accessing fields anyway.
*For clarification on kinds of encapsulation see Abel's excellent answer.

A: Quite some answers have already been added to this interesting thread, however, I didn't quite find the real reason for why this behavior is the way it is. Let me give it a try:
Back in the days
Somewhere between Smalltalk in the 80's and Java in the mid 90's the concept of object-orientation matured. Information hiding, not originally thought of as a concept only available to OO (mentioned first in 1978), was introduced in Smalltalk as all data (fields) of a class is private, all methods are public. During the many new developments of OO in the 90's, Bertrand Meyer tried to formalize much of the OO concepts in his landmark book Object Oriented Software Construction (OOSC) which has since then be considered an (almost) definitive reference on OO concepts and language design.
In the case of private visibility
According to Meyer a method should be made available to a defined set of classes (page 192-193). This gives obviously a very high granularity of information hiding, the following feature is available to classA and classB and all their descendants:
feature {classA, classB}
   methodName

In the case of private he says the following: without explicitly declaring a type as visible to its own class, you cannot access that feature (method/field) in a qualified call. I.e. if x is a variable, x.doSomething() is not allowed. Unqualified access is allowed, of course, inside the class itself.
In other words: to allow access by an instance of the same class, you have to allow the method access by that class explicitly. This is sometimes called instance-private versus class-private.
Instance-private in programming languages
I know of at least two languages currently in use that use instance-private information hiding as opposed to class-private information hiding. One is Eiffel, a language designed by Meyer, that takes OO to its utmost extremes. The other being Ruby, a far more common language nowadays. In Ruby, private means: "private to this instance".
Choices for language design
It has been suggested that allowing instance-private would be hard for the compiler. I don't think so, as it is relatively simple to just allow or disallow qualified calls to methods. If for a private method, doSomething() is allowed and x.doSomething() is not, a language designer has effectively defined instance-only accessibility for private methods and fields.
From a technical point of view, there's no reason to choose one way or the other (esp. when considering that Eiffel.NET can do this with IL, even with multiple inheritance, there's no inherent reason not to provide this feature).
Of course, it's a matter of taste and as others already mentioned, quite some methods might be harder to write without the feature of class-level visibility of private methods and fields.
Why C# allows only class encapsulation and not instance encapsulation
If you look at internet threads on instance encapsulation (a term sometimes used to refer to the fact that a language defines the access modifiers on instance level, as opposed to class level), the concept is often frowned upon. However, considering that some modern languages use instance encapsulation, at least for the private access modifier, makes you think it can be and is of use in the modern programming world.
However, C# has admittedly looked hardest at C++ and Java for its language design. While Eiffel and Modula-3 were also in the picture, considering the many features of Eiffel missing (multiple inheritance) I believe they chose the same route as Java and C++ when it came to the private access modifier.
If you really want to know the why you should try to get a hold of Eric Lippert, Krzysztof Cwalina, Anders Hejlsberg or anyone else who worked on the standard of C#. Unfortunately, I couldn't find a definitive note in the annotated The C# Programming Language.

A: This is perfectly legitimate in many languages (C++ for one). The access modifiers come from the encapsulation principle in OOP. The idea is to restrict access to outside, in this case outside is other classes. Any nested class in C# for example can access it's parents private members also.
While this is a design choice for a language designer. The restriction of this access can complicate some very common scenarios extremely without contributing much to isolation of entities.
There is a similar discussion here

A: I don't think that there's a reason we couldn't add another level of privacy, where data is private to each instance. In fact, that might even provide a nice feeling of completeness to the language.
But in actual practice, I doubt it would really be that useful. As you pointed out, our usual private-ness it is useful for things such as equality checks, as well as most other operations involving multiple instances of a Type. Although, I also like your point about maintaining data abstraction, as that is an important point in OOP.
I think all around, providing the ability to restrict access in such a way could be a nice feature to add to OOP. Is it really that useful? I'd say no, since a class should be able to trust its own code. Since that class is the only things that can access private members, there's no real reason to need data abstraction when dealing with an instance of another class.
Of course, you can always write your code as if private applied to instances. Use the usual get/set methods to access/change the data. That would probably make the code more manageable if the class may be subject to internal changes.

A: This is only my opinion, but pragmatically, I think that if a programmer has access to the source of a class, you can reasonably trust them with accessing the class instance's private members. Why bind a programmers right hand when in their left you've already given them the keys to the kingdom?

A: The reason indeed is equality check, comparison, cloning, operator overloading...
It would be very tricky to implement operator+ on complex numbers, for example.

A: Great answers given above. I would add that part of this problem is the fact that instantiating a class inside itself is even allowed in the first place. It makes since in a recursive logic "for" loop, for example, to use that type of trick as long as you have logic to end the recursion. But instantiating or passing the same class inside itself without creating such loops logically creates its own dangers, even though its a widely accepted programming paradigm. For example, a C# Class can instantiate a copy of itself in its default constructor, but that doesn't break any rules or create causal loops. Why?
BTW....this same problem applies to "protected" members as well. :(
I never accepted that programming paradigm fully because it still comes with a whole suite of issues and risks that most programmers don't fully grasp until issues like this problem rise up and confuse people and defy the whole reason for having private members.
This "weird and wacky" aspect of C# is yet one more reason why good programming has nothing to do with experience and skill, but just knowing the tricks and traps.....like working on a car. Its the argument that rules were meant to be broken, which is a very bad model for any computing language.

A: It seems to me that if data was private to other instances of the same type, it wouldn't necessarily be the same type anymore. It wouldn't seem to behave or act the same as other instances. Behavior could easily be modified based on that private internal data. That would just spread confusion in my opinion.
Loosely speaking, I personally think that writing classes derived from a base class offers similar functionality you are describing with 'having private data per instance'. Instead, you just have a new class definition per 'unique' type.


text:
Q: Add class after scroll to section, when feel and animation to id I search scripts, which will be behaviour during scroll: http://www.dishoom.com/.
I have three sections of the site and would like to scrollowaniu to the middle of the section equalized it to the upper position. The example is above
Regards

A:  <script>
        jQuery(document).ready(function ($) {
            $(window).scroll(function () {
                   scroll = $(window).scrollTop();

                var height_check = jQuery(window).height() ;
                $(document).mousewheel(function (event) {
                    if (event.deltaY) {
                        $(window).scroll(function () {

                            if(scroll >= $("section#home_bg").offset().top)
                            {
                                $('section#barman').removeClass('snaps-active');
                                $('section#galeria').removeClass('snaps-active');
                                $('section#home_bg').addClass('snaps-active');

                                if(scroll >= ($("section#home_bg").offset().top + (0.5*height_check)))
                                {
                                    $('section#home_bg').removeClass('snaps-active');

                                }
                            }
                            if (scroll >= $("section#barman").offset().top) {
                                $('section#barman').addClass('snaps-active');
                                $('section#galeria').removeClass('snaps-active');
                                $('section#home_bg').removeClass('snaps-active');

                                if(scroll >= ($("section#barman").offset().top + (0.5*height_check)))
                                {
                                    $('section#barman').removeClass('snaps-active');

                                }

                            }
                            if(scroll >= ($("section#galeria").offset().top)) {
                                $('section#home_bg').removeClass('snaps-active');
                                $('section#barman').removeClass('snaps-active');
                                $('section#galeria').addClass('snaps-active');

                                if (scroll >= ($("section#galeria").offset().top + (0.5 * height_check))) {
                                    $('section#galeria').removeClass('snaps-active');
                                }

                            }

                        });

                    }

                });

            });

        });
    </script>


text:
Q: Is there a way to have multiple dialog boxes with Twitter-Bootstrap? I am using Twitter Bootstrap for everything and it's great but am at the point where I need multiple dialog boxes on the screen. I have not been able to find in the documentation how to do this so I'm assuming it is not something that is included.
I'm looking for something similar to jQuery-UI dialog boxes (NOT modals)
Is there a way to achieve this with Twitter Bootstrap without writing a new piece of code?

A: There is not problem in doing so. I've a project where it is working fine. There is one 'glitch' the backdrop is stacked so the backdrop (if you use it) of the first dialog is leading and for every dialog one gets stacked on top of it. The dialog you opened first is not greyed out. So probable you want to load you dialog with .modal("show", {backdrop: false}) after the first one and if possible you want your dialogs to be of the same size or bigger then the previously opened dialogs to circumvent the problem.
In our case it's an internal application, so this is not a big issue. But for a public website I could imagine this is a showstopper.