问:
Can I change an item inside customArray
hello I want to modify some data inside custom ArrayList

my Custom Array

```<code>public class Item_GetMembers {

    String userid,username,gender,admin,ban,type;

    public Item_GetMembers(String userid, String username, String gender, String admin, String ban, String type) {
        this.userid = userid;
        this.username = username;
        this.gender = gender;
        this.admin = admin;
        this.ban = ban;
        this.type = type;
    }
}
</code>```

I want to modify ban from 0 to 1 postion 3 Can I do it from the same page or not?

my Adapter

```<code> public class Adapter_GetMembers extends RecyclerView.Adapter<Adapter_GetMembers.AdapterHolder>{

        ArrayList<Item_GetMembers> CategoriesList;
        Context context;

        public Adapter_GetMembers(Context context , ArrayList<Item_GetMembers> categories) {
            this.context = context;
            CategoriesList = categories;
        }

        @Override
        public AdapterHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_getmembers,parent,false);
            AdapterHolder adapterHolder = new AdapterHolder(v);

            return adapterHolder;
        }

        @Override
        public void onBindViewHolder(final AdapterHolder holder, final int position) {
            final Item_GetMembers item_getMembers = CategoriesList.get(position);
item_getMembers.ban.get(3,1); //but wrong why??

        }

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

        class AdapterHolder extends RecyclerView.ViewHolder
        {

            public AdapterHolder(View itemView) {
                super(itemView);

            }
        }
</code>```

}

can I edit data within it? I tried a lot to modify it but it did not work
  , thanks in advance

答:
Try this</p>

```<code>@Override
public void onBindViewHolder(final AdapterHolder holder, final int position) {
    final Item_GetMembers item_getMembers = CategoriesList.get(position);
    //It means if your position is zero then zero position item will move at third position
    if(position == 0)
       moveItem(3, item_getMembers);

}

private void moveItem(int toItemPos, Item_GetMembers item)
{
   for(int i = 0; i < CategoriesList.size(); i++){
        if(toItemPos == i){
            CategoriesList.add(i, item)
            break;
        }
   }
   notifyDataSetChanged();
}
</code>```

Title: Can I change an item inside customArray

Body:
hello I want to modify some data inside custom ArrayList

my Custom Array

public class Item_GetMembers {

    String userid,username,gender,admin,ban,type;

    public Item_GetMembers(String userid, String username, String gender, String admin, String ban, String type) {
        this.userid = userid;
        this.username = username;
        this.gender = gender;
        this.admin = admin;
        this.ban = ban;
        this.type = type;
    }
}

I want to modify ban from 0 to 1 postion 3 Can I do it from the same page or not?

my Adapter

 public class Adapter_GetMembers extends RecyclerView.Adapter<Adapter_GetMembers.AdapterHolder>{

        ArrayList<Item_GetMembers> CategoriesList;
        Context context;

        public Adapter_GetMembers(Context context , ArrayList<Item_GetMembers> categories) {
            this.context = context;
            CategoriesList = categories;
        }

        @Override
        public AdapterHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_getmembers,parent,false);
            AdapterHolder adapterHolder = new AdapterHolder(v);

            return adapterHolder;
        }

        @Override
        public void onBindViewHolder(final AdapterHolder holder, final int position) {
            final Item_GetMembers item_getMembers = CategoriesList.get(position);
item_getMembers.ban.get(3,1); //but wrong why??

        }

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

        class AdapterHolder extends RecyclerView.ViewHolder
        {

            public AdapterHolder(View itemView) {
                super(itemView);

            }
        }

}

can I edit data within it? I tried a lot to modify it but it did not work
  , thanks in advance

Body:
Try this

@Override
public void onBindViewHolder(final AdapterHolder holder, final int position) {
    final Item_GetMembers item_getMembers = CategoriesList.get(position);
    //It means if your position is zero then zero position item will move at third position
    if(position == 0)
       moveItem(3, item_getMembers);

}

private void moveItem(int toItemPos, Item_GetMembers item)
{
   for(int i = 0; i < CategoriesList.size(); i++){
        if(toItemPos == i){
            CategoriesList.add(i, item)
            break;
        }
   }
   notifyDataSetChanged();
}


来源: stackexchange

问:
populate drop down list with month/year
I have a date and I need to populate a drop-down with the months/years between that date and today. For instance, if that date is 10/14/2010 then the drop-down should contain October 2010, November 2010, December 2010, January 2011.

The way I'm thinking of doing this is to pass that date to a function, loop from today backwards step 1 month while adding each month to a collection until we reach that date and finally return a collection of strings. Then, populate the drop-down control on page load. Finally, use some ajax with a page method to parse back the string and trigger a partial page reload.

I'm just wondering if there's an easy way to do it.

Thanks.

答:
Maybe you can try this:

```<code>static IEnumerable<DateTime> monthsBetween(DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate.Year - startDate.Year) * 12 + (endDate.Month - startDate.Month + 1))
                         .Select(m => new DateTime(startDate.Year, startDate.Month, 1).AddMonths(m));
    }
</code>```

This will not give you the result in the exact format that you want, but you get the drift. :)

ContentLicense: CC BY-SA 3.0

Title: populate drop down list with month/year

Body:
Maybe you can try this:

static IEnumerable<DateTime> monthsBetween(DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate.Year - startDate.Year) * 12 + (endDate.Month - startDate.Month + 1))
                         .Select(m => new DateTime(startDate.Year, startDate.Month, 1).AddMonths(m));
    }

This will not give you the result in the exact format that you want, but you get the drift. :)

ContentLicense: CC BY-SA 2.5


问:
Google sample BluetoothAdvertisements not detecting advertisements
I have a BLE wearable (running on Tizen 3.0) sending out BLE advertisements. The advertisements get immediately detected by the Nordic nRF Android App.

However, the BluetoothAdvertisements Google sample app detects none.

In ScannerFragment.buildScanFilters(), I did set the filters to see all BLE devices around.

The platform is Android 8.1.0 on Google Pixel.

Any suggestions will be greatly appreciated.

]
]

答:
Apps also need location permission for BLE scans now.does this sample has location permission at Runtime?

PS.
posted this as  answer after @user2551017 said it resolved the issue


问:
Windows Universal App - MediaElement and M3U
is it possible to open up a m3u webradio stream in a MediaElement class in Windows 10?

Sample stream would be
http://www.antenne.de/webradio/channels/top-40.m3u

Opening normal mp3 in the internet work perfect but i do not get any m3u file opened.

Kind regards
Michael

答:
Starting from Windows 10 version 1607, it is recommended to use the MediaPlayer class instead of MediaElement for media playback & The lightweight XAML control MediaPlayerElement.

Then you can use the MediaPlaybackList to create playlist for the MediaPlayer.

```<code>StorageFolder vfolder = Windows.Storage.KnownFolders.VideosLibrary;
StorageFileQueryResult query = vfolder.CreateFileQueryWithOptions(Constants.QueryOptions);
var files = await query.GetFilesAsync();

MediaPlaybackList playbackList = new MediaPlaybackList();

foreach (StorageFile file in files)
        {
            MediaSource source = MediaSource.CreateFromStorageFile(file);
            playbackList.Items.Add(new MediaPlaybackItem(source));
        }

_mediaPlayer = new MediaPlayer();
_mediaPlayer.AutoPlay = true;
_mediaPlayer.Source = playbackList;
MPElement.SetMediaPlayer(_mediaPlayer);
_mediaPlayer.Play();
</code>```

More information Microsoft Docs

Body:
Starting from Windows 10 version 1607, it is recommended to use the MediaPlayer class instead of MediaElement for media playback & The lightweight XAML control MediaPlayerElement.

Then you can use the MediaPlaybackList to create playlist for the MediaPlayer.

StorageFolder vfolder = Windows.Storage.KnownFolders.VideosLibrary;
StorageFileQueryResult query = vfolder.CreateFileQueryWithOptions(Constants.QueryOptions);
var files = await query.GetFilesAsync();

MediaPlaybackList playbackList = new MediaPlaybackList();

foreach (StorageFile file in files)
        {
            MediaSource source = MediaSource.CreateFromStorageFile(file);
            playbackList.Items.Add(new MediaPlaybackItem(source));
        }

_mediaPlayer = new MediaPlayer();
_mediaPlayer.AutoPlay = true;
_mediaPlayer.Source = playbackList;
MPElement.SetMediaPlayer(_mediaPlayer);
_mediaPlayer.Play();

More information Microsoft Docs


问:
Calculating Interest Rates Python Dataframe
I Need to calculate the compund interest rate so, lets say I have a Dataframe like that:

```<code>   days
1   10
2   15
3   20
</code>```

