问:
how to get sum of integer value from recyclerview
i am want to implement something like invoice. i am using recyclerview in fragment. and textview. i have some item in recyclerview. which content title,unit and price. now i want to get sum of all item's price in my textview which is in fragment. here is image what i want to achive.

here is image for understanding

here is my code for adapter class

```<code>public class Checkout_fragment2_confermation_Adapter extends RecyclerView.Adapter<Checkout_fragment2_confermation_Adapter.ViewHolder>  {

static List<Cart_datamodel> data;
static Context context;

public Checkout_fragment2_confermation_Adapter(Context context , List<Cart_datamodel> data1) {
    data = new ArrayList<Cart_datamodel>();
    this.context = context;
    this.data = data1;
}

@Override
public Checkout_fragment2_confermation_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.checkout_fragmet2confermation_listviwe_single_row, null);
    itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
    Checkout_fragment2_confermation_Adapter.ViewHolder viewHolder = new Checkout_fragment2_confermation_Adapter.ViewHolder(itemLayoutView);

    return viewHolder;
}

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

@Override
public int getItemCount() {
    return data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView  title,price;
    public ImageView img,product_img;

    public ViewHolder(View itemView) {
        super(itemView);
        title = (TextView)itemView.findViewById(R.id.title_checkout_fgment2);
        price =(TextView)itemView.findViewById(R.id.price_checkout_fragment2);
        product_img =(ImageView)itemView.findViewById(R.id.image_checkout_fragment2);
    }
}
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

}
</code>```

here is my fragment class

```<code>public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragmenttab2, container, false);

    dataBaseAdapter = new AddressDataBaseAdapter(getContext());
    cart_adapter = new Item_adding_cart(getContext());
    dbList = cart_adapter.getDataFromDB();

   // listview = (ListView)view.findViewById(R.id.listview);

    recyclerView =(RecyclerView)view.findViewById(R.id.my_recycler_view_checkout_fgrment2);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recycleradapter = new Checkout_fragment2_confermation_Adapter(getContext(),dbList);
    recyclerView.setAdapter(recycleradapter);

    fname =(TextView)view.findViewById(R.id.firstname_conformation);
    lname =(TextView)view.findViewById(R.id.lastname_conformation);
    mobile =(TextView)view.findViewById(R.id.mobile_conformaton);
    address =(TextView)view.findViewById(R.id.address_conformation);
    zipcode =(TextView)view.findViewById(R.id.zipcode_conformation);
    city =(TextView)view.findViewById(R.id.city_conformation);

    addresslist= new ArrayList<Address_Activity_DataModel>();
    addresslist=dataBaseAdapter.getDataFromDB();

    int count = dataBaseAdapter.getrowcount();
    if(count==0){

    }
    else
    {
        showRecords();
    }

   // loaddata();

    return view;

}
</code>```

答:
In your fragment, just iterate through your dbList before/after you add it to your adapter.

```<code>int totalPrice = 0;
for (int i = 0; i<dbList.size(); i++)
{
    totalPrice += dbList.get(i).getPrice();
}
</code>```

I don't suggest you calculate anything in the adapter's onBindView because onBindView won't be called for views that are not loaded and it will be called multiple times.

ContentLicense: CC BY-SA 4.0

Body:
i am want to implement something like invoice. i am using recyclerview in fragment. and textview. i have some item in recyclerview. which content title,unit and price. now i want to get sum of all item's price in my textview which is in fragment. here is image what i want to achive.

here is image for understanding

here is my code for adapter class

public class Checkout_fragment2_confermation_Adapter extends RecyclerView.Adapter<Checkout_fragment2_confermation_Adapter.ViewHolder>  {

static List<Cart_datamodel> data;
static Context context;

public Checkout_fragment2_confermation_Adapter(Context context , List<Cart_datamodel> data1) {
    data = new ArrayList<Cart_datamodel>();
    this.context = context;
    this.data = data1;
}

@Override
public Checkout_fragment2_confermation_Adapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    final View itemLayoutView = LayoutInflater.from(parent.getContext()).inflate(R.layout.checkout_fragmet2confermation_listviwe_single_row, null);
    itemLayoutView.setLayoutParams(new RecyclerView.LayoutParams(RecyclerView.LayoutParams.MATCH_PARENT, RecyclerView.LayoutParams.WRAP_CONTENT));
    Checkout_fragment2_confermation_Adapter.ViewHolder viewHolder = new Checkout_fragment2_confermation_Adapter.ViewHolder(itemLayoutView);

    return viewHolder;
}

@Override
public void onBindViewHolder(Checkout_fragment2_confermation_Adapter.ViewHolder holder, int position) {

    holder.title.setText(data.get(position).getTitle());
    holder.price.setText(data.get(position).getPrice());
    holder.product_img.setImageBitmap(getImage(data.get(position).getImg()));

}

@Override
public int getItemCount() {
    return data.size();
}

public class ViewHolder extends RecyclerView.ViewHolder {
    public TextView  title,price;
    public ImageView img,product_img;

    public ViewHolder(View itemView) {
        super(itemView);
        title = (TextView)itemView.findViewById(R.id.title_checkout_fgment2);
        price =(TextView)itemView.findViewById(R.id.price_checkout_fragment2);
        product_img =(ImageView)itemView.findViewById(R.id.image_checkout_fragment2);
    }
}
public static Bitmap getImage(byte[] image) {
    return BitmapFactory.decodeByteArray(image, 0, image.length);
}

}

here is my fragment class

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.fragmenttab2, container, false);

    dataBaseAdapter = new AddressDataBaseAdapter(getContext());
    cart_adapter = new Item_adding_cart(getContext());
    dbList = cart_adapter.getDataFromDB();

   // listview = (ListView)view.findViewById(R.id.listview);

    recyclerView =(RecyclerView)view.findViewById(R.id.my_recycler_view_checkout_fgrment2);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
    recycleradapter = new Checkout_fragment2_confermation_Adapter(getContext(),dbList);
    recyclerView.setAdapter(recycleradapter);

    fname =(TextView)view.findViewById(R.id.firstname_conformation);
    lname =(TextView)view.findViewById(R.id.lastname_conformation);
    mobile =(TextView)view.findViewById(R.id.mobile_conformaton);
    address =(TextView)view.findViewById(R.id.address_conformation);
    zipcode =(TextView)view.findViewById(R.id.zipcode_conformation);
    city =(TextView)view.findViewById(R.id.city_conformation);

    addresslist= new ArrayList<Address_Activity_DataModel>();
    addresslist=dataBaseAdapter.getDataFromDB();

    int count = dataBaseAdapter.getrowcount();
    if(count==0){

    }
    else
    {
        showRecords();
    }

   // loaddata();

    return view;

}

Body:
In your fragment, just iterate through your dbList before/after you add it to your adapter.

int totalPrice = 0;
for (int i = 0; i<dbList.size(); i++)
{
    totalPrice += dbList.get(i).getPrice();
}

I don't suggest you calculate anything in the adapter's onBindView because onBindView won't be called for views that are not loaded and it will be called multiple times.


来源: stackexchange

问:
How to do excel formula that would Sum values from column C if column A is 'X' or 'Y' and column B is 'Z'?
I have a spreadsheet from which I need to pick out some specific values that are in one of text columns but only if other column matches the year.

I have tried following SUM with IF but I think OR portion in textual column is failing...

=SUM(IF(B:B="*Nuoma*",B:B="*(Nuomininko)*",C:C=2016,D:D))

What I need is if in column B value contains Nuoma OR (Nuomininko) AND column C is 2016 then SUM column D...

答:
Here's a suggestion based on the fact that in your example, both strings 'Nuoma' and 'Nuominiko' contain the same string 'Nuom'. It uses SUMPRODUCT and SEARCH (as a substitute for wildcards) together with a help column for the string matching.

Cell D7 in the screenshot contains this formula:
=IFERROR(SEARCH("Nuom",B7),0)

And the summation in E15 is done by =SUMPRODUCT(E6:E13,--(C6:C13=2016),--(D6:D13=1)). In my example this evaluates to the sum of cells E10 and  E14: 4 + 2 = 6.

If you prefer to avoid the help column and use an array formula instead, this one produces the same result without involving column D (don't forget to do Ctrl + Shift + Enter):

{=SUMPRODUCT(E7:E14,--(C7:C14=2016),IFERROR(SEARCH("Nuom",B7:B14),0))}

I suppose it would be relatively straightforward to extended this to more complicated situations.

ContentLicense: CC BY-SA 3.0


问:
Swift 3 - how to hide Status Bar when using Over Full Screen
I'm developing a swift app and I can't find how to hide Status Bar when I use Over Full Screen presentation on my modal.

However, I put this line of code in my Modal View Controller :

```<code>override var prefersStatusBarHidden: Bool {
    return true
}
</code>```

And it is working if I create a segue which is not a modal, or if I create a segue which is a modal but not with Over Full Screen presentation.

I searched on internet how to fix it, and I found people who had the same problem but there had no solution.

Also, I can't change the color of my Status Bar when I'm using Over Full Screen option. I don't understand why? I think it's related.

Thanks for your help!

答:
We can override preferredStatusBarStyle from individual view controller as you have done correctly.

Along with this, insert a new key named “View controller-based status bar appearance” and set the value to NO in your info.plist.

By disabling the “View controller-based status bar appearance”, you can set the status bar style by using the following code.

```<code>[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; //objective-c
</code>```

Hence it should solve "I can't change the color of my Status Bar when I'm using Over Full Screen option"

Body:
I'm developing a swift app and I can't find how to hide Status Bar when I use Over Full Screen presentation on my modal.

However, I put this line of code in my Modal View Controller :

override var prefersStatusBarHidden: Bool {
    return true
}

And it is working if I create a segue which is not a modal, or if I create a segue which is a modal but not with Over Full Screen presentation.

I searched on internet how to fix it, and I found people who had the same problem but there had no solution.

Also, I can't change the color of my Status Bar when I'm using Over Full Screen option. I don't understand why? I think it's related.

Thanks for your help!

Body:
We can override preferredStatusBarStyle from individual view controller as you have done correctly.

Along with this, insert a new key named “View controller-based status bar appearance” and set the value to NO in your info.plist.

By disabling the “View controller-based status bar appearance”, you can set the status bar style by using the following code.

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent]; //objective-c

Hence it should solve "I can't change the color of my Status Bar when I'm using Over Full Screen option"


问:
python split by "\t" is not showing all elements in it
I am trying to split by "\t" but it is not printing all the elements in it

```<code>import sys
reload(sys)
sys.setdefaultencoding('utf8')

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']
print s[0].split("\t")
</code>```

Results

```<code>['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School']
</code>```

But i want results upto this

```<code>2874875, Submitted
</code>```

How to fix the code and where is the change?

