问:
colored wireframe plot in matplotlib
I am trying to color a wireframe plot according to the z-value. I can't find any code examples on the internet.

Here is an example of a surface plot that has the colors I want and a wireframe plot where I can't manage to get the colors on the lines:

```<code>import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt

# some numbers for the data
P=12000 #W
Q=1     #kg/s
DT=3    #K
cp=4169.32  #J/kgK

dDT=np.logspace(-2,0,20,endpoint=True)
dQ=Q*np.logspace(-3,-1,20,endpoint=True)

# the plotting data
m1,m2=np.meshgrid(dDT,dQ)
err=cp*np.sqrt((m1*Q)**2+(m2*DT)**2)/P

# the wiremesh plot that i need fixed
fig=plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(m1, m2, err, color=err/err.max(),cmap='jet')
ax.set_xlabel('dDT')
ax.set_ylabel('DQ')
ax.set_zlabel('relative error')

# the surface plot that has the colors i want
fig = plt.figure()
ax = fig.gca(projection='3d')

surf = ax.plot_surface(m1, m2, err,rstride=1,  cstride=1, cmap=cm.jet,
    linewidth=0.1, antialiased=False)

fig.colorbar(surf, shrink=0.5, aspect=5)

ax.set_xlabel('dDT')
ax.set_ylabel('DQ')
ax.set_zlabel('relative error')
plt.show()
</code>```

Thank you for any help!

答:
When you use plot_wireframe, each line can only have one color.
Instead, you can use plot_surface.
To get plot_surface to set the edgecolors, you need to give it facecolors.
Then you can set the alpha of facecolors to zero.

```<code>from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm

X, Y, Z = axes3d.get_test_data(0.2)

# Normalize to [0,1]
norm = plt.Normalize(Z.min(), Z.max())
colors = cm.viridis(norm(Z))
rcount, ccount, _ = colors.shape

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rcount=rcount, ccount=ccount,
                       facecolors=colors, shade=False)
surf.set_facecolor((0,0,0,0))
plt.show()
</code>```

Title: colored wireframe plot in matplotlib

Body:
I am trying to color a wireframe plot according to the z-value. I can't find any code examples on the internet.

Here is an example of a surface plot that has the colors I want and a wireframe plot where I can't manage to get the colors on the lines:

import numpy as np
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
import matplotlib.pyplot as plt

# some numbers for the data
P=12000 #W
Q=1     #kg/s
DT=3    #K
cp=4169.32  #J/kgK

dDT=np.logspace(-2,0,20,endpoint=True)
dQ=Q*np.logspace(-3,-1,20,endpoint=True)

# the plotting data
m1,m2=np.meshgrid(dDT,dQ)
err=cp*np.sqrt((m1*Q)**2+(m2*DT)**2)/P

# the wiremesh plot that i need fixed
fig=plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(m1, m2, err, color=err/err.max(),cmap='jet')
ax.set_xlabel('dDT')
ax.set_ylabel('DQ')
ax.set_zlabel('relative error')

# the surface plot that has the colors i want
fig = plt.figure()
ax = fig.gca(projection='3d')

surf = ax.plot_surface(m1, m2, err,rstride=1,  cstride=1, cmap=cm.jet,
    linewidth=0.1, antialiased=False)

fig.colorbar(surf, shrink=0.5, aspect=5)

ax.set_xlabel('dDT')
ax.set_ylabel('DQ')
ax.set_zlabel('relative error')
plt.show()

Thank you for any help!

Body:
When you use plot_wireframe, each line can only have one color.
Instead, you can use plot_surface.
To get plot_surface to set the edgecolors, you need to give it facecolors.
Then you can set the alpha of facecolors to zero.

from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
from matplotlib import cm

X, Y, Z = axes3d.get_test_data(0.2)

# Normalize to [0,1]
norm = plt.Normalize(Z.min(), Z.max())
colors = cm.viridis(norm(Z))
rcount, ccount, _ = colors.shape

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rcount=rcount, ccount=ccount,
                       facecolors=colors, shade=False)
surf.set_facecolor((0,0,0,0))
plt.show()


来源: stackexchange

问:
Multiplying the values in two columns: TypeError: can't multiply sequence by non-int of type 'float'
I am trying to multiply the values in two separate columns

The type of the elements in the first column is 'numpy.float64'

That of the second column is 'float'

When I do

```<code>new_column = df['first_column'] * df['second column']
</code>```

I get

'TypeError: can't multiply sequence by non-int of type 'float'

I don't really understand why I cannot multiply the values of numpy.float64 and float. Aren't they similar to each other and multipliable?

答:
I can reproduce your error message with:

```<code>In [267]: [1,2,3]*3.43
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-267-fc9c3bc4b243> in <module>()
----> 1 [1,2,3]*3.43

TypeError: can't multiply sequence by non-int of type 'float'
</code>```

In Python (not numpy or pandas), a list or other sequence times an integer replicates the sequence:

```<code>In [268]: [1,2,3]*3
Out[268]: [1, 2, 3, 1, 2, 3, 1, 2, 3]
</code>```

If

```<code>df['first_column'] * df['second column']
</code>```

is producing the error, then one term is a sequence (e.g. list) the other a float.  Another possibility is that one is a object dtype array, and contains one or more lists.

```<code>In [271]: np.array([(2,3),(3,)])*3
Out[271]: array([(2, 3, 2, 3, 2, 3), (3, 3, 3)], dtype=object)
In [272]: np.array([(2,3),(3,)])*3.34
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-272-c3152ad55f88> in <module>()
----> 1 np.array([(2,3),(3,)])*3.34

TypeError: can't multiply sequence by non-int of type 'float'
</code>```

It could even be a mix of floats and lists, doing number * on the numbers and replication on the lists.

```<code>In [283]: np.array([(2,3),(3,),12])*np.array([[3],[2]])
Out[283]:
array([[(2, 3, 2, 3, 2, 3), (3, 3, 3), 36],
       [(2, 3, 2, 3), (3, 3), 24]], dtype=object)
</code>```

More likely it's an object array (or data series) with a mix of numbers and strings:

```<code>In [287]: np.array(['astring',12],dtype=object)*np.array([[3]])
Out[287]: array([['astringastringastring', 36]], dtype=object)
In [288]: np.array(['astring',12],dtype=object)*np.array([[3.23]])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-288-5a02408d1a73> in <module>()
----> 1 np.array(['astring',12],dtype=object)*np.array([[3.23]])

TypeError: can't multiply sequence by non-int of type 'float'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to multiply the values in two separate columns

The type of the elements in the first column is 'numpy.float64'

That of the second column is 'float'

When I do

new_column = df['first_column'] * df['second column']

I get

'TypeError: can't multiply sequence by non-int of type 'float'

I don't really understand why I cannot multiply the values of numpy.float64 and float. Aren't they similar to each other and multipliable?

Body:
I can reproduce your error message with:

In [267]: [1,2,3]*3.43
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-267-fc9c3bc4b243> in <module>()
----> 1 [1,2,3]*3.43

TypeError: can't multiply sequence by non-int of type 'float'

In Python (not numpy or pandas), a list or other sequence times an integer replicates the sequence:

In [268]: [1,2,3]*3
Out[268]: [1, 2, 3, 1, 2, 3, 1, 2, 3]

If

df['first_column'] * df['second column']

is producing the error, then one term is a sequence (e.g. list) the other a float.  Another possibility is that one is a object dtype array, and contains one or more lists.

In [271]: np.array([(2,3),(3,)])*3
Out[271]: array([(2, 3, 2, 3, 2, 3), (3, 3, 3)], dtype=object)
In [272]: np.array([(2,3),(3,)])*3.34
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-272-c3152ad55f88> in <module>()
----> 1 np.array([(2,3),(3,)])*3.34

TypeError: can't multiply sequence by non-int of type 'float'

It could even be a mix of floats and lists, doing number * on the numbers and replication on the lists.

In [283]: np.array([(2,3),(3,),12])*np.array([[3],[2]])
Out[283]:
array([[(2, 3, 2, 3, 2, 3), (3, 3, 3), 36],
       [(2, 3, 2, 3), (3, 3), 24]], dtype=object)

More likely it's an object array (or data series) with a mix of numbers and strings:

In [287]: np.array(['astring',12],dtype=object)*np.array([[3]])
Out[287]: array([['astringastringastring', 36]], dtype=object)
In [288]: np.array(['astring',12],dtype=object)*np.array([[3.23]])
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-288-5a02408d1a73> in <module>()
----> 1 np.array(['astring',12],dtype=object)*np.array([[3.23]])

TypeError: can't multiply sequence by non-int of type 'float'


问:
How to fix the red minus flag on my vb.net project on vs2017
I need to fix the red flag marks on my vb.net projects. See here:

I believe it's one of the projects that isn't included in the build. I saw this post earlier but I can't find the general tab she was talking about. I also tried navigating the solution explorer but can't seem to find the right answer for this.

答: If you mouse over the icon, a tooltip should appear indicating the meaning of the icon. According to this MSDN article, this icon "represents an item that is not under Team Foundation version control". </p>

ContentLicense: CC BY-SA 4.0


问:
Turning an array into a multidimensional array? Javascript
I am struggling to create a simple function that will taking an array such as

```<code>["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]
</code>```

and turn it into a multidimensional array that looks like this

```<code>[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]
</code>```

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

答:
There are many ways to do this. Here, we are using the Array.map() method to return items into a new array and then cleaning out any undefined elements using Array.filter().

var startArray = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];

// Create a new array by iterating the first one...
var resultArray = startArray.map(function(item, index, arry){
  // If we are on an even index...
  if(index % 2 === 0){
    // Send the item and the one that follows it into the new array
    return [item, arry[index + 1]];
  }
});

// The resulting array will contain undefined for each enumeration that didn't
// return anything, so we can clean that up by filtering out the undefined elements
resultArray = resultArray.filter(function( element ) {
   return element !== undefined;
});

console.log(resultArray);```
</div>
</div>
</p>

<p>However, it seems that you want to make an array of ingredients and ingredients combine to make a final product, so creating an <code>object</code> would be more appropriate, since objects are really nothing more than groupings of key/value pairs and can be more versatile if you plan on doing OOP operations. The result here is an array of recipe objects:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// Create a new array that will store recipe objects
var cookbook = [];

function addRecipeToCookbook(ary){
  // Create a "recipe" object
  var recipe = {};

  // Iterate the passed array...
  ary.forEach(function(item, index, array){
    // If we are on an even index...
    if(index % 2 === 0){
      // Add the item as a new property of the recipe object with the quantity as the value
      recipe[item] = array[index + 1];
    }
  });

  // Add the object to the new array
  cookbook.push(recipe);
}

// Now you can add as many recipies as you like:
var recipeArray1 = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];
var recipeArray2 = ["pork","2 lbs","BBQ sauce","2 cups","onion","3 ounces"];
var recipeArray3 = ["beef","5 lbs","worchestishire sauce","4 ounces","garlic","1 clove"];

