text:
Q: For some reason Set does not have "contains" Its init in the constructor and it returns set of the strings.
private val listener: () -> Set<String> = {
    NotificationManagerCompat.getEnabledListenerPackages(context)
}

But for some reason I am not able to call .contains() function when I'm calling listener.contains("package")
It says

A: listener is a lambda of type () -> Set<String
in order to use contains() you need listener's value which is Set<>
You can achieve this buy using invoke() as @Михаил Нафталь mentioned:
listener.invoke().contains("value")

or:
listener().contains("value")

Invoking a function type instance


text:
Q: ComboBox Does Not Update After Switching To Another Sheet so I am still quite a noob at VBA and I made two ComboBoxes, first ComboBox is for the list of the sheets in the workbook and the second ComboBox is the list of names that reads in from a specific column. It works fine for first time trying, however, when switching to another sheet through using the first combobox, the second ComboBox still has the old list of names from the previous sheet that I opened. I have been looking for solutions for hours on how to get the second ComboBox to update once a new sheet has been selected from the first ComboBox and I was wondering if there is any way I could get the second ComboBox to refresh? Here is my code that deals with two text boxes:
This is the function when the UserForm gets started, I first populate the first ComboBox with the sheets in the workbook then I populate the second ComboBox.
Private Sub UserForm_Initialize()

'Worksheet object
Dim sht As Worksheet

'Sets the ComboBox1 to "Select a Project"
ComboBox1.Value = "Select a Project"

'Name of the Sheet That is Excluded
Dim prjSum As String
prjSum = "Pjct Resource Summary"

'For every sheet in the workbook
For Each sht In ActiveWorkbook.Sheets
    If Not (sht.name = prjSum) Then 'Excluding PRS
        ComboBox1.AddItem (sht.name) 'Add to the ComboBox1 list
    End If
Next sht

'Populate ComboBox2 starting from E4 to the last name in E column
ComboBox2.List = ActiveSheet.Range("E4", Range("E4").End(xlDown)).Value
End Sub

Here I just set textboxes from their respective cells. I tried doing populating my second ComboBox here but then for some reason, my ComboBox would show nothing or show a name from the first sheet in the workbook.
Private Sub ComboBox2_Change()

currWrkSheet = ComboBox1.Value

If currWrkSheet = "Select a Project" Then
    MsgBox ("Select a Project")
    Exit Sub
End If

'ComboBox2.List = ActiveSheet.Range("E4", Range("E4").End(xlDown)).Value

'Once getting the value of the combobox, it should show the values from the corresponding texboxes/comboboxes
TextBox2.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 2).Value 'BU
TextBox3.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 3).Value 'Function
TextBox4.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 4).Value 'Resource Type
TextBox5.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 6).Value 'Project Role
TextBox6.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 7).Value 'Project Responsibility

'TextBoxes for the Months
TextBox7.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 8).Value
TextBox8.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 9).Value
TextBox9.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 10).Value
TextBox10.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 11).Value
TextBox11.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 12).Value
TextBox12.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 13).Value
TextBox13.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 14).Value
TextBox14.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 15).Value
TextBox15.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 16).Value
TextBox16.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 17).Value
TextBox17.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 18).Value
TextBox18.Value = Worksheets(currWrkSheet).Cells(ComboBox2.ListIndex + 4, 19).Value
End Sub

redpajama_set_name: RedPajamaStackExchange


text:
Q: Config host and open with webpack My question is very basic. I set the dev server like this in my webpack config:
devServer: {
    host: '0.0.0.0',
    port: 4002,
    overlay: true,
    open: true
}

I add the host: '0.0.0.0' in order to access the server via my IP address.
And it works fine with

localhost:4002

OR

< IP_ADDRESS >:4002

The problem is that with the open: true it opens the page in the browser with the hostname:

0.0.0.0:4002

and it does not work.

A: I fixed it with openPage option which specifies the URL I want to open. The open option just tries to infer the URL you want using the host option.
devServer: {
    host: '0.0.0.0',
    port: 4002,
    overlay: true,
    open: true,
    openPage: 'http://localhost:4002'
}


text:
Q: Iptables prerouting and IP forwarding I have a linux machine used as gateway for a Win XP machine. Both are in Virtual machine for testing purpose. Now I want to trick the Win XP user (me) with the forwarding of an IP address: I want to change the destination IP address.
For example I want to go to 1.1.1.1 but linux gateway change it to 2.2.2.2
So if I'm expecting the web page of 1.1.1.1, I'll get the changed one, the one of 2.2.2.2
For example I want to go to Facebook and I'm forced to Google home page.
How can I do it? With prerouting?
Because I've done lot of tries, but no one working :(

A: Maybe you can use the etc/hosts (http://en.wikipedia.org/wiki/Hosts_%28file%29) in Win XP?
You can add a line like this one : "www.google.com www.facebook.com" in your host file to redirect request to www.facebook.com to www.google.com  (you should also add a line without the www).
You can try the same thing on the linux (I don't think it'll work).
The best would be that your linux serves DNS for you, so you can configure your DNS software for that purpose.


text:
Q: MYSQL Partition selecting not working It seems that mysql is only selecting data from the first partition and last partition when you use a date range.
| sales | CREATE TABLE `sales` (
            `id` int(11) NOT NULL AUTO_INCREMENT,
            `quantity_sold` int(11) NOT NULL,
            `prod_id` int(11) NOT NULL,
            `store_id` int(11) NOT NULL,
            `date` date NOT NULL,
            KEY `prod_id` (`prod_id`),
            KEY `date` (`date`),
            KEY `store_id` (`store_id`),
            KEY `id` (`id`)
            ) ENGINE=InnoDB AUTO_INCREMENT=577574322 DEFAULT CHARSET=utf8
            /*!50100 PARTITION BY RANGE (to_days(date))
           (PARTITION p0 VALUES LESS THAN (0) ENGINE = InnoDB,
           PARTITION p201211 VALUES LESS THAN (735203) ENGINE = InnoDB,
           PARTITION p201212 VALUES LESS THAN (735234) ENGINE = InnoDB,
           PARTITION p201301 VALUES LESS THAN (735265) ENGINE = InnoDB,
           PARTITION p201302 VALUES LESS THAN (735293) ENGINE = InnoDB,
           PARTITION p201303 VALUES LESS THAN (735324) ENGINE = InnoDB,
           PARTITION p201304 VALUES LESS THAN (735354) ENGINE = InnoDB,
           PARTITION p201305 VALUES LESS THAN (735385) ENGINE = InnoDB,
           PARTITION p201306 VALUES LESS THAN (735415) ENGINE = InnoDB,
           PARTITION p201307 VALUES LESS THAN (735446) ENGINE = InnoDB,
           PARTITION p201308 VALUES LESS THAN (735477) ENGINE = InnoDB,
           PARTITION p201309 VALUES LESS THAN (735507) ENGINE = InnoDB,
           PARTITION p201310 VALUES LESS THAN (735538) ENGINE = InnoDB,
           PARTITION p201311 VALUES LESS THAN (735568) ENGINE = InnoDB,
           PARTITION p201312 VALUES LESS THAN (735599) ENGINE = InnoDB,
           PARTITION p201401 VALUES LESS THAN (735630) ENGINE = InnoDB,
           PARTITION p201402 VALUES LESS THAN (735658) ENGINE = InnoDB,
           PARTITION p201403 VALUES LESS THAN (735689) ENGINE = InnoDB,
           PARTITION p201404 VALUES LESS THAN (735719) ENGINE = InnoDB,
           PARTITION p201405 VALUES LESS THAN (735750) ENGINE = InnoDB,
           PARTITION p201406 VALUES LESS THAN (735780) ENGINE = InnoDB,
           PARTITION p201407 VALUES LESS THAN (735811) ENGINE = InnoDB,
           PARTITION p201408 VALUES LESS THAN (735842) ENGINE = InnoDB,
           PARTITION p201409 VALUES LESS THAN (735872) ENGINE = InnoDB,
           PARTITION p201410 VALUES LESS THAN (735903) ENGINE = InnoDB,
           PARTITION p201411 VALUES LESS THAN (735933) ENGINE = InnoDB,
           PARTITION p201412 VALUES LESS THAN (735964) ENGINE = InnoDB,
           PARTITION P201501 VALUES LESS THAN (735995) ENGINE = InnoDB,
           PARTITION P201502 VALUES LESS THAN (736023) ENGINE = InnoDB,
           PARTITION p1 VALUES LESS THAN MAXVALUE ENGINE = InnoDB) */ |

Select the sales (should get data from all of the partitions) But only from the first and last?
`mysql> select * from sales where prod_id = 232744 and store_id = 300;
    +-----------+---------------+---------+----------+------------+
    | id        | quantity_sold | prod_id | store_id | date       |
    +-----------+---------------+---------+----------+------------+
    |      2309 |             1 |  232744 |      300 | 2012-11-26 |
    |      2484 |            10 |  232744 |      300 | 2012-11-27 |
    |      2837 |             7 |  232744 |      300 | 2012-11-29 |
    |      3001 |             9 |  232744 |      300 | 2012-11-30 |
    | 571930074 |             4 |  232744 |      300 | 2014-12-02 |
    | 573051350 |            13 |  232744 |      300 | 2014-12-03 |
    | 574181358 |             5 |  232744 |      300 | 2014-12-04 |
    | 575322316 |             9 |  232744 |      300 | 2014-12-05 |
    | 576455102 |             4 |  232744 |      300 | 2014-12-06 |
    | 577545446 |             2 |  232744 |      300 | 2014-12-07 |
    +-----------+---------------+---------+----------+------------+`

The explain partition show that it is scanning all of the partitions.
mysql> explain partitions select * from sales where prod_id = 232744 and store_id =300\G;
    *************************** 1. row ***************************
               id: 1
      select_type: SIMPLE
            table: sales
       partitions: p0,p201211,p201212,p201301,p201302,p201303,p201304,p201305,p201306,p201307,p201308,p201309,p201310,p201311,p201312,p201401,p201402,p201403,p201404,p201405,p201406,p201407,p201408,p201409,p201410,p201411,p201412,P201501,P201502,p1
             type: index_merge
    possible_keys: prod_id,store_id
              key: prod_id,store_id
          key_len: 4,4
              ref: NULL
             rows: 20
            Extra: Using intersect(prod_id,store_id); Using where
    1 row in set (0.00 sec)

If I manually select the partition we can see there is data there, which should be in the data above.
`mysql> select * from sales PARTITION (p201410) where prod_id = 232744 and store_id = 300;
    +-----------+---------------+---------+----------+------------+
    | id        | quantity_sold | prod_id | store_id | date       |
    +-----------+---------------+---------+----------+------------+
    | 509534154 |             2 |  232744 |      300 | 2014-10-01 |
    | 510606312 |            10 |  232744 |      300 | 2014-10-02 |
    | 511682398 |             4 |  232744 |      300 | 2014-10-03 |
    | 512752933 |             2 |  232744 |      300 | 2014-10-04 |
    | 514812731 |             3 |  232744 |      300 | 2014-10-06 |
    | 515862308 |             6 |  232744 |      300 | 2014-10-07 |
    | 516922728 |             5 |  232744 |      300 | 2014-10-08 |
    | 517990349 |            19 |  232744 |      300 | 2014-10-09 |
    | 519066761 |            17 |  232744 |      300 | 2014-10-10 |
    | 520136175 |             3 |  232744 |      300 | 2014-10-11 |
    | 522185901 |             1 |  232744 |      300 | 2014-10-14 |
    | 523238559 |             3 |  232744 |      300 | 2014-10-15 |
    | 524294166 |             7 |  232744 |      300 | 2014-10-16 |
    | 525354982 |             3 |  232744 |      300 | 2014-10-17 |
    | 526412605 |             1 |  232744 |      300 | 2014-10-18 |
    | 527444329 |             1 |  232744 |      300 | 2014-10-19 |
    | 528452608 |             1 |  232744 |      300 | 2014-10-20 |
    | 529488414 |             2 |  232744 |      300 | 2014-10-21 |
    | 530541002 |             3 |  232744 |      300 | 2014-10-22 |
    | 531603714 |             4 |  232744 |      300 | 2014-10-23 |
    | 532672667 |             6 |  232744 |      300 | 2014-10-24 |
    | 534793524 |             1 |  232744 |      300 | 2014-10-26 |
    | 535819138 |             1 |  232744 |      300 | 2014-10-27 |
    | 537957232 |             1 |  232744 |      300 | 2014-10-29 |
    | 539037254 |             1 |  232744 |      300 | 2014-10-30 |
    | 540125545 |             2 |  232744 |      300 | 2014-10-31 |
    +-----------+---------------+---------+----------+------------+
    26 rows in set (0.03 sec)`

If you were to do a select * from sales where prod_id = 232744; it will select all of the data.It seems to be just when you add a store_id condition in there that it doesn't select the correct data.
I'm stumped. I've tried:

*

*Restarting mysql

*I'm about to try a OPTIMIZE TABLE (I have to move the databases because of space constraints)

*Seems to me there is something wrong with the keys? corrupt table?

Thanks!


text:
Q: How to create bar-chart with different color for each bar? We are creating bar chart for file manager application, we have to display different color for each bar.
Written following code globally.
GraphicalView chartView = null;
private CategorySeries series = new CategorySeries("Space");
private XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
private XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
ArrayList<String> names = new ArrayList<String>();
ArrayList<String> sizes = new ArrayList<String>();

Written following code to display different colors.
     public void getBarChart(){
        for(int i = 0;i < name.length; i++){
        series.add(name[i],values[i]);
        multiRenderer.addXTextLabel(i, name[i]);
    }
    dataset.addSeries(series.toXYSeries());
    XYSeriesRenderer renderer = new XYSeriesRenderer();
    renderer.setColor(Color.rgb(0, 255, 255));
    renderer.setFillPoints(true);
    renderer.setLineWidth(2);
    renderer.setDisplayChartValues(true);

    multiRenderer.setXLabels(0);
    multiRenderer.setChartTitle("Chart Used Space");
    multiRenderer.setXTitle("Name of Directory");
    multiRenderer.setAxisTitleTextSize((float)18);
    multiRenderer.setChartTitleTextSize((float)20);
    multiRenderer.setYTitle("Amount of Space in MB");
    multiRenderer.setXLabelsAngle((float)35);
    multiRenderer.setLabelsTextSize((float)15);
    multiRenderer.setXLabelsAlign(Align.LEFT);

    multiRenderer.setZoomButtonsVisible(true);
    multiRenderer.setBarSpacing((float) 1.0);
    multiRenderer.addSeriesRenderer(renderer);
        chartView = ChartFactory.getBarChartView(getBaseContext(), dataset, multiRenderer, org.achartengine.chart.BarChart.Type.DEFAULT);
    }

A: The bar color in a bar chart is given by its renderer. Each series has a renderer. In order to have a separate color for each bar you will have to add several series, each one having only one bar.

A: Hi Have a look at this code.
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;

public class MainActivity extends Activity {
 LinearLayout linearChart;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  linearChart = (LinearLayout) findViewById(R.id.linearChart);
  int colerloop[] = { 1, 2, 2, 2, 3, 3, 3, 3, 1, 1 };
  int heightLoop[] = { 300, 200, 200, 200, 100, 100, 100, 100, 300, 300 };
  for (int j = 0; j < colerloop.length; j++) {
   drawChart(1, colerloop[j], heightLoop[j]);
  }
 }

 public void drawChart(int count, int color, int height) {
  System.out.println(count + color + height);
  if (color == 3) {
   color = Color.RED;
  } else if (color == 1) {
   color = Color.BLUE;
  } else if (color == 2) {
   color = Color.GREEN;
  }

  for (int k = 1; k <= count; k++) {
   View view = new View(this);
   view.setBackgroundColor(color);
   view.setLayoutParams(new LinearLayout.LayoutParams(25, height));
   LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) view
     .getLayoutParams();
   params.setMargins(3, 0, 0, 0); // substitute parameters for left,
           // top, right, bottom
   view.setLayoutParams(params);
   linearChart.addView(view);
  }
 }
}

