text:
Q: OData DataServiceQuery deserialize only first element of collection On my ASP.NET MVC5 application, I have a service reference for an OData api.
I'm making a call for this API, expanding a child propertie, as follows:
DataServiceQuery<CenarioDeInvestimentoCenario> queryCenario;
queryCenario = context.CenarioDeInvestimentoCenario
    .Expand("CenarioDeInvestimentoCenarioItem")
    .Where(a => a.IdAerodromo.Equals(55)) as DataServiceQuery<CenarioDeInvestimentoCenario>;
QueryOperationResponse<CenarioDeInvestimentoCenario> response = queryCenario
    .IncludeTotalCount()
    .Execute() as QueryOperationResponse<CenarioDeInvestimentoCenario>;

This generates the following query string:
LocalHost/MyApi/CenarioDeInvestimentoCenario()?$filter=IdAerodromo eq 55&$expand=CenarioDeInvestimentoCenarioItem

Using this query string from any browser, I can get the correct result set of data as follows on the image bellow. Notice CenarioDeInvestimentoCenarioItem as a collection:

However, inside my ASP.NET application, on the QueryOperationResponse response object, I get just the first CenarioDeInvestimentoCenarioItem collection element, as shown on the pic below:

I have no idea why this is happening. I'm pretty new working with Odata and service reference, so I have no idea what is happening. Can someone help-me please?
Tx!


text:
Q: Python3 Flask session not appearing to update I'm using code below to debug an issue where it doesn't appear my session variable is being updated properly.
print(session)
session['review_status'] = 'Pending'
print('Session review_status is now: ' + session['review_status'])
print(session)

This is outputting the following:
<SecureCookieSession {'review_id': None, 'review_status': 'New'}>
Session review_status is now: Pending
<SecureCookieSession {'review_id': None, 'review_status': 'New'}>

I can't understand why the last print statement isn't reflecting that the review_status value should now be "Pending" and not "New".
The frontend is firing off about 5 ajax requests at once to this endpoint, but the first one should be changing the status to Pending, so by the time the other 4 return, it would be "Pending" for them.

A: It appears this was being caused by the asynchronous calls from the frontend. While watching the debug output, it seems that several of the calls were "finishing" before the Flask session was actually reflecting the new value that was stored.
When I converted the ajax call to "async: false", I then got the expected behavior after the first call finished (the remainder were no longer "New", but rather in "Pending").
I am going to leave this fix in place for now, but would be interested in alternatives to this, and getting a better understanding of how Gunicorn/Flask handles multiple requests to the same endpoint concurrently with regard to the session (ie: does the session remain static until all calls are fulfilled type thing).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure SQL Server "clr strict security" can this be changed I'm trying to change the 'clr strict security' in Azure SQL Server, but not able, is this no more possible in Azure Managed SQL Server.
I've created a certificate first and then I tried to create a login for the certificate and thats failing as well, is this changed and can this be done in some other way.
CREATE LOGIN MIRRepoCertLogin FROM CERTIFICATE MIRRepoCert;
This is also failing with Keyword or statement option 'CERTIFICATE' is not supported in this version of SQL Server
My intention was to run the below commands in Azure SQL Server. Any advise.
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE with override;
EXEC sp_configure 'clr strict security', 0;
RECONFIGURE with override;
EXEC sp_configure 'show advanced options', 0;
RECONFIGURE with override;

A: Important
As far as we know, the sp_configure and the SQL Statemenst of Certificate are not supported by Azure SQL Server.

*

*When I try to execute the CREATE LOGIN xxx FROM CERTIFICATE xxx command. It shows the error is not supported in Azure Managed SQL Server.

*When I try to execute the EXEC sp_configure  command. It also shows is not supported


text:
Q: What is the purpose of the "normal level protection" permission? What is the purpose the "normal" permission level if these permissions are automatically granted by the Android system? This seems like an unnecessary step. The other permission levels require user consent or some other additional criteria to be present, and therefore make sense in terms of design intent. Why do I need to ask for permission if it's granted 100% of the time?

A: In general protection level characterizes the potential risk implied in the permission and indicates the procedure the system should follow when determining whether or not to grant the permission to an application requesting it.

Normal - The default value. A lower-risk permission that gives
  requesting applications access to isolated application-level features,
  with minimal risk to other applications, the system, or the user. The
  system automatically grants this type of permission to a requesting
  application at installation, without asking for the user's explicit
  approval (though the user always has the option to review these
  permissions before installing).

Such permissions are required just to inform the user that the application is using such featured (For now). In the future those permission level group can be treated in another way.

A: Its put in to let the user know exactly what the application is doing. The user can see these before installing - and may choose not to install your app!


text:
Q: listview in android: one activity it applied to all the listview items In our project, for the listview items it is getting linked to the same content.but we need to give diifferent activities to all the listview items..for example: If we click History listview it is opening the related history activity..but the same history activity is opening for all the listview items..plz help to resolve.
java code:
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

public class OurSchool extends ListActivity{

 String[] listItems={"History", "Mission And Objectives", "Principals Forewords", "School System",
         "Calender", "Rules And Regulations", "Our Traditional", "Our Alumini Council","Our Pholosophy","Our Branches"};
 boolean[] listImages= {true, true, true, true, true,true, true, true, true, true};

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.our_school);
        setListAdapter(new ImageAdapter(this, R.layout.our_school, R.id.text1, R.id.image1, listItems, listImages ));
        this.getListView().setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    final int pos, long id) {
                Intent i = new Intent(getApplicationContext(), History.class);
                String product = null;
                // sending data to new activity
                i.putExtra("product", product);
                startActivity(i);
            }
        });

    }

    }

History.java:
    import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;

public class History extends Activity {

    WebView mWebView;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.history);

        mWebView = (WebView)findViewById(R.id.webview);
        mWebView.setBackgroundColor(0);
        mWebView.setBackgroundResource(R.drawable.bg);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.loadUrl("file:///android_asset/History.html");

    }
}

history.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center"
        android:text="About :LITTLE FLOWERS PUBLIC SCHOOL"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <WebView
        android:id="@+id/webview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</LinearLayout>

Thank you,

A: You need to pass listViewItem Position to NextActivity.
 @Override
        public void onItemClick(AdapterView<?> parent, View view,
                final int pos, long id) {
            Intent i = new Intent(getApplicationContext(), History.class);
            // sending data to new activity
            i.putExtra("pos", pos);
            startActivity(i);
        }

Then your nextActivity will be look like
public class History extends Activity {

WebView mWebView;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.history);

    int pos = getIntent().getIntExtra("pos",0);

    mWebView = (WebView)findViewById(R.id.webview);
    mWebView.setBackgroundColor(0);
    mWebView.setBackgroundResource(R.drawable.bg);
    mWebView.getSettings().setBuiltInZoomControls(true);
    switch (pos) {
    case 0:
        mWebView.loadUrl("file:///android_asset/History.html");
        break;
    case 1:
        mWebView.loadUrl("file:///android_asset/Objective.html");
        break;
    case 2:
        mWebView.loadUrl("file:///android_asset/Principles.html");
        break;
    case 3:
        mWebView.loadUrl("file:///android_asset/Calender.html");
        break;
    case 4:
        mWebView.loadUrl("file:///android_asset/ShcoolSystem.html");
        break;

    default:
        mWebView.loadUrl("file:///android_asset/History.html");
        break;
    }

  }
 }