// Just call the reusable function and pass a recipe array:
addRecipeToCookbook(recipeArray1);
addRecipeToCookbook(recipeArray2);
addRecipeToCookbook(recipeArray3);

console.log(cookbook);</code>```

Body:
I am struggling to create a simple function that will taking an array such as

["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"]

and turn it into a multidimensional array that looks like this

[["chicken","10 lbs"],["hot sauce","4 cups"],["celery","1 stalk"]]

essentially index 0 and 1 merge into a new sub array then 2 and 3 merge and so on...

i am trying for loops where i increases +2 but i can't get it quite right, i thought this would be a simple solution but the loops i've made so far are almost crashing my browser...any help would be appreciated. thanks

EDIT:  WOW Thanks for all the rapid responses!  I looked at everything and learned a lot!

Body:
There are many ways to do this. Here, we are using the Array.map() method to return items into a new array and then cleaning out any undefined elements using Array.filter().

var startArray = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];

// Create a new array by iterating the first one...
var resultArray = startArray.map(function(item, index, arry){
  // If we are on an even index...
  if(index % 2 === 0){
    // Send the item and the one that follows it into the new array
    return [item, arry[index + 1]];
  }
});

// The resulting array will contain undefined for each enumeration that didn't
// return anything, so we can clean that up by filtering out the undefined elements
resultArray = resultArray.filter(function( element ) {
   return element !== undefined;
});

console.log(resultArray);

However, it seems that you want to make an array of ingredients and ingredients combine to make a final product, so creating an object would be more appropriate, since objects are really nothing more than groupings of key/value pairs and can be more versatile if you plan on doing OOP operations. The result here is an array of recipe objects:

// Create a new array that will store recipe objects
var cookbook = [];

function addRecipeToCookbook(ary){
  // Create a "recipe" object
  var recipe = {};

  // Iterate the passed array...
  ary.forEach(function(item, index, array){
    // If we are on an even index...
    if(index % 2 === 0){
      // Add the item as a new property of the recipe object with the quantity as the value
      recipe[item] = array[index + 1];
    }
  });

  // Add the object to the new array
  cookbook.push(recipe);
}

// Now you can add as many recipies as you like:
var recipeArray1 = ["chicken","10 lbs","hot sauce","4 cups","celery","1 stalk"];
var recipeArray2 = ["pork","2 lbs","BBQ sauce","2 cups","onion","3 ounces"];
var recipeArray3 = ["beef","5 lbs","worchestishire sauce","4 ounces","garlic","1 clove"];

// Just call the reusable function and pass a recipe array:
addRecipeToCookbook(recipeArray1);
addRecipeToCookbook(recipeArray2);
addRecipeToCookbook(recipeArray3);

console.log(cookbook);


问:
Facebook API how to wait til graphRequest executeAsync is done
I am using facebook graph request to retrieve friends list. But, How can I get to create a function and return it after the call graphRequest.executeAsync() is done?.

```<code>private Map<String, String> getFacebookFriends(AccessToken accessToken, Profile profile) throws InterruptedException, ExecutionException {
    final Map<String, String> friendsMap = new HashMap<>();
    GraphRequest graphRequest = new GraphRequest(accessToken, "/me/friends", null, HttpMethod.GET,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {
                    JSONObject jGraphObj = response.getJSONObject();
                    try {
                        JSONArray friendsData = jGraphObj.getJSONArray("data");
                        for (int i = 0; i < friendsData.length(); i++) {
                            JSONObject friend = friendsData.getJSONObject(i);
                            String friendId = friend.getString("id");
                            String friendName = friend.getString("name");
                            friendsMap.put(friendId, friendName);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    );
    List<GraphResponse> gResponseList = graphRequest.executeAsync().get();
    return friendsMap;
}
</code>```

I am currently using the same technique like in this post. By calling it like graphRequest.executeAsync().get();. But it seems like it's not working.

The function above will return the friendsMap before the graphRequest is done.

Any suggestion is appreciated.

答:
For anyone who needs the version in C#. This is what I have in my Main activity.

```<code>    public static ICallbackManager CallbackManager = CallbackManagerFactory.Create();
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        var facebookCallback = new FacebookCallback<LoginResult>
        {
            HandleSuccess = async shareResult =>
            {
                Bundle parameters = new Bundle();
                parameters.PutString("fields", "id,name,link,email,picture.type(normal),friends");

                GraphRequest request = new GraphRequest(
                    shareResult.AccessToken,
                    "/me",
                    parameters, HttpMethod.Get, new OnGraphResulCallback());

                await Task.Run(() =>
                {
                    var fbResponse = JsonConvert.DeserializeObject<FbResponse>(request.ExecuteAndWait().RawResponse);
                });
            },
            HandleCancel = () =>
            {
                Console.WriteLine("HelloFacebook: Canceled");
            },
            HandleError = shareError =>
            {
                Console.WriteLine("HelloFacebook: Error: {0}", shareError);
            }
        };

        // fb init
        FacebookSdk.SdkInitialize(this.ApplicationContext);
        LoginManager.Instance.RegisterCallback(MainActivity.CallbackManager, facebookCallback);

        Forms.Init(this, bundle);
        LoadApplication(App.Instance);
    }
</code>```

and here are the helper classes:

```<code>public class FacebookCallback<TResult> : Java.Lang.Object, IFacebookCallback where TResult : Java.Lang.Object
{
    public Action HandleCancel { get; set; }
    public Action<FacebookException> HandleError { get; set; }
    public Action<TResult> HandleSuccess { get; set; }

    public void OnCancel()
    {
        HandleCancel.Invoke();
    }

    public void OnError(FacebookException error)
    {
        HandleError.Invoke(error);
    }

    public void OnSuccess(Java.Lang.Object result)
    {
        HandleSuccess.Invoke(result.JavaCast<TResult>());
    }
}

public class FbResponse
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Picture Picture { get; set; }
    public Friends Friends { get; set; }
    public string Email { get; set; }
}
public class Friends
{
    public List<FriendsData> Data { get; set; }
    public Paging Paging { get; set; }
    public Summary Summary { get; set; }
}
public class Summary
{
    public int Total_Count { get; set; }
}
public class Paging
{
    public Cursors Cursors { get; set; }
}
public class Cursors
{
    public string Before { get; set; }
    public string After { get; set; }
}
public class FriendsData
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Picture
{
    public PictureData Data { get; set; }
}
public class PictureData
{
    public bool Is_Silhouette { get; set; }
    public string Url { get; set; }
}
</code>```

Body:
I am using facebook graph request to retrieve friends list. But, How can I get to create a function and return it after the call graphRequest.executeAsync() is done?.

private Map<String, String> getFacebookFriends(AccessToken accessToken, Profile profile) throws InterruptedException, ExecutionException {
    final Map<String, String> friendsMap = new HashMap<>();
    GraphRequest graphRequest = new GraphRequest(accessToken, "/me/friends", null, HttpMethod.GET,
            new GraphRequest.Callback() {
                public void onCompleted(GraphResponse response) {
                    JSONObject jGraphObj = response.getJSONObject();
                    try {
                        JSONArray friendsData = jGraphObj.getJSONArray("data");
                        for (int i = 0; i < friendsData.length(); i++) {
                            JSONObject friend = friendsData.getJSONObject(i);
                            String friendId = friend.getString("id");
                            String friendName = friend.getString("name");
                            friendsMap.put(friendId, friendName);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
    );
    List<GraphResponse> gResponseList = graphRequest.executeAsync().get();
    return friendsMap;
}

I am currently using the same technique like in this post. By calling it like graphRequest.executeAsync().get();. But it seems like it's not working.

The function above will return the friendsMap before the graphRequest is done.

Any suggestion is appreciated.

Body:
For anyone who needs the version in C#. This is what I have in my Main activity.

    public static ICallbackManager CallbackManager = CallbackManagerFactory.Create();
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        var facebookCallback = new FacebookCallback<LoginResult>
        {
            HandleSuccess = async shareResult =>
            {
                Bundle parameters = new Bundle();
                parameters.PutString("fields", "id,name,link,email,picture.type(normal),friends");

                GraphRequest request = new GraphRequest(
                    shareResult.AccessToken,
                    "/me",
                    parameters, HttpMethod.Get, new OnGraphResulCallback());

                await Task.Run(() =>
                {
                    var fbResponse = JsonConvert.DeserializeObject<FbResponse>(request.ExecuteAndWait().RawResponse);
                });
            },
            HandleCancel = () =>
            {
                Console.WriteLine("HelloFacebook: Canceled");
            },
            HandleError = shareError =>
            {
                Console.WriteLine("HelloFacebook: Error: {0}", shareError);
            }
        };

        // fb init
        FacebookSdk.SdkInitialize(this.ApplicationContext);
        LoginManager.Instance.RegisterCallback(MainActivity.CallbackManager, facebookCallback);

        Forms.Init(this, bundle);
        LoadApplication(App.Instance);
    }

and here are the helper classes:

public class FacebookCallback<TResult> : Java.Lang.Object, IFacebookCallback where TResult : Java.Lang.Object
{
    public Action HandleCancel { get; set; }
    public Action<FacebookException> HandleError { get; set; }
    public Action<TResult> HandleSuccess { get; set; }

    public void OnCancel()
    {
        HandleCancel.Invoke();
    }

    public void OnError(FacebookException error)
    {
        HandleError.Invoke(error);
    }

    public void OnSuccess(Java.Lang.Object result)
    {
        HandleSuccess.Invoke(result.JavaCast<TResult>());
    }
}

public class FbResponse
{
    public long Id { get; set; }
    public string Name { get; set; }
    public Picture Picture { get; set; }
    public Friends Friends { get; set; }
    public string Email { get; set; }
}
public class Friends
{
    public List<FriendsData> Data { get; set; }
    public Paging Paging { get; set; }
    public Summary Summary { get; set; }
}
public class Summary
{
    public int Total_Count { get; set; }
}
public class Paging
{
    public Cursors Cursors { get; set; }
}
public class Cursors
{
    public string Before { get; set; }
    public string After { get; set; }
}
public class FriendsData
{
    public int Id { get; set; }
    public string Name { get; set; }
}
public class Picture
{
    public PictureData Data { get; set; }
}
public class PictureData
{
    public bool Is_Silhouette { get; set; }
    public string Url { get; set; }
}


问:
Splice() function not working as expected
I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element.

```<code>    var a = [];
    a.push("cs");
    a.push("ac");
    var curr2 = a.indexOf("ac");
    if(curr2 != -1){
        a = a.splice(curr2,1);
    }
    console.log(a);
</code>```

Expected result : ["cs"] Actual Result : ["ac"]

Can someone explain this behaviour. Thanks!

答:
That's because Splice return the elements that you removed.

Remember that Splice modifies the original Array so when you make

```<code>a = a.splice(curr2,1);
</code>```

You are storing the elements removed.

Replace that line with

```<code>a.splice(curr2,1);
</code>```

And that should solve your problem!

Body:
I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element.

    var a = [];
    a.push("cs");
    a.push("ac");
    var curr2 = a.indexOf("ac");
    if(curr2 != -1){
        a = a.splice(curr2,1);
    }
    console.log(a);

Expected result : ["cs"] Actual Result : ["ac"]

Can someone explain this behaviour. Thanks!

Body:
That's because Splice return the elements that you removed.

Remember that Splice modifies the original Array so when you make

a = a.splice(curr2,1);

You are storing the elements removed.

Replace that line with

a.splice(curr2,1);

And that should solve your problem!


问:
What does "TERMINATED" state of UserTransaction mean on Atomikos logs?

I'm using Atomikos essential transactions as my TM in my J2SE application.

I have the following code:

```<code>if (userTransaction.getStatus()== Status.STATUS_ACTIVE){
userTransaction.commit();
}
</code>```

and then I see in the logs the following exception:

java.lang.IllegalStateException:
  TM_UNIQUE_NAME0003000006 is no longer active but
  in state TERMINATED  at
  com.atomikos.icatch.imp.CoordinatorImp.addParticipant(CoordinatorImp.java:615)
  at
  com.atomikos.icatch.imp.TransactionStateHandler.addParticipant(TransactionStateHandler.java:133)
  at
  com.atomikos.icatch.imp.TransactionStateHandler.committed(TransactionStateHandler.java:347)
  at
  com.atomikos.icatch.imp.TransactionStateHandler.commit(TransactionStateHandler.java:298)
  at
  com.atomikos.icatch.imp.CompositeTransactionImp.doCommit(CompositeTransactionImp.java:319)
  at
  com.atomikos.icatch.imp.CompositeTerminatorImp.commit(CompositeTerminatorImp.java:79)
  at
  com.atomikos.icatch.jta.TransactionImp.commit(TransactionImp.java:236)
  at
  com.atomikos.icatch.jta.TransactionManagerImp.commit(TransactionManagerImp.java:496)
  at
  com.atomikos.icatch.jta.UserTransactionImp.commit(UserTransactionImp.java:129)
  at
  com.mycompany.module.view.myOtherClass.transformMpr(myOtherClass.java:57)
  at
  java.util.Observable.notifyObservers(Unknown
  Source)  at
  com.mycompany.module.model.myClass.notifyObservers(myClass.java:291)
  at
  com.mycompany.module.model.myClass.MultiStateEscalation.run(myClass.java:91)
  at
  java.util.concurrent.Executors$RunnableAdapter.call(Unknown
  Source)  at
  java.util.concurrent.FutureTask$Sync.innerRun(Unknown
  Source)  at
  java.util.concurrent.FutureTask.run(Unknown
  Source)  at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown
  Source)  at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown
  Source)  at
  java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown
  Source)  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown
  Source)  at
  java.lang.Thread.run(Unknown Source)

Where line 57 in the myOtherClass is the line where I call commit() in the above code.  userTransaction is an instance of UserTransaction.

What I can't understand is what does TERMINATED means? I couldn't find these classes in the Atomikos distribution (which is weird since their open source and I additionaly ran a text search for the string over all the sources) and terminated is not one of the statuses defined in javax.transaction.Status.

Has someone incountered this? How can I check if the userTransaction I'm holding is valid for commit?

Thanks,

Ittai

答:
TERMINATED means committed or rolled back. In your case, most likely a timeout / rollback.

Try increasing the timeout if you can.

In general, checking the transaction state does not guarantee that the next line of code can commit. Committing is an application request that can fail due to timeouts and resource issues; otherwise you wouldn't need two-phase-commit :-)

Best

ContentLicense: CC BY-SA 2.5

Body:
I'm using Atomikos essential transactions as my TM in my J2SE application.

I have the following code:

if (userTransaction.getStatus()== Status.STATUS_ACTIVE){
userTransaction.commit();
}

and then I see in the logs the following exception:

java.lang.IllegalStateException:
  TM_UNIQUE_NAME0003000006 is no longer active but
  in state TERMINATED  at
  com.atomikos.icatch.imp.CoordinatorImp.addParticipant(CoordinatorImp.java:615)
  at
  com.atomikos.icatch.imp.TransactionStateHandler.addParticipant(TransactionStateHandler.java:133)
  at
  com.atomikos.icatch.imp.TransactionStateHandler.committed(TransactionStateHandler.java:347)
  at
  com.atomikos.icatch.imp.TransactionStateHandler.commit(TransactionStateHandler.java:298)
  at
  com.atomikos.icatch.imp.CompositeTransactionImp.doCommit(CompositeTransactionImp.java:319)
  at
  com.atomikos.icatch.imp.CompositeTerminatorImp.commit(CompositeTerminatorImp.java:79)
  at
  com.atomikos.icatch.jta.TransactionImp.commit(TransactionImp.java:236)
  at
  com.atomikos.icatch.jta.TransactionManagerImp.commit(TransactionManagerImp.java:496)
  at
  com.atomikos.icatch.jta.UserTransactionImp.commit(UserTransactionImp.java:129)
  at
  com.mycompany.module.view.myOtherClass.transformMpr(myOtherClass.java:57)
  at
  java.util.Observable.notifyObservers(Unknown
  Source)  at
  com.mycompany.module.model.myClass.notifyObservers(myClass.java:291)
  at
  com.mycompany.module.model.myClass.MultiStateEscalation.run(myClass.java:91)
  at
  java.util.concurrent.Executors$RunnableAdapter.call(Unknown
  Source)  at
  java.util.concurrent.FutureTask$Sync.innerRun(Unknown
  Source)  at
  java.util.concurrent.FutureTask.run(Unknown
  Source)  at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$301(Unknown
  Source)  at
  java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(Unknown
  Source)  at
  java.util.concurrent.ThreadPoolExecutor$Worker.runTask(Unknown
  Source)  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown
  Source)  at
  java.lang.Thread.run(Unknown Source)

Where line 57 in the myOtherClass is the line where I call commit() in the above code.  userTransaction is an instance of UserTransaction.

What I can't understand is what does TERMINATED means? I couldn't find these classes in the Atomikos distribution (which is weird since their open source and I additionaly ran a text search for the string over all the sources) and terminated is not one of the statuses defined in javax.transaction.Status.

Has someone incountered this? How can I check if the userTransaction I'm holding is valid for commit?

Thanks,

Ittai


问:
PHP exec() works in command line but not in web
I'm trying to use jarun's "googler" in a PHP script in order to search YouTube and find the URL of the first result. The command I'm executing is googler --np --json -C -n 1 -w youtube.com -x <name of youtube video>, and it works perfectly on my local machine. Here is my code:

```<code><?php
exec("googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine", $results);
var_dump($results);
?>
</code>```

When I execute this in the command line, it works perfectly as it should, but when I do it via a web browser or a GET request, it does not work. I am aware that it is being executed as another user. In my case, it's the user www-data, so I gave that user full sudo permissions without a password, and did the following commands:

```<code>sudo -u pi googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine
</code>```

as well as

```<code>su - pi -c 'googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine'
</code>```

neither of these worked. Does it have to do with googler? What am I doing wrong?

When adding 2>&1 to the command, I get the following error message:

stdout encoding 'ascii' detected. googler requires utf-8 to work properly. The wrong encoding may be due to a non-UTF-8 locale or an improper PYTHONIOENCODING. (For the record, your locale language is and locale encoding is ; your PYTHONIOENCODING is not set.) Please set a UTF-8 locale (e.g., en_US.UTF-8) or set PYTHONIOENCODING to utf-8.

答: You must remove exec from the disable_functions parameter in the php.ini file for your server module installation of PHP (which is separate from your CLI installation). It is typically disabled by default for the server module.

Body:
I'm trying to use jarun's "googler" in a PHP script in order to search YouTube and find the URL of the first result. The command I'm executing is googler --np --json -C -n 1 -w youtube.com -x <name of youtube video>, and it works perfectly on my local machine. Here is my code:

<?php
exec("googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine", $results);
var_dump($results);
?>

When I execute this in the command line, it works perfectly as it should, but when I do it via a web browser or a GET request, it does not work. I am aware that it is being executed as another user. In my case, it's the user www-data, so I gave that user full sudo permissions without a password, and did the following commands:

sudo -u pi googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine

as well as

su - pi -c 'googler --np --json -C -n 1 -w youtube.com -x thomas the dank engine'

neither of these worked. Does it have to do with googler? What am I doing wrong?

When adding 2>&1 to the command, I get the following error message:

stdout encoding 'ascii' detected. googler requires utf-8 to work properly. The wrong encoding may be due to a non-UTF-8 locale or an improper PYTHONIOENCODING. (For the record, your locale language is and locale encoding is ; your PYTHONIOENCODING is not set.) Please set a UTF-8 locale (e.g., en_US.UTF-8) or set PYTHONIOENCODING to utf-8.


问:
Remove last item of a list using javascript
Hello I have a simple unordered list and I would like to remove the last item on click of a button. I read somewhere that pop(); will do this but I am having trouble getting it working.

Here is what I have so far:

```<code><button id="remove">remove item</button>

<ul id="list">
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
</ul>

var listItems = document.getElementById("list").getElementsByTagName("li");
var removeButton = document.getElementById("remove");

removeButton.addEventListener("click", removeItem);

function removeItem() {
    listItems.pop();
}
</code>```

Here is the error I'm getting:

Uncaught TypeError: listItems.pop is not a function at HTMLButtonElement.removeItem

Which is weird because when I type listItems in the console I am getting the correct array:

listItems
(7) [li, li, li, li, li, li, li]

jsfiddle

Anyone have any suggestions? I dont need to use .pop() any method that works will be fine

答:
The function getElementsByTagName returns an HTMLCollection which isn't an array.

See: https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

<button id="remove">remove item</button>

<input type="text">1

<input type="text">2

<input type="text">3

<input type="text">4

<input type="text">5

```

Body:
Hello I have a simple unordered list and I would like to remove the last item on click of a button. I read somewhere that pop(); will do this but I am having trouble getting it working.

Here is what I have so far:

<button id="remove">remove item</button>

<input type="text">

<input type="text">

<input type="text">

<input type="text">

<input type="text">

var listItems = document.getElementById("list").getElementsByTagName("li");
var removeButton = document.getElementById("remove");

removeButton.addEventListener("click", removeItem);

function removeItem() {
    listItems.pop();
}

Here is the error I'm getting:

Uncaught TypeError: listItems.pop is not a function at HTMLButtonElement.removeItem

Which is weird because when I type listItems in the console I am getting the correct array:

listItems
(7) [li, li, li, li, li, li, li]

jsfiddle

Anyone have any suggestions? I dont need to use .pop() any method that works will be fine

Body:
The function getElementsByTagName returns an HTMLCollection which isn't an array.

See: https://developer.mozilla.org/en-US/docs/Web/API/Element/getElementsByTagName

<button id="remove">remove item</button>

<ul id="list">
    <li><input type="text">1</li>
    <li><input type="text">2</li>
    <li><input type="text">3</li>
    <li><input type="text">4</li>
    <li><input type="text">5</li>
</ul>

<script>

var removeButton = document.getElementById("remove");

removeButton.addEventListener("click", removeItem);

function removeItem() {
    var list=document.getElementById("list");
    var listItems = list.getElementsByTagName("li");

    var last=listItems[listItems.length-1];
    list.removeChild(last);
}

</script>


问:
Webgl / Javascript : canvas texture content copy to another context texture object
I'm trying to copy the content (display of an image) of my first webgl context to a texture from another webgl context.
I'm using texImage2D function with a canvas element as a source, getting no errors, but it renders nothing but black.
I don't know what I'm missing, so any kind of help is greatly appreciated.
I'm looking at a webgl1 solution, and using Chrome.

var canvas1;
var texture1;
var image;
var shaderProgram;
var vertex_buffer;
var texture_buffer;
var aVertLocation;
var aTexLocation;
var vertices = [];
var texCoords = [];

var gl;
var gl2;
var canvas2;
var texture2;
var shaderProgram2;
var vertex_buffer2;
var texture_buffer2;
var index_Buffer2;
var aVertLocation2;
var aTexLocation2;
var vertices2 = [];
var texCoords2 = [];

indices = [0, 1, 2, 0, 2, 3];
vertices = [-1, -1, 1, -1, 1, 1, -1, 1];
texCoords = [0, 0, 1, 0, 1, 1, 0, 1];

function initApp()
{
  initWebGL();

  image = new Image();
  image.onload = function(){
    render();
    render2();
  }
  image.crossOrigin = '';
  image.src = 'https://i.imgur.com/ZKMnXce.png';
}

function initWebGL()
{

  canvas1 = document.getElementById('glCanvas1');
  gl = canvas1.getContext('webgl');

  /*====================== Shaders =======================*/

  // Vertex shader source code
  var vertCode =
    'attribute vec2 coordinates;' +
    'attribute vec2 aTexCoord;' +
    'varying highp vec2 vTexCoord;' +
    'void main(void) {' +
      'gl_Position = vec4(coordinates,1.0,1.0);' +
      'vTexCoord = aTexCoord;' +
    '}';
  var vertShader = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(vertShader, vertCode);
  gl.compileShader(vertShader);

  //fragment shader source code
  var fragCode =
    'uniform sampler2D texture;' +
    'varying highp vec2 vTexCoord;' +
    'void main(void) {' +
      ' gl_FragColor = texture2D(texture, vTexCoord);' +
    '}';
  var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(fragShader, fragCode);
  gl.compileShader(fragShader);

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertShader);
  gl.attachShader(shaderProgram, fragShader);
  gl.deleteShader( vertShader );
  gl.deleteShader( fragShader );
  gl.linkProgram(shaderProgram);
  gl.useProgram(shaderProgram);

  aVertLocation = gl.getAttribLocation(shaderProgram, "coordinates");
  aTexLocation = gl.getAttribLocation(shaderProgram, "aTexCoord");

  vertex_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
  gl.enableVertexAttribArray(aVertLocation);
  gl.vertexAttribPointer(aVertLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  texture_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, texture_buffer);
  gl.enableVertexAttribArray(aTexLocation);
  gl.vertexAttribPointer(aTexLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  index_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

  texture1 = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );
  gl.bindTexture(gl.TEXTURE_2D, null);

  //==========================================================//

  canvas2 = document.getElementById('glCanvas2');
  gl2 = canvas2.getContext('webgl');
  var vertShader2 = gl2.createShader(gl2.VERTEX_SHADER);
  var fragShader2 = gl2.createShader(gl2.FRAGMENT_SHADER);
  gl2.shaderSource(vertShader2, vertCode);
  gl2.shaderSource(fragShader2, fragCode);
  gl2.compileShader(vertShader2);
  gl2.compileShader(fragShader2);

  shaderProgram2 = gl2.createProgram();
  gl2.attachShader(shaderProgram2, vertShader2);
  gl2.attachShader(shaderProgram2, fragShader2);
  gl2.deleteShader( vertShader2 );
  gl2.deleteShader( fragShader2 );
  gl2.linkProgram(shaderProgram2);
  gl2.useProgram(shaderProgram2);

  aVertLocation2 = gl2.getAttribLocation(shaderProgram2, "coordinates");
  aTexLocation2 = gl2.getAttribLocation(shaderProgram2, "aTexCoord");

  vertex_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, vertex_buffer2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.vertexAttribPointer(aVertLocation2, 2, gl2.BYTE, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(vertices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  texture_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, texture_buffer2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.vertexAttribPointer(aTexLocation, 2, gl2.BYTE, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(texCoords), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  index_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.bufferData(gl2.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, null);

  texture2 = gl2.createTexture();
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.uniform1i( gl2.getUniformLocation( shaderProgram2, 'texture' ), 0 );
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function updateTexture()
{
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.generateMipmap(gl.TEXTURE_2D);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function render()
{
  if ( !shaderProgram ) return;
  updateTexture();
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.enableVertexAttribArray(aVertLocation);
  gl.enableVertexAttribArray(aTexLocation);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer)
  gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
  gl.disableVertexAttribArray(aVertLocation);
  gl.disableVertexAttribArray(aTexLocation);

}

function updateTexture2()
{
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, canvas1);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
  gl2.generateMipmap(gl2.TEXTURE_2D);
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function render2()
{
  if ( !shaderProgram2 ) return;
  updateTexture2();
  gl2.clearColor(0.0, 0.0, 0.0, 1.0);
  gl2.clear( gl2.COLOR_BUFFER_BIT | gl2.DEPTH_BUFFER_BIT );
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.drawElements(gl2.TRIANGLES, 6, gl2.UNSIGNED_SHORT,0);
  gl2.disableVertexAttribArray(aVertLocation2);
  gl2.disableVertexAttribArray(aTexLocation2);
}

document.addEventListener('DOMContentLoaded', initApp);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="glCanvas1" width="128" height="128" ></canvas>
<canvas id="glCanvas2" width="128" height="128" ></canvas></code>```

Thanks in advance :)

答:
The copy is working just fine. What's not working is your code

Here's what I did to find the bug

First moved the code to snippet so I could actually run it. Please use snippets in the future.

Next I used an image from imgur. Because that image is on another domain I needed to set crossOrigin. Fortunately imgur supports CORS allowing WebGL to use the image. If it was me I wouldn't have used an image because that part is not important. A single colored pixel would show the issue just as well and remove the need for a image

Now that the code is running and the bug shown the first thing to do was to change this line in updateTexture2

```<code>gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, canvas1);
</code>```

to just use the same image

```<code>gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, image);
</code>```

The second canvas was still black showing the issue had nothing to with copying a canvas.

So, next I edited the fragment shader to this

```<code>  gl_FragColor = vec4(1,0,0,1);
</code>```

the second canvas was still black. This showed the issue had nothing to do with textures at all. The code was not drawing anything visible the second canvas.

So, looking at stuff related to the vertex shader the bug was these 2 lines

```<code>gl2.vertexAttribPointer(aVertLocation2, 2, gl2.BYTE, false, 0, 0);

...

gl2.vertexAttribPointer(aTexLocation, 2, gl2.BYTE, false, 0, 0);
</code>```

needed to be gl.FLOAT not gl.BYTE

Some other random comments.

I used multi line template literals for the shaders

There's no reason to call gl.generateMips if your filtering is set not to use mips

This code has no meaning

```<code>gl.bindTexture(gl.TEXTURE_2D, texture1);
gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );
gl.bindTexture(gl.TEXTURE_2D, null);
</code>```

There's no reason to bind the texture here. gl.uniform1i just sets an integer value to the uniform shaderProgram. It does not record anything about the texture itself so just

```<code>gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );
</code>```

Without the the bindTexture calls would be fine. On top of that uniforms default to 0 so you don't really need the gl.uniform1i call. On the other hand maybe you had that their to set it to something other than 0 later.

Finally because WebGL can not share resources across canvases (at least as of July 2017), then, depending on what you're making you might want to consider using a single canvas. See the last solution in this answer

var canvas1;
var texture1;
var image;
var shaderProgram;
var vertex_buffer;
var texture_buffer;
var aVertLocation;
var aTexLocation;
var vertices = [];
var texCoords = [];

var gl;
var gl2;
var canvas2;
var texture2;
var shaderProgram2;
var vertex_buffer2;
var texture_buffer2;
var index_Buffer2;
var aVertLocation2;
var aTexLocation2;
var vertices2 = [];
var texCoords2 = [];

indices = [0, 1, 2, 0, 2, 3];
vertices = [-1, -1, 1, -1, 1, 1, -1, 1];
texCoords = [0, 0, 1, 0, 1, 1, 0, 1];

function initApp()
{
  initWebGL();

  image = new Image();
  image.onload = function(){
    render();
    render2();
  }
  image.crossOrigin = '';
  image.src = 'https://i.imgur.com/ZKMnXce.png';
}

function initWebGL()
{

  canvas1 = document.getElementById('glCanvas1');
  gl = canvas1.getContext('webgl');

  /*====================== Shaders =======================*/

  // Vertex shader source code
  var vertCode = `
    attribute vec2 coordinates;
    attribute vec2 aTexCoord;
    varying highp vec2 vTexCoord;
    void main(void) {
      gl_Position = vec4(coordinates,1.0,1.0);
      vTexCoord = aTexCoord;
    }
  `;
  var vertShader = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(vertShader, vertCode);
  gl.compileShader(vertShader);

  //fragment shader source code
  var fragCode = `
    precision mediump float;
    uniform sampler2D texture;
    varying highp vec2 vTexCoord;
    void main(void) {
       gl_FragColor = texture2D(texture, vTexCoord);
    }
  `;
  var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(fragShader, fragCode);
  gl.compileShader(fragShader);

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertShader);
  gl.attachShader(shaderProgram, fragShader);
  gl.deleteShader( vertShader );
  gl.deleteShader( fragShader );
  gl.linkProgram(shaderProgram);
  gl.useProgram(shaderProgram);

  aVertLocation = gl.getAttribLocation(shaderProgram, "coordinates");
  aTexLocation = gl.getAttribLocation(shaderProgram, "aTexCoord");

  vertex_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
  gl.enableVertexAttribArray(aVertLocation);
  gl.vertexAttribPointer(aVertLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  texture_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, texture_buffer);
  gl.enableVertexAttribArray(aTexLocation);
  gl.vertexAttribPointer(aTexLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  index_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

  texture1 = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );
  gl.bindTexture(gl.TEXTURE_2D, null);

  //==========================================================//

  canvas2 = document.getElementById('glCanvas2');
  gl2 = canvas2.getContext('webgl');
  var vertShader2 = gl2.createShader(gl2.VERTEX_SHADER);
  var fragShader2 = gl2.createShader(gl2.FRAGMENT_SHADER);
  gl2.shaderSource(vertShader2, vertCode);
  gl2.shaderSource(fragShader2, fragCode);
  gl2.compileShader(vertShader2);
  gl2.compileShader(fragShader2);

  shaderProgram2 = gl2.createProgram();
  gl2.attachShader(shaderProgram2, vertShader2);
  gl2.attachShader(shaderProgram2, fragShader2);
  gl2.deleteShader( vertShader2 );
  gl2.deleteShader( fragShader2 );
  gl2.linkProgram(shaderProgram2);
  gl2.useProgram(shaderProgram2);

  aVertLocation2 = gl2.getAttribLocation(shaderProgram2, "coordinates");
  aTexLocation2 = gl2.getAttribLocation(shaderProgram2, "aTexCoord");

  vertex_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, vertex_buffer2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.vertexAttribPointer(aVertLocation2, 2, gl2.FLOAT, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(vertices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  texture_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, texture_buffer2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.vertexAttribPointer(aTexLocation, 2, gl2.FLOAT, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(texCoords), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  index_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.bufferData(gl2.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, null);

  texture2 = gl2.createTexture();
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.uniform1i( gl2.getUniformLocation( shaderProgram2, 'texture' ), 0 );
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function updateTexture()
{
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.generateMipmap(gl.TEXTURE_2D);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function render()
{
  if ( !shaderProgram ) return;
  updateTexture();
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.enableVertexAttribArray(aVertLocation);
  gl.enableVertexAttribArray(aTexLocation);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer)
  gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
  gl.disableVertexAttribArray(aVertLocation);
  gl.disableVertexAttribArray(aTexLocation);

}

function updateTexture2()
{
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, canvas1);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
  gl2.generateMipmap(gl2.TEXTURE_2D);
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function render2()
{
  if ( !shaderProgram2 ) return;
  updateTexture2();
  gl2.clearColor(0.0, 0.0, 0.0, 1.0);
  gl2.clear( gl2.COLOR_BUFFER_BIT | gl2.DEPTH_BUFFER_BIT );
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.drawElements(gl2.TRIANGLES, 6, gl2.UNSIGNED_SHORT,0);
  gl2.disableVertexAttribArray(aVertLocation2);
  gl2.disableVertexAttribArray(aTexLocation2);
}

document.addEventListener('DOMContentLoaded', initApp);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="glCanvas1" width="128" height="128" ></canvas>
<canvas id="glCanvas2" width="128" height="128" ></canvas></code>```