答:
With your data you should do something like this:</p>

```<code>s[2].split("\t")[10:12]
</code>```

Body:
I am trying to split by "\t" but it is not printing all the elements in it

import sys
reload(sys)
sys.setdefaultencoding('utf8')

s = ['A\t"Ravi"\t"Tirupur"\t"India"\t"641652"\t"arunachalamravi@gmail.com"\t"17379602"\t"+ 2"\t"Government Higher Secondary School', ' Tiruppur"\t\t"1989"\t"Maths',' Science"\t"No"\t"Encotec Energy 2 X 600 MW ITPCL"\t"Associate Vice President- Head Maintenance"\t"2015"\t"2016"\t"No"\t"27-Mar-2017"\t"9937297878"\t\t"2874875"\t"Submitted"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t']
print s[0].split("\t")

Results

['A', '"Ravi"', '"Tirupur"', '"India"', '"641652"', '"arunachalamravi@gmail.com"', '"17379602"', '"+ 2"', '"Government Higher Secondary School']

But i want results upto this

2874875, Submitted

How to fix the code and where is the change?

Body:
With your data you should do something like this:

s[2].split("\t")[10:12]


问:
RegularExpressionValidator for more than just AlphaNumerics
I have a RegularExpressionValidator with:

```<code>ValidationExpression="^(a-zA-Z0-9 '-]+$"
</code>```

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

```<code>ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"
</code>```

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.

答:
Please look here and here for how you have to write things that mean alphanumerics, whitespace (probably only horizontal not vertical), dashes, and apostrophes so that it works correctly on Unicode data.

The code there is in Java, but I am pretty sure the same rules and restrictions apply to C♯ as well. The short story is that you have to write this in Java:

```<code>dashes                  = "[\\u002D\\u058A\\u05BE\\u1400\\u1806\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2053\\u207B\\u208B\\u2212\\u2E17\\u2E1A\\u301C\\u3030\\u30A0\\uFE31\\uFE32\\uFE58\\uFE63\\uFF0D]";
horizontal_whitespaces  = "[\\u0009\\u0020\\u00A0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000]";
vertical_whitespace     = "[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]";
whitespace              = "[\\u000A\\u000B\\u000C\\u000D\\u0020\\u0085\\u00A0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]";
identifier_chars        = "[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]]";
apostrophic_chars       = "[\\u0027\\u02BC\\u2019\\uFF07]";
quotation_mark_chars    = "[\\u0022\\u0027\\u00AB\\u00BB\\u2018\\u2019\\u201A\\u201B\\u201C\\u201D\\u201E\\u201F\\u2039\\u203A\\u300C\\u300D\\u300E\\u300F\\u301D\\u301E\\u301F\\uFE41\\uFE42\\uFE43\\uFE44\\uFF02\\uFF07\\uFF62\\uFF63]";
leading_punctuation     = "[\\p{Ps}\\p{Pi}]";
closing_punctuation     = "[\\p{Pe}\\p{Pf}]";
boundary                = "(?:(?<=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]])(?![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]])|(?<![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]])(?=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]]))";
</code>```

Amazing, but true.

ContentLicense: CC BY-SA 2.5

Body:
I have a RegularExpressionValidator with:

ValidationExpression="^(a-zA-Z0-9 '-]+$"

so this was working for alphanumerics, spaces, apostrophes and hyphen.

I was told that I now need it to additionally work for underscore, ampersand '&', comma, parentheses and fullstop.

I tried:

ValidationExpression="^(a-zA-Z0-9 '-_&,().]+$"

but this made it accept virtually anything.

Could someone please tell me where I'm going wrong? I'm relatively new to Regex.

Body:
Please look here and here for how you have to write things that mean alphanumerics, whitespace (probably only horizontal not vertical), dashes, and apostrophes so that it works correctly on Unicode data.

The code there is in Java, but I am pretty sure the same rules and restrictions apply to C♯ as well. The short story is that you have to write this in Java:

dashes                  = "[\\u002D\\u058A\\u05BE\\u1400\\u1806\\u2010\\u2011\\u2012\\u2013\\u2014\\u2015\\u2053\\u207B\\u208B\\u2212\\u2E17\\u2E1A\\u301C\\u3030\\u30A0\\uFE31\\uFE32\\uFE58\\uFE63\\uFF0D]";
horizontal_whitespaces  = "[\\u0009\\u0020\\u00A0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u202F\\u205F\\u3000]";
vertical_whitespace     = "[\\u000A\\u000B\\u000C\\u000D\\u0085\\u2028\\u2029]";
whitespace              = "[\\u000A\\u000B\\u000C\\u000D\\u0020\\u0085\\u00A0\\u1680\\u180E\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200A\\u2028\\u2029\\u202F\\u205F\\u3000]";
identifier_chars        = "[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]]";
apostrophic_chars       = "[\\u0027\\u02BC\\u2019\\uFF07]";
quotation_mark_chars    = "[\\u0022\\u0027\\u00AB\\u00BB\\u2018\\u2019\\u201A\\u201B\\u201C\\u201D\\u201E\\u201F\\u2039\\u203A\\u300C\\u300D\\u300E\\u300F\\u301D\\u301E\\u301F\\uFE41\\uFE42\\uFE43\\uFE44\\uFF02\\uFF07\\uFF62\\uFF63]";
leading_punctuation     = "[\\p{Ps}\\p{Pi}]";
closing_punctuation     = "[\\p{Pe}\\p{Pf}]";
boundary                = "(?:(?<=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]])(?![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]])|(?<![\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]])(?=[\\pL\\pM\\p{Nd}\\p{Nl}\\p{Pc}[\\p{InEnclosedAlphanumerics}&&\\p{So}]]))";

Amazing, but true.


问:
Is there a way to return the field_weights values?
When I run a SphinxQL query I can request the Weight()

```<code>Select ID,Weight(),Title from Index_A where MATCH('@(Title,Description) London')
</code>```

Which returns the weight that Sphinx assigned each match however when I add field_weights to the query:

```<code>Select ID,Weight(),Title from Index_A where MATCH('@(Title,Description) London') OPTION field_weights=(Title=1000)
</code>```

I can't request a column to show the field_weights. I've tried Select field_weights() and Select field_weights(Title) to no avail and I'm trying to get an idea of how this is actually being scored.

答:
I'm not totally sure, but if it's available, it will be via the PACKEDFACTORS() function

http://sphinxsearch.com/docs/current/misc-functions.html

Body:
When I run a SphinxQL query I can request the Weight()

Select ID,Weight(),Title from Index_A where MATCH('@(Title,Description) London')

Which returns the weight that Sphinx assigned each match however when I add field_weights to the query:

Select ID,Weight(),Title from Index_A where MATCH('@(Title,Description) London') OPTION field_weights=(Title=1000)

I can't request a column to show the field_weights. I've tried Select field_weights() and Select field_weights(Title) to no avail and I'm trying to get an idea of how this is actually being scored.


问:
Android activity and fragment life cycle - do I need to use all methods in my code?
Android activity and fragment lifecycles have many stages (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), etc). I have been coding in Android Studio for a few months now and there're many times where I haven't used all of lifecycle methods. </p>

<p>My question is that do you need to use all of the lifecycle methods of a fragment or an activity to write a good code? Will it cause crashes otherwise? </p>

答:
No, You dont need to write all the lifecycle. But you should have the idea of what lifecycle is going on and what will be the behaviour of Android app. Like why you have to attach activity context to fragment context in onAttach() life cycle method.

What lifecycle will be perform on dialog open or moving from one activity to another??

Read here more.

https://developer.android.com/reference/android/app/Activity.html

Body:
Android activity and fragment lifecycles have many stages (onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), etc). I have been coding in Android Studio for a few months now and there're many times where I haven't used all of lifecycle methods.

My question is that do you need to use all of the lifecycle methods of a fragment or an activity to write a good code? Will it cause crashes otherwise?


问:
Add column to sql table with c#
Hello I got a big problem I am trying to add a new column to my MSSQL Database Table and i tried it like thousand times but it wont work.
My destination is to press a button then use the function "eventsspalte_Hinzufügen" to add a new column with the name thats Inserted by the user.

This is the snippet.

```<code>private void eventsspalte_Hinzufügen()
{

    SQL_eingabe = "ALTER TABLE Teilnahmen_Events ADD @tbName bit NOT NULL ;"; //  CONSTRAINT strconst3 DEFAULT 0

    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = SQL_eingabe;
    cmd.Parameters.AddWithValue("@tbName", tb_Eventname.Text);
    cmd.ExecuteNonQuery();
    con.Close();
}
</code>```

The Exception says that cmd.ExecuteQuery() is not able to Execute the sql Command because of the wromg Syntax at @tbName I also tried to use a variable like:

```<code>ALTER TABLE Teilnahmen_Events ADD'"+ tb_Eventname.Text +"'bit NOT NULL ;";
</code>```

but it also didnt work...
I hope you got an solution for me thank you very much.

答:
you cannot pass column name as parameter.

In your second example, single quotes are not needed, so change it into

```<code>ALTER TABLE Teilnahmen_Events ADD "+ tb_Eventname.Text +" bit NOT NULL ;";
</code>```

Title: Add column to sql table with c#

Body:
Hello I got a big problem I am trying to add a new column to my MSSQL Database Table and i tried it like thousand times but it wont work.
My destination is to press a button then use the function "eventsspalte_Hinzufügen" to add a new column with the name thats Inserted by the user.

This is the snippet.

private void eventsspalte_Hinzufügen()
{

    SQL_eingabe = "ALTER TABLE Teilnahmen_Events ADD @tbName bit NOT NULL ;"; //  CONSTRAINT strconst3 DEFAULT 0

    con.Open();
    SqlCommand cmd = con.CreateCommand();
    cmd.CommandType = CommandType.Text;
    cmd.CommandText = SQL_eingabe;
    cmd.Parameters.AddWithValue("@tbName", tb_Eventname.Text);
    cmd.ExecuteNonQuery();
    con.Close();
}

The Exception says that cmd.ExecuteQuery() is not able to Execute the sql Command because of the wromg Syntax at @tbName I also tried to use a variable like:

ALTER TABLE Teilnahmen_Events ADD'"+ tb_Eventname.Text +"'bit NOT NULL ;";

but it also didnt work...
I hope you got an solution for me thank you very much.

Body:
you cannot pass column name as parameter.

In your second example, single quotes are not needed, so change it into

ALTER TABLE Teilnahmen_Events ADD "+ tb_Eventname.Text +" bit NOT NULL ;";


问:
Registered alert script called on BrowserBack
I have a small class that displays an alert via Javascript. I am using this class on a page that checks if the user entered valid zip code. If a valid zip code is not entered, an alert is displayed, and the page is posted back to the same page so they can change it. If they enter a valid zip code, they are redirected to another page. The problem is that if they hit the back button on their browser, the alert is displayed regardless of whether the zip code is valid or not.

