text:
Q: BigQuery Data Location Setting Is there a way to determine "BigQuery Data Location Setting", similar to "Cloud Storage Data Location Setting" or "Datastore Data Location Setting"?
Apparently there are some legal & tax issues for companies operating outside of the US when using services hosted in the US. Our legal guys have asked me to configure the BigQuery location to be in EU. But i couldn't find where to configure this.
Thanks

A: There isn't currently a way to locate your BigQuery data in the EU. Right now, all of it is located in the United States.
That said, one of the reasons why this hasn't been done yet is due to lack of customer interest in EU datacenters. If you have a relationship with google cloud support and want this feature, please let them know. Alternately, vote up the question and we'll take that into account when we prioritize new features.

A: This appears to have changed now, so you can actually select the EU datacenter:
http://techcrunch.com/2015/04/16/google-opens-cloud-dataflow-to-all-developers-launches-european-zone-for-bigquery/

A: Another issue arises when you want to copy datasets from one region to the other which is not currently possibly (at least directly). Here is how you can check the location of your dataset. Open up a Google Cloud Shell and enter this command:
bq show --format=prettyjson {PROJECT_ID}:{DATASET_NAME} | grep location
However, note that you cannot edit the location. You will need to backup/export all your tables, delete the dataset, and recreate the dataset with the desired location.


text:
Q: How to store data lake gen2 with Java Functions? I have Service Bus triggered Java based Azure Function, which should write (json) message to data lake gen 2 storage in CSV or Parquet. Is this possible?
I can find sample code for binary data type for blob. https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-storage-blob-output?tabs=java#example
Where I can find sample code or tutorial for data lake?

A: I will do with java sdk
as it seem like no output binding cannot be found.

redpajama_set_name: RedPajamaStackExchange


text:
Q: switch from one to another layout using radioButton hi i am trying to get through my xml files using a radio group which in a same activity but it perfom just for the first click here is my xml file
  package com.example.carteacache;

  import java.util.ArrayList;
  import java.util.List;

  import android.annotation.SuppressLint;
  import android.os.Bundle;
  import android.support.v7.app.ActionBarActivity;
  import android.view.Menu;
  import android.view.MenuItem;
  import android.view.View;
  import android.view.View.OnClickListener;
  import android.widget.ArrayAdapter;
  import android.widget.Button;
  import android.widget.RadioButton;
  import android.widget.RadioGroup;
  import android.widget.Spinner;
  import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
  public Button bouton1;
  public Button bouton2;
  private Spinner spinner;
  private RadioGroup radiobutO;
  private RadioButton chRadio;
  private String [] paysListe  = {"Sénégal","Gambie","Sierra Leone","Burkina","Mali"};
@SuppressLint("CutPasteId")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    bouton1  = (Button)findViewById(R.id.button1);
    bouton2 = (Button)findViewById(R.id.button2);
    spinner = (Spinner)findViewById(R.id.spinner);
    radiobutO =(RadioGroup) findViewById(R.id.radioGroup);
    final RadioGroup rg = (RadioGroup) findViewById(R.id.radioGroup);
    populateSpinner();

Here is where i am navigating thought the option which will allow  user to get from one to another xml file
    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
    {

        public void onCheckedChanged(RadioGroup group, int checkedId)
        {
            chRadio  =(RadioButton)rg.findViewById(radiobutO.getCheckedRadioButtonId());
            checkedId =  group.getCheckedRadioButtonId();
            setContentView(R.layout.activity_main);
            switch(checkedId)
            {

            case R.id.radio1:
                Toast.makeText(MainActivity.this, chRadio.getText(), Toast.LENGTH_LONG).show();
                setContentView(R.layout.activity_main);
                break;
            case R.id.radio2:
                Toast.makeText(MainActivity.this, chRadio.getText(), Toast.LENGTH_LONG).show();
                setContentView(R.layout.activity_main2);
                // TODO Something
                break;
            case R.id.radio3:
                Toast.makeText(MainActivity.this, chRadio.getText(), Toast.LENGTH_LONG).show();
                setContentView(R.layout.activity_main3);
                // TODO Something

                break;
            }
        }
    });

      bouton1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

        }
    });

   }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
    }

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

 private void populateSpinner() {

        //txtCategory.setText("");

        List<String> pays = new ArrayList<String>();
        for (int i = 0; i < paysListe.length; i++) {
            pays.add(paysListe[i]);
        }

        // Creating adapter for spinner
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_spinner_item, pays);

        // Drop down layout style - list view with radio button
        spinnerAdapter
                .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

        // attaching data adapter to spinner
        spinner.setAdapter(spinnerAdapter);
    }
       }

Am using radioButton to get to next xlm file.
Any help will be much appreciated


text:
Q: Usercontrol runtime width and height I am trying to create a simple User Control (not WPF) in VS2008 which effectively is a SplitContainer with a button in Panel1, which when pressed, toggles the Panel2Collapsed property and resizes the control to the size of Panel1.
Here are the bare bones of the control:
private int _openHeight;
private int _closedHeight;

public MyUserControl(bool open)
{
  InitializeComponent();

  _openHeight = this.Height;
  _closedHeight = splitContainer1.SplitterDistance;
  Open = open;
}

private bool _open;
private bool Open
{
  get { return _open; }
  set
  {
    _open = value;
    splitContainer1.Panel2Collapsed = !_open;
    this.Height = _open ? _openHeight : _closedHeight;
  }
}

private void button1_Click(object sender, EventArgs e)
{
  Open = !Open;
}

The problem is that this.Height in Runtime is the value which the control is in the User Control Designer, rather than what is set at Design-time in the main form's designer.
Any help would be greatly appreciated.
UPDATE
Following on from Lucas' solution, this way means that the _openHeight is only set once, resulting in the desired effect:
private int? _openHeight;
private int _closedHeight;

public MyUserControl(bool open)
{
  InitializeComponent();

  //the _closedHeight doesn't change so can be defined in the constructor
  _closedHeight = splitContainer1.SplitterDistance;

  //set value
  Open = open;

  this.SizeChanged += new EventHandler(MyUserControl_SizeChanged);
  this.Load += new EventHandler(MyUserControl_Load);
}

void MyUserControl_SizeChanged(object sender, EventArgs e)
{
  //this event is called BEFORE the _Load event so gets the height set in the designer
  //  and not any changes at run time (e.g. when you collapse the control)

  if (_openHeight == null)
    _openHeight = this.Height;
}

private bool _open;
private bool Open
{
  get { return _open; }
  set
  {
    _open = value;

    if (_open)
    {
      //sets height only if it has been initialized
      if (_openHeight != null)
        this.Height = (int)_openHeight;
    }
    else
    {
      this.Height = (int)_closedHeight;
    }
  }
}

void MyUserControl_Load(object sender, EventArgs e)
{
  //now that control is loaded, set height
  Open = Open;
}

private void button1_Click(object sender, EventArgs e)
{
  Open = !Open;
}

A: You are reading the control's Height property in it's constructor, which means it's probably BEFORE it shows in the form. The thing is, the size seems to be adjusted when the control needs to be show in the form. Before this, it's a value set in the control's designer, which you are now getting.
The easiest way to solve the issue is to read the Height value when you're sure that the control was already drawn in the form i.e. you can get open parameter out of the control's constructor, add a new method that initializes Open and _closedHeight and call it in Load event of the form.
Something like this:
public MyUserControl()
{
    InitializeComponent();
}

public AdjustControlSize(bool open)
{
    _openHeight = this.Height;
    _closedHeight = splitContainer1.SplitterDistance;
    Open = open;
}

//the rest of the control's code is unchanged
...