For more details please visit the below link.
http://www.androidhub4you.com/2013/05/custom-bar-chart-in-android-dynamic.html
If you follow above link your bar chart will be look like below image.
http://4.bp.blogspot.com/-V7SwZZIRPo8/UaH3pR99oSI/AAAAAAAAAhY/N8etB_mAzec/s1600/device-2013-05-26-171036.png


text:
Q: Multiple dynamic line charts with chart.js | Js and html I'd like to create an html page using Javascript (in particular using chart.js library) and to display dynamic line charts.
I'd also like to add a new chart every time the "Add Chart" button is pressed.
I manage to do all of this more or less, but with some issues:

*

*when a new chart is created the old one disappears, or to better say it is blurred;

*I don't know how to align the new chart with the old one, recursively, so that every new chart is under the older one, I try to do so but without any great accomplishment;

*I don't really understand the role played by
 or <canvas>, and I don't think that it is possible to create a new
 or <canvas> for every new chart since I don't know how many chart there will be displayed.

Could CSS help me? Or is there a way to divide the html page in a dynamic way so that every time a new chart is created it will also create a new area of the html page for the new chart?
This is the code:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Title</title>

        <canvas id="myChart"></canvas>

    <button id="randomizeData">Randomize Data</button>
    <button id="addDataset">Add Dataset</button>
    <button id="removeDataset">Remove Dataset</button>
    <button id="addData">Add Data</button>
    <button id="addChart">Add Chart</button>