A: You might have to change your logic a bit. Becasuse in the present code you are using only History.class in the Intent. Thats why its opening for every list item. You might have to change the class name based on the item clicked.
for example
String item = (String)parent.getItemAtPosition(position);
Intent i;
if(item.equals("History")
  {
  i = new Intent(getApplicationContext(), History.class);
  }
  else if("Mission And Objectives")
  { i = new Intent(getApplicationContext(), AnotherClass.class);}


text:
Q: HTML why does this lock to the left? I recently added a custom HTML/CSS snippet to create an auto-fading slideshow. It currently locks to the left of my screen. When I make the window width smaller the slideshow locks into place, and other elements (like the twitter module) go underneath it.
BEFORE

AFTER

I want it to be so that the space on the left evens out on each side as the screen width decreases.
HTML

CSS
.css-slideshow {
position: relative;         /* positioning facilities */
max-width: auto;            /* maximum width of the image */
height: 370px;
margin: 1em auto .5em auto;             /* some margin */
font-family: "Montserrat", sans-serif;  /* just a custom font */
font-weight: 300;                       /* font-weight, semibold */
}

.css-slideshow figure {
margin: 0;                  /* ensuring there is no margin */
max-width: 495px;
height: 370px;
background: #fff;           /* white background */
position: absolute;         /* positioning facilities */
}

.css-slideshow img {                /* a shadow for our box wrapper */
-webkit-box-shadow: 0 0 2px #666;
box-shadow: 0 0 2px #666;
}

/* Give the figcaption a 0% opacity at first */
.css-slideshow figcaption {
position: absolute;
top: 5px;
color: #fff;
background: rgba(0,0,0, .3);
font-size: .8em;
padding: 8px 12px;
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
filter: alpha(opacity=0);
opacity: 0;
-webkit-transition: opacity .5s;
-moz-transition: opacity .5s;
-o-transition: opacity .5s;
-ms-transition: opacity .5s;
transition: opacity .5s;    /* transition duration */
}

/* Give the figcaption a 100% opacity at first */
.css-slideshow:hover figure figcaption {
-webkit-transition: opacity .5s;
-moz-transition: opacity .5s;
-o-transition: opacity .5s;
-ms-transition: opacity .5s;
transition: opacity .5s;        /* transition duration */
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
filter: alpha(opacity=100);
opacity: 1;
}

/* Here every child of css-transition gets animated */

.css-slideshow figure:nth-child(1) {
-webkit-animation: xfade 36s 31.5s  infinite;
-moz-animation: xfade 36s 31.5s  infinite;
-ms-animation: xfade 36s 31.5s infinite;
-o-animation: xfade 36s 31.5s infinite;
animation: xfade 36s 31.5s infinite;
}
.css-slideshow figure:nth-child(2) {
-webkit-animation: xfade 36s 27s infinite;
-moz-animation: xfade 36s 27s infinite;
-ms-animation: xfade 36s 27s infinite;
-o-animation: xfade 36s 27s infinite;
animation: xfade 36s 27s infinite;
}
.css-slideshow figure:nth-child(3) {
-webkit-animation: xfade 36s 22.5s infinite;
-moz-animation: xfade 36s 22.5s infinite;
-ms-animation: xfade 36s 22.5s infinite;
-o-animation: xfade 36s 22.5s infinite;
animation: xfade 36s 22.5s infinite;
}
.css-slideshow figure:nth-child(4) {
-webkit-animation: xfade 36s 18s infinite;
-moz-animation: xfade 36s 18s infinite;
-ms-animation: xfade 36s 18s infinite;
-o-animation: xfade 36s 18s infinite;
animation: xfade 36s 18s infinite;
}
.css-slideshow figure:nth-child(5) {
-webkit-animation: xfade 36s 13.5s infinite;
-moz-animation: xfade 36s 13.5s infinite;
-ms-animation: xfade 36s 13.5s infinite;
-o-animation: xfade 36s 13.5s infinite;
animation: xfade 36s 13.5s infinite;
}
.css-slideshow figure:nth-child(6) {
-webkit-animation: xfade 36s 9s infinite;
-moz-animation: xfade 36s 9s infinite;
-ms-animation: xfade 36s 9s infinite;
-o-animation: xfade 36s 9s infinite;
animation: xfade 36s 9s infinite;
}
.css-slideshow figure:nth-child(7) {
-webkit-animation: xfade 36s 4.5s infinite;
-moz-animation: xfade 36s 4.5s infinite;
-ms-animation: xfade 36s 4.5s infinite;
-o-animation: xfade 36s 4.5s infinite;
animation: xfade 36s 4.5s infinite;
}
.css-slideshow figure:nth-child(8) {
-webkit-animation: xfade 36s 0s infinite;
-moz-animation: xfade 36s 0s infinite;
-ms-animation: xfade 36s 0s infinite;
-o-animation: xfade 36s 0s infinite;
animation: xfade 36s 0s infinite;
}

@keyframes "xfade" {
 0% {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
    opacity: 1;
 }
14.67% {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
    opacity: 1;
}
16.67% {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter: alpha(opacity=0);
    opacity: 0;
}
 98% {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter: alpha(opacity=0);
    opacity: 0;
 }
 100% {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
    opacity: 1;
 }
}
@-moz-keyframes xfade {
 0% {
   filter: alpha(opacity=100);
   opacity: 1;
 }
14.67% {
    filter: alpha(opacity=100);
    opacity: 1;
}
16.67% {
    filter: alpha(opacity=0);
    opacity: 0;
}
 98% {
   filter: alpha(opacity=0);
   opacity: 0;
 }
 100% {
   filter: alpha(opacity=100);
   opacity: 1;
 }
}
@-webkit-keyframes "xfade" {
 0% {
   filter: alpha(opacity=100);
   opacity: 1;
 }
14.67% {
    filter: alpha(opacity=100);
    opacity: 1;
}
16.67% {
    filter: alpha(opacity=0);
    opacity: 0;
}
 98% {
   filter: alpha(opacity=0);
   opacity: 0;
 }
 100% {
   filter: alpha(opacity=100);
   opacity: 1;
 }
}
@-ms-keyframes "xfade" {
 0% {
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
   filter: alpha(opacity=100);
   opacity: 1;
 }
14.67% {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
    filter: alpha(opacity=100);
    opacity: 1;
}
16.67% {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
    filter: alpha(opacity=0);
    opacity: 0;
}
 98% {
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
   filter: alpha(opacity=0);
   opacity: 0;
 }
 100% {
   -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
   filter: alpha(opacity=100);
   opacity: 1;
 }
}
@-o-keyframes "xfade" {
 0% {
   filter: alpha(opacity=100);
   opacity: 1;
 }
14.67% {
    filter: alpha(opacity=100);
    opacity: 1;
}
16.67% {
    filter: alpha(opacity=0);
    opacity: 0;
}
 98% {
   filter: alpha(opacity=0);
   opacity: 0;
 }
 100% {
   filter: alpha(opacity=100);
   opacity: 1;
 }
}

A: You should divide your body into two sections and put your slideshow in the slideshow section.
Other elements go underneath the slideshow because the image's width is a fixed size. Make sure that the width is relative to the slideshow section width.
.slideshow {
  height: auto;
  width: 60%;
  float: left;
}
.twitter {
  height: auto;
  width: 40%;
  float: right;
}
.css-slideshow {
  position: relative;
  max-width: auto;
  height: 80%;
  margin: 5% 5% 0 5%;
  font-family: "Montserrat", sans-serif;
  font-weight: 300;
}
.css-slideshow figure {
  margin: 0 0 0 0;
  width: 100%;
  height: 100%;
  background: #fff;
  position: absolute;
}
.css-slideshow img {
  height: 100%;
  width: 100%;
  -webkit-box-shadow: 0 0 2px #666;
  box-shadow: 0 0 2px #666;
}

    ...put your slideshow here...

Take a look at this.


text:
Q: How to insert picture in gridview using path that is stored in text file? I have to insert pictures from paths stored in text file. Text file looks like this:
AIPH7,iPhone 7 Plus 256GB__,Iphone,____,~/Pictures/iphone7plus.jpg______,999€______
ASZG0,Zenfone Go_________,Asus______,~/Pictures/zenphonego.jpg_______,138€______
I want to insert picture in gridview from that file location in text file. My gridview is auto generated by this function that reads all data from file and puts it into gridview:
string filePath = @"C:\Users\PC1\Desktop\Project\WebApplication1\file.txt";

public DataTable ConvertToDataTable(string filePath, int numberOfColumns)
      {
        DataTable tbl = new DataTable();
        for (int col = 0; col < numberOfColumns; col++)
        tbl.Columns.Add(new DataColumn("Column" + (col + 1).ToString()));

        string[] lines = File.ReadAllLines(filePath);
        List<string> list1 = new List<string>();
        foreach (string line in lines)
        {
            var cols = line.Split(',');
            DataRow dr = tbl.NewRow();
            for (int cIndex = 0; cIndex < 5; cIndex++)
            {
                if (cols[cIndex].Contains('_'))
                {
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
                else
                {
                    cols[cIndex] += '_';
                    cols[cIndex] = cols[cIndex].Substring(0, cols[cIndex].IndexOf('_'));
                    dr[cIndex] = cols[cIndex];
                }
            }
            for (int cIndex = 0; cIndex < 5; cIndex++ )
                if (dr[cIndex].ToString() == promenljiva)
                    tbl.Rows.Add(dr);
        }

        this.GridView1.DataSource = tbl;
        this.GridView1.DataBind();

        return tbl;
    }

After that i have:
ConvertToDataTable(filePath, 5);

This is the gridview:
<asp:GridView ID="GridView1" runat="server"></asp:GridView>


text:
Q: Pandas Forward Fill NA only between two points and nothing else I want to use pandas forward fill null values only between two non-null data points and nothing else.
For example I have a column named comments
Comments:
Hello World
NA
Hello World
NA
Hello World
NA
NA
NA
NA

Output should look like this:
Hello World
Hello World
Hello World
Hello World
Hello World
NA
NA
NA
NA

A: You can calculate the last valid index and use ffill until this index:
last = df['Comments'].last_valid_index()

df['Comments'].loc[:last] = df['Comments'].loc[:last].ffill()

print(df)

      Comments
0  Hello World
1  Hello World
2  Hello World
3  Hello World
4  Hello World
5          NaN
6          NaN
7          NaN
8          NaN

A: easiest way I found is to use interpolate:
df['Comments'] = df['Comments'].interpolate(method="pad")

This would not fill in NaN values at the beginning and at the end of the series.
Example:
s = pd.Series([np.nan,1,2,np.nan,np.nan,4, np.nan])

s = s.interpolate(method = "pad)

print(s)

0    NaN
1    1.0
2    2.0
3    2.0
4    2.0
5    4.0
6    NaN
dtype: float64


text:
Q: Best Event Handler for capturing and storing the data entered in React Js Application I have created an input textbox for entering items details. To capture and store the data entered, which among below mentioned event handler is the best?

*

*onClick

*onChange

*onLoad

*onKeyPress

A: You need the onChange event handler to get the value of the input.
It would look like this:
onChange={e => setText(e.target.value)}
Using useState hook:
const [text, setText] = useState('')


text:
Q: Unit tests that inherit from a type that uses generics I have an interface with generics that is implemented by some classes. For each of these classes there is proxy class that implement the interface as well. Giving roughly this code:
public interface ISomeInterface<T>
{
    T SomeProperty
    {
        get;
    }

    T SomeAction();
}

public interface IClassA : ISomeInterface<string>
{
    void Action();
}

public class ClassA : IClassA
{
    // Code goes here
}

public class ClassAProxy : IClassA
{
    // Code goes here
}

The unit tests code I would want to look something like this:
public abstract class ISomeInterfaceTests<T>
{
    [TestMethod()]
    public void SomePropertyTest()
    {
        ISomeInterface<T> target;
        ISomeInterface<T> oracle;
        this.CreateInstance(out target, out oracle);

        Assert.AreEqual(oracle.SomeProperty, target.SomeProperty);
    }

    [TestMethod()]
    public void SomeActionTest()
    {
        ISomeInterface<T> target;
        ISomeInterface<T> oracle;
        this.CreateInstance(out target, out oracle);

        T oracleValue = oracle.SomeAction();
        T targetValue = target.SomeAction();

        Assert.AreEqual(oracleValue, targetValue);
    }

    // More tests

    protected abstract void CreateInstance(out ISomeInterface<T> target, out ISomeInterface<T> oracle);
}

[TestClass()]
public class ClassAProxyTests : ISomeInterfaceTests<string>
{
    // ClassAProxy specific tests

    protected override void CreateInstance(out ISomeInterface<string> target, out ISomeInterface<string> oracle)
    {
        // Create target as ClassAProxy here and oracle as ClassA
    }
}

But this gives the error:
UTA002: TestClass attribute cannot be defined on generic class ISomeInterfaceTests<T>.
Is there some nice workaround to this? Currently the best solution I can think of is to have a method in ClassAProxyTests that calls the different test methods in ISomeInterfaceTests<T>. There are several problems to that approach though:

*

*It has to be done manually for each test implementing ISomeInterfaceTests<T>.

*Should one method result in an assertion that fails then the remaining methods will not be executed.

*You cannot use the ExpectedException attribute and would have to wrap the required code in try catch statements.

but alas a better solution escapes me.

A: Sounds like you need to use the GenericTestFixture feature of NUnit 2.5.  This feature allows you to place the [TestFixture] attribute on a generic class, then specify which specializations of the test fixture apply.
Your main test fixture will look as follows (and you may be able to remove some interfaces too):
[TestFixture(typeof(string))]
public class ClassAProxyTests<T> : ISomeInterfaceTests<T> where T: class
{
    // Add ISomeInterfaceTests<T> methods here.
    // ISomeInterfaceTests may no longer be required as the abstraction is defined in ClassAProxyTests.

    // ClassAProxy specific tests

    protected override void CreateInstance(out ISomeInterface<T> target, out ISomeInterface<string> oracle)
    {
        // Create target as ClassAProxy here and oracle as ClassA
    }
}

A: The only reason you have the parent class is to create instances of your interface, yes?
Use MOQ instead.
Edit:

Not quite. The ISomeInterfaceTests<T> class is used to test the functionality of the proxies implementing the ISomeInterface<T> interface - it tests the proxies against the objects they are a proxy for (the oracle).  – Cornelius

Hmm... that sounds like an integration test. Are your oracle objects read from the database somehow, or are you mocking them like you should be? Anyway, I stand by using Moq to get your instances and mocking vs integration testing in general.
But it strikes me that your approach for generalization of your tests may be the issue. Perhaps a different approach? Try this on:
public static class GenericISomeInterfaceTests
{
    public static void SomePropertyTest<T>(ISomeInterface<T> target, ISomeInterface<T> oracle)
    {

        Assert.AreEqual(oracle.SomeProperty, target.SomeProperty);
    }

    public static void SomeActionTest<T>(ISomeInterface<T> target, ISomeInterface<T> oracle)
    {

        T oracleValue = oracle.SomeAction();
        T targetValue = target.SomeAction();

        Assert.AreEqual(oracleValue, targetValue);
    }

    // More tests
}

[TestClass()]
public class ClassAProxyTests
{
    [TestMethod]
    public void SomePropertyStringTest()
    {
        // set up instances (using MOQ, or whatever) with the string generic type.
        // Call them target and oracle

        // then call your generic test methods
        GenericISomeInterfaceTests.SomePropertyTest<string>(target, oracle);
    }

    [TestMethod]
    public void SomeActionStringTest()
    {
        // set up instances (using MOQ, or whatever) with the string generic type.
        // Call them target and oracle

        // then call your generic test methods
        GenericISomeInterfaceTests.SomeActionTest<string>(target, oracle);
    }
}


text:
Q: How to aggregate mongoose collection? In my mongoose model I have an invoiceHeader and invoiceLine collection both relating to account object.
In a view I want to display the total invoiceAmount for the account.
In SQL something like select sum(amount) from invoiceHeader group by account.
How can i achieve similar with nodeJS and mongoose?

A: Assuming amount is the property that you want to sum on, it would be like:
InvoiceHeaderModel.aggregate({
  $match: {
    account: '<Account_ID>'
  }
}, {
  $group: {
    _id: null,
    total: {
      $sum: "$amount"
    }
  }
}, {
  $project: {
    _id: 0,
    total: 1
  }
}, function(err, res) {
  // res contains the result
});

The $match operator is used to match certain documents. The $group operator is used to group the documents. The $project operator is used to select certain fields from the documents.


text:
Q: An Open Cover $\mathscr{F}$ of $2\mathbb{N}$ That Has No Finite Subcover What is an open cover $\mathscr{F}$ for the set $2\mathbb{N}=\{2n:n\in\mathbb{N}\}$ that has no finite subcover? My initial answer is $\mathscr{F}=\begin{Bmatrix}\pmatrix{-n,5n}:n\in\mathbb{N}\end{Bmatrix}$. Is this good? I don't quite see though why it does or doesn't have a finite subcover.

A: It has no finite subcover.  To see this observe that if $n < m$ then $(-n, 5n) \subseteq (-m, 5m)$.  So if there were integers $n_1, n_1, \ldots, n_m$ such that the open sets $(-n_i, 5n_i)$ form the cover, then they would all be contained in some $(-n_i, 5n_i)$ where $n_i$ is maximal among the various $n$.  But clearly $2\mathbb N$ is not contained in this.

A: Yes, your $\mathscr F$ does not have a finite subcover of $2\mathbb{N}$. To see this, suppose that a finite subset $\mathscr G$ of $\mathscr F$ is a cover of $2\mathbb{N}$. Now let $n \in \mathbb{N}$ be the largest natural number such that $(-n,5n) \in \mathscr G$. Such an $n$ exists, because $\mathscr G$ is finite. Then $\bigcup {\mathscr G} = (-n,5n)$ and hence it does not cover $2\mathbb{N}$.
Note that ${\mathscr F} = \{ (-1, n) \mid n \in \mathbb{N} \}$ would work just as well.


text:
Q: почему во время второго Insert, id сходит с ума? CREATE TABLE `devices`.`common` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `Department` INT NULL,
  `InvNumber` VARCHAR(45) NULL,
  `Name` VARCHAR(45) NULL,
  `Got` INT NULL,
  `WrittenOff` INT NULL,
  `Price` INT NULL,
  PRIMARY KEY (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;

INSERT INTO devices.common (department,InvNumber,Name,Got,writtenoff,price)
    SELECT
    department,
    InvNumber,
    Name,
    Got,
    WrittenOff,
    Price
    FROM devices.main;

INSERT INTO devices.common (department,InvNumber,Name,Got,writtenoff,price)
    SELECT
    department,
    InvNumber,
    Name,
    Got,
    WrittenOff,
    Price
    FROM devices.cheap;

A: Согласно документации AUTO_INCREMENT гарантирует уникальность, но не гарантирует непрерывность в общем случае:
If the only statements executing are "simple inserts" where the number of rows to be inserted is known ahead of time, there are no gaps in the numbers generated for a single statement, except for "mixed-mode inserts". However, when "bulk inserts" are executed, there may be gaps in the auto-increment values assigned by any given statement.
insert into table
select ... from ... another_table

можно рассматривать как "bulk insert"


text:
Q: Why is argparse not raising exceptions? I'm using the argparse module to use create an address object via the command line. But when I feed it invalid arguments (i.e. those that should raise an exception), no exceptions are raised. Worse still, nothing is being logged (unless I create a valid object).
So, this works:
-n Patrick -a "151 Piedmont Ave" -c "Winston Salem" -s "NC" -z 27101

This doesn't:
-l ERROR -n Patrick -a "151 Piedmont Ave" -c "Winston Salem" -s "NC" -z 271

Where am I going wrong?
NOTE: This is homework, so guidance over the absolute answer would be appreciated.
"""
property_address.py
"""
import re
import logging
import argparse

LOG_FILENAME = 'property_address.log'
LOG_FORMAT = "%(asctime)s - %(levelname)s - %(funcName)s - %(message)s"
DEFAULT_LOG_LEVEL = "debug"
LEVELS = {'debug': logging.DEBUG,
          'info': logging.INFO,
          'warning': logging.WARNING,
          'error': logging.ERROR,
          'critical': logging.CRITICAL
         }

def start_logging(filename=LOG_FILENAME, level=None):
    logging.basicConfig(filename=filename, level=level, filemode='w', format=LOG_FORMAT)
    logging.info('Starting up the property address program')

class ZipCodeError(Exception):
    "Custom exception for invalid zip codes."
    pass

class StateError(Exception):
    "Custom exception for invalid state abbreviation."
    pass

class Address(object):
    """
    An address object.
    """

    def __init__(self, name, street_address, city, state, zip_code):
        self._name = name
        self._street_address = street_address
        self._city = city
        self._state = state
        self._zip_code = zip_code
        logging.info('Instantiated an address')

    @property
    def name(self):
        return self._name

    @property
    def street_address(self):
        return self._street_address

    @property
    def city(self):
        return self._city

    @property
    def state(self):
        return self._state

    @state.setter
    def state(self, value):
        "Validate that states are abbreviated as US Postal style."
        state_valid = re.compile(r'[A-Z]{2}$')
        if re.match(state_valid, value):
            self._state = value
        else:
            message = 'STATE Exception: State not in correct format'
            logging.error(message)
            raise StateError()

    @property
    def zip_code(self):
        return self._zip_code

    @zip_code.setter
    def zip_code(self, value):
        "Validate zip codes are five digits."
        zip_valid = re.compile(r'\d{5}$')
        if re.match(zip_valid, value):
            self._zip_code = value
        else:
            message = 'ZIP CODE Exception: Zip code not in correct format'
            logging.error(message)
            raise ZipCodeError()

    def __str__(self):
        return self._name

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Set attributes for property address.')
    parser.add_argument(
                        '-l',
                        '--level',
                        dest='level',
                        choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
                        default='INFO',
                        help='Sets the log level to DEBUG, INFO, WARNING, ERROR, and CRITICAL')
    parser.add_argument(
                        '-n',
                        '--name',
                        dest='name',
                        action='store',
                        required=True,
                        help='Sets the name value of the Address object')
    parser.add_argument(
                        '-a',
                        '--address',
                        dest='address',
                        action='store',
                        required=True,
                        help='Sets the street_address value of the Address object')
    parser.add_argument(
                        '-c',
                        '--city',
                        dest='city',
                        action='store',
                        required=True,
                        help='Sets the city value of the Address object')
    parser.add_argument(
                        '-s',
                        '--state',
                        dest='state',
                        action='store',
                        required=True,
                        help='Sets the state value of the Address object')
    parser.add_argument(
                        '-z',
                        '--zip_code',
                        dest='zip_code',
                        action='store',
                        required=True,
                        help='Sets the zip_code value of the Address object')
    args = parser.parse_args()

    # Start our logger
    start_logging(level=(args.level))

    # Create our Address object
    a = Address(args.name, args.address, args.city, args.state, args.zip_code)

A: In Address.__init__ you are assigning to e.g. self._zip_code, which bypasses the setter. The minimal fix is therefore to use:
self.zip_code = zip_code
   # ^ note no underscore

This means the setter is called and your check made.

Beyond that, you have an inconsistency between your attributes; state and zip_code can be changed once set, but the others are read-only. In the likely event that this isn't the desired behaviour, I would remove the getters for attributes without setters and access all directly (i.e. without underscores) in __init__.
Alternatively, if you do want them all to be read-only, remove the setters and put their tests in __init__.

A final option is to test the arguments when parsed, rather than in the class; see e.g. Specify format for input arguments argparse python.
If you still want the class to test its arguments (for when they don't come via argparse), you could consider exposing a @staticmethod for the tests in your class, that then gets called in the setter too:
class Address:

    ...

    @staticmethod
    def valid_zip_code(zip_code, zip_valid=re.compile(r'\d{5}$')):
        if not re.match(zip_valid, zip_code):
            raise ZipCodeError
        return zip_code

    @zip_code.setter
    def zip_code(self, new_zip):
          new_zip = self.valid_zip_code(new_zip)
          self._zip_code = new_zip

...

parser.add_argument('-z', ..., type=Address.valid_zip_code)


text:
Q: rake exit status: 139 I am following https://gorails.com/deploy/ubuntu/16.04
I am running : "bundle exec cap production deploy" and getting the following error:
         01 $HOME/.rbenv/bin/rbenv exec bundle install --path /home/deploy/deploy_test1/shared/bundle --without development test --deployment --q…
        ✔ 01 deploy@107.170.84.18 3.251s
    00:21 deploy:assets:precompile
          01 $HOME/.rbenv/bin/rbenv exec bundle exec rake assets:precompile
          01 /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: w…
          01 /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: w…
          01 bash: line 1: 23934 Segmentation fault      (core dumped) $HOME/.rbenv/bin/rbenv exec bundle exec rake assets:precompile
    (Backtrace restricted to imported tasks)
    cap aborted!
    SSHKit::Runner::ExecuteError: Exception while executing as deploy@107.170.84.18: rake exit status: 139
    rake stdout: Nothing written
    rake stderr: /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated
    /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated
    bash: line 1: 23934 Segmentation fault      (core dumped) $HOME/.rbenv/bin/rbenv exec bundle exec rake assets:precompile

    SSHKit::Command::Failed: rake exit status: 139
    rake stdout: Nothing written
    rake stderr: /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated
    /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated
    bash: line 1: 23934 Segmentation fault      (core dumped) $HOME/.rbenv/bin/rbenv exec bundle exec rake assets:precompile

    Tasks: TOP => deploy:assets:precompile
    (See full trace by running task with --trace)
    The deploy has failed with an error: Exception while executing as deploy@107.170.84.18: rake exit status: 139
    rake stdout: Nothing written
    rake stderr: /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Fixnum is deprecated
    /home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:121: warning: constant ::Bignum is deprecated
    bash: line 1: 23934 Segmentation fault      (core dumped) $HOME/.rbenv/bin/rbenv exec bundle exec rake assets:precompile
......
......
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/cache/strategy/local_cache.rb:138:in `local_cache_key'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/cache/strategy/local_cache.rb:74:in `middleware'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application/bootstrap.rb:79:in `block in <module:Bootstrap>'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:30:in `instance_exec'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:30:in `run'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:55:in `block in run_initializers'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:54:in `run_initializers'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:352:in `initialize!'
/home/deploy/deploy_test1/releases/20170516175610/config/environment.rb:5:in `<top (required)>'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:328:in `require'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:328:in `require_environment!'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:457:in `block in run_tasks_blocks'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:62:in `block (2 levels) in define'
/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
/home/deploy/.rbenv/versions/2.4.0/bin/bundle:22:in `load'
/home/deploy/.rbenv/versions/2.4.0/bin/bundle:22:in `<main>'
Tasks: TOP => environment
(See full trace by running task with --trace)

** DEPLOY FAILED
** Refer to log/capistrano.log for details. Here are the last 20 lines:

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/core_ext/numeric/conversions.rb:131:in `block (2 levels) in <class:Numeric>'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/cache/strategy/local_cache.rb:138:in `local_cache_key'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/activesupport-4.2.4/lib/active_support/cache/strategy/local_cache.rb:74:in `middleware'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application/bootstrap.rb:79:in `block in <module:Bootstrap>'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:30:in `instance_exec'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:30:in `run'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:55:in `block in run_initializers'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/initializable.rb:54:in `run_initializers'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:352:in `initialize!'

/home/deploy/deploy_test1/releases/20170516175610/config/environment.rb:5:in `<top (required)>'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:328:in `require'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:328:in `require_environment!'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/railties-4.2.4/lib/rails/application.rb:457:in `block in run_tasks_blocks'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/sprockets-rails-3.2.0/lib/sprockets/rails/task.rb:62:in `block (2 levels) in define'

/home/deploy/deploy_test1/shared/bundle/ruby/2.4.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'

/home/deploy/.rbenv/versions/2.4.0/bin/bundle:22:in `load'

/home/deploy/.rbenv/versions/2.4.0/bin/bundle:22:in `<main>'

Tasks: TOP => environment

(See full trace by running task with --trace)

my Capfile is the one from here with rbenv 2.4.0:
cap deploy + rbenv: bundle: command not found


text:
Q: How to handle errors in my form fields with a single function in ReactJS? I have a form where the user needs to answer 3 questions to be able to register a new password. All fields are mandatory, and the user is unable to send the data to the server until the 3 questions are answered.
My question is how to handle input field errors with only one function? I currently perform a function for each of the fields. And this is not very good at performance levels.
For example, with just one function I can get the values entered in all input fields:

const handleChangeField = (field) => (event) => {
  const value = event?.target?.value || "";
  setData((prev) => ({ ...prev, [field]: value }));
};

Can you tell me if it is possible to create a function similar to the one above, but to handle errors? In this moment that's what I'm doing:

<TextField
  label="What is your mother's name?"
  className={classes.input}
  error={hasErrorMother}
  helperText={hasErrorMother ? "Required field*" : ""}
  value={data.motherName}
  onInput={(event) =>
    event.target.value.length > 0
      ? setHasErrorMother(false)
      : setHasErrorMother(true)
  }
  onChange={handleChangeField("motherName")}
/>

I handle errors for each of the fields within onInput.
Here's the code I put into codesandbox
Thank you very much in advance.

A: Here is an idea: you keep using handleChangeField but with a few modifications to also handle the error as well. But first, we need to change the state title bit:
// Remove those
// const [hasErrorMother, setHasErrorMother] = useState(false);
// const [hasErrorBorn, setHhasErrorBorn] = useState(false);
// const [hasErrorPet, setHasErrorPet] = useState(false);

// Instead have the error state this way
const [error, setError] = useState({
  motherName: false,
  birthplace: false,
  petName: false
});

...
// handleChangeField will have an extra line for error handling
const handleChangeField = (field) => (event) => {
  const value = event?.target?.value || "";
  setData((prev) => ({ ...prev, [field]: value }));
  setError((prev) => ({ ...prev, [field]: value.length === 0 })); // THIS ONE
};

And in the return statement, the TextField will change to be:
// onInput is removed, because onChange is taking care of the error
<TextField
  label="What is your mother's name?"
  className={classes.input}
  error={error.motherName}
  helperText={error.motherName? "Required field*" : ""}
  value={data.motherName}
  onChange={handleChangeField("motherName")}
/>

Now for the handleContinueAction, this will also change as follows:
...
const handleContinueAction = () => {
  const isValid =
    data.motherName.length > 0 &&
    data.birthplace.length > 0 &&
    data.petName.length > 0;

  if (isValid) {
    console.log("Ok, All data is valid, I can send this to the server now");
  } else {
    // If you want to show error for the incomplete fields
    setError({
      motherName: data.motherName.length === 0,
      birthplace: data.birthplace.length === 0,
      petName: data.petName.length === 0
    })
  }
};

...
// and git rid of this part
// const validateFields = (body) => {
//   if (body.motherName.length === 0) {
//     return setHasErrorMother(true);
//   }

//   if (body.birthplace.length === 0) {
//     return setHhasErrorBorn(true);
//   }

//   if (body.petName.length === 0) {
//     return setHasErrorPet(true);
//   }

//   return true;
};


text:
Q: Help to find $\frac{\mathbb{Z}\times\mathbb{Z}}{\left<(1,2),(2,3)\right>}$ I can prove that $\frac{\mathbb{Z}\times\mathbb{Z}}{\left<(1,2)\right>}$ is isomorphic to $ \mathbb{Z}$.
Please help me to find $\frac{\mathbb{Z}\times\mathbb{Z}}{\left<(1,2),(2,3)\right>}$

A: $$\begin{vmatrix}1&2\\2&3\end{vmatrix}=-1\implies \Bbb Z\times\Bbb Z/\langle (1,2)\,,\,(2,3)\rangle\cong 1$$
The above assumes you know something about Smith normal form of matrices, the Fundamental Theorem of finitely generated groups (or of modules over noetherian rings) and stuff.
Another way: show $\;(1,0)\,,\,(0,1)\in\langle (1,2)\,,\,(2,3)\rangle\;$...

A: Define $\phi : \mathbb{Z} \times \mathbb{Z} \rightarrow \mathbb{Z}, (a, b) \mapsto 2a -b.$ Then $\phi$ is a surjective group homomorphism with ker $\phi = (1, 2)\mathbb{Z}.$ (this give you the first isomorphism) Now $\phi (2,3) = 1.$ So using third isomorphism theorem for groups, we have,
$$\frac{(\mathbb{Z} \times \mathbb{Z})} {\left<(1,2),(2,3)\right>} \cong \frac{\frac{((\mathbb{Z} \times \mathbb{Z})}{\left< (1, 2)\right>}}{\frac{((\left<(1,2),(2,3)\right>)}{\left< (1, 2)\right>}} \cong \frac{\mathbb{Z}}{\mathbb{Z}} = 0.$$

A: Since $$(1,0) = 2 \cdot (1,2) - (2,3)$$
$$(0,1) = -3 \cdot (1,2) + 2 \cdot (2,3)$$
you have that $(1,0),(0,1) \in \langle (1,2), (2,3)\rangle$, so $\mathbb{Z} \times \mathbb{Z} = \langle (1,0), (0,1)\rangle \subseteq \langle (1,2), (2,3)\rangle $.
This means that the quotient is trivial.


text:
Q: Can't launch JetBrains Toolbox on macOS Mojave 10.14.5 I'm trying to launch the JetBrains Toolbox, but it seems I can't. When I launch via Spotlight search, nothing appears to happen. But when I try to run the launcher manually from the command line, this happens:
> /Applications/JetBrains\ Toolbox.app/Contents/jetbrains-toolbox-launcher.app/Contents/MacOS/jetbrains-toolbox-launcher
2019-06-07 10:08:56.436 jetbrains-toolbox-launcher[47157:731143] Staring wrapper...
2019-06-07 10:08:56.437 jetbrains-toolbox-launcher[47157:731143] Running app file:///Applications/Calculator.app/ with arguments (
)

and then, indeed, the Calculator launches.
I just upgraded to macOS Mojave 10.14.5 and I believe the app was working before the upgrade. I recently accidentally deleted large parts of /usr/local with an inadvertent rm -rf /usr/local (non-sudo). I interrupted it fairly quickly and was able to restore my Homebrew apps to apparently-working order by re-linking all of them. I successfully launched the Toolbox application once after that happened, but was unable to do so again.
Unfortunately, I don't remember for sure how I installed Toolbox, but I think I installed it directly from the web rather than with brew cask.
I can see the Toolbox app icon in Launchpad, and just as when launching from Spotlight Search, nothing seems to happen when I try to launch it from there.
Any idea what's going on here?


text:
Q: how to write nordic characters to a json file from python? Suppose I have the following example in python
import json

In [46]: d = {'test': u'Fors\xf8g'}

In [47]: print(d['test'])
Forsøg

In [48]: with open('da.json', 'w') as f:
    ...:         json.dump(d, f, sort_keys=True, indent=4)
    ...:

Opening that json file I see the following.
{
    "test": "Fors\u00f8g"
}

But I would like to see it like the print above with the proper nordic characters. How do I achieve this?

A: What you see is 100% correct. JSON allows strings that contain only ASCII characters and escape all "extended" characters as \u + Unicode character code.
When you or anyone else parses the file again, the correct letter will appear. There is nothing you need to do, really.
If you absolutely don't like how that looks, you need to write the JSON file as UTF-8. This works, too, but Python 2.7's open() does not give you a file encoding choice (Python 3+ does).
You can use the codecs.open(), which allows easy handling of UTF-8 files:
import codecs
import json

d = {'test': u'Fors\xf8g'}

with codecs.open('da.json', 'w', encoding='utf8') as f:
    json.dump(d, f, sort_keys=True, indent=4, ensure_ascii=False)

Since json.dump() is responsible for the escaped characters, we need to tell it to not do that with ensure_ascii=False.


text:
Q: An inequality for polynomials I have been thinking about the validity of the following inequality: if $P(z)=\sum_{k=0}^na_kz^k, a_n\neq 0$ and $P(z)$ is non-zero in $|z|<1, $ then for  $\theta \in [0, 2\pi],$  and $p>0$
\begin{align*}
  &\int_{0}^{2\pi}\left|n\left(1-\frac{|a_0|-|a_n|}{n(|a_0|+|a_n|)}\right)P(e^{i\theta})+(\eta-e^{i\theta})P'(e^{i\theta})\right|^{p}d\theta\\
  &\qquad\qquad\quad \leq \left[n\left(1-\frac{|a_0|-|a_n|}{n(|a_0|+|a_n|)}\right)\right]^{p}\int_{0}^{2\pi}|P(e^{i\theta})|^{p}d\theta,
  \end{align*}
for any $\eta$ lying in the closed unit disc.
In fact the above inequity is motivated by the inequality from Melas and Rubinstein [2] who proved that
if $P(z) $ is a polynomial of degree $n$ then for  $\theta \in [0, 2\pi],$
\begin{align*}
  &\int_{0}^{2\pi}\left|nP(e^{i\theta})+(1-e^{i\theta})P'(e^{i\theta})\right|^{p}d\theta\\
  &\qquad\qquad\quad \leq n^{p}\int_{0}^{2\pi}|P(e^{i\theta})|^{p}d\theta.
  \end{align*}
Alternatively the above result [due to Melas] can be established directly through an inequality due to Arestov [1] involving admissible operators on the class of polynomials.  Is my above claim right? Your suggestions are of great help.
References
[1] Vitaliĭ Vladimirovich Arestov, "On integral inequalities for trigonometric polynomials and their derivatives" (Russian original)
(English translation) Mathematics of the USSR, Izvestiya 18, 1-17 (1982),  Zbl 0517.42001; Izvestiya Akademii Nauk SSSR. Seriya Matematicheskaya, 45, 3-22 (1981), MR607574, Zbl 0538.42001.
[2] Antonios D. Melas and Zalman Rubinstein, "Problem 10255 and solution" American Mathematical Monthly, 103, 177-181 (1996).

A: $\newcommand\ep\varepsilon$This inequality does not hold in general.
Indeed, by continuity/denseness, the condition $a_n\ne0$ can be dropped (in response to a comment by the OP, details on this are now given at the end of this answer).
Now just take $p=2$, $\eta=-1$, $n=2$, $P(z)=1-z+0z^2$ (so that $a_0=1$ and $a_n=a_2=0$). Then the left- and right-hand sides of the conjectured inequality are $8\pi$ and $4\pi$, respectively. $\quad\Box$

Details on the mentioned continuity/denseness: Let again $p=2$, $\eta=-1$, $n=2$, but now $P(z)=1-\ep-z+\ep z^2$ with $\ep<0$ -- so that $a_0=1-\ep$ and $a_n=a_2=\ep\ne0$). Then the roots $1$ and $1/\ep-1$ of $P(z)$ are outside the open unit disk, so that $P(z)\ne0$ if $|z|<1$. Moreover, with $\ep\uparrow0$, the left- and right-hand sides of the conjectured inequality will converge to $8\pi$ and $4\pi$, respectively. More specifically, the difference between the left- and right-hand sides of the conjectured inequality will then be $4(1-\ep)\pi\to4\pi>0$.
$\quad\Box$


text:
Q: Javascript switch statements with shared cases I have created a series of switch statements which perform a similar task.
Currently I have something like this...
switch(seconds % 10) {
    case 0: bs2 = "zero";
    break;
    case 1: bs2 = "one";
    break;
    case 2: bs2 = "two";
    break;
    case 3: bs2 = "three";
    break;
    case 4: bs2 = "four";
    break;
    case 5: bs2 = "five";
    break;
    case 6: bs2 = "six";
    break;
    case 7: bs2 = "seven";
    break;
    case 8: bs2 = "eight";
    break;
    case 9: bs2 = "nine";
}
document.getElementById("s2").className = bs2;

This is followed up another very similar switch statement such as...
switch(minutes % 10) {
    case 0: bm2 = "zero";
    break;
    case 1: bm2 = "one";
    break;
    case 2: bm2 = "two";
    break;
    case 3: bm2 = "three";
    break;
    case 4: bm2 = "four";
    break;
    case 5: bm2 = "five";
    break;
    case 6: bm2 = "six";
    break;
    case 7: bm2 = "seven";
    break;
    case 8: bm2 = "eight";
    break;
    case 9: bm2 = "nine";
}
document.getElementById("m2").className = bm2;

This sort of thing carries on further, but I'm sure you get the idea. It works, but as you can see in both statements the only differences are the expressions and the className that the result is being passed to. It strikes me that there must be a more efficient way of doing the same thing. Any pointers?

A: You can simplify your code by creating a function like following

function getFigure(t) {
var value;
switch(t % 10) {
    case 0: value = "zero";
    break;
    case 1: value = "one";
    break;
    case 2: value = "two";
    break;
    case 3: value = "three";
    break;
    case 4: value = "four";
    break;
    case 5: value = "five";
    break;
    case 6: value = "six";
    break;
    case 7: value = "seven";
    break;
    case 8: value = "eight";
    break;
    case 9: value = "nine";
}
return value;
}
var seconds = 8;
var bm = getFigure(seconds);
console.log(bm);

Or you can further maintain an array with values and get the value like following

let arr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
let seconds = 9;
let minutes = 2;
document.getElementById("s2").className = arr[seconds % 10];
document.getElementById("m2").className = arr[minutes % 10];
.nine {
  color: red;
}
.two {
  color: blue;
}

Seconds

Minutes


text:
Q: Mapping a Collection without using DBRef (Spring Data MongoDB) I've been reading a lot that the use of DBRef for Collection Mapping in Spring Data/MongoDB is discouraged. So, how can I implement a mapping that stores an array of ObjectId taken from those objects inside the students collection?
Assuming that I have the following POJO model:
@Document (collection = "courses")
public class Course {

    @Id
    private String id;

    private String name;

    private List<Student> students = new LinkedList<Student>();

    //.. constructors, getters and setters ..
}

public interface CourseRepository extends MongoRepository<Course, String> { }

The result should be something like this:
courses
{
    _id : ObjectId("foo"),
    _class: "model.Course",
    name: "MongoDB for Dummies",
    students: [ ObjectId("foo2"), ObjectId("foo3"), ... ]
}

Instead of this:
courses
{
    _id : ObjectId("foo"),
    _class: "model.Course",
    name: "MongoDB for Dummies",
    students: [
             DBRef("student", ObjectId("foo2")),
             DBRef("student", ObjectId("foo3"))
    ]
}

Thanks!

A: You might wanna try the obvious and change students to a List<ObjectId>. ;)


text:
Q: Fetching the name of the APIs or Proxy in WSO2 Integration Studio I want to fetch the name of the Proxy or APIs in WSO2 Integration Studio and store it in Property mediator so that they can be printed in the custom Error Sequences and Templates. Are there How can I do that?

A: To get proxy name, use expression="get-property('proxy.name')", and for API you can use expression="get-property('SYNAPSE_REST_API')"
There is one more, "uniwersal property" like expression="get-property('ARTIFACT_NAME')". It gives you concatenation of type proxy or api and the artifact name, for example: proxySampleMyService or apiexample


text:
Q: How to build CDATA values in xml2js for node server? I'm trying to parse a xml file and then change CDATA value of some nodes using xml2js. And then write the new xml document into that file. I've tried everything, but still not getting anywhere. I tried using string "" and "cdata" option in builder class. But it doesn't work. It always writes the text node as undefined i.e. [![CDATA[undefined]]
fs.readFile(xmlFileUrl, function(err, data) {
    parser.parseString(data, function(err, result) {
        //Change a node value to something .... and then build it
        var xml = builder.buildObject(result);
        fs.writeFile(xmlFileUrl), xml, function(err) {
            if (err) {
                console.log(err);
                return;
            }
        });
    });
});


text:
Q: Uploading video to server in windows phone 8.1 Iam currently working with windows phone 8.1 application.I got stuck in a portion where uploading video to server using phone camera.I want send the video at every 10s to server while recording..thnks in advance

A: You can use dispatch timer to save your 10-second video clips(StorageFile) in your app localstorage and send the storagefile to another function that makes the fileupload network calls asynchronously.


text:
Q: on mouse enter misbehaving in Chrome I have this on-mouse-enter trigger code (JavaScript to listen for mouse enters and CSS for transitions) and lately, it's been acting funny in Chrome; tested on v 44.0.2403.157m without any error in the console. By acting funny, I mean that fade in-out effect sometimes is skipping.

var shown = true;
var parent = document.querySelector('.parent');
var child = document.querySelector('.child');

parent.addEventListener('mouseenter', function(){
  child.style.opacity = shown ? 0 : 1;
  shown = !shown;
});
* {
  margin: 0;
  padding: 0;
}

.parent {
  width: 100%;
  margin: 10px auto;
  position: relative;
}

.child {
  position: absolute;
  top: 0;
  width: 100%;
  height: 100%;
  display: block;
  overflow: hidden;
  transition: opacity 0.5s linear;
}

p {
  padding: 1em;
}

The code should work like we have in this example.
I would greatly appreciate to have your code alternatives and thoughts.
Thanks

A: I did some research and there are multiple reports about this issue like here or here.Your code works as expected for me in both Firefox(38.0.5) and Edge(20.10240.16384.0).I assume this problem is caused by Chrome considering your code is written well.


text:
Q: CSS to get a div stuck to the bottom of a bootstrap column I'm working on a template that has three columns - two are lists and the third is going to be data. I'm trying to format the first two lists to be scrollable and then have the bottom of the list column to be a button. I would like the button to be fixed at the bottom always.
I assume that I have to add some sort of fixed height for the list-group and then set overflow-y: scroll to get the scroll look but how can i set the div at the bottom of the list to always be at the bottom of the page?
I've also included a plunker: http://plnkr.co/edit/3W6aFI1nngtMbWzYnUVC
Thanks for the help
For instance, this is what one column would look like:

    Items
    Items
    Items
    Items
    Items
    Items
    Items
    Items
    Items

    <button class="btn btn-block btn-default">New</button>

A: All you need to do is, add a fixed height to the Divs you want to be scrollable and allow scrollbars on the div.
Modify your CSS to include the below snippet or add them in-line to your Divs:
height:100px; overflow:scroll;

Working example here


text:
Q: Find the number of $7$-element subsets $\{a,b,c,d,e,f,g\}$ of $\{1,\cdots,14\}$ such that $7 \mid (a+ b+c+d+e+f+g)$ I would appreciate if somebody could help me with the following problem:
Q: Find the number of $7$-element subsets $\{a,b,c,d,e,f,g\}$ of $\{1,\cdots,14\}$ such that $7 \mid (a+ b+c+d+e+f+g)$
I think I've seen the above problem somewhere, but I can't remember. I want to see the solution again. Or please tell me how to approach it.
Study: After dividing 1 to 14 based on the remainder of dividing by 7, I tried an approach based on the number selected from each set, but I couldn't solve it because there were many trees or many cases.

A: Here is a generating functions solution. Since all summands are distinct, their order does not matter, and we need to keep track of both the total sum and the size of the parts, we need the summands of the form $x^ky$ ($1$ part of size $k$) in the factors of the generating function. We can have $0$ or $1$ of copy of each part, so our factors are of the form $1+x^ky$, and our generating function is
$$
\prod_{k=1}^{14}(1+x^ky).
$$
The smallest possible sum divisible by 7 is $1+2+\dots+7=28$, and the largest possible sum $8+9+\dots+14=77$, so we need the sum of the coefficients of $\prod_{k=1}^{14}(1+x^ky)$ at $x^{7\ell}y^7$, where $4\le\ell\le 11$.
Expanding in Mathematica and adding up these coefficients in the order of increasing $\ell$, we get
$$
1+15+75+155+155+75+15+1=492.
$$
There is also an obvious symmetry here, induced by the map $x\mapsto 15-x$.

A: Here is a Starting Point :
Write the 14 numbers around a circle equally , clockwise , & also write the (Modulo 7) along with the numbers around the circle.
$01,02,03,04,05,06,07,08,09,10,11,12,13,14$
$01,02,03,04,05,06,00,01,02,02,04,05,06,00$
Now choose 7 elements which add up to a multiple of 7 , in other words $(0 \mod 7)$.
You can check that by rotating & selecting the successors of all the elements, you will still have a multiple of 7 , in other words $(0 \mod 7)$. This way you get more Solutions.
You can easily see that, given a Solution, you can always find at least 1 element which has 1 unused successor element clockwise.
If you exchange that element with the successor element, you will get 1 more than a multiple of 7, in other words $(1 \mod 7)$.
You can repeat this to get $(2 \mod 7)$ & $(3 \mod 7)$ etc.
Given a Solution, you can get more Solutions with the rotation & you can get more non-solutions with the increment.
This way , you can get all Possible 7-element subsets.
It is a simple matter to see how many 7-element subsets there are & how many 7-element subsets are with $(0 \mod 7)$, how many 7-element subsets are with $(1 \mod 7)$, how many 7-element subsets are with $(2 \mod 7)$, how many 7-element subsets are with $(3 \mod 7)$, ....

A: From : Find the number of all subsets of $\{1, 2, \ldots,2015\}$ with $n$ elements such that the sum of the elements in the subset is divisible by 5
The answer seems to be $\frac17\binom{14}7+\frac67\binom{2}{1} = 492$.

A: Here's a recursive approach.  For $i\in\{0,\dots,7\}$, $j\in\{0,\dots,14\}$, and $m\in\{0,\dots,6\}$, let $f(i,j,m)$ denote the number of $i$-subsets of $\{1,\dots,j\}$ whose sum is $m \pmod 7$.  Then
$$f(i,j,m) = \begin{cases}
1 &\text{if $i = 0$ and $m=0$} \\
0 &\text{if $i = 0$ and $m > 0$} \\
0 &\text{if $i > 0$ and $j = 0$} \\
\sum_{k=0}^1 f(i-k,j-1,m-jk \pmod 7) &\text{otherwise}
\end{cases}$$
You want to compute $f(7,14,0)$, which turns out to be $492$.

Alternatively, you can reduce the number of states and instead condition on the number ($0$, $1$, or $2$) of times that an element with a given $\bmod 7$ value appears.  For $i\in\{0,\dots,7\}$, $j\in\{0,\dots,6\}$, and $m\in\{0,\dots,6\}$, let $g(i,j,m)$ denote the number of $i$-sets with up to $2$ elements for each $\bmod 7$ value in $\{0,\dots,j\}$ and whose sum is $m \pmod 7$.  Then
$$g(i,j,m) = \begin{cases}
1 &\text{if $i = 0$ and $m=0$} \\
0 &\text{if $i = 0$ and $m > 0$} \\
\binom{2}{i} &\text{if $i > 0$, $j = 0$, and $m = 0$} \\
0 &\text{if $i > 0$, $j = 0$, and $m > 0$} \\
\sum_{k=0}^{\min(2,i)} \binom{2}{k} g(i-k,j-1,m-jk \pmod 7) &\text{otherwise}
\end{cases}$$
You want to compute $g(7,6,0)$, which turns out to be $492$.


text:
Q: CodeIgniter 4 - turn off display of debugger toolbar - without changing CI_ENVIRONMENT CodeIgniter 4 - how to turn off display of debugger toolbar - without changing CI_ENVIRONMENT?
Changing environment variable CI_ENVIRONMENT to production will turn off the debug toolbar - but will also suppress errors.
I want to still see errors - but I do not want to see the debug toolbar at the bottom of all of my views when in 'development' mode.

A: Removing toolbar from $gloabals['after'] in app\config\Filters also do the trick.
Source: https://forum.codeigniter.com/showthread.php?tid=76243&pid=375043#pid375043

A: You should remove (or comment) the 'toolbar' filter in App\Config\Filters.php as told in the official CI4 documentation.
public $globals = [
    'before' => [
        // 'honeypot',
        // 'csrf',
    ],
    'after' => [
        //'toolbar',
        // 'honeypot',
    ],
];

A: Setting CI_DEBUG to 'false' - in \app\Config\Boot\development.php - will hide the 'KINT' toolbar; but allow CodeIgniter's error display to continue.
defined('CI_DEBUG') || define('CI_DEBUG', false);

https://codeigniter4.github.io/CodeIgniter4/testing/debugging.html
"the excellent Kint debugging tool for PHP. It will be enabled whenever the constant CI_DEBUG is defined and its value is truthy. This is defined in the boot files (e.g. app/Config/Boot/development.php)."


text:
Q: Constructors for structs that don't do anything Edit: Just to be clear, the struct doesn't do anything, as in it has no functions. I think I gave the impression that I thought using an initialiser list and leaving the body of the constructor empty was the issue at hand.
Say I'm using a struct to hold two values, and I have a constructor just so I can create an arbitrary struct like this:
struct twoValues
{
    int x;
    int y;

    twoValues(int x_, int y_):y(y_),x(x_)
    {}
};

someFunction(twoValues(1,2));

That saves me from having to do this:
twoValues anInstance;
anInstance.x=1;
anInstance.y=2;
someFunction(anInstance);

Edit: You're all correct, I could also initialise with the following:
twoValues anInstance = {1,2};

I see nothing wrong with this but I had some feedback from a C++ test and one of the negative feedback marks was "constructors for structs that don't do anything". I had limited contact with the guy testing me and so never asked why.
Is it a bad thing and why? I would rather carry on doing it.

A: You've stopped twoValues from being a POD and have prevented instances of the struct from being default- or value- initialized which are often desirable properties. Personally, I would prefer to have a free function for making temporary instances if you need a simple C++03 friendly approach.
E.g.
twoValues makeTwoValues(int x_, int y_)
{
    twoValues tmp = { x_, y_ };
    return tmp;
}

void f() {
    someFunction(makeTwoValues(1,2));
}

E.g. initializing a member of type twoValues
class X {
    twoValues tv;
public:
    X(int x, int y) : tv(makeTwoValues(x, y)) {}
};

A: It's much safer to have this kind of constructor, than to initialize with a list.
When you initialize with a list :
twoValues anInstance = {1, 2};

It really depends on the order of the members in the struct. Which in most cases is totaly random to begin with.
If another programmer happens to add another member, or to sort the members by alphabet, it wont work correctly.
Having a constructor that assigns the values to the right member by NAME is much safer.

A: Probably because you can initialize it like this:
twoValues anInstance = {1, 2};

However, without the constructor you cannot initialize a anInstance in another struct's initializer list in C++03. For example:
struct Bar {
  twoValues v_;
  Bar() : v_(1,2) {} // error!
  Bar() { v_ = {1,2}; } // have to assign value in constructor body
  Bar() : v_{1,2} {} // OK in C++11
};

so in fact the constructor does something, and it does serve a very useful purpose in C++03. It is less of an issue in C++11.

A: There is nothing wrong with this contructor.
Also, it does something, it affect values to x and y, which is what I would expect from such a constructor.
But, maybe there are some coding rules in your company that says that you should do it another way. In that case I would recommend you ask the person that gave you the feedback and make the necessary modifications.

A: The constructor makes the struct a non-POD which may not be desirable in some cases.
If your struct doesn't have constructor, then your struct will be POD1, and you will be allowed to initialize like this:
twoValues anInstance = {1,2}; //C++03 and C++11 both!
twoValues anInstance {1,2};   //C++11 only

which are good.
1. Actually there are other things which make a struct non-POD. So just because your struct doesn't have constructor doesn't necessarily mean it is POD. You would like to see this post to know what those other things are.

A: It depends on what the struct is being used for.  As others have said,
the constructor means that the class is no longer a POD, and that
aggregate initialization cannot be used for it.  In particular, you
cannot have something at namespace scope like:
TwoValues const table[] =
{
    { 1, 2 },
    { 3, 4 },
    // ...
};

You can have:
TwoValues const table[] =
{
    TwoValues(  1, 2  ),
    TwoValues(  3, 4  ),
    // ...
};

but it is more verbose, and it implies dynamic initialization, which may
result in order of initialization issues.
On the other hand, without the constructor, you cannot create temporary
instances on the fly.  Instead of:
extern void f( TwoValues const& );
//  ...

f( TwoValues( 1, 2 ) );

you have to write:
extern void f( TwoValues const& );
//  ...

TwoValues tmp = { 1, 2 };
f( tmp );

If the object is dynamically allocated, it's even worse, since you
either have to allocate first, then initialize, or create a temporary as
above, and then write new TwoValues( tmp ) and use the implicit copy
constructor.
You have to choose.  Depending on what the struct is used for, one or
the other will be preferred; on one hand, I have a lot of structs which
are used exclusively in static tables, and intentionally don't have a
constructor (and contain only types which support static
initialization), and use them a lot for configuring code.  On the other
hand, I also have a lot of structs which are internal to a class, along
the lines of Node in a tree or a graph; these almost always have a
constructor, to facilitate creating them on the fly.  There's no
"correct" answer without knowing the role of the struct in your
application.

A: Declaring an empty constructor has side-effects..
Even though your constructor has an empty body it is still considered to be a constructor, and therefore certain object properties will be lost - such as the object being POD.
Some cases require the use of Plain Old Data-types, which can make it undesirable to do what you've done without a specific reason.
Read more about initialization without a defult constructor in the next section.

c++03 && c++11
You can initialize your members with values without explicitly defining a "constructor that doesn't do anything", just use the brace-initialization syntax as in the below snippet.
struct Obj {
  int x, y;
};

Obj a = {1,3}; /* a.x = 1, a.y = 2 */

c++03
The downside of not having a constructor is that you cannot initialize the object using  = { ... } in certain circumstances when writing C++03.
C++11 fixes this for you, see the next section for relevant examples.

c++11
In C++11 the initialization using braces ( = { ... }) has been given increased functionality.
As seen in the below snippet where the defined constructor of Obj is called even though we use the same form of initialization as earlier in this post.
struct DoubleBoth {
  DoubleBoth (int x, int y)
    : x(x*2), y(y*2)
  {}

  int x, y;
};

The snippets below were all illegal prior to C++11:
DoubleBoth a = {1,2}; /* a.x = 2, a.y = 4 */

struct Wrapper {
  Wrapper ()
    : value {3,4}
  {}

  DoubleBoth value;
};

void func (DoubleBoth v = {1,2}) {  // c++11 only
  ...
}

func ({4,5}); // c++11 only, c++03 requires `DoubleBoth obj (0,1); func (obj);`

A: Structures can have constructors, and the syntax is the same as for classes in C++. The difference between a class and a struct is that class-members are private by default, while struct-members default to public, however Unions will not allow constructors in the structs. You can make a constructor on the union though.


text:
Q: rails 3 partial depending on locale I am developing a rails 3 app for 2 locales (:en, :kr).
I have 2 view files:
index.en.html.haml
index.kr.html.haml

And each file uses partial.
_info.en.html.erb
_info.kr.html.erb

(Partials are erb instead of haml)
= render :partial => "info"

This always uses _info.en.html.erb ignoring locale.
Partial can't be auto-selected for locales?
Thanks.

A: Try
= render :partial => "info"


text:
Q: Same Django Models Shared in two different Projects hosted at different urls I have hosted a django project with one app on [heroku] (keshavbits.herokuapp.com). I have few models with too many data inside it. Now I wanted an another django project that will be hosted at example.herokuapp.com with same settings,views and everything as it is in keshavbits.herokuapp.com. Now the question is how can I access the Database hosted at keshavbits.herokuapp.com in the example.herokuapp.com.
Or how can I share databases b/w these two apps at different locations?


text:
Q: Scala error when providing subclass instance in place of superclass? I am just trying things out in scala and I wrote this code
object Main:
  def main(args: Array[String]): Unit =
    val dInt: Data[Int] = IntData(1)
    val dString: Data[String] = StringData("hello")
    val Data(deconstructedInt) = dInt // unapply
    val Data(deconstructedString) = dString // unapply
    println(deconstructedInt)
    println(deconstructedString)

sealed trait Data[+T]:
  def get: T

case class IntData(get: Int) extends Data[Int]

case class StringData(get: String) extends Data[String]

object Data:
  def apply[T](input: T): Data[T] = input match {
    case i: Int => IntData(i) //compile error here
    case s: String => StringData(s) //compile error here
  }

  def unapply[T](d: Data[T]): Option[String] = d match {
    case IntData(get) => Some(s"int data => get = $get")
    case StringData(get) => Some(s"string data => get = $get")
  }

I get at the location commented in the code this error
Found:    IntData
Required: Data[T]
    case i: Int => IntData(i)

why I am getting this error, isn't IntData (or StringData) a subclass of Data ?

A: IntData is a subtype of Data[Int]. So if T is not Int, IntData is not a subtype of Data[T]. Now, you might say, if input matches the first case, then clearly T is Int. But the compiler is not smart to realise this!
You could try using Scala 3's new match types:
type DataOf[T] = T match {
  case Int => IntData
  case String => StringData
}

def apply[T](input: T): DataOf[T] = input match {
  case i: Int => IntData(i)
  case s: String => StringData(s)
}

Another alternative is union types:
def apply(input: Int | String): Data[Int | String] = input match {
  case i: Int => IntData(i)
  case s: String => StringData(s)
}

However, you will lose type information in doing this. Using the match types solution, apply(42) is inferred to have type IntData. Using the union types solution, it is inferred to have type Data[Int | String].

A: This way compiler connects the dots between Ts and it works:
  object Main:
    def main(args: Array[String]): Unit =
      val dInt: Data[Int] = IntData(1)
      val dString: Data[String] = StringData("hello")
      val Data(deconstructedInt) = dInt // unapply
      val Data(deconstructedString) = dString // unapply
      println(deconstructedInt)
      println(deconstructedString)

  sealed trait Data[+T]:
    def get: T

  case class IntData[T <: Int](get: T) extends Data[T]

  case class StringData[T <: String](get: T) extends Data[T]

  object Data:
    def apply[T](input: T): Data[T] = input match {
      case i: Int    => IntData(i)
      case s: String => StringData(s)
    }

    def unapply[T](d: Data[T]): Option[String] = d match {
      case IntData(get)    => Some(s"int data => get = $get")
      case StringData(get) => Some(s"string data => get = $get")
    }


text:
Q: flex+bison in a php extension I have created a small parser in c using flex and bison. The parser writes the result to some global variables and the caller function reads it from there.
I am trying to package my parser as a php extension. From what i understand from the php documentation true global variables are not recommended because they are not thread-safe and i have to use module globals instead.
In order to use module globals you have to pass in the function TSRMLS_DC as its last argument.
To you know if i can modify the yyparse to accept TSRMLS_DC as an argument. Or if there is another way to access global variable?

A: I wouldn't use global variables, but use a more modern parser generator that is also reentrant. Look for instance how I've done it for the meta extension (I use a slightly changed lemon and re2c).


text:
Q: Как сделать смену направления текста? Всем привет. Хотел бы спросить у знатоков, может быть кто делал подобное: как сделать смену направления текста с каждой новой строки. Полувизуальный пример:
текст слева-направо
текст справа-налево
текст слева-направо
текст справа-налево.. и т.д.
Перенос - не абзац (
), а обычный word-wrap. Я так понимаю, меня интересует смена значений с ltr на rtl и наоборот каждую новую строку.
В примере ниже я сделал это при помощи параграфов и ксса. В моём случае мне нужно, чтобы текст переносился после word-wrap и будучи исключительно в одном параграфе, диве и т.д.

.ltr {
  direction: ltr;
  }
.rtl {
  direction: rtl;
  }

Some text ltr

ltr txet emoS

Some text ltr

ltr txet emoS

Some text ltr

ltr txet emoS

A: Можно сделать как-то так (по идее, можно ускорить, прикидывая, сколько слов влезет в строку и добавляя сразу несколько):

function wrap(element){
  var text = element.getAttribute('data-original');
  if (!text){
    text = element.textContent.trim();
    element.setAttribute('data-original', text);
  }

  var words = text.split(/\s+/);
  var result = '', line = '', reverseLine = false;

  element.innerHTML = 'a';
  var height = element.offsetHeight;

  for (var i = 0; i < words.length; i++){
    var candidate = line + ' ' + words[i];
    element.innerHTML = result + candidate;
    if (element.offsetHeight > height){
      height = element.offsetHeight;
      result += '
' + line + '
';
      line = words[i];
    } else {
      line = candidate;
    }
  }

  if (line) result += '
' + line + '
';
  element.innerHTML = result;
}

function wrapAll(){
  console.time('wrapAll()');
  [].forEach.call(document.querySelectorAll('.weird-word-wrapping'), wrap);
  console.timeEnd('wrapAll()');
}

wrapAll();
window.onresize = wrapAll;
.weird-word-wrapping div:nth-child(2n) {
  direction: rtl;
  unicode-bidi: bidi-override;
  white-space: nowrap;
}

Многие думают, что Lorem Ipsum - взятый с потолка псевдо-латинский набор слов, но это не совсем так. Его корни уходят в один фрагмент классической латыни 45 года н.э., то есть более двух тысячелетий назад. Ричард МакКлинток, профессор латыни из колледжа Hampden-Sydney, штат Вирджиния, взял одно из самых странных слов в Lorem Ipsum, "consectetur", и занялся его поисками в классической латинской литературе. В результате он нашёл неоспоримый первоисточник Lorem Ipsum в разделах 1.10.32 и 1.10.33 книги "de Finibus Bonorum et Malorum" ("О пределах добра и зла"), написанной Цицероном в 45 году н.э. Этот трактат по теории этики был очень популярен в эпоху Возрождения. Первая строка Lorem Ipsum, "Lorem ipsum dolor sit amet..", происходит от одной из строк в разделе 1.10.32

Без ручного переноса, насколько я понимаю, сделать не выйдет.


text:
Q: update index in Solr, error: required field in SolrSchema not found in DataConfig I'm trying to update my index, but I keep on getting the error:

org.apache.solr.handler.dataimport.DataImporter
  verifyWithSchema INFO: UPC is a
  required field in SolrSchema . But not
  found in DataConfigfound in DataConfig

I can't figure out why it's complainting, since:

*

*the first time I ran the import, it worked fine, and the only thing I changed was add a few fields (columns) to schema.xml

*the table I am querying indeed has a UPC column. Here is what my data-config.xml looks like:
<dataConfig>
  <dataSource type="JdbcDataSource"
      driver="com.mysql.jdbc.Driver"
      url="jdbc:mysql://localhost:3306/product"
      user="root"
      password="some_password"/>
  <document>
    <entity name="product"
       query="select * from productdetails">
    </entity>
  </document>
 </dataConfig>

But again, the interesting part is that the import worked a second ago, but fails on re-import. I'm hoping somebody has had this problem before. If not, maybe someone can suggest other things to check for?

A: The reason for this is that when DataImportHandler starts it checks its config against your loaded schema. It is not an error, merely a warning. To remove it you have to add a specific field in your import config with a name that matches your required field.
This is not the cause of your failed reimport as this is simply a warning.


text:
Q: Each composite (positive) $n$ has a (positive) prime divisor no greater than $\sqrt{n}$.
$\forall n \in \mathbb N^+$, $n$ is composite $\;\rightarrow\; \exists p\in \mathbb N^+, p \textrm{ is prime  and } p \leq \sqrt{n} \textrm{ and }  p\; |\; n$.

So far this is what I have...
Suppose this is false.
$p> \sqrt{n}$,  $p|n$
Then, $p^2 > n, p|n,$ where $p|n$ is also $pa=n$
Then $p^2 > pa$

A: Factors come in pairs.  If $j|n$ then there is a $k$ so that $j*k = n$.  And $k$.... is also a factor.
If one of the factors is $j \ge \sqrt{n}$ then $k = \frac nj \le \frac n{\sqrt{n}} = \sqrt{n}$.
So at least one of $j$ or $k$ is $\le \sqrt{n}$ (and the other is $\ge \sqrt{n}$).
So if we assume $j*k = n$ and $1 \ne k \le j \ne n$ we have $k \le \sqrt{n}$.
If $p$ is any prime factor of $k$ than $p \le \sqrt{n}$ and $p|n$.
That's it.  We're done.


text:
Q: Getting the same web and file paths from scripts in different locations Let's say I have this directory structure:
myApp
|____files
|
|__myFolder
|      |___script1.php
|
|__script2.php
|___myClass.php

script1.php and script2.php are identical, and all they do is instantiate myClass, put a file in the files folder, and print out an HTML anchor link to that file.
//script1.php and script2.php:

/*require myClass*/

$myClass = new myClass();
$myClass->copyFile();
$link = $myClass->retHref();
echo 'Click here

Currently I am doing this in myClass.php, to get the absolute path and href:
//myClass.php

class myClass{

    public function copyFile()
    {
        $absPath = dirname(__FILE__).'/files/file.txt';
        //code to copy the file
    }

    public function retHref()
    {
        return $_SERVER['HTTP_REFERER'].'/files/file.txt';
    }

}

Is this the best way to go about this, or is there a better way to
a) Get a file path
and
b) Create a web link
from inside a class, when I don't know where the script will live that instantiates the class and calls its functions?