Then call AdjustControlSize method from form's Load event.
Solution with eventing mechanism
You can also use control's own events to read the Height when appropriate. This way you don't have to change anything in the Form's code.
So, in this case, the code can look like this (I haven't tested this though):
public MyUserControl(bool open)
{
    InitializeComponent();

    _openHeight = this.Height;
    _closedHeight = splitContainer1.SplitterDistance;
    Open = open;
    this.SizeChanged += new EventHandler(MyUserControl_SizeChanged);
}

void CustomPictureBox_SizeChanged(object sender, EventArgs e)
{
    _openHeight = this.Height;
    _closedHeight = splitContainer1.SplitterDistance;
}

This way the control can self adjust itself each time its size is changed.


text:
Q: How to delete an app from developers.vimeo.com? I created wrongly 2 times the same app on developers.vimeo.com. My goal was to create the new one on a new account and then delete the old one from the first account, but, due to a monster bug on vimeo login, I logged with my second account and finished logged with the first one. ... but this is not my question.
The simple question is: what's the right path to delete a existent app ?
We can't find a delete button on the developer panel.

A: Currently, it is not possible to delete API apps created on your Vimeo account.
However, there is no limit to the number of API apps you can create, as long as you follow the Developer Guidelines (https://developer.vimeo.com/guidelines).
That said, if you would like your app manually deactivated, you can always reach out to Vimeo support for further assistance- https://vimeo.com/help/contact.


text:
Q: Is it possible to use a XBee module to controll a quadcopter? I'm thinking to design my own quadcopter and wondered if it's possible to use a XBee module to control the drone?
The reason I'm thinking about an XBee module is because I want to be able to plug it into my computer and control it from there.
UPDATE:
Anyone got any other recomondation on "remote controll" modules ?

A: Depends on many usage factors:

*

*Indoor or Outdoor?

*How far from the computer will it travel?

*Will it merely be receiving commands from the PC? Or will it have complete control over the copter at all times?

*Are you trying to transmit a lot of data to/from the copter? For example, and onboard camera?

Xbee can be great for many applications, but it can lose signal integrity pretty quickly in indoor applications (sorry don't have much experience outdoors but it should be a big improvement). The 100m indoor specification is more of a pipe dream in my experience. If your PC is acting more like a brain than a command center for this quadrocopter you could run into trouble very quickly.
Personally I would have a decent embedded system onboard the quadrocopter that can make good decisions on its own and maybe only report back sensor data when it's needed. Having the PC make time critical control decisions like balancing the thrust from the motors will be a nightmare because of latency and signal integrity. Instead you could, for example, have the computer tell the copter "go left for .5s" and it will know how to execute that command.
I wouldn't bother trying to use a camera onboard with XBee unless all the computer vision processing is done on board the copter.


text:
Q: Nintendo Switch and Power Bank it's just one week until the nintendo switch is in stores and as I plan to play a lot I would like to know if I can connect it to my power bank? I have this doubt because my power bank just have an 1A and 2.1A port and as you can see in the image attached it says 2.6A. Thank you for your help.

A: Your power bank is likely 5V or maybe 12V. The device in question needs 15V. Your power banks likely can't source (15V * 2.6A =) 31 Watts of output (more like 38 Watts when you take regulator efficiency into account).
So no.


text:
Q: What is "Multinomial Deviance" in the glmnet package? I am fitting a multinomial logistic regression using the glmnet package in R:
library(glmnet)
data(MultinomialExample)
cvfit=cv.glmnet(x, y, family="multinomial", type.multinomial = "grouped")
plot(cvfit)

What is "Multinomial Deviance" and how does it relate to "Multinomial Logloss"?

A: Deviance is a specific transformation of a likelihood ratio.  In particular, we consider the model-based likelihood after some fitting has been done and compare this to the likelihood of what is called the saturated model.  This latter is a model that has as many parameters as data points and achieves a perfect fit, so by looking at the likelihood ratio we're measuring in some sense how far our fitted model is from a "perfect" model.
In the multinomial regression case we have data of the form $(x_1, y_1), (x_2, y_2), \ldots , (x_n, y_n)$ where $y_i$ is a $k$-vector which indicates which class observation $i$ belongs to (exactly one entry contains a one and the rest are zero).  Now if we fit some model that estimates a vector of probabilities $\hat{p}(x) = (\hat{p}_1(x), \hat{p}_2(x), \ldots, \hat{p}_k(x))$ then the model-based likelihood can be written
$$
\prod_{i=1}^{n} \prod_{i=j}^{k} \hat{p}_j(x_i)^{y_{ij}} .
$$
The saturated model on the other hand assigns probability one to each event that occurred, which means the vector of probabilities $\hat{p}_i$ is just equal to $y_i$ for each $i$ and we can write the ratio of these likelihoods as
$$
\prod_{i=1}^{n} \prod_{j=1}^{k} \left ( \frac{\hat{p}_j(x_i)}{y_{ij}} \right )^{y_{ij}} .
$$
To find the deviance we take minus two times the log of this quantity (this transformation has importance in mathematical statistics because of a connection with the $\chi^2$ distribution) to get
$$
-2 \sum_{i=1}^{n} \sum_{j=1}^{k} y_{ij} \log \left ( \frac{\hat{p}_j(x_i)}{y_{ij}} \right ) .
$$
(It's also worth pointing out that we treat zero times the log of anything as zero in this situation.  The reason for this is that it's consistent with the idea that the saturated likelihood should equal one.)
The only part of this that's peculiar to glmnet is the way in which the function $\hat{p}(x)$ is estimated.  It's doing a constrained maximization of the likelihood and computing the deviance as the upper bound on $\| \beta \|_1$ is varied, with the model that achieves the smallest deviance on test data being considered a "best" model.
Regarding the question about log loss, we can simplify the multinomial deviance above by keeping only the non-zero terms and write it as $-2 \sum_{i=1}^{n} \log [\hat{p}_{j_i} (x_i)]$, where $j_i$ is the index of the observed class for observation $i$, which is just the empirical log loss multiplied by a constant.  So minimizing the deviance is actually equivalent to minimizing the log loss.


text:
Q: Representation determined by traces A discrete, faithful representation of a surface group $G:\pi_1(S_g) \to PSL_2(\mathbb{R})$ is determined, up to conjugacy by $PGL_2(\mathbb R)$, among such representations by the squares of traces of the images of all the elements. I know this follows from the "9g-9" theorem for Teichmuller space: there is a set of $9g-9$ curves whose lengths determine the hyperbolic surface.  The proof I've seen of this is somewhat non-trivial, and involves careful analysis of how lengths change under twists.
My impression is that the first, weaker statement above is also a specific instance of some more general fact about representations into Lie groups -- what is the right statement, and how is it proved?
Thanks for your help!


text:
Q: Google's text-to speech engine voices? Most of you probably know the text-to-speech synthesizer of google translate, as you can access programmatically here btw:
http://translate.google.com/translate_tts?tl=en&q=text

My impression was it's sometimes using espeak, but in the major languages, the quality is much better than that. Anybody knows what Google is using, or what voices they are using? Clearly it's not the normal and also not the mbrola espeak voices.

A: I would look in the list of Google acquisitions (Wikipedia, list of google acquisitions):
84  December 3, 2010    Phonetic Arts   Speech synthesis     UK     Google Voice, Google Translate  [90]

A: I have made a simple wrap with ruby. https://github.com/c2h2/tts
gem install tts
require 'tts'
'hello world!".to_file "en"

A: Try this one:
Speech Util
It´s free, but only for English.

A: I would be surprised if Google translate is using espeak.  Firstly, the results are too good and lack many typical espeak flaws.    Second, Google is well known to be using ideas like deep nets in their speech group (see the work by Geof Hinton and also http://research.google.com/pubs/SpeechProcessing.html).

A: Try pyttsx: https://github.com/parente/pyttsx
$ pip install pyttsx
$ python
>>> import pyttsx
>>> e = pyttsx.init()
>>> e.say('haha hahaha haha haha hahaha')
>>> e.runAndWait()

A: Use the pyttsx3 module for python3.
just use pip install pyttsx3 for installing


text:
Q: Java: array of objects, two different approaches of initialization I'm currently experimenting with initializing an array of objects, and came across the following two approaches of filling the array of objects:
Approach 1
Cat[] catArray = new Cat[num]

for (int i = 0; i < num; i++) {
    Cat someCat = new Cat();
    catArray[i] = someCat;
}

Approach 2
Cat[] catArray = new Cat[num]

for (int i = 0; i < num; i++) {
    catArray[i] = new Cat();
}

Is there any tangible difference in the above two ways of initializing and filling an array of objects in terms of memory usage and/or performance?

A: Objects in Java are always allocated in the heap, whereas their addresses is in the stack.
Thus, using approach 1 or approach 2 does not really make a difference: in approach 1 you are just copying num times more an address. This should not give you any performance issue.
The compiler might even optimize your code and run approach 1and approach 2 equivalently.
From a programming point of view, approach 1 does not really make sense: someCat is never used and it is not accessible after the for loop. In the for loop you can access the new Cat by simply using catArray[i].


text:
Q: Maya - How to access grid colors through script commands? So I've been looking around for quite some time for this but I've come up empty handed so far.
I'm wondering if there's any way to access Maya's grid colors through script commands. cmds.grid doesn't have any flags for it and I can't find any other command with relevant flags.
I've been looking through some of the openMaya classes as well but so far there's no luck there either.

A: You can take a look at what Maya internally does in performGridOptions.mel. The commands according to this file are:
cmds.displayColor("gridAxis" , q=True)
cmds.displayColor("gridHighlight" , q=True)
cmds.displayColor("grid" , q=True)

This will give you the color index you can get the index with M3dVies's colorAtIndex So for example retrieving the "grid" color would end up doing:
import maya.cmds as cmds
import maya.OpenMayaUI as ui

index = cmds.displayColor("grid" , q=True)
color = ui.M3dView().colorAtIndex(index)
print color.r, color.g,  color.b

Correspondingly you can set the color to any index with displayColor.


text:
Q: Getting filepath of opened device Say i open up /dev/ttyUSB0. Now i want to use its file descriptor to get its filepath.
int myfd;

int main(int argc, char *argv[]){
char linkname[256];
ssize_t r;

myfd = open("/dev/ttyUSB0", O_RDWR);
if(myfd<0){

    perror("open error");
    exit(1);
}

r = readlink("/proc/self/fd/myfd", linkname, sizeof(linkname)-1);

if(r<0){
    perror("lstat");
    exit(EXIT_FAILURE);
}

printf("%s\n", linkname);

close(myfd);

    return 0;
}

What i should be getting is /dev/ttyUSB0.. Am i doing it the wrong way?

A: Surely the string myfd isn't in the /proc filesystem? I think the link is named numerically, so  you need the value of the variable myfd in the call to readlink().


text:
Q: Very, *very* strange characters on Mac OS X after copy-paste from PDF I did a copy-paste from a PDF, the text that should have been pasted is:

(\<(/?[^\>]+)\>)

But, instead, I get some VERY strange characters. Demonstrated in the following screenshot:

The screenshot was taken from TextEdit, zoomed in a lot.
Does anyone have any idea as to what they are?

A: They are characters from the private use part of Unicode.
hence the "space alien"


text:
Q: How to start activity through my app in another app? I am very new to writing android app, I am trying to start specific activity from an other app (App B)through my app (App A). I know how to launch the App B but  I need App B do some specific task with a click of button without showing the launching process  I just want to jump to that task(like playing music with out showing the introduction and starting part of App B).
This is part of App A , the place I want to do specific task  from App B instead of just launching it. ( even maybe I don't need to launch it )
public void playOn(View view) {

        ImageButton sound = (ImageButton) findViewById(R.id.musicButton);
        if (lightt) {
            sound.setImageResource(R.drawable.play_dn);
            lightt = false;
        } else {
            sound.setImageResource(R.drawable.play_up);
           lightt = true;
        }

       Intent intent = getPackageManager().getLaunchIntentForPackage("com.Zample.RUNiBplayMusic");

        if (intent.resolveActivity(getPackageManager()) != null) {
            startActivity(intent);
        }

and this is part of App B that I have access to
<application android:icon="@drawable/ic_launcher" android:label="Bplay Music" android:name="com.Zample.RUNiBplayMusic.Common.App" android:theme="@style/AppTheme">
        <activity android:launchMode="singleTask" android:name=".StartActivity" android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data android:host="com.bplaymusicwifi" android:scheme="bplaymu"/>
            </intent-filter>
        </activity>
        <activity android:finishOnTaskLaunch="true" android:name=".HelpListActivity" android:screenOrientation="portrait"/>
        <activity android:launchMode="singleTask" android:name=".DeviceListActivity" android:screenOrientation="portrait"/>
        <activity android:finishOnTaskLaunch="true" android:name=".PlayModeActivity" android:screenOrientation="portrait"/>
        <activity android:finishOnTaskLaunch="true" android:name=".HelpListActivity" android:screenOrientation="portrait"/>
        <receiver android:label="Bplay Music" android:name=".AppWidget.AppWidgetSmall">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
        <receiver android:label="Bplay Music" android:name=".AppWidget.AppWidgetBig">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
            </intent-filter>
            <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget_info_big"/>
        </receiver>
        <service android:name=".AppWidget.Bplay MusicService"/>
        <service android:name=".Record.RecordService"/>
    </application>

I think this part of the code from App B might help me. but I am not sure.
I hope you can help me how to solve this issue.


text:
Q: Reflectively save domain class instances in Grails The problem is as follows: I want to handle a POST request with JSON body. The body consists of an array of JSON Objects, without further nesting, i.e. simple HashMaps. All of these objects represent JSON-serialized domain classes from an Android Application, which will have their counterpart in my Grails app. I am thinking of parsing the JSON body, iterating through every element and saving each node as its corresponding domain class instance.
a) How should I save the instance? I am quite new to Grails/Groovy so please excuse any huge mistakes. Code so far is
public static Object JSONArray2Instances(String json, Class type) {

    def slurper = new JsonSlurper()
    def result = slurper.parseText(json)
    //we only want to parse JSON Arrays
    if (!(result instanceof JSONArray))
        return null
    result.each {
        def instance = it.asType(type)

        // now I need to save to domain class!

    }
}

b) where do I place the corresponding code? Currently it is in /grails-app/src/groovy. Where do the tests go? (Since it is not a 'real' Grails component)
c) Is an intermediate command object more appropriate?

A: Your code should go in to the controller which is handling the request. Please take a look at
gson-grails plugin which has examples of how to serialize and deserialze objects and map them to domain objects. Please take a look at the grails basics where they talk about the conventions used in the grails application and the layout. There are good examples at grails site. Hope this helps

A: I solved my problem as follows, based on help provided by the comment from allthenutsandbolts. : (Grails-Gson plugin was not needed)
Let N2696AdminAction be the name of a Domain Class
in my controller:
class N2696AdminActionController extends RestfulController{

    static responseFormats = ['json', 'xml']

    def JSONHandlerService

    N2696AdminActionController() {
        super(N2696AdminAction)
    }

    @Override
    @Transactional
    def save(){
        if (request!=null)
        JSONHandlerService.instancesfromJSON(request.JSON)
    }
}

then I delegate persisting to my service as follows

class JSONHandlerService {
def instancesfromJSON(Object request){

    //we only want to parse JSON Arrays
    if (!(request instanceof JSONArray))
    return null
    request.each {

        def domainClass = Class.forName("${it.type}",

true, Thread.currentThread().getContextClassLoader())
        def newDomainObject = domainClass.newInstance(it)
        newDomainObject.save(failOnError:true, flush:true, insert: true)

    }

}
  }

type is a Json attribute which holds the full (package inclusive) name for my class. This way, I can save to multiple Domain Classes with the same POST request.


text:
Q: Strategy to improve performance on key-value pairs table The situation
Our system has a MySQL database with a product table whose parameters can't be modified.
In order to add optional extra parameters, a developer designed a key-value pair table which looks a bit like this:
+----+--------------------+----------+------------+
| Id |        key         |  value   | product_id |
+----+--------------------+----------+------------+
|  1 | provider_id        | 3        |          2 |
|  2 | appliable_discount | 20%      |          2 |
|  3 | pay_mode           | pre-pay  |          2 |
|  4 | pay_mode           | post-pay |          3 |
|  5 | appliable_discount | 15%      |          3 |
|  6 | provider_id        | 4        |          4 |
|  7 | provider_id        | 3        |          5 |
|  8 | expires            | 1        |          2 |
|  9 | expires            | 0        |          4 |
| 10 | color              | red      |          2 |
| 11 | color              | blue     |          4 |
| 12 | foo                | 1        |          2 |
+----+--------------------+----------+------------+

*

*id: auto-incremental id.

*key: the name of the key (string).

*value: the value for that key (string).

*product_id: Implicit Foreign Key to the Product.

[key, product_id] pairs are unique. There can't be 2 different values for the same key for the same product.
Changes on the value columns are rare. Once set, they usually stay the same.
Problem
In one part of our application there is a query to extract all products and a subset of the extra parameters that look like this:
SELECT p.*, sp.value AS hours, cp.value AS appliable_discount, cp2.value AS pay_mode, cp3.value AS provider_id, cp4.value AS expires, cp5.value AS foo, cp6.value AS bar, cp7.value AS etc
FROM products AS p
  LEFT JOIN product_extra_parameters AS cp ON cp.product_id = p.id AND cp.key = 'appliable_discount'
  LEFT JOIN product_extra_parameters AS cp2 ON cp2.product_id = p.id AND cp2.key = 'pay_mode'
  LEFT JOIN product_extra_parameters AS cp3 ON cp3.product_id = p.id AND cp3.key = 'provider_id'
  LEFT JOIN product_extra_parameters AS cp4 ON cp4.product_id = p.id AND cp4.key = 'expires'
  LEFT JOIN product_extra_parameters AS cp5 ON cp5.product_id = p.id AND cp5.key = 'foo'
  LEFT JOIN product_extra_parameters AS cp6 ON cp6.product_id = p.id AND cp6.key = 'bar'
  LEFT JOIN product_extra_parameters AS cp6 ON cp7.product_id = p.id AND cp7.key = 'etc'
WHERE p.id > 1

As you may imagine, performance of this query is really low and we are trying to improve it. We suspect the abuse of left join is the main issue.
Note: To the effect of this question, ignore the fact that it's fetching all products.
What I am looking for
Short term: If it exists, a new strategy to query this table, to get the same information with better performance.
Long term: A better strategy to store this information in a relational database, or to cache that information for better performance.
Since 24 hours old information is acceptable, a solution on the lines of "a cron that updates a table with key: [product_id], name: [json with all extra_parameters]" would be acceptable.
An answer doesn't have to provide both a short term and a long term solution to be accepted.

EDIT: For the long term solution, I've found some valuable insight in this stackoverflow question:
https://stackoverflow.com/questions/2909448/best-pattern-for-storing-product-attributes-in-sql-server

A: How about just getting all parameters and do any filtering logic on the application side. It would cut joins to a single one in the given query, but you'll have to handle the name-value assignment in the application instead of the query (this is an upside actually, it's faster and easier).
The attribute table idea is pretty worn out (but that doesn't mean every generation won't reinvent it), but implementing logic based on those in the database queries is just a really really bad idea.

A: This is a relatively a common problem with relational db's. It gets annoying adding columns for each parameter/value.
One solution is to use a Pivot Query. Unfortunatley pivot isn't possible in MySQL. But you can use a case statement.
Another option is to hold the key value pairs in XML or JSON. Most db's can index and query these. reasonably efficiently. However other users may find this dificult to work with if they need to query/report using these values.

A:
As you may imagine, performance of this query is really low and we are trying to improve it. We suspect the abuse of left join is the main issue.

What indexing do you have on the "product_extra_parameters" table?
The proliferation of joins, left or otherwise, should not be a major issue unless this table is significant in size.

A: You could horizontally partition your product_extra_parameters table. i.e. product id 1 in one table, product id 2 in another (obviously some sort of rule is needed, not just arbitrary). This can be handled by either the DBMS or even triggers on the relevant core table.
A quick google search found the following regarding horizontal partitioning on MySQL: https://dev.mysql.com/doc/refman/8.0/en/partitioning-overview.html


text:
Q: accesing a https site using firefox addon I am using a self signed ssl certificate to set up a https site and using the request package to access the contents on this site. However the program seems to get stuck and it is not printing the contents of the site. Is there any way to overcome this issue.

A: Warning: This should only be used for debugging. Automatically adding an override for a wrong SSL certificate compromises the entire connection - if you do that then you can just skip using SSL in the first place. When you release this extension for other people you should use a valid certificate.

You probably want to add a certificate override manually. That's something you would use nsICertOverrideService.rememberValidityOverride() for (chrome authority required). The only problem is getting the certificate that you want to add an override for. But trying to contact the server and calling nsIRecentBadCertsService.getRecentBadCert() then should do. Something like this:
var Request = require("request").Request;
var host = "example.com";
var port = "443";
Request({
  url: "https://" + host + ":" + port + "/foo",
  onComplete: function(response)
  {
    var status = null;
    try
    {
      status = response.status;
    } catch(e) {}

    if (!status)
    {
      // There was a connection error, probably a bad certificate
      var {Cc, Ci} = require("chrome");

      var badCerts = Cc["@mozilla.org/security/recentbadcerts;1"]
                       .getService(Ci.nsIRecentBadCertsService);
      var status = badCerts.getRecentBadCert(host + ":" + port);
      if (status)
      {
        var overrideService = Cc["@mozilla.org/security/certoverride;1"]
                                .getService(Ci.nsICertOverrideService);
        overrideService.rememberValidityOverride(host, port, status.serverCert,
                                Ci.nsICertOverrideService.ERROR_UNTRUSTED, false);

        // Override added, now you should re-do the request
        ...
      }
    }
  }
});

Note: This code hasn't been tested, in particular I'm not sure whether detecting connection errors will really work by checking response.status (my guess is that it should throw if there was a connection error but the documentation doesn't say anything).


text:
Q: hive-site.xml path in hive0.13.1 I'm a newbie. I would like to know the hive-site.xml and hive-default.xml files locations in hive-0.13.1 version.
I have downloaded hive0.13.1-bin version from the below location.
http://apache.mirrors.pair.com/hive/hive-0.13.1/
Extracted and then configured hive environment variables.  I'm able to run the commands(create table, show, load data, query table..).
But in the conf(/hive/hive-0.13-1/conf) directory, I do not see hive-site.xml  and hive-default.xml files. Where these files are located in hive-0.13.1 version?

A: You can find hive-site.xml.template file in conf directory.
You should make it to hive-site.xml and add following configurations:
<?xml version="1.0"?>
<?xml-stylesheet type="text/xsl" href="configuration.xsl"?>
<!--
   Licensed to the Apache Software Foundation (ASF) under one or more
   contributor license agreements.  See the NOTICE file distributed with
   this work for additional information regarding copyright ownership.
   The ASF licenses this file to You under the Apache License, Version 2.0
   (the "License"); you may not use this file except in compliance with
   the License.  You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->

<configuration>

    <property>
        <name>javax.jdo.option.ConnectionURL</name>
        <value>jdbc:mysql://localhost/metastore?createDatabaseIfNotExist=true</value>
        <description>the URL of the MySQL database</description>
    </property>

    <property>
        <name>javax.jdo.option.ConnectionDriverName</name>
        <value>com.mysql.jdbc.Driver</value>
    </property>

    <property>
        <name>javax.jdo.option.ConnectionUserName</name>
        <value>root</value>
    </property>

    <property>
        <name>javax.jdo.option.ConnectionPassword</name>
        <value>root</value>
    </property>
<property>
  <name>hive.hwi.listen.host</name>
  <value>0.0.0.0</value>
</property>
<property>
  <name>hive.hwi.listen.port</name>
  <value>9999</value>
</property>
<property>
  <name>hive.hwi.war.file</name>
  <value>lib/hive-hwi-0.12.0.war</value>
</property>
<!--
<property>
  <name>hive.metastore.local</name>
  <value>true</value>
</property>
-->
</configuration>

And create metdata in mysql using commands if not exits in chosen DB (mysql).

A: follow the steps
1) Extract folder
2)go to /apache-hive-0.13.1-bin/conf and make a copy of hive-default.xml.template , it looks like hive-default.xml (copy).template.
3) Rename hive-default.xml (copy).template to hive-site.xml.
4) Make a copy of hive-env.sh.template to hive-env.sh.
add in hive-env.sh
export HADOOP_HEAPSIZE=1024
# Set HADOOP_HOME to point to a specific hadoop install directory
export HADOOP_HOME=/home/user17/BigData/hadoop