What I want to get is (suppose the interest rate is 1% every day:

```<code>    days   interst rate
1   10     10,46%
2   15     16,10%
3   20     22,02%
</code>```

My code is as follows:

```<code>def inclusao_juros (x):
    dias = df_arrumada_4['Prazo Medio']
    return ((1.0009723)^dias)-1

df_arrumada_4['juros_acumulado'] = df_arrumada_4['Prazo Medio'].apply(inclusao_juros)
</code>```

What should I do??? Tks

答:
IIUC

```<code>pd.Series([1.01]*len(df)).pow(df.reset_index().days,0).sub(1)
Out[695]:
0    0.104622
1    0.160969
2    0.220190
dtype: float64
</code>```

Jez's : pd.Series([1.01]*len(df),index=df.index).pow(df.days,0).sub(1)

Or using your apply

```<code>df.days.apply(lambda x: 1.01**x -1)
Out[697]:
1    0.104622
2    0.160969
3    0.220190
Name: days, dtype: float64
</code>```

Body:
I Need to calculate the compund interest rate so, lets say I have a Dataframe like that:

   days
1   10
2   15
3   20

What I want to get is (suppose the interest rate is 1% every day:

    days   interst rate
1   10     10,46%
2   15     16,10%
3   20     22,02%

My code is as follows:

def inclusao_juros (x):
    dias = df_arrumada_4['Prazo Medio']
    return ((1.0009723)^dias)-1

df_arrumada_4['juros_acumulado'] = df_arrumada_4['Prazo Medio'].apply(inclusao_juros)

What should I do??? Tks

Body:
IIUC

pd.Series([1.01]*len(df)).pow(df.reset_index().days,0).sub(1)
Out[695]:
0    0.104622
1    0.160969
2    0.220190
dtype: float64

Jez's : pd.Series([1.01]*len(df),index=df.index).pow(df.days,0).sub(1)

Or using your apply

df.days.apply(lambda x: 1.01**x -1)
Out[697]:
1    0.104622
2    0.160969
3    0.220190
Name: days, dtype: float64


问:
How to move content of folder to unique folders every three hours in linux platform?
Whenvever my computer starts up I want to move contents of a folder to a unique folders.

For Example, Folder "A" has some Pictures then in the start up I want to MOVE the contents to a new folder "B". Again after 3 Hours I want to Move the contents from Folder "A" to newly Created Folder "C". Every Three hours I want a new folder to made for keeping the Content. Can any one help?

答:
Crontab can be used to achieve your need easily, more explanation for startup script is here

Reboot or Startup activity:

```<code>#crontab -e
@reboot  /home/user/startup_script.sh
</code>```

Regular interval:

```<code>#crontab -e
* */3 * * *  /home/user/interval_script.sh
</code>```

Note: Design the scripts based on your need.

Body:
Crontab can be used to achieve your need easily, more explanation for startup script is here

Reboot or Startup activity:

#crontab -e
@reboot  /home/user/startup_script.sh

Regular interval:

#crontab -e
* */3 * * *  /home/user/interval_script.sh

Note: Design the scripts based on your need.


问:
Run a command for each item in jq array
This is how my input file looks like:

```<code>[
  {
    "ConfigType": "ABC",
    "Prop1": 3,
    "Prop2": 30
  },
  {
    "ConfigType": "XYZ",
    "Prop3": "Hello",
    "Prop4": "World",
    "Prop5": "Application"
  }
]
</code>```

I need to prepare insert statement for each item.

This is how my jq command looks like which gives me each item.

```<code>cat app-cnfg.json |  jq -r ".[]"
</code>```

How do I execute aws dynamodb put-item --table-name "xxx" --item <<array's element>>?

答:
You can apply the filter to extract each element of the JSON array and feed it to an array in bash and iterate over its content later. Assuming you have bash 4.0 or greater, you can use mapfile command as

```<code>mapfile -t configArr < <(jq -c '.[]'  < app-cnfg.json)
</code>```

and now we loop over the array, to run the command for each config item,

```<code>for config in "${configArr[@]}"; do
    aws dynamodb put-item --table-name "xxx" --item "$config"
done
</code>```

(or) use a more efficient way to read from an input data stream using a while loop and the read command (works on bash versions that don't support mapfile or readarray)

```<code>while IFS= read -r config; do
    aws dynamodb put-item --table-name "xxx" --item "$config"
done< <(jq -c '.[]' < app-cnfg.json)
</code>```

Title: Run a command for each item in jq array

Body:
This is how my input file looks like:

[
  {
    "ConfigType": "ABC",
    "Prop1": 3,
    "Prop2": 30
  },
  {
    "ConfigType": "XYZ",
    "Prop3": "Hello",
    "Prop4": "World",
    "Prop5": "Application"
  }
]

I need to prepare insert statement for each item.

This is how my jq command looks like which gives me each item.

cat app-cnfg.json |  jq -r ".[]"

How do I execute aws dynamodb put-item --table-name "xxx" --item <<array's element>>?

Body:
You can apply the filter to extract each element of the JSON array and feed it to an array in bash and iterate over its content later. Assuming you have bash 4.0 or greater, you can use mapfile command as

mapfile -t configArr < <(jq -c '.[]'  < app-cnfg.json)

and now we loop over the array, to run the command for each config item,

for config in "${configArr[@]}"; do
    aws dynamodb put-item --table-name "xxx" --item "$config"
done

(or) use a more efficient way to read from an input data stream using a while loop and the read command (works on bash versions that don't support mapfile or readarray)

while IFS= read -r config; do
    aws dynamodb put-item --table-name "xxx" --item "$config"
done< <(jq -c '.[]' < app-cnfg.json)


问:
How integrate QR code to Jasper Report Studio
I'm using jasper report studio. I use a barcode type 128, in the preview of the jasper report if it shows me, when processing the report from java (eclipse) it shows me the following error.

```<code>java.lang.NoClassDefFoundError: org/krysalis/barcode4j/HumanReadablePlacement
java.lang.Class.getDeclaredMethods0(Native Method)
java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
java.lang.Class.getDeclaredMethod(Class.java:2128)
java.io.ObjectStreamClass.getPrivateMethod(ObjectStreamClass.java:1475)
java.io.ObjectStreamClass.access$1700(ObjectStreamClass.java:72)
java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:498)
java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:472)
java.security.AccessController.doPrivileged(Native Method)
java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:472)
java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:369)
java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:598)
java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1843)
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1843)
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
java.util.ArrayList.readObject(ArrayList.java:791)
sun.reflect.GeneratedMethodAccessor25.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2136)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:552)
net.sf.jasperreports.engine.base.JRBaseReport.readObject(JRBaseReport.java:770)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2136)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:140)
net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:116)
net.sf.jasperreports.engine.util.JRLoader.loadObjectFromFile(JRLoader.java:107)
icrperusa.utils.Reports.getReportcn(Reports.java:37)
icrperusa.servlet.reports.FacturaElectronica.doGet(FacturaElectronica.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
</code>```

In java it imports the barcode4j-2.1.jar library.

答:
easy, you need to import the dependencie.

Double check because this class is IN the barcode4j.

```<code><dependency>
    <groupId>net.sf.barcode4j</groupId>
    <artifactId>barcode4j</artifactId>
    <version>2.1</version>
</dependency>
</code>```

Body:
I'm using jasper report studio. I use a barcode type 128, in the preview of the jasper report if it shows me, when processing the report from java (eclipse) it shows me the following error.

java.lang.NoClassDefFoundError: org/krysalis/barcode4j/HumanReadablePlacement
java.lang.Class.getDeclaredMethods0(Native Method)
java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
java.lang.Class.getDeclaredMethod(Class.java:2128)
java.io.ObjectStreamClass.getPrivateMethod(ObjectStreamClass.java:1475)
java.io.ObjectStreamClass.access$1700(ObjectStreamClass.java:72)
java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:498)
java.io.ObjectStreamClass$2.run(ObjectStreamClass.java:472)
java.security.AccessController.doPrivileged(Native Method)
java.io.ObjectStreamClass.<init>(ObjectStreamClass.java:472)
java.io.ObjectStreamClass.lookup(ObjectStreamClass.java:369)
java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:598)
java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1843)
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1843)
java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1713)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2000)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
java.util.ArrayList.readObject(ArrayList.java:791)
sun.reflect.GeneratedMethodAccessor25.invoke(Unknown Source)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2136)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2169)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2245)
java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:552)
net.sf.jasperreports.engine.base.JRBaseReport.readObject(JRBaseReport.java:770)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:498)
java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:1058)
java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2136)
java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2027)
java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1535)
java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:140)
net.sf.jasperreports.engine.util.JRLoader.loadObject(JRLoader.java:116)
net.sf.jasperreports.engine.util.JRLoader.loadObjectFromFile(JRLoader.java:107)
icrperusa.utils.Reports.getReportcn(Reports.java:37)
icrperusa.servlet.reports.FacturaElectronica.doGet(FacturaElectronica.java:54)
javax.servlet.http.HttpServlet.service(HttpServlet.java:635)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)

In java it imports the barcode4j-2.1.jar library.

Body:
easy, you need to import the dependencie.

Double check because this class is IN the barcode4j.

<dependency>
    <groupId>net.sf.barcode4j</groupId>
    <artifactId>barcode4j</artifactId>
    <version>2.1</version>
</dependency>


问:
Find process owning a port programmatically
How can I find which process is using a given TCP port?  I know I can call out to netstat (How can you find out which process is listening on a port on Windows?), but if it's not too difficult I'd prefer to use the Windows API directly instead of launching an external process and parsing its output.  I can see that netstat uses functions like GetTcpTable and GetOwnerModuleFromTcpEntry but I don't see how to connect those to a process id.</p>

答: Use the GetTcpTable / GetTcp6Table / GetUdpTable / GetUdp6Table functions. I am not aware of any way to do this without walking the table yourself (that is, you can't query directly by port number). And you have to use different calls for tcp, tcp6, udp and udp6.</p>

ContentLicense: CC BY-SA 4.0


问:
Bootstrap 4: Uncaught ReferenceError: Popper is not defined
I've installed Bootstrap 4 using Node and Gulp and when running the application I get the following error

Uncaught ReferenceError: Popper is not defined

I've only been using the Bootstrap grid system so far and I haven't used anything that would require the Bootstrap JS. Looks to me like Bootstrap is missing something or I haven't installed it correctly (to be honest it's probably me) - has anyone else come across the same issue or know a fix at all?