Body:
I'm trying to copy the content (display of an image) of my first webgl context to a texture from another webgl context.
I'm using texImage2D function with a canvas element as a source, getting no errors, but it renders nothing but black.
I don't know what I'm missing, so any kind of help is greatly appreciated.
I'm looking at a webgl1 solution, and using Chrome.

var canvas1;
var texture1;
var image;
var shaderProgram;
var vertex_buffer;
var texture_buffer;
var aVertLocation;
var aTexLocation;
var vertices = [];
var texCoords = [];

var gl;
var gl2;
var canvas2;
var texture2;
var shaderProgram2;
var vertex_buffer2;
var texture_buffer2;
var index_Buffer2;
var aVertLocation2;
var aTexLocation2;
var vertices2 = [];
var texCoords2 = [];

indices = [0, 1, 2, 0, 2, 3];
vertices = [-1, -1, 1, -1, 1, 1, -1, 1];
texCoords = [0, 0, 1, 0, 1, 1, 0, 1];

function initApp()
{
  initWebGL();

  image = new Image();
  image.onload = function(){
    render();
    render2();
  }
  image.crossOrigin = '';
  image.src = 'https://i.imgur.com/ZKMnXce.png';
}

function initWebGL()
{

  canvas1 = document.getElementById('glCanvas1');
  gl = canvas1.getContext('webgl');

  /*====================== Shaders =======================*/

  // Vertex shader source code
  var vertCode =
    'attribute vec2 coordinates;' +
    'attribute vec2 aTexCoord;' +
    'varying highp vec2 vTexCoord;' +
    'void main(void) {' +
      'gl_Position = vec4(coordinates,1.0,1.0);' +
      'vTexCoord = aTexCoord;' +
    '}';
  var vertShader = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(vertShader, vertCode);
  gl.compileShader(vertShader);

  //fragment shader source code
  var fragCode =
    'uniform sampler2D texture;' +
    'varying highp vec2 vTexCoord;' +
    'void main(void) {' +
      ' gl_FragColor = texture2D(texture, vTexCoord);' +
    '}';
  var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(fragShader, fragCode);
  gl.compileShader(fragShader);

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertShader);
  gl.attachShader(shaderProgram, fragShader);
  gl.deleteShader( vertShader );
  gl.deleteShader( fragShader );
  gl.linkProgram(shaderProgram);
  gl.useProgram(shaderProgram);

  aVertLocation = gl.getAttribLocation(shaderProgram, "coordinates");
  aTexLocation = gl.getAttribLocation(shaderProgram, "aTexCoord");

  vertex_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
  gl.enableVertexAttribArray(aVertLocation);
  gl.vertexAttribPointer(aVertLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  texture_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, texture_buffer);
  gl.enableVertexAttribArray(aTexLocation);
  gl.vertexAttribPointer(aTexLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  index_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

  texture1 = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );
  gl.bindTexture(gl.TEXTURE_2D, null);

  //==========================================================//

  canvas2 = document.getElementById('glCanvas2');
  gl2 = canvas2.getContext('webgl');
  var vertShader2 = gl2.createShader(gl2.VERTEX_SHADER);
  var fragShader2 = gl2.createShader(gl2.FRAGMENT_SHADER);
  gl2.shaderSource(vertShader2, vertCode);
  gl2.shaderSource(fragShader2, fragCode);
  gl2.compileShader(vertShader2);
  gl2.compileShader(fragShader2);

  shaderProgram2 = gl2.createProgram();
  gl2.attachShader(shaderProgram2, vertShader2);
  gl2.attachShader(shaderProgram2, fragShader2);
  gl2.deleteShader( vertShader2 );
  gl2.deleteShader( fragShader2 );
  gl2.linkProgram(shaderProgram2);
  gl2.useProgram(shaderProgram2);

  aVertLocation2 = gl2.getAttribLocation(shaderProgram2, "coordinates");
  aTexLocation2 = gl2.getAttribLocation(shaderProgram2, "aTexCoord");

  vertex_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, vertex_buffer2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.vertexAttribPointer(aVertLocation2, 2, gl2.BYTE, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(vertices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  texture_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, texture_buffer2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.vertexAttribPointer(aTexLocation, 2, gl2.BYTE, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(texCoords), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  index_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.bufferData(gl2.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, null);

  texture2 = gl2.createTexture();
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.uniform1i( gl2.getUniformLocation( shaderProgram2, 'texture' ), 0 );
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function updateTexture()
{
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.generateMipmap(gl.TEXTURE_2D);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function render()
{
  if ( !shaderProgram ) return;
  updateTexture();
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.enableVertexAttribArray(aVertLocation);
  gl.enableVertexAttribArray(aTexLocation);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer)
  gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
  gl.disableVertexAttribArray(aVertLocation);
  gl.disableVertexAttribArray(aTexLocation);

}

function updateTexture2()
{
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, canvas1);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
  gl2.generateMipmap(gl2.TEXTURE_2D);
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function render2()
{
  if ( !shaderProgram2 ) return;
  updateTexture2();
  gl2.clearColor(0.0, 0.0, 0.0, 1.0);
  gl2.clear( gl2.COLOR_BUFFER_BIT | gl2.DEPTH_BUFFER_BIT );
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.drawElements(gl2.TRIANGLES, 6, gl2.UNSIGNED_SHORT,0);
  gl2.disableVertexAttribArray(aVertLocation2);
  gl2.disableVertexAttribArray(aTexLocation2);
}

document.addEventListener('DOMContentLoaded', initApp);

<canvas id="glCanvas1" width="128" height="128" ></canvas>
<canvas id="glCanvas2" width="128" height="128" ></canvas>

Thanks in advance :)

Body:
The copy is working just fine. What's not working is your code

Here's what I did to find the bug

First moved the code to snippet so I could actually run it. Please use snippets in the future.

Next I used an image from imgur. Because that image is on another domain I needed to set crossOrigin. Fortunately imgur supports CORS allowing WebGL to use the image. If it was me I wouldn't have used an image because that part is not important. A single colored pixel would show the issue just as well and remove the need for a image

Now that the code is running and the bug shown the first thing to do was to change this line in updateTexture2

gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, canvas1);

to just use the same image

gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, image);