#hive
export HIVE_HOME=/home/user17/BigData/hive
# Hive Configuration Directory can be controlled by:
export HIVE_CONF_DIR=$HIVE_HOME/conf

5) export hadoop and hive path in .bashrc file
export HADOOP_HOME=/home/user17/BigData/hadoop
export PATH=$PATH:$HADOOP_HOME/bin

export HIVE_HOME=/home/user17/BigData/hive
export PATH=$PATH:$HIVE_HOME/bin

start your hadoop by
start-all.sh

enjoy with your hive.Give the hadoop and hive path in export command according to your system.let me know if not work.


text:
Q: Links inside iframe opens inside app in Ionic2 I'm using Ionic2.
All "a" tags inside my iframe component opens up inside the app without any navigation controller or anything. Here is the setup for my iframe component
This is the a link inside the iframe component:

How can i make this to open up in new browser?

A: Try changing the target option to system -
target="_system"

A: I've found one solution on Ionic forum. You can override the anchor tag's behaviour on iframe's onload property like this.


text:
Q: how to set textMode = Multiline for dynamic text box in c# TextBox txt = new TextBox();
txt.TextMode = "MulitiLine";

is not working
how to set textMode = Multiline for dynamic text box in c#

A: TextBox tx = new TextBox();
txt.TextMode = TextBoxMode.MultiLine;