答:
1-Copy code on this page: https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js

2-Past on new file and save on this name (popper.min.js)

3-Add script on html before bootstrap script:

```<code><script src="popper.min.js"></script>
<script src="bootstrap.js"></script>
</code>```

Body:
1-Copy code on this page: https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js

2-Past on new file and save on this name (popper.min.js)

3-Add script on html before bootstrap script:

<script src="popper.min.js"></script>
<script src="bootstrap.js"></script>


问:
How to Retrieve JTable Data as an Array
I've populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers) constructor. Users can edit the table, and I want to be able to load the new data back into an array (Object[][]). Note that I'd rather not just update the array bit by bit, but be able to just completely load a new array from the table. How can this be done?

答:
I've populated a JTable through a DefaultTableModel with the (Object[][] data, String[] headers)

The DefaultTableModel is a dynamic model, which means rows and columns can be added dynamically. Arrays are not dynamic so when you create a DefaultTableModel using arrays, the data from the arrays is copied to a Vector of Vectors.

I want to be able to load the new data back into an array (Object[][]).
  I'd rather not just update the array bit by bit

Unfortunately you will have to update the array cell by cell since the data is not stored in a 2D array.

Or, since the DefaultTableModel does use a Vector of Vectors to store the data you can use the getDataVector() method to access the data. Then you get each row from the Vector and invoke the List.toArray() method on the row Vector before adding it to your array.

Either way you will need to loop through the Vectors in the model.

If you want to use the 2D array as storage for the TableModel, then you will need to create a custom TableModel that uses the supplied array for the data storage. After implemting all the required methods of the TableModel interface  you will need to provide a getTableDataArray() method to return the reference to the array.

Title: How to Retrieve JTable Data as an Array


问:
Ember CLI "Blueprint" for Creating an Addon
I have been wanting to create Ember addons that adhere to my company's structure and have some pre-formatted files.

For instance, I would like...

The addon spacing to default to 4 spaces instead of 2.

The package.json file to contain certain default packages when created.

I would like to add some new files to the addon when it is first created.

My understanding is that blueprints must live inside an addon/application and therefore there is no way to modify what the addon structure looks like at the time it is generated. Is it possible to do these types of things through the concept of a "blueprint"? Or would I need to fork Ember CLI and modify the internals? I dislike the idea of forking Ember CLI since I would need to manually keep it up to date.

Thanks in advance!

答:
You can definitely use custom blueprints when generating a brand new project. glimmerjs uses this with success. You can use this repo as a guideline https://github.com/glimmerjs/glimmer-blueprint, then generate your new project via

```<code>ember new my-addon -b https://github.com/my-company/my-companys-blueprint.git
</code>```

That blueprint source can be a git repo url, or npm package.

Body:
You can definitely use custom blueprints when generating a brand new project. glimmerjs uses this with success. You can use this repo as a guideline https://github.com/glimmerjs/glimmer-blueprint, then generate your new project via

ember new my-addon -b https://github.com/my-company/my-companys-blueprint.git

That blueprint source can be a git repo url, or npm package.


问:
Unable to access input text field value jQuery
I am unable to access the input field or any of the dynamically created input fields from the following HTML:

```<code><div class="row">
<div class="input_fields_wrap" id="Categories">
<button class="add_field_with_subs">Add More Categories</button>
<div class="input_fields"><input type="text" name="someInput"><a href="#" class="add_sub_field">Add Sub-Categories</a></div>
</div>
</div>
</code>```

Using the following code gives the proper value of "2":

```<code>$("#Categories").children("div").each( () => alert($(this).children.length) );
</code>```

and the alert will trigger appropriately for each dynamically created field...

However, any attempt to get the value of the appropriate input text field yields a response of "undefined".

I've tried .children("input"), .children(":input"), .last(), .find, etc.

Would anyone be able to advise me on what I'm doing incorrectly, please?

答:
children only traverse single level of DOM, use find instead

Make it

```<code>$("#Categories").find("input").each( function(){
   //your logic
});
</code>```

Body:
I am unable to access the input field or any of the dynamically created input fields from the following HTML:

<button class="add_field_with_subs">Add More Categories</button>

<input type="text" name="someInput">Add Sub-Categories

Using the following code gives the proper value of "2":

$("#Categories").children("div").each( () => alert($(this).children.length) );

and the alert will trigger appropriately for each dynamically created field...

However, any attempt to get the value of the appropriate input text field yields a response of "undefined".

I've tried .children("input"), .children(":input"), .last(), .find, etc.

Would anyone be able to advise me on what I'm doing incorrectly, please?

Body:
children only traverse single level of DOM, use find instead

Make it

$("#Categories").find("input").each( function(){
   //your logic
});


问:
How can I make this python code shorter and more efficient
This is my attempt at doing a higher/lower game.

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
</code>```

I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!

Updated Code:

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
</code>```

答:
You could do something like this:</p>

```<code>import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
while True:
    try:
        choice = int(input("Please pick a number between 1 & 100: "))
    except ValueError:
        continue
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
        break
</code>```

Body:
This is my attempt at doing a higher/lower game.

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!

Updated Code:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

Body:
You could do something like this:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
while True:
    try:
        choice = int(input("Please pick a number between 1 & 100: "))
    except ValueError:
        continue
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")
        break


问:
aria-labelledby not being read by NVDA Chrome
When user uses screen reader, I want H2 element to be read out from hidden text stored in span element. This does not work with NVDA and Chrome/FF browsers. When I roll over the h2 element, it just reads "This is header" instead of "This is Test"

```<code><div >
    <span id="hdnlbl" class="visuallyhidden">This is Test</span>
    <h2 aria-labelledby="hdnlbl">This is header</h2>
</div>
</code>```

here is live example https://jsfiddle.net/pwzeus/8jb1mxdm/13/

EDIT

Requirement is that it has to work on mouse over. How do I make that work ?

答:
by the class I understood that your span is hidden-aria-labelledby will be read only when the element(the span in the example) isn't hidden

