text:
Q: Mysql Fulltext search doesn't return any results I have an issue with a full text search in a MySQL table.
MATCH AGAINST returns no results even I if have 7 records containing the words I'm looking for. What can I do to make it return the rows?
SELECT *
FROM site_plugin_products_cache_texts
WHERE MATCH(item_text) AGAINST ('+your +name' IN BOOLEAN MODE);

No rows.

SELECT *
FROM site_plugin_products_cache_texts
WHERE item_text LIKE'%your name%'

7 rows (0.071 s)

http://sqlfiddle.com/#!9/70c3fa/1/0
Thanks.

A: Did you know that MySQL has a stop word list ?
For MyISAM, there are 543 words that do not get included in a fulltext index ???
In the MySQL 5.6 Docs on this (Stopwords for MyISAM Search Indexes), you can see the list.

*

*name is on line 55 column 4

*your is on line 108 column 4

That why all attempts to search on those two words will fail.
If you convert the table to InnoDB, drop and create the FullText index, you will find them. There are only 36 stop words for InnoDB FullText Indexes.
If the table has to remain MyISAM, you have to provide an empty stopword list, restart mysqld, drop and create the FullText Index again.
Here are some of my past posts on this:

*

*May 23, 2011 : Optimizing mysql fulltext search (StackOverflow)

*Oct 25, 2011 : FULLTEXT index ignored in BOOLEAN MODE with 'number of words' conditional

*Jan 26, 2012 : Mysql fulltext search my.cnf optimization

*May 07, 2012 : MySQL EXPLAIN doesn't show 'use index' for FULLTEXT

*Apr 24, 2013 : MySQL - SQL statement to test minimum length of the word 'ft_min_word_len'
Please refer to the Jan 26, 2012 post on how to setup and empty stopword list.
UPDATE 2018-05-04 22:44 EDT
If you run this in SQL Fiddle
SELECT * FROM site_plugin_products_cache_texts
WHERE match(item_text) AGAINST ('+CALL' IN BOOLEAN MODE);

This will work because CALL in not in the stopword list.


text:
Q: How to scale an object in near eye optics and have it appear at correct height at a distance? I'm trying to draw an object in my near eye display and have it appear at the correct size at a distance. I can accomplish this if I'm looking at a wall in my office but not when I step outside. I'm an electrical engineer with only a cursory understanding of optics.
For reference my setup looks something like this. A tiny display above a birdbath optics setup projects the image back to the eye.

So I learned that if I want to draw an object, say a flat tree picture on a wall 10ft away then it is a simple ratio. Based on the eye relief (15mm in my case), and the size of the display and of the pixels.  So if I draw my tree on my display and look at a wall 10ft away, everything is pretty close to the right size. As I back away it gets larger, and as I get closer it gets smaller. That makes sense.

Now if I step outside and look down the road my tree looks huge. How do I learn to draw objects appropriately so they appear the correct size here? Is there some maximum virtual screen size defined by my eye and the optics at infinity? I don't quite understand the concept or math I'd have to do for the scaling.

A: The perceived size of objects is calculated by your brain based on two major items:

*

*The angular size presented to your optic system

*The perceived distance to the object

Two objects with the same angular size will be perceived to be of different sizes if the perceived distance is different.  Something that is "far away" must be larger to give the same angular size.
However, there's no single cue to present depth.  In your office, by seeing the wall, you are assuming objects to be in front of it.  Outside, objects might be much further away and your brain assigns a different distance to the same image.  This is an artefact of the visual processing system.
Unfortunately, this may mean that there is no simple way to present an image such that it always has the same perceived size.  At least not without a much greater understanding of what the user is seeing as cues.
http://psylux.psych.tu-dresden.de/i1/kaw/diverses%20Material/www.illusionworks.com/html/ames_room.html has some descriptions of an Ames room, which exploits this ambiguity to intentionally fool your visual processing system.

redpajama_set_name: RedPajamaStackExchange


text:
Q: GridView_RowUpdating method doesn't works in my asp.net project I have an asp.net project, in which columns in GridView adding manually by button click, here's the method:
protected void addVacations_Click(object sender, EventArgs e)
    {
        using (var conn = new NpgsqlConnection(connStr))
        {
            conn.Open();
            NpgsqlCommand cmd = new NpgsqlCommand("insert into vacations(id,name,date,nodes) values(DEFAULT, @imya, @data, @primVac)", conn);

            cmd.Parameters.Add(new NpgsqlParameter("@imya", imya.Text));
            cmd.Parameters.Add(new NpgsqlParameter("@data", data.Text));
            cmd.Parameters.Add(new NpgsqlParameter("@primVac", primVac.Text));
            cmd.ExecuteNonQuery();
            Response.Redirect(Request.RawUrl);
        }

    }

I have two others buttons, that adding change GridView's columns by clicking them.
  Now i have to add opportunity to change them online by clients. Here's the GridView code:
<asp:GridView ID="GridView1" runat="server" DataKeyNames="id" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None" Width="1650px" AutoGenerateDeleteButton="True" OnRowDeleting="GridView1_RowDeleting" OnRowUpdating="GridView1_RowUpdating" OnRowEditing="GridView1_RowEditing" AutoGenerateEditButton="True" >

Here's GridView1_RowUpdating method:
    protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
 GridViewRow row = GridView1.Rows[e.RowIndex];
            int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
            string name = (row.FindControl("name") as TextBox).Text;
            string date = (row.FindControl("date") as TextBox).Text;
            string prim = (row.FindControl("nodes") as TextBox).Text;

            string constr = ConfigurationManager.ConnectionStrings["postgresConnectionString"].ConnectionString;
            using (NpgsqlConnection cn = new NpgsqlConnection(constr))
            {
                string query = "UPDATE vacations SET name=@name,date=@date,nodes=@prim Where id=@ID5";
                NpgsqlCommand cmd = new NpgsqlCommand(query, cn);
                cmd.Parameters.Add("@name", NpgsqlDbType.Varchar).Value = name;
                cmd.Parameters.Add("@date", NpgsqlDbType.Varchar).Value = date;
                cmd.Parameters.Add("@nodes", NpgsqlDbType.Varchar).Value = prim;
                cmd.Parameters.Add("@id", NpgsqlDbType.Integer).Value = ID5;
                cn.Open();
                cmd.ExecuteNonQuery();
            }
        }

Right now i have next error when trying to change rows:
Server error in the application '/'.
The object reference does not point to an instance of the object.
Description: An unhandled exception occurred during the execution of the current web request. Examine the stack trace for more information about this error and the code snippet that caused it.
Exception Information: System.NullReferenceException: The object reference does not point to an instance of the object.
Source error:
Line 361:            GridViewRow row = GridView1.Rows[e.RowIndex];
Line 362:            int ID5 = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]);
Line 363:            string name = (row.FindControl("name") as TextBox).Text;
The problem exactly in Line 363
I think the problem in my string, if be exact here:
string name = (row.FindControl("name") as TextBox).Text;
        string date = (row.FindControl("date") as TextBox).Text;
        string prim = (row.FindControl("nodes") as TextBox).Text;

So i need help how to correctly declare my strings? Or what wrong in my code.
Update. Here is my column details, all three buttons:
 protected void Button1_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = null;//надо удалить текущие колонны (columns)
        GridView1.DataBind();
        for (int i = 0; GridView1.Columns.Count > i;)
        {
            GridView1.Columns.RemoveAt(i);
        }

        using (var conn = new NpgsqlConnection(connStr))
        {
            conn.Open();

            bf1.HeaderText = "Направление деятельности";
            bf1.DataField = "lineofbusiness";
            bf1.ReadOnly = true;
            bf1.SortExpression = "Napr";

            bf2.HeaderText = "Объект";
            bf2.DataField = "object";
            bf2.SortExpression = "Obj";

            bf3.HeaderText = "Мероприятия";
            bf3.DataField = "events";
            bf3.SortExpression = "Merop";

            bf4.HeaderText = "Срок";
            bf4.DataField = "deadline";
            bf4.SortExpression = "Srok";

            bf5.HeaderText = "Примечания";
            bf5.DataField = "nodes";
            bf5.SortExpression = "Prim";

            GridView1.Columns.Add(bf1);
            GridView1.Columns.Add(bf2);
            GridView1.Columns.Add(bf3);
            GridView1.Columns.Add(bf4);
            GridView1.Columns.Add(bf5);

            NpgsqlCommand cmd = new NpgsqlCommand();
            NpgsqlDataAdapter sqlDa = new NpgsqlDataAdapter("SELECT id, lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + (string)Session["Name"] + "'  ", conn);
            //NpgsqlDataAdapter sqlDa1 = new NpgsqlDataAdapter("SELECT lineofbusiness, object, events, deadline, nodes FROM mainpage where executor = '" + curentExec + "'  ", conn); //показ по исполнителю(раб код)
            DataTable dtbl = new DataTable();

            sqlDa.Fill(dtbl);
            GridView1.DataSource = dtbl;
            GridView1.DataBind();

            Panel2.Visible = false;
            Panel1.Visible = true;
            Panel3.Visible = false;
            //conn.Close(); //надо ли?
        }

    }

    protected void Button2_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = null;//надо удалить текущие колонны (columns)
        GridView1.DataBind();
        for (int i = 0; GridView1.Columns.Count > i;)
        {
            GridView1.Columns.RemoveAt(i);
        }

        using (var conn = new NpgsqlConnection(connStr))
        {
            conn.Open();

            bf1.HeaderText = "Номер";
            bf1.DataField = "id";
            bf1.ReadOnly = true;
            bf1.SortExpression = "11";

            //bf2.HeaderText = "ФИО";
            //bf2.DataField = "name";
            //bf2.SortExpression = "22";

            bf3.HeaderText = "Место";
            bf3.DataField = "place";
            bf3.SortExpression = "33";

            bf4.HeaderText = "Цель";
            bf4.DataField = "target";
            bf4.SortExpression = "44";

            bf5.HeaderText = "Срок";
            bf5.DataField = "date";
            bf5.SortExpression = "44";

            bf6.HeaderText = "Результат";
            bf6.DataField = "result";
            bf6.SortExpression = "44";

            GridView1.Columns.Add(bf1);
            GridView1.Columns.Add(bf2);
            GridView1.Columns.Add(bf3);
            GridView1.Columns.Add(bf4);
            GridView1.Columns.Add(bf5);
            GridView1.Columns.Add(bf6);

            NpgsqlCommand cmd = new NpgsqlCommand();
            //NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM trips", conn);
            NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, place, target, date, result FROM trips where name = '" + (string)Session["Name"] + "'  ", conn);
            DataTable dtblvac = new DataTable();

            sqlDavac.Fill(dtblvac);
            GridView1.DataSource = dtblvac;
            GridView1.DataBind();

            Panel1.Visible = false;
            Panel2.Visible = false;
            Panel3.Visible = true;
        }

    }

    protected void Button3_Click(object sender, EventArgs e)
    {
        GridView1.DataSource = null;//надо удалить текущие колонны (columns)
        GridView1.DataBind();
        for (int i = 0; GridView1.Columns.Count > i;)
        {
            GridView1.Columns.RemoveAt(i);
        }

        using (var conn = new NpgsqlConnection(connStr))
        {
            conn.Open();

            bf1.HeaderText = "Номер";
            bf1.DataField = "id";
            bf1.ReadOnly = true;
            bf1.SortExpression = "NomerVac";

            //bf2.HeaderText = "ФИО";
            //bf2.DataField = "name";
            //bf2.SortExpression = "NameVac";

            bf3.HeaderText = "Дата";
            bf3.DataField = "date";
            bf3.SortExpression = "DataVac";

            bf4.HeaderText = "Примечания";
            bf4.DataField = "nodes";
            bf4.SortExpression = "PrimVac";

            GridView1.Columns.Add(bf1);
            GridView1.Columns.Add(bf2);
            GridView1.Columns.Add(bf3);
            GridView1.Columns.Add(bf4);

            NpgsqlCommand cmd = new NpgsqlCommand();
           //NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT * FROM vacations", conn);
            NpgsqlDataAdapter sqlDavac = new NpgsqlDataAdapter("SELECT id, date, nodes FROM vacations where name = '" + (string)Session["Name"] + "'  ", conn);
            DataTable dtblvac = new DataTable();

            sqlDavac.Fill(dtblvac);
            GridView1.DataSource = dtblvac;
            GridView1.DataBind();

            Panel1.Visible = false;
            Panel2.Visible = true;
            Panel3.Visible = false;
        }
    }