A: You can create canvas after addChart event call, I just update your newChart() function and run in my computer and it's work what you want. Example:
function newChart(){
    document.getElementById('test').insertAdjacentHTML("afterend","
<canvas id='canvas"+cont+"'></canvas>
");
    var can_id="canvas"+cont;
    var ctx2 = document.getElementById(can_id).getContext('2d');
    window.can_id = new Chart(ctx2, config);

    window.can_id.update();
    //alert(config.options.id);
    configSet();
    //alert(config.options.id);
    alert(cont);
    return cont = cont +1;
}

Edit: I edit for use 'table'.
In your html I add only 'table' and in JS I add all 'tr' when call this function. Link:
HTML:

JS:
function newChart(){
    document.getElementById('test').insertAdjacentHTML("afterend","
<canvas id='canvas"+cont+"'></canvas>
");
    var can_id="canvas"+cont;
    var ctx2 = document.getElementById(can_id).getContext('2d');
    window.can_id = new Chart(ctx2, config);

    window.can_id.update();
    //alert(config.options.id);
    configSet();
    //alert(config.options.id);
    alert(cont);
    return cont = cont +1;
}


text:
Q: Create all possible combinations of text Need help in TSQL to create all possible combinations from text.
I have data like below
Input
A
B
C

Need result like below
Output
ABC
BCA
CAB
CBA
BAC
ACB

A: You can use a join:
select i1.col, i2.col, i3.col
from input i1 join
     input i2
     on i2.col not in (i1.col) join
     input i3
     on i3.col not in (i1.col, i2.col);

Here is a rextester for this solution.
EDIT:
It occurs to me that you might want to vary the length of input and that you really want strings with all the permutations.
If so, this can be handled with a recursive CTE:
with input as (
      select v.x
      from (values ('a'), ('b'), ('c')) v(x)
     ),
     cte as (
      select cast(x as varchar(max)) as str, 1 as len
      from input
      union all
      select cte.str + i.x, len + 1
      from cte join
           input i
           on cte.str not like '%' + i.x + '%'
     )
select top (1) with ties str
from cte
order by len desc;

Here is a SQL Fiddle with this solution.

A: i think cross can generate all the possible combination
 select t2.c+t3.col from
(select t1.col+t2.col as c
from t t1 cross join
     t t2
     ) as t2 cross join
     t t3

https://dbfiddle.uk/?rdbms=sqlserver_2016&fiddle=7a22b3c1f5fe81be1e2f3ec09311bd87


text:
Q: Java int calculator: re-use a calculated value for further calculation I developed a simple calculator using integers (no GUI), which is working fine. The calculator deploys seven types of calculation. Goals and achievements listed below.
The goals are:

*

*calculation with all of the types of calculation (done)

*deploy options for continuing calculation, switching operators, exit (done)

*deploy an option continuing with a calculated result (work in progress)

I was wondering how I could use a calculated result for another calculation. I tried to store the variable for a specific result in the corresponding switch-case-options, which is implemented in the MySimpleIntCalculatorHelper class (code's down below with documentation). Unfortunately this throws an error and prevents the calculator from working properly. Is there any advice which one you can tell me? Maybe I oversee something quite obvious!
For any further information about the source code, I'll leave you the link to my GitHub repository if necessary. https://https://github.com/DarkPalad1n/ExamPreCondition/tree/master/src
Thank you in advance!
Kind regards,
Passi
import java.util.Scanner;

/**
 * This class is as an extension of the class MySimpleIntCalculatorAdvanced.
 *
 * It inherits methods from its parental class and deploys useful methods for
 * running the calculator itself.
 *
 * @author DarkPalad1n
 *
 */

public class MySimpleIntCalculatorHelper extends MySimpleIntCalculatorAdvanced {

    static Scanner scanObject = new Scanner(System.in);
    static MySimpleIntCalculatorHelper erg = new MySimpleIntCalculatorHelper();
    static int operator = scanObject.nextInt();
    static int numberOne, numberTwo, numberOneAd;
    static String continueOption;

    // ---------------------CONSTRUCTOR--------------------

    public MySimpleIntCalculatorHelper() {

        chooseOperator();
    }

    // --------------------METHODS--------------------

    /**
     * User enters the menu. User's able to choose between seven operations.
     */
    public static void chooseOperator() {

        System.out.println(
                "Please enter your operator of choice: \n1.Addition \n2.Subtraction \n3.Multiplication \n4.Division \n5.Remainder \n6.Sum \n7.Checksum \n0.Exit");

    }

    /**
     * Method is used to take the user's figure inputs.
     *
     * The condition checks first whether the operator is 0 or 7 before entering the
     * cases where two figures are required.
     *
     * Case 0 ends the calculation.
     *
     * Case 7 only needs one input, which is why the method checks beforehand the
     * chosen case to take the correct input.
     */
    public static void chooseNumberOneAndTwo() {

        if (operator == 0) {
            System.out.println("Thank you for participating!");
            System.exit(0);
        } else if (operator == 7) {
            System.out.println("Please enter your number:");
            numberOneAd = scanObject.nextInt();
        } else {
            System.out.println("Please enter your first number:");
            numberOne = scanObject.nextInt();
            System.out.println("Please enter your second number:");
            numberTwo = scanObject.nextInt();

        }

    }

    /**
     * Method is used to perform mathematical operations in conjunction with the
     * chosen operator.
     */
    public static void performCalculation() {

        switch (operator) {
            case 1:
                erg.add(numberOne, numberTwo);
                break;
            case 2:
                erg.sub(numberOne, numberTwo);
                break;
            case 3:
                erg.mult(numberOne, numberTwo);
                break;
            case 4:
                erg.div(numberOne, numberTwo);
                break;
            case 5:
                erg.mod(numberOne, numberTwo);
                break;
            case 6:
                erg.sum(numberOne, numberTwo);
                break;
            case 7:
                erg.quer(numberOneAd);
                break;
            case 0:
                System.out.println("Thank you for participating!");
                System.exit(0);
            default:
                System.out.println("Unsupported operator. Please retry.");

        }

    }

    /**
     * This method asks the user whether to continue another calculation or not.
     *
     * scanObject.nextLine(); consumes the leftovers \n from .nextInt();. After
     * this workaround continueOption is ready for the user's input.
     */
    public static void continueCalculationOption() {

        System.out.println("Would you like to continue? \n Enter Y to continue. \n Enter N to exit. \n Enter S to switch the operator.");
        scanObject.nextLine();
        continueOption = scanObject.nextLine();
    }

    /**
     * Method is used to perform the users input from continueCalculationOption();.
     *
     * By entering "Y" the user is redirected to chooseNumberOneAndTwo(); to enter
     * new figures for calculation with the same operator.
     *
     * By entering "N" the user is going to exit the calculator.
     *
     * By entering "S" the user is able to switch the operator. It is important to
     * assign (zuweisen) operator to scanObject.nextInt(); for a proper performance
     * of the new operator input.
     */
    public static void performContinueCalculationOption() {

        switch (continueOption) {
            case "Y":
                System.out.println("Continue.");
                chooseNumberOneAndTwo();
                break;
            case "N":
                System.out.println("Thank you for participating.");
                System.exit(0);
                break;
            case "S":
                System.out.println("Switch operator.");
                chooseOperator();
                operator = scanObject.nextInt();
                break;
        }

    }

    /**
     * Method is used to perform at least a sequence of three instructions
     * while continueOption is equal to "Y".
     */
    public static void performCalculationSequence() {

        do {
            performCalculation();
            continueCalculationOption();
            performContinueCalculationOption();
        } while (continueOption.equals("Y"));
    }

    /**
     * This method uses a sequence of the helping methods created in this class
     * to run all the functionalities the calculator offers. The method runs in
     * the main method of the corresponding class.
     *
     * It consists of chooseNumberOneAndTwo(); and performCalculationSequence();.
     * There is a condition if the user's input equals "S" the user is able to
     * switch operators. After this particular method was used and the new
     * operator was selected, new figures are required and the calculation will
     * be performed. run(); will be executed continuously as long as a different
     * operator is chosen or "N" is entered.
     *
     */
    public static void run() {

        chooseNumberOneAndTwo();
        performCalculationSequence();
        if (continueOption.equals("S")) {
            chooseNumberOneAndTwo();
            performCalculationSequence();
            run();
        } else {
            System.out.println();
        }
    }
}

A: You can add a static attribute to your class and save your result in it. To choose the number, you could modify chooseNumberOneAndTwo() to make it accepting a command to choose the last result instead. (like "Ans")
To detect this, you must change scanObject.nextInt() to scanObject.next().   To check if it is a number, you can use numberOne.matches("-?\\d+").
Explanation:

*

*-?: first character is '-'; ? means it is optional (for negative integers)

*\\d: \d means a digit character; '\' is \\ in code

*+: there are 1 or more of the previous character

The completed method could be like this (previousResult is the static attribute to save the last result):
public static void chooseNumberOneAndTwo() {

    String inp;

    if (operator == 0) {
        System.out.println("Thank you for participating!");
        System.exit(0);
    } else if (operator == 7) {
        System.out.println("Please enter your number:");
        inp = scanObject.next();
        if (inp.matches("-?\\d+")) {
            numberOneAd = Integer.parseInt(inp);
        }
        else if (inp.matches("Ans")) {
            numberOneAd = previousResult;
        }
        else {}//Invalid input
    } else {
        System.out.println("Please enter your first number:");
        inp = scanObject.next();
        if (inp.matches("-?\\d+")) {
            numberOne = Integer.parseInt(inp);
        }
        else if (inp.matches("Ans")) {
            numberOne = previousResult;
        }
        else {}//Invalid input
        System.out.println("Please enter your second number:");
        inp = scanObject.next();
        if (inp.matches("-?\\d+")) {
            numberTwo = Integer.parseInt(inp);
        }
        else if (inp.matches("Ans")) {
            numberTwo = previousResult;
        }
        else {}//Invalid input

    }

}

I'd also suggest you to create a new method for this as this method does the same thing 3 times.


text:
Q: react native tcp send byte array I Have this code in c# for tcp:
var client = new TcpClient("192.168.1.x", 502);
var str = client.GetStream();
str.Write(new byte[] { 1, 1, 1, 1 }, 0, 4);
byte[] recieved = new byte[client.ReceiveBufferSize];
var recievesize = str.Read(recieved, 0, client.ReceiveBufferSize);
recieved = recieved.Take(recievesize).ToArray();

what is the equivalent in React native ?


text:
Q: How to write unit test case for angular 8 forms i.e ElementRef.nativeelement.submit() I am trying to write unit test case for angular 8 in jasmine. I have a form as below:
<form ngNoForm method="post" [action]="url" name="redirect" #redirectForm>
    <input  type= "hidden" name="mesgFromBank" value="{{message}}">
  </form>

and my ts file lookes like this:
@ViewChild('redirectForm', { read: ElementRef, static: false }) redirectForm: ElementRef;

 this.redirectForm.nativeElement.action = this.url;
 this.redirectForm.nativeElement.firstChild.value = this.message;
 this.redirectForm.nativeElement.submit();

However I try to write test case, it will be redirecting to the this.url and ultimately it is breaking and I am seeing "NOT FOUND" in my Karma runner in browser.
Can anyone help me in this?
Thanks.


text:
Q: how can get the Google SOAP API key I am doing my work with Search Engine PHP scripts process with Google clone. I want a Google soap API key. What should I do for get that key?

A: Look here: http://googlecode.blogspot.com/2009/08/well-earned-retirement-for-soap-search.html
It's no longer available.
They encourage you to use this: http://code.google.com/intl/nl-NL/apis/customsearch/v1/overview.html


text:
Q: Circuitikz draw SPDT vertically I've been trying to do my homework assignments with LaTeX so my terrible drawing skills don't cause me to lose points, however some of the drawings I need to produce have an SPDT switch that is oriented vertically. The attached image is an example of what I'm trying to create, but I can't seem to get the switch oriented properly. I can recreate the entire circuit otherwise.
The dotted line to position B is not a requirement for my use. I've looked through the documentation but I couldn't find anything about rotating the switch.
I'm relatively unfamiliar with TikZ drawing, however I can use it at a basic level.

A: Switch is nothing but lines and a curve. In the following picture, a simple switch is drawn

\documentclass[border={10}]{standalone}

\usepackage{circuitikz}

\begin{document}

\begin{circuitikz}
\draw (3.5,4) -- (4,3.5);
\draw (4.5,4) to[R,-o] (8.5,4);
\draw (4,3.5) to[short,-o] (4.5,4);
\draw (4,0) to[short,-*]   (4,3.5);
\draw[->,thick] (3.5,3.7)  to[out=45,in=135]   (4.5,3.7);
\draw (0,0) to[battery] (0,4)  to[R,-o] (3.5,4);

\end{circuitikz}

\end{document}

A: Another possibility, instead of using manual shifts, you can do the following with a recent circuitikz (notice that the result is more or less the same as @Archange's nice answer) --- the code is heavily commented to explain what I am doing there.
\documentclass[tikz,border=3.14]{standalone}
\usepackage[siunitx, american, RPvoltages]{circuitikz}

\begin{document}
\begin{tikzpicture}[]
    \ctikzset{voltage=raised}
    %%
    %% let's start with the capacitor --- you'll know why shortly
    %%
    \draw (0,0) coordinate(bot) to[C=\SI{1}{\uF}, v>=$v(t)$, *-] ++(0,2)
    %%
    %% now we position the switch. I am positioning it on the
    %% single throw because it is the only one with the straight
    %% connection to the pole:
    %%
        node[cute spdt up arrow,rotate=90,anchor=in] (S){}
        (S.center) node[above=1ex, font=\tiny, scale=0.8]{$t=0$};
    %%
    %% let's do the left side. The trick to have the wire going
    %% out at the correct angle is to use the internal node for
    %% the pole. When you use a node instead of a coordinate, TikZ
    %% (and circuitikz after 1.2.1) uses the border anchor
    %%
    \draw (S-out 1) to[R, l_=\SI{200}{\ohm}] ++(-3,0) coordinate(left)
    %%
    %% mark the coordinate where we are to use it with
    %% the perpendicular coordinate system; now you can just change
    %% the ++(3,0) above to enlarge or tighten the circuit and the
    %% rest will follow!.
    %%
        to[V, invert] (left|-bot) -- (0,0);
    %%
    %% let go for the right side
    %%
    \draw (S-out 2) to[R, l^=\SI{400}{\ohm}, -*] ++(3,0) coordinate(right);
    %%
    %% Finally, draw a line to the same horizontal end...
    %%
    \draw (bot) -- (bot-|right);
    %%
    %% and if you really like it, the dashed line... using the internal
    %% nodes again
    %%
    \draw [densely dashed] (S-in) -- (S-out 2);
\end{tikzpicture}
\end{document}

Notice that the full circuit is just 8-9 lines...

A: Here is another solution using "rotate" to place the "spdt" vertically :
\documentclass[border=5pt]{standalone}

\usepackage[siunitx,european,straightvoltages]{circuitikz}

\begin{document}

\begin{circuitikz}
\draw
(3,3) node[cute spdt up arrow, rotate = 90] (Sw){}
(3,0)to[C=\SI{4}{\micro\farad}, v=$v_1(t)$,*-](Sw.in)
(0,0)to[V=\SI{100}{\volt}](0,3)
(0,3)|-(Sw.out 1)
(Sw.out 2)-|(6,3)
(0,0)--(6,0)
(6,3)to[C, l_=\SI{1}{\micro\farad}, v^<=$v_2(t)$](6,0)
;
\draw (3,4)node{B};
\draw (3,3.6)node[ocirc]{};
\draw (2.4,3.6)node{A};
\draw (3.5,3.6)node{C};
\end{circuitikz}

\end{document}

And its output :

A: As other suggested, you can use [rotate=90] to achieve this. But in contrary to what they say/show, you can have the wires on the left and right part of the outs.
Here is a code producing as closed as I could reasonably get from your picture:
\documentclass{standalone}

\usepackage[american,RPvoltages,siunitx]{circuitikz}

\begin{document}
    \begin{tikzpicture}
        % Switch
        \draw (3,2.5) node[cute spdt up arrow,rotate=90] (S) {};
        \draw ([yshift=7]S) node [scale=0.5] {$t=0$};
        \node at ([yshift=7]S.cout 1) [scale=.75] {A};
        \node at ([yshift=7]S.cout 2) [scale=.75] {B};
        \draw [densely dashed] ([xshift=1,yshift=1]S.cin) -- ([xshift=-1,yshift=-1]S.cout 2); % Optional dashed line
        % Left part
        \draw (S.in) to [C, l_=1<\micro\farad>, name=C] (3,0)
                     to [short] (0,0)
                     to [V] (0,0 |- S.cout 1) % Using "S.cout 1" y coordinate
                     to [R=200<\ohm>] ([xshift=-1.5]S.cout 1); % Compensating for node size
        % Right part
        \draw (3,0) to [short] (6,0);
        \draw ([xshift=1.5]S.cout 2) to [R=4<\kilo\ohm>] (6,0 |- S.cout 2); % Using "S.cout 1" y coordinate and compensating for node size
        % Capacitor voltage
        \node at (C.north west) [above right] {$+$};
        \node at (C.north) [right] {$v(t)$};
        \node at (C.north east) [below right] {$-$};
        % Filled nodes
        \fill (3,0) circle(.05);
        \fill (6,0 |- S.cout 2) circle(.05);
    \end{tikzpicture}
\end{document}

And the result:

A: Here is another option:
\documentclass[border=5pt]{standalone}

\usepackage[american voltages,siunitx]{circuitikz}

\begin{document}
    \begin{tikzpicture}[x=3.5cm, y=3.5cm]
        % Vertices
        \coordinate [label=above left:\textcolor{blue}{}] (A) at (0.0, 0.8);
        \coordinate [label=above:\textcolor{blue}{}] (B) at (0.8, 0.8);
        \coordinate [label=below:\textcolor{blue}{}] (C) at (1.6, 0.8);
        \coordinate [label=below:\textcolor{blue}{}] (D) at (0.8, 0.0);
        \coordinate [label=below:\textcolor{blue}{}] (E) at (0.0, 0.0);
        \coordinate [label=below:\textcolor{blue}{}] (F) at (1.6, 0.0);
        % Circuit elements
        \draw (A) to [V, l_=$V_s$] (E) to (D);
        \draw (A) to [R,l=$R_s$] ($(B)+(-0.15,0.0)$)node[ocirc]{};
        \draw (D) to [C,l=$C$] ($(B)+(0.0,-0.2)$) node[circ]{};
        \draw (D) to (F) to [R,l_=$R$] (C) to ($(B)+(0.15,0.0)$) node[above right]{B}node[ocirc]{};
        % capacitor voltage
        \draw ($(B)+(0.24, -0.35)$) node[]{$+$};
        \draw ($(B)+(0.24, -0.5)$) node[]{$v(t)$};
        \draw ($(B)+(0.24, -0.65)$) node[]{$-$};
        % Switch
        \draw ($(B)+(0.0, -0.2)$) to ($(B)+(-0.15, 0.03)$) node[above left]{A} node[above right]{$t\text{=}0$};
        \draw[dashed] ($(B)+(0.0, -0.2)$) to ($(B)+(0.15, 0.03)$);
        \draw[-latex',brown!50!black,thick] ($(B)+(-0.15, -0.15)$) to [out=45,in=135] ($(B)+(0.15, -0.15)$);
        % Filled Node
        \fill (D) circle(2pt);
    \end{tikzpicture}
\end{document}

and its output:


text:
Q: Quadratic variation of logarithm of Bessel process I am currently looking at the exposition of the Bessel process given in Bass, Stochastic Processes, chapter 24 (page  200 onwards).
The squared Bessel process of order $\nu  \geq 0$ starting as $y$ is defined as satisfying the SDE:
$$
\begin{align*}
\mathrm{d} Y_t = 2\sqrt{Y_t}\mathrm{d}W_t + \nu\,\mathrm{d}t && Y_0 = y
\end{align*}
$$
In proposition 24.7, it is claimed that for $\nu = 2$, the quadratic variation of $\log Y$ up to $t$ is $\int_0^t\!\mathrm{d}s\,Y_s^{-2}$. Yet, from the following calculation:
$$
\begin{align*}
\mathrm{d} \log Y_t & = \frac{\mathrm{d} Y_t} {Y_t} - \frac{1}{2}\frac{\mathrm{d}\langle Y \rangle_t}{Y_t^2}\\
& = \frac{2}{\sqrt{Y_t}}\mathrm{d}W_t + \frac{\nu - 2}{Y_t}\mathrm{d}t\\
& = \frac{2}{\sqrt{Y_t}}\mathrm{d}W_t
\end{align*}
$$
I rather find $4\int_0^t\!\mathrm{d}s\,Y_s^{-1}$. Did I miss anything?

A: Perhaps they meant that the log of the Bessel process define as $R_t = Y_t^2$ has this particular quadratic variation.
Indeed, we know that the dynamic of $R_t$ is
\begin{equation}
dR_t = dW_t +\frac{\nu-1}{2}\frac{1}{R_t}dt
\end{equation}
Therefore, we have by Ito's lemma:
\begin{equation}
d\log(R_t) = \frac{1}{R_t}dW_t
\end{equation}
You can see the quadratic variation of the above process is$\int_0^t\!\mathrm{d}s\,R_s^{-2}$.


text:
Q: Entity Framework - Handling a join with no records from join table I searched vigorously for an answer to this, but I was unable to find (or understand) a solution. I have a query where I am joining to another table that may or may not have associated records. Here is the query:
  var educationUniversity = result.new_educationUniversity.Select(c => new
    { c.majorDegree, c.dateEnd, c.dateStart, c.institutionName,
      c.degreeProgramCompletionStatus, c.institutionAddress,
      attachmentId = c.attachmentId ?? 0,
      fileName = c.new_attachments.fileName ?? "No Attachment"}).ToList();

The first table is "new_educationUniversity" and it holds details of a user's college or university degree. The user may or may not have uploaded an attachment (which is stored in the "new_attachments" table). The attchmentID is the primary key in the "new_attachments" table and a foreign key in the "new_educationUniversity" table. EF sees the relationship.
I am binding the results to a repeater but the code fails on the line above if there is no related attachment. Everything works fine if there is an attachment or if I remove the reference to the fileName.
Above, I am handling if the fileName is NULL (or at least I am trying to), but I suspect my issue is that the record simply doesn't exist, which is different from NULL I guess. I've tried using something like: c.new_attachments.fileName.SingleOrDefault() or DefaultIfEmpty() with no luck.
As an analogy, imagine you have a CUSTOMERS table and an ORDERS table. You want to query the following:
-customer last name
-customer first name
-customer most recent order Id
However, you have registered customers who have never purchased anything. I'm sure I am doing something completely noobish, so any assistance is GREATLY appreciated. Thanks!

A: So you have a few things going on here:

*

*You can get a null reference exception on your reference to c.new_attachments.fileName.  If new_attachments is null, then this will throw an exception.  Including the null-coalescing operator (the ??) won't help, because you're trying to access the property of something which can be null.

*Unless you're lazy-loading (generally bad), then there's no reason for you to be trying to create a dynamically typed object to send to your repeater.  Just pass the result.new_educationUniversity object directly.

What's the solution?
I'd create a partial class to add a new property to your new_educationUniversity class.  Add a null-reference-safe property reference to determine the file name of the new_attachments property of new_educationUniversity.  Then, bind the repeater to your new property.  Something like:
public partial class new_educationUniversity {
    public String AttachmentFileName {
        get {
            if (new_attachments == null)
                return "";
            else
                return new_attachments.fileName;
        }
    }
}

A: The following line of code seems to be working.
 var educationUniversity = result.new_educationUniversity.Select
(c => new { c.majorDegree, c.dateEnd, c.dateStart, c.institutionName,
c.degreeProgramCompletionStatus, c.institutionAddress, attachmentId = c.attachmentId ?? 0,
 fileName = (c.new_attachments == null ? "***NO ATTACHMENT***" : c.new_attachments.fileName)}).ToList();

I don't fully understand what this line means:
fileName = (c.new_attachments == null ? "***NO ATTACHMENT***" : c.new_attachments.fileName)}

I assume it says "if nothing is there replace with the string "NO ATTACHMENT" otherwise use what is in the DB"
Is this acceptable? So far, so good. Thanks!


text:
Q: How to plot and solve the numerical solution of a integro-differential equation I have a integro-differential equation of the form
$y'(t) =  - \int_0^t {y(t_1 )} e^{t_1  - t} dt_1,  {\rm{ t}} \in {\rm{[0,10], y(0) = 1}}$
My code is:
f[t_Real] := NIntegrate[y[t1]*Exp[t1-t], {t1, 0, t}];

solution1=NDSolve[{D[y[t], t]==-f[t], y[0] == 1}, y[t], {t, 0, 10}];

Plot[Evaluate[y[t] /. solution1], {t, 0, 10}, PlotRange -> All]

But this simply outputs the error:

NIntegrate::nlim: t1 = t is not a valid limit of integration.

A: This is probably what @Guess who it is. had in mind in the comment posted under the question.
solution1 = NDSolve[{
    D[y[t], t] == -Exp[-t] f0[t], y[0] == 1,
    f0'[t] == y[t]*Exp[t], f0[0] == 0},
   y[t], {t, 0, 10}];

Plot[Evaluate[y[t] /. solution1], {t, 0, 10}, PlotRange -> All]

Comparison with Jens's exact solution and how well the combined PrecisionGoal/AccuracyGoal is satisfied:
jsol = (E^(-t/2) (Sqrt[3] Cos[(Sqrt[3] t)/2] + Sin[(Sqrt[3] t)/2])) / Sqrt[3];
Plot[Evaluate[{y[t] - jsol /. solution1,
      {1, -1} (10^-(MachinePrecision/2.) + 10^-(MachinePrecision/2.) jsol)} // Flatten],
 {t, 0, 10}]

A: This integral equation is solvable using the LaplaceTransform technique:
Clear[s, t];
eqn = y'[t] == -Integrate[y[t1] Exp[t1 - t], {t1, 0, t}]

LaplaceTransform[eqn, t, s]

(*
==>
s LaplaceTransform[y[t], t, s] - y[0] == -(
  LaplaceTransform[y[t], t, s]/(1 + s))
*)

Solve[%, LaplaceTransform[y[t], t, s]]

(*
==> {{LaplaceTransform[y[t], t, s] -> ((1 + s) y[0])/(
   1 + s + s^2)}}
*)

InverseLaplaceTransform[%, s, t]

(*
==> {{y[t] -> (
   E^(-t/2) (Sqrt[3] Cos[(Sqrt[3] t)/2] + Sin[(Sqrt[3] t)/2]) y[0])/
   Sqrt[3]}}
*)

ySolution[t_] = y[t] /. First[%] /. y[0] -> 1

(*
==> (E^(-t/
  2) (Sqrt[3] Cos[(Sqrt[3] t)/2] + Sin[(Sqrt[3] t)/2]))/Sqrt[3]
*)

Plot[ySolution[t], {t, 0, 10}]


text:
Q: Fetch dynamic content by latitude and longitude Android I am using Yelp API and right now I am using static method to make an API call as per location and term. I want to make this dynamic and on click of button I should hit the API and get the list of restaurants as per my current location i.e. latitude and longitude. I did try this below code but does not work.
MainActivity.java
    package com........projectmaw;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    double latitude; // Latitude
    double longitude; // Longitude

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        /*
        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });*/

        Log.v("TAG", "MainOnCreate");
        Button searchButton = (Button) findViewById(R.id.restCall);
        Log.v("TAG", "Button Created");
        searchButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // instantiate the location manager, note you will need to request permissions in your manifest
                LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                // get the last know location from your location manager.
                if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                // now get the lat/lon from the location and do something with it.
                latitude = location.getLatitude();
                longitude = location.getLongitude();
                Log.d("Lat and Lon", "lat " + latitude + " " + "Lon " + longitude);
                search();
            }
        });

}

    public void search() {
        Log.v("TAG", "search");
        Intent intent = new Intent("android.intent.action.YELPSEARCH");
        startActivity(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.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();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

}/* End of MainActivity Activity */

Yelp.java
import android.content.Context;
import android.util.Log;

import org.scribe.builder.ServiceBuilder;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.oauth.OAuthService;

public class Yelp {

    OAuthService service;
    Token accessToken;

    static String YELP_CONSUMER_KEY ="xxxxxxxxxxxxxxxxxxxx";
    static String YELP_CONSUMER_SECRET = "xxxxxxxxxxxxxxxxxxxx";
    static String YELP_TOKEN = "xxxxxxxxxxxxxxxxxxxx";
    static String YELP_TOKEN_SECRET = "xxxxxxxxxxxxxxxxxxxx";

    public static Yelp getYelp(Context context) {
        return new Yelp(YELP_CONSUMER_KEY, YELP_CONSUMER_SECRET,
                YELP_TOKEN, YELP_TOKEN_SECRET);
    }

    public Yelp(String consumerKey, String consumerSecret, String token, String tokenSecret) {
        this.service = new ServiceBuilder().provider(TwoStepOAuth.class).apiKey(consumerKey).apiSecret(consumerSecret).build();
        this.accessToken = new Token(token, tokenSecret);
    }

    public String search(String term, String location) {
        Log.v("TAG","YelpSearch");
        OAuthRequest request = new OAuthRequest(Verb.GET, "http://api.yelp.com/v2/search");
        request.addQuerystringParameter("term", term);
        request.addQuerystringParameter("location", location);
        this.service.signRequest(this.accessToken, request);
        Log.v("TAG","Before Response");
        Response response = request.send();
        Log.v("TAG","response :"+response.getBody());
        return response.getBody();
    }

}

YelpHelper.java
import android.app.ListActivity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

public class YelpSearch extends ListActivity implements Serializable {

    @SuppressWarnings("serial")
    class Business implements Serializable {
        final String name;
        final String url;
        final String id;
        final String rating;

        public Business(String name, String url, String id, String rating) {
            this.name = name;
            this.url = url;
            this.id = id;
            this.rating = rating;
        }

        @Override
        public String toString() {
            return "name :"+name+""+"ID : "+id;
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        super.onCreate(savedInstanceState);
        setTitle("Finding Tacos...");
        setProgressBarIndeterminateVisibility(true);
        Log.v("TAG","YelpSearchOnCreate");

        new AsyncTask<Void, Void, List<Business>>() {
            @Override
            protected List<Business> doInBackground(Void... params) {
                Log.v("TAG","Async List");

                String businesses = Yelp.getYelp(YelpSearch.this).search("food", "91754");
                Log.v("TAG","String businsesses"+businesses);
                try {
                    Log.v("TAG","try");
                    return processJson(businesses);
                } catch (JSONException e) {
                    return Collections.<Business>emptyList();
                }
            }

            @Override
            protected void onPostExecute(List<Business> businesses) {
                Log.v("TAG","onPostExecute");
                Log.v("BusinessesList","Businesses "+ businesses);
                //setTitle("Tacos Found");
                setProgressBarIndeterminateVisibility(false);
                getListView().setAdapter(new ArrayAdapter<Business>(YelpSearch.this, android.R.layout.simple_list_item_1, businesses));

            }
        }.execute();
    }

    @Override
    protected void onListItemClick(ListView listView, View view, int position, long id) {
        Business biz = (Business) listView.getItemAtPosition(position);
        Log.v("Sending data to Detail","hi "+biz);
        startActivity(new Intent(getApplicationContext(), YelpBizDetail.class).putExtra("Detailclass",biz));
    }

    List<Business> processJson(String jsonStuff) throws JSONException {
        JSONObject json = new JSONObject(jsonStuff);
        JSONArray businesses = json.getJSONArray("businesses");

        ArrayList<Business> businessObjs = new ArrayList<Business>(businesses.length());
        for (int i = 0; i < businesses.length(); i++) {
            JSONObject business = businesses.getJSONObject(i);
            businessObjs.add(new Business(business.optString("name"), business.optString("mobile_url"),business.optString("id"),business.optString("rating")));
        }
        return businessObjs;
    }
}

How do I make this work.


text:
Q: I have many spam customer in Magento 1.9 so how can i remove? Guy's I have a Magento 1.9 site and some days ago I check my admin side so found lot's of spam customer so I can add google Recaptcha at that time.
But it already has many customers are in site so how can I remove in my site if any suggestions like any module or custom script so please help me.

A: You have create root script this way and filter one by one like
@qq.com and remove it
<?php

 /**
 * Delete Customers
 *
 */
require 'app/Mage.php';
Mage::app('admin')->setUseSessionInUrl(false);

$customerCollection = Mage::getModel("customer/customer")
                ->getCollection()
                ->addAttributeToFilter('email', array('like' => '%@qq.com'));

# $customerCollection->printLogQuery(true);

$customerIds = array();
foreach ($customerCollection as $customer) {
    $customerIds[] = $customer->getEntityId();
}

$customerCollectionNew = Mage::getModel('customer/customer')->getCollection()
                ->addAttributeToFilter('entity_id', array('in' => $customerIds))

if ($customerCollectionNew->count()) {
    foreach ($customerCollectionNew as $customer) {
        try {
            $id = $customer->getId();
            $customer->delete();
            echo 'Customer '.$id.' is deleted.
';

            Mage::log('Customer '.$id.' is deleted.
', null, "customer-delete.log");
        } catch (Exception $e) {
            echo "Customer ".$id." is deleted: " . $e->getMessage() . '
';
            Mage::log("Customer ".$id." could not be removed: " . $e->getMessage(), null, "customer-delete.log");
        }
    }
    echo "
";
    echo "Completed.";
    Mage::log("Completed.", null, "customer-delete.log");
}

Note: I have no test my code you can check it taken one email address


text:
Q: Resuming an application from sleep causes 'Communications link failure' I have a CloudBees Run@cloud instance configured that runs fine, but after a while of inactivity it gets de-activated, and then seems the connection pool is not properly refreshed.
When I return to the site, the first few requests time out with:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 4,746,680 milliseconds ago.  The last packet sent successfully to the server was 0 milliseconds ago.
    sun.reflect.GeneratedConstructorAccessor86.newInstance(Unknown Source)
    sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
    java.lang.reflect.Constructor.newInstance(Constructor.java:513)
    com.mysql.jdbc.Util.handleNewInstance(Util.java:407)
    com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1116)
    com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3092)
    com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2978)
    com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3526)
    com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1989)
    com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2150)
    com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2620)
    com.mysql.jdbc.ConnectionImpl.setAutoCommit(ConnectionImpl.java:5022)
    org.apache.tomcat.dbcp.dbcp.DelegatingConnection.setAutoCommit(DelegatingConnection.java:371)
    org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.setAutoCommit(PoolingDataSource.java:328)
    org.hibernate.transaction.JDBCTransaction.begin(JDBCTransaction.java:87)
    org.hibernate.impl.SessionImpl.beginTransaction(SessionImpl.java:1473)