A: You can use the __DIR__ constant to generate an absolute path to the files directory. In terms of creating a href link, it's a bit more complex. I used the code from this answer in the example below:
class myClass
{

    const FILE_DIRECTORY_PATH = __DIR__.'/files/file.txt';

    public function copyFile()
    {
        $pathToFile = self::FILE_DIRECTORY_PATH;
        //code to copy the file
    }

    public function retHref()
    {
        return $this->urlOrigin($_SERVER).'/files/file.txt';
    }

    private function urlOrigin($s, $use_forwarded_host = false)
    {
        $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on');
        $sp = strtolower($s['SERVER_PROTOCOL']);
        $protocol = substr($sp, 0, strpos($sp, '/')).(($ssl) ? 's' : '');
        $port = $s['SERVER_PORT'];
        $port = ((!$ssl && $port == '80') || ($ssl && $port == '443')) ? '' : ':'.$port;
        $host = ($use_forwarded_host && isset($s['HTTP_X_FORWARDED_HOST'])) ? $s['HTTP_X_FORWARDED_HOST'] : (isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : null);
        $host = isset($host) ? $host : $s['SERVER_NAME'].$port;
        return $protocol.'://'.$host;
    }
}


text:
Q: Python function help, does someone can tell me why it doesent work? my task is to write a python program removes all characters or strings from a string (text)
specified in a list (strings_list). I got it like this but this doesen't work. Anybody can tell me what i got wrong or did I use a wrong function?
Thanks!!
def remove_strings(text, strings_list):
    for strings_list in remove_strings:
        strings_list.remove()

        text_cleaned = remove_strings("yes, no, maybe..",
                                      ["yes", ","])
    return text_cleaned
    print(text_cleaned)

