问:
How to filter and modify an array of objects with a single line of code?
I have the following array of objects coming from my database:

```<code>dataFromDB = [
  { src: 'stringWithSource1',
    selected: true
  },
  { src: 'stringWithSource2',
    selected: false
  },
  { src: 'stringWithSource3',
    selected: true
  },
  AND SO ON...
];
</code>```

When I fetch it from the database I need to store on client-side in a state that must be an array of strings, containing only the src property of the objects that are selected: true.

Example:

```<code>myState = [
  'stringWithSource1',
  'stringWithSource3',
  AND SO ON...
]
</code>```

QUESTION

The line where I'm assigning this, is like the following (see code below):

I tried but that doesn't work because I'm keeping the unselected src as null instead of just skipping them.

```<code>setProductDetails({
  // ... other properties,
  images: dataFromDB.images.map((item) => {
    return item.selected ? item.src : null;
  }
});
</code>```

How can I achieve this behavior in a single line like this? I know I could create an auxiliar variable and handle this. But I would like a one-liner in this case. Is this possible? It feels like I should filter and map at the same time?

答:
You need two parts, because the filtering does not map a value, but the original items.

You could filter by selected and then map src.

```<code>images: dataFromDB.images
    .filter(({ selected }) => selected)
    .map(({ src }) => src)
</code>```

Body:
I have the following array of objects coming from my database:

dataFromDB = [
  { src: 'stringWithSource1',
    selected: true
  },
  { src: 'stringWithSource2',
    selected: false
  },
  { src: 'stringWithSource3',
    selected: true
  },
  AND SO ON...
];

When I fetch it from the database I need to store on client-side in a state that must be an array of strings, containing only the src property of the objects that are selected: true.

Example:

myState = [
  'stringWithSource1',
  'stringWithSource3',
  AND SO ON...
]

QUESTION

The line where I'm assigning this, is like the following (see code below):

I tried but that doesn't work because I'm keeping the unselected src as null instead of just skipping them.

setProductDetails({
  // ... other properties,
  images: dataFromDB.images.map((item) => {
    return item.selected ? item.src : null;
  }
});

How can I achieve this behavior in a single line like this? I know I could create an auxiliar variable and handle this. But I would like a one-liner in this case. Is this possible? It feels like I should filter and map at the same time?

Body:
You need two parts, because the filtering does not map a value, but the original items.

You could filter by selected and then map src.

images: dataFromDB.images
    .filter(({ selected }) => selected)
    .map(({ src }) => src)


来源: stackexchange

问:
Permission default dialog not showing
```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.shareitreplica">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" android:required="true" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" android:required="true" />
    <uses-permission android:name="android.permission.INTERNET" android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>
</code>```

Gradle

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.shareitreplica"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation project(':library')
}
</code>```

My code

```<code>if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE)
                != PackageManager.PERMISSION_GRANTED) {

            System.out.println("Starting");
            if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.INTERNET}, 111);
                System.out.println("Starting1");
            }
        }
</code>```

I think this is the best way to get the permission from user. And the official doc also says this. But on running this code I am not prompted by the os for permission.

I get both the print lines after running the code.
I have Android Oreo version.

答:
The ACCESS_WIFI_STATE permission has access level normal, it does not require the user to grant it at runtime.

See this for reference.

ContentLicense: CC BY-SA 4.0

Title: Permission default dialog not showing

Body:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.shareitreplica">

    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" android:required="true" />
    <uses-permission android:name="android.permission.CHANGE_WIFI_STATE" android:required="true" />
    <uses-permission android:name="android.permission.INTERNET" android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.shareitreplica"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

    implementation project(':library')
}

My code

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE)
                != PackageManager.PERMISSION_GRANTED) {

            System.out.println("Starting");
            if (Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.INTERNET}, 111);
                System.out.println("Starting1");
            }
        }

I think this is the best way to get the permission from user. And the official doc also says this. But on running this code I am not prompted by the os for permission.

I get both the print lines after running the code.
I have Android Oreo version.


问:
How do I get rgdal to open a geodatabase (.gdb) file?
I'm trying to read in a .gdb file using rgdal:: readOGR. I finally got it to work a few days ago by removing the trailing "/" at the end of the path and the .gdb at the end of the file name. Then, poof! today my code won't work. As far as I can tell nothing has changed!

After my code failed, I tried updating everything, so I'm now running: Mac OS10.14.4, RStudio v1.2.1335, R v3.6.0, and rgdal v1.4-3. I've checked that rgdal has the OpenFileGDB driver. I've also tried adding the .gdb extension to the filename, and changing the .lyr filename to match that .gdb filename, but nothing works.

Here is the code I'm using...

```<code>gdb <- path.expand("Data/GIS/CA_LandUse2014/ds2677")
luca <- readOGR(gdb, "ds2677")
</code>```

And here is the error message:

Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv,  :
Cannot open data source

These are the files in the ds2677 folder:

```<code>> list.files(path.expand("Data/GIS/CA_LandUse2014/ds2677"))
[1] "ds2677_LandUse2014.lyr" "ds2677.gdb"
</code>```

And these are the files in ds2677.gdb.

```<code>> list.files(path.expand("Data/GIS/CA_LandUse2014/ds2677/ds2677.gdb"))
 [1] "a00000001.freelist"                          "a00000001.gdbindexes"
 [3] "a00000001.gdbtable"                          "a00000001.gdbtablx"
 [5] "a00000001.TablesByName.atx"                  "a00000002.gdbtable"
 [7] "a00000002.gdbtablx"                          "a00000003.gdbindexes"
 [9] "a00000003.gdbtable"                          "a00000003.gdbtablx"
[11] "a00000004.CatItemsByPhysicalName.atx"        "a00000004.CatItemsByType.atx"
[13] "a00000004.FDO_UUID.atx"                      "a00000004.freelist"
[15] "a00000004.gdbindexes"                        "a00000004.gdbtable"
[17] "a00000004.gdbtablx"                          "a00000004.spx"
[19] "a00000005.CatItemTypesByName.atx"            "a00000005.CatItemTypesByParentTypeID.atx"
[21] "a00000005.CatItemTypesByUUID.atx"            "a00000005.gdbindexes"
[23] "a00000005.gdbtable"                          "a00000005.gdbtablx"
[25] "a00000006.CatRelsByDestinationID.atx"        "a00000006.CatRelsByOriginID.atx"
[27] "a00000006.CatRelsByType.atx"                 "a00000006.FDO_UUID.atx"
[29] "a00000006.freelist"                          "a00000006.gdbindexes"
[31] "a00000006.gdbtable"                          "a00000006.gdbtablx"
[33] "a00000007.CatRelTypesByBackwardLabel.atx"    "a00000007.CatRelTypesByDestItemTypeID.atx"
[35] "a00000007.CatRelTypesByForwardLabel.atx"     "a00000007.CatRelTypesByName.atx"
[37] "a00000007.CatRelTypesByOriginItemTypeID.atx" "a00000007.CatRelTypesByUUID.atx"
[39] "a00000007.gdbindexes"                        "a00000007.gdbtable"
[41] "a00000007.gdbtablx"                          "a0000000a.FDO_GlobalID.atx"
[43] "a0000000a.gdbindexes"                        "a0000000a.gdbtable"
[45] "a0000000a.gdbtablx"                          "a0000000a.spx"
[47] "gdb"                                         "timestamps"
</code>```

答:
This how I went about this in R 3.60 with rgdal 1.4-4 drivers on Windows 10 with no ARC-GIS licenses. Note that I am converting *.gdbtable files to a shp file eventually for use on Google Earth Pro. Only one of gdbtable files did not have 'null geometry' or fields I was interested in. So the numbered files weren't interesting to me. But ogrInfo proved that "a0000000b.gdbtable" was interesting. Caveat: I am just posting how I hacked this out. Much of the time I find GIS code in R idiosyncratic enough that I don't bother to understand the functionally of the libraries like I should. I just get it to work well enough to give me an ESRI shp file for import.</p>

```<code>dir(pattern="*gdbtable")
[1] "a00000001.gdbtable" "a00000002.gdbtable" "a00000003.gdbtable" "a00000004.gdbtable" "a00000005.gdbtable" "a00000006.gdbtable" "a00000007.gdbtable" "a0000000b.gdbtable"

library(data.table)
library(rgdal) #rgdal_1.4-4