I am connecting via JNDI using a datasource configured in the cloudbees-web.xml file as such:
    <resource name="jdbc/myapp" auth="Container" type="javax.sql.DataSource">
        <param name="username" value="myuser" />
        <param name="password" value="mypass" />
        <param name="url" value="jdbc:cloudbees://myurl />
    </resource>

Is there some configuration I'm missing, or is this a bug with the connection pool configuration in the server?

A: [From the Database Guide on the CloudBees Wiki]
MySQL includes a timeout that will close connections that have been idle for long periods of time. For improved Database performance, CloudBees DataSources use the Apache DBCP connection pool to reuse JDBC connections after they are closed by the application.
If you use a connection that has been in the pool idle for too long, your application will likely experience the following error: "The last packet successfully received from the server was XXX seconds ago".
The connection pool includes a setting the will validate and throw out dead connections when calling javax.sql.DataSource.getConnection(). To use this setting, add the following XML params to your DataSource definition in cloudbees-web.xml.
<param name="validationQuery" value="SELECT 1" />
<param name="testOnBorrow" value="true" />

So for your resource, you should be able to do the following:
<resource name="jdbc/myapp" auth="Container" type="javax.sql.DataSource">
    <param name="username" value="myuser" />
    <param name="password" value="mypass" />
    <param name="url" value="jdbc:cloudbees://myurl />
    <param name="validationQuery" value="SELECT 1" />
    <param name="testOnBorrow" value="true" />