A:
def removechar(text, strings_list):
    newstrings = []
    for i in strings_list:

        if text in i:
            newtext = ""
            newtext = i
            newtext = newtext.replace(text, "")
            newstrings.append(newtext)
        else:
            newstrings.append(i)

    print(newstrings)
    return(newstrings)

also, .remove() isnt a function, you would have to use .replace(text, "") instead


text:
Q: Filter ListView when tab changed I need to filter a ListView in one activity with three tabs. For instance, I have one tab where are displayed info about all the devices (custom object), but when I change to other tab, it should display the devices of "type1" and when I change to the last tab it displays the devices of "type2".
I already have a custom adapter, and I want to know if I can use the Filterable interface (... implements Filterable ...) and override the getFilter() method (like filtering based on editText) or I should use another approach?
Grateful for any kind of help.

A: I solve this using the onTabChanged() method, like this (in the onCreate()):
mTabHost.setOnTabChangedListener(new OnTabChangeListener() {

        public void onTabChanged(String tabId) {
            Log.d(debugTag, "onTabChanged: tab number=" + mTabHost.getCurrentTab());

            switch (mTabHost.getCurrentTab()) {
            case 0:
                myDevAdapter.getFilter().filter("all");
                break;
            case 1:
                myDevAdapter.getFilter().filter("type1");
                break;
            case 2:
                myDevAdapter.getFilter().filter("type2");
                break;

            default:
                Log.d(debugTag,"error in onTabChanged");
                break;
            }
        }
    });