sessionInfo()
nrow(ogrDrivers())
as.data.table(ogrDrivers())[grepl("ESRI",long_name),]
cat('
             name                 long_name write  copy isVector
1: ESRI Shapefile            ESRI Shapefile  TRUE FALSE     TRUE
2:    OpenFileGDB              ESRI FileGDB FALSE FALSE     TRUE
')

 setwd("C:/Users/username/Downloads/EAP_ENV_AmbientStations/EAP_ENV_AmbientStations.gdb")
ogrInfo("a0000000b.gdbtable")
cat('
Source: "C:\Users\username\Downloads\EAP_ENV_AmbientStations\EAP_ENV_AmbientStations.gdb\a0000000b.gdbtable", layer: "EAP_ENV_AmbientStations"
Driver: OpenFileGDB; number of rows: 557
Feature type: wkbPoint with 2 dimensions
Extent: (623276.8 93472.33) - (2533932 1367270)
CRS: +proj=lcc +lat_1=47.33333333333334 +lat_2=45.83333333333334 +lat_0=45.33333333333334 +lon_0=-120.5 +x_0=500000.0001016001 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=us-ft +no_defs
Number of fields: 22
         name type length typeName
1     STATION    4      6   String
2     STANAME    4     35   String
3        WBID    4     10   String
... ')

a0000000b <-  readOGR("a0000000b.gdbtable")
writeOGR(a0000000b,dsn="EAP_ENV_AmbientStations.gdb",layer="EAP_ENV_AmbientStations_b",driver="ESRI Shapefile")

as.data.table(data.frame(a0000000b))[,names(.SD)]
 [1] "STATION"    "STANAME"    "WBID"       "DECOREGN"   "ECORGN"     "WATERSHED"  "GLACIAL"    "SPECIALCRI" "CORE"       "STRUCT"     "SURROUND"   "LOCATIONTY" "ELEV"       "RMI"        "LAT_DD"     "LONG_DD"    "TRS"        "QUAD"       "COUNTY"
[20] "CONGDIST"   "LEGDIST"    "CLASS"      "coords.x1"  "coords.x2"  "optional"

bubble(a0000000b['LAT_DD'], col=rgb(0.5,0.5,1,0.5))
</code>```

Body:
I'm trying to read in a .gdb file using rgdal:: readOGR. I finally got it to work a few days ago by removing the trailing "/" at the end of the path and the .gdb at the end of the file name. Then, poof! today my code won't work. As far as I can tell nothing has changed!

After my code failed, I tried updating everything, so I'm now running: Mac OS10.14.4, RStudio v1.2.1335, R v3.6.0, and rgdal v1.4-3. I've checked that rgdal has the OpenFileGDB driver. I've also tried adding the .gdb extension to the filename, and changing the .lyr filename to match that .gdb filename, but nothing works.

Here is the code I'm using...

gdb <- path.expand("Data/GIS/CA_LandUse2014/ds2677")
luca <- readOGR(gdb, "ds2677")

And here is the error message:

Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv,  :
Cannot open data source

These are the files in the ds2677 folder:

> list.files(path.expand("Data/GIS/CA_LandUse2014/ds2677"))
[1] "ds2677_LandUse2014.lyr" "ds2677.gdb"

And these are the files in ds2677.gdb.

> list.files(path.expand("Data/GIS/CA_LandUse2014/ds2677/ds2677.gdb"))
 [1] "a00000001.freelist"                          "a00000001.gdbindexes"
 [3] "a00000001.gdbtable"                          "a00000001.gdbtablx"
 [5] "a00000001.TablesByName.atx"                  "a00000002.gdbtable"
 [7] "a00000002.gdbtablx"                          "a00000003.gdbindexes"
 [9] "a00000003.gdbtable"                          "a00000003.gdbtablx"
[11] "a00000004.CatItemsByPhysicalName.atx"        "a00000004.CatItemsByType.atx"
[13] "a00000004.FDO_UUID.atx"                      "a00000004.freelist"
[15] "a00000004.gdbindexes"                        "a00000004.gdbtable"
[17] "a00000004.gdbtablx"                          "a00000004.spx"
[19] "a00000005.CatItemTypesByName.atx"            "a00000005.CatItemTypesByParentTypeID.atx"
[21] "a00000005.CatItemTypesByUUID.atx"            "a00000005.gdbindexes"
[23] "a00000005.gdbtable"                          "a00000005.gdbtablx"
[25] "a00000006.CatRelsByDestinationID.atx"        "a00000006.CatRelsByOriginID.atx"
[27] "a00000006.CatRelsByType.atx"                 "a00000006.FDO_UUID.atx"
[29] "a00000006.freelist"                          "a00000006.gdbindexes"
[31] "a00000006.gdbtable"                          "a00000006.gdbtablx"
[33] "a00000007.CatRelTypesByBackwardLabel.atx"    "a00000007.CatRelTypesByDestItemTypeID.atx"
[35] "a00000007.CatRelTypesByForwardLabel.atx"     "a00000007.CatRelTypesByName.atx"
[37] "a00000007.CatRelTypesByOriginItemTypeID.atx" "a00000007.CatRelTypesByUUID.atx"
[39] "a00000007.gdbindexes"                        "a00000007.gdbtable"
[41] "a00000007.gdbtablx"                          "a0000000a.FDO_GlobalID.atx"
[43] "a0000000a.gdbindexes"                        "a0000000a.gdbtable"
[45] "a0000000a.gdbtablx"                          "a0000000a.spx"
[47] "gdb"                                         "timestamps"

Body:
This how I went about this in R 3.60 with rgdal 1.4-4 drivers on Windows 10 with no ARC-GIS licenses. Note that I am converting *.gdbtable files to a shp file eventually for use on Google Earth Pro. Only one of gdbtable files did not have 'null geometry' or fields I was interested in. So the numbered files weren't interesting to me. But ogrInfo proved that "a0000000b.gdbtable" was interesting. Caveat: I am just posting how I hacked this out. Much of the time I find GIS code in R idiosyncratic enough that I don't bother to understand the functionally of the libraries like I should. I just get it to work well enough to give me an ESRI shp file for import.

dir(pattern="*gdbtable")
[1] "a00000001.gdbtable" "a00000002.gdbtable" "a00000003.gdbtable" "a00000004.gdbtable" "a00000005.gdbtable" "a00000006.gdbtable" "a00000007.gdbtable" "a0000000b.gdbtable"

library(data.table)
library(rgdal) #rgdal_1.4-4

sessionInfo()
nrow(ogrDrivers())
as.data.table(ogrDrivers())[grepl("ESRI",long_name),]
cat('
             name                 long_name write  copy isVector
1: ESRI Shapefile            ESRI Shapefile  TRUE FALSE     TRUE
2:    OpenFileGDB              ESRI FileGDB FALSE FALSE     TRUE
')

 setwd("C:/Users/username/Downloads/EAP_ENV_AmbientStations/EAP_ENV_AmbientStations.gdb")
ogrInfo("a0000000b.gdbtable")
cat('
Source: "C:\Users\username\Downloads\EAP_ENV_AmbientStations\EAP_ENV_AmbientStations.gdb\a0000000b.gdbtable", layer: "EAP_ENV_AmbientStations"
Driver: OpenFileGDB; number of rows: 557
Feature type: wkbPoint with 2 dimensions
Extent: (623276.8 93472.33) - (2533932 1367270)
CRS: +proj=lcc +lat_1=47.33333333333334 +lat_2=45.83333333333334 +lat_0=45.33333333333334 +lon_0=-120.5 +x_0=500000.0001016001 +y_0=0 +ellps=GRS80 +towgs84=0,0,0,0,0,0,0 +units=us-ft +no_defs
Number of fields: 22
         name type length typeName
1     STATION    4      6   String
2     STANAME    4     35   String
3        WBID    4     10   String
... ')

a0000000b <-  readOGR("a0000000b.gdbtable")
writeOGR(a0000000b,dsn="EAP_ENV_AmbientStations.gdb",layer="EAP_ENV_AmbientStations_b",driver="ESRI Shapefile")

as.data.table(data.frame(a0000000b))[,names(.SD)]
 [1] "STATION"    "STANAME"    "WBID"       "DECOREGN"   "ECORGN"     "WATERSHED"  "GLACIAL"    "SPECIALCRI" "CORE"       "STRUCT"     "SURROUND"   "LOCATIONTY" "ELEV"       "RMI"        "LAT_DD"     "LONG_DD"    "TRS"        "QUAD"       "COUNTY"
[20] "CONGDIST"   "LEGDIST"    "CLASS"      "coords.x1"  "coords.x2"  "optional"

bubble(a0000000b['LAT_DD'], col=rgb(0.5,0.5,1,0.5))


问:
ToggleClass Based on checkbox status
So I've got some nav that consists of form checkboxes floated next to a traditional anchors. If the corresponding checkbox is not checked, I want to add a class (that basically will be styled to dim the anchor tag). What's the best way to do this systematically?</p>

```<code><div id="navPod">
    <form method="post" action="#" id="contentFilterForm" name="contentFilterForm">
        <input type="hidden" name="q" value="<?php echo $q;?>" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'projects'){ echo "checked=\"checked\"";} if($proj){ echo "checked=\"checked\"";} ?> name="pr" value="1" id="filterProjects" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'playground'){ echo "checked=\"checked\"";} if($playground){ echo "checked=\"checked\"";} ?> type="checkbox" name="pl" value="1" id="filterPlayground" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'about'){ echo "checked=\"checked\"";} if($culture){ echo "checked=\"checked\"";} ?> name="cu" value="1" id="filterCulture" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'leadership'){ echo "checked=\"checked\"";} if($leadership){ echo "checked=\"checked\"";} ?> name="le" value="1" id="filterLeadership" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'careers'){ echo "checked=\"checked\"";} if($jobs){ echo "checked=\"checked\"";} ?> name="ca" value="1" id="filterCareers" />

        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'blog'){ echo "checked=\"checked\"";} if($blog){ echo "checked=\"checked\"";} ?> type="checkbox" name="bl" value="1" id="filterBlog" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'delicious'){ echo "checked=\"checked\"";} if($links){ echo "checked=\"checked\"";} ?> type="checkbox" name="li" value="1" id="filterDelicious" />

        <input id="refreshSubmit" type="button" value="" onclick="createURLS()"/>
    </form>

    <div class="subnav">
        <a id="projectsLink" title="Projects" href="/projects/" <?php if($pagetype == 'projects'){ echo "class=\"currentPage\""; } ?> >Projects</a><br />
        <a id="playgroundLink" title="Playground" href="/playground/" <?php if($pagetype == 'playground'){ echo "class=\"currentPage\""; } ?> >Playground</a><br />
        <a id="aboutLink" title="About Centerline Digital" href="/about/" <?php if($pagetype == 'about'){ echo "class=\"currentPage\""; } ?> >About Us</a><br />
        <a id="leadershipLink" title="Leadership" href="/leadership/" <?php if($pagetype == 'leadership'){ echo "class=\"currentPage\""; } ?> >Leadership</a><br />
        <a id="careersLink" title="Careers" href="/careers/" <?php if($pagetype == 'careers'){ echo "class=\"currentPage\""; } ?> >Careers</a><br />
        <a id="blogLink" title="Blog" href="/blog/" <?php if($pagetype == 'blog'){ echo "class=\"currentPage\""; } ?> >Blog</a><br />
        <a id="thoughtsLink" title="Thoughts and Links" href="/thoughts/" <?php if($pagetype == 'delicious'){ echo "class=\"currentPage\""; } ?> >Thoughts and Links</a><br />

        <a target="_blank" title="Subscribe to Custom Feed" id="feedLink" href="/dyn/">Subscribe to Custom Feed</a>
    </div>