The second canvas was still black showing the issue had nothing to with copying a canvas.

So, next I edited the fragment shader to this

  gl_FragColor = vec4(1,0,0,1);

the second canvas was still black. This showed the issue had nothing to do with textures at all. The code was not drawing anything visible the second canvas.

So, looking at stuff related to the vertex shader the bug was these 2 lines

gl2.vertexAttribPointer(aVertLocation2, 2, gl2.BYTE, false, 0, 0);

...

gl2.vertexAttribPointer(aTexLocation, 2, gl2.BYTE, false, 0, 0);

needed to be gl.FLOAT not gl.BYTE

Some other random comments.

I used multi line template literals for the shaders

There's no reason to call gl.generateMips if your filtering is set not to use mips

This code has no meaning

gl.bindTexture(gl.TEXTURE_2D, texture1);
gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );
gl.bindTexture(gl.TEXTURE_2D, null);

There's no reason to bind the texture here. gl.uniform1i just sets an integer value to the uniform shaderProgram. It does not record anything about the texture itself so just

gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );

Without the the bindTexture calls would be fine. On top of that uniforms default to 0 so you don't really need the gl.uniform1i call. On the other hand maybe you had that their to set it to something other than 0 later.

Finally because WebGL can not share resources across canvases (at least as of July 2017), then, depending on what you're making you might want to consider using a single canvas. See the last solution in this answer

