text:
Q: Click an element if another element contains a specific text. Automated Test with Protractor I need to check which one of 3 elements contains the text "10%" but I am not sure I am getting correctly the text of the element. When I run the code I am not getting errors but the if condition is always false(also when it should be true).
My javascript code inside the spec:
await driver.wait(until.elementIsVisible(await driver.findElement(By.css("tr:nth-child(1) .font-weight-bold-light > span"))), 30000)
await driver.wait(until.elementIsVisible(await driver.findElement(By.css("tr:nth-child(2) .font-weight-bold-light > span"))), 30000)
await driver.wait(until.elementIsVisible(await driver.findElement(By.css("tr:nth-child(3) .font-weight-bold-light > span"))), 30000)

var array = ["tr:nth-child(1) .font-weight-bold-light > span", "tr:nth-child(2) .font-weight-bold-light > span", "tr:nth-child(2) .font-weight-bold-light > span"];
var arrayDelete = ["tr:nth-child(1) img:nth-child(2)", "tr:nth-child(2) img:nth-child(2)", "tr:nth-child(3) img:nth-child(2)"]
for (var k = 0; k<array.length; k++){

  var allOpts = (await driver.findElement(By.css(array[k])));
  await driver.sleep(2000)

  if (allOpts == ('10%')) {
    await driver.sleep(2000)
    await driver.wait(until.elementIsVisible(await driver.findElement(By.css(arrayDelete[k]))), 30000)
    // 11 | click | css=.actions > img:nth-child(2) |
    await driver.findElement(By.css((arrayDelete[k]))).click()
    // 12 | pause | 1000 |
    await driver.sleep(5000)
    // 13 | waitForElementVisible | css=.ml-3 | 30000
    await driver.wait(until.elementIsVisible(await driver.findElement(By.css(".ml-3"))), 30000)
    // 14 | click | css=.ml-3 |
    await driver.findElement(By.css(".ml-3")).click()
    // 15 | pause | 3000 |
    await driver.sleep(10000)
    // 16 | verifyElementNotPresent | css=td:nth-child(1) |
    {
      const elements = await driver.findElements(By.css((allOpts)))
      assert(!elements.length)
    }
    console.log(('ho cancellato l obiettivo ')+ k);

  } else {
    console.log(('obiettivo ') + k + (' non cancellato, in quanto il suo peso non è 10%'));
  }
}

I tryed all of these:
if (allOpts == (' 10% '))
if (allOpts == ('10%'))
if (allOpts === (' 10% '))
if (allOpts === ('10%'))
if (allOpts.getText() == (' 10% '))
if (allOpts.getText()  == ('10%'))
if (allOpts.getText()  === (' 10% '))
if (allOpts.getText()  === ('10%'))
if (allOpts.getAttribute("value") == (' 10% '))
if (allOpts.getAttribute("value")  == ('10%'))
if (allOpts.getAttribute("value")  === (' 10% '))
if (allOpts.getAttribute("value")  === ('10%'))

None of these allowed to run the body of the if condition.
Here my html:
<td _ngcontent-lqu-c20="">
  <p _ngcontent-lqu-c20="" class="font-weight-bold-light">
    <!---->
    <span _ngcontent-lqu-c20=""> 10% </span>
  </p>
</td>