A: Textbox txt = new Textbox();
txt.Multiline = true;

It also help you to get the solution.

A: txt.TextMode = TextBoxMode.MultiLine;

hi it will help you to get the solution

A: Use following
TextBox yourTextBox = new TextBox();
yourTextBox.TextMode = TextBoxMode.MultiLine;


text:
Q: Not able to see my website and dashboard too Today I tried to shift my local server website to the live server, and I had completed all the steps given in the internet including the changes done in siteurl and home of wp_options and made changes in wp-config file too. But still I am not able to see my site in interner and not even able to access the dashboard of wordpress. If I am trying to open my site i.e notesbank.in or trying to access the dashboard by notesbank.in/wp-admin , Then I can only see this page.
www.notesbank.in

A: it says"Error establishing a database connection" check wp-config file once


text:
Q: Convert U8_C4 to CV_32FC1 I'm getting a depth image 4 Channel Unsigned, and I would like to convert it to 32F_C1
so that I can use the addWeighed function.
I tried  the following code but I get access violation in addWeight function
           Mat depth_image_zed(new_width, new_height, MAT_TYPE::U8_C4);
           cv::Mat depth_image_ocv = slMat2cvMat(depth_image_zed);
           zed.retrieveMeasure(depth_image_zed, MEASURE::DEPTH, MEM::CPU, new_image_size);
           cv::Mat last_image(depth_image_ocv.rows, depth_image_ocv.cols, CV_32FC1);
           cv::Mat depth_clone = depth_image_ocv.clone();

           cv::Mat u16Image;
           depth_clone.convertTo(u16Image, CV_32FC1, 255.0); // no scaling factor, keep values "as is" !

            cv::Mat result;
            double factor = 0.19;
            cv::addWeighted(u16Image, 1.0 - factor, last_image, factor, 0.0, result);
            last_image = result.clone();

            cv::Mat ucharMatScaled;
            cv::Mat final_depth = result.clone();
            // scale values from 0..1 to 0..255
            final_depth.convertTo(ucharMatScaled, CV_8UC1, 255, 0);

            cv::imshow("original depth", depth_image_ocv);
            cv::imshow("filtered depth", final_depth);

            key = cv::waitKey(1);


text:
Q: make xrandr output on two monitors My notebook has an HDMI connection to external monitor. I want have xrandr to pass parameters so that the image is displayed on both internal and external monitors, and when the external monitor is disconnected, the image continues to be displayed on the internal.
Currently I turn it off it manually:
xrandr --output LVDS1 --off --output HDMI1 --auto

And turn on:
xrandr --output LVDS1 --auto --output HDMI1 --auto

So I want to put xrandr command with correct parameters in $HOME/.xinitrc, so that video would go out on both monitors.


text:
Q: Imageview scaling keeping height fix and width variable I want to make height of a imageview constant and based on aspect ratio width should vary. But I can see if I give width as wrap_content then height is less than fixed height because keeping aspect ratio, height corresponding to wrap_content width is less fixed height. I want width to adjust keeping height exact a fix value.

A: You can change the scaleType to MATRIX. And then you can manage the size by your self, it will not try to save aspect ratio

A: https://github.com/KyoSherlock/AspectRatioLayout
May be this is what you want. You can use AspectRatioImageView.
<com.sherlock.aspectratio.AspectRatioImageView
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_bright"
        android:contentDescription="@null"
        android:scaleType="centerCrop"
        android:src="@drawable/ic_launcher"
        app:widthHeightRatio="2" >


text:
Q: Converting and printing the module names of a process I am trying to print and save the module names of a process.
But when printing the char array I get something that looks like an address.
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>

int main() {

    MODULEENTRY32 me32;
    HWND hwnd = FindWindow(0, L"Window Name");
    DWORD dwPID;
    GetWindowThreadProcessId(hwnd, &dwPID);

    HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID);

    me32.dwSize = sizeof(MODULEENTRY32);
    Module32First(hModuleSnap, &me32);
    std::cout << me32.szModule << std::endl;

    do
    {
        std::cout << me32.szModule << std::endl; // important line

    } while (Module32Next(hModuleSnap, &me32));

    return 0;
}

The output of this in my case was 00AFF53C for every module.
me32.szModule holds the name of the module as a char array.
Microsoft used the following in their example to convert and print the module name:
_tprintf( TEXT("\n\n     MODULE NAME:     %s"), me32.szModule );
But I think you can only use this to print the string.
So how do I convert and save the string in me32?

A: Your project is being compiled with UNICODE defined (as evident by you being able to pass a wide string to FindWindow()).  That causes Module32(First|Next) to map to Module32(First|Next)W, and MODULEENTRY32 to map to MODULEENTRY32W (and FindWindow() to map to FindWindowW()).  Thus, the szModule field is a wchar_t[] array instead of a char[] array, like you are expecting.  std::cout does not have an overload of operator<< for wchar_t data, only char data, but it has an overload for void*, and a fixed array decays into a pointer that can then be assigned to void*.  That is why your code is printing out the string data as a memory address - you are printing out the address of the szModule field rather than its content.
You need to either:

*

*use std::wcout instead, and preferably also explicitly use the W version of the API functions to match:
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <string>

int main() {

    MODULEENTRY32W me32;
    HWND hwnd = FindWindowW(0, L"Window Name");
    DWORD dwPID;
    GetWindowThreadProcessId(hwnd, &dwPID);

    HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID);

    me32.dwSize = sizeof(me32);
    if (Module32FirstW(hModuleSnap, &me32))
    {
        do
        {
            std::wstring moduleName = me32.szModule;
            std::wcout << moduleName << std::endl; // important line
        }
        while (Module32NextW(hModuleSnap, &me32));
    }

    return 0;
}

*explicitly use the A version of the API functions to match your use of std::cout:
#include <windows.h>
#include <TlHelp32.h>
#include <iostream>
#include <string>

int main() {

    MODULEENTRY32A me32;
    HWND hwnd = FindWindow(0, L"Window Name");
    DWORD dwPID;
    GetWindowThreadProcessId(hwnd, &dwPID);

    HANDLE hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, dwPID);

    me32.dwSize = sizeof(MODULEENTRY32A);
    if (Module32FirstA(hModuleSnap, &me32))
    {
        do
        {
            std::string moduleName = me32.szModule;
            std::cout << moduleName << std::endl; // important line
        }
        while (Module32NextA(hModuleSnap, &me32));
    }

    return 0;
}

A: _tprintf() is a typedef for wprintf() if _UNICODE is defined, according to Microsoft's documentation.
Take a look at std::wcout.


text:
Q: Connection error for MongoDb replica-set using docker-compose I'm trying to connect to mongodb replica set running under 4 containers: 3 mongo as a cluster, and 1 to issue mongo commands to others.
Here I don't know how should I connect it to my application with a mongodb url.
docker-compose.yml is
mongo3:
  image: mongo:latest
  hostname: mongo3
  expose:
    - "27017"
    - "28017"
  restart: always

      entrypoint: [ "/usr/bin/mongod", "--replSet", "rs"]

mongo2:
  image: mongo:latest
  hostname: mongo2
  expose:
    - "27017"
    - "28017"
  restart: always
  entrypoint: [ "/usr/bin/mongod", "--replSet", "rs"]

mongo1:
  image: mongo:latest
  hostname: mongo1
  expose:
    - "27017"
    - "28017"
  links:
    - mongo2:mongo2
    - mongo3:mongo3
  restart: always
  entrypoint: [ "/usr/bin/mongod", "--replSet", "rs"]

mongosetup:
  image: mongo:latest
  links:
    - mongo1:mongo1
    - mongo2:mongo2
    - mongo3:mongo3
  volumes:
    - ./scripts:/scripts
    - ./data/runtime/db:/data/db
    - ./data/dump:/dump

  restart: always
  entrypoint: [ "bash", "/scripts/mongo_setup.sh" ]

app:
  image: papagari/swoop.chat:latest
  environment:
    - MONGO_URL=mongodb://mongo1:27017,mongo2:27017,mongo3:27017/swoop?replicaSet=rs
    - ROOT_URL=https://localhost:3000
  links:
    - mongo1:mongo1
    - mongo2:mongo2
    - mongo3:mongo3
  ports:
    - 3000:3000

and /scripts/mongo_setup.sh is
MONGODB1=`ping -c 1 mongo1 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`
MONGODB2=`ping -c 1 mongo2 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`
MONGODB3=`ping -c 1 mongo3 | head -1  | cut -d "(" -f 2 | cut -d ")" -f 1`

echo "Waiting for startup.."
until curl http://${MONGODB1}:28017/serverStatus\?text\=1 2>&1 | grep uptime | head -1; do
  printf '.'
  sleep 1
done

echo curl http://${MONGODB1}:28017/serverStatus\?text\=1 2>&1 | grep uptime | head -1
echo "Started.."

sleep 10

echo SETUP.sh time now: `date +"%T" `
mongo --host ${MONGODB1}:27017 <<EOF
   var cfg = {
        "_id": "rs",
        "version": 1,
        "members": [
            {
                "_id": 0,
                "host": "${MONGODB1}:27017",
                "priority": 2
            },
            {
                "_id": 1,
                "host": "${MONGODB2}:27017",
                "priority": 0
            },
            {
                "_id": 2,
                "host": "${MONGODB3}:27017",
                "priority": 0
            }
        ]
    };
    rs.initiate(cfg, { force: true });
    rs.reconfig(cfg, { force: true });
    db.getMongo().setReadPref('nearest');
EOF

