text:
Q: How to add conditions in Unity unit test hooks for test case Similarly to how SpecFlow has tag features where one can add a @mytag to a scenario and in hooks, say for example in the before scenario, I can do a check if @mytag, do some code.
Is there a way to have my hooks in unity to conditionally do something before the scene starts?
[UnitySetUp]
public IEnumerator UnitySetUp()
{
    //if scenario contains this tag, do this code
    if(mytag)
    {
      do some code
    }
    yield return null;
}

A: I found the answer. It's using TestContext.
[SetUp]
public void SetUp()
{
    if ((string)TestContext.CurrentContext.Test.Properties.Get("tag") == "mytag")
        //do some code
}

[Test]
[NUnit.Framework.Property("tag", "mytag")]
public void TestWithTag()
{

}


text:
Q: Dockerfile or docker image for jboss/openjdk18-rhel7:1.1 Where can I find the docker image (and if possible Dockerfile) for the image jboss/openjdk18-rhel7:1.1
This image is being used in another dockerfile
FROM jboss/openjdk18-rhel7:1.1

ENV \

   PATH="$PATH:"/usr/local/s2i""

A: By default, that means docker will pull an image from the url https://hub.docker.com/jboss/openjdk18-rhel7/ but the repository does not seem exist for me.
Perhaps, you could using https://hub.docker.com/r/jboss/base-jdk/ instead from the same maintainer, like so:

FROM jboss/base-jdk:8

For Dockerfile, see https://hub.docker.com/r/jboss/base-jdk/~/dockerfile/

redpajama_set_name: RedPajamaStackExchange


text:
Q: limits on aws federated users and policies I am working on aws to back up my data. i want to choose following approach for backing up my data.

*

*suppose i have n numbers of organizations and each organization has n number of departments and each department has n numbers of users.

*i want to back up those organizations data based on organization > department >user structure.

*now i have an iam user account and a bucket in aws s3.

*i create a folder structure based on organization structure as
first folder for organization > subfolder for department > child sub folder for users
e.g
organization name :ABC
department name : Developer
user name: testUser
so bucket folder structure on aws will be as
ABC/Developer/testUser/....
so here i show how i am managing organization's data on aws s3.
but now the point is i am allowing organizations users to put/get data to/from s3 on request.
after user's request i will generate federated user credentials for that user will policy which will allow user to put/get data to/from only users folder.
But my questions are:
Q 1. How many federated users can i generate. Is their is any limit for federated users?
Q 2. how many policies an IAM user can generate at a time?
Q 3. As my approach mentioned above their can be n number of federated users so can i generate n number of policies and applies those to federated user.
Thanks & Regerds
Amit Manchanda

A: here is the answer for this question
https://forums.aws.amazon.com/thread.jspa?threadID=172258&tstart=0


text:
Q: How to show current date and time list in dropdown in magento2.1.7? How to show current date and time list in dropdown in magento2.1.7, As I have purchased an extension for store pickup in my magento2 site..
But the date , time functionality is not working properly, so I am trying to create a new controller for getting date and time.
Any help would be appreciated

A: You need to inject in your class constructor an instance of \Magento\Framework\Stdlib\DateTime\DateTime and use that one.
Something like this:
protected $date;
public function __construct(
    ....
    \Magento\Framework\Stdlib\DateTime\DateTime $date,
    ....
) {
    ....
    $this->date = $date;
    ....
}

Then, you can use in your class this:
$date = $this->date->gmtDate();


text:
Q: Runtime issue when compiling a DLL with Conan/CMake that is not present when compiling directly with Visual Studio 2017. Is it possible to solve it? I want to use a DLL build with the help of Conan/CMake (with the Visual Studio 2017 compiler). Unfortunatly it's impiossible to link the DLL with another projet without installing the Visual C++ redistribuables whereas it is possible with a DLL generated directly from Visual Studio 2017. I would like to find a way to generate a DLL that do not need any kind of new dependencies to work. Is there a solution ?
I already tried to modify the compiler's options : /MD, /MT, /MDd, /MTd,
I tried to use the compiler option to take the runtime into account : /clr, /ZW
I tried to use the linker option to take the runtime into account : /WINMD


text:
Q: Using ADO for ASP MVC One of my project requirements is to make a DLL or a helper that will contain all my interaction with the DB and to use ADO instead of EF.
Here is what i have so far:
namespace repository
{
public class access
{
    public string connectionString { get; set; }

    public access()
    {
        connectionString = "Data Source=KISHGAL-PC\\SQLEXPRESS;database=carl;Persist Security Info=True;User ID=sa;Password=123456ca;MultipleActiveResultSets=true";
    }

    public DataSet getData()
    {

        string query = "select * from department";
        SqlDataAdapter adapter = new SqlDataAdapter(query, connectionString);

        DataSet temp = new DataSet();
        adapter.Fill(temp, "test");

        return temp;

    }

}
}

I couldn't find any good examples and usage of DataSet(my client wants me to use DataSet). So i wanna ask if i am on the right track?
I invoke everything from my controller by doing something like this:
[HttpGet]
public ActionResult test()
{
    List<departments> dep = new List<departments>();
    foreach (DataRow dr in cont.getData().Tables["test"].Rows)
    {
        dep.Add(new departments()
        {
            id = Convert.ToInt32(dr["id"]),
            dname = Convert.ToString(dr["dname"])
        });
    }
    return View(dep);
}

So far, i am able to fetch rows and display them from my view but i would like to know how to optimize my code or if there is anything that i missed?