A: First of, your syntax is not typical for protractor (unless you're using some very old version). if this is the tool you'r using checkout their documentation
Second, in this line you're just declaring the element and not doing anything with it
var allOpts = (await driver.findElement(By.css(array[k])));

you should have extracted element's text. But using normal syntax it would look like so
var allOpts = await element(by.css(array[k])).getText();

Three, the reason this is not working
if (allOpts.getText() == (' 10% '))

is because this is promise, which you need to resolve by .then() or by awaiting it. Unless you figure out this process in depth (and I mean it... in ALL details), you won't go too far with protractor
Four, when you do .getText() your string gets trimmed, meaning there is no spaces in the beginning and at the end ('10%' not ' 10% ')
Five, when in doubt, just console.log() the value. It's the easiest way to debug problems
And lastly, don't use ==, use === instead. For 3 years working with protractor I never had a case when I HAD to use ==, but I did have many confusions created by coercion when using it

A: You missed to call getText() to read the content on the web element
var allOpts = (await driver.findElement(By.css(array[k])).getText()).trim()

A: first you need to read the text of the element i.e. by using getText().


text:
Q: How to: Create a plot for 3 categorical variables and a continuous variable in R? I would like to create a plot using R, preferably by using ggplot. I have the following variables to visualize, most of them binary:
Trial: cong/incong
Sentence: him/himself
Condition: normal/slow
Accuracy: number
SE: number
structure(list(TrialType = structure(c(1L, 1L, 1L, 1L, 2L, 2L,
2L, 2L), .Label = c("congruent", "incongruent"), class = "factor"),
    SentenceType = structure(c(1L, 1L, 2L, 2L, 1L, 1L, 2L, 2L
    ), .Label = c("him", "himself"), class = "factor"), Condition = structure(c(1L,
    2L, 1L, 2L, 1L, 2L, 1L, 2L), .Label = c("normal_speech",
    "slow_speech"), class = "factor"), MeanAccuracy = c(0.794871794871795,
    0.762820512820513, 0.967948717948718, 0.967948717948718,
    0.237179487179487, 0.342105263157895, 0.942307692307692,
    0.83974358974359), SE = c(0.0342056016493384, 0.0430264468743046,
    0.0389087806837746, 0.0496183045476835, 0.0135583881898854,
    0.0163760608630386, 0.0170869868584354, 0.0311270245470197
    )), class = "data.frame", row.names = c(NA, -8L))

The SE stands for the standard error, meaning that I would like to present the error bars around the accuracy score.
I figured that my best option is to make two bar plots, One separately for each condition with accuracy on the x-axis. Then, four bars representing both possible combinations of sentence and trial, showing the accuracy in height and error bars presented around this to reflect the uncertainty.
How could I make such a graph? Or, does anyone think that this is not the right type of graph and then what would be (and how to plot it...)?
Thanks in advance!

A: Are you perhaps looking for something like this?
library(ggplot2)

ggplot(df, aes(TrialType, MeanAccuracy, fill = SentenceType)) +
  geom_col(position = position_dodge(width = 1), color = "gray50") +
  geom_errorbar(aes(ymin = MeanAccuracy - SE,
                    ymax = MeanAccuracy + SE), width = 0.25,
                position = position_dodge(width = 1)) +
  scale_fill_manual(values = c("gold", "deepskyblue4")) +
  facet_grid(.~Condition, switch = "x") +
  theme_bw() +
  theme(strip.placement = "outside",
        strip.background = element_blank(),
        panel.border = element_blank(),
        panel.spacing = unit(0, "points"),
        axis.line = element_line())

A: Using some simulated data based on the description you shared, you can try:
library(ggplot2)
library(dplyr)
library(tidyr)
#Data
df <- data.frame(Trial=rep(c('cong','incong'),4),
                 Sentence= rep(c('him','himself'),4),
                 Condition=rep(c('normal','slow'),4),
                 Accuracy=runif(8,0,1),
                 SE=runif(8,0,10),stringsAsFactors = F)
#Plot 1
df %>% pivot_longer(-c(Trial,Sentence,Condition)) %>%
  ggplot(aes(x=name,y=value,fill=Condition))+
  geom_bar(stat = 'identity')+
  facet_wrap(.~Trial+Sentence,scales = 'free')

Output:

Or this:
#Plot 2
df %>% pivot_longer(-c(Trial,Sentence,Condition)) %>%
  ggplot(aes(x=name,y=value,fill=Condition))+
  geom_bar(stat = 'identity')+
  facet_grid(Trial~Sentence,scales = 'free')

Output:

Further details and data are necessary to understand your issue.

redpajama_set_name: RedPajamaStackExchange


text:
Q: wp-admin: "Sorry, you are not allowed to access this page." After 2 weeks not using our WP site, logging into /wp-admin/ gives a whitescreen error:

Sorry, you are not allowed to access this page.

I have:

*

*renamed plugins to plugins.temp.

*created a new admin user via phpMyAdmin. New user has user_meta role of a:1:{s:13:"administrator";s:1:"1";}.

*renamed themes to themes.temp.

*deleted core WordPress files, and replaced with newly uploaded files.

*replaced .htaccess with a default version.

*CHMOD all folders to 755 and all files to 644 recursively.

*turned on WP_DEBUG and found no errors.

*confirmed the site_url & home_url are set correctly in the options table of the db.

all without changing the error.
Help appreciated.
Edit:

*

*I've regenerated the security keys without anything changing.

*The site is singular, not multisite.

*The problem occurs after clearing cookies, and on all devices.

*The error occurs immediately after logging in and reaching /wp-admin/.

*I can get to /wp-admin/index.php but not /wp-admin/ (original error)

*I can get to /wp-admin/plugins.php but not to /wp-admin/update-core.php (the first time, the same error), but the second time was okay.

A: Because you have renamed the plugin and theme directory, it should a problem on your user. But rename the whole wp-content directory, so that all add-ons are inactive, check it again.
User Rights
After them, logged in to a database tool, like "Adminer" or "PhpMyAdmin" and look at the table usermeta with your user ID*, like

SELECT * FROM wp_usermeta WHERE user_id = '1'`

Check the entries wp_capabilities and you should have the administrator key, like a:1:{s:13:"administrator";b:1;}.
*Note: To identify your user ID, look at the frontend, list all your posts and look at the URL, the key ?author= has your User ID. It is also possible after login in the wp-admin area on links with user keys.
Permalinks
Another chance to fix them is the .htaccess file. Maybe this is not correct, and you have issues with the permalinks.


text:
Q: How does START_REDELIVER_INTENT behave with multiple Intents? If a Service has multiple calls to startService() using different Intents, how does it behave with START_REDELIVER_INTENT when the application is restarted after being killed due to low memory?
Example: I call startService(intent, class) three times with different Intents. Before the Service stops itself, the OS kills the application or the Service due to memory usage. Later, the Service returns. According to START_REDELIVER_INTENT onStartCommand() should be called with the original Intent that started it. Will it be called for all three? Only the first one? Only the last one?
I thought about testing it, but I want to know what is supposed to happen, not just what my specific device does. Thanks!

A: the answer adopted is not correct.
He did not see the next few words:

This Intent will remain scheduled for redelivery until the service calls {@link #stopSelf(int)} with the start ID provided to {@link #onStartCommand}

it means that when an intent comes and onStartCommand called, if we don't stopSelf the onStartCommand's startId associated with the intent, the system treats this intent as not-handled, So then when service re-create, these not-handled intents will re-delivered to onStartCommand.
So, it will be called three times.

A:
Will it be called for all three? Only the first one? Only the last
  one?

Only the last one.
The documentation is pretty clear about this:
...if this service's process is killed while it is started (after returning from onStartCommand()), then it will be scheduled for a restart and the last delivered Intent re-delivered to
 it again via onStartCommand().


text:
Q: primary key on very small table I am having a very small tables with at most 5 records that holds some labels. I am using Postgres.
The structure is as follows:
id - smallint
label - varchar(100)
The table will be used mainly to reference the rows from other tables. The question is if it's really necessary to have a primary key on id or to have just an index on the id or have them both?
I did read about indexes and primary keys and I understand that this depends quite a lot on what's the table going to be used for:
Tables with no Primary Key
Edit: I was going to ask about having a primary key or an index or have them both. I edited the question.

A: It is always good practice to have a primary key column. The typical scenario it is needed is when you want to update or delete a row, having a PK makes it much easier and safer.

A: Yes, a primary key is not only good practice -- it's crucial.  A table that lacks a unique key fails to be in First Normal Form.
You must declare a PRIMARY KEY or UNIQUE constraint if you want other tables to reference this one with a foreign key.
In most RDBMS brands, both PRIMARY KEY and UNIQUE constraints implicitly create an index on the column(s).  If it doesn't do this implicitly, you may be required to define the index yourself before you can declare the constraint.

A: Yes, you will need a primary key on the id field, since you do not want two labels that share the same id.
You also want an index, to speed up the search/lookup process in this table (although for small tables there is less performance gain). The sequence will just help you fill in the next ID; it does not prevent you from changing a previous value into one that already exists.

A: There are very little reasons for creating an index instead of a primary key. AS Bill Karwin said, you won't save resources at all. And, as you may have already guessed, there is no need at all to create a new index if you have the primary key.
In some cases it may be hard to find a key candidate. But it doesn't seems to be the case and it clearly goes against some good practices.
By the way. As your table is so small most queries will rather use a full table scan even if there is an index. Don't worry you see a full table scan.

A: From the developer's point of view, PRIMARY KEY is just a combination of NOT NULL and UNIQUE INDEX on one of the columns.
A UNIQUE INDEX is good if:

*

*You need to enforce uniqueness. Using index is the most efficient way to do that.

*

*You need to perform a SELECT, UPDATE or DELETE with a WHERE condition that is selective on the indexed field, that is number of rows affected by the query is much less that total number of the rows (say, 10 rows of 2,000,000).

A UNIQUE INDEX is bad if:

*

*You don't need uniqueness on this field, of course :) But you'll better have one unique index in the table, for each record to be identifiable.

*

*You need fast INSERTS

*You need fast UPDATE's and DELETE's of the indexed value with a WHERE condition that is not selective on the indexed field, that is number of rows affected by the query is comparable to the total number of the rows (say, 1,500,000 rows of 2,000,000).

Given that you are going to have a little table, I'd advice you to create a PRIMARY KEY on it.


text:
Q: Toast is not working in my android application i am a beginner android application developer. currently trying to build a simple calculator app nd want to show the calculated result by using Toast. but right now i am unable to use toast to display this output. there is my code
MainActivity.java
package com.example.calculator;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;

public class MainActivity extends Activity {
    EditText input_field1,input_field2,result_field;
    int result_var;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void add_numbers(View v){

        input_field1= (EditText) findViewById(R.id.field1);
        String no1=input_field1.getText().toString();
        input_field2= (EditText) findViewById(R.id.field2);
        String no2=input_field2.getText().toString();
        int field1_int=Integer.parseInt(no1);
        int field2_int=Integer.parseInt(no2);
        result_field= (EditText) findViewById(R.id.resultfield);
        result_var=field1_int+field2_int;
        result_field.setText("result "+result_var);
        Toast.makeText(getApplicationContext(), result_var, Toast.LENGTH_LONG).show();

    }
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button1"
        android:layout_alignBottom="@+id/button1"
        android:layout_toRightOf="@+id/button1"
        android:text="Substract" />

    <Button
        android:id="@+id/divide"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/button2"
        android:layout_alignBottom="@+id/button2"
        android:layout_toRightOf="@+id/button2"
        android:text="Divide" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="105dp"
        android:text="Add"
        android:onClick="add_numbers" />

    <EditText
        android:id="@+id/field1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="22dp"
        android:ems="10" />

    <EditText
        android:id="@+id/resultfield"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/button1"
        android:layout_below="@+id/button2"
        android:layout_marginTop="16dp"
        android:ems="10" />

    <EditText
        android:id="@+id/field2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button2"
        android:layout_alignLeft="@+id/button1"
        android:ems="10" />

</RelativeLayout>

A: The problem is you need a string to be displayed in a toast. You are trying to display an int. The simplest thing to do is to wrap it with String using String.valueOf().
Toast.makeText(getApplicationContext(), String.valueOf(result_var), Toast.LENGTH_LONG).show();

As a side note generally in java we wouldn't use underscores _ in variable names. Better to name them like this.
EditText mInputField1,mInputField2,mResultField;
int mResultVar;

m for member variables.
Also better to put findViewById in onCreate.

A: result_var should be a string
String result_var="";
String Testing="testing";
    Toast.makeText(getApplicationContext(), result_var+testing, Toast.LENGTH_LONG).show();

Otherwise use as according to you:
// if you have values of field1_int and field2_int

int result_var=field1_int+field2_int;

    Toast.makeText(getApplicationContext(),String.valueOf(result_var), Toast.LENGTH_LONG).show();

A: Try this Toast message has to be String
Toast.makeText(getApplicationContext(), ""+result_var, Toast.LENGTH_LONG).show();

A: A advice, as you are beginner. You should read the required arguments accepted by any method you are using.
Read Toast
For example in your case.
 Toast.makeText(getApplicationContext(), ""+result_var, Toast.LENGTH_LONG).show();

Or
Toast.makeText(getApplicationContext(),String.valueOf(result_var), Toast.LENGTH_LONG).show();


text:
Q: OpenDaylight Archetypes JAR Fluorine Not in Repository? I am trying to install OpenDaylight Fluorine. Per the developer guide i am to call mvn generate:archetype alongside some other parameters which can be found here: link
However, due to the incorrect formatting of the repo's that documention seems to be incorrect.
I've found what i thought to be the correct nexus repo. Here's the link for the nexus repo: link
Here's the command i am trying to run:
 mvn archetype:generate -DarchetypeGroupId=org.opendaylight.controller.archetypes -DarchetypeArtifactId=archetypes-parent -DarchetypeVersion=0.9.0-SNAPSHOT -X

My problem is that when i run it i am getting the error:
org.apache.maven.archetype.downloader.DownloadException: Error downloading org.opendaylight.controller.archetypes:archetypes-parent:jar:0.9.0-SNAPSHOT.
Which makes sense because there isn't a jar there in the repo. My question is where could i find this JAR at? Or am i not running the maven command properly? If i go to parent directories none of the previous releases have a JAR either. I can't find any documentation on another way to install this so any help would be greatly appreciated.

A: The archetype artifacts had expired from our repository (which is a side-effect of our unfortunate reliance on snapshot artifacts). We've update the archetypes and pushed them to the repository again; they are available here and usable with
mvn archetype:generate -DarchetypeGroupId=org.opendaylight.archetypes \
    -DarchetypeArtifactId=opendaylight-startup-archetype \
    -DarchetypeCatalog=remote -DarchetypeVersion=1.0.0-SNAPSHOT


text:
Q: C# MySQL. Ubable to execute query  private void button4_Click(object sender, EventArgs e)
        {
            MySqlConnection connection = new MySqlConnection("datasource=localhost;port=3306;Initial Catalog='liblib';Data Source=localhost;username=root;password=admin");

            String query = "UPDATE loans SET dataRet=@data1 WHERE loans.idloans = @idloan";
            MySqlCommand cmd = new MySqlCommand(query, connection);

            int id = Int32.Parse(textBox9.Text);

                cmd.Parameters.Add("@data1", MySqlDbType.Date).Value = dateTimePicker1.Value;
                cmd.Parameters.Add("@idloan", MySqlDbType.Int32).Value = id;

                connection.Open();

                if (cmd.ExecuteNonQuery() == 1)
                {

                    MessageBox.Show("Succesful!");

                    connection.Close();

                    FIllCard();

                }

            else
            {

                MessageBox.Show("Error");
                connection.Close();
            }

When I execute this UPDATE query in phpmyadmin it works and updates the entry:

UPDATE loans SET dataRet='2017-5-6' WHERE loans.idloans = 23.

But the problem is when I try it in my Form whith parameters. It always returns me "Error" message(ExecuteNonQuery is different from 1), and when I check the database there is no update. The type of the variables in my database are:
idloans - int; dataRet = date;

A: Check out this post: update a mySQL table using C#, It does not have an answer marked as solution, but the OP of that question has authentication problems after using the code of the first answer, perhaps it works for you


text:
Q: Insert options into select from returned JSON array using jQuery I'm a little confused when it comes to insert options into a select box. I found another question similar to mine but I am confused as to the references of "key and value".
So I currently have the following script:
                        $.each(data.visibilities, function(key, value) {
                             $('#dataVisibilitySelect')
                                 .append($("<option></option>")
                                            .attr("value",key)
                                            .text(value));
                        });

Which pulls the visibilities (there are 3 currently) into the select box. But I am unsure about the top line with function(key,value)
At the moment, data.visibilities is returned as an array in the following:
visibilities
[…]
0   {…}
id  1
label   Dispatch
created_at  2017-12-11 09:18:13
updated_at  2017-12-11 09:18:13
1   {…}
id  2
label   Private
created_at  2017-12-11 09:18:13
updated_at  2017-12-11 09:18:13
2   {…}
id  3
label   Public
created_at  2017-12-11 09:18:29
updated_at  2017-12-11 09:18:29

How can I return it so that the id is used as the value and the label is used as the option text?

A: The key holds the index, and value holds the value of the item. So if you want to access the value of label within your JSON, you would use the following variable: value.label
I think this is what you are looking for

<head>
  <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>

<select id="dataVisibilitySelect">

</select>

<script>
  $(document).ready(function() {
    $.each(data.visibilities, function(key, value) {
      $('#dataVisibilitySelect')
        .append("<option value=" + value.id + ">" + value.label + "</option>");
    });
  });

  data = {
    "visibilities": [{
        "id": 1,
        "label": "Dispatch"
      },
      {
        "id": 2,
        "label": "Private"
      },
      {
        "id": 3,
        "label": "Public"
      }
    ]
  };
</script>


text:
Q: How can I change the Color of the SECONDARY toolbar in Xamarin.Forms? Currently I set the Primary toolbar background color with this code in the App.xaml.cs class:
//SET PRIMARY TOOLBAR COLOR
Current.Resources = new ResourceDictionary ();
Color xamarin_color = Color.FromHex ("#3498db");
var navigationStyle = new Style (typeof (NavigationPage));
var barBackgroundColorSetter = new Setter { Property = NavigationPage.BarBackgroundColorProperty, Value = xamarin_color };
navigationStyle.Setters.Add (barBackgroundColorSetter);
Current.Resources.Add (navigationStyle);

The navigationPage PRIMARY toolbar changes its color correctly. But the SECONDARY toolbar doesn't change its default color (gray), and I cannot find any method or property to change it.
How can I change the background color of the secondary toolbar?


text:
Q: Tool for "designing" a resistor network? I'm preparing to calibrate some current sensors for a system with DC 13.6V power, and various loads, from well under an amp, up to about 4 amps. I bought some 2, 3 and 5 ohm power resistors, and plan to arrange them in various series and parallel networks to calibrate each current sensor using a load with known resistance.
It's easy to calculate the resistance of some resistors in series or in parallel, but I don't have a technique for generating a network with a desired resistance. I would like to come up with values that result in "well rounded" maximum amp values, such as very nearly 5 amps for the circuit that is supposed to max out around 4 amps, but so far I've just been making guesses. Sigh.
Is there a tool for doing this, or a reasonable "by hand" method? Thanks.

A: I don't know if you've considered continued fractions, or if they'd do anything you care about, but here's something that may be worth considering.
Let's say you want \$R_x=12.5\:\Omega\$ between nodes \$N_A=N_0\$ and \$N_B\$. Set \$i=0\$:

*

*Select the next higher value above \$R_x\$. In E12, that's \$R_{2i+1}\$ (for \$i=0\$, \$R_1=15\:\Omega\$.) If satisfied with the results, use \$R_{2i+1}\$ to connect \$N_i\$ to \$N_B\$ and you are done!

*Otherwise, compute \$R_y=\frac{R_{2i+1}\cdot R_x}{R_{2i+1}-R_x}\$ (for \$i=0\$, \$R_y=75\:\Omega\$) and select the next lower value of \$R_{2i+2}\$ (for \$i=0\$, \$R_2=68\:\Omega\$.) Connect one end of \$R_{2i+2}\$ to \$N_i\$. The other end is left open and labeled \$N_{i+1}\$. If satisfied with the results of jumpering \$N_{i+1}\$ to \$N_B\$, then jumper those two nodes and you are done!

*Otherwise, compute \$R_x=R_y-R_{2i+2}\$ (for \$i=0\$, \$R_x=7\:\Omega\$), increment \$i\$ (for \$i=0\$, \$i\$ becomes \$i=1\$) and then go to step 1.

In the above starting case of \$12.5\:\Omega\$ and using E12 resistor values, the following possible circuits develop:

simulate this circuit – Schematic created using CircuitLab
And so on. You can see that it rapidly approaches the desired value. Most of the dissipation is usually carried in the first resistor. Whether or not this is good or bad, depends. The gist of this is that you are almost always very, very close with no more than three or four resistors with E12.
Here's the same approach, but used with E24 resistor values:

simulate this circuit
Note that at the even steps of \$i\ge 2\$, you can also consider summing the two series resistor values and picking the next higher value that closely matches as an alternative to step \$i-1\$, too. For example, in step \$i=2\$ of the above E24 resistor selections, \$R_2\$ and \$R_3\$ could be summed and then the choice of \$R_2=330\:\Omega\$ could be used instead of what was used in step \$i=1\$. In the above case, this would have been a better choice for \$i=1\$ than just strictly following the algorithm I gave earlier.
This points up a slight improvement to the algorithm. The value of \$R_x\$ should be considered as either one resistor of next higher value, or else two resistors composed of the next lower value, plus the difference rounded up to its next (or similarly convenient) higher value.
Also, the algorithm doesn't always find optimal choices. For example, this could have been \$12\:\Omega\$ in series with two, parallel \$1\:\Omega\$ resistors. And that would have been exact. But what it does do is to continually diminish the residual error (assuming exact resistor values.)
(Offered in the case it matters to you to have a codified, step-wise algorithm you can follow without just doing "hit and miss.")

A: This is a "I think it's easy enough to go and try with a modern computer" answer.I'd be more than interested in a good answer or reference to an actual theoretical approach to OP's problem. It has been asked before, but I can't find it. The problem is very nice.

The problem of finding a graph (i.e. a network) whose flow (i.e. whose total resistance/conductivity) given edge weights comes as close as possible to a specific value does sounds algorithmically hard¹.

But frankly: I'd just go and find a formula for the resistance of each combinations of 2 resistors (which are only 2: parallel or serial), 3 resistors (all three parallel, all three serial, one parallel to two in series, one in series to two parallel), and 4 resistors.
Then, write a script that simply tries all these with all the different combinations you can draw from your reserve of resistors.
If you don't get close enough, take the list that the last step generated, and act as if you can use these as individual resistors: add these values to your list of available resistors, and repeat.

¹ That guess, by the way, is based on me imagining finding all flows through a graph being similarly complex as finding all paths.

A: There's a tool solving exactly this problem:
http://kirr.homeunix.org/electronics/resistor-network-finder/
It constructs a network with your desired equivalent resistance, out of the values that you have in stock.

A: The simple solution is to design an active "dummy load" using a darlington power transistor or  power FET  as a constant current sink with a 50 to 100mV voltage drop at rated or max load current for ground current sensing.  Then you just need a Pot or a DAC and comparator to regulate the voltage compared with Vsense.

A: Yes, there is at least one calculator for two resistors, which you can access here.
Here is an example calculation to get 12.5 ohms using two 10% resistors in series or parallel combinations.


text:
Q: How to convert media image object to bitmap using android.hardware.camera2 package? I want to convert an image object that I got from  ImageReader.OnImageAvailableListener to bitmap .
I have read a lot of articles and a lot of solution but nothing works with me .
when I have tried to getPixelStride() from the plane then the values is zero ??
I don't know why .
also getRowStride() return zero
Image image = reader.acquireLatestImage();
                int mWidth = image.getWidth();
                int mHeight = image.getHeight();

                final Image.Plane[] planes = image.getPlanes();
             final ByteBuffer buffer = planes[0].getBuffer();
                int offset = 0;
               int pixelStride = planes[0].getPixelStride();
                int rowStride = planes[0].getRowStride();
                int rowPadding = rowStride - pixelStride * mWidth;

                // create bitmap\

                image.close();

                CapturedImage = Bitmap.createBitmap(mWidth + rowPadding / pixelStride, mHeight, Bitmap.Config.RGB_565);
                CapturedImage.copyPixelsFromBuffer(buffer);

can't create the bitmap where the stride is zero
also when trying to
 byte[] bytes = new byte[buffer.remaining()];
         buffer.get(bytes);
       image.close();

CapturedImage = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, null);
then I got an error message that not enough to copy pixel


text:
Q: Change the format of a numpy array in python I have a (2x2) numpy array which contains an (1x3) list, like this below:
[[ 1, 2, 3], [ 4, 5, 6]
 [ 7, 8, 9], [10,11,12]]

and I want to break it to single elements like this (2x6) array (or matrix, I can't tell the difference):
[ 1, 2, 3,  4,  5,  6]
[ 7, 8, 9, 10, 11, 12]

I can create the second array by coping every single element of the first array and put it to the second one. Yet I wonder if there is a more easy way provided by the numpy library.

A: you can simply use resize function to do this
import numpy as np
a=[[ 1, 2, 3], [ 4, 5, 6],
 [ 7, 8, 9], [10,11,12]]
a = numpy.array(a)
a.resize(2,6)
print(a)

OUTPUT
array([[ 1,  2,  3,  4,  5,  6],
       [ 7,  8,  9, 10, 11, 12]])


text:
Q: Excluding some keys from XGrabKeyboard Consider an application where it's desirable to grab the keyboard when focused in order to capture all window manager commands (Alt+F4 and whatnot) for processing. Now, this has the downside that the user has no way of switching to another application or virtual desktop via the keyboard when the keyboard is grabbed. I'd like to have a user-defined whitelist of key combination (say, the key combinations for switching virtual desktops) that are excluded from the grab.
I can think of two possible approaches. When a whitelisted key event arrives, either

*

*Somehow tell X to continue processing it as usual. This sounds like a more natural way of doing it but I can't find a way to do this, or

*Ungrab the keyboard and re-send the event by hand to the window manager for processing, however I don't know where to send it (the root window?) or whether that would even work.

Can anyone fill in the blanks on those? Any other suggestions?
If there's no way to exclude keys from a grab, I guess I'll have to settle for having an "escape key" that ungrabs the keyboard when pressed. The user'll have to press both that and then the window manager command, though, which isn't as nice.

A: I don't think there's a way to do it. None of the mechanisms work quite how you would need them to.
Approach 1 is sort of what the window manager does if it decides not to intercept a click or key for example. However, the WM is using "passive" grabs on particular keys (XGrabKey=passive XGrabKeyboard=active) and then XAllowEvents(). XAllowEvents() does not work with XGrabKeyboard(). also, when you XAllowEvents with one of the Replay modes, the replayed event bypasses all passive grabs on the window that had the original grab and on all its parent windows. The WM's grabs will be on the root window which will always be a parent so there is no way to replay to the root window, best I can tell. Doing XGrabKey on every possible key would be sort of psycho anyhow.
Approach 2 would have bad race condition problems, because other key and mouse events could be processed before you could resend, so you'd reorder keys and send events to destroyed windows and other confusion. Also, there is no good way to send a key event. XSendEvent() is ignored by many clients (it sets a send_event flag in the event allowing this). XTest extension can be used but may be disabled on production X servers and still has race condition issues.
What you probably would need is a protocol extension that let you do an AllowEvents(mode=ReplayKeyboard) after a GrabKeyboard and without bypassing passive grabs on parent windows.
One caveat is that I don't know all the wild stuff that can be done with XKB and XInput2, so maybe there's something in those extensions.
Anyway, as far as I know you have to settle for the "escape key," though it might be nice eventually for the X server and/or the window manager specs to have "VMWare/VNC-type-thing awareness," that won't help you in the short term. An EWMH spec extension could be as simple as a new _NET_WM_WINDOW_TYPE for vnc/vmware/stuff-like-that and the window manager could reduce its keybindings or add an extra modifier to them or something when that window was focused, for example.


text:
Q: glm in python vs R I have some dataset: titanic
Doing this in R
glm(Survived ~ Sex, titanic, family = "binomial")
I get
(Intercept)     SexMale
1.124321   -2.477825

R takes survived as positive outcome.
But when I'm doing the same in Python
sm.formula.glm("Survived ~ Sex", family=sm.families.Binomial(), data=titanic).fit()
I get negative results: i.e. Python takes not survived as positive outcome.
How can I adjust Python's glm function behavior so it will return the same result as R does?

A: You just need to set your reference group to either male or female (depending on what you're interested in):
With a small test dataset in R, the code and model summary looks like this:
df <- data.frame(c(0,0,1,1,0), c("Male", "Female", "Female", "Male", "Male"))
colnames(df) <- c("Survived", "Sex")

model <- glm(Survived ~ Sex, data=df, family="binomial")
summary(model)

Output:
Coefficients:
              Estimate Std. Error z value Pr(>|z|)
(Intercept) -3.084e-16  1.414e+00   0.000    1.000
SexMale     -6.931e-01  1.871e+00  -0.371    0.711

To get something similar in Python/statsmodels:
import pandas as pd
import statsmodels.api as sm

df = pd.DataFrame({"Survived": [0,0,1,1,0],
                   "Sex": ["Male", "Female", "Female", "Male", "Male"]})

model = sm.formula.glm("Survived ~ C(Sex, Treatment(reference='Female'))",
                       family=sm.families.Binomial(), data=df).fit()
print(model.summary())

Which will give:
                                                    coef    std err          z      P>|z|      [0.025      0.975]
-----------------------------------------------------------------------------------------------------------------
Intercept                                      5.551e-16      1.414   3.93e-16      1.000      -2.772       2.772
C(Sex, Treatment(reference='Female'))[T.Male]    -0.6931      1.871     -0.371      0.711      -4.360       2.974

Notice the use of Treatment() to set the reference group. I've set it to Female in this case to match the R output, but with your dataset it might make more sense to use Male. Either way, its just an issue of being explicit about which group is used as reference.


text:
Q: List Box Style in a particular item (option) HTML I'm trying to make this behavior.
When a have a listBox (or comboBox), my first element (something like "choose one") should have a particular style.
With this (test) code:

(...)

<select name="name" id="id">

<option class="testeX" selected="selected" value="#">

Choose One

</option>
<option value="TestValue">
    TestValue
</option>

i can see this behavior on Firefox (but not in Chrome) when i expand my listBox but when i select my 'Choose one' my field doesn't have the (italic) style.
How can i do this? Is possible do this only with HTML, CSS or i need more (like jQuery)?
Thanks.

A: try using the pseudo element 'first-child'

And paragraph tags do not belong inside <option> tags, they should contain plain text.
But styling on <option> tags is limited, not all browsers support it. You might have more luck with other types of styling, like background colours. Or use javascript and custom HTML to simulate the same behaviour as a regular <select> box

A: Form elements are notoriously difficult to style and many are nigh-impossible to get consistent across browsers and OSs. My approach has always been to hide the form element using javascript (usually jQuery) and construct something similar using divs and spans. That way the sky's the limit when it comes to styling.
You need to ask yourself if it's 100% necessary to have that different style though; deviating from standard form elements isn't great usability.

A: As of HTML4, an OPTION may only contain PCDATA, that is plain character data without any child-elements. The characters will be parsed (e.g. entities).
http://www.w3.org/TR/html401/interact/forms.html#edef-OPTION
As of HTML5, only text-content is allowed inside an OPTION.
http://dev.w3.org/html5/spec/the-option-element.html
In other words, you are using invalid HTML, that is hardly to be parsed by any browser. In fact I didn't know of a single browser, that is capable of displaying HTML elements inside an OPTION-tag. (…until I read this question…)

A: Use this CSS
select { font-style: italic;   }

select option  {
  font-style: normal;
}

select option:first-child {
  font-style: italic;
}

Example jsFiddle
But unfortunately this style is applied only on Firefox

A: As others have already pointed out, the mark-up is invalid and getting native form controls consistent across browsers is on the scale somewhere between very difficult to impossible.
In my opinion you are correct in thinking that JavaScript solution is probably the least effort and safest approach if you don't mind the page weight overhead of including one or more libraries and/or plugins and are happy with the non-JS fallback of the <select> not looking so pretty.
Of the many <select> replacement jQuery plugins available, I highly recommend the Select 2 plugin. It has a rich feature set which already supports adding placeholder text to the control that you can style accordingly.

A: italic is not apply in chrome and opera. plz check http://www.electrictoolbox.com/style-select-optgroup-options-css/
we can give any design for options.
<select name="name" id="id">
    <option style='font-style: italic; font-weight:bold;' selected="selected" value="#">
        Choose One
    </option>
    <optgroup label="Option group 1">
        <option value="TestValue">    TestValue</option>
        <option value="TestValue">    TestValue</option>
        <option value="TestValue">    TestValue</option>
    </optgroup>
</select>

css:
select option {
    background: none repeat scroll 0 0 #E5E3E3;
    border: 1px dotted #CCCCCC;
    height: 15px;
    line-height: 15px;
    text-indent: 3px;
    text-transform: capitalize;
    z-index: -9999;
}
optgroup { /* Change font style and text alignment */
    font-style:italic;
    text-align:right;
}

A: Not all browsers support HTML tags within <option> tags.


text:
Q: How to fire a javascript function after setting a radio button value with a mysql query result when the page loads I'm using php & mysql (with a pinch of javascript).  This is a simple "edit" form, that auto-fills the various elements from data in a table.  On the form is a set of radio buttons which are set by the data when the page loads.  As in the "add new" form, this "edit' form has javascript functions which are triggered by onclick(), which display either another set of radio buttons or a text entry box, when the user makes a selection. (That part works just fine.)
How can I trigger/fire these scripts to display the appropriate elements automatically when the page loads?  (Really don't want to delve into the jQuery arena at this time - as I need to get this piece of the project wrapped up ASAP.)
      echo "
";
        echo "Transport: 	";
        echo "<input type=radio id=transppnd name=transp value='pnd'";
        //  $prepdel: var holding 1 or 0 from database table field
        if($prepdel>0){
          echo "checked";
        }
        echo" onclick='showpnd()'>Prep & Deliver";

        echo " <input type=radio id=transpcpu name=transp value='cpu'";
        //  $prepdel: var holding 1 or 0 from database table field
        if($prepdel<1){
            echo "checked";
        }
        echo " onclick='showcpu()'>Customer pickup	";
     echo "
";

A: Looks like you want to call your showcpu() and showpnd() methods on page load.  Just add a script like this at the bottom of your html page:

I don't know php but maybe something like this?
if($prepdel>0){
    echo "";
}

*****************************UPDATE********************************
echo "<input type=hidden id=porc name=porc value='$prepdel'>";


text:
Q: c# -> javascript, Json decoding misses property I have a c# object (below) that I'm trying to send to my javascript.
My problem is, that while I can iterate over the items in the list, I can't get to the string-property ('Period').
Referencing the object in JS shows no property at all. After Json-encoding in c#, I can still see the property just before returning it to caller (hovering over the result variable in below function):
[OutputCache(Duration = 0, VaryByParam = "None")]
public JsonResult GetRankingList() {
 Response.ContentType = "text/javascript";
 var user = _userService.GetUserByPrincipal(User);

 // Note, we do this while the user waits as we need to make progress in repeated calls to get the compared ranking list.
 _businessLogicServiceMaintenance.PerformMaintenanceSteps();

 //TODO: Replace with userid (Guid)
 var rankingList = _presenterService.GetRankingListForDisplay(user);

 if (rankingList == null)
  return Json("");

 var result = Json(rankingList);
 return result;
}

How on earth can I get past this? Any comments appreciated!
Yours, Anders, Denmark,
public class RankingListForDisplay : List<RankingListLine>
{
    public string Period { get; set; }
}

A: Thanks for taking your time - I found a solution.
I changed above implementation of RankingListForDisplay to the one below. For some reason json likes it way better ;-)
public class RankingListForDisplay
{
    public List<RankingListLine> Lines { get; set; }
    public string Period { get; set; }

    public RankingListForDisplay()
    {
        Lines = new List<RankingListLine>();
        Period = "<Unspecified>";
    }
}


text:
Q: pandas to_excel removes hyperlink in cells I created an excel file using openpyxl which has some hyperlinks using the following command:
=HYPERLINK("{}", "{}")'.format(link, "Link Name")
But when I use pandas to sort and then save the excel file. the hyperlinks are gone.
what am I doing wrong?

A: Jimmy
I think this could be useful for you
Cheers
Read Excel file which has one of the column as Hyperlink through python


text:
Q: How do virtual methods work in C#? I know in C++ there are vpointer and vtable.
The virtual function table  is a list of method pointers to the virtual methods in the class.
Each instance of a class has a pointer to the table, which is used when we call a virtual method from the instance.
I want to know how this implemented in C#. As I know the concept of virtual tables are the same. But what about vpointer is GetType() is used instead.
I would appreciate as much details as possible.
Thank you.

A: Vtables are one possible approach in C++, they are not mandated by the C++ standard. The approach .NET uses clearly meets the published standards for the CLI and C#, but the implementation details are not specified (and could potentially change).
You can infer some details from the way that interfaces, overridden members and "new" members work.
Why do you want to know this? If you have a specific problem then stating the problem will allow others to address that directly.

A: Take a look at their documentation in the C# spec: 10.5.3 Virtual Methods (although it's the spec not the implementation).


text:
Q: VPN to specific organization I have a question about VPN in ubuntu 15.10.
I want to connect a VPN of Lund university, Sweden.
What I have are:
my user-name and the password
Also I'm able to configure the VPN from the network manager, I already connected to another VPN, but I have the three files ca.crt, certificate.crt and key.key,  They are general files so I can use to connect to that VPN?
Also I don't know what's the gateway, it can be connect.lu.se?
At least I wanna know How can I connect to Lund university using my user-name and password, which I used on windows8. Below you can find an explanation of what I do.
The right part shows the main network manager window to create the VPN and the left 4 small windows show the advanced options. In order to get the free vpn work, I write the gateway, user-name,password and the three certificate files downloaded, then I go to the advanced options. First tab (General) I put the port to 443, mark on use LZO compression and use TCP. Second tab just put Cipher to AES_128-CBC

Thanks,
Elsaid

A: Run this:
sudo apt-get install openvpn

To install the OpenVPN package. Then, make a new file in your home directory, client.conf. Edit that file to contain the following:
# Specify that we are a client and that we
# will be pulling certain config file directives
# from the server.
client

# Use the same setting as you are using on
# the server.
# On most systems, the VPN will not function
# unless you partially or fully disable
# the firewall for the TUN/TAP interface.
;dev tap
dev tun

# Windows needs the TAP-Win32 adapter name
# from the Network Connections panel
# if you have more than one.  On XP SP2,
# you may need to disable the firewall
# for the TAP adapter.
;dev-node MyTap

# Are we connecting to a TCP or
# UDP server?  Use the same setting as
# on the server.
;proto tcp
proto udp

# The hostname/IP and port of the server.
# You can have multiple remote entries
# to load balance between the servers.
remote connect.lu.se 1194
;remote my-server-2 1194

# Choose a random host from the remote
# list for load-balancing.  Otherwise
# try hosts in the order specified.
;remote-random

# Keep trying indefinitely to resolve the
# host name of the OpenVPN server.  Very useful
# on machines which are not permanently connected
# to the internet such as laptops.
resolv-retry infinite

# Most clients don't need to bind to
# a specific local port number.
nobind

# Downgrade privileges after initialization (non-Windows only)
;user nobody
;group nogroup

# Try to preserve some state across restarts.
persist-key
persist-tun

# If you are connecting through an
# HTTP proxy to reach the actual OpenVPN
# server, put the proxy server/IP and
# port number here.  See the man page
# if your proxy server requires
# authentication.
;http-proxy-retry # retry on connection failures
;http-proxy [proxy server] [proxy port #]

# Wireless networks often produce a lot
# of duplicate packets.  Set this flag
# to silence duplicate packet warnings.
;mute-replay-warnings

# SSL/TLS parms.
# See the server config file for more
# description.  It's best to use
# a separate .crt/.key file pair
# for each client.  A single ca
# file can be used for all clients.
ca ca.crt
cert certificate.crt
key client.key

# Verify server certificate by checking
# that the certicate has the nsCertType
# field set to "server".  This is an
# important precaution to protect against
# a potential attack discussed here:
#  http://openvpn.net/howto.html#mitm
#
# To use this feature, you will need to generate
# your server certificates with the nsCertType
# field set to "server".  The build-key-server
# script in the easy-rsa folder will do this.
ns-cert-type server

# If a tls-auth key is used on the server
# then every client must also have the key.
;tls-auth ta.key 1

# Select a cryptographic cipher.
# If the cipher option is used on the server
# then you must also specify it here.
;cipher x

# Enable compression on the VPN link.
# Don't enable this unless it is also
# enabled in the server config file.
comp-lzo

# Set log file verbosity.
verb 3

# Silence repeating messages
;mute 20

This is a generic client config file for OpenVPN.  Now, to connect, run the following command from your home directory:
sudo openvpn client.conf

To connect using your given config file.
MAKE SURE THAT YOUR CA.CRT, CERTIFICATE.CRT, AND KEY.KEY FILES ARE ALSO IN YOUR HOME DIRECTORY


text:
Q: What are the techniques for Quick Authentication to the XERO API? How can an application check if the user has the correct key? certificate and validate those requirements against those in the xero api? my current algorithm only checks the accessibility of what is required in-order to make an initial connection to the api but doesn't necessarily check that information is valid.
//check for files/keys before running xero
function provideXeroConnection($request = 'xml'){
    //validate everything is inplace
    if(validateXeroAuth()){
        //if it is then bubble the object up to (XeroAc & JSONEngine or XMLEngine)
        return new Xero(XeroAuths::getSetting('xero_consumer'), XeroAuths::getSetting('xero_secret'), XERO_PUBLIC_KEY_PATH, XERO_PRIVATE_KEY_PATH, $request );
    } else return false;
/*
* @TODO validate xero authentication
*/
function validateXeroAuth(){
    $xero_key = XeroAuths::getSetting('xero_consumer');
    $xero_secret = XeroAuths::getSetting('xero_secret');
    if(file_exists(XERO_PUBLIC_KEY_PATH) && file_exists(XERO_PRIVATE_KEY_PATH)){
        if(validateValue($xero_key) && validateValue($xero_secret)){
            return true; //feature not completely implemented @TODO
        } else return false;
    } else return false;
}
//validate the value for xero
function validateValue($value){
    if(isset($value)){
        if(!is_null($value)){
            if(!empty($value)){
                return true;
            } else return false;
        } else return false;
    } else return false;
}

The script in use is opensource and is available at github here. I've also read the example implementation of the script here. But I haven't really found anything for a quick authentication.
The reason I'm asking this.. is I'd much rather have my users keys and certificates authenticated in a couple of seconds rather than minutes (give and take how many invoices or contact information has to be recieved). Any help on this issue would be much appreciated! :)

A: The quick answer to your question is to do a GET Organisation call - if that fails with a 401, you know you have done something wrong.
The long answer is: are you sure you should be using a private API application if you are getting users to authenticate? There are other application types that may be better suited to this scenario (I've made some assumptions so I may be wrong). This might help: API Application type guide.


text:
Q: Azure Deployment Slots and URLs in code I have a txt file in my solution that serves as a template for emails sent by my app.   In the file there are links that contain the host URL of my app.  When I am deployed to a staging slot in my Azure App Service, the url of the deployment is myapp-staging.azurewebsites.net and to test emails in staging we those links must contain that URL.
In production, the host URL will be  myapp.customdomain.com.  The url in the text file now needs reflect this url used in the production slot.
Is there a way to use deployment slots and the benefits of swapping if I need to have URLs in the code being deployed to each slot?   I looked at the Deployment Slot App Settings but I don't see how I could use those to re-write URLs in those text files.

A: You should store only the resource path after the server address, in which case you need to get the server url in the code itself and concatenate with the rest of the path it will contain in the file.
To get the current server path you will use:
string.Format("{0}://{1}", Request.Url.Scheme, Request.Url.Authority)

A:
how I could use those to re-write URLs in those text files.

Firstly, you can check and replace the hostURL from the text file dynamically based on WEBSITE_SITE_NAME. The following code snippet is for your reference.
var siteName = Environment.ExpandEnvironmentVariables("%WEBSITE_SITE_NAME%");

string template = System.IO.File.ReadAllText(Server.MapPath("~/Content/email.txt"));

//determine if it is staging slot

if (siteName.IndexOf("-staging") > 0)
{
    //replace hostURL based on siteName

    template = Regex.Replace(template, @"hostURL:myapp.azurewebsites.net", "hostURL:myapp-staging.azurewebsites.net");
    System.IO.File.WriteAllText(Server.MapPath("~/Content/email.txt"), template);
}
else
{
    //replace hostURL based on siteName

    template = Regex.Replace(template, @"hostURL:myapp.azurewebsites.net", "hostURL:myapp.customdomain.com");
    System.IO.File.WriteAllText(Server.MapPath("~/Content/email.txt"), template);
}

Secondly, if possible, you can deploy two separate text files with different hostURL content to production and staging slot.


text:
Q: Pinching and positive definite matrices A pinching over $M_n({\mathbb C})$ is an endomorphism $T$ where the $(i,j)$-entry of $T(M)$ is given either by $0$ or by $m_{ij}$, depending on the pair $(i,j)$. Let us say that a pinching is symmetric if the rule is the same for $(i,j)$ and $(j,i)$ whenever $j\ne i$.
R. Bhatia has shown that the pinching $M\mapsto D(M):={\rm diag}(m_{11},\ldots,m_{nn})$ is a contraction for every unitarily invariant norm $\|\cdot\|$. In other words,
$$\|D(M)\|\le\|M\|,\qquad\forall M\in M_n({\mathbb C}).$$
Remark that the map $D$ sends the cone of positive definite Hermitian matrices $HPD_n$ into itself.
It is not difficult to extend Bhatia's result to block pinching $\Delta$, in which $\Delta(M)$ is block diagonal, made from diagonal blocks of $M$. Again $\Delta$ sends $HPD_n$ into itself. On an other hand, it is known that some non-block diagonal pinching are not contracting and do not preserve $HPD_n$. For instance, the linear map
$$M=\left( \begin{array}{ccc}
a & b & c \\\\
d & e & f \\\\ g & h & k \end{array} \right)\mapsto B(M)=\left( \begin{array}{ccc}
a & b & 0 \\\\
d & e & f \\\\ 0 & h & k \end{array} \right).$$
The operator norm of $B$ (when $M_n({\mathbb C})$ is endowed with a unitarily invariant norm) is larger than $1$ (Bhatia), and there exists $H\in HPD_n$ such that $B(M)$ is even not semi-positive definite.
Question. Are the following three properties equivalent ?

*

*The pinching $T$ is symmetric and contracting for every unitarily invariant norm of $M_n({\mathbb C})$.

*The pinching $T$ sends $HPD_n$ into itself.

*The pinching $T$ is block diagonal.

A: R. Bhatia proved (in Amer. Math. Monthly 107) that the operator $D_k$ taking $M$ to its $k$-th diagonal ($M_{ij}$, $j-i=k$) contracts any unitarily invariant norm, so 1 implies neither of 2, 3. Still, it is an interesting question to characterize those "contractive pinchings".
EDIT (partly answering the modified question): Consider a symmetric pinching,  $M\mapsto P(M)=(p_{ij}M_{ij})_{ij}$, $p_{ij}=p_{ji}\in\{O,1\}$. Property (2) implies $p_{ii}=1$ for all $i$, since a positive definite matrix has positive diagonal elements. Property (1) doesn't imply the same thing, since all $p_{ij}$ might be zero (as by Guillaume's comment) [EDIT: a slightly less trivial example is $p_{11}=p_{22}=0$, $p_{12}=p_{21}=1$, and $p_{ij}=\delta_{i,j}$ if $i>2$ or $j>2$ ]. So let us assume $p_{ii}=1$ as part of the hypothesis. Then both (1) and (2) imply that the relation between indices $\{(i,j): p_{ij}=1\}$ is reflexive and symmetric. If it is not transitive (i.e. if it is not an equivalence relation, or equivalently (3) doesn't hold), then there are three distinct indices $i,j,k$ with $p_{ij}=p_{jk}=1$ but $p_{ik}=0$. Let $I=\{i,j,k\}$. Then,
considering your $B$ example, $P$ doesn't preserve positive definiteness, since the $I \times I$ principal minor of $P(M)$ can be negative for a positive definite $M$. Hence (2) implies (3), and they are equivalent. Similiarly, restricting $P$ to matrices supported on $I\times I$, if $B$ doesn't contract some "natural" unitarily invariant norm on $3\times 3$ matrices,the same must be true of $P$. But it is easily seen that $B$ doesn't contract the trace norm (sum of singular values), since the all ones $3\times3$ matrix $E$ has trace norm $3$ and $B(E)$ has trace norm $1+2\sqrt{2}$ (cf Bhatia).
Hence (1),(2),(3) are equivalent, if in (1) one assumes $p_{ii}=1$ for all $i$ (i.e. the symmetric pinching also preserves the  diagonal).

A: A pinching has the form $M \mapsto T * M$, where $*$ is the entrywise product and $T$ is a $0/1$-matrix. I have the impression that (1)-(3) are all equivalent to
(4) T is positive,
and that it can be proved via the following: if a $0/1$-matrix $T$, with $1$ on the diagonal, avoids the pattern
$\left( \begin{array}{ccc} 1 & 1 & 0 \\ 1 & 1 & 1 \\ 0 & 1 & 1 \end{array} \right)$, then $T$ must be block-diagonal.
Either (1) or (2) imply that $T$ avoids this pattern: for (1) via your example, for (2) because it implies (4) (apply the pitching to the matrix with all entries equal to 1).

A: If you restrict $T$ to be symmetric, than don't you already have the answer stated in your question? You've claimed that
(3) $\implies$ (1)  by generalizing Bhatia.
Now (3) $\implies$ (2) trivially. It suffices to show that "not (3)" $\implies$ "not (1)/(2)". But this follows from your claim about the operation $B$, after noting that:

if $T$ is a symmetric matrix with entries either 0 or 1, with only 1s on the diagonal, and $T$ is not block diagonal, then there exists $i,j,k$ distinct indices such that $T_{ij} = T_{jk} = 1$ and $T_{ki} = 0$.

Proof: By re-indexing the basis, you can bring the matrix of $T$ to a form where if $j > i$, $T_{ij} = 0$, then $T_{ik} = T_{lj} = 0$ for all $l < i < j < k$. Take $a < b$ such that $T_{ab} = 0$, $T_{a+1,b} = T_{a,b-1} = 1$. Now, if all such $a,b$ differ only by 1 ($b-1 = a$), then clearly the matrix of $T$ is block diagonal. If $a,b$ differs by at least two, chose $a, a+1, b$ to be the triplet.


text:
Q: How remove yandex toolbar from my browser? I want to remove yandex toolbar. I cant see it in my control panel, i also remove it in my registry, but I can see it. I also remove my cache, but it's still there.

here's the extensions of chrome
enter image description here

A: Go to
chrome://extensions/

and remove your toolbar.


text:
Q: How to get a date range prompt using a SQL connection in Excel So I have created a connection in MS Query and am now using it in Excel. I want to create a macro button that when I click it the query automatically runs.
However when it runs I want you to be allowed to select the input for some fields. For example the two date fields and the entry field here:
WHERE
    (ENTERED_ON BETWEEN {ts '2020-02-01 00:00:00'} AND {ts '2020-02-14 00:00:00'})
    AND (ENTRY = 'apple')

Any help would be greatly appreciated. Also just to note the date and time has to be specifically in that format. I also want to keep the prompt as simple as possible for users so ideally with something like:
Dim sUserInput As String
sUserInput = InputBox("Enter Number:", "Collect User Input")

A: Instead of an input prompt, I use a cell range to refer to my date range (which is much easier to format in the way you want it) and VBA coding that updates the command text of the SQL query within the excel workbook. So something like this:
Sql = Sql & " .... SELECT... FROM... " & vbCrLf 'enter your FROM and SELECT statements
Sql = Sql & "WHERE " & vbCrLf
Sql = Sql & "ENTERED_ON BETWEEN '" & Range("A1") & "' AND '" & Range("A2") & "' " & vbCrLf
Sql = Sql & "AND (ENTRY = 'apple')"

With ThisWorkbook.Connections("Your Connection Name Here").ODBCConnection
    .CommandText = Sql
    .Refresh
End With

You can then attach the command to a macro button which will update your command text string with your date ranges. For bigger queries, I would suggest using a SQL to VBA string online convert like here: http://www.dpriver.com/pp/sqlformat.htm
Saves alot of time!


text:
Q: How can I develop C# in Xcode? I installed the mono CSharpPlugin for Xcode but I don't see an entry in the New Project wizard that looks like "CSharp Project" or something similar. My guess is that the plugin hasn't been developed lately and it doesn't work with the newer versions of Xcode, because I saw that the last update to the plugin code was back in 2007.
Is there another way to develop C# applications on a Mac, and benefit from testing, breakpoints, etc? I need this to work on a project for school.

A: Your best bet would be to install MonoDevelop (aka Xamarin Studio) which can be used to write Mono-based applications on Mac OS X. It comes with project templates for Mac apps that you can use to write open source Mac apps in C# (via the MonoMac binding).

A: Xcode 4 changed where templates are installed.  You need to look at the instructions page and then decide the appropriate place to put the files in the new Xcode 4 hierarchy.
For example, the file templates need to go into this directory: "~/Library/Developer/Xcode/UserData/File Templates".
There might be more useful information in this related Stackoverflow question.


text:
Q: How to prove that $\aleph_0+\aleph_0=\aleph_0$ How to prove that $\aleph_0+\aleph_0=\aleph_0$
In my exercise book I have that proof:

Let $B=2\mathbb{N}+1$ and $A=2\mathbb{N}$
$A,B $ disjoint and $A+B=\aleph_0$

But to me it looks like example and not a proof.

A: If the set $A$ has cardinality $\aleph_0$, then there is a bijection $A \to \mathbb{N}$.
Now, since $\mathbb{N} \to 2\mathbb{N}+1$ and $\mathbb{N} \to 2\mathbb{N}$ are bijections, then given two sets $X$ and $Y$ with cardinality $\aleph_0$, there are two bijections
$$ \phi: X \to \mathbb{N} \to 2\mathbb{N} +1 $$
and
$$ \psi: Y \to \mathbb{N} \to 2\mathbb{N} $$
Therefore there is a bijection from the disjoint union $X \cup Y \to \mathbb{N}$ , that is "$\phi \cup \psi$" (it is $\phi$ on the $X$ part and $\psi$ on the $Y$ part of the set).
Recall that $\mathbb{N} = 2\mathbb{N} \cup 2\mathbb{N}+1$ and you're done:
$$\aleph_0 + \aleph_0 = |X| + |Y| = |X \cup Y| = \aleph_0$$


text:
Q: WordPress - Show previewed styles only in Customizer I'm trying to write a WordPress theme that saves my Customizer settings to a separate, static stylesheet so that only a CSS file needs to be served to the user instead of a bunch of get_theme_mod requests. I generate this file with the code below:
<?php
    $my_css = '/* Styles with get_theme_mod() fetched here */';

    $customize_css = fopen(get_template_directory() . '/assets/styles/customize.css', 'w') or die("Unable to open file!");

    // Write static CSS file
    fwrite($customize_css, $my_css);
    fclose($customize_css);

?>

However, I still need to set it up so that I can live preview my settings when using the Customizer, and I'm not sure how to approach that. I know I can put the below code in the <head>:
<style>
   .some-element {
       attribute: <?php echo get_theme_mod('my_theme_setting'); ?>
   }
</style>

But I'm not sure how to/if I can load this only when viewing a Customizer preview. I can't find in the WP documentation if there's something similar to, say, is_admin_bar_showing for the Customizer?

A: Immediately found the answer:
<?php is_customize_preview(); ?>

https://codex.wordpress.org/Function_Reference/is_customize_preview


text:
Q: Multilayer feedforward net fails to train in TensorFlow I started with the TensorFlow tutorial to classify the images in the mnist data set using a single layer feedforward neural net. That works OK, i get 80+ percent on the test set. Then I tried to modify it to a multilayer network by adding a new layer in between. After this modification all my attempts to train the network fails. The first couple of iterations the network becomes a bit better but then it stagnates at 11.35% accuracy.
First twenty iterations using 1 hidden layer:
Train set: 0.124, test set: 0.098
Train set: 0.102, test set: 0.098
Train set: 0.112, test set: 0.101
Train set: 0.104, test set: 0.101
Train set: 0.092, test set: 0.101
Train set: 0.128, test set: 0.1135
Train set: 0.12, test set: 0.1135
Train set: 0.114, test set: 0.1135
Train set: 0.108, test set: 0.1135
Train set: 0.1, test set: 0.1135
Train set: 0.114, test set: 0.1135
Train set: 0.11, test set: 0.1135
Train set: 0.122, test set: 0.1135
Train set: 0.102, test set: 0.1135
Train set: 0.12, test set: 0.1135
Train set: 0.106, test set: 0.1135
Train set: 0.102, test set: 0.1135
Train set: 0.116, test set: 0.1135
Train set: 0.11, test set: 0.1135
Train set: 0.124, test set: 0.1135

It does not matter how long time I train it, it is stuck here. I have tried to change from rectified linear units to softmax, both yields the same result. I have tried to change the fitness function to e=(y_true-y)^2. Same result.
First twenty iterations using no hidden layers:
Train set: 0.124, test set: 0.098
Train set: 0.374, test set: 0.3841
Train set: 0.532, test set: 0.5148
Train set: 0.7, test set: 0.6469
Train set: 0.746, test set: 0.7732
Train set: 0.786, test set: 0.8
Train set: 0.788, test set: 0.7887
Train set: 0.752, test set: 0.7882
Train set: 0.84, test set: 0.8138
Train set: 0.85, test set: 0.8347
Train set: 0.806, test set: 0.8084
Train set: 0.818, test set: 0.7917
Train set: 0.85, test set: 0.8063
Train set: 0.792, test set: 0.8268
Train set: 0.812, test set: 0.8259
Train set: 0.774, test set: 0.8053
Train set: 0.788, test set: 0.8522
Train set: 0.812, test set: 0.8131
Train set: 0.814, test set: 0.8638
Train set: 0.778, test set: 0.8604

Here is my code:
import numpy as np
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# Parameters
batch_size = 500

# Create the network structure
# ----------------------------

# First layer
x = tf.placeholder(tf.float32, [None, 784])
W_1 = tf.Variable(tf.zeros([784,10]))
b_1 = tf.Variable(tf.zeros([10]))
y_1 = tf.nn.relu(tf.matmul(x,W_1) + b_1)

# Second layer
W_2 = tf.Variable(tf.zeros([10,10]))
b_2 = tf.Variable(tf.zeros([10]))
y = tf.nn.softmax(tf.matmul(y_1,W_2) + b_2)

# Loss function
y_true = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_true * tf.log(y), reduction_indices=[1]))

# Training method
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_true,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Train network
# -------------
sess = tf.Session()
sess.run(tf.initialize_all_variables())
batch, batch_labels = mnist.train.next_batch(batch_size)
for i in range(20):
    print("Train set: " + str(sess.run(accuracy, feed_dict={x: batch, y_true: batch_labels}))
            + ", test set: " + str(sess.run(accuracy, feed_dict={x: mnist.test.images, y_true: mnist.test.labels})))
    sess.run(train_step, feed_dict={x: batch, y_true: batch_labels})
    batch, batch_labels = mnist.train.next_batch(batch_size)

So with this code it does not work, but if I change from
y = tf.nn.softmax(tf.matmul(y_1,W_2) + b_2)

to
y = tf.nn.softmax(tf.matmul(x,W_1) + b_1)

then it works. What have I missed?
Edit: Now I have it working. Two changes was needed,first of all initiating the weights to random values instead of zero (yes, actually it was the weights that needed to be not zero, the bias as zero was OK despite the relu function). The second thing is strange to me: If I remove the softmax function from the output layer and instead of manually applying the formula for cross entropy uses the softmax_cross_entropy_with_logits(y,y_true) function then it works. As I understand it that should be the same.. And previously I also tried with the sum of squared errors which didn't work either.. Anyway, the following code is working. (Quite ugly though, but working..) With 10k iterations it gets me 93.59% accuracy on the test set, so not optimal in any way but better than the one with no hidden layer. After only 20 iterations it's already up to 65%.
import numpy as np
import tensorflow as tf

from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("MNIST_data/", one_hot=True)

# Parameters
batch_size = 500

# Create the network structure
# ----------------------------

# First layer
x = tf.placeholder(tf.float32, [None, 784])
W_1 = tf.Variable(tf.truncated_normal([784,10], stddev=0.1))
b_1 = tf.Variable(tf.truncated_normal([10], stddev=0.1))
y_1 = tf.nn.relu(tf.matmul(x,W_1) + b_1)

# Second layer
W_2 = tf.Variable(tf.truncated_normal([10,10], stddev=0.1))
b_2 = tf.Variable(tf.truncated_normal([10], stddev=0.1))
y = tf.matmul(y_1,W_2) + b_2

# Loss function
y_true = tf.placeholder(tf.float32, [None, 10])
cross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y,y_true))

# Training method
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_true,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

# Train network
# -------------
sess = tf.Session()
sess.run(tf.initialize_all_variables())
batch, batch_labels = mnist.train.next_batch(batch_size)
for i in range(10000):
    if i % 100 == 0:
        print("Train set: " + str(sess.run(accuracy, feed_dict={x: batch, y_true: batch_labels}))
                + ", test set: " + str(sess.run(accuracy, feed_dict={x: mnist.test.images, y_true: mnist.test.labels})))
    sess.run(train_step, feed_dict={x: batch, y_true: batch_labels})
    batch, batch_labels = mnist.train.next_batch(batch_size)

A: Few suggestions:
1- Add standard deviation to both weight variable initialization, instead of initializing with zeros:
weight_1 = tf.Variable(tf.truncated_normal([784,10], stddev=0.1))

2- Lower the learning rate until the accuracy value show a varying behavior.
3- When using RELU, initialize bias with a slightly positive value. This suggestion probably has less to do with the issue that you are seeing.
bias_1 = tf.Variable(tf.constant(.05, shape=[10]))


text:
Q: Multiply every entry in column by a fixed number in SQL In SQL, say I have a table of the following layout:
id    name      age
1     george    12
2     tom       14
3     charles   19
4     henry     21
5     fiona     12
6     kate      14
...

If I discover that I've made a terrible inputting mistake, and that everybody is actually twice their age, is there a way to multiply the age column by 2 in one sweep instead of needing to painstakingly go through the whole column and edit each age individually (pretend I have 500 entries so manual work is out of the question).
Is there a SQL solution?

A: Yes, run an update:
update theTable set age = age * 2

Depending on the settings in the database, you might not be allowed to run an update without a where (to protect against mistakes), then you would add a dummy comparison:
update theTable set age = age * 2 where 1 = 1

A: It's really easy:
UPDATE table SET age=age*2


text:
Q: How to solve this JS SyntaxError? I'm new to JS and I'm trying some stuff to learn it. Here I'm stuck with this SyntaxError. I know it's supposed to point to an identifier starting with a digit, but there's none... So where's the problem ? Could you please help me ?
var mouse = document.getElementById('square');
SyntaxError: identifier starts immediately after numeric literal
div.onmouseover = function() {
  var posL = 275;
  var posV = 275;
  var time = setInterval(move, 2);
  function move() {
    if ((posL==275)&&(posV==275)){
      box.style.left = 275px;
      box.style.top = 0px;
      posV = 0;
    }
  }
}

A: Javascript is trying to parse 275px and 0px as code. It recognizes numbers like 275 as a numerical value but is puzzled by the px attached to it. You should use strings here, in JS they are delimited with ' or ".
Corrected code:
var mouse = document.getElementById('square');
//SyntaxError: identifier starts immediately after numeric literal
div.onmouseover = function() {
  var posL = 275;
  var posV = 275;
  var time = setInterval(move, 2);
  function move() {
    if ((posL==275)&&(posV==275)){
      box.style.left = '275px';
      box.style.top = '0px';
      posV = 0;
    }
  }
}

A: You're missing the qoutes:
 box.style.left = "275px";
 box.style.top = "0px";

Also, in div.onmouseover you need to define div first or you probably mean mouse.onmouseover


text:
Q: How to select a particular slide from a presentation using powershell? I need a slide object that takes a particular slide according to the slide number given.
I used slides.select method but it threw an error that select method is not available for that object.
Can anyone help ?
Thanks in advance :)
Following is the part of the code where I'm stuck
    if($slide_count -lt $slide_no)
{
# In case the base ppt does not have the number of slides already
    for($j=$slide_count;$j -le $slide_no;$j++)
   {
    $slide = $my_ppt.Slides.Add($my_ppt.Slides.Count + 1, 15)
   }
}
else
{
   $slide=$my_ppt.Slides.select($slide_no)
}

The else part is where I need help. I tried the actual syntax which threw the same error at the Slides part itself.
      $slide=$my_ppt.Slides($slide_no).select


text:
Q: R - Error writing csv to file - "Error in file(file, ifelse(append, "a","w"... Windows 7. Works until a certain point I've been using R (Rstudio and R version 3.2.4) to automate my analysis. Worked all day on one location dataset. Read and written with no issues to the same drive as this one (just a different folder titled by the location name). It reads and writes multiple times throughout the code with progressive steps being dependent on the output of the other.
Just changed to another dataset - Changed working directory and changed all save directory locations to the correct.
Reads and writes the first part of the code fine (I've checked user permissions as I've read that this can be a problem with Windows 7 users here: R, command line, write to file fails).
Progresses to generate the next output and get the error

"Error in file(file, ifelse(append, "a", "w")) :
cannot open the connection
In addition: Warning message:
In file(file, ifelse(append, "a", "w")) :
cannot open file 'F:/PhD/Working Projects/Chapter 1 Experiments/Current Data (MIDAS)/Dodoma/ Stat Outputs/Dod.Cor.Temp.8595.csv': No such file or directory"

Subsequently the associated ggplot doesn't appear to be generated and gives the error (Doesn't appear in the plot window? could this suggest :

"Saving 22.6 x 16.1 cm image
Error in grDevices::png(..., res = dpi, units = "in") :
unable to start png() device
In addition: Warning messages:
1: In grDevices::png(..., res = dpi, units = "in") :
unable to open file 'F:/PhD/Working Projects/Chapter 1 Experiments/Current Data (MIDAS)/Dodoma/ Graph Outputs//Dod.Climatology.Corrected.8595.png' for writing
2: In grDevices::png(..., res = dpi, units = "in") : opening device failed"

Section of code is this:
# load the data file, hit tab for selections
    dar_baseline <- read.csv(file = "Dodoma_Baseline_Clean.csv",header = TRUE)

#Calculating stats for Temperature (Gather code commented out)
#GGPlot2 - Individual columns code. Check stage 1 to make sure data is OK. NOT FINAL OUTPUT
temp.stats.wide <- dar_baseline %>% group_by(Month) %>%    summarise(meantemp=mean(AIR_TEMPERATURE,na.rm = TRUE),
                                                              sdtemp = sd(AIR_TEMPERATURE,na.rm = TRUE),
                                                              mintemp = min(AIR_TEMPERATURE,na.rm = TRUE),
                                                              maxtemp = max(AIR_TEMPERATURE,na.rm = TRUE),
                                                              sd4temp = sdtemp*4,
                                                              HighSD4temp = meantemp + sd4temp,
                                                              LowSD4temp =  meantemp - sd4temp)

#Save file Temp.stats.wide as ORIGINAL uncorrected dataset (Before SD4 correction).
write.csv(temp.stats.wide, "F:/PhD/Working Projects/Chapter 1    Experiments/Current Data (MIDAS)/Dodoma/Stat Outputs/Dod.Uncor.Temp.8595.csv")

# Join Temperature stats to the raw data. Nicknamed JoinT (Joining of data frames)
dar_joinT <- merge(x = dar_baseline,y = temp.stats.wide,by = "Month")

#After joining data frames - dplyr alternative to for loop
# filter selects row that meet the criteria, hence two filter commands for  high and low SD range
clean_data <- dar_joinT %>% filter(AIR_TEMPERATURE < HighSD4temp) %>%    filter(AIR_TEMPERATURE > LowSD4temp)

#check data with plot - Temperature. Outliers have been left in for demonstration.
ggplot(data = clean_data,aes(Month, meantemp))+
  geom_ribbon(aes(ymin = LowSD4temp, ymax = HighSD4temp), fill = "gray80") +
  geom_line(size=1.5,aes(col="Mean Temperature"))+
  geom_point(data = dar_baseline,aes(Month,AIR_TEMPERATURE, col="Outliers"))+
  geom_point(data = clean_data,aes(Month,AIR_TEMPERATURE, col="Monthly Spread")) +
  scale_colour_manual(name = "Key", values=c("#009E73","#D55E00","black")) +
  ggtitle("Dodoma Temperature Climatology (1985-1995)
      With Outliers") +
  xlab("Month") +
  ylab ("Temperature °C") +
  scale_x_continuous(breaks =1:12) +
  scale_y_continuous(breaks = c(0,5,10,15,20,25,30,35,40,45))+
  theme_minimal()

#Graph saved to demonstrate outliers prior to removal.
ggsave("Dod.Outliers.Plot.8595.png", plot=last_plot(), path =   "F:/PhD/Working Projects/Chapter 1 Experiments/Current Data (MIDAS)/Dodoma/Graph Outputs/", scale = 1, width = NA, height = NA, units = c("cm"), dpi = 300, limitsize = TRUE)

#Clean stats wide (To correct altered mean values given the removal of data   outside of 4 standard deviations)
clean.stats.wide <- clean_data %>% group_by(Month) %>%    summarise(meantemp=mean(AIR_TEMPERATURE,na.rm = TRUE),
                                                              sdtemp = sd(AIR_TEMPERATURE,na.rm = TRUE),
                                                              mintemp = min(AIR_TEMPERATURE,na.rm = TRUE),
                                                              maxtemp = max(AIR_TEMPERATURE,na.rm = TRUE)
                                                             )

#Save clean stats wide as the mean corrected to reflect the data without SD4 errors included.
write.csv(clean.stats.wide, "F:/PhD/Working Projects/Chapter 1    Experiments/Current Data (MIDAS)/Dodoma/ Stat Outputs/Dod.Cor.Temp.8595.csv")

Saving - Clean stats wide is where the error appears.
clean.stats.wide looks like this:

As I said, it's been working fine and works on the first write.csv (temp.stats.wide) and first plot but I can't see the difference between this and the second and it works fine on another data set of the exact same setup.
Help would be greatly appreciated.
**SOLVED - Spacing issues in directory paths (See comments).


text:
Q: Sparc Solaris 2.6 will not boot I have a very old Sparc Solaris network that was working fine last week, but after a power outage none of the workstations will boot.
The network looks like this:
host A: solaris 2.6, shares /export/home to network by NFS
host B: solaris 8, runs NIS server.  Mounts /export/home/ by NFS.
host C: RHEL5, shares /share to network by NFS.  Mounts /export/home/ by NFS.
I figured that the main problem was host A, since you need the home directories available for the other workstations to boot(?).  Host A does not mount anything by NFS as far as I know.  However, this workstation will NOT boot.  The OBP bootup sequence looks like this:
Boot device <blah>
configuring network interface le0
Hostname <hostname>
check file system <everything ok>
check ufs filesystem <everything ok>
NIS domainname is <name>
starting router discovery
starting rpc services: rpcbind keyserv ypbind done
setting default interface for multicast: add net 224.0.0.0: gateway <hostname>
<HANGS at this point>

Is there some kind of debug mode so that I can get more detail as to why the workstation won't boot?  Is my network structure inherently susceptible to power outage?  Is there a way I can boot up to command line so I can at least turn off the NFS mounting?

A: This problem was due to a failure of a foreground NFS volume to mount, due to the NFS volume being unavailable.  To fix this I booted into single user mode (Thanks lain!) and modified vfstab so that it would not try to mount the volumes.  Then I continued boot and everything came up fine.  In the future I will use option bg (for baground mount) in vfstab, since the default is foreground which can cause boot problems.


text:
Q: Xamarin Shell Right to left FlowDirection not working I'm developing a new cross-platform application with Xamarin 4.0 and I want change layouts to right to left direction.
I want shell items and flyout menu in right of screen. I tried this code in Shell tag. But it didn't work.
FlowDirection = "RightToLeft"

What should I do?
Thanks.

A: Unfortunately, it should be the limit of Shell Flyout .
FlowDirection:Just can modify the direction of subview's content, not the parent layout of it.
After testing in official sample Xamarin.Forms - Xaminals , setting FlowDirection = "RightToLeft" can not changing Flyout from left of screen to right of screen.

Note: If have other solutions to solve the direction of parent layout, will update here.

A: in main activity inside OnCreate method: Make it look like that
    protected override void OnCreate(Bundle savedInstanceState)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        base.OnCreate(savedInstanceState);
        Xamarin.Essentials.Platform.Init(this, savedInstanceState);
        global::Xamarin.Forms.Forms.Init(this, savedInstanceState);

        Window.DecorView.LayoutDirection = LayoutDirection.Rtl;

        LoadApplication(new App());
    }


text:
Q: UIPopoverController for iPhone by implementing category I know that Popover controllers are for use exclusively on iPad devices, but on below question there is a comment in which user has mentioned about category, code is as below,
UIPopoverController for iphone not working?
  // UIPopoverController+iPhone.h file
  @interface UIPopoverController (iPhone)
 + (BOOL)_popoversDisabled;
 @end

  // UIPopoverController+iPhone.m file
  @implementation UIPopoverController (iPhone)
 + (BOOL)_popoversDisabled {
     return NO;
 }
 @end

Is this right way?
Will Apple approve this?,
My iPad application is already done, now I am making it universal application, so instead of using any custom popover I want to add this category so that it will solve my issue and will reduce development efforts.

A: This is very hacky way, and you'll be taking a big risk putting it on the AppStore. Sure someone may have put a version in the store where they overlooked this, but it can break any moment and Apple may decide to remove his app.
Have you tested popovers on iPhone? Will you test in iOS7.1? Will it work exactly the same on iOS7.2 or iOS 7.3?
A far better solution would be to take an open source implementation of popovers and use that for iPhone (or both).

A: I have live app with with popover in iPhone.
Just You have to create interface for popover
NSObject+UIPopover_Iphone.h
#import <Foundation/Foundation.h>

@interface UIPopoverController (overrides)
+(BOOL)_popoversDisabled;
@end

NSObject+UIPopover_Iphone.m
#import "NSObject+UIPopover_Iphone.h"

@implementation UIPopoverController (overrides)

+(BOOL)_popoversDisabled
{
    return NO;
}

@end

and now just import NSObject+UIPopover_Iphone.h  in your Viewcontroller.h
Edit
For iOS 8 you can use
WYPopoverController.


text:
Q: Alpha channel gone when converting UIImage to CVPixelBufferRef I'm using this code to create a movie from different uiimages with an AVAssetWriter. The codes works great but the problem is that the Alpha channel is gone when I add the images to the writer. I can't figure out if the alpha doesn't exists in the CVPixelBufferRef or that the AVAssetWriter isn't able to process.
My end result isn't a movie with an alpha channel but multiple images on top of each other and merged in a movie file. I can put images on top of other images in a single frame but all the images (pixel buffers) have a black background...
- (CVPixelBufferRef) pixelBufferFromCGImage: (CGImageRef) image andSize:(CGSize) size {
    @autoreleasepool {
        NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
                                 [NSNumber numberWithBool:YES],     kCVPixelBufferCGImageCompatibilityKey,
                                 [NSNumber numberWithBool:YES],     kCVPixelBufferCGBitmapContextCompatibilityKey,
                                 nil];
        CVPixelBufferRef pxbuffer = NULL;

        CVReturn status = CVPixelBufferCreate(kCFAllocatorDefault, size.width,
                                              size.height, kCVPixelFormatType_32ARGB,     (__bridge CFDictionaryRef) options,
                                              &pxbuffer);
        NSParameterAssert(status == kCVReturnSuccess && pxbuffer != NULL);

        CVPixelBufferLockBaseAddress(pxbuffer, 0);
        void *pxdata = CVPixelBufferGetBaseAddress(pxbuffer);
        NSParameterAssert(pxdata != NULL);

        CGColorSpaceRef rgbColorSpace = CGColorSpaceCreateDeviceRGB();
        CGContextRef context = CGBitmapContextCreate(pxdata, size.width, size.height, 8,     4*size.width, rgbColorSpace, (CGBitmapInfo)kCGImageAlphaPremultipliedFirst);

        NSParameterAssert(context);
        CGContextConcatCTM(context, CGAffineTransformMakeRotation(0));
        CGContextDrawImage(context, CGRectMake(0, 0, CGImageGetWidth(image),
                                               CGImageGetHeight(image)), image);
        CGColorSpaceRelease(rgbColorSpace);
        CGContextRelease(context);

        CVPixelBufferUnlockBaseAddress(pxbuffer, 0);

        return pxbuffer;
    }
}

A: This is never going to work because h.264 does not support an alpha channel. You cannot encode a movie with an alpha channel using the built in iOS logic, end of story. It is possible to composite layers before encoding though. It is also possible to compose encode with a 3rd party library that does support an alpha channel. See this question for more info.


text:
Q: How do I "ping" a different domain to check reachability (within Windows Server)? I'm troubleshooting a connectivity issue between servers on different domains.
I have a Web Service installed on DOMAIN01\SERVER1. This WebService uses Windows Authentication as its authentication mechanism.
Right now, the Web Service is setup to use DOMAIN01\SOME_USER as the only user allowed.
The clients who will connect to this Web Service are on DOMAIN02 and they've requested that the user allowed on the service should be DOMAIN02\OTHER_USER.
Whatever the user is, I need to give permission on the service's root folder to him. So, I went into the security properties of the folder and tried browsing Active Directory, but DOMAIN02 isn't listed. Hence, not allowing me to set permissions.
Given that the domain isn't listed, is it safe to assume that the domain is not accessible from that server?
Is there a way to check whether the domain is "reachable"?
And is there a way to set permissions correctly without being able to browse through active directory?
Ps.: I'm using "domain" terminology here but, to be honest, I'm not sure wheter those are actual domains os subdomains. Does it make any difference?

A: Sounds like there is no trust between Domain01 and Domain02.  To have Domain02 users available to assign rights in the file system of a server within Domain01, then you have to have Domain01 trust Domain02, one way, at minimum.  See TechNet.

A: Forest Trust will enable Domain02 users to access resources on Domain01.  When it comes to ping, you have to use software or hardware router.
For software router you can use RRAS (Routing and Remote Access).  RRAS is available in Windows Server 2003.  You need 2 LAN cards to establish connections between 2 domains.


text: Q: Is there anyway to copy git repo from one EC2 instance to another EC2 instance using Jenkins? I have 3 Instances in AWS one is dev, staging and build server instance. If I build staging branch in build server. How can I copy the repo to another EC2 instance such staging server from build server?


text:
Q: закрытие меню по клику вне блока. не работает кнопка закрытия Уже в отчаянии. Не знаю, что делать :-( Помогите, пожалуйста. Есть мобильное меню. По клику вне меню, меню закрывается, все хорошо. Используется стандартное решение для этого. Но на данном меню есть так же кнопка закрытия, "крестик". И эта кнопка работает не совсем корректно. Это заключается в том, что открытие/закрытие меню сработает по клику на этот крестик, но только если клик произойдет в любую верхнюю или нижнюю область, кроме центра. В центре текст "меню". Я уже по "всякому" пробовал играться с кодом. И никакого результата, к моему сожалению. Помогите, пожалуйста..

$(document).ready(function () {

     $(document).mouseup(function (e){
    if (!$(".header_content_one_menu").is(e.target) && $(".header_content_one_menu").has(e.target).length === 0) {
       $('#header_menu_adaptive').prop('checked', false);
    }

    if (!$(".header_content_one_menu").is(e.target) && $(".header_menu_adaptive_button").has(e.target).length !== 0) {
       $('#header_menu_adaptive').prop('checked', true);
    }
  });

});
#header_menu_adaptive {
    display: none;
}

.header_menu_adaptive_button {
    display: flex;
    align-items: center;
    width: 50px;
    height: 50px;
    cursor: pointer;
    z-index: 999999;
    padding: 0 20px 0 0;
}

#header_menu_adaptive:checked ~ .header_menu_adaptive_button > span {
    transform: rotate(45deg);
    visibility: hidden;
    transition: 0.05s;
}

#header_menu_adaptive:checked ~ .header_menu_adaptive_button> span::before {
    top: 0;
    transform: rotate(0);
    visibility: visible;
}

#header_menu_adaptive:checked ~ .header_menu_adaptive_button > span::after {
    top: 0;
    transform: rotate(90deg);
    visibility: visible;
}

.header_menu_adaptive_button > span::after {
    content: '';
    top: 28px;
    width: 50px;
    height: 2px;
    background-color: #B72A20;
    transition-duration: .25s;
}

#header_menu_adaptive:checked ~ .header_content_one_menu {
    visibility: visible;
    left: 0;
}

.header_menu_adaptive_button > span, .header_menu_adaptive_button> span::before, .header_menu_adaptive_button > span::after {
    display: flex;
    justify-content: center;
    width: 50px;
    position: absolute;
    text-transform: uppercase;
    color: #B72A20;
    font-family: RobotoCondensed;
    letter-spacing: 2.4px;
    transition-duration: .25s;
    font-size: 16px;
    z-index: 11112;
}

.header_menu_adaptive_button > span::before {
    content: '';
    bottom: 29px;
    width: 50px;
    height: 2px;
    background-color: #B72A20;
    transition-duration: .25s;
}

.header_content_one_menu {
    display: grid;
    grid-row-gap: 20px;
    position: absolute;
    visibility: hidden;
    top: 0;
    border-radius: 0 0 0 0;
    left: -100%;
    width: 100%;
    height: auto;
    margin: 0;
    padding: 40px 0 40px 0;
    background-color: yellow;
    transition-duration: .25s;
}

<input id="header_menu_adaptive" type="checkbox">

                        меню

111

222

333

444

555

A: Получилось решить вот таким способом:

if (!$(".header_content_one_menu").is(event.target) && $(".header_content_one_menu").has(event.target).length === 0  && $(".header_menu_adaptive_button").has(event.target).length === 0) {
       $('#header_menu_adaptive').prop('checked', false);
}


text:
Q: need to split each line of a text file into a list for summation I have a text file containing several lines of numbers. I'm trying to create a quick script to iterate through each line of the file and add the numbers of each line together so as I get a new file I can just enter the name and have it run.
So far, I have this:
   def main():
        filename = input("File name: ")
        lists=open(filename, 'r')
        lists = lists.readlines()
        newlists=[]
        print("********")
        for i in range(len(lists)):
            newlists.append(lists[i].strip('\n'))
        finallist=newlists.split(',')

        print(finallist)

    main()

This obviously does not work because you can't use .split() on a list, but I don't know how else to separate it properly. Once I get my data into a list of lists I know how to iterate through each item and add them, but I can't figure out this step.
If anyone could even simply point me in the direction of documentation that would explain the process I need to do, I'd appreciate it greatly.
Thanks

A: How about
def main():
    filename = input("File name: ")
    with open(filename, 'r') as f:
        overall_sum = 0
        for line in f:
             overall_sum += sum(map(int, line.split(',')))
        print(overall_sum)


text:
Q: Getting an error with make I'm a newbie on using make files and other GNU make tools. I'm working on this project called axis2/c which uses the automake toolchain. I'm running into this compile error.
    Making all in description
    /bin/sh ../../../libtool  --tag=CC   --mode=compile gcc -DHAVE_CONFIG_H -I. -I../../.. -I../../../include -I../../../src/core/engine -I../../../util/include -I../../../axiom/include -I../../../neethi/include  -D_LARGEFILE64_SOURCE -DAXIS2_GUTHTHILA_ENABLED  -DAXIS2_JSON_ENABLED -DAXIS2_SVR_MULTI_THREADED  -g -O2 -D_LARGEFILE64_SOURCE -ansi -Wall -Wno-implicit-function-declaration -g -D_GNU_SOURCE -DAXIS2_GUTHTHILA_ENABLED  -DAXIS2_JSON_ENABLED -DAXIS2_SVR_MULTI_THREADED -MT op.lo -MD -MP -MF .deps/op.Tpo -c -o op.lo op.c
    libtool: compile:  gcc -DHAVE_CONFIG_H -I. -I../../.. -I../../../include -I../../../src/core/engine -I../../../util/include -I../../../axiom/include -I../../../neethi/include -D_LARGEFILE64_SOURCE -DAXIS2_GUTHTHILA_ENABLED -DAXIS2_JSON_ENABLED -DAXIS2_SVR_MULTI_THREADED -g -O2 -D_LARGEFILE64_SOURCE -ansi -Wall -Wno-implicit-function-declaration -g -D_GNU_SOURCE -DAXIS2_GUTHTHILA_ENABLED -DAXIS2_JSON_ENABLED -DAXIS2_SVR_MULTI_THREADED -MT op.lo -MD -MP -MF .deps/op.Tpo -c op.c  -fno-common -DPIC -o .libs/op.o
    op.c: In function 'axis2_op_get_axis_specific_mep_const':
    op.c:783: error: 'AXIS2_MEP_URI_IN_OUT_WSDL2' undeclared (first use in this function)
    op.c:783: error: (Each undeclared identifier is reported only once
    op.c:783: error: for each function it appears in.)
    op.c:788: error: 'AXIS2_MEP_URI_IN_ONLY_WSDL2' undeclared (first use in this function)
    op.c:793: error: 'AXIS2_MEP_URI_IN_OPTIONAL_OUT_WSDL2' undeclared (first use in this function)
    op.c:798: error: 'AXIS2_MEP_URI_OUT_IN_WSDL2' undeclared (first use in this function)
    op.c:803: error: 'AXIS2_MEP_URI_OUT_ONLY_WSDL2' undeclared (first use in this function)
    op.c:808: error: 'AXIS2_MEP_URI_OUT_OPTIONAL_IN_WSDL2' undeclared (first use in this function)
    op.c:813: error: 'AXIS2_MEP_URI_ROBUST_IN_ONLY_WSDL2' undeclared (first use in this function)
    op.c:818: error: 'AXIS2_MEP_URI_ROBUST_OUT_ONLY_WSDL2' undeclared (first use in this function)
    make[4]: *** [op.lo] Error 1
    make[3]: *** [all-recursive] Error 1
    make[2]: *** [all-recursive] Error 1
    make[1]: *** [all-recursive] Error 1
    make: *** [all] Error 2

These constants are in a file called axis2_const.h, so I went into op.c and specifically included that (This is a redundant steps). But, I'm still getting this compilation error.
Any idea how I would solve this?
Note: Let me know if I need to include more information.