A: I haven't used onfocuschange  or filterable yet but from what you have said sounds like you will need to use them together.
Another possible approach would be to setup an onclicklistener to filter for you. Having a little trouble picturing this. If I have the right idea. You will display ~100 items. Then click a tab and ~50 will show. Then click the other tab, the other ~50 show. click the last tab and all show again?


text:
Q: Wrong results with Python multiply() and prod() Can anyone explain the following?  I'm using Python 2.5
Consider 1*3*5*7*9*11 ... *49. If you type all that from within IPython(x,y) interactive console, you'll get 58435841445947272053455474390625L, which is correct. (why odd numbers: just the way I did it originally)
Python multiply.reduce() or prod() should yield the same result for the equivalent range. And it does, up to a certain point. Here, it is already wrong:
: k = range(1, 50, 2)
: multiply.reduce(k)
: -108792223

Using prod(k) will also generate -108792223 as the result. Other incorrect results start to appear for equivalent ranges of length 12 (that is, k = range(1,24,2)).
I'm not sure why. Can anyone help?

A: This is because numpy.multiply.reduce() converts the range list to an array of type numpy.int32, and the reduce operation overflows what can be stored in 32 bits at some point:
>>> type(numpy.multiply.reduce(range(1, 50, 2)))
<type 'numpy.int32'>