Now I'm getting an error for mongodb://mongo1:27017,mongo2:27017,mongo3:27017/swoop?replicaSet=rs
Obviously failed to connect to server because the url I've used is not valid. I'm new to docker and mongo db replica set for the first time, trying to understand docker here. How it should work.
Error: MongoError: no primary found in replicaset.
Complete Error:
app_1        |
app_1        | /app/bundle/programs/server/node_modules/fibers/future.js:313
app_1        |                      throw(ex);
app_1        |                      ^
app_1        | MongoError: no primary found in replicaset
app_1        |     at Object.Future.wait (/app/bundle/programs/server/node_modules/fibers/future.js:449:15)
app_1        |     at new MongoConnection (packages/mongo/mongo_driver.js:216:27)
app_1        |     at new MongoInternals.RemoteCollectionDriver (packages/mongo/remote_collection_driver.js:4:16)
app_1        |     at Object.<anonymous> (packages/mongo/remote_collection_driver.js:38:10)
app_1        |     at Object.defaultRemoteCollectionDriver (packages/underscore/underscore.js:750:1)
app_1        |     at new Mongo.Collection (packages/mongo/collection.js:103:40)
app_1        |     at AccountsServer.AccountsCommon (packages/accounts-base/accounts_common.js:23:18)
app_1        |     at new AccountsServer (packages/accounts-base/accounts_server.js:18:5)
app_1        |     at meteorInstall.node_modules.meteor.accounts-base.server_main.js (packages/accounts-base/server_main.js:9:12)
app_1        |     at fileEvaluate (packages/modules-runtime/.npm/package/node_modules/install/install.js:153:1)
app_1        |     - - - - -
app_1        |     at /app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/topologies/replset.js:631:32
app_1        |     at [object Object].<anonymous> (/app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/topologies/replset.js:421:24)
app_1        |     at [object Object].g (events.js:260:16)
app_1        |     at emitOne (events.js:77:13)
app_1        |     at [object Object].emit (events.js:169:7)
app_1        |     at /app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/topologies/server.js:283:14
app_1        |     at /app/bundle/programs/server/npm/node_modules/meteor/npm-mongo/node_modules/mongodb-core/lib/connection/pool.js:436:18
app_1        |     at nextTickCallbackWith0Args (node.js:420:9)
app_1        |     at process._tickCallback (node.js:349:13)