Here is the flow:

Zip entry page -> Enter Zip -> Check Zip

if valid zip -> goto overview.aspx
if not valid zip, goto zip entry page

On overview.aspx, if they hit their browser's back button, the alert is displayed. I don't want this to happen. Below is the code I have for the alert class which works great. And below that the code that checks and displays the alert when the LinkButton is clicked.

```<code>protected void GotoReview(object sender, EventArgs e) {
    if (ValidateZipCode(ZipCode)) {
        Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
        ProductCode, ZipCode));
    }
    else {
        Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
    }
}

private bool ValidateZipCode(string zip) {
    if (zip.Length < 5 || zip.Length > 5) {
        return false;
    }
    if (!Regex.IsMatch(zip, @"^(\d{5}-\d{4})|(\d{5})$")) {
        return false;
    }
    return true;
}

public static class Alert {
    public static void Show(string message) {
        string cleanMessage = message.Replace("'", "\\'");
        string script = "<script type=\"text/javascript\">alert('" + cleanMessage + "');</script>";
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }
}
</code>```

答:
when you click the LinkButton browser requests the same page (zip code entry page) and then gets redirected to overview.aspx (if everything's fine). But when you click Back button, it seems that browser performs previous request - validates zip code, not displays zip code entry page.

In any case, it's better to perform such a check on client, as stated shahkalpesh

OwnerDisplayName: David Anderson

Body:
I have a small class that displays an alert via Javascript. I am using this class on a page that checks if the user entered valid zip code. If a valid zip code is not entered, an alert is displayed, and the page is posted back to the same page so they can change it. If they enter a valid zip code, they are redirected to another page. The problem is that if they hit the back button on their browser, the alert is displayed regardless of whether the zip code is valid or not.

Here is the flow:

Zip entry page -> Enter Zip -> Check Zip

if valid zip -> goto overview.aspx
if not valid zip, goto zip entry page

On overview.aspx, if they hit their browser's back button, the alert is displayed. I don't want this to happen. Below is the code I have for the alert class which works great. And below that the code that checks and displays the alert when the LinkButton is clicked.

protected void GotoReview(object sender, EventArgs e) {
    if (ValidateZipCode(ZipCode)) {
        Response.Redirect(string.Format("~/checkout/overview.aspx?pc={0}&zc={1}",
        ProductCode, ZipCode));
    }
    else {
        Alert.Show("The entered zip code is invalid. Please ensure the zip code is a valid zip code.");
    }
}

private bool ValidateZipCode(string zip) {
    if (zip.Length < 5 || zip.Length > 5) {
        return false;
    }
    if (!Regex.IsMatch(zip, @"^(\d{5}-\d{4})|(\d{5})$")) {
        return false;
    }
    return true;
}

public static class Alert {
    public static void Show(string message) {
        string cleanMessage = message.Replace("'", "\\'");
        string script = "";
        Page page = HttpContext.Current.CurrentHandler as Page;
        if (page != null && !page.ClientScript.IsClientScriptBlockRegistered("alert")) {
            page.ClientScript.RegisterClientScriptBlock(typeof(Alert), "alert", script);
        }
    }
}

OwnerDisplayName: x-yuri


问:
Word Add-in Inserting table (Javascript)
I'm trying to write a add-in for word 2016 using the javascript api. The add-in is supposed to have a button that inserts tables but I can't quite get it to work.

```<code>Word.run(function (context) {
        // Create a proxy object for the document body.
        var body = context.document.body;

        body.insertTable(2, 2, Word.InsertLocation.end, [["a", "b"], ["c", "d"]]);

        // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
        return context.sync();
    }).catch(function (e) {

        console.log(e.message);
    })
</code>```

Here is the method I have to test it. Whenever I activate it, it causes word to hang for a moment and then does nothing.I have also already made sure that the problem has nothing to do with the button that runs the method .If anyone knows why or how to fix it I would be very grateful. Thank you in advance.

答: I found that the problem was because of the build version of word that I was using was not supporting the inserttable method, so updating word was the fix for the problem</p>

Body:
I'm trying to write a add-in for word 2016 using the javascript api. The add-in is supposed to have a button that inserts tables but I can't quite get it to work.

Word.run(function (context) {
        // Create a proxy object for the document body.
        var body = context.document.body;

        body.insertTable(2, 2, Word.InsertLocation.end, [["a", "b"], ["c", "d"]]);

        // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
        return context.sync();
    }).catch(function (e) {

        console.log(e.message);
    })

Here is the method I have to test it. Whenever I activate it, it causes word to hang for a moment and then does nothing.I have also already made sure that the problem has nothing to do with the button that runs the method .If anyone knows why or how to fix it I would be very grateful. Thank you in advance.


问:
create random arrays in javascript
I have a form that asks the user for maximum result in math drills, in order to build some drills:

```<code><input type="text" id="maxR" placeholder="type maximum result" />
<button id="activate" onclick="makeDrills()">MAKE</button>
<p id="drill"></p>
</code>```

And I want to translate all the drills options with their answers as arrays.

I need help with translating this sentence into java-script:

"While c > level add new array of theQ with the both the drill and it's result".

This is my attempts:

```<code><script>
  function theQ(quest, ans) {  // drills constructor
    this.question = quest;
    this.answer = ans;
  }

  var a, b, c ; // arguments
  var quests = [new theQ()]; // arrays holder
  var level = document.getElementById("maxR").value; // user input

  function makeDrills() { // button pushed
    var c = a+b; // pattern of each drill
    while (c > level) { // as long result smaller then user input
      var a = Math.floor(Math.random() * 10);  // choose random number
      var b = Math.floor(Math.random() * 10); // choose another random number
      quests.push("a+b", "c");  // add the drill to the arrays holder
    }
    document.getElementById("drill").innerHTML += quests; // print drills
  }
</script>
</code>```

I read similar questions and try to use their techniques but didn't succeed.

edited:
This code is for educational purpose:

a,b,c are arguments on a+b=c equation. I try to make math drills generator that the kid enter maximum result and push the button and then all possible drills options will appear. I need to put all the options as arrays because I want to use the options as sort of a test.

So for now I just want to understand how to create those arrays.

答:
There are several issues:

When you create the quests array, you should not add one empty question to it. Just do quests = []

You are calculating the sum with var c = a+b before you have the separate values of a and b. var c = a+b is not a pattern -- as you write in comments --; it actually performs the addition right there.

level is a string (because that is what input values always are), so when you do a comparison like c > level, you are comparing with a string value, which will not have the desired outcome.

Since your sum can never be greater than 18 (a and b are both smaller than 10), your code will run for ever if you enter a maximum value that is greater than 18. Moreover, it seems not reasonable to use this as a stop-condition. You could even get into a situation where the first sum already is greater than allowed, and you'll end up with no questions at all. Just define how many questions you want to produce, either by asking the user for that, or defining the number of times in the code (for example: 10 questions).

You can make sure that your sum is within limits by looking how much remains after you have generated the first number. If your maximum is 10, and you generated a 6, then let your second number be a random number between 0 and 4. This way you always get valid numbers.

"a+b" is not very useful as question, as the user does not know what a means. Instead make it dynamic and ask for a + ' + ' + b + ' = ', which will render like 6 + 3 =.

Similarly "c" is a string, and not the result of the sum, it should be c, or why not just a+b, so you don't need the c variable.

quests.push("a+b", "c"); is pushing two string values to the array, but you want to push a question object, so you need to use quests.push(new theQ(a + ' + ' + b + ' = ', a+b)).

As quests is an array of objects, you should not expect that assigning that to an innerHTML property will render something useful. You should specify how the questions should be rendered. So you need to iterate over the questions, and then generate the piece of HTML you want for each question.

The code with all these corrections is below. It also has a button and code to verify the input of the answers.

function theQ(quest, ans) {  // drills constructor
    this.question = quest;
    this.answer = ans;
}

var quests = []; // array of questions

function makeDrills() { // button pushed
    var a, b; // We don't need c
    // Read the input only when button is pressed:
    var level = document.getElementById("maxR").value; // user input
    // Empty questions array
    quests = [];

    // Let's say we want to produce 10 questions
    while (quests.length < 10) {
        // choose a random integer below the maximum
        a = Math.floor(Math.random() * level);
        // choose a random integer such that sum is not greater than maximum
        b = Math.floor(Math.random() * (level-a+1));
        // Question is a dynamicly created string, answer is calculated here
        // You need to call theQ here:
        quests.push(new theQ(a + ' + ' + b + ' = ', a+b));
    }

    var container = document.getElementById("drill");
    // Set the HTML for all questions
    container.innerHTML = quests.map(function (quest, i) {
        // Add the question to the drill section, give the input element an ID
        // that corresponds to the question number
        return quest.question + '<input placeholder="enter sum" id="answer' + i + '">
';
    }).join(''); // join all HTML pieces together into one string
}

function verify() {
    if (quests.length == 0) return; // Nothing to do
    // Count the number of wrong answers. Iterate over answers with reduce:
    var errorCount = quests.reduce(function (count, quest, i) {
        // Add 1 penalty if answer is incorrect
        return count + (quest.answer != document.getElementById('answer' + i).value);
    }, 0); // Atart counting from 0
    if (errorCount == 0)
        alert('Congratulations! You answered all questions correctly.');
    else
        alert('You have entered ' + errorCount + ' wrong answer(s). Try to correct them.');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="text" id="maxR" placeholder="type maximum sum" />
<button id="activate" onclick="makeDrills()">Generate questions</button>
<div id="drill"></div>
<button id="verify" onclick="verify()">Verify</button></code>```

Title: create random arrays in javascript

Body:
I have a form that asks the user for maximum result in math drills, in order to build some drills:

<input type="text" id="maxR" placeholder="type maximum result" />
<button id="activate" onclick="makeDrills()">MAKE</button>

And I want to translate all the drills options with their answers as arrays.

I need help with translating this sentence into java-script:

"While c > level add new array of theQ with the both the drill and it's result".

This is my attempts:

I read similar questions and try to use their techniques but didn't succeed.

edited:
This code is for educational purpose:

a,b,c are arguments on a+b=c equation. I try to make math drills generator that the kid enter maximum result and push the button and then all possible drills options will appear. I need to put all the options as arrays because I want to use the options as sort of a test.

So for now I just want to understand how to create those arrays.

Body:
There are several issues:

When you create the quests array, you should not add one empty question to it. Just do quests = []

You are calculating the sum with var c = a+b before you have the separate values of a and b. var c = a+b is not a pattern -- as you write in comments --; it actually performs the addition right there.

level is a string (because that is what input values always are), so when you do a comparison like c > level, you are comparing with a string value, which will not have the desired outcome.

Since your sum can never be greater than 18 (a and b are both smaller than 10), your code will run for ever if you enter a maximum value that is greater than 18. Moreover, it seems not reasonable to use this as a stop-condition. You could even get into a situation where the first sum already is greater than allowed, and you'll end up with no questions at all. Just define how many questions you want to produce, either by asking the user for that, or defining the number of times in the code (for example: 10 questions).

You can make sure that your sum is within limits by looking how much remains after you have generated the first number. If your maximum is 10, and you generated a 6, then let your second number be a random number between 0 and 4. This way you always get valid numbers.

"a+b" is not very useful as question, as the user does not know what a means. Instead make it dynamic and ask for a + ' + ' + b + ' = ', which will render like 6 + 3 =.

Similarly "c" is a string, and not the result of the sum, it should be c, or why not just a+b, so you don't need the c variable.

quests.push("a+b", "c"); is pushing two string values to the array, but you want to push a question object, so you need to use quests.push(new theQ(a + ' + ' + b + ' = ', a+b)).

As quests is an array of objects, you should not expect that assigning that to an innerHTML property will render something useful. You should specify how the questions should be rendered. So you need to iterate over the questions, and then generate the piece of HTML you want for each question.

The code with all these corrections is below. It also has a button and code to verify the input of the answers.

function theQ(quest, ans) {  // drills constructor
    this.question = quest;
    this.answer = ans;
}

var quests = []; // array of questions

function makeDrills() { // button pushed
    var a, b; // We don't need c
    // Read the input only when button is pressed:
    var level = document.getElementById("maxR").value; // user input
    // Empty questions array
    quests = [];

    // Let's say we want to produce 10 questions
    while (quests.length < 10) {
        // choose a random integer below the maximum
        a = Math.floor(Math.random() * level);
        // choose a random integer such that sum is not greater than maximum
        b = Math.floor(Math.random() * (level-a+1));
        // Question is a dynamicly created string, answer is calculated here
        // You need to call theQ here:
        quests.push(new theQ(a + ' + ' + b + ' = ', a+b));
    }

    var container = document.getElementById("drill");
    // Set the HTML for all questions
    container.innerHTML = quests.map(function (quest, i) {
        // Add the question to the drill section, give the input element an ID
        // that corresponds to the question number
        return quest.question + '<input placeholder="enter sum" id="answer' + i + '"><br>';
    }).join(''); // join all HTML pieces together into one string
}

function verify() {
    if (quests.length == 0) return; // Nothing to do
    // Count the number of wrong answers. Iterate over answers with reduce:
    var errorCount = quests.reduce(function (count, quest, i) {
        // Add 1 penalty if answer is incorrect
        return count + (quest.answer != document.getElementById('answer' + i).value);
    }, 0); // Atart counting from 0
    if (errorCount == 0)
        alert('Congratulations! You answered all questions correctly.');
    else
        alert('You have entered ' + errorCount + ' wrong answer(s). Try to correct them.');
}

<input type="text" id="maxR" placeholder="type maximum sum" />
<button id="activate" onclick="makeDrills()">Generate questions</button>
<div id="drill"></div>
<button id="verify" onclick="verify()">Verify</button>


问:
How to make unecesary text Messenger bot nodejs
So, I build a messenger bot using node js. How can I make:

Whenever user send a random text (except the right command) the Bot will reply "Sorry I cant recognize that command"..

How to make bot storing the Text from user and will confirm later ? Example :
USER : Hello.
BOT : What Else ?
USER : World.
BOT : What Else ?
USER : done.
BOT : I understood,
BOT : 1. Hello
BOT : 2. World
BOT : Is that correct ?

Here is my current scripts for no. 1 :

```<code>function replyByText(sender, text, payload) {
let kata = text.toLowerCase()
let date = new Date()
let current_hour = date.getHours()
if (S(kata).contains('produk') || S(kata).contains('produknya') || S(kata).contains('product')) {
    sendOpeningProduct(sender, "Wait Sec..")
}

if (S(kata).contains('layanan')|| S(kata).contains('services')|| S(kata).contains('diagnose')){
    // sendOpeningServices(sender, 'Wait sec..' )
    sendPlainMessage(sender, 'Hi, what concern you most about your health? Please describe your symptoms..' )
}

if (S(kata).contains('health symptoms')){
    sendPlainMessage(sender, 'Tell me What You Feel..' )
}

if (S(kata).contains('im feeling sick') || S(kata).contains('im feeling unwell') || S(kata).contains('im feeling dizzy') || S(kata).contains('dizzy') || S(kata).contains('sick')){
    sendPlainMessage(sender, 'How old are you ?' )
}

if (S(kata).contains('3') || S(kata).contains('4') || S(kata).contains('5') || S(kata).contains('6') || S(kata).contains('7') || S(kata).contains('8') || S(kata).contains('9')){
    sendPlainMessage(sender, 'I see...' )
    sendOpeningProductKids(sender, "Just try our products")
}}
</code>```

Any help will appreciate..

答:
Solution to No 1:

```<code>function replyByText(sender, text, payload) {
    let kata = text.toLowerCase()
    let date = new Date()
    let current_hour = date.getHours()

    if (S(kata).contains('produk') || S(kata).contains('produknya') || S(kata).contains('product')) {
        sendOpeningProduct(sender, "Wait Sec..")
    }

    else if (S(kata).contains('layanan')|| S(kata).contains('services')|| S(kata).contains('diagnose')){
        // sendOpeningServices(sender, 'Wait sec..' )
        sendPlainMessage(sender, 'Hi, what concern you most about your health? Please describe your symptoms..' )
    }

    else if (S(kata).contains('health symptoms')){
        sendPlainMessage(sender, 'Tell me What You Feel..' )
    }

    else if (S(kata).contains('im feeling sick') || S(kata).contains('im feeling unwell') || S(kata).contains('im feeling dizzy') || S(kata).contains('dizzy') || S(kata).contains('sick')){
        sendPlainMessage(sender, 'How old are you ?' )
    }

    else if (S(kata).contains('3') || S(kata).contains('4') || S(kata).contains('5') || S(kata).contains('6') || S(kata).contains('7') || S(kata).contains('8') || S(kata).contains('9')){
        sendPlainMessage(sender, 'I see...' )
        sendOpeningProductKids(sender, "Just try our products")
    }
    else{
        sendPlainMessage(sender, 'Sorry I cant recognize that command' )
    }

}
</code>```

Solution to No 2:

You will have to save state between each call to your webhook. follow these steps.

There are several ways to solve this problem. You may solve this problem this way. Save state by updating a covesation model/object on each webhook call. Use the user's unique psid got from facebook api as a primary key or as part of a composite key for the model/object

Body:
So, I build a messenger bot using node js. How can I make:

Whenever user send a random text (except the right command) the Bot will reply "Sorry I cant recognize that command"..

How to make bot storing the Text from user and will confirm later ? Example :
USER : Hello.
BOT : What Else ?
USER : World.
BOT : What Else ?
USER : done.
BOT : I understood,
BOT : 1. Hello
BOT : 2. World
BOT : Is that correct ?

Here is my current scripts for no. 1 :

function replyByText(sender, text, payload) {
let kata = text.toLowerCase()
let date = new Date()
let current_hour = date.getHours()
if (S(kata).contains('produk') || S(kata).contains('produknya') || S(kata).contains('product')) {
    sendOpeningProduct(sender, "Wait Sec..")
}

if (S(kata).contains('layanan')|| S(kata).contains('services')|| S(kata).contains('diagnose')){
    // sendOpeningServices(sender, 'Wait sec..' )
    sendPlainMessage(sender, 'Hi, what concern you most about your health? Please describe your symptoms..' )
}

if (S(kata).contains('health symptoms')){
    sendPlainMessage(sender, 'Tell me What You Feel..' )
}

if (S(kata).contains('im feeling sick') || S(kata).contains('im feeling unwell') || S(kata).contains('im feeling dizzy') || S(kata).contains('dizzy') || S(kata).contains('sick')){
    sendPlainMessage(sender, 'How old are you ?' )
}

if (S(kata).contains('3') || S(kata).contains('4') || S(kata).contains('5') || S(kata).contains('6') || S(kata).contains('7') || S(kata).contains('8') || S(kata).contains('9')){
    sendPlainMessage(sender, 'I see...' )
    sendOpeningProductKids(sender, "Just try our products")
}}

Any help will appreciate..

Body:
Solution to No 1:

function replyByText(sender, text, payload) {
    let kata = text.toLowerCase()
    let date = new Date()
    let current_hour = date.getHours()

    if (S(kata).contains('produk') || S(kata).contains('produknya') || S(kata).contains('product')) {
        sendOpeningProduct(sender, "Wait Sec..")
    }

    else if (S(kata).contains('layanan')|| S(kata).contains('services')|| S(kata).contains('diagnose')){
        // sendOpeningServices(sender, 'Wait sec..' )
        sendPlainMessage(sender, 'Hi, what concern you most about your health? Please describe your symptoms..' )
    }

    else if (S(kata).contains('health symptoms')){
        sendPlainMessage(sender, 'Tell me What You Feel..' )
    }

    else if (S(kata).contains('im feeling sick') || S(kata).contains('im feeling unwell') || S(kata).contains('im feeling dizzy') || S(kata).contains('dizzy') || S(kata).contains('sick')){
        sendPlainMessage(sender, 'How old are you ?' )
    }

    else if (S(kata).contains('3') || S(kata).contains('4') || S(kata).contains('5') || S(kata).contains('6') || S(kata).contains('7') || S(kata).contains('8') || S(kata).contains('9')){
        sendPlainMessage(sender, 'I see...' )
        sendOpeningProductKids(sender, "Just try our products")
    }
    else{
        sendPlainMessage(sender, 'Sorry I cant recognize that command' )
    }

}

Solution to No 2:

You will have to save state between each call to your webhook. follow these steps.

There are several ways to solve this problem. You may solve this problem this way. Save state by updating a covesation model/object on each webhook call. Use the user's unique psid got from facebook api as a primary key or as part of a composite key for the model/object


问:
Launching Baidu Map intent from custom app
Inside my app I am supplied with a shipment address. And when the user presses a button it launches an intent to google maps with that address as a parameter.

```<code>String uri = String.format(Locale.ENGLISH, "google.navigation:q=" + shipmentAdress);
                                                    Intent intent = new Intent(Intent.ACTION_VIEW,
                                                            Uri.parse(uri));
                                                    startActivity(intent);
</code>```

I would like to do the same thing for our customers in China that do not have access to Google Maps but to Baidu Maps. Keep in mind that I don't have GPS coords, just the address.

Does anyone know how I would go about doing that? All their documentation is in Chinese and so is their app, and I've only gotten so far with Google Translate.

I've got it down to something like "baidumap://map/geocoder?src=openApiDemo&address=" but it usually returns and error (I think, I used screenshots of the error and Pleco's OCR to sort of translate it.)

答:
Figured it out eventually:</p>

```<code>String uri = String.format(Locale.CHINA, "baidumap://map/navi?query=" + shipmentAdress);
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(uri));
startActivity(intent);
</code>```

Body:
Inside my app I am supplied with a shipment address. And when the user presses a button it launches an intent to google maps with that address as a parameter.

String uri = String.format(Locale.ENGLISH, "google.navigation:q=" + shipmentAdress);
                                                    Intent intent = new Intent(Intent.ACTION_VIEW,
                                                            Uri.parse(uri));
                                                    startActivity(intent);

I would like to do the same thing for our customers in China that do not have access to Google Maps but to Baidu Maps. Keep in mind that I don't have GPS coords, just the address.

Does anyone know how I would go about doing that? All their documentation is in Chinese and so is their app, and I've only gotten so far with Google Translate.

I've got it down to something like "baidumap://map/geocoder?src=openApiDemo&address=" but it usually returns and error (I think, I used screenshots of the error and Pleco's OCR to sort of translate it.)

Body:
Figured it out eventually:

String uri = String.format(Locale.CHINA, "baidumap://map/navi?query=" + shipmentAdress);
Intent intent = new Intent(Intent.ACTION_VIEW,
Uri.parse(uri));
startActivity(intent);


问:
How to access a variable in a singleton class used by a module in Play 2.5 scala
I made a scheduler in Play Framework 2.5 using akka quartz (https://github.com/theatrus/akka-quartz)

Everything is good until I want to cancel a job
because I can't access the variable holding the Cancellable object.

Below is the code:

This is for the module

RecurrentTaskModule.scala

```<code>class RecurrentTaskModule extends AbstractModule with AkkaGuiceSupport {
    override def configure() = {
        bindActor[WeatherHistoryApiActor]("weather-history-api-call")
        bind(classOf[RecurrentTask]).asEagerSingleton()
   }
}

@Singleton
class RecurrentTask @Inject() (actorSystem: ActorSystem,
@Named("weather-history-api-call") val weatherHistoryApiActor: ActorRef,
lifecycle: ApplicationLifecycle, scheduleModel: TxScheduleModel) {
    var scheduleMap: Map[String, Cancellable] = _
    val f = quartzActor ? AddCronSchedule(actorRef,
                    "%d %s %s %s %s %s".format(0,"*","*","*","*","*",
                    Message(""),true)

  val r = Await.result(f, timeout.duration).asInstanceOf[AddCronScheduleResult]
    r match {
        case AddCronScheduleSuccess(cancel: Cancellable) => {
            scheduleMap.put("%s".format(schedule._1), cancel)
        }
        case AddCronScheduleFailure(reason: Throwable) => {
        }
    }
}
</code>```

In my config

application.conf

```<code>play.modules.enabled += "tasks.RecurrentTaskModule"
</code>```

As you can see, if I can just access the

```<code>var scheduleMap
</code>```

I can easily cancel the the job by calling the Cancellable object in the map

By the way, I want to access it in my Application.scala (controller)

答:
You can inject your RecurrentTask singleton into your controller instance:

class Application @Inject() (recurrentTask: RecurrentTask) {

Body:
I made a scheduler in Play Framework 2.5 using akka quartz (https://github.com/theatrus/akka-quartz)

Everything is good until I want to cancel a job
because I can't access the variable holding the Cancellable object.

Below is the code:

This is for the module

RecurrentTaskModule.scala

class RecurrentTaskModule extends AbstractModule with AkkaGuiceSupport {
    override def configure() = {
        bindActor[WeatherHistoryApiActor]("weather-history-api-call")
        bind(classOf[RecurrentTask]).asEagerSingleton()
   }
}

@Singleton
class RecurrentTask @Inject() (actorSystem: ActorSystem,
@Named("weather-history-api-call") val weatherHistoryApiActor: ActorRef,
lifecycle: ApplicationLifecycle, scheduleModel: TxScheduleModel) {
    var scheduleMap: Map[String, Cancellable] = _
    val f = quartzActor ? AddCronSchedule(actorRef,
                    "%d %s %s %s %s %s".format(0,"*","*","*","*","*",
                    Message(""),true)

  val r = Await.result(f, timeout.duration).asInstanceOf[AddCronScheduleResult]
    r match {
        case AddCronScheduleSuccess(cancel: Cancellable) => {
            scheduleMap.put("%s".format(schedule._1), cancel)
        }
        case AddCronScheduleFailure(reason: Throwable) => {
        }
    }
}

In my config

application.conf

play.modules.enabled += "tasks.RecurrentTaskModule"

As you can see, if I can just access the

var scheduleMap

I can easily cancel the the job by calling the Cancellable object in the map

By the way, I want to access it in my Application.scala (controller)


问:
python extend list by incremental values
Is there a nice simple method for extending a list n times, and doing so incrementally based on the existing values?

Basically I'm extrapolating a gradient, but don't want to invoke numpy/scipy if I can really avoid it.

I have some lists, lets say:

```<code>x = [1,2,3,4,5]
y = [10,20,30,40,50]
</code>```

Where I have already got a value for the average of the pairwise differences (the 'average gradient' of the list). I would now like to extend each list (let's say 20 times, to a total length of 25 each), where each subsequent value added is the previous value plus the computed average difference (if this was negative, obviously it would decrease).

So, x[5] would evaluate to x[4] + gradient.

Thus, the x list would ultimately end up:

```<code>x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]
</code>```

Because the average difference in the original x = 1 (obviously this is just test data, in actuality I want to do this with more complicated floats in the y list.

答:
You could use list.extend() and a generator expression:

```<code>>>> x = [1, 2, 3, 4, 5]
>>> gradient, n = x[1]-x[0], 10
>>> x.extend(x[-1] + gradient for _ in range(1, n+1))
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
</code>```

For lists of integers you can also pass a range to list.extend():

```<code>>>> x.extend(range(x[-1]+gradient, x[-1] + gradient*n + 1, gradient))
</code>```

Body:
Is there a nice simple method for extending a list n times, and doing so incrementally based on the existing values?

Basically I'm extrapolating a gradient, but don't want to invoke numpy/scipy if I can really avoid it.

I have some lists, lets say:

x = [1,2,3,4,5]
y = [10,20,30,40,50]

Where I have already got a value for the average of the pairwise differences (the 'average gradient' of the list). I would now like to extend each list (let's say 20 times, to a total length of 25 each), where each subsequent value added is the previous value plus the computed average difference (if this was negative, obviously it would decrease).

So, x[5] would evaluate to x[4] + gradient.

Thus, the x list would ultimately end up:

x = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25]

Because the average difference in the original x = 1 (obviously this is just test data, in actuality I want to do this with more complicated floats in the y list.

Body:
You could use list.extend() and a generator expression:

>>> x = [1, 2, 3, 4, 5]
>>> gradient, n = x[1]-x[0], 10
>>> x.extend(x[-1] + gradient for _ in range(1, n+1))
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]

For lists of integers you can also pass a range to list.extend():

>>> x.extend(range(x[-1]+gradient, x[-1] + gradient*n + 1, gradient))


问:
isBundle() in Magento?
How do you tell if a product page is set up as a bundle in Magento 1.4?  I can't find a way to do it.</p>

答:
this code should work in your product page (catalog/product/view.phtml):</p>

```<code>$product = $this->getProduct();
if($product->getTypeId() === 'bundle'){
    // Something…
}
</code>```

Title: isBundle() in Magento?

Body:
this code should work in your product page (catalog/product/view.phtml):

$product = $this->getProduct();
if($product->getTypeId() === 'bundle'){
    // Something…
}


问:
Create an Asana task with External Data
I am having trouble creating an asana task with external data.  I can create a task fine, but i can't figure out what the cocktail is to be able to use the "external" data that is mentioned in the documentation.

```<code>$.ajax({
   url : global.task.url,
   type: "post",
   data: {
    assignee: "my-email@hidden.com",
    name: "Test task",
    notes: "this is a note",
    projects: 123123123123,
    workspace: global.workspace,
    external: {
     "id": "test",
     "data": "12345099"
    }
   },
   beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", "Bearer " + "MY-TOKEN");
   }
 })