</div>
</code>```

答:
based on the html I would try this

```<code>$('input:checkbox').each(function(){
var anchor_id = $(this).attr('id').replace('filter','').toLowerCase();;
     $('#'+anchor_id+'Link').toggleClass('someclass', $(this).attr('checked'));
});
$('input:checkbox').change(function(){
    var anchor_id = $(this).attr('id').replace('filter','').toLowerCase();;
     $('#'+anchor_id+'Link').toggleClass('someclass', $(this).attr('checked'));
})
</code>```

working demo

ContentLicense: CC BY-SA 3.0

Title: ToggleClass Based on checkbox status

Body:
So I've got some nav that consists of form checkboxes floated next to a traditional anchors. If the corresponding checkbox is not checked, I want to add a class (that basically will be styled to dim the anchor tag). What's the best way to do this systematically?

    <form method="post" action="#" id="contentFilterForm" name="contentFilterForm">
        <input type="hidden" name="q" value="<?php echo $q;?>" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'projects'){ echo "checked=\"checked\"";} if($proj){ echo "checked=\"checked\"";} ?> name="pr" value="1" id="filterProjects" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'playground'){ echo "checked=\"checked\"";} if($playground){ echo "checked=\"checked\"";} ?> type="checkbox" name="pl" value="1" id="filterPlayground" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'about'){ echo "checked=\"checked\"";} if($culture){ echo "checked=\"checked\"";} ?> name="cu" value="1" id="filterCulture" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'leadership'){ echo "checked=\"checked\"";} if($leadership){ echo "checked=\"checked\"";} ?> name="le" value="1" id="filterLeadership" />
        <input class="checkbox" type="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'careers'){ echo "checked=\"checked\"";} if($jobs){ echo "checked=\"checked\"";} ?> name="ca" value="1" id="filterCareers" />

        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'blog'){ echo "checked=\"checked\"";} if($blog){ echo "checked=\"checked\"";} ?> type="checkbox" name="bl" value="1" id="filterBlog" />
        <input class="checkbox" <?php if($pagetype == 'home'){ echo "checked=\"checked\"";} if($pagetype == 'delicious'){ echo "checked=\"checked\"";} if($links){ echo "checked=\"checked\"";} ?> type="checkbox" name="li" value="1" id="filterDelicious" />

        <input id="refreshSubmit" type="button" value="" onclick="createURLS()"/>
    </form>

        <a id="projectsLink" title="Projects" href="/projects/" <?php if($pagetype == 'projects'){ echo "class=\"currentPage\""; } ?> >Projects

        <a id="playgroundLink" title="Playground" href="/playground/" <?php if($pagetype == 'playground'){ echo "class=\"currentPage\""; } ?> >Playground

        <a id="aboutLink" title="About Centerline Digital" href="/about/" <?php if($pagetype == 'about'){ echo "class=\"currentPage\""; } ?> >About Us

        <a id="leadershipLink" title="Leadership" href="/leadership/" <?php if($pagetype == 'leadership'){ echo "class=\"currentPage\""; } ?> >Leadership

        <a id="careersLink" title="Careers" href="/careers/" <?php if($pagetype == 'careers'){ echo "class=\"currentPage\""; } ?> >Careers

        <a id="blogLink" title="Blog" href="/blog/" <?php if($pagetype == 'blog'){ echo "class=\"currentPage\""; } ?> >Blog

        <a id="thoughtsLink" title="Thoughts and Links" href="/thoughts/" <?php if($pagetype == 'delicious'){ echo "class=\"currentPage\""; } ?> >Thoughts and Links

        Subscribe to Custom Feed

Body:
based on the html I would try this

$('input:checkbox').each(function(){
var anchor_id = $(this).attr('id').replace('filter','').toLowerCase();;
     $('#'+anchor_id+'Link').toggleClass('someclass', $(this).attr('checked'));
});
$('input:checkbox').change(function(){
    var anchor_id = $(this).attr('id').replace('filter','').toLowerCase();;
     $('#'+anchor_id+'Link').toggleClass('someclass', $(this).attr('checked'));
})

working demo


问:
How can I use a properties file in the Deployed Resources/web-resources/ in a spring project
I'm working on a spring project and I'm trying to make integration test, but when I run the test the @ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring-servlet.xml"}) uses a .properties file for the datasource but it says that it can't find the .properties file in web-resources/META-INF because it always tries to look up in webapp/META-INF.

I'm using springframework 5.1.7 with java8, in the integration test I used @ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring-servlet.xml"}) to specify the application context file and in this file I try to specify the path to my .properties in the web-resources/META-INF, but when I run the test it can't find the file.

```<code>@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring-servlet.xml"})
@WebAppConfiguration
public class OtrasAdicionalesControllerTest {
</code>```

```<code><bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="/META-INF/jdbc.properties" />
</bean>
</code>```

```<code>java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/META-INF/jdbc.properties]
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:89)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:286)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:166)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:705)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
    at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:134)
    at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:61)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 common frames omitted
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/META-INF/jdbc.properties]
    at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:158)
    at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:159)
    at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:99)
    at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
    at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:162)
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:80)
    ... 35 common frames omitted