</resource>

If you are using the bees app:bind command instead of cloudbees-web.xml to inject your datasources, you can use these params as arguments to the command
bees app:bind -a APP_ID -db DB_NAME -as JNDI_ALIAS validationQuery="SELECT 1" testOnBorrow=true


text:
Q: Salesforce Identity Connect and AD user management If a user is deleted from Active Directory, is the corresponding user record deleted or simply deactivated from Salesforce data store?

A: Users cannot be deleted from a Salesforce org, the user would be deactivated.


text:
Q: GridbagLayout with JTextField and JButton, reformats when JButton visible I have GridBagLayout where I add a JLabel, a JTextfield and two JButtons with and image, the image is 25x25 pixel. Whenever I show or hide the button the whole layout moves. I tried to setSize(), setMinimumSize(), setPreferredSize() and setMaximumSize() but it will just ignore that an resize the JLabel and the JTextField. How can I set a fix size for these two components or just make all the cells in the GridBagLayout the same size.
Demo
JPanel panel = new JPanel();
panel.setLayout(new GridBagLayout());

GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.5;

c.gridx = 0;
c.gridy = 0;
panel.add(new JLabel("Auftrag Nummer:"), c);

JTextField orderNumberField = new JTextField();
c.gridx = 1;
c.gridy = 0;
panel.add(orderNumberField, c);

JButton searchButton = DefaultLayouts.imageButton("SEARCH");
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(10, 0, 0, 0);
panel.add(searchButton, c);

JButton checkButton = DefaultLayouts.imageButton("CHECK");
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(10, 0, 0, 0);
panel.add(checkButton, c);

DefautlLayouts.imageButton gets the path and the tooltip and sets some defaults
public static JButton imageButton(String propertiesName) {
    JButton button = DefaultLayouts.button();
    button.setIcon(new ImageIcon(imagesProperties.getProperty(propertiesName + "_PATH")));
    button.setToolTipText(imagesProperties.getProperty(propertiesName + "_TOOLTIP"));

    button.setContentAreaFilled(false);
    button.setFocusPainted(false);
    button.setBorder(BorderFactory.createEmptyBorder());

    return button;
}

A: One option you have is that, you can envelope the buttton with a JPanel that has constant size, then if you hide button, the JPanel will still be there to hold the space.

A: I solved this problem with an empty png that is 25x25 pixel that is at the same position as the button that gets shown and hidden.
Will updated this in the future with a better solution.
Edit
I used the DesigneGridLayout to solve this problem.
JPanel panel = DefaultLayouts.panel();
DesignGridLayout layout = new DesignGridLayout(panel);

JTextField orderNumberField = new JTextField();
JButton searchButton = DefaultLayouts.imageButton("SEARCH");
JButton checkButton = DefaultLayouts.imageButton("CHECK");

layout.row().grid().add(new JLabel("Auftrag Nummer:")).add(orderNumberField);
layout.emptyRow();
layout.row().grid().add(searchButton).add(checkButton);

A: In addition to setting the components whose sizes you would like to keep static on a JPanel with a specified dimension, If the layout is the dominant one on the frame, try using frame.setResizable(false);.


text:
Q: How to send message to Azure event hub with amqp using JMeter How to send message to Azure event hub with amqp using JMeter.
can anyone please help in this regard.

A: *

*Download azure-messaging-eventhubs  library and all its dependencies and drop them to JMeter Classpath

*Restart JMeter to pick the libraries up

*Add JSR223 Sampler to your Thread group

*Write Java (or even better Groovy) code implementing your scenario in the JSR223 Sampler. Example code can be found at Use Java to send events to or receive events from Azure Event Hubs (azure-messaging-eventhubs) article, I'll add it here just in case:
import com.azure.messaging.eventhubs.*