A: You would be better to separate out your query a little bit; You can have your  methods for Create, Update, Delete and Insert as the methods of your class . below code T is a generic type you can use it to pass in a list of type T to the method. Any type basically , your query statements should be separated - so that you can have an encapsulated dll - and the DB tables, do not matter the access of them is the same - the query is passed in to the dll method and you can use that base library for any ER model. There are other ways to do this as well DAL is what this functionality is referred as.
public DataSet SelectAll(string table)
{//.. code to select all}
public DataSet Select(string query)
{//.. code to select all}

public int Insert<T>(List<T> values)
{//.. code to select all}

public int Update<T>(List<T> values)
{//.. code to select all}


text:
Q: Working with subreport that used multiple tables in MS Access I created a subreport that use multiple tables (3 tables) and to update and delete data from a table.
Below is the Form to update and delete that subreport data.

When I clicked on the Edit button, all the data loaded on the form but the first combobox was not load data. See below image]3
Here is the code I wrote for Edit Button
> Private Sub EditState_Click()
>     If Not (Me.subformStateBudget.Form.Recordset.EOF And Me.subformStateBudget.Form.Recordset.BOF) Then
>         With Me.subformStateBudget.Form.Recordset
>              Me.cbState = .Fields("State")
>              Me.cbCategory = .Fields("Category")
>              Me.cbYear = .Fields("Year")
>              Me.Ctl4 = .Fields("4")
>              Me.Ctl5 = .Fields("5")
>              Me.Ctl6 = .Fields("6")
>              Me.Ctl7 = .Fields("7")
>              Me.Ctl8 = .Fields("8")
>              Me.Ctl9 = .Fields("9")
>              Me.Ctl10 = .Fields("10")
>              Me.Ctl11 = .Fields("11")
>              Me.Ctl12 = .Fields("12")
>              Me.Ctl1 = .Fields("1")
>              Me.Ctl2 = .Fields("2")
>              Me.Ctl3 = .Fields("3")
>
>             Me.cbState.Tag = .Fields("State")
>             'Change caption of Save Button to Update
>             Me.savestate.Caption = "Update"
>             'Change Edit Button to hidden
>             Me.EditState.Enabled = False
>
>
>         End With
>     End If End Sub


text:
Q: CREATE OR REPLACE VIEW Vs Checking view existing or not? I am using Maria DB 5.5 version and it does not allow clause 'CREATE VIEW IF NOT EXISTS' while view creation. As requirement, I need to check whether view existing or not while creation.
Here I have 2 approach for this problem …

*

*Do SQL using INFORMATION_SCHEMA.TABLES and create the view only if view is not present

*Use 'CREATE OR REPLACE VIEW' so that no error/warning should throw if view is already present if view might have to handle more than 50k records.

Out of these 2 options, which options is better & recommended approach?

A: If you must know whether the view existed before your operation, using the information schema is helpful.
Otherwise, CREATE OR REPLACE is much simpler. Your view definition can stand alone as a DDL statement.
The first option requires the server to process several queries, so it will take slightly longer than the second option.  But view creation (in MySQL and MariaDB) is very fast: no actual data is retrieved until you use the view in a query.

A: So the VIEW contains an ever-growing UNION across many databases.  So, the only way the VIEW would not exist is when two new users are updating the view 'simultaneously'.
Suggested workaround:
SELECT GET_LOCK('update_view');
DROP VIEW ...;
CREATE VIEW ...;
SELECT RELEASE_LOCK('update_view');

This avoids the need for OR REPLACE (etc), except for the very first time -- when the DROP VIEW will complain that the VIEW does not exist.  That can be solved by creating a dummy VIEW when the machine is first configured.
(Study the parameters on GET_LOCK.)


text:
Q: gcc compiling error for c++ program When I'm trying to compile a C++ program with gcc, it gives me following error:
gcc: error trying to exec 'cc1plus': execvp: No such file or directory
error: command 'gcc' failed with exit status 1

A: You're missing g++ package on your machine. Install it via:
sudo apt-get install g++

Reference.


text:
Q: Android - How to upload photo from the SD card to the Facebook wall I use the Facebook Android SDK.
Goal
Create multiple posts in news feed of Facebook logged in user that will contain photo from the Android device (its SD card) and some comment. The result should be the same as when you do it using the Add photo/video feature directly in Facebook. In the end, it should look like this:
Wanted Facebook result

Problem
I can't do it.
I went through the numerous similar posts on Stack Overflow, but no answer there so far.
What I have tried to implement so far
Approach 1: SD card photos 2 Facebook album
How
Upload pictures from my mobile (its SD card) to an album that is created for my application the first time I upload a picture from it. In this case, when constructing the params object, I use the picture key and put the bytes of the picture as its value. I use me/photos in the request(...) call of the Facebook (or AsyncFacebookRunner) object. **
The problem
Not all uploaded images are displayed on my wall. Instead, there is something like x photos were added to the album xxx.
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("picture", bytes); //bytes contains photo bytes, no problem here
asyncRunner.request("me/photos", params, "POST", new PostPhotoRequestListener(), null);

Facebook result

Approach 2: Internet photos 2 facebook news feed
How
Display pictures stored somewhere on the Internet in posts on my wall. In this case, when constructing the params object, I use the link key and set the url to picture as its value. I use me/feed in the request(...) call.
The problem
This produces some strange output, but it isn't what I want.
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putString("link", "http://i1114.photobucket.com/albums/k538/tom_rada/bota2.jpg");
asyncRunner.request("me/feed", params, "POST", new PostPhotoRequestListener(), null);

Facebook result

Approach 3: Mix of approach 1 and 2
How
I try to use the picture key and set photo bytes as its value (as in 1.), and call the request with me/feed (as in 2.),
The problem
Message is produced as I would like it to be, but no photo is included
The code snippet is this (for one picture)
Bundle params = new Bundle();
params.putString("message", "Uploaded on " + now());
params.putByteArray("picture", bytes); //bytes contains photo bytes, no problem here
asyncRunner.request("me/feed", params, "POST", new PostPhotoRequestListener(), null);

Facebook result

So, any ideas how I could reach my goal?
EDIT - WORKAROUND FOUND
It seems that the only way to create new posts containing photos on user's wall is to add photos and related comments to user's Wall photos album.
How - Code snippet
Beware: The facebook.request call should be replaced with async call, so the operation doesn't block the UI thread !!!
String wallAlbumID = null;
String response = facebook.request("me/albums");
JSONObject json = Util.parseJson(response);
JSONArray albums = json.getJSONArray("data");
for (int i =0; i < albums.length(); i++) {
    JSONObject album = albums.getJSONObject(i);
    if (album.getString("type").equalsIgnoreCase("wall")) {
        wallAlbumID = album.getString("id");
        Log.d("JSON", wallAlbumID);
        break;
    }
}

... and then
if (wallAlbumID != null) {
    Bundle params = new Bundle();
    params.putString("message", "Uploaded on " + now());
    params.putByteArray("source", bytes);
    asyncRunner.request(wallAlbumID+"/photos", params, "POST", new PostPhotoRequestListener(), null);
}

A: Facebook facebook = new Facebook("your appid");

  private void uploadImage()
        {
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            final byte[] data = stream.toByteArray();

            facebook.authorize(FacebookActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener()
            {
                @Override
                public void onComplete(Bundle values)
                {
                   //uploadImageOnlyToWall(data, "Uploading Image only to wall","Test Post from Android while uploading photo with message");

                    uploadImageToWallAndAlbums(imageUrl, "Image via link");

                }

                @Override
                public void onFacebookError(FacebookError error)
                {
                    Toast.makeText(FacebookActivity.this, "FaceBook Error", Toast.LENGTH_LONG).show();
                }
                @Override
                public void onError(DialogError e)
                {
                    Toast.makeText(FacebookActivity.this, "Error", Toast.LENGTH_LONG).show();
                }
                @Override
                public void onCancel()
                {
                    Toast.makeText(FacebookActivity.this, "Canceled", Toast.LENGTH_LONG).show();
                }
            });

        }

       private void uploadImageOnlyToAlbum(byte[] byteArray,String caption)
           {
               Bundle params = new Bundle();
               params.putByteArray("picture", byteArray);
               params.putString("caption",caption);
               AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
               mAsyncRunner.request("me/photos", params, "POST", new SampleUploadListener(), null);
            }

           private void uploadImageToWallAndAlbums(byte[] byteArray,String caption)
           {
               Bundle params = new Bundle();
               params.putString("method", "photos.upload");
               params.putByteArray("picture", byteArray);
               params.putString("caption", caption);
               AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
               mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
            }

A: If the user has not previously posted a photo on his/her wall (there is no wall photo album), you can use me/photo request to post a photo first. This will automatically create a wall album.

A:       Facebook facebook = new Facebook("your App_id");

        private void uploadImage()

   {

 Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
        final byte[] data = stream.toByteArray();

        facebook.authorize(FacebookActivity.this, new String[]{ "user_photos,publish_checkins,publish_actions,publish_stream"},new DialogListener()
        {
            @Override
            public void onComplete(Bundle values)
            {
               //uploadImageOnlyToWall(data, "Uploading Image only to wall","Test Post from Android while uploading photo with message");

                uploadImageToWallAndAlbums(imageUrl, "Image via link");

            }

            @Override
            public void onFacebookError(FacebookError error)
            {
                Toast.makeText(FacebookActivity.this, " Error", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onError(DialogError e)
            {
                Toast.makeText(FacebookActivity.this, "Error", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onCancel()
            {
                Toast.makeText(FacebookActivity.this, "Canceled", Toast.LENGTH_LONG).show();
            }
        });

    }

   private void uploadImageOnlyToAlbum(byte[] byteArray,String caption)
       {
           Bundle params = new Bundle();
           params.putByteArray("picture", byteArray);
           params.putString("caption",caption);
           AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
           mAsyncRunner.request("me/photos", params, "POST", new SampleUploadListener(), null);
        }

       private void uploadImageToWallAndAlbums(byte[] byteArray,String caption)
       {
           Bundle params = new Bundle();
           params.putString("method", "photos.upload");
           params.putByteArray("picture", byteArray);
           params.putString("caption", caption);
           AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(facebook);
           mAsyncRunner.request(null, params, "POST", new SampleUploadListener(), null);
        }

A: Add this class on your code
public class SampleUploadListener implements RequestListener{

    @Override
    public void onMalformedURLException(MalformedURLException e, Object state) {
        Log.d(TAG, "******************* FACEBOOK::onMalformedURLException *******************");
    }

    @Override
    public void onIOException(IOException e, Object state) {
        Log.d(TAG, "******************* FACEBOOK::onIOException *******************");
    }

    @Override
    public void onFileNotFoundException(FileNotFoundException e, Object state) {
        Log.d(TAG, "******************* FACEBOOK::onFileNotFoundException *******************");
    }

    @Override
    public void onFacebookError(FacebookError e, Object state) {
        Log.d(TAG, "******************* FACEBOOK::onFacebookError *******************");
    }

    @Override
    public void onComplete(String response, Object state) {
        Log.d(TAG, "******************* FACEBOOK::onComplete *******************");
    }

}


text:
Q: Cordova Change Page | cannot redefine property: org ripple.js:38 When I change the page, I got this error on developer tools.
Error: cannot redefine property: org ripple.js:38
How can I fix it?

A: Cordova applications should adopt the SPA (Single Page Application) design. I think multi page uses is not appropriate for Cordova Application.
We should adhere to the Single Page Application principle.


text:
Q: Selenium find by id doesn't work extranje access to the input I am doing screen scraping with selenium. there i have a problem,
I'm trying to access to an HTML input (by id), but c# told me that is not visible, but I can see it.
this is the c# exception:
Element is not currently visible and so may not be interacted with
but viewing this I tried to do with selenium extension of Firefox, and the command to access is strange.

how can I access to this input from my c# code?
thanks.
edit1: this is the HTML:
<input type="text" value="" name="pxfirstname1" id="pxfirstname1" style="background-color: rgb(255, 255, 255);">

Also i checked on the CSS and doesn't have any hidden option.
Edit2: I tried to export to C#, but this is the result:
this is the code:
//code
driver.FindElement(By.Id("conSelC12")).Click();
driver.FindElement(By.Id("submitInfo")).Click();
// ERROR: Caught exception [Error: Dom locators are not implemented yet!]
// ERROR: Caught exception [Error: Dom locators are not implemented yet!]
driver.FindElement(By.Id("searchInf")).Click();
//more code

// ERROR: Caught exception [Error: Dom locators are not implemented yet!]
the other commands works fine

A: You should be able to export the code to C# from the plugin and then you can compare their suggested C# against your existing C# and see the problem or at least have working C# code


text:
Q: Specifying a violation handler for contracts Support for contract based programming in C++
 was adopted ino the C++20 working draft in Rapperswil. One part of this language feature is this notion of a violation handler which will be invoked when a contract is violated.
Herb Sutter's trip report states that:

You get to install your own violation handler and ship a release build with the option of turning on enforcement at run time.

But the wording in [dcl.attr.contract] that this paper added says:

The violation handler of a program is a function of type "noexceptopt
   function of (lvalue reference to const std::contract_violation) returning void", and is specified in an implementation-defined manner. [...] There should be no programmatic way of setting or modifying the violation handler. It is implementation-defined how the violation handler is established for a program and how the std::contract_violation ([support.contract.cviol]) argument value is set, except as specified below.

This is very unclear to me. How might an implementation allow me to set my own violation handler, in a non-programmatic way? What will I have to do on gcc, clang, and msvc?

A:
How might an implementation allow me to set my own violation handler, in a non-programmatic way?

That's for implementations to determine, but I rather suspect it would be a command line parameter of some sort. You'd name a function, and the compiler/linker would make that the violation handler. And if not that, then they would probably pick some specific function name that you implement.
The point here is that the function being used is static, from the perspective of the C++ abstract model. When the compiler starts, it knows exactly which function will be called, much like the call by the system to main, as well as the part of the program that handles main's return values.


text:
Q: Count Button's Color in C# I have a problem in my program. I have 3 buttons and the default color is white. When my button back color is changed into red, so my program will count how many buttons are red. I have an idea to use foreach but it doesn't work
Button[] Tombol = new Button[]{B1, B2, B3}
int counterbutton = 0;

foreach (Button Tombol2.BackColor = Color.Red in Tombol) //I have problem here. I don't know how to solve
{
  counterbutton++;
}

A: I think the right syntax is;
foreach(Button btn in Tombol)
{
    if(btn.BackColor == Color.Red)
       counterbutton++;
}

A: foreach(Button b in Tombol)
{
    if(b.BackColor == Color.Red)
        counterbutton++;
}

A: An exemple with linq :
var counter = Tombol.Count(b=>b.BackColor == Color.Red)

A: Button[] Tombol = new Button[]{B1, B2, B3}
int counterbutton = 0;
foreach (Button btn in Tombol) //I have problem here. I don't know how to solve
{
  if(btn.BackColor == Color.Red)
  counterbutton++;
}

A: Try this
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Button[] Tombol = new Button[]{B1, B2, B3};
            int counterbutton = 0;
            B1.BackColor = Color.Red;
            B3.BackColor = Color.Red;

            foreach (Button b in Tombol)
            {
                if(b.BackColor == Color.Red) //I have problem here. I don't know how to solve
                {
                    counterbutton++;
                }
            }
        }
    }
}


text:
Q: Data structure(s) useful for finding values that can be identified with multiple keys of different types As an example, consider the storage of hospital records. If John Smith is feeling sick, the doctor might need to look up his record by name to find his medical history. However, the doctor might also need to lookup all patients who experienced the symptoms John experienced to help the diagnosis. In another case, he may need a list of all patients admitted to the hospital at a certain time. What data structure(s) would be used to store patient records and search for them based on name, symptom, date of admission, and possibly other identifiers?

A: I'll throw this out there: this reads like the use-case for a relational database. Perhaps storing the data in a database and accessing it with queries is a good, long-term solution? If you're interested in the theory/algorithms, you can study how databases solve these problems. Things like indexes, query optimization, etc. are quite deep and probably can't be meaningfully covered here.


text:
Q: dynamically spanning a div over a grid array I want to build a dynamic website that displays a kind of link list. The information for my links I have stored in a json-file that looks like that:
{
"name" : "Example 1",
"color" : "#9c88ff",
"serversystems": [
  {
    "name" : "example 1",
    "info" : "example text",
    "logo" : "logo.png",
    "instances" : [
      {
        "name" : "subexample 1",
        "link" : "#",
        "info" : "example text"
      },
      {
        "name" : "subexample 2",
        "link" : "#",
        "info" : "example text"
      },
      {
        "name" : "subexample 3",
        "link" : "#",
        "info" : "example text"
      },
      {
        "name" : "subexample 4",
        "link" : "#",
        "info" : "example text"
      }
    ]
  },
  {
    "name" : "example 2",
    "info" : "example text",
    "instances" : [
      {
        "name" : "subexample 1",
        "link" : "#",
        "info" : "example text"
      }
    ]
  },
  {
    "name" : "example 3",
    "info" : "example text",
    "logo" : "logo.png",
    "instances" : [
      {
        "name" : "subexample 1",
        "link" : "#",
        "info" : "example text"
      }
    ]
  }
]}

One servertype can consist of a couple of serversystems, which in turn can consist of a couple of serverinstances.
My JavaScript gets all the data from the json-file, creates html-elements and appends them to the wrapper div.
To position these blocks on the website, my wrapper div spans a css grid:
#wrapper {
  grid-column: 2;
  grid-row: 2;

  display: grid;
  grid-gap: 3px;
  grid-template-columns: repeat(auto-fill, 100px);
  grid-auto-rows: 100px;
  grid-auto-flow: dense;
}

The idea is to have it look roughly like this:
what one servertype "block" should look like
The thing I just can't seem to figure out: as the number of systems and instances varies, the size of these blocks on my website varies as well. How can I use JavaScript to get the height of the final html-block (after appending all it's contents) so that I can make it span a certain amount of columns and rows on the grid?


text:
Q: How to turn a pandas pivot_table into a simple table I have a simple DataFrame defined by:
df = pd.DataFrame({
    'year': [2019, 2020, 2019, 2020, 2019, 2020, 2019, 2020],
    'name': ['Alice', 'Alice', 'Alice', 'Alice', 'Bob', 'Bob', 'Bob', 'Bob'],
    'sales': [100, 200, 300, 400, 500, 600, 700, 800]
})

This DataFrame is easily turned into a pivot table using pivot_table :
table = pd.pivot_table(
    df,
    index=['name'],
    columns=['year'],
    aggfunc=np.sum)

Now I need to turn this DataFrame into a simple JSON array. Unfortunately, the to_json method doesn't return a simple array:
table.reset_index().to_json(orient="records")

[
    {
      "["name",""]":"Alice",
      "["sales",2019]":400,
      "["sales",2020]":600
    },
    {
     "["name",""]":"Bob",
     "["sales",2019]":1200,
     "["sales",2020]":1400}
]

How can I turn the table DataFrame into a simple (without multiindex) DataFrame?
[
    {
      "name":"Alice",
      "2019":400,
      "2020":600
    },
    {
     "name":"Bob",
     "2019":1200,
     "2020":1400
    }
]

A: you need to pass the values param to get rid of the multiindex , also get rid of the lists in the param inside pivot when passing a single column:
table = pd.pivot_table(
df,
index='name',
columns='year',
values='sales',
aggfunc=np.sum)

table.reset_index().to_json(orient="records")

'[{"name":"Alice","2019":400,"2020":600},{"name":"Bob","2019":1200,"2020":1400}]'

Adding another alternative if you like:
out = (df.groupby(['name','year'])['sales'].sum().unstack()
                  .reset_index().to_json(orient='records'))

'[{"name":"Alice","2019":400,"2020":600},{"name":"Bob","2019":1200,"2020":1400}]'


text:
Q: Sharepoint - change way of displaying a field on a list I have a sharepoint list that contains a multiple lookup field. I would like to change the way its values are displayed (normaly you get links to chosen items like item1;item2;item3), so that I could for instance construct my own link to redirect me to the source list filtered by items chosen on this lookup.
I try to do that by creating a custom field by that is inheriting SPFieldLookup, but i'm a bit stuck since I can't don't know which method/property to override to change what is being displayed (if this is possible at all). Any help would be appreciated

A: I'd create a custom field type that inherits from SPFieldLookup. But instead of do the rendering server side I'd use a XSTL to render the field:
How to: Customize the Rendering of a Field on a List View
This way you do not have to implement a custom SPField class at all. You just have to create a custom field type definition that points to the OOTB SPLookupField.
<?xml version="1.0" encoding="utf-8" ?>
<FieldTypes>
    <FieldType>
        <Field Name="TypeName">CustomLookupField</Field>
        <Field Name="TypeDisplayName">Custom Lookup Field</Field>
        <Field Name="TypeShortDescription">Custom Lookup Field</Field>
        <Field Name="FieldTypeClass">Microsoft.SharePoint.SPFieldLookup</Field>
        <Field Name="ParentType">Lookup</Field>
    </FieldType>
</FieldTypes>


text:
Q: Django forms.py phone number charfield only accept number/integer, I did it but the validation error not working, go to def validate(self) my forms.py
from django import forms
from .models import Account

FRUIT_CHOICES= [
    ('Afghanistan', 'Afghanistan'),
    ('Albania', 'Albania'),
    ('Algeria', 'Algeria'),
    ('Andorra', 'Andorra'),
    ('Angola', 'Angola'),
    ('Antigua and Barbuda', 'Antigua and Barbuda'),
    ('Argentina', 'Argentina'),
    ('Armenia', 'Armenia'),
    ('Australia', 'Australia'),
    ('Austria', 'Austria'),
    ('Azerbaijan', 'Azerbaijan'),
    ('Bahamas', 'Bahamas'),
    ('Bahrain', 'Bahrain'),
    ('Bangladesh', 'Bangladesh'),
    ('Barbados', 'Barbados'),
    ('Malaysia', 'Malaysia'),
    ]

class RegistrationForm(forms.ModelForm):

    password=forms.CharField(widget=forms.PasswordInput())
    confirm_password=forms.CharField(widget=forms.PasswordInput())
    phone_number=forms.CharField(widget=forms.TextInput(attrs={
        'placeholder':'Enter Phone Number'
    }))
    country=forms.CharField(widget=forms.Select(choices=FRUIT_CHOICES))
    email=forms.EmailField(help_text="We'll never share your email with anyone else")
    class Meta:
        model=Account
        fields=['first_name','last_name','email','phone_number','password']

    def __init__(self,*args,**kwargs):
        super().__init__(*args,**kwargs)

        self.fields['first_name'].widget.attrs['placeholder']='Enter First Name'
        self.fields['last_name'].widget.attrs['placeholder']='Enter last Name'
        self.fields['email'].widget.attrs['placeholder']='Enter Email'
        self.fields['password'].widget.attrs['placeholder']='Enter Password'
        self.fields['confirm_password'].widget.attrs['placeholder']='Repeat Password'
        for abc in self.fields:
            self.fields[abc].widget.attrs['class']='form-control'

    def clean(self):
        cleanned_data=super().clean()
        password=cleanned_data.get('password')
        confirm_password=cleanned_data.get('confirm_password')
enter image description here
        if password != confirm_password:
            raise forms.ValidationError("Password and confirm password does not match")

    **def validate(self):
        cleanned_data=super().clean()
        phone_number=cleanned_data.get('phone_number')
        if phone_number.is_number() == False:
            raise forms.VallidationError("Please enter valid phone number, Example=012111111")**

okay, regarding this function
def validate(self): #this is working, the charfield only accept integer
        cleanned_data=super().clean()
        phone_number=cleanned_data.get('phone_number')
        if phone_number.is_number() == False:
            raise forms.VallidationError("Please enter valid phone number, Example=012111111")

Supposedly I shall get the error when the phone number contain alphabet "Please enter valid phone number, Example=012111111" , right?
But the output came out
phone_number
"gbfhbgf" value must be an integer.
May I know any solution to edit this error?
enter image description here


text:
Q: Drop One Row, when there are duplicates Lets say I have a dataframe;
signers <- data.frame(
        id = c(11,11,12,13,14,15,16,17,17,18,19,20,20,21) ,
        first =
            c("Benjamin","Ben","Robert","George","Thomas","Jared","James","John","James","George","George","James","Edmund","George") ,
        last =
            c( "Franklin","F","Morris","Clymer","Fitzsimons","Ingersoll","Wilson","Blair","Madison","Washington","Mason","McClurg","E","Wythe")
        )

which looks like this...
id    first       last
1  11 Benjamin   Franklin
2  11      Ben          F
3  12   Robert     Morris
4  13   George     Clymer
5  14   Thomas Fitzsimons
6  15    Jared  Ingersoll
7  16    James     Wilson
8  17     John      Blair
9  17    James    Madison
10 18   George Washington
11 19   George      Mason
12 20    James    McClurg
13 20   Edmund          E
14 21   George      Wythe

I would like to drop the second, third, fourth, etc  occurrence of every duplicate id number.  So in this case I would like a data frame without rows 2 , 9 and 13.

A: Just use duplicated:
signers[!duplicated(signers$id), ]
#    id    first       last
# 1  11 Benjamin   Franklin
# 3  12   Robert     Morris
# 4  13   George     Clymer
# 5  14   Thomas Fitzsimons
# 6  15    Jared  Ingersoll
# 7  16    James     Wilson
# 8  17     John      Blair
# 10 18   George Washington
# 11 19   George      Mason
# 12 20    James    McClurg
# 14 21   George      Wythe


text:
Q: Is there a way to start reading an ESDS file from 10th record in an IBM Mainframe batch program? Given:
The ESDS file has record length of 80.
It has 200 records.
I have checked the following links, however didn't get a satisfactory answer.
IBM Mainframe Forum
Geekinterview

A: That is an odd requirement, but if you want to process away nine standard headers or something, the easiest way is to do nine reads when you open the dataset.  E.G.
Open My-ESDS
Perform Read-My-ESDS 9 times
Perfomr Do-Normal-Stuff

There are other options available -- you could read the file as "unformatted", which makes you deal with everything about the format.  I do not recommend this unless you really need some very specific file handling.
If you don't need the first nine records, you could sort/drop them before kicking off your program, that is easy and easily maintained.
Can you give any idea why you want to skip the first nine and start at the tenth?  It might make a difference...


text:
Q: Sorted insert function for linked list I need to insert a node into a sorted link list, but I'm getting errors. Can someone help with what's wrong?
struct NodeType
{
ItemType value;
NodeType * next;
}

void sortedInsert( NodeType * & head, int data )
{
    NodeType * p = head;
    NodeType * prev = NULL;
    while (p->value < data)
    {
        prev = p;
        p= p -> next;
    }
    NodeType * newnode = new NodeType;
    newnode -> value = data;
    newnode -> next = prev;
    p -> next = newnode ;

I changed the program below but I'm getting an Thread 1: EXC_BAD_ACCESS (code=1, address=0x8) error on the line prev -> next = newnode, how can I change that line?
void sortedInsert( NodeType * & head, int data ){

NodeType * p = head;
NodeType * prev = NULL;
while (p->value < data)
    {
        prev = p;
        p= p -> next;
    }
NodeType * newnode = new NodeType;
    newnode -> value = data;
    newnode -> next = p;
    prev -> next = newnode;
if(head== nullptr)
{
    NodeType * newnode = new NodeType;
    newnode -> value = data;
    newnode -> next = head;
    return;
}
}

A: A possible solution:
What's going on is tricky, so I explain it line by line as it happens.
void sortedInsert( NodeType * & head, int data )
{
    NodeType ** p = &head; // You don't really want to find a node, you want to
                           // find where the new node goes, so rather than
                           // tracking nodes, track their next pointers. Once
                           // you find it, you know exactly where to put the
                           // new node

                           // head exists to tell you where the first node is.
                           // That makes it a glorified next pointer. We can
                           // hide the different name by adding an extra level
                           // of indirection. Now head and any next all look the
                           // same and no special cases are needed to manage
                           // insertion at the head

    while (*p &&  // make sure there is a node. Don't want to peek into a node
                  // that doesn't exist. This also finds the end of the list
                  // for us
           (*p)->value < data) // the current node goes before the new node
                               // don't want to insert here, so keep looking
    {
        p= &(*p) -> next; // advance p to point at the current node's next
    }

    // now we've found where the new node has to go - the end of the list or
    // the insertion point before the first larger node
    NodeType * newnode = new NodeType;
    newnode -> value = data; // set the data
    newnode -> next = *p; // point at the current node's next
    *p = newnode ; // insert new node at insertion point found earlier

    // note: the preceding four lines probably could be
    // *p = new NodeType{data, *p};
}

And once more without all the commentary and fluff
void sortedInsert( NodeType * & head, int data )
{
    NodeType ** p = &head;
    while (*p &&  (*p)->value < data)
    {
        p= &(*p) -> next;
    }
    *p = new NodeType{data, *p};
}

A: You are redefining pointers in these lines:
prev = p;
p = p -> next;

You are defining prev as p, then you are changing p, because you are using pointers, you are also redifining prev.
You can avoid doing this by doing something like this
while(p->next -> value < data){
p = p->next;
} //Whats this is doing is analizing the next value, so there's no need to use a prev
because your p is prev.

Once you have reached the point where it stops, you are going to have something like this:
eg:
Say I have data = 12, when the process stops, my p is going to be in this position in this example array.
5 7 9 10  11 14
---------[P]--

Now I must do (pseudo code)
auto aux = p.next;

node mynode(data);

mynode.next = aux;

p.next = mynode;

Hope this is useful :)


text:
Q: Maximum code words i am new to coding theory. i am trying to understand some of the basics by solving a few questions. I came across this one. Assuming $\\C$ is a binary (not necessarily linear) code of length $\\n$ and minimum hamming distance $\\d$. Atmost how many codewords can $\\C$ have? Give an example to the extremal case. I am stuck at the example part. i think using the fact that
$\left|C\right|\times \sum _{r=0}^e^nC_r\le 2^n$ - am i right?
I dont know what to do about the example part.

A: The sphere packing bound says that the number of codewords in a code with length $n$ and distance d over an alphabet of size $q$ is at most $\frac{q^n}{\sum_{k=0}^{\lfloor \frac{d-1}{2} \rfloor} \binom{n}{k} (q-1)^k}$.
Codes which attain equality are said to be perfect. Examples of perfect codes which are non-trivial are hamming and golay codes (in fact, the Hamming code, Binary Golay and Ternary Golay are the only parameters you can get for non-trivial perfect codes over a finite field).


text:
Q: AngularJS why I'm getting this Error: $rootScope:infdig Infinite $digest Loop and How to Fix it I'm writing a directive in D3 and Angular. I'm not sure why I keep getting the Infinite $digest loop error as I don't see any reassignments for newValue. Functionality works just fine but the annoying errors in browser makes me want to dig into it.
Here is the code of directive:
scope.$watch('mode', function (newValue, oldValue) {
    if (newValue !== oldValue) {
        scope.triggerAnimation();
    }
});

scope.triggerAnimation = function() {
    var speed = 4;
    var start = Date.now();

    if (scope.mode === null) {
        d3.timer(function() {
            var angle = (Date.now() - start) * speed;
            var transform = function(d, i) { return "rotate(" + angle / 50 + "," + centerX + "," + centerY + ")"; };

            svg.selectAll(".sidenode, .sidenodeedge").attr("transform", transform);
            if (scope.mode == null) {
                return true;
            } else {
                return false;
            }
        });
        scope.mode = 1;
    } else {
        scope.mode = null;
    }
}

A: In your code you have a the following:
scope.$watch('mode', function (newValue, oldValue) {
    if (newValue !== oldValue) {
        scope.triggerAnimation();
    }
});

and then you you run the function, which always will change the scope.mode value
scope.triggerAnimation = function() {
    ...
    if (scope.mode === null) {
        // some code here
        scope.mode = 1;
    } else {
        scope.mode = null;
    }
}

It looks like it always will change scope.mode value from null to 1. And each time will rise $digest call. And again...and again...


text:
Q: vagrant symlink protocol error inside synced folder using relative path I am trying to create a vanilla ubuntu/trusty64 guest box with symbolic links using a relative path on an ubuntu host.
> mkdir -p tmp1/tmp2
> mkdir -p tmp1/tmp3
> vagrant init ubuntu/trusty64

Inside the newly created Vagrantfile add the folder syncing:
...
config.vm.box = "ubuntu/trusty64"
config.vm.synced_folder File.expand_path("~/tmp1"),
                                         "/home/vagrant/tmp1",
                                         :create => true
...

Then bring up the box and ssh to it:
> vagrant up
> vagrant ssh

Then, cd to the tmp2 directory and try to create a symlink to tmp3:
> cd tmp1/tmp2
> ln -s ../tmp3 test
ln: failed to create symbolic link 'test': Protocol error

Version info:
> vagrant version
Vagrant 1.7.4
> vboxmanage --version
5.0.4r102546

Has anyone seen this before?

A: Had same issue with the homestead environment on Windows 10. In the end it worked by starting the terminal with admin credentials (Run as administrator).

A: This is a known issue in Virtualbox 5.0.4 . See bug report
Just to note, this doesn't only affect Mac OSX hosts as the ticket reports. I ran into the same issue with Arch linux as a host. Either revert Virtualbox to version 5.0.2, which seems to work, or wait for the release of Virtualbox 5.0.5, which supposedly fixes the issue.

A: virtual box 5.2.6
vagrant 2.0.1
windows 10
same problem (ln: failed to create symbolic link ... Protocol error )
when I ran "composer install" to install drafter-install
(if your homestead is running, vagrant halt firstly)
my solution is execute cmd as "administrator privilege"

*

*vagrant up

*vagrant ssh

*cd to my project's dir

*composer install

that's all, and work well for me


text:
Q: Executing unit test method from a separate windows form I called unit test methods on a windows form. On a list box, all unit test methods get displayed.
I wanted to execute all unit test methods displayed on this form in one go.
Any pointer would be helpful.

A: I tried and i think i got the solution.
I wanted to call all unit tests from another project to a UI (separate Project)
Code:
public class UnitTest1
{
    [TestMethod]
    public static void TestMethod1()
    {
        SerializingLearn.Articles s = new SerializingLearn.Articles();
        s.sTitle = "a";
        s.sText = "b";
        s.sAuthor = "c";
        s.serialize(@"c:\124.txt");
    }
    [TestMethod]
    public static void TestMethod2()
    {
        SerializingLearn.Articles s = new SerializingLearn.Articles();
        s.sTitle = "a1";
        s.sText = "b1";
        s.sAuthor = "c1";
        s.serialize(@"c:\154.txt");
    }
}

If test methods were made static it can be easily called from another project/UI
I can execute these unit tests from that UI, on click of a button.


text:
Q: How to get the second smallest eigenvalue of laplacian matrix of a complex network with python? I'm trying to compute the second smallest eigenvalue of the laplacian matrix of a complex network(with 10000 nodes) with python using the shift-invert mode, here is the code:
import numpy as np
import networkx as nx
from scipy import sparse
G = nx.watts_strogatz_graph(10000,4,0.1)
degree_dict = nx.degree(G)
degree_list = []
for i in degree_dict:
    degree_list.append(degree_dict[i])
lap_matrix = sparse.diags(degree_list, 0)-nx.adjacency_matrix(G)
eigval, eigvec = sparse.linalg.eigsh(lap_matrix, 2, sigma=0, which='LM')
second_eigval = eigval[1]

when running above code, i got:
RuntimeError: Factor is exactly singular

Does the error mean the laplacian matrix is singular?
Any ideas as to how I should proceed?
Is there any other way to compute this second smallest eigenvalue(with Matlab or any other programming language)?

A: Your code works for me (SciPy 1.0.0) almost exactly as written, except I simplified the formation of degree_list (which threw a KeyError in your version)
import numpy as np
import networkx as nx
from scipy import sparse

G = nx.watts_strogatz_graph(10000,4,0.1)
degree_dict = nx.degree(G)
degree_list = [x[1] for x in degree_dict]
lap_matrix = sparse.diags(degree_list, 0)-nx.adjacency_matrix(G)
eigval, eigvec = sparse.linalg.eigsh(lap_matrix, 2, sigma=0, which='LM')

Now eigval is [1.48814294e-16, 4.88863211e-02]; the smallest eigenvalue is  zero within machine precision but the second smallest is not.


text:
Q: How can I combine JS files into one without errors Below is a list of JS files I am running on my site. I want to combine them all in to one minified file. When I do so the page brings up common jquery errors. But all I have done is minified them and put them in the same file (in the same order).
When I keep them individually entered then there is no errors
jquery-1.8.3.min.js
modernizr-2.6.2-respond-1.1.0.min.js
bootstrap.js
script.js (custom js)
jquery.validate.js
bootstrap.notify.js
jquery.hoverintent.min.js
jquery.cookie.js
jquery.superfish.min.js
jquery.cycle2.min.js
respond.min.js
jquery.magnific-popup.min.js
html5shiv-printshiv.min.js

A: What you're looking for is a build manager. You can use something like Bower or Grunt. If you want to roll your own build manager, this blog post might be helpful.

A:
Like Bobby told you, you can use Grunt to work with some useful tools that allow you minify all your files.
Concretly, the plugin that could help you is contrib-uglify, made by the Grunt Team. If you want to use Grunt (and its tools), you can read the Getting Started to install Grunt, and the, follow the instructions to install contrib-uglify. Then, if you want to know how work uglify, you have everything that you need in the Github repository.
Grunt is very simple and interesting. I began to use it recently and I can say that it's very useful.
I hope that I have help you!


text:
Q: How to debug ssh connection to remote user (when connection to root works fine) I have an Xubuntu "Caller" and Fedora "Callee" in my garage.  I'm setting them up to connect via SSH.  Both are running OpenSSH, so the configurations are similar.
I can connect as the root account on both systems, but I am unable to connect to the sole user account on the Callee from the Caller's root or user accounts.
I have verified that the authorized-keys record for the Caller's root account is identical in both root and user on the Callee, so I would expect root to be able to connect to the user. There is a minimal log of the failure in Callee's /var/log/security file, and a somewhat verbose record in /var/log/messages, but neither one gives any details I know how to use. They both basically say it failed, and the messages include UID and PID info.  It just seems the cryptology broke.
How can I find out more? Where should I look? What should I check?
ADDITIONAL INFO:
the error message is

kevin@Callee: Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

The failure occurs when calling the user, but not when calling the root, if exactly the same contents are in the authorized-keys of both accounts on the Callee.
In the user account,
drwx------. 2 kevin kevin 4096 Jan 17 06:34 .ssh

and
-rw-------. 1 kevin kevin  96 Jan 17 06:34 authorized-keys

When I try the -v switch on ssh, with the root Caller trying to contact first root then the user on the Callee, the root call succeeds but the user call fails.  The -v outputs are identical except for the name of the target down to and including the line
debug1: Offering public key: /root/.ssh/id_ed25519 ED25519 SHA256:6QuMnJvYJWqqoQ0ASVbUJvgWdR5Grzb2r8IxiYUmNho

but when connecting to root the next line says "Server accepts key" whereas  at the same spot the user says
debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic

and continues with vain attempts for just a few lines.  Trying the same with ssh -vvv does not give any additional useful information.
So the Callee as user does not like the same key that it liked as root, despite the authorized-keys files being identical.  What gives?

A: -rw-------. 1 kevin kevin  96 Jan 17 06:34 authorized-keys

This file should normally be called authorized_keys with an underscore instead of a dash. Sshd looks for the underscore form by default.


text:
Q: Virtual Assistant Skill - how to kill/end the current skills bot you are in I was trying to implement an msbot skill that handles the directory services, such as the contact number and email of a person. My issue is I cannot get out of the skills bot. I have tried everything but nothing works.
I am trying to do the following on the skills bot to end or kill it, and return the dialog state to the parent:

*

*EndDialogAsync()

*CancelAllDialogsAsync()

*EndComponentAsync()

but unfortunately I am not able to return to the parent bot, instead it keeps comming back to the skills bot, and its not what I wanted. I maybe doing it wrong, I am not sure how to end the skills bot state and return to the parent bot, as the main functions are there.

A: You need to send an EndOfConversation Activity. See how our skills sample does it:
protected override async Task OnMessageActivityAsync(ITurnContext<IMessageActivity> turnContext, CancellationToken cancellationToken)
{
    if (turnContext.Activity.Text.Contains("end") || turnContext.Activity.Text.Contains("stop"))
    {
        // Send End of conversation at the end.
        await turnContext.SendActivityAsync(MessageFactory.Text($"ending conversation from the skill..."), cancellationToken);
        var endOfConversation = Activity.CreateEndOfConversationActivity();
        endOfConversation.Code = EndOfConversationCodes.CompletedSuccessfully;
        await turnContext.SendActivityAsync(endOfConversation, cancellationToken);
    }
[...]


text:
Q: Does argument parser in python has options like -continue or -single Do we have any options in argument parser for continuing the execution from that respective position till the end of the code, on providing a command-line argument?
I have a script. When I execute with script.py -f_2 it does execute only function_2. But I want to execute all the subsequent functions function_3 & function_4 as well till the end. How can I achieve this?
This script also read's and writes content from a file called sample_update.in using config parser.
import sys
import os
import math
import alert
import ConfigParser
import argparse
from alert import alert_user

configParser = ConfigParser.ConfigParser()
configParser.add_section('Input')
configParser.add_section('Output')
configParser.read('sample_updated.ini')

def function_1(a, b):
    c = a + b
    # write to ini file
    print "input_1 of function_1: ", a
    print "input_2 of function_1: ", b
    print "output of function_1: ", c
    configParser.set('Input', 'function_1_1', str(a))
    configParser.set('Input', 'function_1_2', str(b))
    configParser.set('Output', 'function_1', str(c))
    return c

def function_2(c, b):
    d = c * b
    # write to ini file
    print "input_1 of function_2: ", c
    print "input_2 of function_2: ", b
    print "output of function_2: ", d

    configParser.set('Output', 'function_2', str(d))
    return d

def function_3(d, c):
    e = d / c
    # write to ini file
    print "input_1 of function_3: ", d
    print "input_2 of function_3: ", c
    print "output of function_3: ", e

    configParser.set('Output', 'function_3', str(e))
    return e

def function_4(d, e):
    f = d - e
    # write to ini file
    print "input_1 of function_4: ", d
    print "input_2 of function_4: ", e
    print "output of function_4: ", f

    configParser.set('Output', 'function_4', str(f))
    return f

if __name__ == '__main__':

    a = input("value of a: ")

    b = input("value of b: ")

    parser = argparse.ArgumentParser()

    # create argument parser

    parser.add_argument('-f_2', action='store_true', default=None, dest='function_2', help="execute from function_2")

    parser.add_argument('-f_3', action='store_true', default=None, dest='function_3', help="execution starts from function_3")

    parser.add_argument('-f_4', action='store_true', default=None, dest='function_4', help="execution starts from function_4")

    cmd_arguments = parser.parse_args()

    # print selected functions

    if cmd_arguments.function_2:
        function_2(configParser.getint('Output', 'function_1'), b)

    if cmd_arguments.function_3:
        function_3(configParser.getint('Output', 'function_2'),

    if cmd_arguments.function_4:
        function_4(configParser.getint('Output', 'function_2'), configParser.getint('Output', 'function_3'))

    if not len(sys.argv) > 1:
        # store function outputs
        function_1(a, b)
        function_2(configParser.getint('Output', 'function_1'), b)
        function_3(configParser.getint('Output', 'function_2'), configParser.getint('Output', 'function_1'))
        function_4(configParser.getint('Output', 'function_2'), configParser.getint('Output', 'function_3'))

    with open('sample_updated.ini', 'w') as configfile:
        configParser.write(configfile)

A: There is no explicit function in ConfigParser.  You need to code that yourself.  To keep going in your case you should try:
if cmd_arguments.function_2:
    function_2(configParser.getint('Output', 'function_1'), b)

if cmd_arguments.function_2 or cmd_arguments.function_3:
    function_3(configParser.getint('Output', 'function_2'),

if cmd_arguments.function_2 or cmd_arguments.function_3 or \
       cmd_arguments.function_4:
    function_4(configParser.getint('Output', 'function_2'),


text:
Q: Wire.onReceive() function on Arduino I am trying to take what is in this example given by the Arduino Wire library, and apply it to a program I am writing.
This is my code. The Comm.NDP[] statements are other class instances not saved in this file, so I believe you can ignore them.
**
* I2C.cpp handles sending of event messages
*    between the LORA and MEGA via I2C protocol.
*/

#include "I2C.h"
#include "DATA.h"
#include "Globals.h"
#include <Wire.h>
#include <Arduino.h>

/**
 * Constructor used to reference all other variables & functions.
 */
I2C::I2C() {
}

/**
 * Assigns the proper address to the current micro controller.
 */
void I2C::initialize() {
  //Sets the address for the current micro controller.
  //   Mega - 0
  //   LoRa - 1
  Wire.begin(0);
  Wire.setClock(8000000);
  //Registers recieveEvent as a interrupt.
  Wire.onReceive(receiveEvent); // register event
}

/**
 * Receives byte over I2C Connection.
 */
static void receiveEvent(int howmany) {
  //Iterator used below.
  int i = 0;
  for(i=0;i<120;i++) {
    Comm.NDP[i] = ' ';
  }
  //Resets iterator.
  i = 0;
  //Checks to see if serial port is empty.
  while (1 < Wire.available()) {
    //Reads in single character from serial port.
    char character = Wire.read();
    NDP[i] = character;
    i++;
  }
  Serial.println(Comm.NDP);
}

The example code from Arduino's Wire.h library
#include <Wire.h>

void setup() {
  Wire.begin(8); // join i2c bus with address #8
  Wire.onReceive(receiveEvent); // register event
  Serial.begin(9600); // start serial for output
}

void loop() {
  delay(100);
}

// function that executes whenever data is received from master
// this function is registered as an event, see setup()
void receiveEvent(int howMany) {
  while (1 < Wire.available()) { // loop through all but the last
    char c = Wire.read(); // receive byte as a character
    Serial.print(c); // print the character
  }
  int x = Wire.read(); // receive byte as an integer
  Serial.println(x); // print the integer
}

I am getting this error from the Arduino IDE.

error: invalid use of non-static member function

Wire.onReceive(receiveEvent); // register event

                          ^

exit status 1
invalid use of non-static member function

A: You're missing declaration of receiveEvent before first use. Either move it's definition before begin or add there:
void receiveEvent(int howMany);


text:
Q: Auto login and access the Oracle ADF application from Oracle Apex I am using Oracle Apex 5.1. In that application I need to access Oracle ADF application from Oracle Apex. I used Iframe to view the ADF application from Apex. Since I logged in Oracle apex, I don't want to login it again in ADF application. So I tried to auto login while loading the page using AJAX post method. Browser doesn't allow the request due to cross domain access issues. If any possible way to auto login or where I am going wrong in the code, please help me. Thanks in advance.
Code used to login in Ajax:

$.ajax({
    url: 'https://xxxxxx.co.xx:7302/xxxx/faces/pages/login/login.jspx',
    data: {j_username: "xxxxx",j_password:"xxxxx"},
    type: 'POST',
    crossDomain: true,
    dataType: 'text/html',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    headers: {
              'Access-Control-Allow-Origin': '*'
             }

});

The Error:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://xxxxx.co.xx:7302/xxxx/faces/pages/login/login.jspx. (Reason: CORS header 'Access-Control-Allow-Origin' missing).

If any possible way to auto login, please help me. Thanks in advance.

A: You'll want to use single-sign-on to achieve this, and you'll need to configure the WebLogic server that runs the ADF part to do SSO with your APEX instance.
Here is a video about the ADF part - https://www.youtube.com/watch?v=G7X7quNT-58
On the APEX side: http://www.oracle.com/technetwork/developer-tools/apex/learnmore/apex-oam-integration-1375333.pdf


text:
Q: Multiple modal popup elements, can't set z-index I have two modals that can be opened on the page.
But they both have the same z-index, so I try to set a higher z-index for one of them:
<script type="text/javascript">
    require(['jquery',
        'Magento_Ui/js/modal/modal','mage/validation'],function($){
        myModal.modal({
            responsive: true,
            zIndex: 950,
            ...

But the zIndex: 950, doesn't work at all. I wonder maybe it is some deprecated or undocumented option because the off. docs don't mention it.
https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/widgets/widget_modal.html
Update:
I have found out that here
baseIndex = zIndex + this._getVisibleCount();

_getVisibleCount() returns 0 even though one modal is already open. That's my problem.

A: By default, there is no zIndex/z-index property available for modals. It will set higher z-index on the last created popup. So last created popup will be always on top with higher z-index.
But you can use modalClass property to set CSS class and set required z-index on that class.
var options = {
  ...
  modalClass: 'css_class_for_z_index'
  ...
};

OR if you want to set z-index dynamically, you can overwrite _setActive function in modal.js. Check this answer for more.


text:
Q: Computing the gradient of a two-layer neural network w.r.t. the data I want to verify that I am computing the following gradient correctly. I am looking at this conjecture, and the gradient is paramount. Using the definitions from the the paper, consider the data $\vec{x} = \{ x_1, x_2, ..., x_d \} \in \mathbb{R}^d$, 2 vectors $\vec{a} = \{ a_1, a_2, ..., a_k \} \in \mathbb{R}^k$, and $\vec{b} = \{ b_1, b_2, ..., b_k \} \in \mathbb{R}^k$ and a matrix which we represent as a vector of vectors $\vec{w_l} = \{ w_{l,1}, w_{l,2}, ..., w_{l,d}\} \in \mathbb{R}^d$ for $1 \le l \le k$. We also have a Lipschitz function $\varphi$. Define a function
$$f: x \mapsto \sum_{l=1}^k a_l \varphi( \langle \vec{w}_l, \vec{x} \rangle + b_l)$$
where$\langle \vec{w}_l, \vec{x} \rangle =\sum_{i=1}^d w_{l,i}x_i$. I want to properly write out the following gradient vector $\nabla f$ as a function of $x$.
$$\nabla f(x)=\begin{bmatrix} \frac{\partial}{\partial x_1} f\\
\frac{\partial}{\partial x_2} f \\
... \\
\frac{\partial}{\partial x_d} f
\end{bmatrix}$$
Now, for each $x_i$ I compute $\frac{\partial}{\partial x_i} f$:
$$\frac{\partial}{\partial x_i} f = \sum_{l=1}^k a_l \varphi'(\langle \vec{w}_l, \vec{x} \rangle + b_l)w_{l,i}$$
where $\varphi'$ is the derivative of $\varphi$. The conclusion here is that we see each element of $\nabla f$ is itself a sum of a function of all of the data. This is my main doubt. Do we in fact have the entire dot product $\langle \vec{w_l}, \vec{x} \rangle$ inside each element of the sum inside each element of the gradient $\nabla f$? Basically I would just like confirmation this computation is correct. Thanks.

A: Yes, the computation is correct.
Recall the chain-rule: if $h(t) = f(g(t))$ then $$h'(t) = f'(g(t))g'(t).$$ Note that where $f$ and $f'$ are evaluated does not change. Both are evaluated at $g(t)$.
That is what is going on in your calculation. Before differentiation $\phi$ is evaluated at $\langle \vec w_l, \vec x \rangle + \vec b_l$, and after differentiation $\phi'$ is still evaluated at the same point.


text:
Q: libgdx texture packer finding ,storing and using regions example I am using Texture packer libgdx texture packer
for my libgdx game . I have created pack file also . now I have one balloon_burst_pack.png and one
balloon_burst_pack.pack file.
only thing is from online documentation I cant figure out how exactly should i retrieve all 15 png images from pack file.
my image names are like balloon_color_0001.png, balloon_color_0002.png which I have packed in one balloon_packed.png
small code i have tried is :
 atlas = new TextureAtlas(Gdx.files.internal("Animations/balloon_color_pack/balloon_burst_pack.pack"));

   for (int i = 0; i< 15;i++ ) {

        region[i] = atlas.findRegion("balloon_colour"+"000"+i);
        System.out.println("region detected is"+region[i].getRegionX());
   }

anyone who have used same texture packer please give me reference to use packed file .
please explain me step by step if possible..
Thanks.

A: The problem with your png names is that texture packer trims all names after first '_'
so you must change the names of your png to something like ballooncolor_0001.png, ballooncolor_0002.png etc insted of  balloon_color_0001.png etc then use kumar saurabh's code to load all the file
or eith current setup you can use name as balloon instead of ballon_color

A: When you use Texture Packer tool and pack images its provides balloon_burst_pack.png file and its related packer file balloon_burst_pack.pack(for example) which contain x and y coordinate of all images in one balloon_burst_pack.png file according to their names.
For example you can find x and y coordinates and size of balloon_color_0001.png in balloon_burst_pack.pack. Once you find its co-ordinate and size you can get it by TextureRegion class.
Texture balloonBrust = new Texture(Gdx.files.internal("path of your balloon_burst_pack.png file"));
TextureRegion baloon1Region = new TextureRegion(balloonBrust ,x coordinate ,y coordinate, width, height);

now you can draw it using SpriteBatch class.


text:
Q: How can editors change the width of table cells in the RTE of TYPO3 7.6? How can editors resize table cells in the RTE manually? It's not possible to set the width of a cell by resizing the cell with the mouse or a numeric value in the cell properties. At least I haven't found a possibility to enable that.

A: have a look here:
https://docs.typo3.org/typo3cms/extensions/rtehtmlarea/7.6/Configuration/PageTsconfig/interfaceConfiguration/Index.html#rteresize
Greets,
David


text:
Q: StringFormat file size in datagrid column I want to display in a datagrid column size of a directory but I don't know how to format the string with "StringFormat" in XAML to display KB , MB or GB and keep the ability to sort by size .
Thanks

A: You can have an additional property in ItemsSource of the data grid. Populate that new property with the size of directory keeping unit a constant. So let say you have a directory with 100 KB and another with 1 MB. So convert 1 MB into equivalent KB and populate in the newly added property. Do not show this property on Datagrid just use it in sort member path. and keep the string property in View which would show 100 KB or 1 MB values. To better understand what I am trying to say, please refer this SO post
Let me know if things are not clear to you !!


text:
Q: $u^2$, $v^2$ and $w^2$ s.t. $|u|=|v|=|w|=1$ and $-uv-vw-uw=-i$? Let $A,B, C$ the vertices of a triangle in the complex plane. Why I can supposse that the afixes of $A, B, C$ can be $u^2$, $v^2$ and $w^2$ s.t. $|u|=|v|=|w|=1$ and $-uv-vw-uw=-i$?
I saw this ideea in a proof of an exercise and I can't understand why.

A: Depending on the problem, sometimes the lengths of the sides are not important, only the ratios. Then the first equation just lets you know that you can choose the origin of the complex plane to be in the circumcenter of the triangle. Then, in principle, you can choose $A=u=e^{i\phi_A}$ and similar to $B$ and $C$. The second equation is just a phase of the triangle. You can rotate the triangle by an angle $\phi$, so  $u'=ue^{i\phi}$ (similar for $v$ and $w$). Then the left side of your second equation is just multiplied by $e^{2i\phi}$.


text:
Q: Cannot connect to 5GHz band with b43 driver I am using Lubuntu 14.10 on my Macbook 3,1 and I switched to the b43 driver as suggested here. The problem I have with this driver is that I cannot detect and connect to the 5GHz band wifi networks.
Is there anything I could do to be able to connect to that frequency band again?

A: In kernel 3.17 and above there has been some success in getting 5GHZ to work with the b43 driver, so here are the directions for installing the 3.18 kernel, I can not promise that it might not cause some other kind of issues.
cd /tmp/

wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.18-vivid/linux-headers-3.18.0-031800-generic_3.18.0-031800.201412071935_amd64.deb

wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.18-vivid/linux-headers-3.18.0-031800_3.18.0-031800.201412071935_all.deb

wget http://kernel.ubuntu.com/~kernel-ppa/mainline/v3.18-vivid/linux-image-3.18.0-031800-generic_3.18.0-031800.201412071935_amd64.deb

sudo dpkg -i linux-headers-3.18.0-*.deb linux-image-3.18.0-*.deb
Reboot
Set the channel manually on the router and in network manager that you want to connect to, make sure it is within the range of your devices channels by looking at the occupancy section in the file you posted. Changing the channel from auto to fixed is your best option.
Also linux connects best to wpa2 AES CCMP Only not mixed mode or TKIP.
Do:
sudo rm /etc/udev/rules.d/70-persistent-net.rules

Reboot


text:
Q: How to stop and get exact result from For loop in C language How to get an exit from for loop because my code always gets the latest result from the for loop? What's wrong with my for loop condition? This is my code:
#include <stdio.h>
#include <string.h>

int main(){
    int i, n = 3, a;
    char x[20];
    struct data {
        char nim[10];
    };

    struct data batas[100];

    printf("TEST1 : "); scanf("%[^\n]s", batas[0].nim);
    printf("TEST2 : "); scanf(" %[^\n]s", batas[1].nim);
    printf("TEST3 : "); scanf(" %[^\n]s", batas[2].nim);

    char str[10];
    printf("TEST : "); scanf(" %[^\n]s", str);
    for(i=0; i<n; i++){
        if (strcmp(str, batas[i].nim) == 0) {
            puts("Value exist");
            strcpy(x, "FLAG");
        } else {
            puts("Value doesn't exist");
            strcpy(x, "FLAGXX");
        }
    }
    printf("%s\n", x);
    return 0;
}

Here, from the result of x always gets the FLAGXX result. I want to get the FLAG result here.

A: The best way to get the exact result is to not overwrite it with an inexact result. You want x to contain "FLAG" if one of the strings was matched; but unless it was the last loop iteration, x will be overwritten later when a non-match is encountered.
One typical algorithm would be to break the for loop when a match is found. (An explanation of break and the oppositionally related continuecan be found here, which happens to be the first google hit.)
I would also recommend to simply use a boolean flag which is false when the loop is entered and set to true when a match is found; there is no reason to copy strings around (and the same string!) during every iteration.


text:
Q: Copying specific data from multiple files & sheets I am currently in a middle of a problem to automate excel data crawling.
I receive a daily data pack with 10+ worksheets each day. So I am trying to make it easier to crawl 30 daily data pack and accumulate them in one sheet to make a monthly data sheet.
Currently, the code below works to bring data from a designated worksheet, yet, as I've mentioned, there are 8 more worksheets in each file. I'd like to automate data crawling from 8 more sheets with one click.
The challenge is that every worksheet has a different format, which means data to be crawled are not at equivalent cells (x,y) from each other.
The "Call" function after setting up multiple modules doesn't seem to be applicable as it creates file dialog box 8 more times. I am trying to figure out how I could deal with this.
Sub getData()

    Dim strSht As String
    Dim rngData As Range
    Dim strPath As String
    Dim filename As String
    Dim rngT As Range

    Application.ScreenUpdating = False

    strSht = "GN2"                                             'Data of saved sheets
    Set rngData = Range("Q7:BB31")                             ' Range where data is typed
    Set rngT = Range("B7:AM31")                                ' Range of data to be pasted

    With Application.FileDialog(msoFileDialogFolderPicker)
        .Show

        If .SelectedItems.Count = 0 Then
            Exit Sub
        Else
            strPath = .SelectedItems(1) & "\"
        End If
    End With

    filename = Dir(strPath & "*.xls*")

    If filename = "" Then
        MsgBox "No files on the folder."
        Exit Sub
    End If

    Do While filename <> ""

        With rngT
            .FormulaArray = "='" & strPath & "[" & filename & "]" _
                & strSht & "'!" & rngData.Address(1, 1, 1)
            .Value = .Value
        End With

        Set rngT = rngT.Offset(25)

        filename = Dir
    Loop

    Set rngData = Nothing

End Sub


text:
Q: Search device contact directory for contact details in react native I am working on a project and want to access the contact directory on my device to get a contact detail then return back to the react native app. I have tried npm I react-native-contacts and it works fine but it returns an array of the contact which means I have to design a view for it... but what I want is to access the device contact directory itself and select from the contact list then return the selected contact back to react native app. Please how can I achieve this?

A: After some research, this worked for me npm i react-native-select-contact . I could access the native contact directory and get a contact detail that was return to my react native app.


text:
Q: Magento - Custom admin router but with no menu item I want to create an admin controller - without having any menu items associated with it.
Ideally I want to have my controller accessible via /index.php/admin/my_controller/.
So far I have rewritten the adminhtml controller as follows but i simnply get a 404 inside the admin console (i.e. not the main 404 page):
    <admin>
    <routers>
        <my_module>
            <use>admin</use>
            <args>
                <module>Me_Mymodule</module>
                <frontName>my_controller</frontName>
            </args>
        </my_module>
         <adminhtml>
            <args>
                <modules>
                    <my_module after="Mage_Adminhtml">Me_Mymodule</my_module>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>

A: Your current config technique has been obsolete since version 1.4. Instead it is more convenient to structure it like this.
<admin>
    <routers>
        <adminhtml>
            <args>
                <modules>
                    <my_module before="Mage_Adminhtml">Me_Mymodule_Adminhtml</my_module>
                </modules>
            </args>
        </adminhtml>
    </routers>
</admin>

Then to get the /index.php/admin/mymodule/ path create the class Me_Mymodule_Adminhtml_MymoduleController extends Mage_Adminhtml_Controller_Action in Me/Mymodule/controllers/Adminhtml/MymoduleController.php. In your example you used an underscore in the controller name, be careful of that as it will be used as a directory separator when searching for the correct class.
Remember to generate URLs for your controller like Mage::getUrl('adminhtml/mymodule') so that it adds the secret key to paths, this is necessary when making an admin controller or it will refuse the page.
If there are no menu items then it will not be possible to add them to the ACL. You do not need an adminhtml.xml file in this case.

A: Even if you do not add your controller to menu, you still have to add acl section for your controller adminhtml.xml. Do not forget to relog to admin after that.

A: For you goal xml config is redundant.
Use following to add your controller to /admin frontname

                        Company_Module_Adminhtml

Now every controller that will be created in controller/Adminhtml folder will accessed through admin like
/admin/yourfilename/index

The class name of controller should be Module_Module_Adminhtml_YourfilenameController and should extend Mage_Adminhtml_Controller_Action
That's the trick.


text:
Q: Is there a link between two magic squares with the same constant? For instance we consider the magic squares of order $3$ with the constant $15$.
We can find :
\begin{array}{ | l | c | r | }
     \hline
     8 & 3 & 4 \\ \hline
     1 & 5 & 9 \\ \hline
     6 & 7 & 2 \\
     \hline
    \end{array}
and
\begin{array}{ | l | c | r | }
     \hline
     -2 & 8 & 9 \\ \hline
     16 & 5 & -6 \\ \hline
     1 & 2 & 12 \\
     \hline
    \end{array}
Do we have a tool to transform the first matrix into the second ? I mean that does the invariant (same constant) is sufficient to classify all the magic squares of a given constant under a group's action ?
I know that of it was the same numbers for the two matrices, there exists an action from the group $\mathcal{D}_4$ on the set of magic squares of order $3$.
Thanks in advance !

A: All magic squares of order 3 are based on the same structure. As you note in the question, actions from $\mathcal{D}_4$, the dihedral group of order 8, permute the numbers while preserving the row and column (and diagonal) sums, and hence preserve the magic property.
There are other things we can do which preserve the magic property. For example, we can add a constant to each cell value, or multiply each value by a constant. Thus we can apply any linear operation $x' = ax + b$ to each value.
To see what else preserves the magic property, we need to look at how magic squares can be produced.
Magic squares are closely related to Latin squares. "A Latin square is a $n\times n$ array filled with n different symbols, each occurring exactly once in each row and exactly once in each column". Eg,
$$\begin{array}{|r|r|r|}
\hline
A & B & C\\
\hline
C & A & B\\
\hline
B & C & A\\
\hline
\end{array}$$
We can create a magic square using a pair of
mutually orthogonal Latin squares, that is, two Latin squares of the same order that when superimposed produce distinct pairs of values in each cell. (An old name for this construction is the Graeco-Latin square, but as Wikipedia mentions, that name is rarely used these days, although you may encounter it in works on magic squares).
The order 3 magic square can be produced by combining
$$\begin{array}{|r|r|r|}
\hline
2 & 0 & 1\\
\hline
0 & 1 & 2\\
\hline
1 & 2 & 0\\
\hline
\end{array}$$
with
$$\begin{array}{|r|r|r|}
\hline
1 & 2 & 0\\
\hline
0 & 1 & 2\\
\hline
2 & 0 & 1\\
\hline
\end{array}$$
which is just the previous matrix reflected vertically. Note that this square is magic, with a constant sum of 3, although it's not a proper magic square because it has repeated values. When we combine the two squares we get
$$\begin{array}{|r|r|r|}
\hline
21 & 02 & 10\\
\hline
00 & 11 & 22\\
\hline
12 & 20 & 01\\
\hline
\end{array}$$
The 1st digit in each cell comes from the corresponding position in the 1st Latin square, the 2nd digit comes from the 2nd Latin square. Notice that all of these ordered pairs are distinct.
Now, we treat each of those values as a number written in base 3. This gives us
$$\begin{array}{|r|r|r|}
\hline
7 & 2 & 3\\
\hline
0 & 4 & 8\\
\hline
5 & 6 & 1\\
\hline
\end{array}$$
which is a valid magic square because there are no repeated values. If we add 1 to each cell, we get
$$\begin{array}{|r|r|r|}
\hline
8 & 3 & 4\\
\hline
1 & 5 & 9\\
\hline
6 & 7 & 2\\
\hline
\end{array}$$
which is your first matrix.
If we use any linear operation of the form $au + bv + c$ on the $(u,v)$ values in a cell, we'll also get a magic square. We just need to be a little careful when choosing $a$ and $b$ to avoid getting repeated values. For example, with $a=7, b=4, c=-6$ we get
$$\begin{array}{|r|r|r|}
\hline
7\cdot2+4\cdot1-6 & 7\cdot0+4\cdot2-6 & 7\cdot1+4\cdot0-6\\
\hline
7\cdot0+4\cdot0-6 & 7\cdot1+4\cdot1-6 & 7\cdot2+4\cdot2-6\\
\hline
7\cdot1+4\cdot2-6 & 7\cdot2+4\cdot0-6 & 7\cdot0+4\cdot1-6\\
\hline
\end{array}$$
or
$$\begin{array}{|r|r|r|}
\hline
12 & 2 & 1\\
\hline
-6 & 5 & 16\\
\hline
9 & 8 & -2\\
\hline
\end{array}$$
which is your 2nd matrix, rotated by 180°.

As I said earlier, all magic squares of order 3 are based on the same structure. Clearly, if you permute the rows or columns of a Latin square, the result is still a Latin square. So given any Latin square we can permute it so that its 1st row and column are in natural order, eg
$$\begin{array}{|r|r|r|}
\hline
0 & 1 & 2\\
\hline
1 & 2 & 0\\
\hline
2 & 0 & 1\\
\hline
\end{array}
$$
This is known as the reduced form.
The Wikipedia article on Small Latin squares and quasigroups states that there is only one reduced Latin square of order three. That's pretty easy to see. If we start with
\begin{array}{|r|r|r|}
\hline
0 & 1 & 2\\
\hline
1 &  & \\
\hline
2 &  & \\
\hline
\end{array}
there's only one possible way to complete the square.
For a magic square, we need the diagonals to sum to the row constant. So we need to permute the rows & columns of the standard Latin square so that the diagonals of our mutually orthogonal Latin squares are either $(0, 1, 2)$ or $(1,1,1)$. It's easy to see that both diagonals cannot be of the same form, so we need to start with an arrangement like
$$\begin{array}{|r|r|r|}
\hline
2 &  & 1\\
\hline
 & 1 & \\
\hline
1 &  & 0\\
\hline
\end{array}$$
and clearly there's only one way to complete that Latin square:
$$\begin{array}{|r|r|r|}
\hline
2 & 0 & 1\\
\hline
0 & 1 & 2\\
\hline
1 & 2 & 0\\
\hline
\end{array}$$
which is the first $(0,1,2)$ Latin square given earlier.

We need to choose $a$ and $b$ to ensure that all the cell values are distinct. Our cell value equation is $x = f(u, v) = au + bv + c$. Given two cells, $(u, v)$ and $(u', v')$, we want $f(u, v) \ne  f(u', v')$.
Let
$$au + bv + c = au' + bv' + c$$
$$a(u-u') = b(v'-v) \tag{1}$$
The possible values of $u-u', v'-v$ are in $\{0, \pm1, \pm2\}$.
We only want (1) to be true when $u-u' = v'-v = 0$. So we just need to choose non-zero $a$ and $b$ such that $a \ne \pm b$, $a \ne \pm 2b$, and $2a \ne \pm b$. We are free to choose any $c$.
Here is a Python script that generates order 3 magic squares using the above method, with MathJax output.


text:
Q: Is single PWM kind of AC voltage? Does alternating current mean any variable voltage or only specific case of it when polarity (e.g. current flow direction) gets reversed?
I want to understand what AC really is, and if PWM or AC passed through a rectifier (which is essentially \$\lvert sin(x)\rvert\$ if \$sin(x)\$ was passed on input) is an AC voltage?
If not - what is it?

A: DC means that the voltage and/or current (practically) don't change over time. Example: a 5 V USB adapter that we use to charge a phone.
AC means that the voltage and/or current do change over time and that is relevant for the application. Example: mains AC is a voltage that changes over time, it is a 50 Hz or 60 Hz sinusoidal shaped voltage.
Any other voltage or current that changes over time can be called AC so a PWM signal is AC as long as it isn't a 0 % (exactly) or 100% (exactly) PWM signal because those signals are constant and thus they're DC.
Do note that a signal can have an AC and a DC component. A 50% PWM signal which is 5 V 50% of the time (and 0 V the other 50% of the time) has an average value of 2.5 V. You get 2.5 V if you filter it! That means it has a DC voltage component of 2.5 V. I'm talking about a 50% Duty Cycle signal like shown here:

Source
So on top of that 2.5 V DC there's a 2.5 V peak AC signal. The amplitude of the AC component is 2.5 V. The AC signal varies between -2.5 V and + 2.5 V relative to the +2.5 V DC.

A: Different people will give you different answers, so be prepared for confusion.  If you're strict:

*

*DC means a constant, unvarying voltage or at least (in the case of battery power) voltage that you'd really like to be constant.

*AC means voltage that alternates -- nominally sinusoidally -- between two equal voltages.  And if it comes with a voltage rating, it's RMS.  So "120V" from the wall goes from +170V to -170V and back 60 times a second (or 50, if you're somewhere that does 120V 50Hz AC).

*PWM, or any other sort of pulsed power, pulses from 0V to some DC rail.

It's very common if you're thinking in terms of circuit analysis to think of PWM as being the sum of an AC waveform + a DC one.  So in this sense the answer to your question is "yes".  But in general if you're going outside the common definitions (which is often useful in circuit analysis) it's a good idea to define your terms for the problem at hand -- and if anyone objects, point out that it's just for the problem at hand.
But: everyone cooks up their own terminology, and different communities of engineers may have some common "dictionary" within their own community.  So I, being a purveyor of analog electronics with microprocessors and fancy signal processing software, that generally do signal processing or control motors in itty bitty clean things with power rails that rarely exceed 24V, will have a different set of terminology from a controls engineer at a ginormous strip mine, who deals with 400VDC rails that control motors in great big dirty things.
Moreover, I use different terms at different times, and so will a lot of board designers.  If I'm holding a board in my hand and you say "is the output AC or PWM", I'll probably say "PWM".  But if you then ask me to analyze the effect of its output on the motor it's driving, you may find me saying "the output is the sum of an AC square wave and DC, and the motor mostly responds to the DC".

A: Clearly an AC source is one that fluctuates from a positive position to a negative position. PWM is not so. The source of PWM is either all positive or all negative at a steady zero to peak taking a reference from ground.

A: Ok, AC means signals (current or voltage) jumping across zero; whereas PWM is DC (current or voltage) switched ON/OFF at desired time interval, non-zero crossing.


text:
Q: JS play sound on button click I'm using a select input (one element will be all the times "selected"). Now when the user hits the demoPlay button the currently selected sound should be played, see my code for this.
<select class="form-control" id="notificationSounds" name="notificationSound">
  <option value="1">Beep sound</option>
  <audio id="demoSound1">
    <source src="/sounds/beep.ogg" type="audio/ogg">
    Playing audio elements is not supported by your browser
  </audio>

  <option value="2" selected>Funny sound</option>
  <audio id="demoSound2">
    <source src="/sounds/frog.ogg" type="audio/ogg">
    Playing audio elements is not supported by your browser
  </audio>
</select>

<button type="button" id="demoPlay" class="btn btn-success">Play sound</button>

<script type="text/javascript">
  $(document).ready(function() {
    $("#demoPlay").click(function() {
      selected_element = "notificationDemo_" + $('#notificationSounds').find(":selected").val();
      $("#selected_element").play()
    })
  })
</script>

For some reason it returns:

Returns: Uncaught TypeError: $(...).play is not a function

A: You have several issues here. Firstly, you cannot place audio elements within a select, only option elements. Move them outside.
Secondly, you're using the string literal '#selected_element' as a jQuery selector, whereas selected_element is a variable whose value you need to concatenate to the selector, ie. $('#' + selected_element).
You're also looking for the #notificationDemo_N element, when the audio actually have the id of demoSoundN.
Finally, play() is not a jQuery method. You either need to trigger() the underlying event on the element, or call play() on the Element object directly.
With all that said, try this:
<select class="form-control" id="notificationSounds" name="notificationSound">
  <option value="1">Beep sound</option>
  <option value="2" selected>Funny sound</option>
</select>

<audio id="demoSound1">
  <source src="/sounds/beep.ogg" type="audio/ogg">
  Playing audio elements is not supported by your browser
</audio>

<audio id="demoSound2">
  <source src="/sounds/frog.ogg" type="audio/ogg">
  Playing audio elements is not supported by your browser
</audio>

<button type="button" id="demoPlay" class="btn btn-success">Play sound</button>

$(function() {
  $("#demoPlay").click(function() {
    var selected_element = "demoSound" + $('#notificationSounds').val();
    $('#' + selected_element).get(0).play();
  });
});

A: play() isn't a jQuery function, so you need to get to the underlying DOM object to use it.
 $("#selected_element").get(0).play()


text:
Q: adding a horizontal scroll bar to HTML table in VF page I have a HTML table in my VF page with 18 columns and without the horizontal scroll, the table is looking very clumsy. Is there a way to add one?
I already tried giving the scroll:auto feature in output panel. but this does not work, the VF page automatically tries to fit the table to screensize..
VF Code:
    <apex:pageblock >

   .
   .
   (Rest of the table)
   .
   .

</apex:pageblock>

A: Generally speaking, you're looking for Fixed TableRC if you want a library that does this; salesforce uses something called x-grid that accomplishes the same thing (see the "enhanced list view" feature to see what I'm talking about).
Trying to do this from scratch is a very time-consuming process. I wrote my own version in a matter of about three work days (and it's relatively slow and clunky compared to the plugin I've linked). For most projects, I normally recommend writing your own, but in this particular case, I'd strongly advise leveraging a plugin of some sort to save yourself time.
A simple CSS trick and some JS for a scrolling header simply won't work. Browsers don't support overflow on a tbody, for example, and there's no standards that literally specify a way to make this sort of table without resorting to JS manipulation (if there is, my day of research before I even went this route was useless). Even if there was a way that appeared in HTML5, it would be useless for older versions of IE anyways.
For a simple explanation, what you basically need to do is absolutely position the outer container (either the table or div), then absolutely position the header and body parts, and if you're not using a real table, you need to also resize all the cell elements. You also set the overflow parameter for the head to "hidden", and the body is set to "auto" for the scrollbars. Finally, the body needs a scroll event handler that sets the offset of the header to match its own. There's several libraries out there that accomplish this, as previously linked, although I did end up writing my own.

A: Use overflow-x: scroll;

<apex:page standardController="account" extensions="accounts_conte">

                A
                B
                C

 1, 0	 2, 0	 3, 0

 1, 1	 2, 1	 3, 1

 1, 2	 2, 2	 3, 2

 1, 3	 2, 3	 3, 3

 1, 4	 2, 4	 3, 4

 1, 5	 2, 5	 3, 5

 1, 6	 2, 6	 3, 6

 1, 7	 2, 7	 3, 7

 1, 8	 2, 8	 3, 8

 1, 9	 2, 9	 3, 9

 1, 10	 2, 10	 3, 10

 1, 11	 2, 11	 3, 11

 1, 12	 2, 12	 3, 12

 1, 13	 2, 13	 3, 13

 1, 14	 2, 14	 3, 14

 1, 15	 2, 15	 3, 15

 1, 16	 2, 16	 3, 16

 1, 17	 2, 17	 3, 17

 1, 18	 2, 18	 3, 18

 1, 19	 2, 19	 3, 19

 1, 20	 2, 20	 3, 20

</apex:page>

A: Try this
#table-scroll
{
overflow:auto;
width:500px;
}

   .
   .
   (Rest of the table)
   .
   .

Please give correct answer if it works


text:
Q: Spring Boot run dashboard missing from Intellij IDEA 2018.2 I have added the Custom VM Option -Dide.run.dashboard=true in Help -> Edit custom VM options. But I cannot seem to find this "Run Dashboard" for Spring boot that which is mentioned in this JetBrains blog post https://blog.jetbrains.com/idea/2017/05/intellij-idea-2017-2-eap-run-dashboard-for-spring-boot/
I have tried looking at JetBrains blog posts but cannot seem to find what happened to this Dashboard in 2018.2 version of Intellij IDEA.

A: My Intellij IDEA version is 2018.1, and I encounter the same problem as first. It did not work after changing -Dide.run.dashboard=true to idea.exe.vmoptions and idea64.exe.vmoptions.
I found another way to get "Run Dashboard" back again.
In your Spring Boot or Spring Cloud project, open the workspace.xml in .idea directory (in the top level directory):

Find the tag component with the name property RunDashboard, at first, it should be like this:
<component name="RunDashboard">
    <option name="ruleStates">
      <list>
        <RuleState>
          <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
        </RuleState>
        <RuleState>
          <option name="name" value="StatusDashboardGroupingRule" />
        </RuleState>
      </list>
    </option>
</component>

Next, add the following code to the component tag, along with the existing option tag:
<option name="configurationTypes">
    <set>
        <option value="SpringBootApplicationConfigurationType" />
    </set>
</option>

Finally, it should be like this:
<component name="RunDashboard">
    <option name="configurationTypes">
        <set>
            <option value="SpringBootApplicationConfigurationType" />
        </set>
    </option>
    <option name="ruleStates">
        <list>
        <RuleState>
            <option name="name" value="ConfigurationTypeDashboardGroupingRule" />
        </RuleState>
        <RuleState>
            <option name="name" value="StatusDashboardGroupingRule" />
        </RuleState>
        </list>
    </option>
</component>

Then, just press Ctrl+S (Save this file), and the "Run Dashboard" will pop up!


text:
Q: Conjecture: Range[1,n^2,n] has at least one item which is just the product of two primes Conjecture(Two Primes Modulo Conjecture): For any integer n>2, there exists two primes p,q satisfy: $p*q\equiv 1  \text{mod} (n)$ and $ p*q<n^2 $.
In other words, Range[1,n^2,n] = {1, n+1, 2n+1,..., (n-1)n+1} has at least one item which is just the product of two primes.
In[160]:= n = 3;
Dynamic[n]
While[
 NestWhile[# + 1 &, 1, PrimeOmega[n* # + 1] != 2 &] < n, n++]
n

Out[161]= 327 468
Out[162]= $Aborted

23*997=22931 22931%2293==1
Do you think this conjecture is True or False? I think this is not a very difficult question, but I don't know how to prove still.

A: I don't think this is known at present. Using Linnik's theorem it can be shown that there is such a number $\ll n^{10}$. On GRH this can be improved to $\ll n^4\log^4 n$ (slightly better: $<(1+o(1))\varphi(n)^4\log^4n$).


text:
Q: Python: Classes, Methods, Parameter Attributes I am rather new to using classes. I struggle with functions (i.e. methods) in classes and how to access the classes attributes via method parameter.
My aim is to have a method accessing an instance's list (and the instances contained therein, yadda yadda)
While:
class dictclasser:
    def __init__(self, attribute):
        self.attribute = attribute

    def printattr(self):
        self.printattr2()

    def printattr2(self):
        return self.attribute

classcollection = []

while True:
    attribute = input()
    classcollection.append(dictclasser(attribute))
    for i in classcollection:
        print(i.printattr())

Returns None
class dictclasser:
    def __init__(self, attribute):
        self.attribute = attribute

    def printattr(self):
        return self.attribute

classcollection = []

while True:
    attribute = input()
    classcollection.append(dictclasser(attribute))
    for i in classcollection:
        print(i.printattr())

Returns everything as intended. I cannot figure out why printattr can access the instances attribute and printattr2 cannot. I have checked "Similar Question" to no avail.
Thanks in advance!

A: Because you missed a return statement in the first printattr. In order to propagate the return value of printattr2 onwards from printattr you have to return the returned value:
def printattr(self):
    return self.printattr2()

A: Your printattr function has no return statement. Change
self.printattr2()

to
return self.printattr2()


text:
Q: How to set AutomationId for dynamically created controls in Windows Forms? I'm trying to set AutomationId for dynamically created items. The example code is as following:
public Form1()
{
    InitializeComponent();
    var menu = new MenuStrip();

    var item = new ToolStripMenuItem();
    item.Text = "Plik";
    item.Name = "File";

    var subitem = new ToolStripMenuItem();
    subitem.Text = "Nowy";
    subitem.Name = "New";

    item.DropDownItems.Add(subitem);

    this.Controls.Add(menu);
    menu.Items.Add(item);

    this.MainMenuStrip = menu;
}

private void button1_Click(object sender, EventArgs e)
{
    var formHandle = AutomationElement.FromHandle(this.Handle);

    Condition propCondition = new PropertyCondition(
        AutomationElement.NameProperty, "File");

    var menuHandle = formHandle.FindFirst(TreeScope.Descendants, propCondition);
    // menuHandle is null here
    menuHandle.SetFocus();
}

Form itself has AutomationId equal to "Form1". However, created menu items doesn't seem to have AutomationID.
How can I manually set AutomationId for dynamically created control?


text:
Q: Use variable in update execSQL statement in android studio I want to update the sqlite database table with a function as follows
execSQL works when I use 1 directly but not work when I use the variable dep
public void update(long id,int dep) {
    Log.i("ee","havu entered in update");

    db.beginTransaction();
    db.execSQL("UPDATE deci set dp = dep WHERE _id = 1");
    //db.execSQL("UPDATE deci set dp = 1 WHERE _id = 1");
    db.setTransactionSuccessful();
    db.endTransaction();
    db.close();
    /*ContentValues contentValues = new ContentValues();
    contentValues.put(dp, dep);
    int i = db.update(deci, contentValues );*/
    return ;
}

A: Pass the variables like this:
db.execSQL("UPDATE deci set dp = " + dep + " WHERE _id = " + id );

In your code I see commented statements that use ContentValues
which is always a better and safer way:
ContentValues cv = new ContentValues();
cv.put("dp", dep);
db.update(deci , cv, "_id = ?", new String[]{id});