</code>```

答:
try to replace

```<code> "/META-INF/jdbc.properties"
</code>```

to

```<code>"classpath:jdbc.properties"
</code>```

Body:
I'm working on a spring project and I'm trying to make integration test, but when I run the test the @ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring-servlet.xml"}) uses a .properties file for the datasource but it says that it can't find the .properties file in web-resources/META-INF because it always tries to look up in webapp/META-INF.

I'm using springframework 5.1.7 with java8, in the integration test I used @ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring-servlet.xml"}) to specify the application context file and in this file I try to specify the path to my .properties in the web-resources/META-INF, but when I run the test it can't find the file.

@RunWith(SpringRunner.class)
@ContextConfiguration(locations = {"file:src/main/webapp/WEB-INF/spring-servlet.xml"})
@WebAppConfiguration
public class OtrasAdicionalesControllerTest {

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="/META-INF/jdbc.properties" />
</bean>

java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
    at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: org.springframework.beans.factory.BeanInitializationException: Could not load properties; nested exception is java.io.FileNotFoundException: Could not open ServletContext resource [/META-INF/jdbc.properties]
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:89)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:286)
    at org.springframework.context.support.PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(PostProcessorRegistrationDelegate.java:166)
    at org.springframework.context.support.AbstractApplicationContext.invokeBeanFactoryPostProcessors(AbstractApplicationContext.java:705)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:531)
    at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:134)
    at org.springframework.test.context.web.AbstractGenericWebContextLoader.loadContext(AbstractGenericWebContextLoader.java:61)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:108)
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:251)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
    at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
    ... 25 common frames omitted
Caused by: java.io.FileNotFoundException: Could not open ServletContext resource [/META-INF/jdbc.properties]
    at org.springframework.web.context.support.ServletContextResource.getInputStream(ServletContextResource.java:158)
    at org.springframework.core.io.support.EncodedResource.getInputStream(EncodedResource.java:159)
    at org.springframework.core.io.support.PropertiesLoaderUtils.fillProperties(PropertiesLoaderUtils.java:99)
    at org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:181)
    at org.springframework.core.io.support.PropertiesLoaderSupport.mergeProperties(PropertiesLoaderSupport.java:162)
    at org.springframework.beans.factory.config.PropertyResourceConfigurer.postProcessBeanFactory(PropertyResourceConfigurer.java:80)
    ... 35 common frames omitted

Body:
try to replace

 "/META-INF/jdbc.properties"

to

"classpath:jdbc.properties"


问:
Modifying a data structure while iterating over it
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

```<code>int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}
</code>```

答:
Iterators are invalidated by some operations that modify a std::vector.

Other containers have various rules about when iterators are and are not invalidated. This is a post (by yours truly) with details.

By the way, the entrypoint function main() MUST return int:

```<code>int main() { ... }
</code>```

Body:
What happens when you add elements to a data structure such as a vector while
iterating over it. Can I not do this?

I tried this and it breaks:

int main() {
    vector<int> x = { 1, 2, 3 };

    int j = 0;
    for (auto it = x.begin(); it != x.end(); ++it) {
        x.push_back(j);
        j++;
        cout << j << " .. ";
    }
}

Body:
Iterators are invalidated by some operations that modify a std::vector.

Other containers have various rules about when iterators are and are not invalidated. This is a post (by yours truly) with details.

By the way, the entrypoint function main() MUST return int:

int main() { ... }


问:
JS: Filter object array for partial matches
Is it possible to filter for those objects, which matches for a search string?

```<code>const arr = [
    { title: 'Just an example' },
    { title: 'Another exam'},
    { title: 'Something different'}
]
</code>```

I tried this

```<code>arr.filter(x => { return x.title === searchStr });
</code>```

But this will filter only exact matches, but I need to find all partial matches. let searchStr = 'exam' should give me two objects (first and second), let searchStr = 'examp' should give me only one object as the result.

答:
You can check with the indexOf and also add toLowerCase() method to increase the possibility of a match</p>

```<code>myArr.filter(function(x) {
    return x.title.toLowerCase().indexOf(searchString.toLowerCase()) > -1;
}
</code>```

Body:
Is it possible to filter for those objects, which matches for a search string?

const arr = [
    { title: 'Just an example' },
    { title: 'Another exam'},
    { title: 'Something different'}
]

I tried this

arr.filter(x => { return x.title === searchStr });

But this will filter only exact matches, but I need to find all partial matches. let searchStr = 'exam' should give me two objects (first and second), let searchStr = 'examp' should give me only one object as the result.

Body:
You can check with the indexOf and also add toLowerCase() method to increase the possibility of a match

myArr.filter(function(x) {
    return x.title.toLowerCase().indexOf(searchString.toLowerCase()) > -1;
}


问:
Is there a way to validate, from the DBMS side, if a "boolean" column is already checked (true) in the table but for a subset of rows only
I'm using MSSQL Server and I want to know if there is a way, from the DBMS side, to validate if a "boolean" column is already checked (true) in the table but for a subset of rows only.

Here's an example:

I have the following tables

Users

```<code>id | name
--------------------
10 | John Smith
11 | Lee Sin
</code>```

Types

```<code>id | name
--------------------
20 | Developer
21 | Tester
22 | User
</code>```

UsersTypes

```<code>UserId  | TypeId | IsDefaultChoice
--------------------
10      | 20     | true
10      | 21     | false
11      | 20     | true
</code>```

I want to insert into a table "UsersTypes" the following:

```<code>UserId  | TypeId | IsDefaultChoice
--------------------
10      | 22     | true
</code>```

* Note: There will be multiple rows with "true" value in the "IsDefaultChoice" column across the table, but I want that only one row may be set to "true" per group of UserId in the table "UsersTypes".

I'm looking for a way to force the insert to fail because the user "John Smith" has already one entry "IsDefaultChoice" to true and can't have two "true" entries for this user upon insertion (or update)

答:
Yes, you can add a filtered unique index:

```<code>create unique index unq_usertypes_default
    on usertypes(userId)
    where IsDefaultChoice = 'TRUE';
</code>```

This will ensure that IsDefaultChoice is set for at most one row in UserTypes.  Note that this potentially complicates updating rows to a new default -- you have to be sure you unset the previous one.

Note that SQL Server does not have a boolean type.  I assume you mean bit, which does recognize 'TRUE' and 'FALSE' as valid values.

Body:
I'm using MSSQL Server and I want to know if there is a way, from the DBMS side, to validate if a "boolean" column is already checked (true) in the table but for a subset of rows only.

Here's an example:

I have the following tables

Users

id | name
--------------------
10 | John Smith
11 | Lee Sin

Types

id | name
--------------------
20 | Developer
21 | Tester
22 | User

UsersTypes

UserId  | TypeId | IsDefaultChoice
--------------------
10      | 20     | true
10      | 21     | false
11      | 20     | true

I want to insert into a table "UsersTypes" the following:

UserId  | TypeId | IsDefaultChoice
--------------------
10      | 22     | true

* Note: There will be multiple rows with "true" value in the "IsDefaultChoice" column across the table, but I want that only one row may be set to "true" per group of UserId in the table "UsersTypes".

I'm looking for a way to force the insert to fail because the user "John Smith" has already one entry "IsDefaultChoice" to true and can't have two "true" entries for this user upon insertion (or update)

Body:
Yes, you can add a filtered unique index:

create unique index unq_usertypes_default
    on usertypes(userId)
    where IsDefaultChoice = 'TRUE';

This will ensure that IsDefaultChoice is set for at most one row in UserTypes.  Note that this potentially complicates updating rows to a new default -- you have to be sure you unset the previous one.

Note that SQL Server does not have a boolean type.  I assume you mean bit, which does recognize 'TRUE' and 'FALSE' as valid values.


问:
sql server connection not showing up
I have mysql installed (including the connector for .net) and visual studio 2019 installed but when I try to connect via the one of the connections I have on the work bench by entering the name (it doesnt show up on the dropdown) I get the following error: server was not found or not accessible

here is the relevant server information

here a few other stack overflow related questions I found but none of them were helping me:

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

SQL Server is not showing in Visual Studio

How do I ensure Remote connections are allowed?

Also I have visual studio 2019 which meant I couldn't download the special mysql toolbar but does that mean it won't work at all with visual studio 2019?

答: what ended up working is if I go back and install vs2017 as oppose to vs 2019.</p>

Title: sql server connection not showing up


问:
Infinispan NotSerializableException when spinning up WAR in Wildfly 16
I am trying to run my application on 2 Wildfly 16 nodes running in Standalone mode using the standalone-full-ha.xml configuration. When the 2nd node starts up, the first attempts to distribute/balance the default web cache to the new node.

When it does this, I see the following error message in the log on the first node, and the 2nd node fails to start:

```<code>13:45:48,487 ERROR [org.infinispan.remoting.rpc.RpcManagerImpl] (transport-thread--p18-t8) ISPN000073: Unexpected error while replicating: org.infinispan.commons.marshall.NotSerializableException: org.wildfly.transaction.client.ContextTransactionManager
Caused by: an exception which occurred:
    in field com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.transactionManager
    in object com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired@73962bdb
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.instance
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in field java.util.Collections$SynchronizedCollection.c
    in object java.util.Collections$SynchronizedList@333ebcd4
    in field org.jboss.weld.contexts.CreationalContextImpl.dependentInstances
    in object org.jboss.weld.contexts.CreationalContextImpl@4dc7055b
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.creationalContext
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37

13:45:50,718 ERROR [org.infinispan.statetransfer.OutboundTransferTask] (transport-thread--p18-t8) Failed to send entries to node node2: org.wildfly.transaction.client.ContextTransactionManager: org.infinispan.commons.marshall.NotSerializableException: org.wildfly.transaction.client.ContextTransactionManager
Caused by: an exception which occurred:
    in field com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.transactionManager
    in object com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired@73962bdb
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.instance
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in field java.util.Collections$SynchronizedCollection.c
    in object java.util.Collections$SynchronizedList@333ebcd4
    in field org.jboss.weld.contexts.CreationalContextImpl.dependentInstances
    in object org.jboss.weld.contexts.CreationalContextImpl@4dc7055b
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.creationalContext
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
</code>```

Some other things to note:

It fails when starting up one of my WARs that is distributed inside an EAR, but not the other 2 WARs that are also deployed in the EAR

My web.xml is marked as <distributable/> for all 3 WARs

My other caches seem to replicate just fine

I can't seem to figure out where the ContextTransactionManager is being used, or why it my be serialized to a session cache. I'm assuming it might be in my code somewhere, but I can't figure out where to even start looking. Any help would be appreciated!

Update (05/28/2019): Here are a couple screenshots from the management console showing 2 sessions that get created at startup (we use JSP in our web app, and we have a startup service that runs to pre-compile all of the JSP files):

答:
Update: This ended up being a really simple and somewhat stupid problem in the first place. We had marked a method in the LoggedInUser class with the @javax.transaction.Transactional annotation, which was not necessary in the first place, but was causing the serialization issue.

Just wanted to post an update in case anyone else ran across something similar.

Body:
I am trying to run my application on 2 Wildfly 16 nodes running in Standalone mode using the standalone-full-ha.xml configuration. When the 2nd node starts up, the first attempts to distribute/balance the default web cache to the new node.

When it does this, I see the following error message in the log on the first node, and the 2nd node fails to start:

13:45:48,487 ERROR [org.infinispan.remoting.rpc.RpcManagerImpl] (transport-thread--p18-t8) ISPN000073: Unexpected error while replicating: org.infinispan.commons.marshall.NotSerializableException: org.wildfly.transaction.client.ContextTransactionManager
Caused by: an exception which occurred:
    in field com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.transactionManager
    in object com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired@73962bdb
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.instance
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in field java.util.Collections$SynchronizedCollection.c
    in object java.util.Collections$SynchronizedList@333ebcd4
    in field org.jboss.weld.contexts.CreationalContextImpl.dependentInstances
    in object org.jboss.weld.contexts.CreationalContextImpl@4dc7055b
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.creationalContext
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37

13:45:50,718 ERROR [org.infinispan.statetransfer.OutboundTransferTask] (transport-thread--p18-t8) Failed to send entries to node node2: org.wildfly.transaction.client.ContextTransactionManager: org.infinispan.commons.marshall.NotSerializableException: org.wildfly.transaction.client.ContextTransactionManager
Caused by: an exception which occurred:
    in field com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorBase.transactionManager
    in object com.arjuna.ats.jta.cdi.transactional.TransactionalInterceptorRequired@73962bdb
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.instance
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@333ebcb5
    in field java.util.Collections$SynchronizedCollection.c
    in object java.util.Collections$SynchronizedList@333ebcd4
    in field org.jboss.weld.contexts.CreationalContextImpl.dependentInstances
    in object org.jboss.weld.contexts.CreationalContextImpl@4dc7055b
    in field org.jboss.weld.contexts.SerializableContextualInstanceImpl.creationalContext
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37
    in object org.jboss.weld.contexts.SerializableContextualInstanceImpl@57504e37

Some other things to note:

It fails when starting up one of my WARs that is distributed inside an EAR, but not the other 2 WARs that are also deployed in the EAR

My web.xml is marked as <distributable/> for all 3 WARs

My other caches seem to replicate just fine

I can't seem to figure out where the ContextTransactionManager is being used, or why it my be serialized to a session cache. I'm assuming it might be in my code somewhere, but I can't figure out where to even start looking. Any help would be appreciated!

Update (05/28/2019): Here are a couple screenshots from the management console showing 2 sessions that get created at startup (we use JSP in our web app, and we have a startup service that runs to pre-compile all of the JSP files):


问:
Why jQuery puts equals in whitespaces when I try to append some String
I have this string:

```<code>var strAppend ="<button id='btnUEN' class='k-primary' onclick='getCategoryByUEN(" + stronClick +  ")'>"+ name +" </button>"
$("#nav_clacom_1474").append(strAppend);
</code>```

I did put a console.log to strAppend and I have this value:

```<code><button id='btnUEN' class='k-primary' onclick='getCategoriaByUEN('1','TEST AND TEST')'>TEST AND TEST</button>
</code>```

But the HTML code don't look well... show this:

```<code><button id='btnUEN' class='k-primary' onclick='getCategoriaByUEN('1','TEST'="" AND="" TEST')'="">TEST AND TEST</button>
</code>```

Why and how I can resolve this...

答:
Welcome to escaping strings. What's happening is that you have a delimiters causing your HTML to behave differently than you expected.

In this case, your single quotes inside the onclick attribute are causing the onclick's single quotes surrounding the attribute to prematurely end, because they are behaving as delimiters. To prevent this from happening, you have to escape those delimiters by adding a backslash.

Here's a workaround to replace all ' with \' inside your variable.

```<code>var stronClick_escaped = stronClick.replace(/'/g, "\\'")
var strAppend ="<button id='btnUEN' class='k-primary' onclick='getCategoryByUEN(" + stronClick_escaped +  ")'>"+ name +" </button>"
$("#nav_clacom_1474").append(strAppend);
</code>```

The reason I replaced it with "\\'" is because \ is an escape character! So you have to escape it, too.

Edit: The quotation marks that cause your strings to prematurely end are delimiters, and the characters inside the string that are escaped are escape characters.

Body:
I have this string:

var strAppend ="<button id='btnUEN' class='k-primary' onclick='getCategoryByUEN(" + stronClick +  ")'>"+ name +" </button>"
$("#nav_clacom_1474").append(strAppend);

I did put a console.log to strAppend and I have this value:

<button id='btnUEN' class='k-primary' onclick='getCategoriaByUEN('1','TEST AND TEST')'>TEST AND TEST</button>

But the HTML code don't look well... show this:

<button id='btnUEN' class='k-primary' onclick='getCategoriaByUEN('1','TEST'="" AND="" TEST')'="">TEST AND TEST</button>

Why and how I can resolve this...

Body:
Welcome to escaping strings. What's happening is that you have a delimiters causing your HTML to behave differently than you expected.

In this case, your single quotes inside the onclick attribute are causing the onclick's single quotes surrounding the attribute to prematurely end, because they are behaving as delimiters. To prevent this from happening, you have to escape those delimiters by adding a backslash.

Here's a workaround to replace all ' with \' inside your variable.

var stronClick_escaped = stronClick.replace(/'/g, "\\'")
var strAppend ="<button id='btnUEN' class='k-primary' onclick='getCategoryByUEN(" + stronClick_escaped +  ")'>"+ name +" </button>"
$("#nav_clacom_1474").append(strAppend);

The reason I replaced it with "\\'" is because \ is an escape character! So you have to escape it, too.

Edit: The quotation marks that cause your strings to prematurely end are delimiters, and the characters inside the string that are escaped are escape characters.


问:
How does Spark load ordered parquet partitioned files with order?
After I sorted all the entries and use write() function to S3, I want to re-load the data with exactly the same order and same partitions.

I tried to use read() and load() function but none of these work. Do we have a way to load the partitioned parquet files with same order and partitions?

答: if read() and load() did not help i would suggest to read file names from S3 and order it in fashion you need and then read back those files in the order in the spark. You can always build up your DataFrame (if you are and keep adding data to it from these partitions that you just read)</p>


问:
PowerShell: Run batch file and write output to text file
I have a batch file in my PowerShell script that I want to run and write its output to a text file. I tried the following:

```<code>Start-Process C:\path\file.bat | Out-File C:\path\output.txt
</code>```

I also tried using Tee-Object and Write-Output in place of Out-File, but nothing is being written to the text file.

答:
You just needed a couple more parameters:

```<code>Start-Process -FilePath 'C:\Path\File.bat' -RedirectStandardOutput 'C:\Path\Output.txt' -Wait -WindowStyle Hidden
</code>```

-RedirectStandardOutput to send output to your text file, -Wait to wait for the batch file to complete and -WindowStyle Hidden to hide the window used for the batch file.

Body:
I have a batch file in my PowerShell script that I want to run and write its output to a text file. I tried the following:

Start-Process C:\path\file.bat | Out-File C:\path\output.txt

I also tried using Tee-Object and Write-Output in place of Out-File, but nothing is being written to the text file.

Body:
You just needed a couple more parameters:

Start-Process -FilePath 'C:\Path\File.bat' -RedirectStandardOutput 'C:\Path\Output.txt' -Wait -WindowStyle Hidden

-RedirectStandardOutput to send output to your text file, -Wait to wait for the batch file to complete and -WindowStyle Hidden to hide the window used for the batch file.


问:
Subversion - problem creating a new repository
I have recently taken over a linux box running subversion.

The folder where the the repos look like they are installed is in: /home/svn

In this folder I see a folder named web_projects and in that folder I see conf dev db etc etc

I am trying to add a new repository to this server, but I'm getting the following error:

`svnadmin: '/home/svn/web_projects/my_project' is a subdirectoy of an existing repository rooted at '/home/svn/web_projects'

Does anyone know why I can't seem to add a new repository?

答:
the problem is that you used the "top level" directory as a svn repository, so now you can't have two repositories because one is nested in another project's directory.

Structure your /home/svn area like so /home/svn/project1 /home/svn/project2 /home/svn/project3 ...  with multiple svnadmin create commands like

```<code>svnadmin create /home/svn/projectN
</code>```

Since you can't nest one repository into another, to start you will have to move your svn files from /home/svn to /home/svn/project1

Body:
the problem is that you used the "top level" directory as a svn repository, so now you can't have two repositories because one is nested in another project's directory.

Structure your /home/svn area like so /home/svn/project1 /home/svn/project2 /home/svn/project3 ...  with multiple svnadmin create commands like

svnadmin create /home/svn/projectN

Since you can't nest one repository into another, to start you will have to move your svn files from /home/svn to /home/svn/project1


问:
base_url in CakePHP
In most web applications we need global var base_url. In cakephp to get base_url currently i put the following code on beforeRender method in app_controller.php

```<code>function beforeRender(){
    $this->set('base_url', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));
}
</code>```

Is there any alternative? Means is there any global variable available to get the base url rather than this?

答: You can use FULL_BASE_URL constant.

ContentLicense: CC BY-SA 2.5

Title: base_url in CakePHP

Body:
In most web applications we need global var base_url. In cakephp to get base_url currently i put the following code on beforeRender method in app_controller.php

function beforeRender(){
    $this->set('base_url', 'http://'.$_SERVER['SERVER_NAME'].Router::url('/'));
}

Is there any alternative? Means is there any global variable available to get the base url rather than this?

Body: You can use FULL_BASE_URL constant.


问:
IIf(Instr) in SSRS reporting error - Switch cases in SSRS Expression
My report looks as below:

And my SSRS form of the report is as below:

I want only one line of total and don't want the total percentage line to show up.For this, I would like to add a case/switch statement in the expression:

```<code>If Column_grouping contains "percent" then show "%value"
If column_grouping does not contain "percent" then show "total"
</code>```

And my SSRS expression is as below:

```<code>=Switch
(Fields!Column_Grouping.Value like "*percent*", Fields!Total_value_Count_pct.Value,
Fields!Column_Grouping.Value not like "%percent%",Sum(Fields!Total_value_Count.Value))
</code>```

Evidently this expression is wrong. Any help to fix this?!

答:
I'm thinking you could simplify the expression a bit and just use an IIF statement.  The SWITCH is best used with more than 2 expressions to evaluate.  Additionally, you should be able to use InStr or Contains as you indicated in the title of the question.  I would think the following expression should work.

```<code>= IIF(Fields!Column_Grouping.Value.Contains("percent"),
      Fields!Total_value_Count_pct.Value, Fields!Total_value_Count.Value)
</code>```

Refer to this answer for a more detailed explanation on how InStr works.  Contains will simply check if the string occurs in the field you are using it on.

Body:
My report looks as below:

And my SSRS form of the report is as below:

I want only one line of total and don't want the total percentage line to show up.For this, I would like to add a case/switch statement in the expression:

If Column_grouping contains "percent" then show "%value"
If column_grouping does not contain "percent" then show "total"

And my SSRS expression is as below:

=Switch
(Fields!Column_Grouping.Value like "*percent*", Fields!Total_value_Count_pct.Value,
Fields!Column_Grouping.Value not like "%percent%",Sum(Fields!Total_value_Count.Value))

Evidently this expression is wrong. Any help to fix this?!

Body:
I'm thinking you could simplify the expression a bit and just use an IIF statement.  The SWITCH is best used with more than 2 expressions to evaluate.  Additionally, you should be able to use InStr or Contains as you indicated in the title of the question.  I would think the following expression should work.

= IIF(Fields!Column_Grouping.Value.Contains("percent"),
      Fields!Total_value_Count_pct.Value, Fields!Total_value_Count.Value)

Refer to this answer for a more detailed explanation on how InStr works.  Contains will simply check if the string occurs in the field you are using it on.


问:
CS0103 The name 'Request' does not exist in the current context
I am trying to Implement this in an asp.netcoreapp2.2 mvc project but this is giving me error . I Downloaded their code and it complies fine. Here Request is HttpRequestBase WebpageRenderingPage which isn't seems to be available in my Project

I tried to add System.web.dll manually but that doesn't work.
Used Headers in PostDetailController.cs

```<code>using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MovieBlend.Models;
using MovieBlend.Services;
using PusherServer;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using System.Web;
</code>```

Index.cshtml

```<code>@model MovieData
@{
    ViewData["Title"] = Model.Title;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.4/vue.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.16.2/axios.min.js"></script>
<script src="https://js.pusher.com/4.0/pusher.min.js"></script>
<script>
    var pusher
</script>
@using Humanizer
@using StmlParsing
<style>
    .user_name {
        font-size: 14px;
        font-weight: bold;
    }

    .comments-list .media {
        border-bottom: 1px dotted #ccc;
    }

    h1 {
        color: snow;
        text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    }

    h3 {
        text-align: center;
        color: snow;
        text-shadow: -1px 0 black, 0 1px black, 1px 0 black, 0 -1px black;
    }

    .poster_name {
        text-align: left;
        color: darkred;
        text-decoration: underline
    }

    section {
        width: 100%;
        float: left;
    }

    .banner-section {
        background-image: url("https://static.pexels.com/photos/373912/pexels-photo-373912.jpeg");
        background-size: cover;
        height: 380px;
        left: 0;
        position: absolute;
        top: inherit;
        background-position: 0;
    }

    .post-title-block {
        padding: 100px 0;
    }

        .post-title-block h1 {
            color: #fff;
            font-size: 85px;
            font-weight: bold;
            text-transform: capitalize;
        }

        .post-title-block li {
            font-size: 20px;
            color: #fff;
        }

    .image-block {
        float: left;
        width: 100%;
        margin-bottom: 10px;
    }

    .footer-link {
        float: left;
        width: 100%;
        background: #222222;
        text-align: center;
        padding: 30px;
    }

        .footer-link a {
            color: #A9FD00;
            font-size: 18px;
            text-transform: uppercase;
        }

    .div-post {
        margin-top: 45px;
    }
</style>
<div id="app">
    <section class="banner-section"></section>
    <section class="post-content-section">
        <div class="container">
            <div class="row">
                <div class="col-lg-12 col-md-12 col-sm-12 post-title-block">
                    <h1 class="text-center">@Model.Title</h1>
                    <h3> @Model.Release | @Model.Language | @Model.Genre</h3>
                </div>
                <div class="col-lg-9 col-md-9 col-sm-12 div-post">
                    <p>
                        <h6 class="poster_name">Posted By @Model.User_name</h6>
                        <h7 class="poster_name">Posted @Model.Postedate.Humanize()</h7>
                        <br />@Html.Raw(@StmlParser.Parse(Model.Description))
                    </p>
                </div>
            </div>
        </div>
    </section>
    <div class="container">
        <br />
        <p>You Comment</p>
        <form onsubmit="return false;">
            <input type="text" id="Name" placeholder="Your Name" v-model="comment.Name" class="form-control" />
            <textarea rows="3" placeholder="Your Comment" id="Body" v-model="comment.Body" class="form-control"></textarea>
            <button class="btn btn-success" v-on:click="submit_comment()">save</button>
        </form>
    </div>
    <div class="container">
        <div class="row">
            <div class="page-header">
                <h3><small class="pull-right">{{comments.length}}</small>Comments</h3>
            </div>
            <div class="comments-list">
                <div class="media-body">
                    <h4 class="media-heading user_name">{{com.name}}</h4>
                    {{com.body}}
                </div>
            </div>
        </div>
    </div>
</div>
<script>
    var pusher = new Pusher('7ba0ddfcfbfe565ee8ee', {
        cluster: 'ap2'
    });
    var my_channel = pusher.subscribe('asp_channel');
    var app = new Vue({
        el: '#app',
        data: {
            comments: [],
            comment: {
                Name: '',
                Body: '',
                BlogPostID: @Model.Id
            }
        },
        created: function() {
            this.get_comments();
            this.listen();
        },
        methods: {

            get_comments: function() {
                axios.get('@Url.Action("Comments", "PostDetail", new { id = @Model.Id }, protocol: Request.Url.Scheme)')
                    .then((response) => {

                        this.comments = response.data;

                    });

            },
            listen: function() {
                my_channel.bind("asp_event", (data) => {
                    if (data.BlogPostID == this.comment.BlogPostID) {
                        this.comments.push(data);
                    }

                })
            },
            submit_comment: function() {
                axios.post('@Url.Action("AddComment", "PostDetail", new {}, protocol: Request.Url.Scheme)', this.comment)
                    .then((response) => {
                        this.comment.Name = '';
                        this.comment.Body = '';
                        alert("Comment Submitted");

                    });
            }
        }
    });
</script>
</code>```

Its giving me error in this lines

```<code> axios.post('@Url.Action("AddComment", "PostDetail", new {}, protocol: Request.Url.Scheme)', this.comment)
</code>```

and

```<code> axios.get('@Url.Action("Comments", "PostDetail", new { id = @Model.Id }, protocol: Request.Url.Scheme)')
</code>```

saying Request isn't available

csporj file

```<code><Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <UserSecretsId>aspnet-MovieBlend-2E001261-E25D-4A77-9170-29F16D765657</UserSecretsId>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="CoreCompat.System.Drawing" Version="1.0.0-beta006" />
    <PackageReference Include="Humanizer" Version="2.6.2" />
    <PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    <PackageReference Include="PusherServer" Version="4.1.0" />
    <PackageReference Include="StmlParser" Version="1.0.2" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="System.Web">
      <HintPath>E:\Downloads\Compressed\System.Web\System.Web.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Abstractions">
      <HintPath>E:\Downloads\Compressed\System.Web.Abstractions\System.Web.Abstractions.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

</code>```

How to solve this problem?

答:
You need to add the @page directive at the top of the page to indicate that it is a razor page. The top of the page should look like:

```<code>@page
@model MovieData
@{
    ViewData["Title"] = Model.Title;
}
</code>```

Then you should be able to access the Request property. I do something similar (but just calling Request.Scheme):

```<code>var _url = '@Url.Action("UploadFile", "Data", new { projectId = Model.ID }, Request.Scheme)';
</code>```

Body:
I am trying to Implement this in an asp.netcoreapp2.2 mvc project but this is giving me error . I Downloaded their code and it complies fine. Here Request is HttpRequestBase WebpageRenderingPage which isn't seems to be available in my Project

I tried to add System.web.dll manually but that doesn't work.
Used Headers in PostDetailController.cs

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using MovieBlend.Models;
using MovieBlend.Services;
using PusherServer;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Authorization;
using System.Web;

Index.cshtml

@model MovieData
@{
    ViewData["Title"] = Model.Title;
}

@using Humanizer
@using StmlParsing

@Model.Title

 @Model.Release | @Model.Language | @Model.Genre

Posted By @Model.User_name

                        <h7 class="poster_name">Posted @Model.Postedate.Humanize()</h7>

@Html.Raw(@StmlParser.Parse(Model.Description))

You Comment

        <form onsubmit="return false;">
            <input type="text" id="Name" placeholder="Your Name" v-model="comment.Name" class="form-control" />
            <textarea rows="3" placeholder="Your Comment" id="Body" v-model="comment.Body" class="form-control"></textarea>
            <button class="btn btn-success" v-on:click="submit_comment()">save</button>
        </form>

{{comments.length}}Comments

{{com.name}}

                    {{com.body}}

Its giving me error in this lines

 axios.post('@Url.Action("AddComment", "PostDetail", new {}, protocol: Request.Url.Scheme)', this.comment)

and

 axios.get('@Url.Action("Comments", "PostDetail", new { id = @Model.Id }, protocol: Request.Url.Scheme)')

saying Request isn't available

csporj file

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <UserSecretsId>aspnet-MovieBlend-2E001261-E25D-4A77-9170-29F16D765657</UserSecretsId>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
    <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="CoreCompat.System.Drawing" Version="1.0.0-beta006" />
    <PackageReference Include="Humanizer" Version="2.6.2" />
    <PackageReference Include="Microsoft.AspNet.Mvc" Version="5.2.7" />
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.2.0" PrivateAssets="All" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="2.2.3" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
    <PackageReference Include="PusherServer" Version="4.1.0" />
    <PackageReference Include="StmlParser" Version="1.0.2" />
  </ItemGroup>

  <ItemGroup>
    <Reference Include="System.Web">
      <HintPath>E:\Downloads\Compressed\System.Web\System.Web.dll</HintPath>
    </Reference>
    <Reference Include="System.Web.Abstractions">
      <HintPath>E:\Downloads\Compressed\System.Web.Abstractions\System.Web.Abstractions.dll</HintPath>
    </Reference>
  </ItemGroup>

</Project>

How to solve this problem?

Body:
You need to add the @page directive at the top of the page to indicate that it is a razor page. The top of the page should look like:

@page
@model MovieData
@{
    ViewData["Title"] = Model.Title;
}

Then you should be able to access the Request property. I do something similar (but just calling Request.Scheme):

var _url = '@Url.Action("UploadFile", "Data", new { projectId = Model.ID }, Request.Scheme)';


问:
shuffle array in Go
I tried to translate the following Python code to Go

```<code>import random

list = [i for i in range(1, 25)]
random.shuffle(list)
print(list)
</code>```

but found my Go version lengthy and awkward because there is no shuffle function and I had to implement interfaces and convert types.

What would be an idiomatic Go version of my code?

答:
Use Shuffle() from the math/rand library.

Here's an example:

```<code>package main

import (
    "fmt"
    "math/rand"
    "strings"
)

func main() {
    words := strings.Fields("ink runs from the corners of my mouth")
    rand.Shuffle(len(words), func(i, j int) {
        words[i], words[j] = words[j], words[i]
    })
    fmt.Println(words)
}
</code>```

Since it comes from the math/rand library it needs to be seeded. See here for more details.

Title: shuffle array in Go

Body:
I tried to translate the following Python code to Go

import random

list = [i for i in range(1, 25)]
random.shuffle(list)
print(list)

but found my Go version lengthy and awkward because there is no shuffle function and I had to implement interfaces and convert types.

What would be an idiomatic Go version of my code?

Body:
Use Shuffle() from the math/rand library.

Here's an example:

package main

import (
    "fmt"
    "math/rand"
    "strings"
)

func main() {
    words := strings.Fields("ink runs from the corners of my mouth")
    rand.Shuffle(len(words), func(i, j int) {
        words[i], words[j] = words[j], words[i]
    })
    fmt.Println(words)
}

Since it comes from the math/rand library it needs to be seeded. See here for more details.


问:
How can I generate a requirements.txt file for a package not available on my development platform?
I'm trying to generate requirements/dev.txt and prod.txt files for my python project. I'm using pip-compile-multi to generate them from base.in dev.in and prod.in files. Everything works great until I add tensorflow-gpu==2.0.0a0 into the prod.in file. I get this error when I do: RuntimeError: Failed to pip-compile requirements/prod.in.

I believe this is because tensorflow-gpu is only available on Linux, and my dev machine is a Mac. (If I run pip install tensorflow-gpu==2.0.0a0 I am told there is no distribution for my platform.) Is there a way I can generate a requirements.txt file for pip for a package that is not available on my platform? To be clear, my goal is to generate a requirements.txt file using something like pip-compile-multi (because that will version dependencies) that will only install on Linux, but I want to be able to actually generate the file on any platform.

答:
Use environment markers from PEP 496:</p>

```<code>tensorflow-gpu==2.0.0a0; sys_platform!='darwin'
</code>```

Body:
Use environment markers from PEP 496:

tensorflow-gpu==2.0.0a0; sys_platform!='darwin'


问:
How to convert a number read from a file from str to int?
I use bash, I have to read a file that contains many lines

Each line is composed by a single number. Then, for each line (number) I have to check if value > 80.

And here's my problem, no matter what I try, I always get:

```<code>>integer expression expected
</code>```

after the if condition. That's because the variable I use to put the value of the line is a string.

Here's my original file

```<code>[root@michelep_centos2 ~]# cat temp1

0

0

0

98

0

0

79

0

81
</code>```

In the bash script I have

```<code>##!/bin/bash

file=/root/temp1

while IFS= read -r line

do

        if [ 'expr $line /1' -gt 80 ]

        then echo "hit>80"

        fi

done <"$file"
</code>```

And here expr returns error as $line is a string. I have tried using another variable

```<code>val=$(($line + 0))

if [ $val -gt 80 ]
</code>```

Here the if condition returns "integer expression expected"

I have used also echo

```<code>val=$(echo "$((line /1))")

if [ $val -gt 80 ]
</code>```

I get

syntax error: invalid arithmetic operator (error token is ...

from echo command and of course again the if condition returns

integer expression expected

答:
Try this Shellcheck-clean pure Bash code:

```<code>#! /bin/bash -p

file=/root/temp1

while read -r line ; do
    (( line > 80 )) && echo "$line > 80"
done <"$file"
</code>```

The problem with the code in the question is that it doesn't handle empty lines.  This code does handle empty lines because variables containing the empty string are treated as if they contained zero in arithmetic expressions (((...))).

Body:
I use bash, I have to read a file that contains many lines

Each line is composed by a single number. Then, for each line (number) I have to check if value > 80.

And here's my problem, no matter what I try, I always get:

>integer expression expected

after the if condition. That's because the variable I use to put the value of the line is a string.

Here's my original file

[root@michelep_centos2 ~]# cat temp1

0

0

0

98

0

0

79

0

81

In the bash script I have

##!/bin/bash

file=/root/temp1

while IFS= read -r line

do

        if [ 'expr $line /1' -gt 80 ]

        then echo "hit>80"

        fi

done <"$file"

And here expr returns error as $line is a string. I have tried using another variable

val=$(($line + 0))

if [ $val -gt 80 ]

Here the if condition returns "integer expression expected"

I have used also echo

val=$(echo "$((line /1))")

if [ $val -gt 80 ]

I get

syntax error: invalid arithmetic operator (error token is ...

from echo command and of course again the if condition returns

integer expression expected

Body:
Try this Shellcheck-clean pure Bash code:

#! /bin/bash -p

file=/root/temp1

while read -r line ; do
    (( line > 80 )) && echo "$line > 80"
done <"$file"

The problem with the code in the question is that it doesn't handle empty lines.  This code does handle empty lines because variables containing the empty string are treated as if they contained zero in arithmetic expressions (((...))).


问:
Is there a Collection that hold implementations to an abstract generic class with multiple types
I have this abstract class, and implementations, which has an Input type and Output type:

```<code>public abstract class Action<TInput, TOutput>
{
    public Action() {}

    public virtual TOutput Execute(TInput input)
    {
        throw new NotImplementedException();
    }
}

public class Foo<int, string> : Action<int, string>
{
    public override string Execute(int i)
    {
        ...
    }
}

public class Bar<string, int> : Action<string, int>
{
    public override int Execute(string s)
    {
        ...
    }
}
</code>```

How can I hold these imp. in a Collection and loop through them?

like:

```<code>actions.Add(new Foo());
actions.Add(new Bar());

object obj;

foreach(var item in actions)
    obj = item.Execute(obj);
</code>```

答:
You can't quite do what you're trying to do.

```<code>actions.Add(new Foo()); // expects and returns string
actions.Add(new Bar()); // expects and returns int

object obj;

foreach(var item in actions)
    obj = item.Execute(obj);
</code>```

If Foo expects string and Bar expects int (and technically any implementation could expect any other type) then what value can you pass to each item in the collection that will work with all of them? Also, what would you do with the return values, since each of them could be of a different type?

You can solve the problem of getting it compile by declaring the inputs and outputs as object, although that would defeat the purpose of making it generic. You would just replace your base class with this...

```<code>public abstract class Action
{
    public abstract object Execute(object input);
}
</code>```

...but that wouldn't be a very useful class.

But the real problem is that methods that receive and return object aren't usually very useful either. The type system allows us to know the types of arguments, return values, variables, etc. That's part of what indicates the intent of our code. For example, we write a method like this:

```<code>bool IsAnagram(string input)
</code>```

because we want to know if (bool) an input (string) is an anagram. Knowing that it does that is our reason for calling it. If we don't want to know if a string is an anagram, we don't call this method because we don't need it.

But what if we have a method like this:

```<code>object GetResult(object input)
</code>```

It has no reason to exist. Why would we call it? If we have a value of some type and we want to do something with it and get some result, we would write a method that does that.

Similarly, if we get back object from the method, what do we do with it? We don't know what it is. It's a bit like going to the store to buy something, except we have nothing in mind that we want to buy, and they hand us a package and we don't know what's inside. We couldn't have any plans for what we intended to do when we got it, since we didn't know what we would get. So we just wouldn't do it.

It only makes sense to use object in specific scenarios where we don't care what the type is. Those scenarios are less common because in order for our application to do anything it almost always needs to be doing something with specified types - creating them, getting them from somewhere, passing them to other methods, and getting more expected types in return.

If you just want a collection of things to do, and they all take different arguments and return different types, then you have to declare the collection according to its least common denominator, which is just Action with no arguments and no return values.

You could do this:

```<code>var actions = new List<Action>();

actions.Add(() =>
{
    var foo = new Foo();
    foo.Execute(5);
});

actions.Add(() =>
{
    var bar = new Bar();
    bar.Execute("Hello!");
});

foreach (var action in actions)
{
    action.Invoke();
}
</code>```

...and there may be cases where a collection of Action is useful. But in most cases there's no reason to take a bunch of unrelated actions that do different things and put them in a collection with each other.

Body:
I have this abstract class, and implementations, which has an Input type and Output type:

public abstract class Action<TInput, TOutput>
{
    public Action() {}

    public virtual TOutput Execute(TInput input)
    {
        throw new NotImplementedException();
    }
}

public class Foo<int, string> : Action<int, string>
{
    public override string Execute(int i)
    {
        ...
    }
}

public class Bar<string, int> : Action<string, int>
{
    public override int Execute(string s)
    {
        ...
    }
}

How can I hold these imp. in a Collection and loop through them?

like:

actions.Add(new Foo());
actions.Add(new Bar());

object obj;

foreach(var item in actions)
    obj = item.Execute(obj);

Body:
You can't quite do what you're trying to do.

actions.Add(new Foo()); // expects and returns string
actions.Add(new Bar()); // expects and returns int

object obj;

foreach(var item in actions)
    obj = item.Execute(obj);

If Foo expects string and Bar expects int (and technically any implementation could expect any other type) then what value can you pass to each item in the collection that will work with all of them? Also, what would you do with the return values, since each of them could be of a different type?

You can solve the problem of getting it compile by declaring the inputs and outputs as object, although that would defeat the purpose of making it generic. You would just replace your base class with this...

public abstract class Action
{
    public abstract object Execute(object input);
}

...but that wouldn't be a very useful class.

But the real problem is that methods that receive and return object aren't usually very useful either. The type system allows us to know the types of arguments, return values, variables, etc. That's part of what indicates the intent of our code. For example, we write a method like this:

bool IsAnagram(string input)

because we want to know if (bool) an input (string) is an anagram. Knowing that it does that is our reason for calling it. If we don't want to know if a string is an anagram, we don't call this method because we don't need it.

But what if we have a method like this:

object GetResult(object input)

It has no reason to exist. Why would we call it? If we have a value of some type and we want to do something with it and get some result, we would write a method that does that.

Similarly, if we get back object from the method, what do we do with it? We don't know what it is. It's a bit like going to the store to buy something, except we have nothing in mind that we want to buy, and they hand us a package and we don't know what's inside. We couldn't have any plans for what we intended to do when we got it, since we didn't know what we would get. So we just wouldn't do it.

It only makes sense to use object in specific scenarios where we don't care what the type is. Those scenarios are less common because in order for our application to do anything it almost always needs to be doing something with specified types - creating them, getting them from somewhere, passing them to other methods, and getting more expected types in return.

If you just want a collection of things to do, and they all take different arguments and return different types, then you have to declare the collection according to its least common denominator, which is just Action with no arguments and no return values.

You could do this:

var actions = new List<Action>();

actions.Add(() =>
{
    var foo = new Foo();
    foo.Execute(5);
});

actions.Add(() =>
{
    var bar = new Bar();
    bar.Execute("Hello!");
});

foreach (var action in actions)
{
    action.Invoke();
}

...and there may be cases where a collection of Action is useful. But in most cases there's no reason to take a bunch of unrelated actions that do different things and put them in a collection with each other.


问:
Modeling KDD Cup 99 dataset using Neural Network
I have task to modeling KDD Cup 99 Dataset using Neural Network. I am using Jupyter Notebook to compile it each functions.

Here is the code:

```<code>import pandas

#importing the dataset
dataset = pandas.read_csv('kddcup.data_10_percent_corrected')

#change Multi-class to binary-class
dataset['normal.'] = dataset['normal.'].replace(['back.', 'buffer_overflow.', 'ftp_write.', 'guess_passwd.', 'imap.', 'ipsweep.', 'land.', 'loadmodule.', 'multihop.', 'neptune.', 'nmap.', 'perl.', 'phf.', 'pod.', 'portsweep.', 'rootkit.', 'satan.', 'smurf.', 'spy.', 'teardrop.', 'warezclient.', 'warezmaster.'], 'attack')

x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 41].values

#encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x_1 = LabelEncoder()
labelencoder_x_2 = LabelEncoder()
labelencoder_x_3 = LabelEncoder()
x[:, 1] = labelencoder_x_1.fit_transform(x[:, 1])
x[:, 2] = labelencoder_x_2.fit_transform(x[:, 2])
x[:, 3] = labelencoder_x_3.fit_transform(x[:, 3])
onehotencoder_1 = OneHotEncoder(categorical_features = [1])
x = onehotencoder_1.fit_transform(x).toarray()
onehotencoder_2 = OneHotEncoder(categorical_features = [4])
x = onehotencoder_2.fit_transform(x).toarray()
onehotencoder_3 = OneHotEncoder(categorical_features = [70])
x = onehotencoder_3.fit_transform(x).toarray()
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)

#splitting the dataset into the training set and test set
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)

#feature scaling
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)

# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense

# Initialising the ANN
classifier = Sequential()

# Adding the input layer and the first hidden layer
classifier.add(Dense(output_dim = 60, init = 'uniform', activation = 'relu', input_dim = 118))

#Adding a second hidden layer
classifier.add(Dense(output_dim = 60, init = 'uniform', activation = 'relu'))

#Adding a third hidden layer
classifier.add(Dense(output_dim = 60, init = 'uniform', activation = 'relu'))

# Adding the output layer
classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))

# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Fitting the ANN to the Training set
#keras.utils.to_categorical(y, num_classes=None, dtype='float32')
from keras.utils import to_categorical
classifier.fit(to_categorical(x_train), to_categorical(y_train), verbose=1, batch_size = 10, nb_epoch = 20)

# Predicting the Test set results
y_pred = classifier.predict(x_test)
y_pred = (y_pred > 0.5)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

#the performance of the classification model
print("the Accuracy is: "+ str((cm[0,0]+cm[1,1])/(cm[0,0]+cm[0,1]+cm[1,0]+cm[1,1])))
recall = cm[1,1]/(cm[0,1]+cm[1,1])
print("Recall is : "+ str(recall))
print("False Positive rate: "+ str(cm[1,0]/(cm[0,0]+cm[1,0])))
precision = cm[1,1]/(cm[1,0]+cm[1,1])
print("Precision is: "+ str(precision))
print("F-measure is: "+ str(2*((precision*recall)/(precision+recall))))
from math import log
print("Entropy is: "+ str(-precision*log(precision)))

</code>```

But when I run the code, I found this error

答:
Try using the np.argmax before training your classifier:</p>

```<code>conv = to_categorical(y_train)
y_train1 = np.argmax(conv,axis=1)
classifier.fit(x_train, y_train1, verbose=1, batch_size = 10, nb_epoch = 20)
</code>```

Body:
I have task to modeling KDD Cup 99 Dataset using Neural Network. I am using Jupyter Notebook to compile it each functions.

Here is the code:

import pandas

#importing the dataset
dataset = pandas.read_csv('kddcup.data_10_percent_corrected')

#change Multi-class to binary-class
dataset['normal.'] = dataset['normal.'].replace(['back.', 'buffer_overflow.', 'ftp_write.', 'guess_passwd.', 'imap.', 'ipsweep.', 'land.', 'loadmodule.', 'multihop.', 'neptune.', 'nmap.', 'perl.', 'phf.', 'pod.', 'portsweep.', 'rootkit.', 'satan.', 'smurf.', 'spy.', 'teardrop.', 'warezclient.', 'warezmaster.'], 'attack')

x = dataset.iloc[:, :-1].values
y = dataset.iloc[:, 41].values

#encoding categorical data
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
labelencoder_x_1 = LabelEncoder()
labelencoder_x_2 = LabelEncoder()
labelencoder_x_3 = LabelEncoder()
x[:, 1] = labelencoder_x_1.fit_transform(x[:, 1])
x[:, 2] = labelencoder_x_2.fit_transform(x[:, 2])
x[:, 3] = labelencoder_x_3.fit_transform(x[:, 3])
onehotencoder_1 = OneHotEncoder(categorical_features = [1])
x = onehotencoder_1.fit_transform(x).toarray()
onehotencoder_2 = OneHotEncoder(categorical_features = [4])
x = onehotencoder_2.fit_transform(x).toarray()
onehotencoder_3 = OneHotEncoder(categorical_features = [70])
x = onehotencoder_3.fit_transform(x).toarray()
labelencoder_y = LabelEncoder()
y = labelencoder_y.fit_transform(y)

#splitting the dataset into the training set and test set
from sklearn.cross_validation import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = 0.3, random_state = 0)

#feature scaling
from sklearn.preprocessing import StandardScaler
sc_x = StandardScaler()
x_train = sc_x.fit_transform(x_train)
x_test = sc_x.transform(x_test)

# Importing the Keras libraries and packages
import keras
from keras.models import Sequential
from keras.layers import Dense

# Initialising the ANN
classifier = Sequential()

# Adding the input layer and the first hidden layer
classifier.add(Dense(output_dim = 60, init = 'uniform', activation = 'relu', input_dim = 118))

#Adding a second hidden layer
classifier.add(Dense(output_dim = 60, init = 'uniform', activation = 'relu'))

#Adding a third hidden layer
classifier.add(Dense(output_dim = 60, init = 'uniform', activation = 'relu'))

# Adding the output layer
classifier.add(Dense(output_dim = 1, init = 'uniform', activation = 'sigmoid'))

# Compiling the ANN
classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy'])

# Fitting the ANN to the Training set
#keras.utils.to_categorical(y, num_classes=None, dtype='float32')
from keras.utils import to_categorical
classifier.fit(to_categorical(x_train), to_categorical(y_train), verbose=1, batch_size = 10, nb_epoch = 20)

# Predicting the Test set results
y_pred = classifier.predict(x_test)
y_pred = (y_pred > 0.5)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

#the performance of the classification model
print("the Accuracy is: "+ str((cm[0,0]+cm[1,1])/(cm[0,0]+cm[0,1]+cm[1,0]+cm[1,1])))
recall = cm[1,1]/(cm[0,1]+cm[1,1])
print("Recall is : "+ str(recall))
print("False Positive rate: "+ str(cm[1,0]/(cm[0,0]+cm[1,0])))
precision = cm[1,1]/(cm[1,0]+cm[1,1])
print("Precision is: "+ str(precision))
print("F-measure is: "+ str(2*((precision*recall)/(precision+recall))))
from math import log
print("Entropy is: "+ str(-precision*log(precision)))

But when I run the code, I found this error

Body:
Try using the np.argmax before training your classifier:

conv = to_categorical(y_train)
y_train1 = np.argmax(conv,axis=1)
classifier.fit(x_train, y_train1, verbose=1, batch_size = 10, nb_epoch = 20)