final String connectionString = 'EVENT HUBS NAMESPACE CONNECTION STRING'
final String eventHubName = 'EVENT HUB NAME'

// create a producer using the namespace connection string and event hub name
EventHubProducerClient producer = new EventHubClientBuilder()
        .connectionString(connectionString, eventHubName)
        .buildProducerClient()

// prepare a batch of events to send to the event hub
EventDataBatch batch = producer.createBatch()
batch.tryAdd(new EventData('First event'))
batch.tryAdd(new EventData('Second event'))
batch.tryAdd(new EventData('Third event'))
batch.tryAdd(new EventData('Fourth event'))
batch.tryAdd(new EventData('Fifth event'))

// send the batch of events to the event hub
producer.send(batch)

// close the producer
producer.close()


text:
Q: Using CPU heat to generate electricity I've been reading Tanenbaum's Structured Computer Organization and he says one of the major bottlenecks for increasing CPU clock speed is heat. So I started thinking: Is it possible to remove the heatsink altogether and use that heat to generate more electricity? I've been searching on this and found these thermoelectric materials and this thermoelectric generator:

I read on that Wikipedia article that "Silicon-germanium alloys are currently the best thermoelectric materials around 1000 °C (...)", and I know CPU normally operate around 30~40°C. So, getting to 1000 °C would require more CPUs.
So I thought: What about putting a lot of CPUs in parallel without their heatsinks to gather more heat? We can also overclock these CPUs a whole lot and see how much heat they can generate.
But I'm stuck. I don't know what to think next. I don't even know if it's a good line of thought.
My question is: why not develop some sort of heatsink that generates electricity from the CPU's heat? I know somebody must already have thought about that and thought about a reason why not to do it, but I can't figure it out.
So, why is it not possible?

EDIT for clarification: I do not want CPUs to work at 1000 °C. I'll list my reasoning steps (not necessarily correct), which were roughly:

*

*CPU clock speed is limited by working temperature (T).

*CPUs generate heat. Heat makes T rise.

*Heatsinks take care of that heat in order to maintain T=40°C.

*Replace heatsink with thermoelectric generator (built from SiGe or similar material)

*Put a lot of CPUs side by side to increase heat generation.

*Heat comes out the CPUs to TEG, so CPUs stays at T=40°C.

*Is this possible?

*How to build such a TEG? Which material to use?

*Why such device doesn't exist already?

*Asked this question.

EDIT2: I see that my idea is fundamentally wrong and bad. Thanks for all the answers and comments. Sorry about any misunderstandings.

A: The issue with thermoelectric generators is they are horrendously inefficient.
For a CPU you HAVE to get rid of the heat they produce or they melt down.
You could hook up a peltier module and extract a small amount of electricity from them but you would still need to dissipate the remainder of the heat via a classical heat exchange method. The amount of electricity generated would likely not be significant enough to warrant the cost of the setup.
You CAN also use peltiers as coolers. However, you need to ADD power to pump out the heat. That power then needs to be dissipated along with the heat you are removing via the heat-exchanger. In the end the latter needs to be larger so your net effect is worse.
Heat to power is a "holy grail" idea and is up there with cold fusion as a theoretical dream.
EDITED FOR CLARITY
Efficient DIRECT conversion from heat to electricity is a "holy grail" idea and is up there with cold fusion as a theoretical dream.

A: Funny thinking, but no. Your CPU is not just a chip, there are bonding wires and a casing involved which would not exactly stand a chance at 1000°C.
That aside, there are still some laws of thermodynamics to be considered. You still have to put in a huge amount of energy into the system to get very little out.
The Peltier element you are referring needs a big dT (difference between cold and hot side) so simply removing the heat sinks will bring up the "cold" side to the same temperature as the hot side, so no more energy to be gained here, you'll need to cool the cold Side which will ruin the efficiency even more. On the other hand those Peltier elements can be used to generate a temperature difference as in cooling the CPU.

A: The laws of thermodynamics state that putting together two energy sources of the same temperature don't equate to a higher energy level. For example, putting pouring a cup of hot water into another cup of hot water doesn't make the combination any hotter than the separate cups.
Heat is also one of the lowest forms of energy in that there is very little you can do with it. Electricity can run circuits, wind can create mechanical motion, but heat can't do much beyond putting more energy into a fluid or solid.
That said, the most feasible method of getting energy from heat is boiling a fluid (water for instance) to turn a turbine. Putting multiple heat sinks together and attached to a tub might make water boil if the CPU's are all above 100 C. But, as you can probably infer, this is a terrible idea.

A: In theory, it is possible.  All you need is some "substance" that generates electricity when one of its surfaces is at 40c and the other is at 20c.
Currently, there are thermocouples that do exactly this (change heat to electricity), but at a much higher temperature.

A: For generating electricity, you want the hot side (processor) to be as hot as possible for maximum efficiency. The thermal generator slows down the movement of heat as it extracts energy from it.
For doing computation, you want the processor to be as cold as possible. Higher temperatures increase the electrical resistance of the silicon. This is why you have highly-conductive heatsinks, fans etc: to move heat away as fast as possible.
These requirements directly contradict one another.

A: Surprised that nobody else has mentioned this:
Generating electricty from the waste heat from some process that burns fuel can make sense.  Generating electricity from the waste heat from a system that is powered by electricity in the first place?  That makes no sense.  If it's possible for you to save energy by doing that, then it's possible for you to save even more energy by building a system that uses electricity more efficiently in the first place.

A: tl;dr
Yes, you can extract a small amount of power from a CPU's waste heat, but your heat sink must be the bigger the more power you want to extract.
explanation
There is no machine which converts heat into power, only machines which convert heat difference into power. In your case, that difference is the one between the CPU temperature and the environment temperature. The maximum theoretical efficiency for this process is (1 - T_cold / T_hot), so for an environment temperature of 25 deg C, a CPU temperature of 40 deg C and a heat flow of 50W you could generate 2.4 watts of electricity with an ideal converter (the temperatures are absolute temperatures in Kelvins). If you allow the CPU to reach 60 deg C, you can get up to 5 watts, and if you allow 100 deg C, you can get up to 10 watts. Real-life heat-to-power converters are more inefficient, especially thermoelectric elements. I'd recommend a stirling engine, which is closer to the ideal efficiency.
This is how heat flows with a passive heatsink:
[CPU] --> [Environment]
The CPU-to-Environment junction has a thermal resistance, measured in Kelvins/Watt, directly equivalent to how electrical resistance is measured in Volts/Ampere. You might have encountered Kelvin/Watt values in some datasheets. An ideal heatsink has zero resistance, so the temperature difference is 0 and the CPU operates at environment temperature (25 deg C). With a real-life heatsink of 0.5K/W and a heat flow of 50W (the CPU generates 50W of heat), the temperature difference is 25K and the CPU is at 50 deg C.
This is how heat flows with your proposed machine:
[CPU] --> [Hot end of machine] --> [Cold end of machine] --> [Environment]
There are thermal resistances, i.e. temperature differences, at all three points.
Let us assume that the connection between CPU and hot end of machine is ideal, i.e. they are at the same temperature.
The thermal resistance inside the machine is used to generate electricity.
The thermal resistance between the cold end and the environment is given by the cold-end heat sink.
Say the heat sink at the cold end is the same that we used for the CPU, with 0.5K/W, and we want the CPU to be at 50 deg C. Then the cold end of the machine is already at 50 deg C, and there can be  no temperature difference over the machine, i.e. it can generate no power. If we use a heat sink twice was big (0.25K/W), then the cold end will be at 37.5 deg C and the temperature difference over the machine is 12.5 deg C, so it can generate a little bit of power.
Any machine that extracts power from a temperature difference poses a thermal resistance equal to (temperature difference)/(Heat flow).
The thermal resistance of the machine is added to the thermal resistance of the heatsink, so the CPU temperature will always be hotter if there is a machine in between.
BTW Some overclockers go the opposite way: They add a thermoelectric element which runs in reverse, using electric power to pump heat from the CPU to the heatsink, creating a negative temperature difference. The CPU is at the cold end, and the heatsink is at the hot end.
BTW This is why nuclear power plants have enormous cooling towers, which work as the cold-end heat sink.


text:
Q: DevExpress RepositoryItemTextEdit Appearance TextOptions WordWrap=Wrap not working When I go into the In-Place Editor Repository and set the WordWrap property = Wrap on a TextEdit (it is being used as the editor in the Vertical Grid) there is no wrapping at runtime. The text tickertapes instead.
My users are clamoring for wordwrap, and they also want to see the text in the field too --not like the MemoExEdit which displays a two-state icon: "empty" and "has some text" and the user only gets to see the text when they give the editor focus.
Is it possible to get wordwrap on an in-place TextEdit? Or is that property setting ignored?

A: TextEdit is a single-line editor.
You should use MemoEdit instead.

A: The MemoExEdit can be used as well. Simply set the ShowIcon property to false and the text in the field will be displayed instead of the icon.