As Mike Graham says, you can use the dtype parameter to use Python integers instead of the default:
>>> res = numpy.multiply.reduce(range(1, 50, 2), dtype=object)
>>> res
58435841445947272053455474390625L
>>> type(res)
<type 'long'>

But using numpy to work with python objects is pointless in this case, the best solution is KennyTM's:
>>> import functools, operator
>>> functools.reduce(operator.mul, range(1, 50, 2))
58435841445947272053455474390625L

A: The CPU doesn't multiply arbitrarily large numbers, it only performs specific operations defined on particular ranges of numbers represented in base 2,  0-1 bits.
Python '*' handles large integers perfectly through a proper representation and special code beyond the CPU or FPU instructions for multiply.
This is actually unusual as languages go.
In most other languages, usually a number is represented as a fixed array of bits. For example in C or SQL you could choose to have an 8 bit integer that can represent 0 to 255, or -128 to +127 or you could choose to have a 16 bit integer that can represent up to 2^16-1 which is 65535. When there is only a range of numbers that can be represented, going past the limit with some operation like * or + can have an undesirable effect, like getting a negative number. You may have encountered such a problem when using the external library which is probably natively C and not python.


text:
Q: Export an object to be reused in another JavaScript file without the default operator I have two files in a tree that defines an object.
The common.js file.
export default {
  table: {
    actions: {
      save:   'Save',
      delete: 'Delete',
      update: 'Update'
    }
  }
};