I've searched many placed all I got is with local machine or the server machine not with docker links.
Update
response of rs.status() in mongo1 container, which look pretty fine, primary and secondary are initialized properly.
{
    "set" : "rs",
    "date" : ISODate("2016-10-19T06:31:10.861Z"),
    "myState" : 1,
    "term" : NumberLong(1),
    "heartbeatIntervalMillis" : NumberLong(2000),
    "members" : [
        {
            "_id" : 0,
            "name" : "172.17.0.4:27017",
            "health" : 1,
            "state" : 1,
            "stateStr" : "PRIMARY",
            "uptime" : 62,
            "optime" : {
                "ts" : Timestamp(1476858630, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2016-10-19T06:30:30Z"),
            "infoMessage" : "could not find member to sync from",
            "electionTime" : Timestamp(1476858629, 1),
            "electionDate" : ISODate("2016-10-19T06:30:29Z"),
            "configVersion" : 13918,
            "self" : true
        },
        {
            "_id" : 1,
            "name" : "172.17.0.3:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 51,
            "optime" : {
                "ts" : Timestamp(1476858630, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2016-10-19T06:30:30Z"),
            "lastHeartbeat" : ISODate("2016-10-19T06:31:09.633Z"),
            "lastHeartbeatRecv" : ISODate("2016-10-19T06:31:10.291Z"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "172.17.0.2:27017",
            "configVersion" : 13918
        },
        {
            "_id" : 2,
            "name" : "172.17.0.2:27017",
            "health" : 1,
            "state" : 2,
            "stateStr" : "SECONDARY",
            "uptime" : 51,
            "optime" : {
                "ts" : Timestamp(1476858630, 1),
                "t" : NumberLong(1)
            },
            "optimeDate" : ISODate("2016-10-19T06:30:30Z"),
            "lastHeartbeat" : ISODate("2016-10-19T06:31:09.633Z"),
            "lastHeartbeatRecv" : ISODate("2016-10-19T06:31:09.283Z"),
            "pingMs" : NumberLong(0),
            "syncingTo" : "172.17.0.4:27017",
            "configVersion" : 13918
        }
    ],
    "ok" : 1
}

Any tips will be helpful. TIA

A: As you said on the comments, as you replicaSet configuration is alright, probably your app is starting along with the others and before the replicaSet is configured, it breaks.
You could try using depends_on on the app configuration, that will make the app container start after the others. But be aware that this might not work because it waits until the container is ready and not until the replicaSet is configured
If this doesn't work I think the easiest way is to start app separately after running docker-compose.


text:
Q: replaceAll with regex in java I want to use replaceAll() for the following replacements:
#one# -> <element name="one">
#two# -> <element name="two">

and so on...
What regular expression do I need?
Here is a naive try:
replaceAll("#[\w]#", "<element name=\"[?1]\"");
// my hope is that I can remember a value somehow (`[\w]`) and use it for the substitution ([?1])
// which is, written like this, a nonsense

A: You need to use:
str = str.replaceAll("#(\\w+)#", "<element name=\"$1\">");

*

*You need \\w+ OR [^#]+ to match more than 1 character

*You need to put them in parentheses to make it a capturing group

*You can use back-reference to this matched group by using $1 n replacement string


text:
Q: how we sort search result according the keyword occurrence in php and mysql below is my query :
This query is work fine but now i wish this query result is sort by keyword occurrence.
Example:
In my database :
srno| name          | business                         |city
  - | ------------- | -------------------------------  |-------
  1 | janefer group | advertisement company import     |manchester
  2 | abc           | golf import export               |new york
  3 | xyz           | golf import                      |new york

and if i pass keyword in search box
$search ="golf import export xyz";
then i want result like where all keyword match this post come first and so on
Query
$qry="SELECT *, MATCH (name,business,city) AGAINST ('$serach*' IN BOOLEAN MODE) AS Relevance FROM tbl_services WHERE MATCH (name,business,city) AGAINST ('$serach*' IN BOOLEAN MODE)  ORDER BY Relevance DESC LIMIT 1 , 12"

A: you mispelled the word $search  in query try this
$qry="SELECT *, MATCH (name,business,city) AGAINST ('$search*' IN BOOLEAN MODE) AS Relevance FROM tbl_services WHERE MATCH (name,business,city) AGAINST ('$search*' IN BOOLEAN MODE)  ORDER BY Relevance DESC LIMIT 1 , 12"

A: I wish out like below where many keyword match the post show first and so on
$seach "golf import export xyz";
become first post because have many matching keyword:
name : abc
business: golf import export
city: new york
second post:
name :xyz
business: golf import
city :new york


text:
Q: RichTextBox text is disappearing in VisualBrush after detaching from control on screen I have a thumbnail preview which is done through VisualBrush. Preview is of an ItemsControl which contains along other elements RichTextBox.
var preview = new VisualBrush(itemsControl, ViewboxUnits = BrushMappingMode.Absolute,
                    Viewbox = Rect(controlSize),
                    Stretch = Stretch.Uniform);

When ItemsControl is a part of the Application visual tree everything the preview and the controls themselves display just fine, but when I remove ItemsControl from the Application visual tree (e.g. canvas.Remove(itemsControl)) RichTextBox controls become invisible in the preview (VisualBrush) while all other controls are displaying as usual.
public void SetActiveControl(ItemsControl newItemsControl) {
    canvas.Children.Remove(currentItemsControl);
    canvas.Children.Add(newItemsControl);
    currentItemsControl = newItemsControl;
}

I compared properties of RichTextBox before and after its beeing detached from Application visual tree. The difference is in the properties IsLoaded (before TRUE, after FALSE) and IsVisible (before TRUE, after FALSE). But other elements (e.g. Path) have the same differences and still display in preview correctly.
I can't grasp how doing canvas.Remove(itemsControl) hides RichTextBox but keeps other controls! Any ideas would be greatly appreciated!

A: Visual brush cannot be frozen. So you can create ImageBrush from VisualBrush before detaching your control from visual tree. Here is an example how to do that: "Freeze" that VisualBrush.


text:
Q: Import test-users into Meteor app with use of npm script? We can easily create a user from meteor shell like this
Accounts.createUser({username: 'john', password: '12345'})

Similarly, I just want to add multiple users via npm script. Any ideas?
In other words, I want to use fixtures functionality via npm command and not on the initial run.
Thank you.

A: For normal collections (i.e. different than Meteor.users), you can directly tap into your MongoDB collection. Open a Meteor Mongo shell while your project is running in development mode, then directly type Mongo shell commands.
For Meteor.users collection, you want to leverage the accounts-base and accounts-password packages automatic management, so instead of directly fiddling the MongoDB, you want to insert documents / users through your Meteor app.
Unfortunately, your app source files (like your UsersFixtures.js file) are absolutely not suitable for CLI usage.
The usual solution is to embed a dedicated method within your app server:
// On your server.
// Make sure this Method is not available on production.
// When started with `meteor run`, NODE_ENV will be `development` unless set otherwise previously in your environment variables.
if (process.env.NODE_ENV !== 'production') {
  Meteor.methods({
    addTestUser(username, password) {
      Accounts.createUser({
        username,
        password // If you do not want to transmit the clear password even in dev environment, you can call the method with 2nd arg: {algorithm: "sha-256", digest: sha256function(password)}
      })
    }
  });
}

Then start your Meteor project in development mode (meteor run), access your app in your browser, open your browser console, and directly call the method from there:
Meteor.call('addTestUser', myUsername, myPassword)

You could also use Accounts.createUser directly in your browser console, but it will automatically log you in as the new user.


text:
Q: Reading xml Structure in sql server 2012 Sample Xml Structure
<?xml version="1.0" encoding="UTF-8"?>
<XmlSerializableHashtable xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Entries>
      <Entry>
         <key xsi:type="xsd:string">col1</key>
         <value xsi:type="xsd:string">500</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col2</key>
         <value xsi:type="xsd:string">0/60,1/1000</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col3</key>
         <value xsi:type="xsd:string">localhost</value>
      </Entry>
   </Entries>
</XmlSerializableHashtable>

No i am trying to get value where key is col3
I am trying with the Xquery
Declare @x xml;
Set @x = (Select valuefrom sometable)

Select @x.query('/Entries/Entry/')

A: This Query will be helpful.
DECLARE @xmlData AS XML
DECLARE @sRawData AS VARCHAR(2000)

SET @sRawData = '<?xml version="1.0" encoding="UTF-8"?>
<XmlSerializableHashtable xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
   <Entries>
      <Entry>
         <key xsi:type="xsd:string">col1</key>
         <value xsi:type="xsd:string">500</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col2</key>
         <value xsi:type="xsd:string">0/60,1/1000</value>
      </Entry>
      <Entry>
         <key xsi:type="xsd:string">col3</key>
         <value xsi:type="xsd:string">localhost</value>
      </Entry>
   </Entries>
</XmlSerializableHashtable>'

SET @xmlData = CAST(@sRawData AS XML)

SELECT MainDataCenter.Col.value('(key)[1]','varchar(max)') AS [key]
      ,MainDataCenter.Col.value('(value)[1]','varchar(max)') AS Value
FROM @xmlData.nodes('/XmlSerializableHashtable/Entries/Entry') AS MainDataCenter(Col)
WHERE MainDataCenter.Col.value('(key)[1]','varchar(max)') = 'col3'


text:
Q: SWIG2 with NUMPY I am trying to build a SWIG2.0 interface for my C++ class. Only requirement is that I need to be able to pass a numpy array from python into the C++ class.
I have a simple C++ Class as :
//
// File : matmanip.h
//
#ifndef __MAT_MANIP_H
#define __MAT_MANIP_H

#include <iostream>

class MatManip
{
public:
  MatManip();

  // Matrix of length d
  void set_matrix( float * M, int d );

};

#endif

The .cpp file :
#include <iostream>
#include "matmanip.h"

// File : matmanip.cpp
MatManip::MatManip() { std::cout << "Constructor\n"; }

void MatManip::set_matrix( float * M, int d )
{
  for( int i=0 ; i<d ; i++ )
    std::cout << "M[" << i << "] = " << M[i] << std::endl;
}

My swig interface file (matmanip.i). I obtained numpy.i file from https://github.com/numpy/numpy/blob/master/tools/swig/numpy.i :
%module matmanip

%{
#define SWIG_FILE_WITH_INIT
#include "matmanip.h"
%}

%include "numpy.i"

%init %{
import_array();
%}

%apply( float * IN_ARRAY1, int DIM1) {(double * seq, int n) };
%include "matmanip.h"

Here is what I do to compile:
    $ swig -c++ -python matmanip.i
    $ g++ -fPIC -c matmanip.cpp
    $ g++ -fPIC -c matmanip_wrap.cxx -I /usr/include/python2.7
    $ g++ -shared matmanip.o matmanip_wrap.o  -o _matmanip.so
    $ ls
matmanip.cpp  matmanip.o    _matmanip.so       numpy.i
matmanip.h    matmanip.py   matmanip_wrap.cxx
matmanip.i    matmanip.pyc  matmanip_wrap.o

Until this point everything work! I can even see the _matmanip.so.
However, as I try to import matmanip in python here is the error
$ python
>>> import numpy as np
>>> from matmanip import MatManip
>>> m = MatManip()
Constructor
>>> m.set_matrix( np.array( [2.0, 3.4, 5.8] ) )
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "matmanip.py", line 82, in set_matrix
    def set_matrix(self, *args): return _matmanip.MatManip_set_matrix(self, *args)
TypeError: MatManip_set_matrix() takes exactly 3 arguments (2 given)
>>>

I am really puzzled! My swig version is 2.0.12. Numpy is 1.12.1. Python version is 2.7.12. g++ version is 5.4.0. I am on Ubuntu 16.04.


text:
Q: Как сделать чтобы выбранные из списка значения накапливались в поле формы? Используется
Access 2016
Сценарий:
- вводим первые символы значения из списка;
- список "подкидывает" в строку ввода наиболее подходящее значение из списка;
- наживаем "Ввод";
- Выбранное значение попадает в поле формы "Поле1" через запятую;
и т.д. для остальных значений.
Файл - ссылка
Вопрос.
Как сделать чтобы выбранные в списке значения накапливались в поле формы через запятую?
Значение предполагается использовать: текстовые, числовые, текстовые+числовые.
Рисунок


text:
Q: How do I set the PYTHONUTF8 environment variable to enable UTF-8 encoding by default in Python? Python 3.7 introduced the PYTHONUTF8 environment variable to enable UTF-8 encoding by default. How do I set this variable from within a Python program? (I can't find it in my operating system's list of environment variables.)

A: Usually you would specify this with a command line argument
python3.7 -X utf8

If you want to enable UTF-8 mode from environment variable:
export PYTHONUTF8=1  # linux / macOS
set PYTHONUTF8=1  # windows

It should be set before entering the Python runtime.

A: To access environment variables, and modify them if your platform allows it (which Windows and all popular Unixes do), just use os.environ.
However, this isn't going to do any good, unless you're trying to set the environment variable for Python child processes that you're launching with subprocess or the like. Python reads its environment variables at startup, uses them to pick up configuration information, and doesn't check them again later.

The point of these environment variables (and command-line flags) is to set them in your shell, launcher script, etc., so they're available when Python starts, not to set them from within Python.
Normally, if you need this setting, you're going to need it globally, so you'll want to set it in your shell profile script (for Linux), your OS's GUI for environment variables (for Windows), or both (for macOS—although on Mac, everything is already guaranteed to be set to UTF-8, and I believe even if you manage to break that somehow, Python will ignore it).
You're not going to find this in your existing list of environment variables (unless maybe you're on an unusual Linux distro that does something odd with the locale settings but needs its default Python to ignore them), but that doesn't matter; you can add any environment variables you want.

But if you want to change things on the fly, while you can't do that by setting an environment variable, you don't need to, either.
As the docs explain, what it controls is setting the filesystem encoding, preferred encoding, and stdio files encoding.
The first two, you can just call the same functions in sys and locale to set them at any time.
If you also want to change the stdio files, that's a bit trickier. I believe the proposal to make it easier to change the encoding for these files on the fly was rejected or deferred, so the only thing you can do is replace them with new file objects wrapped around the same file descriptor, which looks something like this (untested for now):
sys.stdout = open(sys.stdout.fileno(), 'w', encoding='utf-8', errors='surrogateescape')
sys.stderr = open(sys.stderr.fileno(), 'w', encoding='utf-8', errors='backslashescape')
sys.stdin = open(sys.stdin.fileno(), 'r', encoding='utf-8', errors='surrogateescape')

If you've already printed anything to stdout or typed/piped anything into stdin, you may need to flush everything first.
The only remaining issue that I know of is that sys.argv and os.environ will (at least on Unix) have already been decoded with the wrong encoding. You can fix the args by reencoding and redecoding before setting the default encodings. I think this uses the locale settings, so it would look like:
sys.argv = [arg.encode(locale.getpreferredencoding(), errors='surrogateescape').decode('utf8', errors='surrogateescape') for arg in sys.argv]

Fixing the environment is a bit trickier, because if you try to mutate os.environ it's going to do a putenv call that you don't want. If this is an issue, the best option is probably to make a transcoded copy of environ and use that for lookups, and explicitly pass it to subprocess, etc.

A: You can technically set it using os.environ["PYTHONUTF8"] = "on" (the value doesn't matter), but this won't affect the running script. By the time you do it in a Python script, Python has already started and checked for this variable, didn't find it, and therefore isn't using UTF-8 encoding by default. It would affect any Python interpreter you launched from your script, though.
The point of the environment variable is to set it before you launch your Python script. You do this in the same way you would set any other environment variable. You don't mention what OS you're using, but on Linux, you generally add the appropriate command to ~/.bash_profile. On Windows, you set them using a button on the Advanced page of the System Properties dialog.
Obviously you won't find this environment variable in your system's list of environment variables if you haven't set it yet.

A: Yeah I tried various combinations on windows.  It's very fussy - if you have a quote or anything in your environment variable it will error out.
From reading the source it's very particular.
on windows it must be
set PYTHONUTF8=1
Make sure no quotes or anything.
if (opt) {
    if (strcmp(opt, "1") == 0) {
        config->utf8_mode = 1;
    }
    else if (strcmp(opt, "0") == 0) {
        config->utf8_mode = 0;
    }
    else {
        return _PyStatus_ERR("invalid PYTHONUTF8 environment "
                            "variable value");
    }
    return _PyStatus_OK();
}


text:
Q: tcl - detect if x11 is running on ARM or x86 I have a tcl script that currently detects its platform by looking at tk windowingsystem and then loads different libraries depending on if the result is x11, win32, aqua, etc...
However, this is causing issues on linux - as the libraries for raspberry pi and standard linux are different.
What I'm looking for is a way to differentiate between x11 running on ARM, and x11 running on x86.
Any suggestions?

A: The standard Tcl package platform sounds ideal:
% package require platform
1.0.13
% platform::identify
macosx10.8-x86_64


text:
Q: Taylor's formula and its quadratic term I struggle with the following problem:
For a function
$$f: \mathbb{C} \rightarrow \mathbb{R}~,$$
$f$ attains its maximum for $z_0= e^{i\pi/3}$, $f(z_0)=F_{max}.$
Assume we may use Taylor's theorem (identifying $\mathbb{C} =\mathbb{R}^2$) and write
$$ f(z)= F_{max} + \underbrace{f^\prime(z_0)(z-z_0)}_{=0} + \frac{1}{2}f^{\prime \prime}(z_0)(z-z_0,z-z_0) + O(|z-z_0|^3).$$
Now I hope to get an error term of the form
$$ F_{max} - f(z) = c(|z-z_0|^2) + O(|z-z_0|^3)~,~ c=const.~~~~~~~~~(1)$$
That would be true if the quadratic form $f^{\prime \prime}(z_0)$ would be just a multiple of the identity, which would in turn imply that $f$ takes the same values on small circles around $z_0$ (right?).
What I know is that $f(z)=f(\tilde{z})$ whenever the triangles $(0,1,z)$ and $(0,1,\tilde{z})$ are similar, for example $f(i)=f(1/2+i1/2)= f(1+i).$
But those values don't happen to lie on a circle around $z_0$, I think.
Can I use this information show that $f^{\prime \prime}(z_0)$ is just a multiple of the identity?
Or is there maybe another way to obtain equation $(1)$?
Thank you for helping.


text:
Q: For template classes, do non generic member functions get duplicated? Or only the ones that actually use generic parts?
Like in this example:
template<class T>
class foo
{
public:
    void addStuff(int x,T y)
    {

        ints_.push_back(x);
        generics_.push_back(y);
    }
    void clear()
    {
        ints_.clear();
        generics_.clear();
    }
    void setName(std::string name)
    {

        name_ = name;
    }

    std::string name_;

    std::vector<int> ints_;
    std::vector<T> generics_;
};

The non generic functions are inline, since putting them in a .cpp file would require specialization.
Doe they get duplicated as well?
Just curious...

A: Each class which is created via a template parameter is its own class.  That is, if you had foo<int>, foo<double> and foo<char> then there would exist 3 different addStuff, clear and setName functions.  That's because there would be 3 different classes.  Templates are compile time entities.  They are introduced during compilation and there is no attempt at "reducing" code size like this.

A: Technically, yes, since they are distinct functions belonging to distinct classes.  In practice, maybe, since compilers/linkers are pretty smart and have figured out that such repeated code can be condensed in many situations.  And there is always the possibility that they are not inlined completely such that no actual function needs to be stored at all.
There is a definite cost in executable size for using template trickery, but it is not as much now as it was in years past.


text:
Q: How to insert NULL into a datetime in python with pymysql I'm trying to insert some datetime  in My-SQL database in an SQL da on python with pymysql but sometimes those dates that , I retrieve are Nonetype, I want to insert a date to null when this happen, What should i do ?
I tried what i seen on stackoverflow, nothing worked,"", 0, "NULL", ternary conditions inserting None ...
datetime.datetime.fromtimestamp(item[3]) if type(item[3][3]) is not None else None
Every time the same Error

"""INSERT INTO database (atr1, atr2, atr3,
            atr4, atr5, atr6, atr7, atr8, atr9)
            VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')""" % (item[0], item[1],\
            item[2], datetime.datetime.fromtimestamp(item[3]),\
            datetime.datetime.fromtimestamp(item[4]), item[5],\
            item[6], item[9],time.strftime('%Y-%m-%d %H:%M:%S')))

    item[2],datetime.datetime.fromtimestamp(item[3]),\
TypeError: an integer is required (got type NoneType)

Thanks for your help!


text:
Q: Exclude rows which have NA value for a column This is a sample of my data

I have written this code which removes all categorical columns (eg. MsZoning). However, some non-categorical columns have NA value. How can I exclude them from my data set.
def main():
    print('Starting program execution')
    iowa_train_prices_file_path='C:\\...\\programs\\python\\kaggle_competition_iowa_house_prices_train.csv'
    iowa_file_data = pd.read_csv(iowa_train_prices_file_path)
    print('Read file')

    model_random_forest = RandomForestRegressor(random_state=1)
    features = ['MSSubClass','MSZoning',...]
    y = iowa_file_data.SalePrice
    # every colmn except SalePrice
    X = iowa_file_data.drop('SalePrice', axis = 1)
    #The object dtype indicates a column has text (hint that the column is categorical)
    X_dropped = X.select_dtypes(exclude=['object'])
    print("fitting model")
    model_random_forest.fit(X_dropped, y)

    print("MAE of dropped categorical approach");

pd.set_option('display.max_rows', 500)
pd.set_option('display.max_columns', 500)
pd.set_option('display.width', 1000)
main()

When I run the program, I get error ValueError: Input contains NaN, infinity or a value too large for dtype('float32') which I believe is due to NA value of Id=8.
Question 1 - How do I remove such rows entirely
Question 2 - What is the type of such columns which are mostly nos. but have text in between? I thought I'll do print("X types",type(X.columns)) but that doesn't give the result

A: To remove nans, you can replace them with another value. It is common practice to use zeros.
iowa_file_data = iowa_file_data.fillna(0)

If you still want to remove the whole column, use
iowa_file_data = iowa_file_data.dropna(axis='columns')

And if you want to remove the entire row, use
iowa_file_data = iowa_file_data.dropna()

For your second question, from what I understand, you might want to see some info about the pandas object dtype: link.


text:
Q: Error when I try to window an audio file with FFT in matlab I'm trying to use the FFT algorithm to plot a graph of a simple audio voice file with magnitude against frequency, It works BUT I'm trying to window the signal for the purpose of removing the frequency leakage on the side lobes of the main frequencies. It is just giving me an error
here is the code without the windowing (which works):
[x,fs]=audioread('E:\voice_hum.wav');

x1=x;

plot_points = 100000;
h=fft(x1,plot_points);
freq = h(1:50001);    %dump data after half FS
mag = abs(freq);
freq = 0.5 * fs *(0:50000)/50000;    %frequency on x-axis
plot(freq,mag)

here is the code when I tried implementing a hamming window:
[x,fs]=audioread('E:\voice_hum.wav');

x1 = x(1:100);

w = hamming(100);
plot_points = 100000;

x1 = x1.*w';  %window the signal
h=fft(x1,plot_points);
freq = h(1:50001);  %dump data after half FS

mag = abs(freq);
freq = 0.5 * fs *(0:50000)/50000;

plot(freq,mag)

it is giving me this error:

Error using  .*  Matrix dimensions must agree.
Error in lab8b (line 12) x1 = x1.*w';  %window the signal

I'm a little confused about it, does someone know what I should do?

A: You are using dot-multiplication between w (a column vector) and x1 (a column vector, if you have only one audio channel).
In order to multiply two vectors with dot-multiplication (i.e. a.*b) they should have the same dimension, while you are using a.*b', which is dot-multiplying a column and a row.
So you can either use x1'*w (matrix multiplication) or x1.*w with the very same result.

A: Use x1 = x1.*w; instead. Always remember to check your array dimension before the operation.


text:
Q: NSDateFormatter and default locale cause bug Looks like locale setter has some magic, which forces the dateFormatter works properly
+(NSDate*)dateTimeFromJSONDateString:(NSString*)dateString{ //dateString i.e. 2013-11-19T12:47:38+04:00
    static NSDateFormatter *kDateFormatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        kDateFormatter = [[NSDateFormatter alloc] init];
//      kDateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ru_RU"];
        [kDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
    });
    NSLog(@"%@",  kDateFormatter.locale.localeIdentifier); // this one prints 'ru_RU' always either I set kDateFormatter.locale explicitly or not

    return [kDateFormatter dateFromString:dateString];
}

so this method returns nil when 6th line is commented, otherwise it returns correct date.
Am I doing something wrong, or we have sdk bug here?

A: The problem solved by setting the formatter's locale to en_US_POSIX. It is necessary while parsing fixed-format date strings because the format of the date strings is constant unlike device' locale.
The code should be like
+(NSDate*)dateTimeFromJSONDateString:(NSString*)dateString{
    static NSDateFormatter *_dateFormatter;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _dateFormatter = [[NSDateFormatter alloc] init];
        _dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
        [_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
    });
    if (string)
        return [_dateFormatter dateFromString:string];
    else
        return nil;
}

A: I don't know if it's documented or is a bug, but in iOS 7 (or XCode 5, not sure of the origin of the problem) you have to set the explicitly locale of NSDateFormatter before parsing date strings, or you get nil dates
Until XCode 5/iOS 7,  NSDateFormatter had as default the locale of the phone, and you didn't get a nil date
I found this problem mantaining old applications, that suddenly started returning nil dates


text:
Q: Blazor wasm debuging in VS2022 stopped working I'm developing blazor wasm app and debuging stopped working correctly in VS2022 17.1.6.

*

*I'm able to set breakpoints, but I can't view the values of any variables

*I can't step over lines (Frame not in module)

*If I create new blazor wasm project, debuging works correctly.

What Am I missing ?
I can see strange errors:
    dotnet.6.0.4.i2krt2oq01.js:1 /__w/1/s/src/mono/mono/metadata/class.c:2227 <disabled>
    dotnet.6.0.4.i2krt2oq01.js:1 * Assertion: should not be reached at /__w/1/s/src/mono/mono/metadata/class.c:2228
    Assertion: should not be reached at /__w/1/s/src/mono/mono/metadata/class.c:2228

A: Check if you have interloop between base and inherited component. In my case, I was calling base method which builds itself (layout via RenderFragment builder)

A: The same thing happened to me. I could not see the value of variables, and breakpoints were not working.
My issue was resolved by changing the solution configuration from 'Release' to 'Debug'. See the below picture. My breakpoints have worked correctly, and I have been able to view the values of variables since making this change.


text:
Q: redux-react-session installing package Error Terminal Error
PS C:\Users\Danial Sama\Downloads\Program Languegs\React Native\danshgah\poroje> npm install redux-react-session
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: poroje@0.1.0
npm ERR! Found: react@18.2.0
npm ERR! node_modules/react
npm ERR!   react@"^18.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^0.14.0 || ^15.0.0 || ^16.0.0" from redux-react-session@2.6.1
npm ERR! node_modules/redux-react-session
npm ERR!   redux-react-session@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See C:\Users\Danial Sama\AppData\Local\npm-cache\eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\Danial Sama\AppData\Local\npm-cache\_logs\2022-08-18T06_51_08_504Z-debug-0.log

This Error showing when i wanted to add redux-react-session package
and don't know how to fix it.

A: Try This.
npm install redux-react-session --legacy-peer-deps

or
npm install --legacy-peer-deps


text:
Q: Restrict a filter to a custom post type. Am I doing this right? So I had this little bit of code to short a music charts custom post type that all starts with  numbers (the trick was to make the 10th position appear last in the list, not between 1 and 2):
add_filter('posts_orderby', 'orderby_post_title_int', 10, 2 );
function orderby_post_title_int( $orderby ) { return '(wp_posts.post_title+0) ASC'; }

This was working well until I discovered that is was also changing every other posts ;-)
So I tried wrapping the filter around a conditionnal statement:
if ($post_type == 'chart') {
    add_filter('posts_orderby', 'orderby_post_title_int', 10, 2 );
}

Didn't work. Then I decided to go within the function like this :
function orderby_post_title_int( $orderby, $query ) {
    if ($query->query_vars['post_type'] == 'chart') {
       return '(wp_posts.post_title+0) ASC';
    }
    return $orderby;
}

And still nothing. At this point, it doesn't change the regular post, but won't change the chart post type either.
So I guess my question is: am I in the right direction here? Is it possible to restrict a filter to a specific custom post type? If so, what should I explore as a way to do it?
Thank you

A: I think you're looking for the "conditional" get_post_type.
In your case it would be:
function orderby_post_title_int( $orderby, $query ) {
    if ( 'chart' == get_post_type() ) {
       return '(wp_posts.post_title+0) ASC';
    }
    return $orderby;
}

Or you could insert the conditional in your original function, which you know was working?
(Note if this is a custom post type archive, you'd use the is_post_type_archive() conditional instead.)


text:
Q: GoLang multi-tenant application database connections I am new to golang and currently trying to build a multi-tenant application. In my application each tenants have their own database. My requirement is that I need to switch database connection per tenant request, how can this be accomplished in golang. I prefer postgresql for this project.
I can have a map of database connection to tenant, but not sure if this is a good practice.
Your help and suggestion is highly appreciated

A: I've handled a similar kind of requirement in Rails. Probably you can use the same approach in go-lang also.
I will have one master DB, which will hold just the tenant information. Like tenant name and db_name.
And I've got a rack middleware which will switch DB based on a subdomain(I'm using the subdomain to identify the tenant).
For example, Your master DB can have table tenants and an example record might probably look like this:
{
    id: 1,
    name: 'XYZ',
    db_name: 'xyz'
}
and when your application receives a request with subdomain xyz, Your middleware should switch to xyz DB.

A: its a better solutions to create an schema instead of an entire database and on each request change the schema of the request identifying the tenant.other solutions is to create a database and reopen a connection on each request after the tenant recognition on the middleware


text:
Q: couldn't find file 'jquery', couldn't find 'foundation' I'm having troubles with upgrading from an older Rails 3.0 project to the latest Rails 3.2 (Rails 4 is a bit too edgy) and using the asset pipeline as advertised. I've successfully used the asset pipeline in newer projects with gems like foundation, but getting it to work in this older project seems to be hard, repeatingly getting Sprockets::FileNotFound errors. The gemfile is correctly featuring all the gems in the asset group.
source 'http://rubygems.org'

gem "rails", "~> 3.2.13"

... database gems ...
gem 'nokogiri'

group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'
  gem 'compass-rails'
  gem 'uglifier', '>= 1.0.3'
  gem 'zurb-foundation', '~> 4.0.0'
  gem 'jquery-ui-rails'
end
gem 'jquery-rails'
....

Note that I solved a similar error Sprockets::FileNotFound: couldn't find file 'jquery' by moving jquery-rails outside the :assets-group, but that is not how at least foundation is supposed to work...
Another problem I'm facing (and might be related) is that rails g foundation:install doesn't work, even though bundle install command lists that the zurb-foundation gem (4.0.9) is being used.
I've tried comparing a freshly generated project that works with the foundation assets with my current project but I seem to look over the difference between the upgraded Rails project's configuration but Sprockets::FileNotFound: couldn't find file 'jquery' foundation persists.
Note that I've seen solutions suggesting to move files into your project's vendor-folders, but that is not the type of solution I'm after. I'd like to take full advantage of the asset pipeline and try to keep my project as clean as possible.
Any suggestions?

A: I seem to have found the answer myself... guess asking the question helped me spotting the differences between the newly created project and the old project better...
In application.rb the Bundler require statement differed from the newly created project:
Bundler.require(:default, Rails.env) if defined?(Bundler) (old) vs. Bundler.require(*Rails.groups(:assets => %w(development test))) if defined?(Bundler) (new)
I guess the difference entails that besides the default groups the asset groups need to be included when the environment is either development or test.


text:
Q: How to chmod files that have a specific set of permissions I want to find all files in a folder that have -rw-r----- (640? is that the right code?) permissions, and change them all to have -rw-rw-rw- instead.  How do I do this, with chmod?
I know I could do the whole folder with
sudo chmod -R 666 /path/to/folder

but I think (perhaps mistakenly?) that it would be more efficient to just do the ones that actually need it?
Alternatively, rather than specifically looking for -rw-r-----, I could chmod any file that doesn't have 666 already?  Would that be better?

A: find /path/to/folder -perm 640 -exec chmod 666 {} \;


text:
Q: Replace a segment of text in the cell of a specific column only when other text is not present I am trying to replace the AM– with – but only in the cells that do not contain a PM anywhere in the text.
As an example, some cells would be like:
Sat 9:00 AM–11:30 AM
and other cells are:
Wed 10:00 AM–1:00 PM
The code I have is:
    Dim find_value, replace_value As String

find_value = " AM–"
replace_value = "–"

    Columns("I").Replace What:=find_value, _
                            Replacement:=replace_value, _
                            LookAt:=xlPart, _
                            SearchOrder:=xlByRows, _
                            MatchCase:=True, _
                            SearchFormat:=False, _
                            ReplaceFormat:=False

This replaces all of the instances but I want to only replace the AM– if the PM does not exist.


text:
Q: Magento2 Sort by Rating I am working on Magento2.2.1, I want to sort by rating. I have applied the below code but it's not working with Ajax neither Page load as well. Pagination is not coming.
$collection->getSelect()->joinLeft(
                            'rating_option_vote_aggregated',
                            'e.entity_id = rating_option_vote_aggregated.entity_pk_value',
                            array('vote_count' => 'SUM(rating_option_vote_aggregated.vote_count)'))
                    ->group('e.entity_id')
                    ->order('vote_count ' . $this->getCurrentDirectionReverse());

Can anyone please suggest

A: For pagination issue  make plugin in your custom module like
create di.xml file under etc directory of your module
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
 <type name="Magento\Catalog\Model\ResourceModel\Product\Collection">
        <plugin name="product-collection-sorting" type="NameSpace\ModuleName\Plugin\Product\Collection" sortOrder="1"/>
    </type>
</config>

create plugin file
<?php namespace NameSpace\ModuleName\Plugin\Product;

class Collection

{

public function afterGetSelectCountSql(\Magento\Catalog\Model\ResourceModel\Product\Collection $subject, $result)
{

   if(count($result->getPart(\Magento\Framework\DB\Select::GROUP)) > 0) {
       $result->reset(\Magento\Framework\DB\Select::GROUP);
   }
   return $result;
 }
}


text:
Q: Function that depends on the row number In pandas, is it possible to reference the row number for a function.  I am not talking about .iloc.
iloc takes a location i.e. a row number and returns a dataframe value.
I want to access the location number in the dataframe.
For instance, if the function is in the cell that is 3 rows down and 2 columns across, I want a way to return the integer 3.  Not the entry that is in that location.
Thanks.

A: Consider the dataframe df
df = pd.DataFrame([[1, 2], [3, 4]], ['a', 'b'], ['c', 'd'])

df

And the row row
row = df.ix['a']

row

c    1
d    2
Name: a, dtype: int64

There is nothing about this row that indicates that it was the first row of df.  That information is essentially lost... sort of.
You can take @jezrael's advice and use get_loc
df.index.get_loc(row.name)

0

But this only works if your index is unique.
Your only other option is to track its position when you get it.  The best way to do that is:
Use enumerate on df.iterrows()
for i, (idx, row) in enumerate(df.iterrows()):
    print "row position: {:>3d}\nindex value: {:>4s}".format(i, idx)
    print row, '\n'

row position:   0
index value:    a
c    1
d    2
Name: a, dtype: int64

row position:   1
index value:    b
c    3
d    4
Name: b, dtype: int64

A: Sorry I couldnt add a code sample but Im on my phone.  piRSquared confirmed my fears when he said the info is lost.  I guess ill have to do a loop everytime or add a column with numbers ( that will get scrambled if i sort them : / ).
Thanks everyone.


text:
Q: oracle, underlying table/view code, ddl, show table I am wondering what the analog of the below teradata code is in Oracle. I want to find the underlying table or view ETL code. Basically, I want to find the code that is used to create the table/view. Is there a query to do this? Please send this code. I only know how to do this in the schema browser.  I am using ORacle SQL Developer, Schema Browser. Then clicked on SQL.
I was looking for the underlying SQL on this table. This is the SQL code that creates the view. THis is the DDL. I just wanted to know how the view was created similarly, the analog to teradata code.
teradata
show VIEW Schema.Table
oracle
?

A: For views please execute this query:
select text from user_views where view_name = 'EMP_VIEW';

For tables you can execute this query:
select dbms_metadata.get_ddl( 'TABLE', 'EMP', 'SCOTT' ) from dual

A: Oracle has a package DBMS_METADATA which is can be used to exctract DDL command to create it. You can use GET_DDL function to get table definition.
SELECT DBMS_METADATA.GET_DDL(
           object_type => 'TABLE',
           name => 'Table' ,
           schema => 'Schema')
FROM DUAL;


text:
Q: Can't get nodeJS Express post to display body data I feel like I've tried everything, would appreciate some fresh eyes to look upon my problem. As the title suggests, I'm sending a http post request to my NodeJS server that is running express, and nodeJS returns the req.body to be undefined/empty.
NodeJS Express Code:
const express = require('express');
const path = require('path');
const app = express();
const PORT = process.env.PORT || 5000;

app.use(function(req, res, next) {
 res.header("Access-Control-Allow-Origin", "*");
 res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
 Content-Type, Accept");
 next();
});

app.post('/addComment', (req, res) => {
 console.log(req.body);
});

app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

Javascript Browser Code:
let data = {name: 'aName'};

fetch('http://localhost:5000/addComment', {
 method: 'post',
 body: JSON.stringify(data)
});

A: You have to use body-parser middleware :
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json());
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
Content-Type, Accept");
next();
});
app.post('/addComment', (req, res) => {
console.log(req.body);
});