</code>```

the above code results in a 500 bad request.

I have also tried sending external stringified, which results in the error "No matching route for request".

The code above works perfectly if i remove the "external" from data.

i will be the first to say i do not typically call APIs so i feel like i must be doing something silly.  any help appreciated!

UPDATE:

i was able to create a task by passing in external as:

```<code>'external.id' = "test",
'external.data' = "123123123"
</code>```

however, i do not see the external data i generated, so there is still something going on.

UPDATE (2):

if i run the code below, i will get a 500 server error.
if i comment out the "external" piece in the data, the tasks adds correctly.

```<code>$.ajax({
 url : "https://app.asana.com/api/1.0/tasks",
 contentType: "application/json",
 type: "post",
 beforeSend: function (xhr){
  xhr.setRequestHeader("Authorization", "Bearer " + settings.token);
 },
 data: JSON.stringify({
  data: {
   assignee: "my-email@hidden.com",
   name: "Test task",
   notes: "this is a note",
   projects: [5555555555555], //not the real one i am passing in
   external: {
    id: "testID",
    data: "some sweet data"
   },
   workspace: 555555555555 //not what i am really passing in
  }
 })
})
</code>```

答: The issue I had here was that I was passing in my external ID as an integer which kept returning a "Invalid Request" error from Asana. Once I converted it to a string the task creation with external data worked fine.</p>

Title: Create an Asana task with External Data

Body:
I am having trouble creating an asana task with external data.  I can create a task fine, but i can't figure out what the cocktail is to be able to use the "external" data that is mentioned in the documentation.

$.ajax({
   url : global.task.url,
   type: "post",
   data: {
    assignee: "my-email@hidden.com",
    name: "Test task",
    notes: "this is a note",
    projects: 123123123123,
    workspace: global.workspace,
    external: {
     "id": "test",
     "data": "12345099"
    }
   },
   beforeSend: function (xhr) {
    xhr.setRequestHeader("Authorization", "Bearer " + "MY-TOKEN");
   }
 })

the above code results in a 500 bad request.

I have also tried sending external stringified, which results in the error "No matching route for request".

The code above works perfectly if i remove the "external" from data.

i will be the first to say i do not typically call APIs so i feel like i must be doing something silly.  any help appreciated!

UPDATE:

i was able to create a task by passing in external as:

'external.id' = "test",
'external.data' = "123123123"

however, i do not see the external data i generated, so there is still something going on.

UPDATE (2):

if i run the code below, i will get a 500 server error.
if i comment out the "external" piece in the data, the tasks adds correctly.

$.ajax({
 url : "https://app.asana.com/api/1.0/tasks",
 contentType: "application/json",
 type: "post",
 beforeSend: function (xhr){
  xhr.setRequestHeader("Authorization", "Bearer " + settings.token);
 },
 data: JSON.stringify({
  data: {
   assignee: "my-email@hidden.com",
   name: "Test task",
   notes: "this is a note",
   projects: [5555555555555], //not the real one i am passing in
   external: {
    id: "testID",
    data: "some sweet data"
   },
   workspace: 555555555555 //not what i am really passing in
  }
 })
})


问:
AngularJS ng-options not binding to ng-model
There are similar questions here, but I still can't figure out what I'm doing wrong. I have ng-options populating a  tag in a form. In the form's submit controller when I console.log the ng-model it comes back undefined. I'd appreciate any help.

```<code><label ng-controller="educationController">
    select your level of education
    <select ng-model="selectedEducation" ng-options="education for education in degrees" required>
    </select>
  </label>