text:
Q: Connectedness and invertibility of Laplacian matrix Context:
In the context of circuit theory and graph theory, suppose we have a graph $G,$ then the Laplacian (Kirchhoff) matrix $L$ is defined as follows:
$$
L = D-A \tag{1}
$$
where $D$ is the degree matrix and $A$ the adjacency matrix. Alternatively, in terms of the incidence matrix $M$ it can be also expressed as:
$$
L = M^T M \tag{2}
$$
I am interested in the case where the graph $G$ is connected. Then if we partition $G$ into connected subgraphs that are themselves connected, the Laplacian can then be represented as a block matrix. Let's assume we partition the graph into two parts, the boundary nodes $B$ and the connection nodes $C.$ Then $|V(G)|=|V(G_B)|+|V(G_C)|.$ The corresponding Laplacian matrix can be put in the form of the following block matrix:
$$
L = \begin{bmatrix}
       L_{BB} & L_{BC}          \\
       L_{CB} & L_{CC}
     \end{bmatrix}
\tag{3}
$$
One often is interested in reducing the size of the network/graph, using a scheme such as the Kron reduction, which relies on taking the Schur complement  (Laplacian matrices are M-Matrices) of $L$ with respect to one of its blocks. But that is only possible if the submatrix of the chosen block is invertible, and in general this is assumed to follow from the connectedness of the graph.
Questions:

*

*Does the fact that $G$ and its subcomponents ($B$ and $C$) are connected ensure that the submatrices of the block representation of the Laplacian $L$ are invertible? (does this follow from a known theorem?) And therefore the Schur complements can be safely taken.

*In relation to connected graphs and their corresponding incidence matrices $M$ [*], is there a simple way to see that the kernel of $M$ is given by $\text{ker } M^T=\text{span } \mathbb{1}?$
[*]: The incidence matrix $M$ is usually defined with each column corresponding to an edge of $G,$ where then each column contains exactly one $1$ at the row corresponding to the tail-node of the edge and a $-1$ at the row corresponding to the head-node of the edge.

A: For your second question, if we think of $M^{\mathsf T}$ as a linear transformation, it takes an element of $\mathbb R^V$ (an assignment of a real scalar to every vertex) to an element of $\mathbb R^E$ (an assignment of a real scalar to every edge) by giving every edge the difference of the values on its endpoints.
So $\ker M^{\mathsf T}$ consists of all elements of $\mathbb R^V$ such that for every edge, the difference of values on its endpoints is $0$: the values on the endpoints are equal.
As a result, once we pick a value to put on one vertex, if we want to get an element of $\ker M^{\mathsf T}$, that value propagates to every other vertex in the same connected component. (All neighbors of the starting vertex must have the same value, and then all of their neighbors must have that value, and so on.) When the graph is connected, this means that each element of $\ker M^{\mathsf T}$ must be a multiple of $\mathbf 1_V$.
(In general, the same argument tells us that $\ker M^{\mathsf T}$ is generated by elements of $\mathbb R^V$ which are $1$ on a connected component of the graph, and $0$ elsewhere.)

A: For your first question, I think you can easily prove that $L_{BB}$ and $L_{CC}$ are
weakly chained diagonally dominant matrices from your connection assumptions:
For each row of $L_{BB}$ (similar proof holds for $L_{CC}$) there is two possible cases:

*

*the node associated to the row in $B$ is connected to some node in $C$. Then the row is strictly diagonally dominant (as there are non 0 coefficients in the same row in $L_{BC}$).

*the node  associated to the row in $B$ is not connected to some node in $C$ and then diagonally dominant but not strictly. But as you graph is connected, there exists a path from this node to another node $n$ in $B$ which is connected to some node in $C$. The node $n$ is then associated to a row of $L_{BB}$
This is exactly the definition of a weakly chained diagonally dominant matrix.

As these matrices have the property of being non-singular, you can conclude that $L_{BB}$ and $L_{CC}$ are invertible.
$L_{BC}$ (and $L_{CB}$ which is equal to $L_{BC}$ for undirected graph which is the case you seem to consider) can be singular, but you don't need nonsingularity of this matrix for applying Schur complement.


text:
Q: How do I do a content search in Firebase? I have about 300 records stored in FireBase.
The structure of each record looks something like:
unique ID/key (e.g. -K1vsg7F4V_5usvPejZV)
 - city
 - firstName
 - lastName
 - image (encoded as base64)

With the images especially, a current export is 15Mb.
So everytime I want to do search for, say a first name, I need to download 15Mb and then do a search on that data in the browser. It's incredibly bandwidth heavy and slow to use this way.
I've been reading up online that content searches is coming? But I don't see it yet?
Thoughts? Or have I missed something obvious?

A: Why download data and do another search? Just query for the firstName you are interested in.
ref.orderByChild("firstName").equalTo("Kato")

Another super simple option is to store your images in another node using the same key.
images
  unique ID/key
      image:
  unique ID/key
      image:

Then you only load in the image you need when it's needed and won't affect your other data.


text:
Q: How deal with testing in Java for long time? I want to test this method:
/**
  * Get the expiry date from a token
  *
  * @param token
  * @return the expiry date
  */
  public Long getExpiryDateFromJwtToken(String token) {
    return Jwts.parser().setSigningKey(jwtSecret).parseClaimsJws(token).getBody().getExpiration().getTime();
}

And this is the test (yes, longer test than methods :) ):
    @Test
    void canGetExpiryDateFromJwtToken() {

        // Set the security context
        SecurityContextHolder.setContext(securityContext);

        // Mock the time at.. now
        Long currentTimeMillis = System.currentTimeMillis();

        // Mock the methods
        when(timeSource.getCurrentTimeMillis()).thenReturn(currentTimeMillis);
        when(securityContext.getAuthentication()).thenReturn(authentication);

        // Create an usersEntitiy
        UsersEntity usersEntity = new UsersEntity(1L, "username", "password");
        // Build the entity to return from getPrincipal
        UserDetailsImpl user = UserDetailsImpl.build(usersEntity);
        when(authentication.getPrincipal()).thenReturn(user);

        // Finally, generate a token
        String token = jwtUtils.generateJwtToken(authentication);

        // Get the expiry date (our method under test)
        Long expiryDate = jwtUtils.getExpiryDateFromJwtToken(token);

        // Finally, assert equals
        assertEquals(currentTimeMillis+86400000, expiryDate);
    }

But, I have a small clock shift.
For example:
AssertionFailedError: expected: <1646512977798> but was: <1646512977000>

So, the time it is the same, only about 798 of difference.
Edit 1
For the moment, I solved with:
// Finally, assert equals. Accept a small clock shift
Long expectedExpiryDate = currentTimeMillis + Long.parseLong(jwtExpirationMs);
assertEquals(expectedExpiryDate/10000, expiryDate/10000);

Is there a more elegant method?

A: In general, when you work with temporal data types it's a good idea to pass a java.time.Clock so u can set the time and control the environment.
The problem in the implementation https://github.com/bezkoder/spring-boot-spring-security-jwt-authentication/blob/master/src/main/java/com/bezkoder/springjwt/security/jwt/JwtUtils.java is with new Date(). A suggestion: Clone this implementation and make a better generateJwtToken and accept a Clock so u can control the timestamp.


text:
Q: Placing an Picture in ImageView selected from Gallery I want to select an image from gallery and place that selected image in the ImageView.  I have also an Intent that will take picture through camera and place it in ImageView and it is working well. But, gallery Intent is only opening the chooser and then select the image, but it is not getting placed in the ImageView
In Log this error is coming up

E/OpenGLRenderer: SFEffectCache:clear(), mSize = 0

Open Gallery Method
 private void openGallery() {
    tvGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(), "Opening Gallery, Please wait..", Toast.LENGTH_SHORT).show();
            private int PICK_IMAGE_REQUEST = 1;
            Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            galleryIntent.setType("image/*");
            startActivityForResult(galleryIntent,PICK_IMAGE_REQUEST);
            Log.e("Status:", "Photopicker canceled");

        }
    });
}

onActivityResult
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    /*camera preview*/
    if (resultCode == RESULT_OK) {
        Bitmap bp = (Bitmap) data.getExtras().get("data");
        previewView.setImageBitmap(bp);
    }
    /*gallery preview*/
   else if (requestCode == PICK_IMAGE_REQUEST) {
        if (resultCode == RESULT_OK) {

            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            previewView = (ImageView) findViewById(R.id.imgPostIssue);
            previewView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        }

    }
}

LOG ERROR
09-08 15:40:02.355 30860-30860/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:03.836 30860-30860/bluecoppertech.com.taskmeld E/Status:: Photopicker canceled
09-08 15:40:07.460 30860-30860/bluecoppertech.com.taskmeld E/OpenGLRenderer: SFEffectCache:clear(), mSize = 0
09-08 15:40:21.754 30860-30860/bluecoppertech.com.taskmeld E/OpenGLRenderer: SFEffectCache:clear(), mSize = 0
09-08 15:40:32.885 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.885 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.885 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.media.session.MediaController', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.895 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.widget.Toolbar', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.905 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.app.ActivityManager$TaskDescription', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.915 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.app.SharedElementCallback', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.915 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.945 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.app.SharedElementCallback', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.965 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.app.assist.AssistContent', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.975 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.view.SearchEvent', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:32.995 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.os.PersistableBundle', referenced from method bluecoppertech.com.taskmeld.Activity.activity.utils.PostNewIssue.access$super
09-08 15:40:33.225 32246-32246/bluecoppertech.com.taskmeld E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering

A: Below is the working solution of choosing a picture from library or capturing one from camera and using it in a imageview.
Source : SO
//functions to select image from the device
    private void selectImage() {
        final CharSequence[] items = {"Take Photo","Choose from Library", "Cancel" };
        AlertDialog.Builder builder = new AlertDialog.Builder(signature_new.this);
        builder.setTitle("Add Photo!");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    startActivityForResult(intent, REQUEST_CAMERA);
                } else if (items[item].equals("Choose from Library")) {
                    Intent intent = new Intent(
                            Intent.ACTION_PICK,
                            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    intent.setType("image/*");
                    startActivityForResult(
                            Intent.createChooser(intent, "Select File"),
                            SELECT_FILE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CAMERA) {
                Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
                ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);

                File destination = new File(Environment.getExternalStorageDirectory(),
                        System.currentTimeMillis() + ".jpg");

                FileOutputStream fo;
                try {
                    destination.createNewFile();
                    fo = new FileOutputStream(destination);
                    fo.write(bytes.toByteArray());
                    fo.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                imageF.setImage(ImageSource.bitmap(thumbnail));

            } else if (requestCode == SELECT_FILE) {
                Uri selectedImageUri = data.getData();
                try {

                    Bitmap bm=decodeUri(selectedImageUri);
                    imageViewF.setImage(ImageSource.bitmap(bm));
                    //uploadbm=bm;
                    //dialog_dimension();
                }
                catch(FileNotFoundException e) {
                    e.printStackTrace();
                }

            }
        }
    }

A: this is the intent to open gallery
Intent Gallery_intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(Gallery_intent, constants.RESULT_LOAD_IMAGE);

and this is on activity result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
     if (requestCode == constants.RESULT_LOAD_IMAGE && resultCode == RESULT_OK && data != null) {
 File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = false;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        b = BitmapFactory.decodeFile(getRealPathFromURI(data.getData()), options);
        int bmpHeight = b.getHeight();
        int bmpWidth = b.getWidth();
        if (bmpHeight > 1500) {
            bmpHeight = bmpHeight / 4;
            bmpWidth = bmpWidth / 4;
        }
        Bitmap out = Bitmap.createScaledBitmap(b, bmpWidth, bmpHeight, false);

        File file = new File(dir, "resize.png");
        FileOutputStream fOut;
        try {
            fOut = new FileOutputStream(file);
            out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
            b.recycle();
            out.recycle();
        } catch (Exception e) {
        }

         ImageView.setImageURI(Uri.fromFile(file));
  }

A: Correcting your code... your conditions are quite wrong in onActivityResult
private void openGallery() {
    tvGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Toast.makeText(getApplicationContext(), "Opening Gallery, Please wait..", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent();
            // Show only images, no videos or anything else
           intent.setType("image/*");
           intent.setAction(Intent.ACTION_GET_CONTENT);
          // Always show the chooser (if there are multiple options available)
          startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

        }
    });
}

Your OnActivityResult
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            previewView = (ImageView) findViewById(R.id.imgPostIssue);
            previewView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

            ImageView previewView = (ImageView) findViewById(R.id.imgPostIssue);
            previewView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

A:
How to place an image into ImageView from Gallery

private int PICK_IMAGE_REQUEST = 1;
private void openGallery() {
        tvGallery.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                // Show only images, no videos or anything else
                intent.setType("image/*");
                intent.setAction(Intent.ACTION_GET_CONTENT);
                // Always show the chooser (if there are multiple options available)
                startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

            }
        });
    }

OnActivityResult