app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

see body-parser.

A: If you are using the latest express, you can actually use do
    const express = require('express');
    const path = require('path');
    const app = express();
    const PORT = process.env.PORT || 5000;

    app.use(express.json())
    app.use (express.urlencoded({extended: false}))

    app.use(function(req, res, next) {
       res.header("Access-Control-Allow-Origin", "*");
       res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,
       Content-Type, Accept");
       next();
   });

   app.post('/addComment', (req, res) => {
       console.log(req.body);
   });

   app.listen(PORT, () => console.log(`Listening on ${ PORT }`));

Express now bundle body-parser by default due to popular demand.


text:
Q: ArcPy Geocode Addresses works in ArcPy window but not in a standalone script This issue sounds like a repeat of ArcPy function works in ArcMap Python window but not from standalone script? but I am receiving a different outcome so this is why I am posting here.
The following is a simple geocoding script that works if loaded in the arcpy window but not running outside of Arc software.  There is no error when running outside of Arc and it runs all the way through with a very low yield of geocoded features.
This is an issue with all Address Locators, Composite Locators and Custom Composite locators.  Currently using StreetMap Premium 2017 R2 as the source for the custom Composite_Parcel locator listed below.  The only difference between the Composite_Parcel and the standard USA_2017R2_TT_CompositeZip4 ESRI install is I changed the "Derive output geometry from display fields = No" to "Derive output geometry from display fields = Yes" in the USA_2017R2TT_PointAddress locator.
# Local variables:
tbl_WM_REPAIR_LEAKS_UAT_20190325113927 = "C\\ZZZZZ\\YYYYY\\XXXXXX\\\\Test Geocode\\Test Geocode.gdb\\tbl_UAT_20190325113927"
Composite_Parcels = "C:\\ZZZZZ\\YYYYY\\XXXXXX\\Composite_Parcels"
Geo_Model_Builder = "C:\\ZZZZZ\\YYYYY\\XXXXXX\\Test Geocode.gdb\\Geo_py_script_try_2"