In another file, I am calling the common.js file I just stated.
var common = require('common.js');

And whenever I access the object, as said, I get this;
console.log(common);

{
  common:{
    default: {
      table: {
        actions: {
          save: 'Save',
          delete: 'Delete',
          update: 'Update'
        }
      }
    }
  }
}

What I'm looking forward to get is the following;
{
  common: {
    table: {
      actions: {
        save:   'Save',
        delete: 'Delete',
        update: 'Update'
      }
    }
  }
}

That is without the default key. Is there a way I can export the table object and get it without the default key?

A: Just use import syntax instead of require syntax, and the value of the import will be the default export:
import common from 'common.js';
const obj = {
  common,
  // ...
}

https://codesandbox.io/s/5350980o54


text:
Q: Set mouse speed with profiles I have two mice, one at home with resolution 800dpi and one at work with resolution 1000dpi.
The two mice behave differently. When I come to work, I need to set the pointer speed to max. When I work from home, I need to turn the speed down a bit.
I would like to have profiles for the two mice. Ideally, these would be applied automatically, depending on what mouse is connected.
How would I do that?
Running Ubuntu 15.10.

A: You can detect which mouse is connected in X11 using xinput. Eg
$ xinput --list
...
Logitech USB Optical Mouse               id=11   [slave  pointer  (2)]