@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        /*camera preview*/

        if (resultCode != RESULT_CANCELED) {

            if (requestCode == 0) {
                Bitmap bp = (Bitmap) data.getExtras().get("data");
                previewView.setImageBitmap(bp);
            }
        /*gallery preview*/
            else {

                Uri uri = data.getData();

                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
                    Log.d(TAG, String.valueOf(bitmap));

                    ImageView previewView = (ImageView) findViewById(R.id.imgPostIssue);
                    previewView.setImageBitmap(bitmap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }


text:
Q: Returning an IQueryable of any kind I'm trying to define a delegate type to return my data set.
public Func<ArticleServerEntities, object, IQueryable<object>> GetItemsSource { get; set; }

Here's how I populate it.
class TextValuePair
{
    public string Text { get; set; }
    public object Value { get; set; }
}

GetItemsSource = (ctx, val) => ctx.Set<Category>()
                                  .OrderBy(c => c.Title)
                                  .Select(c => new TextValuePair { Text = c.Title, Value = c.Id }),

And here's how I call it.
using (var context = new ArticleServerEntities())
{
    action.ListBox.ItemsSource = action.GetItemsSource(context, parentValue).ToList();
}

But calling it generates a System.NotSupportedException exception.

Unable to cast the type 'System.Int32' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types.

Although the error message doesn't quite make sense to me, I believe this is related to the fact that the delegate returns IQueryable<TextValuePair> instead of IQueryable<object>.
But in practice I need this delegate to be able to return an IQueryable of any kind--just as ListBox.ItemsSource accepts a collection of any type.
Does anyone see a way around this, or better understand the error message?

A: The error message indicates that the problem is in this projection:
.Select(c => new TextValuePair { Text = c.Title, Value = c.Id }),

Most likely your TextValuePair Value member is of type object, while your Id is of type int.
In order to avoid the unsupported cast, you should really project to some generic class like
class TextValuePair<TValue>
{
    public string Text { get; set; }
    public TValue Value { get; set; }
}

and then
.Select(c => new TextValuePair<int> { Text = c.Title, Value = c.Id }),


text:
Q: $\{ X_{i} \}_{i=1}^{n} \thicksim iid N(\theta, 1)$. What is distribution of $X_{2} - X_{1}$? So the full question is:
Let $\{ X_{i} \}_{i=1}^{n} \thicksim \text{iid N}(\theta, 1)$. Show then that $\text{T}(X)=X_{2}-X{1} \thicksim \text{N}(0,2)$.
Now, I get that $\mathbb{E}[T(X)]=0$. But I do not get why the variance goes from 1 to 2? Can someone please explain? I didn't think the variance would change? ie, in my view it should be $\mathbb{Var}[\text{T}(X)] = 1$.
For your reference, this is to do with sufficient statistics and ancillatry (ancillary statistics).

A: $\mathbb{Var}(aX_1+bX_2)=a^2\mathbb{Var}(X_1)+b^2\mathbb{Var}(X_2)$ if $X_1$ and $X_2$ are independent, so $\mathbb{Var}(X_1-X_2)=\mathbb{Var}(1\cdot X_1+(-1)\cdot X_2)=1^2\mathbb{Var}(X_1)+(-1)^2\mathbb{Var}(X_2)=\mathbb{Var}(X_1)+\mathbb{Var}(X_2)=1+1=2$.


text:
Q: JGraphX - how to live preview and apply more complicated graph changes I have a graph with two kinds of vertices:

*

*main vertices which represent graph nodes

*port vertices which are children of main vertices and edges are connected to them.

(Edges cannot be directly connected to node because the port vertex is modelling real object which must be explicitly visualized.) Each port vertex is positioned such that it tightly adjoins its parent in direction of opposite node of edge connected to it. This is accomplished by layout algorithm. See picture:
+------+  port             +------+
|      +-+               +-+      |
| node | |---------------| |      |
|      +-+     edge      +-+      |
+------+                   +------+

However, when a node is then being dragged, its ports still have its old relative positions against parent. What should I do for refreshing port positions according to new coordinates of node? At least after dropping node, ideally also during live preview (mxGraphHandler.isLivePreview() == true).
Current wrong graph:
+------+  port
|      +-+
| node | |
|      +-+
+------+  \
           \
            \  +------+
             +-+      |
             | |      |
             +-+      |
               +------+

Expected correct graph:
+------+
|      |
| node |
|      |  port
+------+-+
       | |
       +-+
          \
           \
            \
             +-+
             | |
             +-+------+
               |      |
               |      |
               |      |
               +------+

I digged into live preview process and have some clue and some unsorted unclarities:

*

*seems I will have to implement own extension of mxMovePreview and override start/getPreviewStates method since their current implementation hardcodes the set of affected nodes and for example opposite port of dragged node is not included

*seems I won't be able to fully reuse strategy for port positioning because while in layout it is applied to geometry of cells, in preview it is applied to mxCellStates and mxCellStatePreview

*the methods which receive dx,dy apply linear transformations (shift by constant vector), complicated geometry recomputation will require reconstruction of coordinates?

*the positioning of ports is similar to updating edge terminal points in mxCellStatePreview.revalidateState - perhaps I should implement own extension of mxCellStatePreview and rewrite this method?

*how to implement refreshing after dropping node? Seems different than live preview. Listener on mxEvent.STOP will suffice or some overload will be needed too?

I will appreciate any help of setting in right direction. Thank you.

A: Have you set the port geometry to relative to the parent ?
geo.setParent (<>);
  geo.setRelative(true);


text:
Q: Having troubles w/ drawing hourglass with asterisks in Java. (nested loops) (user decides # of rows) as the title states, I'm having problems drawing this hourglass figure. The goal is to have the user choose the number of rows (has to be odd and positive) and then draw the hourglass with that info. The top and bottom row will have the same amount of asterisks as there are rows.
Should look something like this:
*******
 *****
  ***
   *
  ***
 *****
*******

Here is the code I have so far:
public static void main(String[] args)
{
    double nRows;
    Scanner console = new Scanner(System.in);

    System.out.print("Please enter an odd-number of output-lines (enter zero to exit the program): ");
    nRows = console.nextDouble();

    for(int row=1; row<=nRows; row++ )
        {
            for(int column = 1; column<=nRows-row; column++)
                System.out.print(" ");
            for(int column = 1; column<= row*2-1; column++)
                System.out.print("*");
        System.out.println();
        }
    }

This prints the bottom triangle.
The problem I'm having troubles with is finding out the equation to print the top half. I assume that once I figure out the code for the top half, I'll have to use if statements to tell it when to switch between the top half and the bottom half?
Any help with this would be greatly appreciated.
EDIT: updated the variables to be a little easier to read.
As for what I've been told thus far, here is my understanding:
for( int row = nRows; row>=1; row--)
   {
     for ( int column = 1; column<=nRows-ir; column++)
             System.out.print(" ");
     for ( int column = 1; column<=row*2-1; column++)
             System.out.print("*");
     System.out.println();
   }

A: I'm assuming "ir" is for the column and "ic" is for the row (a bit confusing). There's no equation to make it do the top, all you'd have to do is take the same code you use the generate the bottom and have it iterate in the opposite order. This can be done by making ic start as the maximum and having it decrement instead of increment. I'd include a code snippet of my own, but I'd having a little bit of trouble reading that. (Please name your variables after what they represent. For example, row and column instead of ic and ir)
Hope I helped!

A: This works:
public static void main(String args[]) {
  int nRows;
  Scanner console = new Scanner(System.in);
  System.out.print("Please enter an odd-number of output-lines (enter zero to exit the program): ");
  nRows = console.nextInt();

for(int i=0; i < nRows/2; i++ ) {
    for(int j = nRows - i; j < nRows; j++) {
        System.out.print(" ");
    }
    for(int j = 0; j < nRows - 2*i; j++) {
        System.out.print("*");
    }
    System.out.println();
}

for(int i=0; i < (nRows+1)/2; i++ )
{
    for(int j = 1; j <= nRows/2 - i; j++)
        System.out.print(" ");
    for(int j = 0; j <= i*2; j++)
        System.out.print("*");
    System.out.println();
}
}

A: Try to check this out.
The outer for loop will determine the height of the hourglass.
The inner for loop will prints the * to show the pattern.
Hope this help the other who might need this somehow.
public static void hourGlass(int size) {
    // 2 for loops only
    int dimension = (size * 2) - 1, space = 0, stars = size - 1, printed = 0;

    for(int i=0; i<dimension; i++) {
        int actual = space;
        for (int j=dimension; j > 0; j--) {
            if(actual > 0) {
                System.out.print(" ");
                actual--;
            }
            else {
                System.out.print("*");
                if(stars==printed) {
                    actual = space;
                    printed = 0;
                } else {
                    actual = 1;
                    printed++;
                }
            }
        }
        if(i <= size-2) { // will pattern spaces and stars from top to middle
            space++;
            stars--;
        }
        else { // will pattern spaces and stars from middle to top
            space--;
            stars++;
        }
        System.out.println();
    }
}


text:
Q: Declared variable isn't seen as declared I have a variable that I am populating from a select statement(@ENTY_TABLE_NAME):
DECLARE @ENTY_TABLE_NAME varchar(500)
DECLARE @ENTY_ID INT;
DECLARE @FIELD_ID INT;
DECLARE @VALUE VARCHAR(50);

SET @ENTY_ID = 1
SET @FIELD_ID = 90
SET @VALUE = '0'

SET @ENTY_TABLE_NAME =
(SELECT TOP 1 ENTY_TABLE_NAME
FROM ENTY
WHERE ENTY.ENTY_ID=@ENTY_ID);

SELECT DISTINCT ATTR_VAL
FROM @ENTY_TABLE_NAME _ATTR
WHERE FIELD_ID= @FIELD_ID AND ATTR_VAL LIKE'%' + @VALUE + '%'
ORDER BY ATTR_VAL

After I am trying to use another select statement but it is returning an error:
Msg 1087, Level 16, State 1, Line 26
Must declare the table variable "@ENTY_TABLE_NAME".

Why is it saying I haven't declared a variable that I have an fact declared? How do I fix this?

A: The problem is not that the variable is not declared.  The problem is that you cannot use a variable as a table name in a regular SQL statement (unless the variable is a table variable).
If the table name needs to be a variable, then use dynamic SQL:
declare @sql nvarchar(max);

set @sql = '
SELECT DISTINCT ATTR_VAL
FROM @ENTY_TABLE_NAME _ATTR
WHERE FIELD_ID = @FIELD_ID AND ATTR_VAL LIKE ''%'' + @VALUE + ''%'''
ORDER BY ATTR_VAL';

set @sql = replace(@sql, '@ENTY_TABLE_NAME', ENTY_TABLE_NAME);

exec sp_executesql @sql, N'@FIELD_ID int, @VALUE varchar(50)', @FIELD_ID = @FIELD_ID, @VALUE = @VALUE;


text:
Q: kivy GUI does not adapt to 'Customize display' on windows I just have a new laptop with 14" screen and resolution of 1920 x 1080 running windows 10. As everything on the screen becomes very small I have set the "Change the size of text, apps and other items" option to 125%.
Applications like Office and PyCharm enlarge and look crispy and clear. Unfortunately, my kivy app becomes blurry and vague.
What do I need to do to get this crispy and clear as well?


text:
Q: Changing the width of individual pieces in pie charts in Swift 3.0 (using charts iOS) I have a piechart that displays two values: a total and a subtotal. It currently like this:
the grey and red width is the same
I need it to look like this:
The grey part needs to be thinner, and then red, thicker
I have set the attributes thusly:
let chart = PieChartView()

chart.data = pieChartData
chart.legend.enabled = false
chart.transparentCircleColor = nil

func setChart(labels: [String], pieSplit: [Double]) {
    var dataEntries: [ChartDataEntry] = []

    for i in 0..<labels.count {
        let dataEntry = PieChartDataEntry(value : pieSplit[i], label : labels[i])
        dataEntries.append(dataEntry)
    }

    let dataSet = PieChartDataSet(values: dataEntries, label: self.totalSpent)
    dataSet.selectionShift = 7.0
    dataSet.drawValuesEnabled = false
    let chartData = PieChartData(dataSets: [dataSet])

So the chart is a uniform width, I assume the default width. Setting a userInteractionEnabled to 'true' changes the width of the grey part when clicked (becomes some default value thinner), but this isn't what I need. Any advice?


text:
Q: Stop Click callback when double clicked on node in Fancytree I want to the control to not go into Click callback when Double click on the node in fancytree

A: This is standard browser behavior, Fancytree does not do anything special about the click events.
However: from jQuery help (http://api.jquery.com/dblclick/):

It is inadvisable to bind handlers to both the click and dblclick events for the same element. The sequence of events triggered varies from browser to browser, with some receiving two click events before the dblclick and others only one. Double-click sensitivity (maximum time between clicks that is detected as a double click) can vary by operating system and browser, and is often user-configurable.

See also https://github.com/mar10/fancytree/issues/578

A: You're giving very little to work with, so I'll give you a general double click implementation example.
HTML
<input type="button" id="yourControl">

JS

var waitingForSecondClick = false;

$(document).ready(function() {
  $('#yourControl').click(function() {
    if (waitingForSecondClick) {
      waitingForSecondClick = false;
      onDoubleClick();
    } else {
        waitingForSecondClick = true;
        setTimeout(function() { waitingForSecondClick = false}, 300);
    }

    return false;
  });

  function onDoubleClick() {
    alert('Double clicked!');
  }
});

Check this fiddle


text:
Q: Css no opacity on inside div when image is on body My code is like this

My content

The problem with my code is that it body has an image so that it would be on full screen and class "innermost" has original content including pics and texts , opacity is assigned to "inner" class. And this opacity affects all element of "innermost".
Is there any solution to prevent opacity of "innermost" class without affecting body style.
Thanks for reading.
Update
is there any other alternative of my code , such that i can have image on full screen.

A: It is not going to happen the way you want. If innermost is inside inner, it is part of its content, and will be transparent too.
Depending on what you want to achieve, you can apply an alternative. For example, a transparent background. Or remove innermost from inner, and use position absolute:

My content

A: I think you can try to add css property "style: none" for your class "innermost". Doing that, you "stop" the opacity specified below.

A: If a parent element has an opacity value set at, say, 0.5, all of its children will inherit that opacity setting, and there's no way to reverse that opacity on the child elements.
Read this http://www.impressivewebs.com/fixing-parent-child-opacity/


text:
Q: Pig error in local mode I'm trying to find out the salary in descending order but the output is not correct. I'm running pig in local mode.
My input is as below:
a,a@xyz.com,5000

b,b@xyz.com,3000

c,c@xyz.com,10000

a,a1@xyz.com,2000

c,c1@xyz.com,40000

d,d@xyz.com,7000

e,e@xyz.com,1000

f,f@xyz.com,9000

f,f1@xyz.com,110000

As I needed email and salary(in desc) so here is what I did.
A = load '/local_input_path' USING PigStorage(',');

B = foreach A generate $1,$2;

c = ORDER B by $1 DESC;

But the output is not as expected:
(f@xyz.com,9000)

(d@xyz.com,7000)

(a@xyz.com,5000)

(c1@xyz.com,40000)

(b@xyz.com,3000)

(a1@xyz.com,2000)

(f1@xyz.com,110000)

(c@xyz.com,10000)

(e@xyz.com,1000)

When I don't mention B = foreach A generate $1,$2; and proceed,output is as expected.
Any suggestion on this?

A: Cast the bytearray into int and then order :
Try this code :
a = LOAD '/local_input_path' using PigStorage(',');

b = FOREACH a GENERATE $1,(int)$2;

c = order b by $1 DESC;
dump c;

A: It's treating your numbers as strings and performing a lexicographical sort instead of numeric. When you're loading, assign names and types to help prevent this and make your code more readable/maintainable.
...USING PigStorage(',') AS (letter:chararray, email:chararray, salary:int)


text:
Q: I installed Ubuntu on my laptop but why can't I get any sound? After installing Ubuntu I can't get any sound out of my laptop unless I plug it into my monitor via HDMI. However, out of the speakers on the laptop there is nothing.
How can I fix this?

A: It's most likely due to which sound device is selected for play through.
Left click on the speaker at the top right of the screen (assuming unity desktop) and you'll find Sound Settings... Click that.

After clicking on Sound Settings... the following screen will load:

Notice Play sound through on the left side of the Output Tab. Based on your explanation you'll likely find that an HDMI device is selected. Select the device you'd like to hear sound through and test the sound to verify it works.


text:
Q: comparing values of array and fill dropdown I have two array
  array1[1;2;3;]
  array2[1;1;1;1;2;2;3;3;]

I filled 1st array in dropdown menu. Now i need to check if in 2nd array is elements with same value "1;" and on select fill dropdown2 with elements of array2 with same value. I just need example of code.

A: I created a jsFiddle which may help you achieve your goal: http://jsfiddle.net/XTdrr/
The initial HTML:
<select id="select1" onChange="populateSelect2()">
    <option value="">Choose...</option>
</select>
<br/>
<select id="select2"></select>

The initial JavaScript variables
var array1 = [1, 2, 3];
var array2 = [1, 1, 1, 1, 2, 2, 3, 3];

var select1 = document.getElementById("select1");
var select2 = document.getElementById("select2");

First, it populates the first dropdown list with the values in array1.
window.onload = function () {

    // here we populate select1 with the elements in array1

    for (var i = 0; i < array1.length; i++)
    {
        var opt = document.createElement('option');
        opt.value = array1[i];
        opt.innerHTML = array1[i];
        select1.appendChild(opt);
    }
}

When something is selected int the first dropdown, it looks for matching elements in array2 and populates the second dropdown with those.
function populateSelect2()
{
    // first, empty select2

    for (var i = select2.options.length - 1; i >= 0; i--)
    {
        select2.remove(i);
    }

    // then add new items
    // based on the selected value from select1 and matches from array2

    for (var i = 0; i < array2.length; i++)
    {
        if (array2[i] == select1.value)
        {
            var opt = document.createElement('option');
            opt.value = array2[i];
            opt.innerHTML = array2[i];
            select2.appendChild(opt);
        }
    }
}


text:
Q: How to store and use a native executable in a SWC with AIR? I am developing an AIR application. This application needs some hardware accesses that are not possible with AIR. I decided to use the NativeApplication class in AIR, which launches a C# executable. The AIR application and the "native" application then communicate with the standard output and standard input streams.
A bit like that:
private var np:NativeProcess = new NativeProcess();
private var npi:NativeProcessStartupInfo = new NativeProcessStartupInfo();
private var args:Vector.<String> = new Vector.<String>();

private function creationCompleteHandler(event:FlexEvent):void {
   args.push("myCommand");
   args.push("myParameter");
   npi.arguments = args;
   npi.executable = File.applicationDirectory.resolvePath("MyNativeExe.exe");
   np.addEventListener(ProgressEvent.STANDARD_OUTPUT_DATA, onData);
   np.start(npi);
}

private function onData(e:ProgressEvent):void {
   while(np.standardOutput.bytesAvailable != 0) {
     trace(String.fromCharCode(np.standardOutput.readByte()));
   }
}

I put MyNativeExe.exe file in the application directory, set the "extendedDesktop" value in the *-app.xml supportedProfiles, and it works fine.
Now, I would like to create a kind of AS3 SWC library that embeds MyNativeExe.exe and which provide an AS3 class to manage the interaction with MyNativeExe.exe. Therefore I could easily reuse this work in other AIR projects by simply addind the SWC file as a library. I may have to manually add the "extendedDesktop" value to the new AIR projects, but it is not a problem.
And I am stuck. I can embed an EXE file in a SWC file, by manually selecting the resources to embed with Flash Builder but...

*

*it will not be automatically embeded in the final SWF file as only the needed parts of the SWC file are merged with the SWF

*even if it is (enforcing the merge with an [Embed] tag, ...), how can I access and execute the embedded EXE file? NativeProcessInfo.executable needs a File object, and not a byte stream.

The only idea I have would be to embed the EXE file with [Embed], load it as a byte array, create a new file with the byte array as data, and then execute the file. I don't know if it works, but I do not like the idea, as it implies having the EXE kind of duplicated.
Does someone have an idea?
Thank you!

A: You should look into the Air Native Extensions. Simply put, one of the a new features in Air 3.0 was the ability to compile and link to custom language extensions directly from air. I haven't found an example of using C# directly, but there is a link on that page to doing with managed C++.


text:
Q: How can I align input-group-append elements to the right?

        <text class="font-weight-bold float-left" >Lotti</text>

            <input type="text" class="m-0 form-control form-control-sm" style="max-width: 150px;height:25px" @bind="testoRicerca" @bind:event="oninput" @onkeypress="CercaLotto" />
            <button class="border-0 bg-filter m-0" title="Cerca lotto" @onclick="TrovaLotto"></button>
            <button class="@buttonPoszioniLottoClass" title="Posizioni lotto" @onclick="ShowPosizioniLotto"></button>
            <button class="border-0 bg-transparent m-0" title="Note di entrata lotto" @onclick="ShowNoteEntrataLotto"></button>

That produces this:

I want to align highlighted elements on the right, and keep on same line the text "Lotti".
Thank you very much

A: you can use the d-flex function from bootstrap like this:

        <text class="font-weight-bold float-left" >Lotti</text>

            <input type="text" class="m-0 form-control form-control-sm" style="max-width: 150px;height:25px" @bind="testoRicerca" @bind:event="oninput" @onkeypress="CercaLotto" />
            <button class="border-0 bg-filter m-0" title="Cerca lotto" @onclick="TrovaLotto"></button>
            <button class="@buttonPoszioniLottoClass" title="Posizioni lotto" @onclick="ShowPosizioniLotto"></button>
            <button class="border-0 bg-transparent m-0" title="Note di entrata lotto" @onclick="ShowNoteEntrataLotto"></button>

A: Thank you
I solved with this:

            <text class="font-weight-bold mr-auto">Lotti</text>

                <input type="text" class="m-0 form-control form-control-sm" style="width:120px;height:25px" @bind="testoRicerca" @bind:event="oninput" @onkeypress="CercaLotto" />
                <button class="border-0 bg-filter m-0" title="Cerca lotto" @onclick="TrovaLotto"></button>
                <button class="@buttonPoszioniLottoClass" title="Posizioni lotto" @onclick="ShowPosizioniLotto"></button>
                <button class="border-0 bg-transparent m-0" title="Note di entrata lotto" @onclick="ShowNoteEntrataLotto"></button>


text:
Q: '"' is getting escaped with CFURLCreateStringByAddingPercentEscapes but not with custom NSCharacterSet '"' is getting escaped with CFURLCreateStringByAddingPercentEscapes but not with custom NSCharacterSet. But when I add '\"' to NSCharacterSet then it is getting escaped.
Why the two behavior between two different apis? Would it be safe to add '\"' to custom NSCharacterSet?
NSString* escAcctQuery1 = (NSString *)CFBridgingRelease(CFURLCreateStringByAddingPercentEscapes(NULL,
                                 (CFStringRef) jsonQuery, NULL,
                                 (CFStringRef) @"!*();':@&=+$,/?%#[]{}",
                                  kCFStringEncodingUTF8));

Output: @"%7B%22%24or%22%3A%5B%7B%22uninstalled%22%3Afalse%7D%2C%7B%22uninstalled%22%3A%7B%22%24exists%22%3Afalse%7D%7D%5D%2C%22
NSCharacterSet *customCharacterset = [[NSCharacterSet
      characterSetWithCharactersInString:@"!*();':@&=+$,/?%#[]{}"] invertedSet];
NSString *escAcctQuery = [jsonQuery
      stringByAddingPercentEncodingWithAllowedCharacters:customCharacterset];

Output: @"%7B"%24or"%3A%5B%7B"uninstalled"%3Afalse%7D%2C%7B"uninstalled"%3A%7B"%24exists"%3Afalse%7D%7D%5D%2C"


text:
Q: .NET 5.0 MVC return Json is throwing a JSON Parser error We have an application that we are migrating from .NET Core 2.2 to .NET 5.0. Everything is working as expected except one thing. When we encounter an exception we catch it and add it to a list of error messages that will be return as JSON. Here is a very simplified example:
public JsonResult TestingJson()
{
    Response response = new Response();

    try
    {
        throw new TimeoutException();
    }
    catch (Exception ex)
    {
        response.ErrorMessages.Add(new ErrorMessage {
            Exception = ex,
            Text = ex.Message,
            CreatedDate = DateTime.Now
        });
    }

    return Json(response);
}

The return Json(response) is giving me: "SyntaxError: Unexpected end of JSON input". If I don't add "Exception = ex" as I am building out my response object everything works fine. It seems as if it cannot convert the exception to JSON. My issue is, it all worked fine in Core 2.2. Did I miss something in my migration? I know this is a vague question but I am hoping someone has run into something like this and might know what I am missing.
Thank you

A: asp.net core 2.2 use Newtonsoft.Json by default.As part of the work to improve the ASP.NET Core shared framework, Newtonsoft.Json (Json.NET) has been removed from the ASP.NET Core shared framework since asp.net core 3.0.
To meet your requirement,you need add NewtonSoft support:
1.Install the Microsoft.AspNetCore.Mvc.NewtonsoftJson package version 5.0.0.
2.Update Startup.ConfigureServices to call AddNewtonsoftJson.
services.AddControllers()
    .AddNewtonsoftJson();

Reference:
https://learn.microsoft.com/en-us/aspnet/core/migration/22-to-30?view=aspnetcore-5.0&tabs=visual-studio#use-newtonsoftjson-in-an-aspnet-core-30-mvc-project


text:
Q: Cisco anyconnect vpn client connects to server but there is no connectivity I can connect to Cisco anyconnect server with no problem but when I ping a destination ip I get:
Pinging 172.16.10.153 with 32 bytes of data:
Reply from 192.168.180.52: Destination host unreachable.
Request timed out.
Request timed out.
Request timed out.

This happens on my windows 10 desktop pc and on my laptop there's no such problem.
After connecting to vpn here's ipconfig's output:

Ethernet adapter Ethernet 2:

   Connection-specific DNS Suffix  . : tamindc.ir
   Link-local IPv6 Address . . . . . : fe80::7d9c:2b50:f191:3748%42
   Link-local IPv6 Address . . . . . : fe80::ca9c:8535:634f:bae1%42
   IPv4 Address. . . . . . . . . . . : 192.168.180.52
   Subnet Mask . . . . . . . . . . . : 255.255.255.255
   Default Gateway . . . . . . . . . : ::

Unknown adapter Local Area Connection:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . : lan
   IPv6 Address. . . . . . . . . . . : fd80::20fa:87fa:5227:ece
   Temporary IPv6 Address. . . . . . : fd80::e1a3:940b:65f1:5f86
   Link-local IPv6 Address . . . . . : fe80::20fa:87fa:5227:ece%23
   IPv4 Address. . . . . . . . . . . : 192.168.0.131
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : fe80::1%23
                                       192.168.0.1

Also route print gives me:
Interface List
 42...00 05 9a 3c 7a 00 ......Cisco AnyConnect Secure Mobility Client Virtual Miniport Adapter for Windows x64
  5...00 ff 0f d3 1b 7d ......Windscribe VPN
 23...f4 6d 04 e7 38 2a ......Realtek PCIe GbE Family Controller
  1...........................Software Loopback Interface 1

IPv4 Route Table

Active Routes:
Network Destination        Netmask          Gateway       Interface  Metric
          0.0.0.0          0.0.0.0      192.168.0.1    192.168.0.131     35
        127.0.0.0        255.0.0.0         On-link         127.0.0.1    331
        127.0.0.1  255.255.255.255         On-link         127.0.0.1    331
  127.255.255.255  255.255.255.255         On-link         127.0.0.1    331
       172.16.0.0      255.255.0.0         On-link    192.168.180.52      2
      172.16.8.60  255.255.255.255         On-link    192.168.180.52      2
   172.16.255.255  255.255.255.255         On-link    192.168.180.52    257
       172.18.0.0      255.255.0.0         On-link    192.168.180.52      2
   172.18.255.255  255.255.255.255         On-link    192.168.180.52    257
     172.20.11.11  255.255.255.255      192.168.0.1    192.168.0.131     36
     172.20.11.12  255.255.255.255      192.168.0.1    192.168.0.131     36
      188.214.4.9  255.255.255.255      192.168.0.1    192.168.0.131     36
      192.168.0.0    255.255.255.0         On-link     192.168.0.131    291
      192.168.0.1  255.255.255.255         On-link     192.168.0.131     36
    192.168.0.131  255.255.255.255         On-link     192.168.0.131    291
    192.168.0.255  255.255.255.255         On-link     192.168.0.131    291
   192.168.180.52  255.255.255.255         On-link    192.168.180.52    257
        224.0.0.0        240.0.0.0         On-link         127.0.0.1    331
        224.0.0.0        240.0.0.0         On-link     192.168.0.131    291
        224.0.0.0        240.0.0.0         On-link    192.168.180.52  10000
  255.255.255.255  255.255.255.255         On-link         127.0.0.1    331
  255.255.255.255  255.255.255.255         On-link     192.168.0.131    291
  255.255.255.255  255.255.255.255         On-link    192.168.180.52  10000

Persistent Routes:
  None

IPv6 Route Table

Active Routes:
 If Metric Network Destination      Gateway
 23   4131 ::/0                     fe80::1
 42     36 ::/0                     On-link
  1    331 ::1/128                  On-link
 23   4131 fd80::/64                On-link
 42     36 fd80::/64                On-link
 23    291 fd80::20fa:87fa:5227:ece/128
                                    On-link
 23    291 fd80::e1a3:940b:65f1:5f86/128
                                    On-link
 42    291 fe80::/64                On-link
 23    291 fe80::20fa:87fa:5227:ece/128
                                    On-link
 42    291 fe80::7d9c:2b50:f191:3748/128
                                    On-link
 42    291 fe80::ca9c:8535:634f:bae0/126
                                    On-link
 42    291 fe80::ca9c:8535:634f:bae1/128
                                    On-link
  1    331 ff00::/8                 On-link
 23    291 ff00::/8                 On-link
Persistent Routes:
  None

Thanks in advance.

A: Solution
The software Netbalancer was causing this issue and disabling it did the trick.
Run ncpa.cpl
Right click on Cisco AnyConnect Secure Mobility Client Connection and click properties.
From the items uncheck the NDIS LightWeight Filter.


text:
Q: Drupal removing a node reference from a node Ok, trying to process a script, both PHP and JavaScript, where I am moving a particular content type NODE from one reference to another.  This is the structure:
I have a PROJECT
Inside each PROJECT are PAGES
Inside each PAGE are CALLOUTS
and Inside each CALLOUT are PRODUCTS.
What I want to do is take a PRODUCT from one CALLOUT to another CALLOUT.  I am able to merge these, but now what I want to do is delete the first instance.  An example:
I have PRODUCT AAG-794200 that is on PAGE 6 CALLOUT A.  I am merging that PRODUCT with PAGE 6 CALLOUT B.
I can get the product to merge, but now I need to remove it from CALLOUT A.  Here is my code:
$merge = explode(',', $merge); //Merge SKUs
$mpages = explode(',', $mpages); //Merge Pages
$mcallouts = explode(',', $mcallouts); //Merge Callouts
$mcallout_nid = explode(',', $mcallout_nid);  //Merge Current callout

$length = count($merge);
$e = 0;
while ($e < $length) {
    //Where is the SKU going to?
    $to_callout_letter = strtoupper($mcallouts[$e]);
    $to_page_num = $mpages[$e];
    $sku = $merge[$e];
    $from_callout = $mcallout_nid[$e];

    //Where is the SKU coming from?
    $other_callout = node_load($from_callout);

    //Need page ID of current callout for project purposes
    $page_nid = $other_callout->field_page[0]['nid'];
    $page = node_load($page_nid);
    //Need the project NID
    $project_nid = $page->field_project[0]['nid'];

    //We need to get the NID of the page we are going to
    $page_nid = db_query('SELECT * FROM content_type_page WHERE field_page_order_value = "%d" and field_project_nid = "%d" ORDER BY vid DESC LIMIT 1', $to_page_num, $project_nid);

    $page_nid_res = db_fetch_array($page_nid);
    $to_page_nid = $page_nid_res['nid'];

    //We need to get the NID of the callout here
    $co_nid = db_query('SELECT * FROM content_type_callout WHERE field_identifier_value = "%s" and field_page_nid = "%d"', $to_callout_letter, $to_page_nid);
    $co_nid_res = db_fetch_array($co_nid);
    $to_callout_letter_nid = $co_nid_res['nid'];

    //Load the present callout the SKU resides on
    $f_callout = node_load($from_callout);

    $callout = node_load($to_callout_letter_nid);
    $long = count($f_callout->field_skus);
    $deletecallout = array();
    foreach($f_callout->field_skus as $skus) {
        $s = 0;
        while ($s < $long) {
            if($skus['nid'] == $sku) {
                $callout->field_skus[] = $skus;
                $s++;
            }
            else {
                $deletecallout[] = $skus;
                $s++;
            }
        }
    }

    foreach($other_callout->field_images as $old_image) {
        $callout->field_images[] = $old_image;
    }
    foreach($other_callout->field_line_art as $old_image) {
        $callout->field_line_art[] = $old_image;
    }
    foreach($other_callout->field_swatches as $old_image) {
        $callout->field_swatches[] = $old_image;
    }

    $callout->field_copy_text[0]['value'] .= $other_callout->field_copy_text[0]['value'];
    $callout->field_notes[0]['value'] .= $other_callout->field_notes[0]['value'];
    $callout->field_image_notes[0]['value'] .= $other_callout->field_image_notes[0]['value'];
    $callout->field_status[0]['value'] = 'In Process';
    node_save($callout);

This causes the PRODUCTS to MERGE, but not delete the original.
Thanks for any help.  I know it's something simple, and it will be a palm-to-face moment.

A: I was actually able to solve this myself.  @Chris - The brace ended after node_save(callout);  I must have missed that when I copied and pasted.  However, here is the code I ended up using:
$merge = explode(',', $merge); //Merge SKUs
$mpages = explode(',', $mpages); //Merge Pages
$mcallouts = explode(',', $mcallouts); //Merge Callouts
$mcallout_nid = explode(',', $mcallout_nid);  //Merge Current callout
if($merge[0] !== '0') {
    //Store NIDs of Old Callouts to the proper SKU
    $oc_sku = array();
    $oc_sku_e = count($merge);
    $oc_sku_ee = 0;
    while ($oc_sku_ee < $oc_sku_e) {
        $curr_sku = $merge[$oc_sku_ee];
        $curr_oldco = $mcallout_nid[$oc_sku_ee];
        $oc_sku[$curr_sku] = $curr_oldco;
        $oc_sku_ee++;
    }

    //Convert page numbers to page_nids
    $pc = count($mpages); //How many pages are we getting
    $pc_e = 0;
    while($pc_e < $pc) {
        $nid = $mpages[$pc_e];
        $sql = db_query('SELECT * FROM content_type_page WHERE field_page_order_value = "%d" AND field_project_nid = "%d" ORDER BY vid DESC LIMIT 1', $nid, $project_nid);
        $res = db_fetch_array($sql);
        if($res) {
            $npage_arr[] = $res['nid'];
        } else {  //If there is no page, we need to create it here.
            $node = new StdClass();
            $node->type = 'page';
            $node->title = 'Page ' . $nid . ' of ' . $project->title;
            $node->field_project[0]['nid'] = $project_nid;
            $node->field_page_order[0]['value'] = $nid;
            $node = node_submit($node);
            node_save($node);
            $npage_arr[] = $node->nid;
        }
    $pc_e++;
    }

    // Convert callout letters to callout_nids
    $coc = count($mcallouts);
    $coc_e = 0;
    while($coc_e < $coc) {
        $cnid = strtoupper($mcallouts[$coc_e]);
        $pnid = $npage_arr[$coc_e];
        $page_node = node_load($pnid);
        $sql = db_query('SELECT * FROM content_type_callout WHERE field_identifier_value = "%s" AND field_page_nid = "%d" ORDER BY vid DESC LIMIT 1', $cnid, $pnid);
        $res = db_fetch_array($sql);
        if($res) {
            $cpage_arr[] = $res['nid'];
        } else { //If there is no callout that exists, we need to make it here.
            $callout_node = new stdClass();
            $callout_node->type = 'callout';
            $callout_node->field_page[0]['nid'] = $pnid;
            $callout_node->field_identifier[0]['value'] = $cnid;
            $callout_node->field_sequence[0]['value'] = 0;
            $callout_node->title = "Callout ".$callout." on page ".$page_node->field_page_order[0]['value'];
            $callout_node->field_project[0]['nid'] = $project->nid;
            $callout_node->field_wholesaler[0]['value'] = $project->field_wholesaler[0]['value'];
            $callout_node->field_skus = array();

            $callout_node->status = 1;
            $callout_node->uid = 1;
            $callout_node->revision = true;
            $callout_node = node_submit($callout_node);
            node_save($callout_node);
            $cpage_arr[] = $callout_node->nid;
        }
    $coc_e++;
    }

    //Now we need to assign the skus to the appropriate callout for processing
    $coc2 = count($cpage_arr);
    $coc_e2 = 0;
    while($coc_e2 < $coc2) {
        $co = $cpage_arr[$coc_e2];
        if($co !== '0') {
            $sku = $merge[$coc_e2];
            $m_arr[$co][] = $sku;
        }
    $coc_e2++;
    }

    //we need a way to centrally store all NID's of SKUs to the callouts they belong to
    $oc_arr = array();
    $oc = count($mcallout_nid);
    $oc_e = 0;
    while($oc_e < $oc) {
        $f_callout = $mcallout_nid[$oc_e];
        $former_callout = node_load($f_callout);
        foreach($former_callout->field_skus as $key=>$skus) {
            $oc_arr[] = $skus;
        }
        $oc_e++;
    }

    //Now we are processing the Pages/Callouts/SKUs to save
    $pc_e2 = 0;
    foreach($m_arr as $key=>$values) {
        $callout = node_load($key);
        foreach($values as $value) {
            $oc = count($oc_arr);
            $oc_e = 0;
            while($oc_e < $oc) {
                $skus = $oc_arr[$oc_e];
                if($value == $skus['nid']) {
                    $callout->field_skus[] = $skus;
                    //$nid = $oc_sku[$value];
                    $old_callout_info[] = $oc_sku[$value];
                    $oc_e = $oc;
                }
                else {
                    $oc_e++;
                }
            }
        }

        foreach($old_callout_info as $nid) {
/*          $nid = $oc_sku[$value]; */
            $former_callout = node_load($nid);
            foreach($former_callout->field_images as $old_image) {
            $callout->field_images[] = $old_image;
            }
            foreach($former_callout->field_line_art as $old_image) {
                $callout->field_line_art[] = $old_image;
            }
            foreach($former_callout->field_swatches as $old_image) {
                $callout->field_swatches[] = $old_image;
            }
            $callout->field_copy_text[0]['value'] .= $former_callout->field_copy_text[0]['value'];
        }
        $callout->field_notes[0]['value'] .= $former_callout->field_notes[0]['value'];
        $callout->field_image_notes[0]['value'] .= $former_callout->field_image_notes[0]['value'];
        $callout->field_logos = $former_callout->field_logos;
        $callout->field_affiliations = $former_callout->field_affiliations;
        $callout->field_graphics = $former_callout->field_graphics;
        $callout->revision = 1;

        $callout->field_status[0]['value'] = 'inprocess';
        node_save($callout);
        $pc_e2++;
    }
    }

I realize this can probably be simplified in a way, but as for now, this works perfectly considering what I'm trying to do.  No complaints from the client so far.  Thanks for taking a look Drupal Community.


text:
Q: Is it bad practice to create a new RunSpace from withing a custom C# cmdlet? Is it considered bad practice (or are there specific reasons not to) create a new RunSpace in a custom c# cmdlet?  For example, I have a custom Cmdlet, as below and need to call an existing cmdlet and I am wondering if there will be any threading or other issues with doing this.
 public class SPCmdletNewBusinessSite : SPNewCmdletBase<SPSite>
    {

...
     private void ExecuteRunspaceCommand()
            {
                Runspace runspace = RunspaceFactory.CreateRunspace();
                PSSnapInException snapInError;
                runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.SharePoint.PowerShell", out snapInError);
                runspace.ThreadOptions = PSThreadOptions.Default;
                runspace.Open();

                Pipeline pipeline = runspace.CreatePipeline();

                Command newSiteProc = new Command("New-SPSite");
                newSiteProc.Parameters.Add(new CommandParameter("Url", "http://goober-dc/9393"));
                newSiteProc.Parameters.Add(new CommandParameter("OwnerAlias", "GOOBER\\Administrator"));
                newSiteProc.Parameters.Add(new CommandParameter("Template", "STS#1"));
                newSiteProc.Parameters.Add(new CommandParameter("Language", "1033"));
                newSiteProc.Parameters.Add(new CommandParameter("ContentDatabase", "Site_Specific_ContentDB"));

                pipeline.Commands.Add(newSiteProc);
                Collection<PSObject> results = new Collection<PSObject>();

                results = pipeline.Invoke();
                foreach (PSObject obj in results)
                {
                    base.WriteObject(((SPSite)obj.BaseObject).RootWeb.Title);
                }

            }
}

Specifically, I want to create a SharePoint 2010 SPSite and specify a specific content database for the SPSite.  There is an overload for SPSitesCollection.Add() which accepts an SPContentDatabase as a parameter, but this is an internal method.  I want to create the RunSpace to enable calling the New-SPSite cmdlet (which allows specifying a new content db) and therefore be able to create the site with a specific content database.
I have found http://msdn.microsoft.com/en-us/library/ms714873(v=VS.85).aspx indicates you can invoke cmdlets from within cmdlets, but New-SPSite (actual class SPCmdletNewSite) is also internal and cannot be invoked directly.

A: If you want to call another cmdlet inside a cmdlet, the usual practice is to use a nested pipeline not a new runspace. This lets you use the cmdlet's scope, giving you access to the same variables and context. A new runspace is completely isolated and is more heavyweight as a result but may be desired if you don't to polluate the calling scope. I think you probably want a nested pipeline so you don't have to reload the sharepoint snapin (I'm presuming it's already loaded when you call your new sharepoint cmdlet.)
You can use this method from within your cmdlet. It's a nested pipeline because your command is running in a pipeline already.
var pipe = Runspace.DefaultRunspace.CreateNestedPipeline(...);
pipe.Invoke()

http://msdn.microsoft.com/en-us/library/system.management.automation.runspaces.runspace.createnestedpipeline(v=VS.85).aspx


text:
Q: Abstracting leads to a term ill-typed... yet well-typed I was stuck on a problem for a while, for which I derived a smaller standalone example:
Axiom f : nat -> Set.

Goal forall (n : nat) (e : n = n) (x : f n),
  match e in _ = _n return f _n -> Prop with
  | Logic.eq_refl => fun v : f n => v = x
  end x.

Now, if you try to destruct e, you get the following error message:
Error: Abstracting over the terms "n0" and "e" leads to a term
"fun (n0 : nat) (e : n0 = n0) =>
 forall x : f n0,
 match e in (_ = _n) return (f _n -> Prop) with
 | Logic.eq_refl => fun v : f n0 => v = x
 end x" which is ill-typed.

After scratching my head for a while, I couldn't figure out what was ill-typed in that term... So I tried this:
Definition illt :=
  fun (n : nat) (e : n = n) =>
  forall x : f n,
  match e in _ = _n return f _n -> Prop with
  | Logic.eq_refl => fun v : f n => v = x
  end x.

And Coq accepts it, at type forall n : nat, n = n -> Prop.
So, what is wrong with this error message, and how could I solve/tweak my initial goal?

BTW this is all coq8.3. If this is something fixed in 8.4, please tell me, and my apologies! :)

EDIT: To address Robin Green's comment, here is the Set Printing All versions of the error message:
Error: Abstracting over the terms "n0" and "e" leads to a term
"fun (n0 : nat) (e : @eq nat n0 n0) =>
 forall x : f n0,
 match e in (@eq _ _ _n) return (f _n -> Prop) with
 | eq_refl => fun v : f n0 => @eq (f n0) v x
 end x" which is ill-typed.

It is a well-typed term, and nothing is implicit.

A: Here is a possible explanation of the problem.  What happens when constructing a pattern-matching construct can also be described using a theorem.  Here is my view of the theorem that is being used in your case.
Check eq_rect.

eq_rect
 : forall (A : Type) (x : A) (P : A -> Type),
   P x -> forall y : A, x = y -> P y

So when pattern matching on an equality, you have to provide a formula P parametrized on any value y that happens to be provably equal to x.  Intuitively, you should be able to replace your pattern-matching expression by apply eq_rect, but the property P that should come up there is beyond the reach of what Coq can guess, because every occurrence of x in your formula is bound to be in type f n and cannot just be in type f m where m = n.  The error message does not say that, it is probably a mistake.
To perform your proof, I suggest rather to use the fact that proofs of equality are unique in certain classes of types, and nat belongs to such a class.  This is treated in the file Eqdep_dec.
Require Eqdep_dec Arith.

Now your proof goes through quite easily.
Goal forall n (x : f n) (e : n = n),
  match e in _ = _n return f _n -> Prop with
  | Logic.eq_refl => fun v : f n => v = x
  end x.
intros n x e; replace e with (eq_refl n).
  reflexivity.
apply Eqdep_dec.UIP_dec, eq_nat_dec.
Qed.

Now, this solution may feel unsatisfactory.  Where does this UIP_dec come from?  UIP stands for uniqueness of identity proofs and unfortunately, this property is not guaranteed for all arbitrary types.  It is guaranteed for all types where equality is decidable (as expressed by UIP_dec), for instance nat.


text:
Q: How to avoid used many if statements in definition? I have a function which create list of url. Function works fine. But I do not like what this function looks like:
def prepareadres(city,y,m,d):
    month = [31,28,31,30,31,30,31,31,30,31,30,31]
    d = d + 1
    d0 = 0
    m0 = 0
    if (d > month[0]):
        d = d - month[0]
        m = m + 1
    if (d > month[1]):
        d = d - month[1]
        m = m + 1
    if (d > month[2]):
        d = d - month[2]
        m = m + 1
    if (d > month[3]):
        d = d - month[3]
        m = m + 1
    if (d > month[4]):
        d = d - month[4]
        m = m + 1
    if (d > month[5]):
        d = d - month[5]
        m = m + 1
    if (d > month[6]):
        d = d - month[6]
        m = m + 1
    if (d > month[7]):
        d = d - month[7]
        m = m + 1
    if (d > month[8]):
        d = d - month[8]
        m = m + 1
    if (d > month[9]):
        d = d - month[9]
        m = m + 1
    if (d > month[10]):
        d = d - month[10]
        m = m + 1
    if (d > month[11]):
        d = d - month[11]
        m = m + 1
    if d == sum(month):
        print("year complete")
        #print(df.iloc[0, :-2])
    if (m < 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m0) + str(m) + "-" + str(d0) + str(d)
    elif (m < 10) and (d >= 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-"+ str(m0) + str(m) + "-" + str(d)
    elif (m >= 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d0) + str(d)
    else:
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d)
    #print(adres)
    return adres

Code looks awful as I mention.I used many if statements and want to simplify this.  Can you suggest more elegant ways of writing this definition, avoiding the use of if statements?

A: Use a for loop to iterate over the months:
def prepareadres(city,y,m,d):
    months = [31,28,31,30,31,30,31,31,30,31,30,31]
    d = d + 1
    d0 = 0
    m0 = 0
    for month in months:
        if d > month:
             d = d - month
             m += 1
    if d == sum(months):
        print("year complete")
        #print(df.iloc[0, :-2])
    if (m < 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m0) + str(m) + "-" + str(d0) + str(d)
    elif (m < 10) and (d >= 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-"+ str(m0) + str(m) + "-" + str(d)
    elif (m >= 10) and (d < 10):
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d0) + str(d)
    else:
        adres = "https://sinoptik.ua/погода-" + city + "/" + str(y) + "-" + str(m) + "-" + str(d)
    #print(adres)
    return adres


text: Q: Nuance naturally speaking SDK WPF I am developing a wpf app and i want to add speech to text functionality. I want to achieve this using nuance naturally speaking SDK. Below is my requirement explained briefly, 1) User speak out text and this should be typed on the screen in a rich text box control. 2) User speak out command and program should execute the command logic, for example i have a list whose items are apple, mango, grape. Select an item from list using command 'list item mango'. My questions are, a) Do i have to use Dragon SDK Client (DSC) Edition to fulfill my requirement or is there any other SDK or API form nuance for this requirement. b) Can anyone please suggest a basic tutorial for me to start on this, like how to setup SDK and a sample application in wpf will be great.I have no clue from where to start and how to implement this.


text:
Q: dismissViewControllerAnimated shows a white screen I got a ViewController named viewControllerA which presents ViewControllerB with this common code:
ViewControllerB *viewControllerB = [[UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil] instantiateViewControllerWithIdentifier:@"Identifier"];
[self presentViewController:viewControllerB animated:YES completion:nil];

viewControllerB is a UITabbarController but when calling
[self dismissViewControllerAnimated:YES completion:nil];

from one of the TabbarControllers ViewControllers (say page 2) I just get a white screen. I was expecting to see viewControllerA but instead I just see an empty screen.
also
NSLog(@"%@", [[self presentingViewController] class]);

logs viewControllerA.
Does anybody know why I get a empty white screen instead of viewControllerA?
EDIT
I put a breakpoint on viewDidAppear in viewControllerA and it does break there when calling dismissViewControllerAnimated. But how is it possible that it only shows a white screen?
Also I think you should know that viewControllerA's layout is created programatically. viewControllerB is created much later and in the meantime we decided to use a storyboard so viewControllerB's layout is created with storyboard.

A: you can remove your self (in viewcontrollerB)
[self.presentingViewController dismissViewControllerAnimated:NO completion:nil];

A: If you present viewControllerB from viewControllerA using
[self presentViewController:viewControllerB animated:YES completion:nil];

you should probably call [self dismissViewControllerAnimated:YES completion:nil]; in the  viewControllerA, but not from one of the of the pages of your TabBarViewController.


text:
Q: Javascript return doesn't work? returns undefined I got a wierd issue with a javascript script.
This is my code:
function checkDiscountCode()
{

  var discountCode = $('#korcode').val();
  var errorMessage = $('#errorMessage').text();

  if(discountCode.length > 2)
  {

     $.getJSON( 'calc.php?code=' + discountCode, function( json )
     {
       var color = json.color;
       var soort = json.soort;
       var waarde = json.waarde;
       var message = json.message;

       if(errorMessage != message)
       {
          $('#error').html('' + message + '');
       }

       if(message == 'OK!')
       {
          var outputData = soort + '-' + waarde;
          console.log('outputData = ' + outputData);
          return outputData;
       }

     });
  }
}

The console log give the right data, for example 0-12.00 but when I request this function in another function, for example just a alert(checkDiscountCode()); it says undefined..
Can anyone please help me? I don't see the issue..
Thanks in advance!

A: Your checkDiscountCode() function doesn't have a return statement, so it returns undefined by default.
The return statement that you've included is inside the anonymous function passed as a callback for $.getJSON(), so it returns from that function back to the jQuery code that called it, not back to your code (and even then it returns undefined if message is not 'OK!'). (Also your $.getJSON() doesn't run unless discountCode.length > 2, though your checkDiscountCode() function doesn't try to return a value either way.)

A: You're returning from a callback passed to a function that does work asynchronously. You'll have to adapt the code to take a callback and change the caller to deal with the fact that it's asynchronous.
That means that rather than this:
// won't work
function checkSomething() {
    someAsynchronousFunction(function(result) {
        return result == "success";
    });
}
if(checkSomething()) {
    alert("It worked.");
}else{
    alert("It didn't work.");
}

You'll have to change your code to look like this:
function checkSomething(callback) {
    someAsynchronousFunction(function(result) {
        callback(result == "success");
    });
}
checkSomething(function(result) {
    if(result) {
        alert("It worked.");
    }else{
        alert("It didn't work.");
    }
});

A: If discountCode.length > 2 is not true, you aren't returning a value, thus it will return undefined.

I'll also add that if you did put it in another function alert(checkDiscountCode()) and you closed firebug up, or opened in another browser that doesn't have console open, your browser will encounter a javascript error, if you left the console.log(...) line still in your code.
A console window has to be open in order to log to it.

A: JQuery's getJSON() method runs asynchronously. You should add a callback function to checkDiscountCode(); the callback function will run the rest of your app's logic. For example:
function sampleCallback(outputData) {
  console.log('outputData = ' + outputData);
}

function checkDiscountCode(callback) {
  $.getJSON( 'calc.php?code=' + discountCode, function( json ) {
    // get output data, and then call callback.
    callback(outputData);
  });
}

checkDiscountCode(sampleCallback);

A: And if discountCode.length > 2 you are invoking the $.getJSON function, but that takes a callback, and returns nothing immediately.  Hence, in either case, you get undefined.


text:
Q: Javascript call one object method after another I have this object:
const Foo = {

  bar(x) {

  },

  baz(x) {

  },

}

How can I rewrite this object to be able to call it's methods like this:
Foo.bar(x).baz(y);

instead of calling them like this:
Foo.bar(x);
Foo.baz(y);

Like in the jQuery where you can call one function after another...
$('bac').addClass('x').removeClass('y');

A: You will have to return the object itself with each function, so as you could call the function on it again (that's also what jQuery does).
const Foo = {

  bar(x) {
     return this;
  },

  baz(x) {
     return this;
  },

}

A: This is known as a Fluent API

In software engineering, a fluent interface (as first coined by Eric Evans and Martin Fowler) is an implementation of an object oriented API that aims to provide more readable code.
  A fluent interface is normally implemented by using method cascading (concretely method chaining)

In this case it is implemented by returning the self-object this:

const foo = {

    bar(x) {
        console.log("bar")
        return this; // here
    },

    baz(x) {
        console.log("baz")
        return this; // and here

    }
}

foo.bar(10).baz(20);

A: You should return this at the end of each function. In this context this refers to the Foo object itself.
const Foo = {

  bar(x) {
      return this;
  },

  baz(z) {
      return this;
  }

}

Example:
Foo.bar(x).baz(z);

is executed as:
Foo.bar(x) // <-- returns 'Foo'
   .baz(z) // <-- call 'baz' function of 'Foo'

A: You Should Return The Object Itself From The Method To Call Another Method Again:

const Foo = {

  bar(x) {
    alert("BAR");
    return this;
  },

  baz(x) {
    alert("BAZ");
    return this;
  },

}

onload = function() {
  Foo.bar().baz();
}


text:
Q: to set dropdownlist value in view when record is extracted in mvc working with MVC 3.
I have a dropdownlist which populates Gender with value 'M' for text 'Male' and 'F' for text 'Female'.
Now, when I extract record it is not setting the value as per the record's value.
I have following on code in view.
@if(Model != null)
{
    @Html.DropDownListFor(model => model.GENDER,
        new SelectList(ViewBag.gender, "Value", "key", Model.GENDER))
}
else
{
    @Html.DropDownListFor(model => model.GENDER,
        new SelectList(ViewBag.gender, "Value", "Key"))
}

The above code means that when page first loads it has no value for gender field as model is empty so just populate list and when person is extracted i.e. when model is not null it populates and set value equal to model.gender. But it is not setting the value. What could be the problem?

A: Are you passing an NULL object (your model) to your view ? How many places in the view are you going to write @if(Model != null).. . Is that not going to mess up the concept of Clean code. ?
I guess this is how you should do it. You should always pass the model/ Viewmodel to the view no matter it is the firs time (Create Entity) or the Editing time. Some thing like this
public ActionResult Create()
{
   CustomerViewModel model=new CustomerViewModel();
   return View(model);
}

For Edit action, You fill the Model/ViewModel object filled with data.
public ActionResult Edit(int id)
{
   CustomerViewModel model=new CustomerViewModel();
   model=CustomerService.GetCustomerFromId(id);
   return View(model);
}

and in the View, you use it like this
@model CustomerViewModel

@Html.DropDownListFor(model => model.GENDER,
        new SelectList(ViewBag.gender, "Value", "key", Model.GENDER))


text:
Q: Null response from API in Angular Learning Angular 2 and building an app with .Net Core
I've an API from which json response is passed to Client Side. In my Angular2 service, used Observable to read the response and pass it to my component and then to view.
Tested in PostMan and my API is responding expected output. I'm sure the service has some issue which is taking time to resolve.
API :
[HttpGet]
    public List<MovieFields> Get()
    {
        path += @"\Data\MovieSource.json";
        string jsonSource = System.IO.File.ReadAllText(path);
        List<MovieFields> source = JsonConvert.DeserializeObject<List<MovieFields>>(jsonSource);
        return source;
    }

Json c# class :
public class MovieFields
{
    public string Id { get; set; }
    public string Title { get; set; }
}

Service :
export class MoviesService{

constructor(private http: Http) {
}

getMovies() {
    return this.http.get('api/Movies')
        .map(res => <Array<MovieProperties>>res.json());
}

}
Component :
export class AllMoviesComponent implements OnInit {

private movieProp: Array<MovieProperties>;
ngOnInit() {
    this.moviesService.getMovies()
        .subscribe(ban => this.movieProp = ban);
}

Angular Json Interface :
export interface MovieProperties {
Id: string;
Title: string;

}
and finally my JSON:
 [
{
  "Id": "1",
  "Title": "Olympus Has Fallen"
},
{
  "Id": "2",
  "Title": "Man of Steel"
}  ]

Answer : edited my service as below
getMovies(): Observable<MovieProperties[]> {

    return this.http.get('api/Movies')
        .map(this.extractData)
        .catch(this.handleErrors);
}
private extractData(res: Response) {
    let data = res.json();
    return data;
}

thanks Sajeetharan

A: Your method inside the service should be like this,
getMovies() : Observable<MovieProperties[]>{
    return this._http.get('api/Movies')
        .map((response: Response) => <MovieProperties[]>response.json())
        .catch(this.handleError);
}

private handleError(error: Response){
    console.error(error);
    return Observable.throw(error.json().error || 'Server error');
}

A: export interface MovieProperties {
id: string;
title: string;
}

Changing the case like this worked for me.


text:
Q: 404 page not found in YAMS I would like some help here. I am using MODx with YAMS module which is for multilingual. I follow the installation and setup document from YAMS but I still get 404 page not found.
I would like to get:

localhost/sub/en/index.php?id=1
localhost/sub/fr/index.php?id=1
localhost/sub/th/index.php?id=1

the original link is

localhost/sub/index.php?id=1

here is rewrite rule in htaccess file. I got the rewrite rule from YAMS in "Server Config" tab.
# Friendly URLs
RewriteEngine On
RewriteBase /sub/

# Fix Apache internal dummy connections from breaking [(site_url)] cache
RewriteCond %{HTTP_USER_AGENT} ^.*internal\ dummy\ connection.*$ [NC]
RewriteRule .* - [F,L]

# Exclude /assets and /manager directories from rewrite rules
RewriteRule ^(manager|assets) - [L]

# Redirect from mydomain.com/rootname to mydomain.com/rootname/
RewriteRule ^en$ en/ [R=301,L]
RewriteRule ^fr$ fr/ [R=301,L]
RewriteRule ^th$ th/ [R=301,L]

# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^th/(.*)$ index.php?q=$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^fr/(.*)$ index.php?q=$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^en/(.*)$ index.php?q=$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

I am trying to search all the solutions everywhere. still no luck. please suggest or point me what i do wrong?
Thanks in advance

A: If you are getting links like localhost/en/index.php?id=1 in the frontend You have to fill the "MODx Subdirectory" field with "sub". You will find it in Modules->Yams->Other Params

A: Actually the problem is .htaccess file. I copys all .htaccess from YAMS and replaces the whole original .htaccess file. To solve my problem, I copy only friendly URL part and replace only this part in original .htaccess file.
here what I copy from YAMS and replace in my .htaccess file:
# Redirect from mydomain.com/rootname to mydomain.com/rootname/
RewriteRule ^en$ en/ [R=301,L]
RewriteRule ^fr$ fr/ [R=301,L]
RewriteRule ^th$ th/ [R=301,L]

# The Friendly URLs part
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^th/(.*)$ index.php?q=$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^fr/(.*)$ index.php?q=$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^en/(.*)$ index.php?q=$1 [L,QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Many thanks for suggestions.