</code>```

this is the controller

```<code>angular.module('drsApp.reviewerApplication');
app.controller('educationController', educationController)
function educationController($scope){
$scope.degrees=[
  "Bachelor Degree",
  "Master Degree",
  "Doctorate Degree"
  ]
};
</code>```

this is in the form's controller

```<code>console.log("education: "+ $scope.selectedEducation);
</code>```

答:
It's showing undefined because you write the ng-model name wrong.The ng-model name should be "selectedEducation" instead of "education" like in console--

console.log("education: "+ $scope.selectedEducation);

you can check it here--

<!DOCTYPE html>

        select your level of education
        <select ng-model="selectedEducation" ng-options="education for education in degrees" required>
        </select>
        <button ng-click="formSubmit()">Submit</button>

```

Body:
There are similar questions here, but I still can't figure out what I'm doing wrong. I have ng-options populating a  tag in a form. In the form's submit controller when I console.log the ng-model it comes back undefined. I'd appreciate any help.

    select your level of education
    <select ng-model="selectedEducation" ng-options="education for education in degrees" required>
    </select>

this is the controller

angular.module('drsApp.reviewerApplication');
app.controller('educationController', educationController)
function educationController($scope){
$scope.degrees=[
  "Bachelor Degree",
  "Master Degree",
  "Doctorate Degree"
  ]
};