# Process: Geocode Addresses
print 'Started Geocoding'
arcpy.GeocodeAddresses_geocoding(tbl_WM_REPAIR_LEAKS_UAT_20190325113927, Composite_Parcels,
                                 "Street AddrAdded VISIBLE NONE;City City VISIBLE NONE;State State VISIBLE NONE;ZIP <None> VISIBLE NONE;ZIP4 <None> VISIBLE NONE",
                                 Geo_Model_Builder, "STATIC")

If ran outside of Arc here is the breakdown by Loc_name:

*

*Point Address: 285

*Null: 2278

If loaded into arcpy window in Catalog or Maps here is the breakdown by Loc_name:

*

*Point Address: 1830

*Street Address: 525

*StreetName: 84

*Admin Places: 122

*Null: 2

Software Specs:

*

*Arc 10.4.1

*Advanced License

Python:

*

*Python 2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit
(Intel)] on win32

I've tried to edit performance Search timeout of the Address Locator from 1 second to 10 seconds but this did not change the results of the output.

A: The issue to this problem was the Arc 10.4 python 2.7 32 bit environment.  The arcpy.GeocodeAddresses_geocoding function runs on the Arc 10.4 2.7 64 bit background processing (there are a few other functions that run on 64 bit background processing).
To solve this I installed the C:\Python27\ArcGISx6410.4 background processing python package on my machine and created a Arc_104_64 bit python environment.  I am now using this to execute the script outside the Arc software and it returns the same values as it does inside the Arc software.
The following are steps I took:

*

*Install ArcGISx6410.4 python folder

*Open Anaconda Prompt

*conda create -n Arc_104_64 python=2.7.10

*Proceed ([y]/n)? y

*conda install - Arc_104_64 numpy=1.9.2 matplotlib=1.4.3 pysal

*Copy from ArcGISx6410.4\Lib\site-packages: DTBGGP64.pth and matplolib-1.4.3-py2.7-nspkg.pth

*Paste into Local\conda\conda\envs\Arc_104_64\Lib\site-packages folder

Ran the geocoding script in the newly create environment.