var canvas1;
var texture1;
var image;
var shaderProgram;
var vertex_buffer;
var texture_buffer;
var aVertLocation;
var aTexLocation;
var vertices = [];
var texCoords = [];

var gl;
var gl2;
var canvas2;
var texture2;
var shaderProgram2;
var vertex_buffer2;
var texture_buffer2;
var index_Buffer2;
var aVertLocation2;
var aTexLocation2;
var vertices2 = [];
var texCoords2 = [];

indices = [0, 1, 2, 0, 2, 3];
vertices = [-1, -1, 1, -1, 1, 1, -1, 1];
texCoords = [0, 0, 1, 0, 1, 1, 0, 1];

function initApp()
{
  initWebGL();

  image = new Image();
  image.onload = function(){
    render();
    render2();
  }
  image.crossOrigin = '';
  image.src = 'https://i.imgur.com/ZKMnXce.png';
}

function initWebGL()
{

  canvas1 = document.getElementById('glCanvas1');
  gl = canvas1.getContext('webgl');

  /*====================== Shaders =======================*/

  // Vertex shader source code
  var vertCode = `
    attribute vec2 coordinates;
    attribute vec2 aTexCoord;
    varying highp vec2 vTexCoord;
    void main(void) {
      gl_Position = vec4(coordinates,1.0,1.0);
      vTexCoord = aTexCoord;
    }
  `;
  var vertShader = gl.createShader(gl.VERTEX_SHADER);
  gl.shaderSource(vertShader, vertCode);
  gl.compileShader(vertShader);

  //fragment shader source code
  var fragCode = `
    precision mediump float;
    uniform sampler2D texture;
    varying highp vec2 vTexCoord;
    void main(void) {
       gl_FragColor = texture2D(texture, vTexCoord);
    }
  `;
  var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
  gl.shaderSource(fragShader, fragCode);
  gl.compileShader(fragShader);

  shaderProgram = gl.createProgram();
  gl.attachShader(shaderProgram, vertShader);
  gl.attachShader(shaderProgram, fragShader);
  gl.deleteShader( vertShader );
  gl.deleteShader( fragShader );
  gl.linkProgram(shaderProgram);
  gl.useProgram(shaderProgram);

  aVertLocation = gl.getAttribLocation(shaderProgram, "coordinates");
  aTexLocation = gl.getAttribLocation(shaderProgram, "aTexCoord");

  vertex_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
  gl.enableVertexAttribArray(aVertLocation);
  gl.vertexAttribPointer(aVertLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  texture_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ARRAY_BUFFER, texture_buffer);
  gl.enableVertexAttribArray(aTexLocation);
  gl.vertexAttribPointer(aTexLocation, 2, gl.FLOAT, false, 0, 0);
  gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(texCoords), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ARRAY_BUFFER, null);

  index_buffer = gl.createBuffer();
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
  gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);

  texture1 = gl.createTexture();
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.uniform1i( gl.getUniformLocation( shaderProgram, 'texture' ), 0 );
  gl.bindTexture(gl.TEXTURE_2D, null);

  //==========================================================//

  canvas2 = document.getElementById('glCanvas2');
  gl2 = canvas2.getContext('webgl');
  var vertShader2 = gl2.createShader(gl2.VERTEX_SHADER);
  var fragShader2 = gl2.createShader(gl2.FRAGMENT_SHADER);
  gl2.shaderSource(vertShader2, vertCode);
  gl2.shaderSource(fragShader2, fragCode);
  gl2.compileShader(vertShader2);
  gl2.compileShader(fragShader2);

  shaderProgram2 = gl2.createProgram();
  gl2.attachShader(shaderProgram2, vertShader2);
  gl2.attachShader(shaderProgram2, fragShader2);
  gl2.deleteShader( vertShader2 );
  gl2.deleteShader( fragShader2 );
  gl2.linkProgram(shaderProgram2);
  gl2.useProgram(shaderProgram2);

  aVertLocation2 = gl2.getAttribLocation(shaderProgram2, "coordinates");
  aTexLocation2 = gl2.getAttribLocation(shaderProgram2, "aTexCoord");

  vertex_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, vertex_buffer2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.vertexAttribPointer(aVertLocation2, 2, gl2.FLOAT, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(vertices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  texture_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ARRAY_BUFFER, texture_buffer2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.vertexAttribPointer(aTexLocation, 2, gl2.FLOAT, false, 0, 0);
  gl2.bufferData(gl2.ARRAY_BUFFER, new Float32Array(texCoords), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ARRAY_BUFFER, null);

  index_buffer2 = gl2.createBuffer();
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.bufferData(gl2.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl2.STATIC_DRAW);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, null);

  texture2 = gl2.createTexture();
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.uniform1i( gl2.getUniformLocation( shaderProgram2, 'texture' ), 0 );
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function updateTexture()
{
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.pixelStorei(gl.UNPACK_COLORSPACE_CONVERSION_WEBGL, gl.NONE);
  gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  gl.generateMipmap(gl.TEXTURE_2D);
  gl.bindTexture(gl.TEXTURE_2D, null);
}

function render()
{
  if ( !shaderProgram ) return;
  updateTexture();
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT );
  gl.bindTexture(gl.TEXTURE_2D, texture1);
  gl.enableVertexAttribArray(aVertLocation);
  gl.enableVertexAttribArray(aTexLocation);
  gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer)
  gl.drawElements(gl.TRIANGLES, 6, gl.UNSIGNED_SHORT, 0);
  gl.disableVertexAttribArray(aVertLocation);
  gl.disableVertexAttribArray(aTexLocation);

}