(we use it for errors when the error is hidden the error isn't read for the input and when the error is visible it will be read for the input)

good luck

shelli

accessibility expert

Body:
When user uses screen reader, I want H2 element to be read out from hidden text stored in span element. This does not work with NVDA and Chrome/FF browsers. When I roll over the h2 element, it just reads "This is header" instead of "This is Test"

    This is Test

This is header

here is live example https://jsfiddle.net/pwzeus/8jb1mxdm/13/

EDIT

Requirement is that it has to work on mouse over. How do I make that work ?


问:
Add multiple filters to nested aggregation filters Elasticsearch
So I would like to add a couple more filters to the aggregate filter for the "inner" portion of the aggregate section. The other two filters I need to add are in the query section. I was able to get this code to work correctly, it just needs the second and third nested filters added from the first section down into the aggregate area, where I am only filtering by the "givingMatch.db_type" terms currently.

Here is the current code that just needs the additional filters added:

```<code>    GET /testserver/_search
{
    "query": {
        "bool": {
            "filter": [
           {
                    "nested": {
                        "path": "givingMatch",
                        "query": {
                            "bool": {
                                "filter": {
                                    "terms": {
                                        "givingMatch.db_type": [
                                            "FECmatch",
                                            "StateMatch"
                                        ]
                                    }
                                }
                            }
                        }
                    }
                },
                {
                    "nested": {
                        "path": "givingMatch",
                        "query": {
                            "bool": {
                                "filter": {
                                    "range": {
                                        "givingMatch.Status": {
                                            "from": 0,
                                            "to": 8
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                {
                    "nested": {
                        "path": "givingMatch",
                        "query": {
                            "bool": {
                                "filter": {
                                    "range": {
                                        "givingMatch.QualityScore": {
                                            "from": 17
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            ]
        }
    },
    "aggs": {
        "categories": {
            "nested": {
                "path": "givingMatch"
            },
            "aggs": {
              "inner": {
                "filter": {
                  "terms": {
                    "givingMatch.db_type":["FECmatch","StateMatch"]
                  }
                },
                "aggs":{
                  "org_category": {
                    "terms": {
                        "field": "givingMatch.org_category",
                        "size": 1000
                    },
                    "aggs": {
                      "total": {
                        "sum":{
                          "field": "givingMatch.low_gift"
                        }
                      }
                    }
                }
                }
              }

            }
        }
    },
    "size": 0
}
</code>```

Giving these results:

```<code>...."aggregations": {
    "categories": {
      "doc_count": 93084,
      "inner": {
        "doc_count": 65492,
        "org_category": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "DEM",
              "doc_count": 28829,
              "total": {
                "value": 29859163
              }
            },
            {
              "key": "REP",
              "doc_count": 21561,
              "total": {
                "value": 69962305
              }
            },...
</code>```

答:
Hopefully this will save someone else a few hours. To add multiple filters, the aggregate section would become:

```<code>GET materielelectrique_search_alias/product/_search?explain=false
{
  "aggs": {
    "categories": {
      "nested": {
        "path": "givingMatch"
      },
      "aggs": {
        "inner": {
          "filter": {
            "bool": {
              "must": [
                {
                  "terms": {
                    "givingMatch.db_type": [
                      "FECmatch",
                      "StateMatch"
                    ]
                  }
                },
                {
                  "range": {
                    "givingMatch.QualityScore": {
                      "from": 17
                    }
                  }
                },
                {
                  "range": {
                    "givingMatch.Status": {
                      "from": 0,
                      "to": 8
                    }
                  }
                }
              ]
            }
          },
          "aggs": {
            "org_category": {
              "terms": {
                "field": "givingMatch.org_category",
                "size": 1000
              },
              "aggs": {
                "total": {
                  "sum": {
                    "field": "givingMatch.low_gift"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</code>```

This allows for multiple filters within the nested aggs.

Body:
So I would like to add a couple more filters to the aggregate filter for the "inner" portion of the aggregate section. The other two filters I need to add are in the query section. I was able to get this code to work correctly, it just needs the second and third nested filters added from the first section down into the aggregate area, where I am only filtering by the "givingMatch.db_type" terms currently.

Here is the current code that just needs the additional filters added:

    GET /testserver/_search
{
    "query": {
        "bool": {
            "filter": [
           {
                    "nested": {
                        "path": "givingMatch",
                        "query": {
                            "bool": {
                                "filter": {
                                    "terms": {
                                        "givingMatch.db_type": [
                                            "FECmatch",
                                            "StateMatch"
                                        ]
                                    }
                                }
                            }
                        }
                    }
                },
                {
                    "nested": {
                        "path": "givingMatch",
                        "query": {
                            "bool": {
                                "filter": {
                                    "range": {
                                        "givingMatch.Status": {
                                            "from": 0,
                                            "to": 8
                                        }
                                    }
                                }
                            }
                        }
                    }
                },
                {
                    "nested": {
                        "path": "givingMatch",
                        "query": {
                            "bool": {
                                "filter": {
                                    "range": {
                                        "givingMatch.QualityScore": {
                                            "from": 17
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            ]
        }
    },
    "aggs": {
        "categories": {
            "nested": {
                "path": "givingMatch"
            },
            "aggs": {
              "inner": {
                "filter": {
                  "terms": {
                    "givingMatch.db_type":["FECmatch","StateMatch"]
                  }
                },
                "aggs":{
                  "org_category": {
                    "terms": {
                        "field": "givingMatch.org_category",
                        "size": 1000
                    },
                    "aggs": {
                      "total": {
                        "sum":{
                          "field": "givingMatch.low_gift"
                        }
                      }
                    }
                }
                }
              }

            }
        }
    },
    "size": 0
}

Giving these results:

...."aggregations": {
    "categories": {
      "doc_count": 93084,
      "inner": {
        "doc_count": 65492,
        "org_category": {
          "doc_count_error_upper_bound": 0,
          "sum_other_doc_count": 0,
          "buckets": [
            {
              "key": "DEM",
              "doc_count": 28829,
              "total": {
                "value": 29859163
              }
            },
            {
              "key": "REP",
              "doc_count": 21561,
              "total": {
                "value": 69962305
              }
            },...

Body:
Hopefully this will save someone else a few hours. To add multiple filters, the aggregate section would become:

GET materielelectrique_search_alias/product/_search?explain=false
{
  "aggs": {
    "categories": {
      "nested": {
        "path": "givingMatch"
      },
      "aggs": {
        "inner": {
          "filter": {
            "bool": {
              "must": [
                {
                  "terms": {
                    "givingMatch.db_type": [
                      "FECmatch",
                      "StateMatch"
                    ]
                  }
                },
                {
                  "range": {
                    "givingMatch.QualityScore": {
                      "from": 17
                    }
                  }
                },
                {
                  "range": {
                    "givingMatch.Status": {
                      "from": 0,
                      "to": 8
                    }
                  }
                }
              ]
            }
          },
          "aggs": {
            "org_category": {
              "terms": {
                "field": "givingMatch.org_category",
                "size": 1000
              },
              "aggs": {
                "total": {
                  "sum": {
                    "field": "givingMatch.low_gift"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

This allows for multiple filters within the nested aggs.


问:
Is there any way to factor out "const" field initializers in C++
In C++ I have a class with some const fields:

```<code>class Obj {
   static const AType defaultAType;
   const AType &cRef;
public:
   Obj() : cRef(defaultAType) { ... }
   Obj(AType &aType) : cRef(aType) { ... }
};
</code>```

This is a simple example.  But a real one might have many fields, and several different constructor overloads.  References and "const" fields can't be initialized in the body of a constructor or in a method called by the constructor to the best of my knowledge.  But it is a pain in the butt to synchronously maintain a number of initializers in lets say 5 separate constructor overloads.  Is there any way to properly factor out these initializers (other than a macro) ??

答:
In a comment, you said,

Yes that is the structure however const items, references, and class items can't be initialized in the body of constructors or in a non-constructor method.

A delegating constructor can be used to initialize reference member variables.

Expanding your example code a bit, I can see something like:

```<code>class Obj {
   static const AType defaultAType;
   const AType &aRef;
   static const BType defaultBType;
   const BType &bRef;
public:

   // Delegate with default values for both references
   Obj() : Obj(defaultAType, defaultBType) {}

   // Delegate with default value for the B reference
   Obj(AType &aType) : Obj(aType, defaultBType) {}

   // Delegate with default value for the A reference
   Obj(BType &bType) : Obj(defaultAType, bType) {}

   // A constructor that has all the arguments.
   Obj(AType& aType, BType& bType) : aRef(aType), bRef(bType) {}
};
</code>```

Body:
In C++ I have a class with some const fields:

class Obj {
   static const AType defaultAType;
   const AType &cRef;
public:
   Obj() : cRef(defaultAType) { ... }
   Obj(AType &aType) : cRef(aType) { ... }
};

This is a simple example.  But a real one might have many fields, and several different constructor overloads.  References and "const" fields can't be initialized in the body of a constructor or in a method called by the constructor to the best of my knowledge.  But it is a pain in the butt to synchronously maintain a number of initializers in lets say 5 separate constructor overloads.  Is there any way to properly factor out these initializers (other than a macro) ??

Body:
In a comment, you said,

Yes that is the structure however const items, references, and class items can't be initialized in the body of constructors or in a non-constructor method.

A delegating constructor can be used to initialize reference member variables.

Expanding your example code a bit, I can see something like:

class Obj {
   static const AType defaultAType;
   const AType &aRef;
   static const BType defaultBType;
   const BType &bRef;
public:

   // Delegate with default values for both references
   Obj() : Obj(defaultAType, defaultBType) {}

   // Delegate with default value for the B reference
   Obj(AType &aType) : Obj(aType, defaultBType) {}

   // Delegate with default value for the A reference
   Obj(BType &bType) : Obj(defaultAType, bType) {}

   // A constructor that has all the arguments.
   Obj(AType& aType, BType& bType) : aRef(aType), bRef(bType) {}
};


问:
Unwanted MSI appearance after installation
I used windows installer (msi project) and actually I have the msi file after installation it throws a shortcuts to the desktop.

My problem is when i double-click on the shortcut for my application, it displays somthing like the installation then it runs my application. I don't want the installtion windows to appear where my application doesn't need to throw any file or to install something before running all pre-requests are installed through the msi file. I want that when the end-user clicks on the shortcut, it runs the application directly ...

I hope I explained my problem well.

One additional note i'm using VS 2005, C#

What if i want to remove this action where it always happens. everytime i double click on the exe file it appears this window . my application is not so complicated to so.

EDIT: where can i find the log file ?!?

please help.
thnx indavence

答:
One of the "features" of the MSI installation system is that it can automatically repair some things when your application is run.

A good way to see this in action is to have two versions of Microsoft Office installed side-by-side. After running MS Word 2007, an invocation of MS Word 2003 will start with MsiExec popping up to fix a few things before the application starts.

Almost certainly, what you're seeing is this kind of repair - check the log file and find out what is being fixed, then alter your installation project so things aren't broken on first install.

Hope this helps.

LastEditorDisplayName: moocha

OwnerDisplayName: Bevan


问:
Converting PHP array to a single JSON object using js
I have a php array(zero indexed) which I am sending to front end directly by echoing its json_encode format.

I want the JSON object to look like

```<code>{
    'A': null,
    'B': null,
    'C': null
}
</code>```

But when I tried console.log i.e.,

```<code>console.log(<?php echo json_encode($array); ?>)
</code>```

its printing js array

Also when I try print_r($array) in backend it prints

```<code>[array] => Array
    (
        [0] => A
        [1] => B
        [2] => C

    )
</code>```

Thanks in advance

答:
This code gives you the desired out put

```<code>$array = array
    (
        '0' => 'A',
        '1' => 'B',
        '2' => 'C'

    );
    $array = array_fill_keys($array, NULL);

echo json_encode($array);
</code>```

Out Put:

```<code>{"A":null,"B":null,"C":null}
</code>```

Javascript:

```<code><script type="text/javascript">
<!--
var data =<?php echo json_encode($array); ?>;

console.log(data);
//-->
</script>
</code>```

Out Put:

```<code> Object {A: null, B: null, C: null}
    A:null
    B:null
    C:null
</code>```

Body:
I have a php array(zero indexed) which I am sending to front end directly by echoing its json_encode format.

I want the JSON object to look like

{
    'A': null,
    'B': null,
    'C': null
}

But when I tried console.log i.e.,

console.log(<?php echo json_encode($array); ?>)

its printing js array

Also when I try print_r($array) in backend it prints

[array] => Array
    (
        [0] => A
        [1] => B
        [2] => C

    )

Thanks in advance

Body:
This code gives you the desired out put

$array = array
    (
        '0' => 'A',
        '1' => 'B',
        '2' => 'C'

    );
    $array = array_fill_keys($array, NULL);

echo json_encode($array);

Out Put:

{"A":null,"B":null,"C":null}

Javascript:

<script type="text/javascript">
<!--
var data =<?php echo json_encode($array); ?>;

console.log(data);
//-->
</script>

Out Put:

 Object {A: null, B: null, C: null}
    A:null
    B:null
    C:null


问:
How to add two selectedindices for two listboxes to method that uses type table for handling multiple listbox parameters
I'm trying to fetch a dataset that uses two list boxes for building the query.  How to write?

```<code>public void LoadChecklist(Object sender, System.EventArgs e)
{
    string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLDEV1"].ConnectionString;
    var SearchResultsTable = new DataTable();
    using (var con = new SqlConnection(strConnString))
    {
        using (var cmd = new SqlCommand("sp_get_QUADRA_CHECKLIST", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            using (var adapter = new SqlDataAdapter(cmd))
            {
                using (var dtSIPA = new DataTable())
                {
                    //dtSIPA.Columns.Add("Id", typeof(int));//assuming you are looking for a list of int values
                    dtSIPA.Columns.Add("SIPA", typeof(string));
                    dtSIPA.Columns.Add("RO", typeof(string));
                    int[] yourSelectedIndexes = ddlSIPA.GetSelectedIndices();
                    int[] yourSelectedIndexes2 = lbRO.GetSelectedIndices();
                    for (int i = yourSelectedIndexes.Length - 1; i >= 0; i--)
                    {
                        dtSIPA.Rows.Add(ddlSIPA.Items[yourSelectedIndexes[i]].Value);
                    }
                    for (int j = yourSelectedIndexes2.Length - 1; j >= 0; j--)
                    {
                        dtSIPA.Rows.Add(lbRO.Items[yourSelectedIndexes[j]].Value);
                    }

                    //if (SearchResultsTable.Rows.Count >= 0)
                    //{
                        cmd.Parameters.Add("@AP_DEV", SqlDbType.Bit).Value = CbAPDev.Checked;
                        cmd.Parameters.Add("@PROD_DEV", SqlDbType.Bit).Value = cbProdDev.Checked;
                        cmd.Parameters.Add("@ROTYPE", SqlDbType.NVarChar, 255).Value = ddlROTYPE.SelectedItem.Value;
                        cmd.Parameters.Add("@SIPA", SqlDbType.Structured).Value = dtSIPA;
                        cmd.Parameters.Add("@RO", SqlDbType.Structured).Value = dtSIPA;
                    //Response.Write(dtSIPA);
                    //}
                    //else
                    //{ ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Selections not found!');", true); }
                }
                try
                {
                    adapter.Fill(SearchResultsTable);
                    GV1.DataSource = SearchResultsTable;
                    GV1.DataBind();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    Response.Write(ex);
                }
            }
        }
    }
</code>```

I should get a dataset back filtered to the selections made in the two list boxes ddlSIPA and lbRO but I'm sure I don't have the code right.

```<code>Exception Details: System.IndexOutOfRangeException: Index was outside the

bounds of the array.

Line 571:                        for (int j =
yourSelectedIndexes2.Length - 1; j >= 0; j--)
Line 572:                        {
Line 573:                     dtSIPA.Rows.Add(lbRO.Items
[yourSelectedIndexes[j]].Value);
Line 574:                        }
Line 575:
</code>```

Source File:  \sw.nos.boeing.com\ewh\dev\VOL01\vanity\qualityvisibility\QUADRA\SAVE_ASSESSMENT.aspx.cs    Line:  573

```<code>USE [VISIBILITY_BOARD]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER On
GO

 /* Create a table type. */
CREATE TYPE SIPA_TYPE AS TABLE
( SIPA NVARCHAR(255) NULL,
    RO NVARCHAR(MAX) NULL);
GO

CREATE PROCEDURE [dbo].[sp_get_QUADRA_CHECKLIST] (@AP_DEV bit = '', @PROD_DEV bit = '', @ROTYPE nvarchar(255) = '', @SIPA AS SIPA_TYPE READONLY, @RO AS SIPA_TYPE READONLY) AS

SELECT '' AS QUES_ANSWER
    , '' AS COMMENTS
    , cl.RO_TYPE
    , cl.RO
    , cl.QUES_ID
    , cl.DFQRO AS QDRO
    , cl.QUADRA_QUES

FROM Tbl_QUADRA_CL cl

WHERE (cl.SIPA IN(SELECT SIPA FROM @SIPA) OR (SELECT COUNT(SIPA) FROM @SIPA) = 0)
    AND (cl.RO IN(SELECT RO FROM @RO) OR (SELECT COUNT(RO) FROM @RO) = 0)
    AND (cl.RO_TYPE = @ROTYPE OR @ROTYPE IS NULL)
    AND (cl.AP_DEV = @AP_DEV OR @AP_DEV IS NULL)
    AND (cl.PROD_DEV = @PROD_DEV OR @PROD_DEV IS NULL)
GROUP BY
     cl.RO_TYPE
    , cl.RO
    , cl.QUES_ID
    , cl.DFQRO
    , cl.QUADRA_QUES
</code>```

答:
I found an error.

```<code>dtSIPA.Columns.Add("SIPA", typeof(string));
dtSIPA.Columns.Add("RO", typeof(string));
int[] yourSelectedIndexes = ddlSIPA.GetSelectedIndices();
int[] yourSelectedIndexes2 = lbRO.GetSelectedIndices();
for (int i = yourSelectedIndexes.Length - 1; i >= 0; i--)
{
    dtSIPA.Rows.Add(ddlSIPA.Items[yourSelectedIndexes[i]].Value);
}
for (int j = yourSelectedIndexes2.Length - 1; j >= 0; j--)
{
    dtSIPA.Rows.Add(lbRO.Items[yourSelectedIndexes[j]].Value);
}
</code>```

You are adding two columns here, SIPA and RO but while adding rows for these columns, you are adding the rows separately.

First off the number of selections in the two list boxes ddlSIPA and lbRO should be the same. Only then can they be added together in a single row.

Your code adds the values of ddlSIPA and bRO as separate rows instead of a single row. Your code should be something like this

```<code>dtSIPA.Columns.Add("SIPA", typeof(string));
dtSIPA.Columns.Add("RO", typeof(string));
int[] yourSelectedIndexes = ddlSIPA.GetSelectedIndices();// or lbRO.GetSelectedIndices(), they have to be same in count
int[] yourSelectedIndexes2 = lbRO.GetSelectedIndices();
for (int i = yourSelectedIndexes.Length - 1; i >= 0; i--)
{
    dtSIPA.Rows.Add(ddlSIPA.Items[yourSelectedIndexes[i]].Value, lbRO.Items[yourSelectedIndexes2[i]].Value);
}
</code>```

Two values have to be added for a single row instead of adding both values as rows.

Body:
I'm trying to fetch a dataset that uses two list boxes for building the query.  How to write?

public void LoadChecklist(Object sender, System.EventArgs e)
{
    string strConnString = System.Configuration.ConfigurationManager.ConnectionStrings["SQLDEV1"].ConnectionString;
    var SearchResultsTable = new DataTable();
    using (var con = new SqlConnection(strConnString))
    {
        using (var cmd = new SqlCommand("sp_get_QUADRA_CHECKLIST", con))
        {
            cmd.CommandType = CommandType.StoredProcedure;
            using (var adapter = new SqlDataAdapter(cmd))
            {
                using (var dtSIPA = new DataTable())
                {
                    //dtSIPA.Columns.Add("Id", typeof(int));//assuming you are looking for a list of int values
                    dtSIPA.Columns.Add("SIPA", typeof(string));
                    dtSIPA.Columns.Add("RO", typeof(string));
                    int[] yourSelectedIndexes = ddlSIPA.GetSelectedIndices();
                    int[] yourSelectedIndexes2 = lbRO.GetSelectedIndices();
                    for (int i = yourSelectedIndexes.Length - 1; i >= 0; i--)
                    {
                        dtSIPA.Rows.Add(ddlSIPA.Items[yourSelectedIndexes[i]].Value);
                    }
                    for (int j = yourSelectedIndexes2.Length - 1; j >= 0; j--)
                    {
                        dtSIPA.Rows.Add(lbRO.Items[yourSelectedIndexes[j]].Value);
                    }

                    //if (SearchResultsTable.Rows.Count >= 0)
                    //{
                        cmd.Parameters.Add("@AP_DEV", SqlDbType.Bit).Value = CbAPDev.Checked;
                        cmd.Parameters.Add("@PROD_DEV", SqlDbType.Bit).Value = cbProdDev.Checked;
                        cmd.Parameters.Add("@ROTYPE", SqlDbType.NVarChar, 255).Value = ddlROTYPE.SelectedItem.Value;
                        cmd.Parameters.Add("@SIPA", SqlDbType.Structured).Value = dtSIPA;
                        cmd.Parameters.Add("@RO", SqlDbType.Structured).Value = dtSIPA;
                    //Response.Write(dtSIPA);
                    //}
                    //else
                    //{ ScriptManager.RegisterStartupScript(this, GetType(), "showalert", "alert('Selections not found!');", true); }
                }
                try
                {
                    adapter.Fill(SearchResultsTable);
                    GV1.DataSource = SearchResultsTable;
                    GV1.DataBind();
                }
                catch (System.Data.SqlClient.SqlException ex)
                {
                    Response.Write(ex);
                }
            }
        }
    }

I should get a dataset back filtered to the selections made in the two list boxes ddlSIPA and lbRO but I'm sure I don't have the code right.

Exception Details: System.IndexOutOfRangeException: Index was outside the

bounds of the array.

Line 571:                        for (int j =
yourSelectedIndexes2.Length - 1; j >= 0; j--)
Line 572:                        {
Line 573:                     dtSIPA.Rows.Add(lbRO.Items
[yourSelectedIndexes[j]].Value);
Line 574:                        }
Line 575:

Source File:  \sw.nos.boeing.com\ewh\dev\VOL01\vanity\qualityvisibility\QUADRA\SAVE_ASSESSMENT.aspx.cs    Line:  573

USE [VISIBILITY_BOARD]
GO

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER On
GO

 /* Create a table type. */
CREATE TYPE SIPA_TYPE AS TABLE
( SIPA NVARCHAR(255) NULL,
    RO NVARCHAR(MAX) NULL);
GO

CREATE PROCEDURE [dbo].[sp_get_QUADRA_CHECKLIST] (@AP_DEV bit = '', @PROD_DEV bit = '', @ROTYPE nvarchar(255) = '', @SIPA AS SIPA_TYPE READONLY, @RO AS SIPA_TYPE READONLY) AS

SELECT '' AS QUES_ANSWER
    , '' AS COMMENTS
    , cl.RO_TYPE
    , cl.RO
    , cl.QUES_ID
    , cl.DFQRO AS QDRO
    , cl.QUADRA_QUES

FROM Tbl_QUADRA_CL cl

WHERE (cl.SIPA IN(SELECT SIPA FROM @SIPA) OR (SELECT COUNT(SIPA) FROM @SIPA) = 0)
    AND (cl.RO IN(SELECT RO FROM @RO) OR (SELECT COUNT(RO) FROM @RO) = 0)
    AND (cl.RO_TYPE = @ROTYPE OR @ROTYPE IS NULL)
    AND (cl.AP_DEV = @AP_DEV OR @AP_DEV IS NULL)
    AND (cl.PROD_DEV = @PROD_DEV OR @PROD_DEV IS NULL)
GROUP BY
     cl.RO_TYPE
    , cl.RO
    , cl.QUES_ID
    , cl.DFQRO
    , cl.QUADRA_QUES

Body:
I found an error.

dtSIPA.Columns.Add("SIPA", typeof(string));
dtSIPA.Columns.Add("RO", typeof(string));
int[] yourSelectedIndexes = ddlSIPA.GetSelectedIndices();
int[] yourSelectedIndexes2 = lbRO.GetSelectedIndices();
for (int i = yourSelectedIndexes.Length - 1; i >= 0; i--)
{
    dtSIPA.Rows.Add(ddlSIPA.Items[yourSelectedIndexes[i]].Value);
}
for (int j = yourSelectedIndexes2.Length - 1; j >= 0; j--)
{
    dtSIPA.Rows.Add(lbRO.Items[yourSelectedIndexes[j]].Value);
}

You are adding two columns here, SIPA and RO but while adding rows for these columns, you are adding the rows separately.

First off the number of selections in the two list boxes ddlSIPA and lbRO should be the same. Only then can they be added together in a single row.

Your code adds the values of ddlSIPA and bRO as separate rows instead of a single row. Your code should be something like this

dtSIPA.Columns.Add("SIPA", typeof(string));
dtSIPA.Columns.Add("RO", typeof(string));
int[] yourSelectedIndexes = ddlSIPA.GetSelectedIndices();// or lbRO.GetSelectedIndices(), they have to be same in count
int[] yourSelectedIndexes2 = lbRO.GetSelectedIndices();
for (int i = yourSelectedIndexes.Length - 1; i >= 0; i--)
{
    dtSIPA.Rows.Add(ddlSIPA.Items[yourSelectedIndexes[i]].Value, lbRO.Items[yourSelectedIndexes2[i]].Value);
}

Two values have to be added for a single row instead of adding both values as rows.


问:
Firebase GET_ACCOUNTS Permission crash
In my crash report in firebase tell me that "missing permission get_account"

I have get_account in my manifest file and here is my code to request it to the user at runtime

SplashActivity.class

```<code>   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(SplashActivity.this.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(SplashActivity.this.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final Dialog dialog = new Dialog(this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(false);
            LayoutInflater lf = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View dialogview = lf.inflate(R.layout.access_permission_dialog, null);
            Button ok_btn = (Button) dialogview.findViewById(R.id.ok_btn);
            Button cancel_btn = (Button) dialogview.findViewById(R.id.cancel_btn);
            ok_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    flag = 1;
                    dialog.dismiss();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION
                                , Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                                , Manifest.permission.READ_CALENDAR
                                , Manifest.permission.GET_ACCOUNTS
                                , Manifest.permission.READ_CONTACTS

                        }, AppConstants.MY_APP_PERMISSIONS);

                    }
</code>```

Any idea why it keeps crashing ?

答:
Solved my problem adding this

```<code>ContextCompat.checkSelfPermission(SplashActivity.this.getApplicationContext(), Manifest.permission.GET_ACCOUNTS)
</code>```

This permission is under Contacts as this doc says

Android Permissions

Title: Firebase GET_ACCOUNTS Permission crash

Body:
In my crash report in firebase tell me that "missing permission get_account"

I have get_account in my manifest file and here is my code to request it to the user at runtime

SplashActivity.class

   if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(SplashActivity.this.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ContextCompat.checkSelfPermission(SplashActivity.this.getApplicationContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            final Dialog dialog = new Dialog(this);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setCancelable(false);
            LayoutInflater lf = (LayoutInflater) this
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View dialogview = lf.inflate(R.layout.access_permission_dialog, null);
            Button ok_btn = (Button) dialogview.findViewById(R.id.ok_btn);
            Button cancel_btn = (Button) dialogview.findViewById(R.id.cancel_btn);
            ok_btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    flag = 1;
                    dialog.dismiss();
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION
                                , Manifest.permission.ACCESS_COARSE_LOCATION
                                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                                , Manifest.permission.READ_EXTERNAL_STORAGE
                                , Manifest.permission.READ_CALENDAR
                                , Manifest.permission.GET_ACCOUNTS
                                , Manifest.permission.READ_CONTACTS

                        }, AppConstants.MY_APP_PERMISSIONS);

                    }

Any idea why it keeps crashing ?

Body:
Solved my problem adding this

ContextCompat.checkSelfPermission(SplashActivity.this.getApplicationContext(), Manifest.permission.GET_ACCOUNTS)

This permission is under Contacts as this doc says

Android Permissions


问:
ArticlesGrid where are Article.props? or How to reference props?
In the ArticlesGrid example we have the following render function:

```<code>render () {
  return this.state.articles && (
     <div className='articles'>
       { this.state.articles.map( function (article) {
         return <Article article={article} key={article.id} />;
       })}
     </div>
  );
}
</code>```

So we have a component Article which has as one of it's props article which equals the object article, so far so good

Could someone explain what's going on with the next statement:

```<code>var Article = function({article}) {
</code>```

why isn't it

```<code>var Article = function(this.props.article) {
</code>```

??

in fact, when I try to console.log this.props I get undefined.  I thought Article was a component too.

UPDATE:  Here's the entire code:

```<code>class ArticlesGrid extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
     articles: []
  };
}

componentDidMount () {

  var url =
     'http://api.nytimes.com/svc/search/v2/articlesearch.json?'
      + 'api-key=d68154fxxxxxxxxxxxxxxxxc7f5';

   $.getJSON(url, function(data, status) {
      return this.setState({articles: this.parse(data)});
   }.bind(this));
}

parse(results) {
  if(!results || !results.response) return [];
  var articles = results.response.docs;

  var parsedArticles = [];
  for (var i = 0; i < articles.length;i++){
     var article = articles[i];
     if (article.multimedia.find(this.isXL)) {

        parsedArticles.push({
           id: article._id,
           title: article.headline.main || 'Untitled',
           imageURL: article.multimedia.find(this.isXL).url || '#',
           webURL: article.web_url || '#'
        });
     }
  }

  return parsedArticles;
}

isXL (image) {
  return image.subtype === 'xlarge';
}

render () {

  return this.state.articles && (
     <div className='articles'>
       { this.state.articles.map( function (article) {
         return <Article article={article} key={article.id} />;
       })}
     </div>
  );
}
}

var Article = function({article}) {
  var imgURL = 'https://static01.nyt.com/' + article.imageURL;

  return (
     <div className='article'>
        <a className='article-link' href={article.webURL}>
           <img className='article-image'
                title={article.title}
                src={imgURL} />
        </a>
     </div>
  );
}

ReactDOM.render(<ArticlesGrid/>,document.getElementById('container'));
</code>```

答:
when I try to console.log this.props I get undefined. I thought
  Article was a component too.

Yes Article is a component too but it is a functional component. props to this are passed as argument to this function. So if you want to log props of this component then you can do it following way

```<code>var Article = function(props) {
  console.log(props)
  var imgURL = 'https://static01.nyt.com/' + article.imageURL;
</code>```

What is var Article = function({article}) {

This is called object destructuring. It means that if an object is passed to this function then take article property of that object. So basically

var Article = function({article}) {

roughly means

```<code>var Article = function(props) {
   var article = props.article
   ...
</code>```

Body:
In the ArticlesGrid example we have the following render function:

render () {
  return this.state.articles && (

       { this.state.articles.map( function (article) {
         return
;
       })}

  );
}

So we have a component Article which has as one of it's props article which equals the object article, so far so good

Could someone explain what's going on with the next statement:

var Article = function({article}) {

why isn't it

var Article = function(this.props.article) {

??

in fact, when I try to console.log this.props I get undefined.  I thought Article was a component too.

UPDATE:  Here's the entire code:

class ArticlesGrid extends React.Component {
 constructor(props) {
  super(props);
  this.state = {
     articles: []
  };
}

componentDidMount () {

  var url =
     'http://api.nytimes.com/svc/search/v2/articlesearch.json?'
      + 'api-key=d68154fxxxxxxxxxxxxxxxxc7f5';

   $.getJSON(url, function(data, status) {
      return this.setState({articles: this.parse(data)});
   }.bind(this));
}

parse(results) {
  if(!results || !results.response) return [];
  var articles = results.response.docs;

  var parsedArticles = [];
  for (var i = 0; i < articles.length;i++){
     var article = articles[i];
     if (article.multimedia.find(this.isXL)) {

        parsedArticles.push({
           id: article._id,
           title: article.headline.main || 'Untitled',
           imageURL: article.multimedia.find(this.isXL).url || '#',
           webURL: article.web_url || '#'
        });
     }
  }

  return parsedArticles;
}

isXL (image) {
  return image.subtype === 'xlarge';
}

render () {

  return this.state.articles && (

       { this.state.articles.map( function (article) {
         return
;
       })}

  );
}
}

var Article = function({article}) {
  var imgURL = 'https://static01.nyt.com/' + article.imageURL;

  return (

  );
}

ReactDOM.render(<ArticlesGrid/>,document.getElementById('container'));

Body:
when I try to console.log this.props I get undefined. I thought
  Article was a component too.

Yes Article is a component too but it is a functional component. props to this are passed as argument to this function. So if you want to log props of this component then you can do it following way

var Article = function(props) {
  console.log(props)
  var imgURL = 'https://static01.nyt.com/' + article.imageURL;

What is var Article = function({article}) {

This is called object destructuring. It means that if an object is passed to this function then take article property of that object. So basically

var Article = function({article}) {

roughly means

var Article = function(props) {
   var article = props.article
   ...


问:
What is the opposite of evt.preventDefault();
Once I've fired an evt.preventDefault(), how can I resume default actions again?

答:
You can always use this attached to some click event in your script:

```<code>location.href = this.href;
</code>```

example of usage is:

```<code>jQuery('a').click(function(e) {
    location.href = this.href;
});
</code>```

Body:
You can always use this attached to some click event in your script:

location.href = this.href;

example of usage is:

jQuery('a').click(function(e) {
    location.href = this.href;
});


问:
What does .jpg?t= mean?
this webcam image has ?t=1512496926 append to it. What does it mean? Is it the time? Does it do anything at all?

答:
Looks like it's a "cache buster".  By appending the current time (or any changing value) to the URL, browsers always re-request the content from the server instead of relying on their local cache.  Because the request has technically changed.

The server-side code (if there even is any) can simply ignore this value.  And it likely is doing so.  The intent is simply to ensure that users always get the latest version of the information.  For a webcam image like this one, it ensures that the users aren't seeing an old image.

Title: What does .jpg?t= mean?


问:
How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?
I've read through several posts about using this but must be missing something as it's not working for me. My activity A has launchmode="singleTop" in the manifest. It starts activity B, with launchmode="singleInstance". Activity B opens a browser and receives an intent back, which is why it's singleInstance. I'm trying to override the back button so that the user is sent back to activity A, and can then press Back to leave the activity, rather than back to activity B again.

```<code>// activity B
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
  && keyCode == KeyEvent.KEYCODE_BACK
  && event.getRepeatCount() == 0) onBackPressed();
 return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
 startActivity(new Intent(this, UI.class)
 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
 return;
}
</code>```

After returning from the browser, the stack is...
A,B,Browser,B

I expect this code to change the stack to...
A
... so that pressing back once more takes the user back to the Home Screen.

Instead, it seems to change the stack to...
A,B,Browser,B,A
...as though those flags aren't there.

I tried calling finish() in activity B after startActivity, but then the back button takes me back to the browser again!

What am I missing?

答:
I use three flags to resolve the problem:</p>
```<code>intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TASK |
                Intent.FLAG_ACTIVITY_NEW_TASK);
</code>```

Body:
I've read through several posts about using this but must be missing something as it's not working for me. My activity A has launchmode="singleTop" in the manifest. It starts activity B, with launchmode="singleInstance". Activity B opens a browser and receives an intent back, which is why it's singleInstance. I'm trying to override the back button so that the user is sent back to activity A, and can then press Back to leave the activity, rather than back to activity B again.

// activity B
@Override
public boolean onKeyDown(int keyCode, KeyEvent event)  {
 if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.ECLAIR
  && keyCode == KeyEvent.KEYCODE_BACK
  && event.getRepeatCount() == 0) onBackPressed();
 return super.onKeyDown(keyCode, event);
}
@Override
public void onBackPressed() {
 startActivity(new Intent(this, UI.class)
 .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK));
 return;
}

After returning from the browser, the stack is...
A,B,Browser,B

I expect this code to change the stack to...
A
... so that pressing back once more takes the user back to the Home Screen.

Instead, it seems to change the stack to...
A,B,Browser,B,A
...as though those flags aren't there.

I tried calling finish() in activity B after startActivity, but then the back button takes me back to the browser again!

What am I missing?

Body:
I use three flags to resolve the problem:

intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
                Intent.FLAG_ACTIVITY_CLEAR_TASK |
                Intent.FLAG_ACTIVITY_NEW_TASK);


问:
Django and service workers - serve "sw.js" at application's root url
So I'm building a Django progressive web app with offline support using service workers.

According to google's documentation, the sw.js file should be at the root of the app's url:

You need to do this because the scope of a service worker (the set of
  urls that the ServiceWorker will load for) is defined by the directory
  where it resides.

At the moment, I'm serving all static assets from http://example.com/static/ folder. But I need to serve this specific file at a url like: http://example.com/sw.js.

Any idea how I can achieve this? I could make a specific nginx rule to do this redirection, but I don't know if it's the cleanest way of doing this. Maybe this setting should reside in urls.py?

Note: I've seen this question which suggests using the static() method from django.conf.urls.static. But django's docs say that the static method is only for development use so not good for me.

Note (2): I guess I could change the STATIC_URL setting, but I'm happy with my files being served from /static directory. I only want this one file to be at url's root.

答:
In Django 1.11 urls.py should look:</p>

```<code>from django.views.generic import TemplateView

urlpatterns = [
  url(r'^sw.js', (TemplateView.as_view(template_name="sw.js", content_type='application/javascript', )), name='sw.js'),
]
</code>```

Body:
In Django 1.11 urls.py should look:

from django.views.generic import TemplateView

urlpatterns = [
  url(r'^sw.js', (TemplateView.as_view(template_name="sw.js", content_type='application/javascript', )), name='sw.js'),
]


答:
Here's a suggestion: initialize choice with something that is guaranteed to be unequal number (e.g. a negative number, a "sentinel"). Then you can start with the while loop right away, because the condition will always be true for the first time.

Then you can remove the first if/then/else block and the first call to input() outside the while loop.

BTW, "shorter code" is not always "efficient code" :)

Title: How can I make this python code shorter and more efficient

Body:
This is my attempt at doing a higher/lower game.

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = int(input("Please pick a number between 1 & 100: "))
if choice < number:
    print("Higher")
elif choice > number:
    print("Lower")
else:
    print("Well done!")
while choice != number:
    choice = int(input("Pick again: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")

I'm new to python and I'm just wondering is there a way of shortening the code to make it more efficient? Don't think there is a need for two 'if/elif/else' statements but can't see a way to merge them. Sorry if it's a stupid question!

Updated Code:

import random
print("A game of Higher or Lower")
number = random.randint(1, 100)
choice = ""
while choice != number:
    choice = int(input("Please pick a number: "))
    if choice < number:
        print("Higher")
    elif choice > number:
        print("Lower")
    else:
        print("Well done!")


问:
disable nganimate for some elements
I'm using the ngAnimate module, but all my ng-if, ng-show, etc, are affected by that, I want to leverage ngAnimate for some selected elements.
For performance and some bugs in elements that shows and hide very speedy.

thanks.

答:
I know that it is a delayed reply, but here we use in MainController:

```<code>// disable all animations
$animate.enabled(false);
</code>```

But the problem is that when we disable all animations, the ui-select are configured to opacity: 0.

So, its necessary to set opacity to 1 using CSS:

```<code>.ui-select-choices {
    opacity: 1 !important;
}
</code>```

This will properly set opacity and the ui-select will work.

Title: disable nganimate for some elements

Body:
I know that it is a delayed reply, but here we use in MainController:

// disable all animations
$animate.enabled(false);

But the problem is that when we disable all animations, the ui-select are configured to opacity: 0.

So, its necessary to set opacity to 1 using CSS:

.ui-select-choices {
    opacity: 1 !important;
}

This will properly set opacity and the ui-select will work.


问:
How to get all PHAssets from MacOS's Photo Library
I want to parse all images from my MacOS Photos Library, using PHAsset. However all examples I find are only working for iOS, like the one below, where the last line, which retrieves the assets is not available on macos framework:

```<code>    NSMutableArray *photos = [[NSMutableArray alloc] init];
    PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
    allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

 // Below compilation error as fetchAssetsWithMediaType is only on iOS framework
    PHFetchResult *allPhotos = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];
</code>```

What fetchAssets command should I use on MacOS (version 10.13), or is there another way to do so ?

答:
The Photos framework — or at least, the main subset of that framework, which provides apps with read/write access to the entire Photos library — is not available in macOS.

Photos and PhotosUI are present in macOS, but only in support of specific app-extension features:

Photo Editing extensions. The user invokes these from the Photos app while in Edit mode for a single asset, and it provides direct access to the photo/video data for that asset, so it doesn’t even use the PHAsset class.

Photo Project extensions. These involve collections of assets and selectively loading data for each, so more of the PHAsset/PHImageManager system is present. However, it’s still a reduced subset compared to iOS (only what’s needed for a project extension, like fetching the assets in that project), and it’s accessible only to app extensions, not standalone apps.

If you’d like the full Photos framework on macOS, your best bet is to file a feature request with Apple.

Body:
I want to parse all images from my MacOS Photos Library, using PHAsset. However all examples I find are only working for iOS, like the one below, where the last line, which retrieves the assets is not available on macos framework:

    NSMutableArray *photos = [[NSMutableArray alloc] init];
    PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
    allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];

 // Below compilation error as fetchAssetsWithMediaType is only on iOS framework
    PHFetchResult *allPhotos = [PHAsset fetchAssetsWithMediaType:PHAssetMediaTypeImage options:allPhotosOptions];

What fetchAssets command should I use on MacOS (version 10.13), or is there another way to do so ?


问:
Run a command for each item in jq array
This is how my input file looks like:

```<code>[
  {
    "ConfigType": "ABC",
    "Prop1": 3,
    "Prop2": 30
  },
  {
    "ConfigType": "XYZ",
    "Prop3": "Hello",
    "Prop4": "World",
    "Prop5": "Application"
  }
]
</code>```

I need to prepare insert statement for each item.

This is how my jq command looks like which gives me each item.

```<code>cat app-cnfg.json |  jq -r ".[]"
</code>```

How do I execute aws dynamodb put-item --table-name "xxx" --item <<array's element>>?

答:
You can pipe to xargs:

```<code>jq -c '.[]' app-cnfg.json \
    | xargs -L 1 aws dynamodb put-item --table-name "xxx" --item
</code>```

The -c option to jq makes sure each element is on a single line, and the -L 1 option to xargs makes sure that the command is called once per item.

If you wanted to avoid potential problems with trailing whitespace (which would make args treat the following line as continuation of the current one), you can get your objects zero byte separated:

```<code>jq -j '.[] | tostring + "\u0000"' app-cnfg.json \
    | xargs -0 -n1 aws dynamodb put-item --table-name "xxx" --item
</code>```

The -j option suppresses newlines from jq, tostring stringifies the objects and + "\u0000" appends a zero byte.

xargs -0 -n1 expects zero byte delimited input and runs the command for each argument once.

Title: Run a command for each item in jq array

Body:
This is how my input file looks like:

[
  {
    "ConfigType": "ABC",
    "Prop1": 3,
    "Prop2": 30
  },
  {
    "ConfigType": "XYZ",
    "Prop3": "Hello",
    "Prop4": "World",
    "Prop5": "Application"
  }
]

I need to prepare insert statement for each item.

This is how my jq command looks like which gives me each item.

cat app-cnfg.json |  jq -r ".[]"

How do I execute aws dynamodb put-item --table-name "xxx" --item <<array's element>>?

Body:
You can pipe to xargs:

jq -c '.[]' app-cnfg.json \
    | xargs -L 1 aws dynamodb put-item --table-name "xxx" --item

The -c option to jq makes sure each element is on a single line, and the -L 1 option to xargs makes sure that the command is called once per item.

If you wanted to avoid potential problems with trailing whitespace (which would make args treat the following line as continuation of the current one), you can get your objects zero byte separated:

jq -j '.[] | tostring + "\u0000"' app-cnfg.json \
    | xargs -0 -n1 aws dynamodb put-item --table-name "xxx" --item

The -j option suppresses newlines from jq, tostring stringifies the objects and + "\u0000" appends a zero byte.

xargs -0 -n1 expects zero byte delimited input and runs the command for each argument once.


问:
Why MVC Model Binder set required for int, long values?
I have a Model Like this

```<code>public int Id {get;set;}

[Required]
public string FirstName{get; set}
[Required]
public string LastName{get; set}
</code>```

The Id is auto generate in DB. when I want call Create action The ModelState says that "The Id field is required"!!!! I Found this for my problem but it not clean solution.
Is there an other way to solve this?

Is there a way that I change Mvc ModelBinder behavior for value types?

答:
You can also set the property type to Nullable<T>, and then just manually enforce any required validation you might need to do before working with the database.

public int? Id {get;set;}
```

Further Reading:

Unrequired property keeps getting data-val-required attribute

ASP.NET MVC optional field being treated as required

"The Id field is required" validation message on Create

Body:
I have a Model Like this

public int Id {get;set;}

[Required]
public string FirstName{get; set}
[Required]
public string LastName{get; set}

The Id is auto generate in DB. when I want call Create action The ModelState says that "The Id field is required"!!!! I Found this for my problem but it not clean solution.
Is there an other way to solve this?

Is there a way that I change Mvc ModelBinder behavior for value types?

Body:
You can also set the property type to Nullable<T>, and then just manually enforce any required validation you might need to do before working with the database.

public int? Id {get;set;}

Further Reading:

Unrequired property keeps getting data-val-required attribute

ASP.NET MVC optional field being treated as required

"The Id field is required" validation message on Create


问:
How do I split the output from mysqldump into smaller files?
I need to move entire tables from one MySQL database to another. I don't have full access to the second one, only phpMyAdmin access. I can only upload (compressed) sql files smaller than 2MB. But the compressed output from a mysqldump of the first database's tables is larger than 10MB.

Is there a way to split the output from mysqldump into smaller files? I cannot use split(1) since I cannot cat(1) the files back on the remote server.

Or is there another solution I have missed?

Edit

The --extended-insert=FALSE option to mysqldump suggested by the first poster yields a .sql file that can then be split into importable files, provided that split(1) is called with a suitable --lines option. By trial and error I found that bzip2 compresses the .sql files by a factor of 20, so I needed to figure out how many lines of sql code correspond roughly to 40MB.

答:
Late reply but was looking for same solution and came across following code from below website:

```<code>for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip > "$I.sql.gz"; done
</code>```

http://www.commandlinefu.com/commands/view/2916/backup-all-mysql-databases-to-individual-files

OwnerDisplayName: lindelof

LastEditorDisplayName: lindelof

Body:
Late reply but was looking for same solution and came across following code from below website:

for I in $(mysql -e 'show databases' -s --skip-column-names); do mysqldump $I | gzip > "$I.sql.gz"; done

http://www.commandlinefu.com/commands/view/2916/backup-all-mysql-databases-to-individual-files


问:
failed to open a new window after push button pyqt5
i learning pyqt5 and trying to open a new window by click a button from another window. if there are not input() function it will close the open window immediately, so i put input() to keep the window open.  the window will open for long, but then it has stopped working. Can some one help me ? Thank you</p>

```<code>import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App1(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'open window'
        self.left = 60
        self.top = 60
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.show()
        m.getch()
        input()                  '''here is the problem'''

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button - pythonspot.com'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):

        app1 = QApplication(sys.argv)
        ex1 = App1()
        sys.exit(app1.exec_())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())
</code>```

答:
You need to save a reference to the window or it will be garbage collected when  on_click() finishes executing. The easiest way is to store it in App through the use of self

```<code>@pyqtSlot()
def on_click(self):
    self.ex1 = App1()
</code>```

Body:
i learning pyqt5 and trying to open a new window by click a button from another window. if there are not input() function it will close the open window immediately, so i put input() to keep the window open.  the window will open for long, but then it has stopped working. Can some one help me ? Thank you

import sys
from PyQt5.QtWidgets import QApplication, QPushButton,QMainWindow,QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot

class App1(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'open window'
        self.left = 60
        self.top = 60
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        self.show()
        m.getch()
        input()                  '''here is the problem'''

class App(QMainWindow):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 button - pythonspot.com'
        self.left = 200
        self.top = 200
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

        button = QPushButton('PyQt5 button', self)
        button.setToolTip('This is an example button')
        button.move(100, 70)
        button.clicked.connect(self.on_click)

        self.show()

    @pyqtSlot()
    def on_click(self):

        app1 = QApplication(sys.argv)
        ex1 = App1()
        sys.exit(app1.exec_())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

Body:
You need to save a reference to the window or it will be garbage collected when  on_click() finishes executing. The easiest way is to store it in App through the use of self

@pyqtSlot()
def on_click(self):
    self.ex1 = App1()


问:
Since 03/12/1017 Not received notifications from azure notification hub
On  sending test message (WNS) received back message:-

The Notification was received and dropped by the Push Notification Service as device in disconnected state

Everything has been fine for the last 2 years with no changes.

答: I see a lot of X-WNS-DEVICECONNECTIONSTATUS-disconnected error messages shown in the logs for your namespace. This happens when the device is offline and not connected to WNS. Can you check if that is the case with you. </p>