text:
Q: Creating Supplier stream of Stream I am creating a Supplier Stream of String and working on the same.
public void test(Stream<String> s) {
    Supplier<Stream<String>> streamSupplier = () -> s;

    System.out.println(streamSupplier.get().count());

    streamSupplier.get().parallel()
        .collect(Collectors.groupingBy(it -> counter.getAndIncrement() / 2))
        .values()
        .stream()
        .forEach(input -> {
            System.out.println("input " + input);
        });

I am getting an error "stream has already been operated upon or closed" when I try to work with the stream. How can I resolve this. Thank you.

A: Not really sure what you are trying to achieve with this one, but a stream can only be used once. Quoting from the documentation:

A stream should be operated on (invoking an intermediate or terminal stream operation) only once. This rules out, for example, "forked" streams, where the same source feeds two or more pipelines, or multiple traversals of the same stream. A stream implementation may throw IllegalStateException if it detects that the stream is being reused. However, since some stream operations may return their receiver rather than a new stream object, it may not be possible to detect reuse in all cases.

I think that you want to have a re-usable stream, so in this case I would suggest you pass in the original collection instead of the Stream of this collection dataset.


text:
Q: Variable within a variable javascript I need to call a variable from within a variable.
I have a variable called vmX_cores. I need to loop through the vms I have and call that variable dynamically.
var vms = ["vm1", "vm2", "vm3"];
var totalVms = vms.length;

var vm1_cores = 2;
var vm2_cores = 4;
var vm3_cores = 8;

function ifScript() {
   if (totalVms == 0) {
      return 'done';
   } else {
      var curVM = vms[totalVms - 1];
      var variableToUse = curVM + '_cores';
      totalVms--;
      return 'notDone';
   }
}

When I call variableToUse this returns "vmX_cores" but I need it to return the number not a string.

A: You can use window[vmX_cores] to get the value of that variable string.
eg :
var x = window["vm1_cores"]
In your case :
var x = window[variableToUse]

A: A global variable is accessible as a property of the global object, which is window for a browser and global for node. See Getting a reference to the global object in an unknown environment in strict mode
Since you have the name of the variable/property, you can use bracket access.
// This code works in ES3, ES5 and strict mode to get the global object
var globalObj = (function(){ return this || (1,eval)('this') })();
var variableToUse = curVM + '_cores';
var actualValue = globalObj[variableToUse];


text:
Q: How to show that $\lim_{r\to0} U(r)=0$ in the radial differential equation? We have the following differential equation:
$$\left({- \hbar ^2 \over 2 \mu } \frac{d^2}{dr^2} + {\hbar^2 \ell(\ell+1) \hbar^2 \over 2 \mu r^2} + V(r) \right)U(r)= EU(r)$$
in order to find the eigenvector $\psi (\mathbf{r})$ which it is the unique  basis for $H$ , $L_z$ and $L$.
We know that the effective potential $${\hbar^2 \ell(\ell+1) \hbar^2 \over 2 \mu r^2}$$ represents the centrifugal force which pushes the particle outward. It is necessary to know the behaviour of $U(r)$ or $V(r)$ at the origin $r=0$.
In the lecture, they indicated  $\lim_{r\to 0} U(r)=0$, but I can't find a way to get this result. Could you explain "what's going on", mathematically and physically? By physically I mean that when the radius is too small the radial function vanishes; what's behind this result?

A: This derivation utilises the idea of 3D isotropic harmonic oscillator, and is not simply based, but is a total line by line replication of part of  this  article Wikipedia 3D isotropic harmonic oscillator.
The article above linked above is a  page I would urge the OP to read, also I would encourage the OP to  watch and take notes on the relevant YouTube videos by J. Binney (Oxford) and L. Susskind (Stanford).

The potential of a 3D isotropic harmonic oscillator is

${\displaystyle V(r)={\frac {1}{2}}m_{0}\omega ^{2}r^{2}.}$

In this article it is shown that an N-dimensional isotropic harmonic oscillator has the energies

$${\displaystyle E_{n}=\hbar \omega {\Bigl (}n+{\frac {N}{2}}{\Bigr )}\quad {\text{with}}\quad n=0,1,\ldots ,\infty ,}$$

i.e., n is a non-negative integral number; $ω$ is the (same) fundamental frequency of the $N$ modes of the oscillator. In this case $N= 3$, so that the radial Schrödinger equation becomes,

$${\displaystyle \left[-{\hbar ^{2} \over 2m_{0}}{d^{2} \over dr^{2}}+{\hbar ^{2}l(l+1) \over 2m_{0}r^{2}}+{\frac {1}{2}}m_{0}\omega ^{2}r^{2}-\hbar \omega {\bigl (}n+{\tfrac {3}{2}}{\bigr )}\right]u(r)=0.}$$

Introducing

$${\displaystyle \gamma \equiv {\frac {m_{0}\omega }{\hbar }}}$$

and recalling that ${\displaystyle u(r)=rR(r)\,}$, we will show that the radial Schrödinger equation has the normalized solution,

$${\displaystyle R_{n,l}(r)=N_{nl}\,r^{l}\,e^{-{\frac {1}{2}}\gamma r^{2}}\;L_{{\frac {1}{2}}(n-l)}^{(l+{\frac {1}{2}})}(\gamma r^{2}),}$$

where the function ${\displaystyle L_{k}^{(\alpha )}(\gamma r^{2})}$ is a generalized Laguerre polynomial in $γr^2$ of order $k$ (i.e., the highest power of the polynomial is proportional to $γkr^2k$).
The normalization constant $N_{nl} is,

$${\displaystyle N_{nl}=\left[{\frac {2^{n+l+2}\,\gamma ^{l+{\frac {3}{2}}}}{\pi ^{\frac {1}{2}}}}\right]^{\frac {1}{2}}\left[{\frac {[{\frac {1}{2}}(n-l)]!\;[{\frac {1}{2}}(n+l)]!}{(n+l+1)!}}\right]^{\frac {1}{2}}.}$$

The eigenfunction $R_n,l(r)$ belongs to energy $E_n$ and is to be multiplied by the spherical harmonic ${\displaystyle Y_{lm}(\theta ,\phi )\,}$, where

$${\displaystyle l=n,n-2,\ldots ,l_{\min }\quad {\hbox{with}}\quad l_{\min }={\begin{cases}1&\mathrm {if} \;n\;\mathrm {odd} \\0&\mathrm {if} \;n\;\mathrm {even} \end{cases}}}$$

This is the same result as given in this article if we realize that ${\displaystyle \gamma =2\nu \,}$.
Derivation
First we transform the radial equation by a few successive substitutions to the generalized Laguerre differential equation, which has known solutions: the generalized Laguerre functions. Then we normalize the generalized Laguerre functions to unity. This normalization is with the usual volume element $r^2 dr$.
First we scale the radial coordinate

$${\displaystyle y={\sqrt {\gamma }}r\quad {\hbox{with}}\quad \gamma \equiv {\frac {m_{0}\omega }{\hbar }},}$$

and then the equation becomes

$${\displaystyle \left[{d^{2} \over dy^{2}}-{l(l+1) \over y^{2}}-y^{2}+2n+3\right]v(y)=0}$$

with $${\displaystyle v(y)=u\left(y/{\sqrt {\gamma }}\right)}$$
Consideration of the limiting behaviour of $v(y)$ at the origin and at infinity suggests the following substitution for $v(y)$,

$${\displaystyle v(y)=y^{l+1}e^{-y^{2}/2}f(y).}$$

This substitution transforms the differential equation to

$${\displaystyle \left[{d^{2} \over dy^{2}}+2\left({\frac {l+1}{y}}-y\right){\frac {d}{dy}}+2n-2l\right]f(y)=0,}$$

where we divided through with ${\displaystyle y^{l+1}e^{-y^{2}/2}}$, which can be done so long as $y$ is not zero.
Transformation to Laguerre polynomials
If the substitution ${\displaystyle x=y^{2}\,}$ is used, ${\displaystyle y={\sqrt {x}}}$, and the differential operators become

$${\displaystyle {\frac {d}{dy}}={\frac {dx}{dy}}{\frac {d}{dx}}=2y{\frac {d}{dx}}=2{\sqrt {x}}{\frac {d}{dx}},{\text{ and }}}{\displaystyle {\frac {d^{2}}{dy^{2}}}={\frac {d}{dy}}\left(2y{\frac {d}{dx}}\right)=4x{\frac {d^{2}}{dx^{2}}}+2{\frac {d}{dx}}.}$$

The expression between the square brackets multiplying $f(y)$ becomes the differential equation characterizing the generalized Laguerre equation :

$${\displaystyle x{\frac {d^{2}g}{dx^{2}}}+{\Big (}(l+{\frac {1}{2}})+1-x{\Big )}{\frac {dg}{dx}}+{\frac {1}{2}}(n-l)g(x)=0}$$

with ${\displaystyle g(x)\equiv f({\sqrt {x}})\,\;}$.
Provided ${\displaystyle k\equiv (n-l)/2\,}$ is a non-negative integral number, the solutions of this equations are generalized (associated) Laguerre polynomials

$${\displaystyle g(x)=L_{k}^{(l+{\frac {1}{2}})}(x).}$$

From the conditions on $k$ follows: (i) ${\displaystyle n\geq l\,}$ and (ii) n and l are either both odd or both even. This leads to the condition on $l$ given above.
Recovery of the normalized radial wavefunction
Remembering that ${\displaystyle u(r)=rR(r)\,}$, we get the normalized radial solution

$${\displaystyle R_{n,l}(r)=N_{nl}\,r^{l}\,e^{-{\frac {1}{2}}\gamma r^{2}}\;L_{{\frac {1}{2}}(n-l)}^{(l+{\frac {1}{2}})}(\gamma r^{2}).}$$

The normalization condition for the radial wavefunction is

$${\displaystyle \int _{0}^{\infty }r^{2}|R(r)|^{2}\,dr=1.}$$

Substituting ${\displaystyle q=\gamma r^{2}\,\;}$, gives ${\displaystyle dq=2\gamma r\,dr\,\;}$ and the equation becomes

$${\displaystyle {\frac {N_{nl}^{2}}{2\gamma ^{l+{3 \over 2}}}}\int _{0}^{\infty }q^{l+{1 \over 2}}e^{-q}\left[L_{{\frac {1}{2}}(n-l)}^{(l+{\frac {1}{2}})}(q)\right]^{2}\,dq=1.}$$

By making use of the orthogonality properties of the generalized Laguerre polynomials, this equation simplifies to

$${\displaystyle {\frac {N_{nl}^{2}}{2\gamma ^{l+{3 \over 2}}}}\cdot {\frac {\Gamma [{\frac {1}{2}}(n+l+1)+1]}{[{\frac {1}{2}}(n-l)]!}}=1.}$$

Hence, the normalization constant can be expressed as

$${\displaystyle N_{nl}={\sqrt {\frac {2\,\gamma ^{l+{3 \over 2}}\,({\frac {n-l}{2}})!}{\Gamma ({\frac {n+l}{2}}+{\frac {3}{2}})}}}}$$

Other forms of the normalization constant can be derived by using properties of the gamma function, while noting that n and lare both of the same parity. This means that $n + l$ is always even, so that the gamma function becomes

$${\displaystyle \Gamma \left[{1 \over 2}+\left({\frac {n+l}{2}}+1\right)\right]={\frac {{\sqrt {\pi }}(n+l+1)!!}{2^{{\frac {n+l}{2}}+1}}}={\frac {{\sqrt {\pi }}(n+l+1)!}{2^{n+l+1}[{\frac {1}{2}}(n+l)]!}},}$$

where we used the definition of the double factorial. Hence, the normalization constant is also given by

$${\displaystyle N_{nl}=\left[{\frac {2^{n+l+2}\,\gamma ^{l+{3 \over 2}}\,[{1 \over 2}(n-l)]!\;[{1 \over 2}(n+l)]!}{\;\pi ^{1 \over 2}(n+l+1)!}}\right]^{1 \over 2}={\sqrt {2}}\left({\frac {\gamma }{\pi }}\right)^{1 \over 4}\,({2\gamma })^{\ell \over 2}\,{\sqrt {\frac {2\gamma (n-l)!!}{(n+l+1)!!}}}.}$$


text:
Q: What alternatives are there for Entity Framework in ASP.NET MVC3 I want to develop ASP.NET MVC site but I am confused about the use of EF. While developing my database structure/tables will be changed frequently and also after going to the production if anything happened?
If EF not for ASP.NET MVC3 then I would use ....... ?

A: *

*nHibernate

*RavenDb
Don't bother with anything else, in my opinion.
nHibernate is a very mature and open source ORM that can use SQL Server to get data into/out of your ASP.NET MVC (and version) project(s). It is the most direct competitor to EF it terms of popular options in the ORM space.
If you like new and cutting edge technology, then give RavenDB a go. It is its own database and doesn't require an ORM. It just saves the class library objects straight to its own DB. Therefore, you don't have database schema migration issues, etc.
I would go for RavenDb IMO. I'm leaving EF because I'm just so sick of SQL Server and all the hoops and barriers to getting my domain models to work nicely with a traditional RDBMS. (And this is after working with SQL Server since '95) ...


text:
Q: PHP: How to execute try block even if exception found? I have a try block in which some exceptions will be definitely thrown but I don't want to stop the execution of the try block if this happens.
This is the code:
try {
    $queryStr = "SELECT * FROM `$current_table` WHERE ...";
    $query = $db->prepare($queryStr);
    $query->execute();

    while($row = $query->fetch()) {

    }

} catch(PDOException $e) {
    //echo $e->getMessage();
}

This try/catch block is inside a for loop, so $current_table will be changing continously. Now this current table can take 4 values april-june-2014, july-september-2014, october-december-2014 and jan-march-2015. These table names are stored in an array.
Now when it will query the first table and if it is found, then it's well and good but if it is not found then I want to check the other tables and see if those exists. If any of the table is not found, it will throw an exception and then it won't check the other tables.
Is there a way to do that?

A: Use a continue statement:
for (/* condition */) {
  try {
    // things
  } catch (Exception $e) {
    continue;
  }

  // won't reach here if exception was caught
}

See: http://php.net/continue
Example (try this out on WriteCodeOnline):
$counter = 0;

for ($i = 0; $i < 5; $i++) {
  try {
    $counter++;
    if ($counter != 3) {
      throw new Exception("Test");
    }
  } catch (Exception $e) {
    continue;
  }

  echo "This only prints when an exception is not thrown (when \$counter is 3). See: \$counter = " . $counter;
}

echo "\n";
var_dump($counter);

A: You can put your code that must execute irrespective of exception, into a finally block. Check this
http://php.net/manual/en/language.exceptions.php

A:

I want to check the other tables and see if those exists

You can use 'SHOW TABLES' query to locate what tables are existed. After it match it to april-june-2014, july-september-2014, october-december-2014 and jan-march-2015 and etc.
$needTables = array('april-june-2014', 'july-september-2014', 'october-december-2014', 'jan-march-2015')

$existedTables = reportExistedTablesWrapper();//SHOW TABLES

$tables = array_intersect($existedTables, $needTables);

foreach ($tables as $current_table)
{
    $queryStr = "SELECT * FROM `$current_table` WHERE ...";
    $query = $db->prepare($queryStr);
    $query->execute();

    while($row = $query->fetch()) {

    }
}

A: try This:
try {
    $queryStr = "SELECT * FROM `$current_table` WHERE ...";
    $query = $db->prepare($queryStr);
    $query->execute();

    while($row = $query->fetch()) {

    }

} catch(PDOException $e) {
    //echo $e->getMessage();
}
finally {
    echo "Finally.\n";
}

A: I actually had some structure problems in tables so because of that I was unable to get data from them. But this code is working fine. The remaining code in try block will be executed even if there is an exception. So there is no need to add anything else.


text:
Q: Turning on/off network settings on Android Is there a (simple) possibility for turning the mobile network on/off with Java code?
If so, for mobile service too?
'Cause I'd like to make an app which turns the network on and service off (or the opposite).
Thanks for help.

A: The wireless network you can turn on by the following code:
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);

A: You need permissions to do that. I think CHANGE_WIFI_STATE is the right one.


text:
Q: invoke cmd.exe using JavaScript Is there a way to Invoke cmd.exe using client side javascript? Until now i have been using WCF service to run remote processes and execute cmd.exe too. but I need a more reliable way as I don't want to host the WCF services on different systems.
Any sample code will be much appreciated.
Thanks.

A: Without any plugin and big client side relaxing of security settings ?
Of course you can't. Even IE doesn't let you breach user security so easily.


text:
Q: Missing QGIS raster menu tools with error'"osgeo [python-gdal]" module is missing'? I recently had to reinstall QGIS (version 2.2.0-9) and the raster menu is missing its tools. I understand that the GdalTools plugin must be installed and enabled. I have already installed the GDal complete framework package. When I try to load the Gdal Tools plguin, the following error message occurs:

A similar error message occurs when I go to 'manage and install plugins' and try to reinstall the openlayers plugin. The following message occurs:

Does anyone know how to install the "osgeo [python-gdal]" module mentioned?
I am using MacOsx 10.8.5.

A: I assume that you use the QGIS version of KyngChaos
Have you installed the required packages ?

*

*The GDAL complete package

*....

If you did, the osgeo module is in:

/Library/Frameworks/GDAL.framework/Versions/1.11/Python/2.7/site-packages (or /Library/Frameworks/GDAL.framework/Versions/1.10/Python/2.7/site-packages

And there is a Python path configuration file (.pth) pointing to the module in:

/Library/Python/2.7/site-packages/gdal-py2.7.pth (or /Library/Python/2.7/site-packages/gdal-py2.7.pth)

The content of this file is:
import sys; sys.path.insert(0,'/Library/Frameworks/GDAL.framework/Versions/1.11/Python/2.7/site-packages')

or
import sys; sys.path.insert(0,'/Library/Frameworks/GDAL.framework/Versions/1.10/Python/2.7/site-packages')

To control, open the Terminal.app and type:
$ python
 ......
 >>> import osgeo
 >>> osgeo.__file__
 '/Library/Frameworks/GDAL.framework/Versions/1.11/Python/2.7/site-packages/osgeo/__init__.pyc'

or the same in the Python console of QGIS
After, in the GDALTools parameters:

*

*for binaries, put: /Library/Frameworks/GDAL.framework/Programs:/usr/bin

*for the path of the Python modules, put /Library/Frameworks/GDAL.framework/Versions/1.11/Python/2.T/site-packages (or 1.10)

*for the help files, put /Library/Frameworks/GDAL.framework/Versions/1.11/Resources/doc/gdal (or 1.10)


text:
Q: how to open row in edit mode in gridview how to make gridview ro visible false when i click on delete button because i am using static data and
i want to open the row in gridview in edit mode when i click on edit button.
How to do this in c#

A: Are the Delete button and edit button are embedded wit the gridview Row?? Or they are separated and selecting a checkbox embedded wit the gridview Row and do the editing and deleting thing??


text:
Q: Typecasting in C -2147483648 I am using C, and in my program I am typecasting a variable from double to int using this code:
x1=(int)((x1+0.25)*2);

For some reason I get the value of x1 as -2147483648.00
What am I doing wrong?
Full code:
#include <stdio.h>

int main(){
double x1=-10., y1=15.,x2=10.,y2=15.,t;
int i, Y=0,X=20,j;
char check;
do {
scanf("%c",&check);

if (check!='T')
  break;

scanf("ime: %lf ( %lf, %lf), ( %lf, %lf)\n",&t,&x1,&y1,&x2,&y2);
printf("Time: %.1lf\n",t);

for (i=20; i>=Y; i--) {
  printf("|");
  for (j=-20; j<=X; j++) {
if (x1>0)
  x1=(int)((x1+0.25)*2);
else if (x1<0)
  x1=(int)((10-0.25)*2);
else
  x1=0;
if (x2>0)
  x2=(int)((x2+0.25)*2);
    else if (x2<0)
  x2=(int)((x2-0.25)*2);
else
  x2=0;
(y1>0)?(y1=(int)(y1+0.5)):(y1=(int)(y1-0.5));
(y2>0)?(y2=(int)(y2+0.5)):(y2=(int)(y2-0.5));
if ((x1==x2)&&(x2==j)&&(y1==y2)&&(y2==i))
  printf("*");
else if ((x1==j) && (y1==i))
  printf("1");
else if ((x2==j) && (y2==i))
  printf("2");
else
  printf(" ");
  }
  printf("|\n");
}
for (i=0;i<43;i++)
  printf("-");
printf("\n");

printf ("x1=%.2lf, y1=%.2lf, x2=%.2lf, y2=%.2lf",x1,y1,x2,y2);
printf("\n");
}
 while (check=='T');

return 0;
}

Input: Without the asterisk and space
Time: 0.00 ( -10.00, 20.00), ( 10.00, 20.00)
Time: 0.10 ( -8.00, 14.95), ( 8.00, 14.95)
Time: 0.20 ( -6.00, 14.80), ( 6.00, 14.80)
Time: 0.30 ( -4.00, 14.56), ( 4.00, 14.56)
Time: 0.40 ( -2.00, 14.22), ( 2.00, 14.22)
Time: 0.50 (  0.00, 13.77), ( 0.00, 13.77)
Boom!

A: This is simple one:
You are trying to typecast double to int. whereas the x2 is exceeding way beyond integer range.
check this:
http://www.cplusplus.com/forum/beginner/44774/
And that's why when you try to get x2 from int to double again, it's impossible.
Try to run your program by removing typecast for x2, and see, it's working.
You can truncate double using math.h in C. Or though you can add floating values directly it will not make huge difference; but definitely not a good programming practice.
And yeah, please post program with proper indenting and formatting to make it more readable.

A: When I run the program you have provided, it is x2 that becomes -2,147,483,648 first, not x1.
When you convert a floating-point value to int, the C standard does not define the behavior of the integer portion of the floating-point value is not representable in the int type. Apparently, on the system you are using:

*

*The int type represents values from -2,147,483,648 to 2,147,483,647.

*Your program creates a floating-point value outside that range.

*When a value outside that range is converted to int, your C implementation produces -2,147,483,648.

There are two problems:

*

*You need to figure out why your program is producing such large values and decide whether you want to do that or not.

*When you want to take the integer part of a floating-point value, you should #include <math.h> and use trunc rather than converting it to an int. If you want to round to the nearest integer, use round, rather than adding .5 (or subtracting if negative) and taking the integer part.

Your code is essentially doubling x1 and x2 repeatedly, and it is not clear why or what the goal is.


text:
Q: Display dynamically an image using express and EJS I have a collection containing different URLs of images. I retrieve the URL I want and want to pass it to the jade template like:
app.get('/',function(req,res){
    mongoDB.getUsedHomePageOne(function(err, result){
        if(!err){
            console.log("getUsedHomePageOne : ");
            console.log(result);
            app.locals['homePageImg'] = result.url;
        }
    });

    app.render('userPageEjs.html',function(err,renderedData){
        console.log(renderedData);
        res.send(renderedData);
    });
});

and the getUsedHomePageOne looks like:
DBMongo.prototype.getUsedHomePageOne  = function(callback){
    this.homePageColl.findOne({used:1}, callback);
};

and in the jade template:
<img src="<%= homePageImg %>"/>

So this won't work except if I load twice the page, I assume because it gets cached and is computed quickly enough or something.
What is the proper way of doing it?
PS: the 2nd time I load the page, everything will load correctly.
PS2: I don't want to delay the rendering for the image, I would like to load the image once it is ready, but render the HTML page before anyway.

A: From what I've gathered in your code:
app.get('/',function(req,res){
    mongoDB.getUsedHomePageOne(function(err, result){
        if(!err){
            console.log("getUsedHomePageOne : ");
            console.log(result);
            app.locals['homePageImg'] = result.url;
            app.render('userPageEjs.html',function(err,renderedData){
               console.log(renderedData);
               res.send(renderedData);
            });
        }
    });
});

Basically, you have an async function to the DB and you quickly render the template before waiting for the DB function to complete. The normal pattern when using async functions whose results should be used down the line, you have to call the next function inside the async function. However, this might lead to callback hell (similar to how I've written the fix above), so an alternative like Promises or async.js is usually preferred.


text:
Q: Some properties are missing from API's returned data, need solid way to check property I'm aware that api team is the one responsible for sending correct data to the client that requested the data. However, I still would like to know the best way of checking if property exists or not.
// when state property is missing from the api response
myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555'
  },
  birthDate : '20000101'
}

or
// or when birtdate is missing
myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555',
    state    : 'MN'
  }
}

or
// when addressInfo is missing
myObject = {
  name : 'Scott',
  birthDate : '20000101'
}

Is the code below enough for the checking?
if (myObject.addressInfo !== undefined && myObject.addressInfo.state !== undefined) {

    // console.log(
}

A: state value could be set as undefined though still be a property of myObject ; try utilizing Object.hasOwnProperty(property)

var myObject = {
  name : 'Scott',
  addressInfo : {
    address1 : '444 St Peter St',
    address2 : 'Apartment D',
    zipCode  : '55555'
  },
  birthDate : '20000101'
};

console.log(myObject.addressInfo.hasOwnProperty("state"))

A: If you are willing to use a library like lodash or underscore, then a very convenient way to test if a key is present in an object is the _.has method:
var x = { "a": 1 };
_.has(x,"a"); //returns true
_.has(x,"b"); //returns false

A: Right way to check proerty exists:
if(myObj.hasOwnProperty(myProp)){
    alert("yes, i have that property");
}

and
if(myProp in myObj){
    alert("yes, i have that property");
}

From answer:
check if object property exists - using a variable