function updateTexture2()
{
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.texImage2D(gl2.TEXTURE_2D, 0, gl2.RGBA, gl2.RGBA, gl2.UNSIGNED_BYTE, canvas1);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MAG_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_MIN_FILTER, gl2.LINEAR);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_S, gl2.CLAMP_TO_EDGE);
  gl2.texParameteri(gl2.TEXTURE_2D, gl2.TEXTURE_WRAP_T, gl2.CLAMP_TO_EDGE);
  gl2.generateMipmap(gl2.TEXTURE_2D);
  gl2.bindTexture(gl2.TEXTURE_2D, null);
}

function render2()
{
  if ( !shaderProgram2 ) return;
  updateTexture2();
  gl2.clearColor(0.0, 0.0, 0.0, 1.0);
  gl2.clear( gl2.COLOR_BUFFER_BIT | gl2.DEPTH_BUFFER_BIT );
  gl2.bindTexture(gl2.TEXTURE_2D, texture2);
  gl2.enableVertexAttribArray(aVertLocation2);
  gl2.enableVertexAttribArray(aTexLocation2);
  gl2.bindBuffer(gl2.ELEMENT_ARRAY_BUFFER, index_buffer2);
  gl2.drawElements(gl2.TRIANGLES, 6, gl2.UNSIGNED_SHORT,0);
  gl2.disableVertexAttribArray(aVertLocation2);
  gl2.disableVertexAttribArray(aTexLocation2);
}