this is in the form's controller

console.log("education: "+ $scope.selectedEducation);

Body:
It's showing undefined because you write the ng-model name wrong.The ng-model name should be "selectedEducation" instead of "education" like in console--

console.log("education: "+ $scope.selectedEducation);

you can check it here--

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<body>

    <div ng-app="myApp" ng-controller="educationController">

        select your level of education
        <select ng-model="selectedEducation" ng-options="education for education in degrees" required>
        </select>
        <button ng-click="formSubmit()">Submit</button>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('educationController', function ($scope) {
            $scope.degrees=[
              "Bachelor Degree",
              "Master Degree",
              "Doctorate Degree"
         ];
            $scope.formSubmit=function (){
              console.log("education: "+ $scope.selectedEducation);
            }
        });

    </script>

</body>

</html>


问:
Stop JavaScript Timer from another Function
I have the following Javascript code

```<code> function scrollOpenTimed() {
            var openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
        }

function a() {
      var _ouibounce = ouibounce(document.getElementById('modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
        console.log('ouibounce fired!');
        // cancel the openTimer
        }
      });
}
</code>```

At the moment I have scrollOpen being triggered after 3 seconds.

I want to cancel the timer and stop scrollOpen function being triggered When the callback function in function a() / ouibounce() function is triggered.

Any ideas how to do this appreciated.

Thanks

答:
Move

```<code>var openTimer;
</code>```

outside of the function to make it global.

Body:
I have the following Javascript code

 function scrollOpenTimed() {
            var openTimer = setTimeout(function(){ scrollOpen(); }, 3000);
        }

function a() {
      var _ouibounce = ouibounce(document.getElementById('modal'), {
        aggressive: true,
        timer: 0,
        callback: function() {
        console.log('ouibounce fired!');
        // cancel the openTimer
        }
      });
}

At the moment I have scrollOpen being triggered after 3 seconds.

I want to cancel the timer and stop scrollOpen function being triggered When the callback function in function a() / ouibounce() function is triggered.

Any ideas how to do this appreciated.

Thanks

Body:
Move

var openTimer;

outside of the function to make it global.


问:
SQL Server- get manager of employee (with exceptions)
I am currently stuck with a (for me) quite complicated problem.

I have created following table with cte's:

```<code>EmployeeID | OrganisationID | Level | Manager1 | Manager2 | Manager3 | Manager4 | Manager5
1          | 1001           | 1     | NULL     | NULL     | NULL     | NULL     | NULL
8          | 1011           | 1     | 1        | NULL     | NULL     | NULL     | NULL
2          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
3          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
4          | 1003           | 4     | 1        | 2        | NULL     | 4        | NULL
5          | 1004           | 3     | NULL     | NULL     | 2        | NULL     | NULL
6          | 1005           | 5     | 1        | NULL     | 2        | 6        | 6
7          | 1006           | 5     | NULL     | 7        | 7        | NULL     | NULL
</code>```

What I want to get from this is the manager of each employee, based on their Level. So for someone from level 5, I need to get his Manager5 However, there are some conditions:

If the EmployeeID and the ManagerX have the same value, we need to look at ManagerX-1. (And if that's the same too, we go one higher again, etc)

If the ManagerX is empty, we need to look at ManagerX-1. (And if that's empty too, we go one higher again, etc)

For employees from level 1, we can just take the manager1

So what I would like as result would be:

```<code>EmployeeID | RealManager
1          | NULL
8          | 1
2          | 1
3          | 1
4          | 2
5          | 2
6          | 2
7          | NULL
</code>```

I only got this far

```<code>SELECT EmployeeID,
Case
    when level = 1 then Manager1
    when level = 2 then ISNULL(Manager2,Manager1)
    when level = 3 then ISNULL(Manager3,ISNULL(Manager2,Manager1))
    when level = 4 then ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1)))
    when level = 5 then ISNULL(Manager5,ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1))))
    else null
    END as RealManager
FROM cte
</code>```

But this doesn't check the first condition (and it doesn't look quite performant).

Any sugestions or ideas?

答:
I would do something like this:

--set to 'null' all managers that have same value as employees
;with cte2 (EmployeeID, Level, Manager1, Manager2, Manager3, Manager4, Manager5)
as
(
    select
        EmployeeID
        ,Level
        ,Manager1
        ,case when Manager2 = EmployeeID then null else Manager2 end as Manager2
        ,case when Manager3 = EmployeeID then null else Manager3 end as Manager3
        ,case when Manager4 = EmployeeID then null else Manager4 end as Manager4
        ,case when Manager5 = EmployeeID then null else Manager5 end as Manager5
    from cte
)

--now just select the first non-null manager based on employee's level
select
    EmployeeID
    ,case Level
        when 1 then Manager1
        when 2 then coalesce(Manager2, Manager1)
        when 3 then coalesce(Manager3, Manager2, Manager1)
        when 4 then coalesce(Manager4, Manager3, Manager2, Manager1)
        when 5 then coalesce(Manager5, Manager4, Manager3, Manager2, Manager1)
    end as RealManager
from cte2
```

Body:
I am currently stuck with a (for me) quite complicated problem.

I have created following table with cte's:

EmployeeID | OrganisationID | Level | Manager1 | Manager2 | Manager3 | Manager4 | Manager5
1          | 1001           | 1     | NULL     | NULL     | NULL     | NULL     | NULL
8          | 1011           | 1     | 1        | NULL     | NULL     | NULL     | NULL
2          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
3          | 1002           | 2     | 1        | 1        | NULL     | NULL     | NULL
4          | 1003           | 4     | 1        | 2        | NULL     | 4        | NULL
5          | 1004           | 3     | NULL     | NULL     | 2        | NULL     | NULL
6          | 1005           | 5     | 1        | NULL     | 2        | 6        | 6
7          | 1006           | 5     | NULL     | 7        | 7        | NULL     | NULL

What I want to get from this is the manager of each employee, based on their Level. So for someone from level 5, I need to get his Manager5 However, there are some conditions:

If the EmployeeID and the ManagerX have the same value, we need to look at ManagerX-1. (And if that's the same too, we go one higher again, etc)

If the ManagerX is empty, we need to look at ManagerX-1. (And if that's empty too, we go one higher again, etc)

For employees from level 1, we can just take the manager1

So what I would like as result would be:

EmployeeID | RealManager
1          | NULL
8          | 1
2          | 1
3          | 1
4          | 2
5          | 2
6          | 2
7          | NULL

I only got this far

SELECT EmployeeID,
Case
    when level = 1 then Manager1
    when level = 2 then ISNULL(Manager2,Manager1)
    when level = 3 then ISNULL(Manager3,ISNULL(Manager2,Manager1))
    when level = 4 then ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1)))
    when level = 5 then ISNULL(Manager5,ISNULL(Manager4,ISNULL(Manager3,ISNULL(Manager2,Manager1))))
    else null
    END as RealManager
FROM cte

But this doesn't check the first condition (and it doesn't look quite performant).

Any sugestions or ideas?


问:
Calculating the difference between dates not working and giving an huge error
Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y  H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.

This is how I do the check if the coupon is expired:

```<code>if ($date1B > $date2B) {
   echo "<script>alert('Expired coupon!!');</script>";
}
</code>```

Now what I want is to calculate the days when the coupon will be expired.

This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.

```<code>$date1 = date("d-m-Y  H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
</code>```

When I replace variables with the existing variables I get these errors:

date_diff() expects parameter 1 to be DateTimeInterface, string given in

and

Call to a member function format() on boolean in

The full .PHP page:

```<code><?php
   date_default_timezone_set("America/Curacao");

   $date1A = date("d/m/Y  H:i:s");
   $date1B = date("dmYHis");
   $date2B = "27032017042100";
   $date2A = date_create_from_format('dmYHis', $date2B);

   echo "Datum 1: " . $date1A . "<br>" ;
   echo "Datum 1: " . $date1B . "<br><br>";
   echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "<br>";
   echo "Datum 2: " . $date2B . "<br>";

   if ($date1B > $date2B) {
      echo "<script>alert('Klaar!!');</script>";
   }

   $date1 = date("d/m/Y  H:i:s");
   $date2 = date_format($date2A, 'd/m/Y H:i:s');
   $diff = date_diff($date1,$date2);
   echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>
</code>```

答:
Based on @ShaktiPhartiyal answer, to output in the format that you want, just use:

```<code>$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
</code>```

And the output will be:

```<code>1154 days 0 Hours 0 Minute 0 Seconds
</code>```

Body:
Hi I'm making an online coupon system for mobile devices. The coupons are for a limited time active and I have to do a check on the coupons. I use date(d/m/Y  H:i:s) for just showing the date and time, and I also have a expire date which is a just a string that I later convert into a date.

This is how I do the check if the coupon is expired:

if ($date1B > $date2B) {
   echo "";
}

Now what I want is to calculate the days when the coupon will be expired.

This is what I found on W3Schools, but the example below uses date_create(), so you make an custom date and time. I already have 2 dates and times.

$date1 = date("d-m-Y  H:i:s");
$date2 = date_format($date2A, 'd-m-Y H:i:s');
$diff = date_diff($date1,$date2);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");

When I replace variables with the existing variables I get these errors:

date_diff() expects parameter 1 to be DateTimeInterface, string given in

and

Call to a member function format() on boolean in

The full .PHP page:

<?php
   date_default_timezone_set("America/Curacao");

   $date1A = date("d/m/Y  H:i:s");
   $date1B = date("dmYHis");
   $date2B = "27032017042100";
   $date2A = date_create_from_format('dmYHis', $date2B);

   echo "Datum 1: " . $date1A . "
" ;
   echo "Datum 1: " . $date1B . "

";
   echo "Datum 2: " . date_format($date2A, 'd/m/Y H:i:s') . "
";
   echo "Datum 2: " . $date2B . "
";

   if ($date1B > $date2B) {
      echo "";
   }

   $date1 = date("d/m/Y  H:i:s");
   $date2 = date_format($date2A, 'd/m/Y H:i:s');
   $diff = date_diff($date1,$date2);
   echo $diff->format("%a days %h Hours %i Minute %s Seconds ");
?>

Body:
Based on @ShaktiPhartiyal answer, to output in the format that you want, just use:

$startDate = date_create('2014-06-13');
$endDate = date_create('2017-08-10');
$diff = date_diff($startDate, $endDate);
echo $diff->format("%a days %h Hours %i Minute %s Seconds ");

And the output will be:

1154 days 0 Hours 0 Minute 0 Seconds


问:
How to send a device management request using NodeRed or any REST client
I am trying to sent a DM firmware update command from a NodeRed Flow.

Function node:

```<code>msg.payload = {"MgmtInitiationRequest": {
"action":"firmware/update",
"devices": [{
"typeId": "myType",
"deviceId": "myDevice"
}]

}}
msg.headers={"Content-Type":"application/json"}
return msg;
</code>```

I send it to a http request node with a POST to

```<code>https://orgid.internetofthings.ibmcloud.com/api/v0002/mgmt/requests
</code>```

Basic Authentication with api keys.  I based it of Initiate a device management request

I get back a 403 which the docs have as:

One or more of the devices does not support the requested action

Anyone see what I'm missing?  It works fine from the IoT Platform UI to the same devicetype/deviceid.

EDIT: Same 403 if I use a Rest client like Postman.

答:
Has your appliance published the set of supported commands it supports when it announced itself as a managed device?

A device connects to the Watson IoT Platform and uses the managed devices operation to become a managed device.

Which looks something like this

Topic: iotdevice-1/mgmt/manage

{
...
        "supports": {
            "deviceActions": true,
            "firmwareActions": boolean
        },
...
    },
...
}

https://console.ng.bluemix.net/docs/services/IoT/devices/device_mgmt/index.html

Body:
I am trying to sent a DM firmware update command from a NodeRed Flow.

Function node:

msg.payload = {"MgmtInitiationRequest": {
"action":"firmware/update",
"devices": [{
"typeId": "myType",
"deviceId": "myDevice"
}]

}}
msg.headers={"Content-Type":"application/json"}
return msg;

I send it to a http request node with a POST to

https://orgid.internetofthings.ibmcloud.com/api/v0002/mgmt/requests

Basic Authentication with api keys.  I based it of Initiate a device management request

I get back a 403 which the docs have as:

One or more of the devices does not support the requested action

Anyone see what I'm missing?  It works fine from the IoT Platform UI to the same devicetype/deviceid.

EDIT: Same 403 if I use a Rest client like Postman.


问:
Create virtual uart on stm32 microcontroller
I need to create a virtual uart port on a stm32 microcontroller. The pins are given and can be changed to timer input channels. The recieving signal is going to be modulated in current and voltage and i need to detect both. Those two pins can not be assigned to a uart. Does somebody has a tutorial or something, that can lead me in the right direction? I just started programming microcontrollers and i am still strugeling with all the timer, interrupts and details stuff.</p>

答:
If we are talking aobut baudrates for small (9600), then you can achieve this with timer and EXTI.
On EXTI set pin to rising and falling edge and between each IRQs check timer value.

If value is greater than start and stop condition time, you failed, else you have to check time spent for EXTi and calculate whether you received 10101010 or 11001100 or any other combination.

For TX mode, use timer for precise interrupts at bit slice for UART output data and create state machine for data output bit by bit.

Another option is to use SPI as virtual UART.


问:
Remote control for Autodesk Forge Viewer
Remote control for Autodesk Forge Viewer. Allows to interact with Viewer using Natural Language or Speech Recognition interfaces to perform conversation in chat-like mode.

Currently works fine in Google Chrome and Mozilla Firefox due a Speech-To-Text issues.

Feel free to check it on GitHub repository: viewer-remote

答:
Thank you for raising this issue here for all to evaluate and discuss!

You also say: "Probably you could suggest some more places to discuss this with developers?"

Not really. This is probably the best place, and I can think of no other ones. We are trying to concentrate all questions and discussions on Forge related technical issues here on StackOverflow.


问:
Is a UserControl not in the HitTestResult?
I defined a usercontrol:

```<code><s:SurfaceUserControl x:Class="Prototype_Concept_1.CodeBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:s="http://schemas.microsoft.com/surface/2008">
    <Grid>

            <Viewbox>
                <s:SurfaceScrollViewer Margin="10,10,10,10"
        x:Name="scroll"
        Width="250"
        Height="250"
        VerticalScrollBarVisibility="Visible"
        HorizontalScrollBarVisibility="Visible"
        CanContentScroll="True">
                    <RichTextBox
           Name="TextInput"
            AcceptsReturn="True"
                TextChanged="TextChangedEventHandler"
            Width="350"
            ScrollViewer.VerticalScrollBarVisibility="Hidden"
            ScrollViewer.HorizontalScrollBarVisibility="Hidden">
                        <RichTextBox.Document>
                            <FlowDocument Name="flowDocument">
                            </FlowDocument>
                        </RichTextBox.Document>
                        <RichTextBox.Resources>
                            <Style TargetType="{x:Type Paragraph}">
                                <Setter Property="Margin" Value="0"/>
                            </Style>
                        </RichTextBox.Resources>
                    </RichTextBox>
                </s:SurfaceScrollViewer>
            </Viewbox>

    </Grid>
</s:SurfaceUserControl>
</code>```

Then i use a TagVisualization and do a custom Hittest:

```<code>private void TagVisualizer_VisualizationAdded(object sender, TagVisualizerEventArgs e)
        {

            Point pt = e.TagVisualization.Center;

            // Perform the hit test against a given portion of the visual object tree.
           hitResultsList.Clear();

            // Set up a callback to receive the hit test result enumeration.
            VisualTreeHelper.HitTest(MainGrid,
                              null,
                              new HitTestResultCallback(MyHitTestResult),
                              new PointHitTestParameters(pt));

            // Perform actions on the hit test results list.
            if (hitResultsList.Count > 0)
            {
                Console.WriteLine("Number of hits: " + hitResultsList.Count);
                foreach (DependencyObject o in hitResultsList)
                {

                    if (e.TagVisualization is LoupeTagVisualization)
                    {
                        if (o.GetType() == typeof(Ellipse))
                        {
                            Console.WriteLine(((o as Ellipse).Tag as SourceFile).getName());

                            CodeBox cb = new CodeBox();

                            MainScatter.Items.Add(cb);

                            break;
                        }
                    }
                    else if (e.TagVisualization is BinTagVisualization)
                    {
                        Console.WriteLine("BinTagVisualization");
                        Console.WriteLine(o.GetType());
                        if (o.GetType() == typeof(CheckBox))
                        {
                            (o as CheckBox).Visibility = System.Windows.Visibility.Collapsed;
                        }
                    }
                }
            }

        }

        // Return the result of the hit test to the callback.
        public HitTestResultBehavior MyHitTestResult(HitTestResult result)
        {
            // Add the hit test result to the list that will be processed after the enumeration.
            hitResultsList.Add(result.VisualHit);

            // Set the behavior to return visuals at all z-order levels.
            return HitTestResultBehavior.Continue;
        }
</code>```

The problem is, I don't actually see the Codebox in the results, only the UI elements (grid, border, surfacescrollviewer, etc) that the Codebox is composed of. But how can I get the Codebox itself?

I set isHittestVisible to true

答: Try setting the user control's background to Transparent. Sometimes in WPF, a null ({x:null}, the default) background prevents hit-testability

OwnerDisplayName: anon

Body:
I defined a usercontrol:

<s:SurfaceUserControl x:Class="Prototype_Concept_1.CodeBox"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:s="http://schemas.microsoft.com/surface/2008">
    <Grid>

            <Viewbox>
                <s:SurfaceScrollViewer Margin="10,10,10,10"
        x:Name="scroll"
        Width="250"
        Height="250"
        VerticalScrollBarVisibility="Visible"
        HorizontalScrollBarVisibility="Visible"
        CanContentScroll="True">
                    <RichTextBox
           Name="TextInput"
            AcceptsReturn="True"
                TextChanged="TextChangedEventHandler"
            Width="350"
            ScrollViewer.VerticalScrollBarVisibility="Hidden"
            ScrollViewer.HorizontalScrollBarVisibility="Hidden">
                        <RichTextBox.Document>
                            <FlowDocument Name="flowDocument">
                            </FlowDocument>
                        </RichTextBox.Document>
                        <RichTextBox.Resources>

                        </RichTextBox.Resources>
                    </RichTextBox>
                </s:SurfaceScrollViewer>
            </Viewbox>

    </Grid>
</s:SurfaceUserControl>

Then i use a TagVisualization and do a custom Hittest:

private void TagVisualizer_VisualizationAdded(object sender, TagVisualizerEventArgs e)
        {

            Point pt = e.TagVisualization.Center;

            // Perform the hit test against a given portion of the visual object tree.
           hitResultsList.Clear();

            // Set up a callback to receive the hit test result enumeration.
            VisualTreeHelper.HitTest(MainGrid,
                              null,
                              new HitTestResultCallback(MyHitTestResult),
                              new PointHitTestParameters(pt));

            // Perform actions on the hit test results list.
            if (hitResultsList.Count > 0)
            {
                Console.WriteLine("Number of hits: " + hitResultsList.Count);
                foreach (DependencyObject o in hitResultsList)
                {

                    if (e.TagVisualization is LoupeTagVisualization)
                    {
                        if (o.GetType() == typeof(Ellipse))
                        {
                            Console.WriteLine(((o as Ellipse).Tag as SourceFile).getName());

                            CodeBox cb = new CodeBox();

                            MainScatter.Items.Add(cb);

                            break;
                        }
                    }
                    else if (e.TagVisualization is BinTagVisualization)
                    {
                        Console.WriteLine("BinTagVisualization");
                        Console.WriteLine(o.GetType());
                        if (o.GetType() == typeof(CheckBox))
                        {
                            (o as CheckBox).Visibility = System.Windows.Visibility.Collapsed;
                        }
                    }
                }
            }

        }

        // Return the result of the hit test to the callback.
        public HitTestResultBehavior MyHitTestResult(HitTestResult result)
        {
            // Add the hit test result to the list that will be processed after the enumeration.
            hitResultsList.Add(result.VisualHit);

            // Set the behavior to return visuals at all z-order levels.
            return HitTestResultBehavior.Continue;
        }

The problem is, I don't actually see the Codebox in the results, only the UI elements (grid, border, surfacescrollviewer, etc) that the Codebox is composed of. But how can I get the Codebox itself?

I set isHittestVisible to true


问:
Ant Design - prevent table row click in specific column/area
I'm using ant design table component. I have "actions" column that I don't want the onRowClick event will trigger in this column.

How can it be done?

http://codepen.io/liron_e/pen/zZjVKZ?editors=001

```<code>const { Table, Modal } = antd;

const confirm = (id) => {
  Modal.confirm({
    title: 'Confirm',
    content: 'Bla bla ...',
    okText: 'OK',
    cancelText: 'Cancel',
  });
};

const info = (id) => {
  Modal.info({
    title: 'Info',
    content: 'Bla bla ...',
    okText: 'OK',
    cancelText: 'Cancel',
  });
};

const columns = [
  {
    key: 'status',
    title: 'text',
    dataIndex: 'text'
  }, {
    key: 'actions',
    title: 'actions',
    dataIndex: 'id',
    render: (id) => {
      return (
        <span>
          <a href="#" onClick={() => confirm(id)}>
            Clone
          </a>
          <span className="ant-divider" />
          <a href="#" onClick={() => confirm(id)}>
            Replace
          </a>
        </span>
      );
    }
  }
];

 const dataSource = [
   {
     id: '1',
     text: 'Hello'
   },{
     id: '123',
     text: 'adsaddas'
   },{
     id: '123344',
     text: 'cvbbcvb'
   },{
     id: '5665',
     text: 'aasddasd'
   },
 ];

ReactDOM.render(
  <div>
    <Table
      columns={columns}
      onRowClick={() => this.info()}
      dataSource={dataSource}
    />
  </div>
, mountNode);
</code>```

As you can try when pressing on row the info modal would open.
When pressing some action the info and the confirm modals would open, and I would like that only confirm modal would open.

Thanks (:

答:
Just stop propagation in your action handler:

     confirm(id)}>
        Clone

     confirm(id)}>
        Replace

Body:
I'm using ant design table component. I have "actions" column that I don't want the onRowClick event will trigger in this column.

How can it be done?

http://codepen.io/liron_e/pen/zZjVKZ?editors=001

const { Table, Modal } = antd;

const confirm = (id) => {
  Modal.confirm({
    title: 'Confirm',
    content: 'Bla bla ...',
    okText: 'OK',
    cancelText: 'Cancel',
  });
};

const info = (id) => {
  Modal.info({
    title: 'Info',
    content: 'Bla bla ...',
    okText: 'OK',
    cancelText: 'Cancel',
  });
};

const columns = [
  {
    key: 'status',
    title: 'text',
    dataIndex: 'text'
  }, {
    key: 'actions',
    title: 'actions',
    dataIndex: 'id',
    render: (id) => {
      return (

           confirm(id)}>
            Clone

           confirm(id)}>
            Replace

      );
    }
  }
];

 const dataSource = [
   {
     id: '1',
     text: 'Hello'
   },{
     id: '123',
     text: 'adsaddas'
   },{
     id: '123344',
     text: 'cvbbcvb'
   },{
     id: '5665',
     text: 'aasddasd'
   },
 ];

ReactDOM.render(

 this.info()}
      dataSource={dataSource}
    />

, mountNode);

As you can try when pressing on row the info modal would open.
When pressing some action the info and the confirm modals would open, and I would like that only confirm modal would open.

Thanks (:

Body:
Just stop propagation in your action handler:

<span>
    <a href="#" onClick={() => confirm(id)}>
        Clone
    </a>
    <span className="ant-divider" />
    <a href="#" onClick={() => confirm(id)}>
        Replace
    </a>
</span>


问:
HttpContext.Authentication.SignOutAsync does not delete auth cookie
According to ASP.NET Core documentation the method  HttpContext.Authentication.SignOutAsync() must delete the authentication cookie as well.

Signing out

To sign out the current user, and delete their cookie (italics mine - A.C.) call the following inside your controller

await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance");

But it does not! Everything else seems okay, esp. auth scheme, because user gets signed-in  correctly and the cookie .AspNetCore. is created.

Any ideas why cookie remains after the user's sing-out?

答:
I solved the problem with deleting my site cookies with the following snippet placed in my Logout() method in the controller. I found that multiple cookies would be created by my site.

```<code>// Delete the authentication cookie(s) we created when user signed in
            if (HttpContext.Request.Cookies[".MyCookie"] != null)
            {
                var siteCookies = HttpContext.Request.Cookies.Where(c => c.Key.StartsWith(".MyCookie"));
                foreach (var cookie in siteCookies)
                {
                    Response.Cookies.Delete(cookie.Key);
                }
            }
</code>```

And in Startup.cs:

```<code>app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationScheme = "Cookies",
                LoginPath = new PathString("/Account/Login/"),
                AccessDeniedPath = new PathString("/Home/Index/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName = ".MyCookie"
            });
</code>```

Notice that I do not use await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance"); since I am using OpenIdConnect with Google.

Body:
I solved the problem with deleting my site cookies with the following snippet placed in my Logout() method in the controller. I found that multiple cookies would be created by my site.

// Delete the authentication cookie(s) we created when user signed in
            if (HttpContext.Request.Cookies[".MyCookie"] != null)
            {
                var siteCookies = HttpContext.Request.Cookies.Where(c => c.Key.StartsWith(".MyCookie"));
                foreach (var cookie in siteCookies)
                {
                    Response.Cookies.Delete(cookie.Key);
                }
            }

And in Startup.cs:

app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AuthenticationScheme = "Cookies",
                LoginPath = new PathString("/Account/Login/"),
                AccessDeniedPath = new PathString("/Home/Index/"),
                AutomaticAuthenticate = true,
                AutomaticChallenge = true,
                CookieName = ".MyCookie"
            });

Notice that I do not use await HttpContext.Authentication.SignOutAsync("MyCookieMiddlewareInstance"); since I am using OpenIdConnect with Google.


问:
Multiple select option text standing under the checkbox in materialize.css
In the example you see below, the text (Faculty not selected) stands under the checkbox, i didn't get any special features when i checked the attributes from style palette. Normally text should be near the checkbox. Any idea about the problem?

```<code><div class="container">
    <div class="row">
      <form class="col s12">
          <div class="row mt50">
            <div class="input-field col s3">
                <select class="validate faculty" name="faculty" id="faculty" onchange="getCourse();">
                    <option value="">Choose</option>
                    <option value="FEng">Faculty of Engineering</option>
                    <option value="FMed">Faculty of Medicine</option>
                    <option value="FSci">Faculty of Science</option>
                </select>
                <label for="faculty">Faculty</label>
              </div>
              <div class="input-field col s4">
                <select name="course" id="course" multiple>
                    <option value="" disabled>Faculty not selected</option>
                <select/>
                <label for="course">Course</label>
              </div>
          </div>
      </form>
    </div>
</div>
</code>```

答: You just need to add either display:inline or display:flex on #course. Something is probably making the checkbox display:block by default.</p>

Body:
In the example you see below, the text (Faculty not selected) stands under the checkbox, i didn't get any special features when i checked the attributes from style palette. Normally text should be near the checkbox. Any idea about the problem?

      <form class="col s12">

                <select class="validate faculty" name="faculty" id="faculty" onchange="getCourse();">
                    <option value="">Choose</option>
                    <option value="FEng">Faculty of Engineering</option>
                    <option value="FMed">Faculty of Medicine</option>
                    <option value="FSci">Faculty of Science</option>
                </select>
                Faculty

                <select name="course" id="course" multiple>
                    <option value="" disabled>Faculty not selected</option>
                <select/>
                Course

      </form>


问:
How to find memory leak with com.opensymphony.oscache on legacy java application
I have an old legacy Java application that several times per week just starts to be very slow and I have to restart Tomcat.

I checked New Relic Top Transactions and Error logs but I can't find the source of the problem, it seems the top transactions are more a consequence than a source of the problem.

So, I suppose it could be a memory leak and I did a heap dump and tried to analyze it on Eclipse Memory Analyser but I'm having difficulties in identifying the memory leak and if it is really a memory leak.

It seams the problem suspect 1 is com.opensymphony.oscache.web.ServletCache.

These are some of the results of Memory Analyser:

Also, this is VisualVM monitor:

Thank you!
Any help or guidance with this would be very helpful!

This is oscache.properties file:

```<code>cache.memory=true
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener
cache.path=/home/oscache/tb
</code>```

答:
I would suggest to use trial version of YourKit Java Profiler ,it will give you much more detail about your legacy application code.
Here is link : I  used this tool back in 2014 as a trial version to detect memory leaks in a Web Application based on struts 2 and Hibernate.

Your Kit

Body:
I have an old legacy Java application that several times per week just starts to be very slow and I have to restart Tomcat.

I checked New Relic Top Transactions and Error logs but I can't find the source of the problem, it seems the top transactions are more a consequence than a source of the problem.

So, I suppose it could be a memory leak and I did a heap dump and tried to analyze it on Eclipse Memory Analyser but I'm having difficulties in identifying the memory leak and if it is really a memory leak.

It seams the problem suspect 1 is com.opensymphony.oscache.web.ServletCache.

These are some of the results of Memory Analyser:

Also, this is VisualVM monitor:

Thank you!
Any help or guidance with this would be very helpful!

This is oscache.properties file:

cache.memory=true
cache.persistence.class=com.opensymphony.oscache.plugins.diskpersistence.HashDiskPersistenceListener
cache.path=/home/oscache/tb