Note the value in id=, 11 in this example, which is the device's id.
You can use this id to set the ratio for mouse movement:
xinput --set-ptr-feedback $id threshold numerator denominator

or simply
xset m numerator/denominator threshold

To auto-detect a change in mouse is a little more difficult. The simplest is to run udevadm monitor and look for the udev events generated when a mouse in plugged in.


text:
Q: The Google Save To Drive button is hidden on mouse hovering I am trying to integrate Save To Drive button into my project.
At first, this is how I did.

      ${lang.SurveyResultList_SaveCSVDrive}

This is what I got

Then I tried this

      ${lang.SurveyResultList_SaveCSVDrive}

And got this

This is what I expect. However, after a few times saving files to Google Drive, the button's tooltip position was automatically switched back to like the first screenshot above when I hover my mouse over the button. This happened on both Google Chrome and Mozilla Firefox. Does anyone know how to force the tooltip's position always below the button (like the 2nd screenshot)?
UPDATED: As requested by other users, I will post additional html, css and js codes that directly related to the question.
The Save To Drive button is contained within a div element, which in turn is part of a menu element. The html code of the menu is.

    ${lang.SurveyResultList_Download}

${lang.SurveyResultList_DownloadCSV}

${lang.SurveyResultList_DownloadExcel}

${lang.SurveyResultList_SetCustomElement}

                  ${lang.SurveyResultList_SaveCSVDrive}

And here are the css styles of the elements
.yo-popup-5 {
    position: absolute;
    width: 170px;
    height: 150px;
    left: -10px;
    text-align: left !important;
    opacity: 0.9;
    border-radius: 5px;
    background-color: #01579b;
    top: 20px;
}

.yo-popup-5 .yo-popup-item:hover {
    /*border-right: solid 5px #03a9f4;*/
}

.yo-popup-5 .yo-popup-item {
    font-family: Arial, sans-serif;
    font-size: 16px;
    font-weight: normal;
    line-height: 1.5;
    letter-spacing: -0.1px;
    color: #ffffff;
    margin: 10px 1px 10px 10px!important;
}

.yo-popup-5 .yo-popup-item a {
    font-family: Arial, sans-serif;
    font-size: 16px;
    font-weight: normal;
    line-height: 1.5;
    letter-spacing: -0.1px;
    color: #ffffff;
    text-decoration: none;
}

.yo-popup-5 .yo-popup-item a:hover {
    color: #00bcd4;
}

.yo-popup .yo-popup-item:hover {
    border-right: solid 5px #03a9f4;
}

.yo-popup-item {
    margin: 20px 1px 20px 10px;
    font-family: Arial, sans-serif;
    font-size: 16px;
    font-weight: normal;
    line-height: 1.5;
    letter-spacing: -0.1px;
    color: #ffffff;
}

.yo-popup-item a {
    font-family: Arial, sans-serif;
    font-size: 16px;
    font-weight: normal;
    line-height: 1.5;
    letter-spacing: -0.1px;
    color: #ffffff;
    text-decoration: none;
}

.yo-popup-item a:hover {
    color: #00bcd4;
}

This is the javascript function toggleList
function toggleList(event) {
    var list = initSelector();

    var cur_child = $(event.currentTarget).next().children();
    cur_child.css('z-index', 102);
    cur_child.slideToggle(500);
    $(list).each(function() {
        var child = $(this).next().children();
        if ($(child).css('display') != 'none' && $(child).prop('id') != $(cur_child).prop('id')) {
            if ($(child).prop('id').endsWith('-list')
                    && $(child).prop('id').startsWith('yo-')) {
                $(child).css('z-index', (Number($(child).css('z-index')) - 1));
                $(child).slideUp(500);
            }
        }
    });
    event.stopPropagation();
}

I have noticed the html code generated by Google Drive API upon runtime.

                        <iframe ng-non-bindable="" frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" style="margin: 0px; position: absolute; z-index: 1; border-style: none; outline: none; width: 350px; height: 78px;" tabindex="0" vspace="0" width="100%" id="I0_1522823882765" name="I0_1522823882765" src="https://drive.google.com/savetodrivehover?authuser=1&usegapi=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en.HC2g6SRsg_U.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAGLTcCPz5Aj2-ryLqteRLkIrqMk6EuzCaQ#id=I0_1522823882765&_gfid=I0_1522823882765&parent=http%3A%2F%2Fdemo.surveii.com&pfname=&rpctoken=11814994">

And when I hovered my mouse on the Save To Drive button, the html code was changed to

                        <iframe ng-non-bindable="" frameborder="0" hspace="0" marginheight="0" marginwidth="0" scrolling="no" style="margin: 0px; position: absolute; z-index: 1; border-style: none; outline: none; width: 350px; height: 78px;" tabindex="0" vspace="0" width="100%" id="I0_1522823882765" name="I0_1522823882765" src="https://drive.google.com/savetodrivehover?authuser=1&usegapi=1&jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en.HC2g6SRsg_U.O%2Fm%3D__features__%2Fam%3DAQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAGLTcCPz5Aj2-ryLqteRLkIrqMk6EuzCaQ#id=I0_1522823882765&_gfid=I0_1522823882765&parent=http%3A%2F%2Fdemo.surveii.com&pfname=&rpctoken=11814994">

(Notice the div element that I highlighted)
Please take a look and let me know what should I do to relocate the button's tooltip. Thanks.

A: This has nothing to do with Drive API at all.
Check the order to which you place your
 tags, your DOM elements in the page. Observe the hierarchy of page elements.