document.addEventListener('DOMContentLoaded', initApp);

<canvas id="glCanvas1" width="128" height="128" ></canvas>
<canvas id="glCanvas2" width="128" height="128" ></canvas>


答:
pop is an array function. You'll have to remove the list item like this:

```<code>function removeItem() {
    var last = listItems[listItems.length - 1];
    last.parentNode.removeChild(last);
}
</code>```

Note 1: We don't need to decrement listItems.length because it's a live HTMLCollection (returned by getElementsByTagName) that reflects the DOM (if an element is removed from the DOM then it gets automatically removed from the collection).

Note 2: You may want to check if the collection is empty before attempting to remove the last item (which won't exist if it's empty). Check the example bellow to see how.

Example:

var listItems = document.getElementById("list").getElementsByTagName("li");
var removeButton = document.getElementById("remove");

removeButton.addEventListener("click", removeItem);

function removeItem() {
    if(listItems.length === 0) return;           // if there is no items in listItems then quit the function (don't attempt to remove what doesn't exist)

    var last = listItems[listItems.length - 1];
    last.parentNode.removeChild(last);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button id="remove">remove item</button>

<ul id="list">
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
</ul></code>```

Title: Remove last item of a list using javascript

Body:
pop is an array function. You'll have to remove the list item like this:

function removeItem() {
    var last = listItems[listItems.length - 1];
    last.parentNode.removeChild(last);
}

Note 1: We don't need to decrement listItems.length because it's a live HTMLCollection (returned by getElementsByTagName) that reflects the DOM (if an element is removed from the DOM then it gets automatically removed from the collection).

Note 2: You may want to check if the collection is empty before attempting to remove the last item (which won't exist if it's empty). Check the example bellow to see how.

Example:

var listItems = document.getElementById("list").getElementsByTagName("li");
var removeButton = document.getElementById("remove");

removeButton.addEventListener("click", removeItem);

function removeItem() {
    if(listItems.length === 0) return;           // if there is no items in listItems then quit the function (don't attempt to remove what doesn't exist)

    var last = listItems[listItems.length - 1];
    last.parentNode.removeChild(last);
}

<button id="remove">remove item</button>

<ul id="list">
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
    <li><input type="text"></li>
</ul>


问:
How to create bar chart with data points in Excel?
I want to create this style of chart in Excel.

It is basically a bar chart with  has categories on the y-axis, a single dimension on the x-axis, and two points per category showing change over time. I have the data I need, however I do not know

How to create the data points on a bar chart in Excel; or

The easiest way to create a similar chart.

Thanks for your help.

答:
consider the following screenshot:

create an XY scatter chart

Add a series with Y Value for Y and StartValue for X

Add a series with Y Value for Y and End Point for X

Add horizontal error bars set to minus, no cap, custom value and select the Difference values from column E

format the error bars to be thick and grey

hide the Y axis labels (set to "none")

add a helper series with Y value for Y and Y Labels from column G for X

add data labels to this series and use the text from column A. With Excel 2013 and later you can use "Value from cells". With earlier versions you need to edit each label and point it to the cell with the text.

format the Y labels series to have no marker. The marker is still visible in the screenshot, so you can see where it needs to sit.

not in the screenshot: Add data labels to the End point series and use the values from column F.

not in the screenshot: format the markers for Start Value and End Point to be a bit bigger and the desired color.


问:
Table striping rows in CSS Grid
I'm trying to replace a grid of data & interactive components that had been set up in Bootstrap with a CSS Grid-based layout.

I was able to replicate the grid, but am having trouble getting something like table striping working.From what I understand of CSS Grid, since I know the number of columns that will be displayed ahead of time but not the number of rows (dynamically generated data from the server), I need to use grid-template-columns: repeat(3, auto);, and each cell must be a direct child of the wrapper div.

I've tried using nth-child to get the effect I want, but can't figure out what selector would let me target a dynamic range of elements.

Is there a better way to set up a grid layout using CSS Grid when the number of rows is unknown ahead of time?

Here's a fiddle with what I have so far, which includes all the code below. In my real project, the rows are dynamically generated and there are 5 columns right now- though that may change in the future.

.grid-table {
  display: grid;
  display: -ms-grid;
  grid-template-columns: repeat(3, auto);
  -ms-grid-template-columns: repeat(3, auto);
}

.grid-table :nth-child(-n+3) {
  background-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-table">
  <span>Room Name</span>
  <span>Start Date</span>
  <span>End Date</span>

  <span>Room 100</span>
  <span>Tuesday</span>
  <span>Wednesday</span>

  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>

  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>

  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
</div></code>```

答:
Use a selector that targets every other row in one column.

For other columns, simply adjust and repeat.

.grid-table {
  display: grid;
  grid-template-columns: repeat(3, auto);
}

.grid-table > span:nth-child(-n+3) {
  background-color: red;
}

.grid-table > span:nth-child(6n+4),
.grid-table > span:nth-child(6n+5),
.grid-table > span:nth-child(6n+6) {
  background-color: lightgreen;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-table">
  <span>Room Name</span>
  <span>Start Date</span>
  <span>End Date</span>
  <span>Room 100</span>
  <span>Tuesday</span>
  <span>Wednesday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room Name</span>
  <span>Start Date</span>
  <span>End Date</span>
  <span>Room 100</span>
  <span>Tuesday</span>
  <span>Wednesday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
</div></code>```

Title: Table striping rows in CSS Grid

Body:
I'm trying to replace a grid of data & interactive components that had been set up in Bootstrap with a CSS Grid-based layout.

I was able to replicate the grid, but am having trouble getting something like table striping working.From what I understand of CSS Grid, since I know the number of columns that will be displayed ahead of time but not the number of rows (dynamically generated data from the server), I need to use grid-template-columns: repeat(3, auto);, and each cell must be a direct child of the wrapper div.

I've tried using nth-child to get the effect I want, but can't figure out what selector would let me target a dynamic range of elements.

Is there a better way to set up a grid layout using CSS Grid when the number of rows is unknown ahead of time?

Here's a fiddle with what I have so far, which includes all the code below. In my real project, the rows are dynamically generated and there are 5 columns right now- though that may change in the future.

.grid-table {
  display: grid;
  display: -ms-grid;
  grid-template-columns: repeat(3, auto);
  -ms-grid-template-columns: repeat(3, auto);
}

.grid-table :nth-child(-n+3) {
  background-color: red;
}

  Room Name
  Start Date
  End Date

  Room 100
  Tuesday
  Wednesday

  Room 200
  Tuesday
  Friday

  Room 200
  Tuesday
  Friday

  Room 200
  Tuesday
  Friday

Body:
Use a selector that targets every other row in one column.

For other columns, simply adjust and repeat.

.grid-table {
  display: grid;
  grid-template-columns: repeat(3, auto);
}

.grid-table > span:nth-child(-n+3) {
  background-color: red;
}

.grid-table > span:nth-child(6n+4),
.grid-table > span:nth-child(6n+5),
.grid-table > span:nth-child(6n+6) {
  background-color: lightgreen;
}

<div class="grid-table">
  <span>Room Name</span>
  <span>Start Date</span>
  <span>End Date</span>
  <span>Room 100</span>
  <span>Tuesday</span>
  <span>Wednesday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room Name</span>
  <span>Start Date</span>
  <span>End Date</span>
  <span>Room 100</span>
  <span>Tuesday</span>
  <span>Wednesday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
  <span>Room 200</span>
  <span>Tuesday</span>
  <span>Friday</span>
</div>


问:
Call explorer context menu in listview
Below image is a screenshot of beyond compare which calls windows explorer context menu of a file/folder when right-click and select Explorer menu.

Call-Explorer-Context-Menu

Please help to make it on vb.net, or please share a link for a tutorial. Thank you in advance.

答:
To get the shell menu of a file/folder you must ask the containing folders IShellFolder for a IContextMenu instance. Checkout this blog series called How to host an IContextMenu for all the details.

There is a .NET version of it here.

Title: Call explorer context menu in listview


问:
How to undo changes in an arbitrary commit?
I have some commit that is several commits previous to HEAD.  While committing, there were a few changes that were staged that I had not noticed.  Looking through my git log I noticed these unwanted changes.  Searching google for 'undo changes for an arbitrary commit', returns many results on undoing an entire commit and removing changes in the index.  However, what would be a way to remove these changes in this arbitrary commit?

答:
First of all, make sure your working tree is clean. git status helps you find this. It should not report any changes waiting to be committed. If there are changes you can either commit them (in a temporary branch if needed) or stash them.

After you make sure the working tree is clean, create a branch on the current commit but do not check it out:

```<code>$ git branch backup
</code>```

It is not really needed, you can use the reflog instead, but it is easier (and more visible) this way. backup is just a name I chose for the branch, it is nothing special with it; the only constraint is that it must not already exist.

Assuming you want to modify the third commit in the past, run:

```<code>$ git rebase --interactive HEAD~4
</code>```

Git opens in the default editor a temporary file whose content looks like this:

```<code>pick 7f0c5e794 the commit you want to change
pick 9f96dcae9 commit message #2
pick 02ed04062 commit message #3
pick beac35780 the most recent commit
</code>```

This is the plan for the rebase. Of course, it contains the hashes and the subjects of your last three commits. They are the last four commits (because of HEAD~4) in the chronological order (older first).

Edit the line of the commit you want to modify (the first line); change pick to edit then save the file and exit the editor.

When you exit the editor, Git starts the rebasing. It checks out the commit HEAD~3 and exits, allowing you to edit the commit, as you asked it in the plan.

Make the changes you want, stage them then run git commit --amend to modify the commit (your goal). The best way to do the changes is to run:

```<code>$ git reset --mixed HEAD~1
</code>```

This brings the repo in the status it was before the commit you want to modify, with files changed in the working tree and nothing added to the index. Add to the index only the files you need and commit (without --amend). This is the "edited"1 commit you wanted.

After you edit the commit you still have uncommitted changes in the working tree. You have to either commit them (create a new commit that didn't exist in the original history), stash them (and apply them after you complete the rebase) or discard them completely (git reset --hard does it; make sure you really don't need them before running this command).

After you resolve the problem of uncommitted changes one way or another, run:

```<code>$ git rebase --continue
</code>```

Git continues the rebase; it processes the other commits as you have told it in the plan. Our plan mentions pick for the other commits and this means Git just applies the changes of these commits you don't want to modify.

If everything goes well, after this command completes you have a new history line that looks like you wanted. If it doesn't look like you wanted you can run

```<code>$ git reset --hard backup
</code>```

to go back where you started from and start over.

If the rebase doesn't complete successfully (it may encounter conflicts) you can always abort it by running git rebase --abort. Git will undo all the changes and you will be where you started from (on the commit pointed at by the backup branch).

Or, you can solve the conflicts, commit and the run git rebase --continue until the rebase completes.

After you end the rebase one way or another and you are pleased with the result or have quit the idea of changing the past commit, run git branch -D backup to remove the backup branch.

1 The Git commits are immutable. It is not possible to edit a commit. "Editing" a commit in fact creates a new commit that is used instead of the old one. Of course, the new commit has a different hash than the original.

The old commit is still present in the repository and it is accessible by its hash or by using a branch. When there is no branch that can be used to reach it and there is no reference to it in the reflog, the commit object is removed on the next garbage collection cycle.

Body:
First of all, make sure your working tree is clean. git status helps you find this. It should not report any changes waiting to be committed. If there are changes you can either commit them (in a temporary branch if needed) or stash them.

After you make sure the working tree is clean, create a branch on the current commit but do not check it out:

$ git branch backup

It is not really needed, you can use the reflog instead, but it is easier (and more visible) this way. backup is just a name I chose for the branch, it is nothing special with it; the only constraint is that it must not already exist.

Assuming you want to modify the third commit in the past, run:

$ git rebase --interactive HEAD~4

Git opens in the default editor a temporary file whose content looks like this:

pick 7f0c5e794 the commit you want to change
pick 9f96dcae9 commit message #2
pick 02ed04062 commit message #3
pick beac35780 the most recent commit

This is the plan for the rebase. Of course, it contains the hashes and the subjects of your last three commits. They are the last four commits (because of HEAD~4) in the chronological order (older first).

Edit the line of the commit you want to modify (the first line); change pick to edit then save the file and exit the editor.

When you exit the editor, Git starts the rebasing. It checks out the commit HEAD~3 and exits, allowing you to edit the commit, as you asked it in the plan.

Make the changes you want, stage them then run git commit --amend to modify the commit (your goal). The best way to do the changes is to run:

$ git reset --mixed HEAD~1

This brings the repo in the status it was before the commit you want to modify, with files changed in the working tree and nothing added to the index. Add to the index only the files you need and commit (without --amend). This is the "edited"1 commit you wanted.

After you edit the commit you still have uncommitted changes in the working tree. You have to either commit them (create a new commit that didn't exist in the original history), stash them (and apply them after you complete the rebase) or discard them completely (git reset --hard does it; make sure you really don't need them before running this command).

After you resolve the problem of uncommitted changes one way or another, run:

$ git rebase --continue

Git continues the rebase; it processes the other commits as you have told it in the plan. Our plan mentions pick for the other commits and this means Git just applies the changes of these commits you don't want to modify.

If everything goes well, after this command completes you have a new history line that looks like you wanted. If it doesn't look like you wanted you can run

$ git reset --hard backup

to go back where you started from and start over.

If the rebase doesn't complete successfully (it may encounter conflicts) you can always abort it by running git rebase --abort. Git will undo all the changes and you will be where you started from (on the commit pointed at by the backup branch).

Or, you can solve the conflicts, commit and the run git rebase --continue until the rebase completes.

After you end the rebase one way or another and you are pleased with the result or have quit the idea of changing the past commit, run git branch -D backup to remove the backup branch.

1 The Git commits are immutable. It is not possible to edit a commit. "Editing" a commit in fact creates a new commit that is used instead of the old one. Of course, the new commit has a different hash than the original.

The old commit is still present in the repository and it is accessible by its hash or by using a branch. When there is no branch that can be used to reach it and there is no reference to it in the reflog, the commit object is removed on the next garbage collection cycle.


问:
guava-libraries: is Iterators.cycle() thread-safe?
Suppose I have the following class:

```<code>public class Foo {

    private List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
    private Iterator<Integer> iterator = Iterators.cycle(list);

    public void bar(){
        Integer value = iterator.next();
        doSomethingWithAnInteger(value);
    }
}
</code>```

If an instance of Foo is acessed simultaneously by two threads, I need that each thread gets a different value from iterator.next(). Does the bar() method have to be made synchronized? Or is iterator.next() guaranteed to be thread-safe?

In this example, I am using an ArrayList as the underlying Iterable. Does the thread-safety of the cyclic iterator depend on the specific iterable implementation?

答:
Pretty much nothing in Guava is guaranteed to be thread safe unless documented as such.

You do not have to synchronize the entire bar method, but you should wrap the call to  iterator.next() in a synchronized block. eg:

```<code>public void bar(){
    Integer value;
    synchronized (iterator) {
        value = iterator.next();
    }
    doSomethingWithAnInteger(value);
}
</code>```

Body:
Suppose I have the following class:

public class Foo {

    private List<Integer> list = Lists.newArrayList(1, 2, 3, 4, 5);
    private Iterator<Integer> iterator = Iterators.cycle(list);

    public void bar(){
        Integer value = iterator.next();
        doSomethingWithAnInteger(value);
    }
}

If an instance of Foo is acessed simultaneously by two threads, I need that each thread gets a different value from iterator.next(). Does the bar() method have to be made synchronized? Or is iterator.next() guaranteed to be thread-safe?

In this example, I am using an ArrayList as the underlying Iterable. Does the thread-safety of the cyclic iterator depend on the specific iterable implementation?

Body:
Pretty much nothing in Guava is guaranteed to be thread safe unless documented as such.

You do not have to synchronize the entire bar method, but you should wrap the call to  iterator.next() in a synchronized block. eg:

public void bar(){
    Integer value;
    synchronized (iterator) {
        value = iterator.next();
    }
    doSomethingWithAnInteger(value);
}


问:
Accessing Android Context in Xamarin.Forms
I've seen some old solutions to getting the Android Context using Xamarin.Forms. These older solution suggest the use of Xamarin.Forms.Forms.Context but due to the ever changing Xamarin.Forms platform this no longer works.

In my example I have used the DependencyService.Get<Interface>() from my Shared Code project to use a platform specific implementation of the Interface class.

The use of Android Context is needed a ton when using platform specific functionality using Xamarin.Andriod.

So how do we get the global information interface for an Android Context?

答:
Go to the class you created in your App.Droid project part of your solution.

Make sure you have using Android.Content; included at the top.

Create a variable to hold the Context and initialize it with Android.App.Application.Context.

That's it!

```<code>using Android.Content;

[assembly: Xamarin.Forms.Dependency(typeof(DroidClass))]
namespace App.Droid
{
   public class DroidClass : Interface
   {
     Context context = Android.App.Application.Context;

     public DroidClass()
     {
        Toast.MakeText(context, "Grabbed Context!", ToastLength.Long).Show();
         }
      }
   }
</code>```

Body:
Go to the class you created in your App.Droid project part of your solution.

Make sure you have using Android.Content; included at the top.

Create a variable to hold the Context and initialize it with Android.App.Application.Context.

That's it!

using Android.Content;

[assembly: Xamarin.Forms.Dependency(typeof(DroidClass))]
namespace App.Droid
{
   public class DroidClass : Interface
   {
     Context context = Android.App.Application.Context;

     public DroidClass()
     {
        Toast.MakeText(context, "Grabbed Context!", ToastLength.Long).Show();
         }
      }
   }