问:
How To Detect that Android Device is connected with USB OTG Or Not programmatically
I am working with custom OTG fingerprint scanner. I want to check that OTG is connected to my Android device or not in a specific android activity. </p>

答:
```<code>public class BootUpReceiver extends BroadcastReceiver {

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    String TAG = "OTG   ";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
//        Log.e("USB", "Device Connected -> " + action);
//Initialising global class to access USB ATTACH and DETACH state
        final GlobalClass globalVariable = (GlobalClass) context.getApplicationContext();

        if (action.equalsIgnoreCase("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {

            UsbDevice device = (UsbDevice) intent
                    .getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if(device != null) {
                int vendorID = device.getVendorId();
                int productID = device.getProductId();
                if(String.valueOf(productID).equalsIgnoreCase(context.getString(R.string.productID/*product id of your specific device*/))&& (String.valueOf(vendorID).equalsIgnoreCase(context.getString(R.string.vendorID/*vendor id of your specific device*/)))){
    //If Product and Vendor Id match then set boolean "true" in global variable
                    globalVariable.setIs_OTG(true);
                }else{
                    globalVariable.setIs_OTG(false);
                }
            }
        } else if (action.equalsIgnoreCase("android.hardware.usb.action.USB_DEVICE_DETACHED")) {
      //When ever device Detach set your global variable to "false"
            globalVariable.setIs_OTG(false);
        }  }
</code>```

From any Activity you can call global variable to check the current USB state:

```<code> final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
                        if (globalVariable.is_OTG()) {
                            //Perform your functionality
                        }
</code>```

GlobalClass:

```<code>public class GlobalClass extends Application {

    private boolean is_OTG = false;

    public boolean is_OTG() {
        return is_OTG;
    }

    public void setIs_OTG(boolean is_OTG) {
        this.is_OTG = is_OTG;
    }

}
</code>```

manifest:

```<code> <application
        android:name="com.GlobalClass"
</code>```

receiver:

```<code> <receiver
            android:name=".BootUpReceiver"
            android:enabled="true" >
          <!--  <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.HOME" />
            </intent-filter>-->

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />

        </receiver>
</code>```

Body:
public class BootUpReceiver extends BroadcastReceiver {

private static final String ACTION_USB_PERMISSION = "com.android.example.USB_PERMISSION";
    String TAG = "OTG   ";

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
//        Log.e("USB", "Device Connected -> " + action);
//Initialising global class to access USB ATTACH and DETACH state
        final GlobalClass globalVariable = (GlobalClass) context.getApplicationContext();

        if (action.equalsIgnoreCase("android.hardware.usb.action.USB_DEVICE_ATTACHED")) {

            UsbDevice device = (UsbDevice) intent
                    .getParcelableExtra(UsbManager.EXTRA_DEVICE);
            if(device != null) {
                int vendorID = device.getVendorId();
                int productID = device.getProductId();
                if(String.valueOf(productID).equalsIgnoreCase(context.getString(R.string.productID/*product id of your specific device*/))&& (String.valueOf(vendorID).equalsIgnoreCase(context.getString(R.string.vendorID/*vendor id of your specific device*/)))){
    //If Product and Vendor Id match then set boolean "true" in global variable
                    globalVariable.setIs_OTG(true);
                }else{
                    globalVariable.setIs_OTG(false);
                }
            }
        } else if (action.equalsIgnoreCase("android.hardware.usb.action.USB_DEVICE_DETACHED")) {
      //When ever device Detach set your global variable to "false"
            globalVariable.setIs_OTG(false);
        }  }

From any Activity you can call global variable to check the current USB state:

 final GlobalClass globalVariable = (GlobalClass) getApplicationContext();
                        if (globalVariable.is_OTG()) {
                            //Perform your functionality
                        }

GlobalClass:

public class GlobalClass extends Application {

    private boolean is_OTG = false;

    public boolean is_OTG() {
        return is_OTG;
    }

    public void setIs_OTG(boolean is_OTG) {
        this.is_OTG = is_OTG;
    }

}

manifest:

 <application
        android:name="com.GlobalClass"

receiver:

 <receiver
            android:name=".BootUpReceiver"
            android:enabled="true" >
          <!--  <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />

                <category android:name="android.intent.category.HOME" />
            </intent-filter>-->

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

            <intent-filter>
                <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
                <action android:name="android.hardware.usb.action.USB_DEVICE_DETACHED" />
            </intent-filter>
            <meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" android:resource="@xml/device_filter" />

        </receiver>


来源: stackexchange

问:
why the second route.MapRoute of the same controller get a Null id
I am beginner in ASP.NET MVC.

I have these routes

www.site.com/Afficher/Livre/1

www.site.com/Afficher/Auteur/2

I wrote a One controller with 2 actions. always the second action in the route.MapRoute always get a  null in the id

the controller File : AfficherController

```<code>    public string Auteurs()
    {
        return "liste des auteurs";
    }

    public string Auteur(int? idAuteur)
    {
        return "liste des livres de l'auteur "+idAuteur+" sont :";
    }

    public string Livre(int idlivre)
    {
        return "details du livre " + idlivre + " est : ";
    }
</code>```

the routing file

```<code>  routes.MapRoute(
     name: "afficherLivre",
     url: "{controller}/{action}/{idlivre}",
     defaults: new { controller = "Afficher", action = "Livre", id = UrlParameter.Optional }
 );

        routes.MapRoute(
           name: "AfficherAuteur",
           url: "{controller}/{action}/{idAuteur}",
           defaults: new { controller = "Afficher", action = "Auteur", id =  UrlParameter.Optional }
       );
 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Afficher", action = "Auteurs", id = UrlParameter.Optional }
        );
</code>```

答:
If you want to pass a parameter through the url, its name should be the same in three places in your ASP.NET code: in url and defaults parameters of MapRoute and also in action parameter. You changed url and action parameter, but forgot to replace id with idAuteur in defaults parameter. Your code should work if you'll do so.

But what is more important, it looks like you are creating own MapRoute for every action. You don't have to. Just leave MapRoute with name Default and change parameter names to id in actions Auteur and Livre.

Good luck!

ContentLicense: CC BY-SA 3.0

Body:
I am beginner in ASP.NET MVC.

I have these routes

www.site.com/Afficher/Livre/1

www.site.com/Afficher/Auteur/2

I wrote a One controller with 2 actions. always the second action in the route.MapRoute always get a  null in the id

the controller File : AfficherController

    public string Auteurs()
    {
        return "liste des auteurs";
    }

    public string Auteur(int? idAuteur)
    {
        return "liste des livres de l'auteur "+idAuteur+" sont :";
    }

    public string Livre(int idlivre)
    {
        return "details du livre " + idlivre + " est : ";
    }

the routing file

  routes.MapRoute(
     name: "afficherLivre",
     url: "{controller}/{action}/{idlivre}",
     defaults: new { controller = "Afficher", action = "Livre", id = UrlParameter.Optional }
 );

        routes.MapRoute(
           name: "AfficherAuteur",
           url: "{controller}/{action}/{idAuteur}",
           defaults: new { controller = "Afficher", action = "Auteur", id =  UrlParameter.Optional }
       );
 routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Afficher", action = "Auteurs", id = UrlParameter.Optional }
        );


问:
Declaring Sass variables using BEM methodology
I am trying to implement the BEM methodology to my sass variables.

```<code>// Variables
  // Colors
  $color--blue--light: #3696D1;
  $color--grey: #2D4452;
  ...
  // Fonts
  $body__font--sans-serif--roboto: 'Roboto', sans-serif;
  ...

/* Global */

body {
  font-family: $body__font--sans-serif--roboto;
  background-color: $color--blue--light;
  color: $color--grey;
}...
</code>```

Is this one a good approach to the BEM methodology?

Even I am going to use the color variable for different blocks (body, header...), should I add any block when declaring the color variable?

答:
If helps to organize and standardize your code is a good approach, instead if You feel it's unnecessary You could use another convention.

For example I use BEM in markup:

```<code><div class="myBtnClass myBtnClass--blue">
     <div class="myBtnClass__inner">
      etc etc etc
</code>```

In variables naming I don't feel helpful being so verbose and strict and I use simply

```<code> $red: #cc0000;
 $roboto: 'Roboto', sans-serif;
</code>```

But can depend also on the complexity of project You are working on.

Body:
I am trying to implement the BEM methodology to my sass variables.

// Variables
  // Colors
  $color--blue--light: #3696D1;
  $color--grey: #2D4452;
  ...
  // Fonts
  $body__font--sans-serif--roboto: 'Roboto', sans-serif;
  ...

/* Global */

body {
  font-family: $body__font--sans-serif--roboto;
  background-color: $color--blue--light;
  color: $color--grey;
}...

Is this one a good approach to the BEM methodology?

Even I am going to use the color variable for different blocks (body, header...), should I add any block when declaring the color variable?

Body:
If helps to organize and standardize your code is a good approach, instead if You feel it's unnecessary You could use another convention.

For example I use BEM in markup:

<div class="myBtnClass myBtnClass--blue">
     <div class="myBtnClass__inner">
      etc etc etc

In variables naming I don't feel helpful being so verbose and strict and I use simply

 $red: #cc0000;
 $roboto: 'Roboto', sans-serif;

But can depend also on the complexity of project You are working on.


问:
How can user explorer data from Google Analytics be exported?
I am looking for the solution that will help me create the following table of data:

user IDs (or users) will be listed as rows

visited pages by users (including conversions)

Can you share how it could be done via API or with use of R?

Thank you for your help.

All the best,

Lukas

答:
It cannot be done via the API (a design decision by Google). You could create custom dimensions for UserId and ClientId and use that (does not work retroactively; also, ask your lawyer first about privacy legislation).

If you have an Google 360 account you could do an export to BigQuery, which would include UserId and ClientId.


问:
R - select only factor columns of dataframe
I am trying to select only factor columns from my data frame. Example is below:

```<code>bank[,apply(bank[,names(bank)!="id"], is.factor)]
</code>```

But the code behaves strangely. Step by step:

```<code>sapply(bank[,names(bank)!="id"], is.factor)
</code>```

I get:

```<code>age         sex      region      income     married    children         car
      FALSE        TRUE        TRUE       FALSE        TRUE       FALSE        TRUE
   save_act current_act    mortgage         pep      ageBin
       TRUE        TRUE        TRUE        TRUE        TRUE
</code>```

Looks OK. Now, I assume that I just pass this matrix of TRUE/FALSE to the next step and get only the columns I need:

```<code>bank[,sapply(bank[,names(bank)!="id"], is.factor)]
</code>```

But as result I get all the same columns as in original bank dataframe. Nothing is filtered out. I tried it one way or another but can't find a solution. Any advice on what I am doing wrong?

答:
```<code>df = mtcars
colnames(df) = gsub("mpg","id",colnames(df))
df$am = as.factor(df$am)
df$gear = as.factor(df$gear)
df$id = as.factor(df$id)

library(dplyr)
df %>%  select_if(is.factor) %>% select(-id)
</code>```

Body:
I am trying to select only factor columns from my data frame. Example is below:

bank[,apply(bank[,names(bank)!="id"], is.factor)]

But the code behaves strangely. Step by step:

sapply(bank[,names(bank)!="id"], is.factor)

I get:

age         sex      region      income     married    children         car
      FALSE        TRUE        TRUE       FALSE        TRUE       FALSE        TRUE
   save_act current_act    mortgage         pep      ageBin
       TRUE        TRUE        TRUE        TRUE        TRUE

Looks OK. Now, I assume that I just pass this matrix of TRUE/FALSE to the next step and get only the columns I need:

bank[,sapply(bank[,names(bank)!="id"], is.factor)]

But as result I get all the same columns as in original bank dataframe. Nothing is filtered out. I tried it one way or another but can't find a solution. Any advice on what I am doing wrong?


问:
Coveralls notifies when there are no changes
Here are my repo settings:

So I expect notifications only if something changes. But it continues to inform me of the following letters:

"Coverage remained the same at 100.0% when pulling [commit-hash] on dev into [commit-hash] on master."

How to fix it?

Edit: I think this happens only with PRs. But anyway...

Yeah, I also use Travis CI, where Coveralls check triggers.

答: Oh! I got it, it is not Coveralls' notifications, it is GitHub notifications, which you can manage on 'Settings' page. These messages were sent because Coveralls left comments on PRs in repository I am watching.</p>


问:
Is this duplicating a Maven dependency in a multi module project (i.e Spring)?
Here is the simple situation breakdown and I'd like to know if I'm doing this optimally or if there is a better convention. I have created a dummy project just for learning purposes.

I have created a multi module Maven project. Simply the parent POM, with two sibling child POMS, one being a service layer, and the other being a web layer.

The end result goal is to have a fully functioning WAR in the Web project's target folder, that I can simply deploy into a Tomcat.

Here is where I am not clear:
- Both the Service project, and the Web project need to use Spring. The Service project needs to use Spring simply for it's dependency injection purpose. I need to take a simple Dog class, and auto-inject it into the DogService object. That's all working fine.
- Then I need to auto-inject a DogService object into a Dog controller. The Dog controller exists within the Web project in the multi module structure. This is also working fine, because I have declared a dependency in the Web project for the Service project, therefore all Service JARs are included in the final built WAR, from the web project.

1) Is there a way to simply declare a Spring dependency for both child projects without having to declare the dependencies in each child POM.xml? I just want to make sure I'm not duplicating resources. I believe the way to do this is just to declare the dependency in the Parent POM.xml.

2) If I do #1 above ^, is this the optimal way of creating the project? In essence, the WEB module is the one that contains all the final jars, and in essence it's almost as if the SERVICE project doesn't even exist in Tomcat. As far as Tomcat 'knows', all there is, is a bunch of JAR files containing classes, some of them having been written in my WEB module, and some of them having been written in the SERVICE module, all of which is irrelevant to the production/Tomcat environment. True or false?

Thanks!

答:
Is there a way to simply declare a Spring dependency for both child projects without having to declare the dependencies in each child POM.xml? I just want to make sure I'm not duplicating resources. I believe the way to do this is just to declare the dependency in the Parent POM.xml.

Maven is quite intelligent about dependency management and will not "duplicate" resources--it caches each dependency once* and manages the classpath so that all of the projects that you work with share the same jars. In general, declare dependencies in the modules where they're needed; don't clutter up modules or especially parents with random pieces just to avoid occasionally re-specifying a dependency. This is like hauling your boat trailer on your daily commute because you occasionally go to the lake.

Keep in mind that dependencies are transitive, so that if service-module depends on spring-web (does it really, or are you spamming dependencies?), if web-module depends on service-module it will pull in the dependency as well without having to repeat yourself.

If I do #1 above ^, is this the optimal way of creating the project?

No, it isn't. Be minimalist about your dependencies: If you need it, include it, but don't add dependencies "defensively". This will just bloat your deployment and slow down builds, along with adding opportunities for problems like version mismatches.

As far as Tomcat 'knows', all there is, is a bunch of JAR files containing classes, some of them having been written in my WEB module, and some of them having been written in the SERVICE module, all of which is irrelevant to the production/Tomcat environment. True or false?

Mostly false. In a war, your top-level project (web-module) has its classes directly in the archive, and dependencies are embedded as jar file inside it. Tomcat does not distinguish between service-module and your Spring and other dependencies, however.

Better still would be using Spring Boot's standalone jar and embedded container features--Boot will take care of packaging up the jars you need into a single runnable file that doesn't need external support.

*Release dependencies only, but snapshots aren't relevant here.


问:
JAVA Array of int to bytes array
I have an int array int[] stegoBitsArray = {0,1,1,0,1,1,0,0,0,1,1,0,0,0,0,1...} I want each 8 bits converted to byte and added to byte array which i would later convert to char array because 01101100 is letter "l" and so on so ... So i tried using ByteBuffer but it throws me BufferOverflowException here's my code snippet:

```<code> int[] stegoBitsArray = getStegoTextFromImage(stegoImage);
 ByteBuffer byteBuffer = ByteBuffer.allocate(stegoBitsArray.length);
 for (int i = 0; i < stegoBitsArray.length; i++) {
    byteBuffer.putInt(stegoBitsArray[i]);
 }
</code>```

Or it's more better to convert from int array to characters?

答:
To convert from binary to char you have to convert each 8 bit binary into byte and then you can cast from byte to char. Example:

```<code>byte b = Byte.parseByte("01100001", 2);
        System.out.println((char)b);
</code>```

Prints

```<code>a
</code>```

Title: JAVA Array of int to bytes array

Body:
I have an int array int[] stegoBitsArray = {0,1,1,0,1,1,0,0,0,1,1,0,0,0,0,1...} I want each 8 bits converted to byte and added to byte array which i would later convert to char array because 01101100 is letter "l" and so on so ... So i tried using ByteBuffer but it throws me BufferOverflowException here's my code snippet:

 int[] stegoBitsArray = getStegoTextFromImage(stegoImage);
 ByteBuffer byteBuffer = ByteBuffer.allocate(stegoBitsArray.length);
 for (int i = 0; i < stegoBitsArray.length; i++) {
    byteBuffer.putInt(stegoBitsArray[i]);
 }

Or it's more better to convert from int array to characters?

Body:
To convert from binary to char you have to convert each 8 bit binary into byte and then you can cast from byte to char. Example:

byte b = Byte.parseByte("01100001", 2);
        System.out.println((char)b);

Prints

a


问:
CheckNullability of PrimaryKeyJoinColumn
I have a Entity class that has the ObjectX attribute:

```<code>@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public ClassOfObjectX getObjectX() {
return this.ObjectX;
}
</code>```

This ObjectX can´t be null?

In Hibernate 3.4 I could save this object in the repository without any problem
but now in Hibernate 3.6 it´s throwing this exception:

```<code>org.hibernate.PropertyValueException: not-null property references a null or transient value:
</code>```

答:
Can you check if it works when you set the property
hibernate.check_nullability to false?

ContentLicense: CC BY-SA 2.5

Body:
I have a Entity class that has the ObjectX attribute:

@OneToOne(fetch = FetchType.LAZY)
@PrimaryKeyJoinColumn
public ClassOfObjectX getObjectX() {
return this.ObjectX;
}

This ObjectX can´t be null?

In Hibernate 3.4 I could save this object in the repository without any problem
but now in Hibernate 3.6 it´s throwing this exception:

org.hibernate.PropertyValueException: not-null property references a null or transient value:


问:
MongoDB and PHPLib retrieving an embedded document from a cursor
I have the following code:

```<code><?php

require __DIR__ . '/vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->bbcData->programmeData;
$result = $collection->find( [ '_id' => 'b007jwd9'] );

foreach ($result as $entry) {
    echo $entry['_id'], ': ', $entry['complete_title'], "\n";
}

?>
</code>```

The JSON is the following:

```<code>{"complete_title":{"name":"wimsey - murder must advertise","episode":"sudden decease of a man in dress clothes"},"media_type":"audio","_id":"b007jwd9","categories":{"category1":["drama", "crime"]}}
</code>```

I want to print out the name of the complete_title however the docs do not show the syntax for this. Currently I'm getting an error saying the complete_title is an BSONDocument so it can not be converted into a String.

答:
Use iterator_to_array to get array.

```<code>foreach ($result as $entry) {
    $array = iterator_to_array($entry['complete_title']);
    echo $entry['_id'], ': ', $array['name'], "\n";
}
</code>```

Body:
I have the following code:

<?php

require __DIR__ . '/vendor/autoload.php';

$client = new MongoDB\Client("mongodb://localhost:27017");
$collection = $client->bbcData->programmeData;
$result = $collection->find( [ '_id' => 'b007jwd9'] );

foreach ($result as $entry) {
    echo $entry['_id'], ': ', $entry['complete_title'], "\n";
}

?>

The JSON is the following:

{"complete_title":{"name":"wimsey - murder must advertise","episode":"sudden decease of a man in dress clothes"},"media_type":"audio","_id":"b007jwd9","categories":{"category1":["drama", "crime"]}}

I want to print out the name of the complete_title however the docs do not show the syntax for this. Currently I'm getting an error saying the complete_title is an BSONDocument so it can not be converted into a String.

Body:
Use iterator_to_array to get array.

foreach ($result as $entry) {
    $array = iterator_to_array($entry['complete_title']);
    echo $entry['_id'], ': ', $array['name'], "\n";
}


问:
Add .html to url in Azure web.config rewrite
I am looking to use the sub-page link for a website on Azure, for example:

Html file mysubpage.html placed in the wwwroot directory in Azure.  I wish to be able to access this page by typing mysite.com/mysubpage into the web browser.  However, when I visit this url I get the output "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."

I understand that I need to do this with a web.config file in the wwwroot directory, but am unsure as to what contents the web.config file needs to contain?

I currently have the following:

```<code><?xml version="1.0" ?> <configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Rewrite Rule">
                    <match url=".*" />
                    <conditions>
                        <add input="{StaticRewrites:{REQUEST_URI}}" pattern="(.+)" />
                    </conditions>
                    <action type="Rewrite" url="{C:1}" />
                </rule>
                <rule name="Remove html Extension" stopProcessing="true">
                    <match url="^(.+)\.html$" />
                    <action type="Redirect" url="{R:1}" redirectType="Permanent" />
                </rule>
            </rules>
            <rewriteMaps>
                <rewriteMap name="StaticRewrites" defaultValue="">
                    <add key="/mysubpage" value="/mysubpage.html" />
                </rewriteMap>
            </rewriteMaps>
        </rewrite>
    </system.webServer> </configuration>
</code>```

答:
Solved the issue.  The following worked which removed the removal of the html extension:

```<code><?xml version="1.0" ?> <configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Rewrite Rule">
                    <match url=".*" />
                    <conditions>
                        <add input="{StaticRewrites:{REQUEST_URI}}" pattern="(.+)" />
                    </conditions>
                    <action type="Rewrite" url="{C:1}" />
                </rule>
            </rules>
            <rewriteMaps>
                <rewriteMap name="StaticRewrites" defaultValue="">
                    <add key="/mysubpage" value="/mysubpage.html" />
                </rewriteMap>
            </rewriteMaps>
        </rewrite>
    </system.webServer> </configuration>
</code>```

I understand that it you want to re-route numerous urls you can do this by adding extra lines with add as follows:

```<code>                    <add key="/mysubpage1" value="/mysubpage1.html" />
                    <add key="/mysubpage2" value="/mysubpage2.html" />
</code>```

Body:
I am looking to use the sub-page link for a website on Azure, for example:

Html file mysubpage.html placed in the wwwroot directory in Azure.  I wish to be able to access this page by typing mysite.com/mysubpage into the web browser.  However, when I visit this url I get the output "The resource you are looking for has been removed, had its name changed, or is temporarily unavailable."

I understand that I need to do this with a web.config file in the wwwroot directory, but am unsure as to what contents the web.config file needs to contain?

I currently have the following:

<?xml version="1.0" ?> <configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Rewrite Rule">
                    <match url=".*" />
                    <conditions>
                        <add input="{StaticRewrites:{REQUEST_URI}}" pattern="(.+)" />
                    </conditions>
                    <action type="Rewrite" url="{C:1}" />
                </rule>
                <rule name="Remove html Extension" stopProcessing="true">
                    <match url="^(.+)\.html$" />
                    <action type="Redirect" url="{R:1}" redirectType="Permanent" />
                </rule>
            </rules>
            <rewriteMaps>
                <rewriteMap name="StaticRewrites" defaultValue="">
                    <add key="/mysubpage" value="/mysubpage.html" />
                </rewriteMap>
            </rewriteMaps>
        </rewrite>
    </system.webServer> </configuration>

Body:
Solved the issue.  The following worked which removed the removal of the html extension:

<?xml version="1.0" ?> <configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="Rewrite Rule">
                    <match url=".*" />
                    <conditions>
                        <add input="{StaticRewrites:{REQUEST_URI}}" pattern="(.+)" />
                    </conditions>
                    <action type="Rewrite" url="{C:1}" />
                </rule>
            </rules>
            <rewriteMaps>
                <rewriteMap name="StaticRewrites" defaultValue="">
                    <add key="/mysubpage" value="/mysubpage.html" />
                </rewriteMap>
            </rewriteMaps>
        </rewrite>
    </system.webServer> </configuration>

I understand that it you want to re-route numerous urls you can do this by adding extra lines with add as follows:

                    <add key="/mysubpage1" value="/mysubpage1.html" />
                    <add key="/mysubpage2" value="/mysubpage2.html" />


问:
Swift: downloading data from url causes semaphore_wait_trap freeze
In my application, button tapping downloads data from an Internet site. The site is a list of links containing binary data. Sometimes, the first link may not contain the proper data. In this case, the application takes the next link in the array and gets data from there. The links are correct.

The problem I have is that frequently (not always though) the application freezes for seconds when I tap on the button. After 5-30 seconds, it unfreezes and downloading implements normally. I understand, something is blocking the main thread. When stopping the process in xCode, I get this (semaphore_wait_trap noted):

This is how I do it:

```<code>// Button Action
@IBAction func downloadWindNoaa(_ sender: UIButton)
    {
            // Starts activity indicator
            startActivityIndicator()

            // Starts downloading and processing data

            // Either use this
            DispatchQueue.global(qos: .default).async
                {
                    DispatchQueue.main.async
                        {
                            self.downloadWindsAloftData()
                        }
                }

            // Or this - no difference.
            //downloadWindsAloftData()
        }
    }

func downloadWindsAloftData()
    {
        // Creates a list of website addresses to request data: CHECKED.
        self.listOfLinks = makeGribWebAddress()

        // Extract and save the data
        saveGribFile()
    }

// This downloads the data and saves it in a required format. I suspect, this is the culprit

    func saveGribFile()
    {
        // Check if the links have been created
        if (!self.listOfLinks.isEmpty)
        {
            /// Instance of OperationQueue
            queue = OperationQueue()

            // Convert array of Strings to array of URL links
            let urls = self.listOfLinks.map { URL(string: $0)! }

            guard self.urlIndex != urls.count else
            {
                NSLog("report failure")
                return
            }

            // Current link
            let url = urls[self.urlIndex]

            // Increment the url index
            self.urlIndex += 1

            // Add operation to the queue
            queue.addOperation { () -> Void in

                // Variables for Request, Queue, and Error
                let request = URLRequest(url: url)
                let session = URLSession.shared

                // Array of bytes that will hold the data
                var dataReceived = [UInt8]()

                // Read data
                let task = session.dataTask(with: request) {(data, response, error) -> Void in

                    if error != nil
                    {
                        print("Request transport error")
                    }
                    else
                    {
                        let response = response as! HTTPURLResponse
                        let data = data!

                        if response.statusCode == 200
                        {
                            //Converting data to String
                            dataReceived = [UInt8](data)
                        }
                        else
                        {
                            print("Request server-side error")
                        }
                    }

                    // Main thread
                    OperationQueue.main.addOperation(
                        {
                            // If downloaded data is less than 2 KB in size, repeat the operation
                            if dataReceived.count <= 2000
                            {
                                self.saveGribFile()
                            }

                            else
                            {
                                self.setWindsAloftDataFromGrib(gribData: dataReceived)

                                // Reset the URL Index back to 0
                                self.urlIndex = 0
                            }
                        }
                    )
                }
                task.resume()
            }
        }
    }

// Processing data further
func setWindsAloftDataFromGrib(gribData: [UInt8])
    {
        // Stops spinning activity indicator
        stopActivityIndicator()

        // Other code to process data...
    }

// Makes Web Address

let GRIB_URL = "http://xxxxxxxxxx"

func makeGribWebAddress() -> [String]
    {
        var finalResult = [String]()

        // Main address site
        let address1 = "http://xxxxxxxx"

        // Address part with type of data
        let address2 = "file=gfs.t";
        let address4 = "z.pgrb2.1p00.anl&lev_250_mb=on&lev_450_mb=on&lev_700_mb=on&var_TMP=on&var_UGRD=on&var_VGRD=on"

        let leftlon = "0"
        let rightlon = "359"
        let toplat = "90"
        let bottomlat = "-90"

        // Address part with coordinates
        let address5 = "&leftlon="+leftlon+"&rightlon="+rightlon+"&toplat="+toplat+"&bottomlat="+bottomlat

        // Vector that includes all Grib files available for download
        let listOfFiles = readWebToString()

        if (!listOfFiles.isEmpty)
        {
            for i in 0..<listOfFiles.count
            {
                // Part of the link that includes the file
                let address6 = "&dir=%2F"+listOfFiles[i]

                // Extract time: last 2 characters
                let address3 = listOfFiles[i].substring(from:listOfFiles[i].index(listOfFiles[i].endIndex, offsetBy: -2))

                // Make the link
                let addressFull = (address1 + address2 + address3 + address4 + address5 + address6).trimmingCharacters(in: .whitespacesAndNewlines)

                finalResult.append(addressFull)
            }
        }

        return finalResult;
    }

func readWebToString() -> [String]
    {
        // Final array to return
        var finalResult = [String]()

        guard let dataURL = NSURL(string: self.GRIB_URL)
            else
        {
            print("IGAGribReader error: No URL identified")
            return []
        }

        do
        {
            // Get contents of the page
            let contents = try String(contentsOf: dataURL as URL)

            // Regular expression
            let expression : String = ">gfs\\.\\d+<"
            let range = NSRange(location: 0, length: contents.characters.count)

            do
            {
                // Match the URL content with regex expression
                let regex = try NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.caseInsensitive)
                let contentsNS = contents as NSString
                let matches = regex.matches(in: contents, options: [], range: range)

                for match in matches
                {
                    for i in 0..<match.numberOfRanges
                    {
                        let resultingNS = contentsNS.substring(with: (match.rangeAt(i))) as String
                        finalResult.append(resultingNS)
                    }
                }

                // Remove "<" and ">" from the strings
                if (!finalResult.isEmpty)
                {
                    for i in 0..<finalResult.count
                    {
                        finalResult[i].remove(at: finalResult[i].startIndex)
                        finalResult[i].remove(at: finalResult[i].index(before: finalResult[i].endIndex))
                    }
                }
            }
            catch
            {
                print("IGAGribReader error: No regex match")
            }

        }
        catch
        {
            print("IGAGribReader error: URL content is not read")
        }

        return finalResult;
    }
</code>```

I have been trying to fix it for the past several weeks but in vain. Any help would be much appreciated!

答:
```<code>        let contents = try String(contentsOf: dataURL as URL)
</code>```

You are calling String(contentsOf: url) on the main thread (main queue).  This downloads the content of the URL into a string synchronously The main thread is used to drive the UI, running synchronous network code is going to freeze the UI. This is a big no-no.

You should never call readWebToString() in the main queue. Doing DispatchQueue.main.async { self.downloadWindsAloftData() } exactly put the block in the main queue which we should avoid. (async just means "execute this later", it is still executed on Dispatch.main.)

You should just run downloadWindsAloftData in the global queue instead of main queue

```<code>    DispatchQueue.global(qos: .default).async {
        self.downloadWindsAloftData()
    }
</code>```

Only run DispatchQueue.main.async when you want to update the UI.

Body:
In my application, button tapping downloads data from an Internet site. The site is a list of links containing binary data. Sometimes, the first link may not contain the proper data. In this case, the application takes the next link in the array and gets data from there. The links are correct.

The problem I have is that frequently (not always though) the application freezes for seconds when I tap on the button. After 5-30 seconds, it unfreezes and downloading implements normally. I understand, something is blocking the main thread. When stopping the process in xCode, I get this (semaphore_wait_trap noted):

This is how I do it:

// Button Action
@IBAction func downloadWindNoaa(_ sender: UIButton)
    {
            // Starts activity indicator
            startActivityIndicator()

            // Starts downloading and processing data

            // Either use this
            DispatchQueue.global(qos: .default).async
                {
                    DispatchQueue.main.async
                        {
                            self.downloadWindsAloftData()
                        }
                }

            // Or this - no difference.
            //downloadWindsAloftData()
        }
    }

func downloadWindsAloftData()
    {
        // Creates a list of website addresses to request data: CHECKED.
        self.listOfLinks = makeGribWebAddress()

        // Extract and save the data
        saveGribFile()
    }

// This downloads the data and saves it in a required format. I suspect, this is the culprit

    func saveGribFile()
    {
        // Check if the links have been created
        if (!self.listOfLinks.isEmpty)
        {
            /// Instance of OperationQueue
            queue = OperationQueue()

            // Convert array of Strings to array of URL links
            let urls = self.listOfLinks.map { URL(string: $0)! }

            guard self.urlIndex != urls.count else
            {
                NSLog("report failure")
                return
            }

            // Current link
            let url = urls[self.urlIndex]

            // Increment the url index
            self.urlIndex += 1

            // Add operation to the queue
            queue.addOperation { () -> Void in

                // Variables for Request, Queue, and Error
                let request = URLRequest(url: url)
                let session = URLSession.shared

                // Array of bytes that will hold the data
                var dataReceived = [UInt8]()

                // Read data
                let task = session.dataTask(with: request) {(data, response, error) -> Void in

                    if error != nil
                    {
                        print("Request transport error")
                    }
                    else
                    {
                        let response = response as! HTTPURLResponse
                        let data = data!

                        if response.statusCode == 200
                        {
                            //Converting data to String
                            dataReceived = [UInt8](data)
                        }
                        else
                        {
                            print("Request server-side error")
                        }
                    }

                    // Main thread
                    OperationQueue.main.addOperation(
                        {
                            // If downloaded data is less than 2 KB in size, repeat the operation
                            if dataReceived.count <= 2000
                            {
                                self.saveGribFile()
                            }

                            else
                            {
                                self.setWindsAloftDataFromGrib(gribData: dataReceived)

                                // Reset the URL Index back to 0
                                self.urlIndex = 0
                            }
                        }
                    )
                }
                task.resume()
            }
        }
    }

// Processing data further
func setWindsAloftDataFromGrib(gribData: [UInt8])
    {
        // Stops spinning activity indicator
        stopActivityIndicator()

        // Other code to process data...
    }

// Makes Web Address

let GRIB_URL = "http://xxxxxxxxxx"

func makeGribWebAddress() -> [String]
    {
        var finalResult = [String]()

        // Main address site
        let address1 = "http://xxxxxxxx"

        // Address part with type of data
        let address2 = "file=gfs.t";
        let address4 = "z.pgrb2.1p00.anl&lev_250_mb=on&lev_450_mb=on&lev_700_mb=on&var_TMP=on&var_UGRD=on&var_VGRD=on"

        let leftlon = "0"
        let rightlon = "359"
        let toplat = "90"
        let bottomlat = "-90"

        // Address part with coordinates
        let address5 = "&leftlon="+leftlon+"&rightlon="+rightlon+"&toplat="+toplat+"&bottomlat="+bottomlat

        // Vector that includes all Grib files available for download
        let listOfFiles = readWebToString()

        if (!listOfFiles.isEmpty)
        {
            for i in 0..<listOfFiles.count
            {
                // Part of the link that includes the file
                let address6 = "&dir=%2F"+listOfFiles[i]

                // Extract time: last 2 characters
                let address3 = listOfFiles[i].substring(from:listOfFiles[i].index(listOfFiles[i].endIndex, offsetBy: -2))

                // Make the link
                let addressFull = (address1 + address2 + address3 + address4 + address5 + address6).trimmingCharacters(in: .whitespacesAndNewlines)

                finalResult.append(addressFull)
            }
        }

        return finalResult;
    }

func readWebToString() -> [String]
    {
        // Final array to return
        var finalResult = [String]()

        guard let dataURL = NSURL(string: self.GRIB_URL)
            else
        {
            print("IGAGribReader error: No URL identified")
            return []
        }

        do
        {
            // Get contents of the page
            let contents = try String(contentsOf: dataURL as URL)

            // Regular expression
            let expression : String = ">gfs\\.\\d+<"
            let range = NSRange(location: 0, length: contents.characters.count)

            do
            {
                // Match the URL content with regex expression
                let regex = try NSRegularExpression(pattern: expression, options: NSRegularExpression.Options.caseInsensitive)
                let contentsNS = contents as NSString
                let matches = regex.matches(in: contents, options: [], range: range)

                for match in matches
                {
                    for i in 0..<match.numberOfRanges
                    {
                        let resultingNS = contentsNS.substring(with: (match.rangeAt(i))) as String
                        finalResult.append(resultingNS)
                    }
                }

                // Remove "<" and ">" from the strings
                if (!finalResult.isEmpty)
                {
                    for i in 0..<finalResult.count
                    {
                        finalResult[i].remove(at: finalResult[i].startIndex)
                        finalResult[i].remove(at: finalResult[i].index(before: finalResult[i].endIndex))
                    }
                }
            }
            catch
            {
                print("IGAGribReader error: No regex match")
            }

        }
        catch
        {
            print("IGAGribReader error: URL content is not read")
        }

        return finalResult;
    }

I have been trying to fix it for the past several weeks but in vain. Any help would be much appreciated!

Body:
        let contents = try String(contentsOf: dataURL as URL)

You are calling String(contentsOf: url) on the main thread (main queue).  This downloads the content of the URL into a string synchronously The main thread is used to drive the UI, running synchronous network code is going to freeze the UI. This is a big no-no.

You should never call readWebToString() in the main queue. Doing DispatchQueue.main.async { self.downloadWindsAloftData() } exactly put the block in the main queue which we should avoid. (async just means "execute this later", it is still executed on Dispatch.main.)

You should just run downloadWindsAloftData in the global queue instead of main queue

    DispatchQueue.global(qos: .default).async {
        self.downloadWindsAloftData()
    }

Only run DispatchQueue.main.async when you want to update the UI.


问:
Defining a list from scratch in prolog
So I need to define a list predicate: list(.) that returns true if the list is of the form cons(b,cons(d,cons(e,cons(h,nil)))). for the list bdeh.

I need to define the cons(.,.) binary predicate as well.

So far I have :

```<code>cons(atom(A),nil):- cons(A,nil).
cons(A,B):- cons(A, cons(B,_)).

list(atom(A)):-cons(A,nil).
list(A):- list(cons(_,A)).
</code>```

but I don't think that the list(.) predicate is actually traversing through my cons. Can anyone help out in how to traverse the list or to proceed?

答:
I need to define the cons(.,.) binary predicate as well.

Based on your question, cons/2 is not a predicate, it is a functor. A functor has no inherent semantical meaning. A functor is used to structure data in some way that makes sense to the programmer.

Your predicate list/1 needs to verify that the parameter is a list. Two things are lists:

the nil/0 constant; and

a compound term of the functor cons/2 where the second element is a list as well.

So we can define it like:

```<code>list(nil).
list(cons(_,X)) :-
    list(X).
</code>```

How does this work? The first clause simply states that nil is a list: if you call list(nil). it will succeed ("return" true). If you do not give it a nil, it will check the second clause and see if you gave it a compound term of cons/2. If that is not the case the clause (and thus the predicate call) will fail. If it is the case, it will unpack the compound term. Prolog is not interested in the first element (that's why we call it _), the second element we name X, and Prolog will perform a recursive call to list/1 with that second element to check if it is a list as well. Therefore it will traverse through the nested cons/2 structures until it finds a nil (or cut off earlier if the second element is not a nil and not a cons/2 compound term).

Title: Defining a list from scratch in prolog

Body:
So I need to define a list predicate: list(.) that returns true if the list is of the form cons(b,cons(d,cons(e,cons(h,nil)))). for the list bdeh.

I need to define the cons(.,.) binary predicate as well.

So far I have :

cons(atom(A),nil):- cons(A,nil).
cons(A,B):- cons(A, cons(B,_)).

list(atom(A)):-cons(A,nil).
list(A):- list(cons(_,A)).

but I don't think that the list(.) predicate is actually traversing through my cons. Can anyone help out in how to traverse the list or to proceed?

Body:
I need to define the cons(.,.) binary predicate as well.

Based on your question, cons/2 is not a predicate, it is a functor. A functor has no inherent semantical meaning. A functor is used to structure data in some way that makes sense to the programmer.

Your predicate list/1 needs to verify that the parameter is a list. Two things are lists:

the nil/0 constant; and

a compound term of the functor cons/2 where the second element is a list as well.

So we can define it like:

list(nil).
list(cons(_,X)) :-
    list(X).

How does this work? The first clause simply states that nil is a list: if you call list(nil). it will succeed ("return" true). If you do not give it a nil, it will check the second clause and see if you gave it a compound term of cons/2. If that is not the case the clause (and thus the predicate call) will fail. If it is the case, it will unpack the compound term. Prolog is not interested in the first element (that's why we call it _), the second element we name X, and Prolog will perform a recursive call to list/1 with that second element to check if it is a list as well. Therefore it will traverse through the nested cons/2 structures until it finds a nil (or cut off earlier if the second element is not a nil and not a cons/2 compound term).


问:
Set directory permissions with inheritance during application installation?
I found a thread on the Microsoft Forums where the answer tells how to set directory permissions using the LockPermission table. I tried it, but it doesn't seem to set the inheritance for any of the subdirectories. I need to be able to set the permissions for a particular folder that I create and have those permissions be inherited by all of the files and directories within and beneath it. Is there a way to do this without having to add a line in the LockPermission table for each and every directory (and file) that I want to affect?</p>

答:
For anyone looking to know the joys and pains of using MsiLockPermissionsEx, here is a tutorial, some best practices and a helper script. The helper script extracts SDDL from existing system resources - so you just use Regedit and Windows Explorer to set permissions and the helper script extracts them for you.

The article also discusses the challenge of supporting XP and Windows 7 permissions with a single package.

You can check it out here: http://csi-windows.com/toolkit/csigetsddlfromobject


问:
No enum constant in build.gradle
I'm trying to run todo-mvp of google samples but it gives me this error:

```<code>Error:(55, 0) No enum constant org.gradle.api.tasks.testing.logging.TestLogEvent.SKİPPED
</code>```

I don't have experience with testing and don't know gradle proficiently. What might be the cause?

答:
Changing computer's language is solution but if you don't want to change your language here is alternative solution :

```<code>// Always show the result of every unit test, even if it passes.
testOptions.unitTests.all {
    testLogging {
        events 'passed', 'SKIPPED', 'FAILED', 'standardOut', 'standardError'
    }
}
</code>```

I see this solution on there : TestLogEvent and I realized we can use uppercase letters.

As you can see the problem is i character, since there is no İ character in English you need to convert them to I. I come to this idea from my logcat :

```<code>No enum constant org.gradle.api.tasks.testing.logging.TestLogEvent.SKİPPED
</code>```

Title: No enum constant in build.gradle

Body:
I'm trying to run todo-mvp of google samples but it gives me this error:

Error:(55, 0) No enum constant org.gradle.api.tasks.testing.logging.TestLogEvent.SKİPPED

I don't have experience with testing and don't know gradle proficiently. What might be the cause?

Body:
Changing computer's language is solution but if you don't want to change your language here is alternative solution :

// Always show the result of every unit test, even if it passes.
testOptions.unitTests.all {
    testLogging {
        events 'passed', 'SKIPPED', 'FAILED', 'standardOut', 'standardError'
    }
}

I see this solution on there : TestLogEvent and I realized we can use uppercase letters.

As you can see the problem is i character, since there is no İ character in English you need to convert them to I. I come to this idea from my logcat :

No enum constant org.gradle.api.tasks.testing.logging.TestLogEvent.SKİPPED


问:
How to use .graphqls files in a Node application?
I'm attempting to refactor my Node-based Apollo GraphQL server instance to use .graphqls schema files instead of being string-based. I'm attempting to go by the example here to include the files in my schema:

```<code>import facility_schema from './facility-objects.graphqls';
</code>```

however, I get a SyntaxError from the import. This happens if I just run either node or babel-node. However, running this sample project on GitHub, it appears to work.

Am I missing a package? Am I using the wrong interpreter? I know I'm missing something, I just don't know what.

答:
For plain Node/Apollo, the following worked for me (with babel-node):

import { readFileSync } from 'fs'
const schema = readFileSync(__dirname + '/schema.graphqls', 'utf8')
```

For Meteor/Apollo, you can try using the following new plugin (didn't try it myself, though):

https://github.com/Swydo/meteor-graphql

Body:
I'm attempting to refactor my Node-based Apollo GraphQL server instance to use .graphqls schema files instead of being string-based. I'm attempting to go by the example here to include the files in my schema:

import facility_schema from './facility-objects.graphqls';

however, I get a SyntaxError from the import. This happens if I just run either node or babel-node. However, running this sample project on GitHub, it appears to work.

Am I missing a package? Am I using the wrong interpreter? I know I'm missing something, I just don't know what.

Body:
For plain Node/Apollo, the following worked for me (with babel-node):

import { readFileSync } from 'fs'
const schema = readFileSync(__dirname + '/schema.graphqls', 'utf8')

For Meteor/Apollo, you can try using the following new plugin (didn't try it myself, though):

https://github.com/Swydo/meteor-graphql


问:
Watir getting started error
I was trying to begin one project of Watir, to do so i create one file (test.rb)

```<code>require 'watir'

browser = Watir::Browser.new
browser.goto 'google.com'
browser.text_field(title: 'Search').set 'Hello World!'
browser.button(type: 'submit').click

puts browser.title
# => 'Hello World! - Google Search'
browser.closeenter code here
</code>```

But when i run (ruby teste.rb), it gives me one error

```<code>/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- watir/loader
 (LoadError)
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /Library/Ruby/Gems/2.0.0/gems/commonwatir-4.0.0/lib/watir.rb:1:in `<top (required)>'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `rescue in require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:144:in `require'
        from teste.rb:1:in `<main>'
</code>```

I already install watir (gem install watir).
Can someone help me?

Thanks

答: Try with require "watir-webdriver"

Title: Watir getting started error

Body:
I was trying to begin one project of Watir, to do so i create one file (test.rb)

require 'watir'

browser = Watir::Browser.new
browser.goto 'google.com'
browser.text_field(title: 'Search').set 'Hello World!'
browser.button(type: 'submit').click

puts browser.title
# => 'Hello World! - Google Search'
browser.closeenter code here

But when i run (ruby teste.rb), it gives me one error

/System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require': cannot load such file -- watir/loader
 (LoadError)
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:55:in `require'
        from /Library/Ruby/Gems/2.0.0/gems/commonwatir-4.0.0/lib/watir.rb:1:in `<top (required)>'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:135:in `rescue in require'
        from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/rubygems/core_ext/kernel_require.rb:144:in `require'
        from teste.rb:1:in `'

I already install watir (gem install watir).
Can someone help me?

Thanks

Body: Try with require "watir-webdriver"


问:
SQL, need to transform a table
I'm working with Microsoft SQL Server 2014.
I have a table with next data format:

```<code>|customerId | action | amount | isSuccessful | paymentCount |
|____1____  |__ W__  |____10__|____0____     |_____2________|
|____1____  |__ D__  |____20__|____1____     |_____3________|
|____1____  |__ W__  |____30__|____1____     |_____1________|
|____1____  |__ D__  |____40__|____0____     |_____1________|
</code>```

What I need is to do report with this format:

```<code>|customerId|depositAmount|withdrawalAmount|depositAttemptCount|withdrawalAttemptCount|
|____1____ |______20 ____|________30_____ |________4_______  _|________3__________ |
</code>```

How it's possible to 'transform' table with select?

I would appreciate any help.

答:
You can use conditional aggregation here:</p>

```<code>select customerId,
    sum(case when action = 'D' and isSuccessful = 1 then amount else 0 end) as depositAmount,
    sum(case when action = 'W' and isSuccessful = 1 then amount else 0 end) as withdrawalAmount,
    sum(case when action = 'D' then paymentCount else 0 end) as depositAttemptCount,
    sum(case when action = 'W' then paymentCount else 0 end) as withdrawalAttemptCount
from your_table
group by customerId;
</code>```

Title: SQL, need to transform a table

Body:
I'm working with Microsoft SQL Server 2014.
I have a table with next data format:

|customerId | action | amount | isSuccessful | paymentCount |
|____1____  |__ W__  |____10__|____0____     |_____2________|
|____1____  |__ D__  |____20__|____1____     |_____3________|
|____1____  |__ W__  |____30__|____1____     |_____1________|
|____1____  |__ D__  |____40__|____0____     |_____1________|

What I need is to do report with this format:

|customerId|depositAmount|withdrawalAmount|depositAttemptCount|withdrawalAttemptCount|
|____1____ |______20 ____|________30_____ |________4_______  _|________3__________ |

How it's possible to 'transform' table with select?

I would appreciate any help.

Body:
You can use conditional aggregation here:

select customerId,
    sum(case when action = 'D' and isSuccessful = 1 then amount else 0 end) as depositAmount,
    sum(case when action = 'W' and isSuccessful = 1 then amount else 0 end) as withdrawalAmount,
    sum(case when action = 'D' then paymentCount else 0 end) as depositAttemptCount,
    sum(case when action = 'W' then paymentCount else 0 end) as withdrawalAttemptCount
from your_table
group by customerId;


问:
How to filter records with arithmetic operation on columns of different type in Slick 3
For example I have this simplified model where timestamp and duration both represent seconds.

case class Item(id: Int, : Long, duration: Int)

val max_timestmap: Long = ???
val stmt = items.filter(x => (x.timestamp + x.duration) <= max_timestamp)
db.run(stmt.result)

Above will not compile with following error that I have hard time understanding.

ambiguous implicit values:
[error]  both value BooleanOptionColumnCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[slick.lifted.Rep[Option[Boolean]]]
[error]  and value BooleanCanBeQueryCondition in object CanBeQueryCondition of type => slick.lifted.CanBeQueryCondition[Boolean]
[error]  match expected type slick.lifted.CanBeQueryCondition[Nothing]
[error]                 filter(x => (x.timestamp + x.duration) <= max_timestamp)

Update 1:
Seems like the issues stems for the fact that timestamp is Long and duration is Int. When both are of the same data type it seems to compile.

Update 2:
I found this solution to work. Cast duration to Long using x.duration.asInstanceOf[Rep[Long]] or probably more appropriate x.duration.asColumnOf[Long]

答:
Though not very helpful in telling the exact problem, the error message makes sense if one looks at method filter and trait/object CanBeQueryCondition in Query.scala:

```<code>sealed abstract class Query[+E, U, C[_]] extends QueryBase[C[U]] { self =>
  ...
  def filter[T <: Rep[_]](f: E => T)(implicit wt: CanBeQueryCondition[T]): Query[E, U, C] =
    withFilter(f)
  ...
}

...

trait CanBeQueryCondition[-T] extends (T => Rep[_])

object CanBeQueryCondition {
  implicit val BooleanColumnCanBeQueryCondition : CanBeQueryCondition[Rep[Boolean]] =
    new CanBeQueryCondition[Rep[Boolean]] {
      def apply(value: Rep[Boolean]) = value
    }
  implicit val BooleanOptionColumnCanBeQueryCondition : CanBeQueryCondition[Rep[Option[Boolean]]] =
    new CanBeQueryCondition[Rep[Option[Boolean]]] {
      def apply(value: Rep[Option[Boolean]]) = value
    }
  implicit val BooleanCanBeQueryCondition : CanBeQueryCondition[Boolean] =
    new CanBeQueryCondition[Boolean] {
      def apply(value: Boolean) = new LiteralColumn(value)
    }
}
</code>```

As pointed out by @Federico Pellegatta, the explicit cast requirement leads to T = Nothing (T <: Rep[_]) for the implicit parameter CanBeQueryCondition[T], thus the reported error.

Body:
Though not very helpful in telling the exact problem, the error message makes sense if one looks at method filter and trait/object CanBeQueryCondition in Query.scala:

sealed abstract class Query[+E, U, C[_]] extends QueryBase[C[U]] { self =>
  ...
  def filter[T <: Rep[_]](f: E => T)(implicit wt: CanBeQueryCondition[T]): Query[E, U, C] =
    withFilter(f)
  ...
}

...

trait CanBeQueryCondition[-T] extends (T => Rep[_])

object CanBeQueryCondition {
  implicit val BooleanColumnCanBeQueryCondition : CanBeQueryCondition[Rep[Boolean]] =
    new CanBeQueryCondition[Rep[Boolean]] {
      def apply(value: Rep[Boolean]) = value
    }
  implicit val BooleanOptionColumnCanBeQueryCondition : CanBeQueryCondition[Rep[Option[Boolean]]] =
    new CanBeQueryCondition[Rep[Option[Boolean]]] {
      def apply(value: Rep[Option[Boolean]]) = value
    }
  implicit val BooleanCanBeQueryCondition : CanBeQueryCondition[Boolean] =
    new CanBeQueryCondition[Boolean] {
      def apply(value: Boolean) = new LiteralColumn(value)
    }
}

As pointed out by @Federico Pellegatta, the explicit cast requirement leads to T = Nothing (T <: Rep[_]) for the implicit parameter CanBeQueryCondition[T], thus the reported error.


答:
Here is how I would do it in 2 lines of code:

the dataframe:

```<code>df1=pd.DataFrame({'A':[0,2,2],'B':[3,1,3],'C':[2,0,1],'D':[1,3,0],'ListVal':[[0.0,0.1,0.2,0.3],[0.5,0.6,0.7,0.8],[0.15,0.25,0.35,0.45]]})
</code>```

convert it to a list of lists:

```<code>df_vals=df1.values.tolist()
</code>```

and use the following list comprehension:

```<code>desired=[[d[4][e] if i<4 else e for i,e in enumerate(d)]for d in df_vals]
</code>```

and convert back to a Dataframe if you want:

```<code>df=pd.DataFrame(desired, columns=['A','B','C','D','ListVal'])
</code>```

output:

```<code>print df
      A     B     C     D                   ListVal
0  0.00  0.30  0.20  0.10      [0.0, 0.1, 0.2, 0.3]
1  0.70  0.60  0.50  0.80      [0.5, 0.6, 0.7, 0.8]
2  0.35  0.45  0.25  0.15  [0.15, 0.25, 0.35, 0.45]
</code>```

Title: Replace indices with values from a list in a data frame

Body:
I have the following data frame:

A | B | C | D | ListVal
---------------------------------
0 | 3 | 2 | 1 | [0.0,0.1,0.2,0.3]
---------------------------------
2 | 1 | 0 | 3 | [0.5,0.6,0.7,0.8]
---------------------------------
2 | 3 | 1 | 0 | [0.15,0.25,0.35,0.45]

For each row, I would like to use the numbers in columns A-D as indices to the list in column ListVal, and fill the values in the respective columns. So for the above data frame, I want to convert it to:

A   |  B  |  C  |  D  | ListVal
-----------------------------------------
0.0 | 0.3 | 0.2 | 0.1 | [0.0,0.1,0.2,0.3]
-----------------------------------------
0.7 | 0.6 | 0.5 | 0.8 | [0.5,0.6,0.7,0.8]
-----------------------------------------
0.35| 0.45| 0.25| 0.15| [0.15,0.25,0.35,0.45]

Note that indices per row are non-repeating.

I tried to do this using numpy by converting last column into a matrix and the first four columns to another matrix. But stuck there, as well!

Body:
Here is how I would do it in 2 lines of code:

the dataframe:

df1=pd.DataFrame({'A':[0,2,2],'B':[3,1,3],'C':[2,0,1],'D':[1,3,0],'ListVal':[[0.0,0.1,0.2,0.3],[0.5,0.6,0.7,0.8],[0.15,0.25,0.35,0.45]]})

convert it to a list of lists:

df_vals=df1.values.tolist()

and use the following list comprehension:

desired=[[d[4][e] if i<4 else e for i,e in enumerate(d)]for d in df_vals]

and convert back to a Dataframe if you want:

df=pd.DataFrame(desired, columns=['A','B','C','D','ListVal'])

output:

print df
      A     B     C     D                   ListVal
0  0.00  0.30  0.20  0.10      [0.0, 0.1, 0.2, 0.3]
1  0.70  0.60  0.50  0.80      [0.5, 0.6, 0.7, 0.8]
2  0.35  0.45  0.25  0.15  [0.15, 0.25, 0.35, 0.45]


问:
WAMP server suddenly stops working
I was working with WAMP server and wordpress yesterday and today when I started WAMP the database get an error.

When I run wamp status I get this:

And in MySQL log I get:

```<code>2017-03-30T23:30:44.499590Z 0 [ERROR] InnoDB: Unable to create temporary file; errno: 0
2017-03-30T23:30:44.507591Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2017-03-30T23:30:44.509591Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2017-03-30T23:30:44.510591Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-03-30T23:30:44.511591Z 0 [ERROR] Failed to initialize plugins.
2017-03-30T23:30:44.511591Z 0 [ERROR] Aborting
</code>```

Please Help Me.
Thanks

Note: is not a problem of Skype!

答:
Maybe you can try to change the root password of your mysql.
Go to the mysql console. You'll see that mysql asks you for a password, but leave it empty (press enter). After that, use this statement "SET PASSWORD = PASSWORD('your_new_password');"
Once you do that, you can access to phpmyadmin with the user "root" and the new password you chose. Now, feel free to update/delete the user that was giving you problems.  </p>

Title: WAMP server suddenly stops working

Body:
I was working with WAMP server and wordpress yesterday and today when I started WAMP the database get an error.

When I run wamp status I get this:

And in MySQL log I get:

2017-03-30T23:30:44.499590Z 0 [ERROR] InnoDB: Unable to create temporary file; errno: 0
2017-03-30T23:30:44.507591Z 0 [ERROR] InnoDB: Plugin initialization aborted with error Generic error
2017-03-30T23:30:44.509591Z 0 [ERROR] Plugin 'InnoDB' init function returned error.
2017-03-30T23:30:44.510591Z 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.
2017-03-30T23:30:44.511591Z 0 [ERROR] Failed to initialize plugins.
2017-03-30T23:30:44.511591Z 0 [ERROR] Aborting

Please Help Me.
Thanks

Note: is not a problem of Skype!


问:
Writting a file with german letters like ü ,ä, ö and ß in python
I am creating files with this function in python 2

```<code> with io.FileIO(station_data['name']+".pls", "w") as file:
       file.write("[playlist] " + \n + "numberofentries=1" + \n + "File1=" + station_data['streamURL'] + \n + "Title1=" + station_data['name'] )
</code>```

But when in station_[name] is an "Ä" or "Ü" and so on, I get this error

```<code>UnicodeEncodeError: 'ascii' codec can't enconde character u'\xfc' in position 171: ordinal not in range(128)
</code>```

This is the whole script

```<code>import requests
import sys
import os
import json
import io
from objbrowser import browse

class RadioStations():
  user_agent = {'User-agent': 'User-Agent: XBMC Addon Radio'}
  data = []
  no_data = True
  url = "http://radio.de/info/menu/broadcastsofcategory?category=_top"
  try:
    response  = requests.get(url, headers = user_agent)
    data = response.json()
    no_data = False
    print("Data found")
  except requests.HTTPError, e:
    print("HTTP error %s", e.code)
    no_data = False
  except requests.ConnectionError, e:
    data.append({'name': 'no station data'})
    no_data = True
    print("Connection error %s", e)
  print("Getting StreamUrls and creating files")
  for item in data:
     id2 = str(item['id'])
     url = "http://radio.de/info/broadcast/getbroadcastembedded?broadcast=" + id2
     response = requests.get(url, headers = user_agent)
     station_data = response.json()
     with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
       txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
       file.write(txt)
     if "errorCode" in station_data.keys():
       print("no such entry")

  print("Finished")
</code>```

It is based on this script on GitHub

答:
What you should do is open the file as wb which will write to file in binary mode. That way you can write non-ascii characters to files, and why not just use the open() command?
And as a tip, use string formatting to make your script look neater.

```<code>with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
   txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
   file.write(txt) # don't forget to encode it if you're on Python 3
</code>```

For python 2, you don't need to .encode('utf-8').

Body:
I am creating files with this function in python 2

 with io.FileIO(station_data['name']+".pls", "w") as file:
       file.write("[playlist] " + \n + "numberofentries=1" + \n + "File1=" + station_data['streamURL'] + \n + "Title1=" + station_data['name'] )

But when in station_[name] is an "Ä" or "Ü" and so on, I get this error

UnicodeEncodeError: 'ascii' codec can't enconde character u'\xfc' in position 171: ordinal not in range(128)

This is the whole script

import requests
import sys
import os
import json
import io
from objbrowser import browse

class RadioStations():
  user_agent = {'User-agent': 'User-Agent: XBMC Addon Radio'}
  data = []
  no_data = True
  url = "http://radio.de/info/menu/broadcastsofcategory?category=_top"
  try:
    response  = requests.get(url, headers = user_agent)
    data = response.json()
    no_data = False
    print("Data found")
  except requests.HTTPError, e:
    print("HTTP error %s", e.code)
    no_data = False
  except requests.ConnectionError, e:
    data.append({'name': 'no station data'})
    no_data = True
    print("Connection error %s", e)
  print("Getting StreamUrls and creating files")
  for item in data:
     id2 = str(item['id'])
     url = "http://radio.de/info/broadcast/getbroadcastembedded?broadcast=" + id2
     response = requests.get(url, headers = user_agent)
     station_data = response.json()
     with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
       txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
       file.write(txt)
     if "errorCode" in station_data.keys():
       print("no such entry")

  print("Finished")

It is based on this script on GitHub

Body:
What you should do is open the file as wb which will write to file in binary mode. That way you can write non-ascii characters to files, and why not just use the open() command?
And as a tip, use string formatting to make your script look neater.

with open("{}.pls".format(station_data['name']).encode('utf-8'), "wb") as file:
   txt = "[playlist]\nnumberofentries=1\nFile1={}\nTitle1={}".format(station_data['streamURL'],station_data['name'])
   file.write(txt) # don't forget to encode it if you're on Python 3

For python 2, you don't need to .encode('utf-8').


问:
Accidentally included a breakpoint - how do I undo my mistake? (thread 1: breakpoint 1.1)
Whenever I try to run my code for my sign up view controller, I am brought back to my code in which they are displaying there is a breakpoint. I've pressed command + 7, the blue line was on the 34th line:

ref = FIRDatabase.database().reference()
        userStorage = storage.child("users")}

^ Can anyone help me resolve this issue?

答: In Xcode find the blue chevron-icon for the relevant break-point you want to delete in the code. Hovering over the blue icon with your mouse simply control-click and then select 'delete breakpoint'.</p>


问:
Transposing row vector X to get compatible dimensions warning in Scilab
I am learning to use Scilab, I tried plotting a function wich I know have a discontinuity at a certain value but the plot I got had a non expectable behavior so I tried to plot a very well known function "y=1/x".

I created the "x" vector

```<code>x=[-10:1:10];
</code>```

Then created the "y" function

```<code>y=1/x;
</code>```

And then used the plot command

```<code>plot(x,y)
</code>```

I got the following warning

WARNING: Transposing row vector X to get compatible dimensions

And my plot is a straight line, I don't know what I'm doing wrong.

答: Take care: 1/x compute some thing like 1*pinv(x) not the array [1/x(1),1/x(2),...]. to obtain the previous result use 1 ./x for element wise disvision.</p>

Body:
I am learning to use Scilab, I tried plotting a function wich I know have a discontinuity at a certain value but the plot I got had a non expectable behavior so I tried to plot a very well known function "y=1/x".

I created the "x" vector

x=[-10:1:10];

Then created the "y" function

y=1/x;

And then used the plot command

plot(x,y)

I got the following warning

WARNING: Transposing row vector X to get compatible dimensions

And my plot is a straight line, I don't know what I'm doing wrong.


问:
Removing duplicates in lists
How can I check if a list has any duplicates and return a new list without duplicates?</p>

答:
Here's the fastest pythonic solution comaring to others listed in replies.

Using implementation details of short-circuit evaluation allows to use list comprehension, which is fast enough. visited.add(item) always returns None as a result, which is evaluated as False, so the right-side of or would always be the result of such an expression.

Time it yourself

```<code>def deduplicate(sequence):
    visited = set()
    adder = visited.add  # get rid of qualification overhead
    out = [adder(item) or item for item in sequence if item not in visited]
    return out
</code>```

ContentLicense: CC BY-SA 4.0

Title: Removing duplicates in lists

Body:
Here's the fastest pythonic solution comaring to others listed in replies.

Using implementation details of short-circuit evaluation allows to use list comprehension, which is fast enough. visited.add(item) always returns None as a result, which is evaluated as False, so the right-side of or would always be the result of such an expression.

Time it yourself

def deduplicate(sequence):
    visited = set()
    adder = visited.add  # get rid of qualification overhead
    out = [adder(item) or item for item in sequence if item not in visited]
    return out


问:
to find minimum missing number in oracle
i want to find the minimum missing number of a column named (s_no) and the table named (test_table) in oracle and I write the following code..

```<code>select
    min_s_no-1+level missing_number
from (
    select min(s_no) min_s_no, max(s_no) max_s_no
    from test_table
) connect by level <= max_s_no-min_s_no+1
minus
select s_no from test_table
;
</code>```

it gives me all the missing number as a result. But I want to select the minimum
number. Can any one help me please.
thanks in advance.

答:
Using analytical function LEAD you can get the number from the next row in ascending order. Comparing of this value with  with the original number increased by 1 you get the missing values (if two numbers do not match).

To get the first missing value in ascending order is the same selecting the MIN value:

```<code>select
num,
lead(num) over (order by num)  num_lead,
case when num + 1 != lead(num) over (order by num)  then num + 1 end as  missing_num
from test_data
order by num;

       NUM   NUM_LEAD MISSING_NUM
---------- ---------- -----------
         4          5
         5          6
         6          9           7
         9         10
        10         13          11
        13

-- first missing number = MIN missing number
select min(missing_num)
from (
select
case when num + 1 != lead(num) over (order by num)  then num + 1 end as  missing_num
from test_data
);

MIN(MISSING_NUM)
----------------
               7
</code>```

ADDENDUM

A good practice in writing SQL is to consider edge cases - here a table that contains a complete interval without holes. The first missing value will be the successor of the last number.

```<code>select nvl(min(missing_num),max(num)+1) first_missing_value
from (
select
num,
case when num + 1 != lead(num) over (order by num)  then num + 1 end as  missing_num
from test_data
);
</code>```

A complete table return no MISSING_NUM, so the original query return NULL. Using the NVL the expected result is provided.

Body:
i want to find the minimum missing number of a column named (s_no) and the table named (test_table) in oracle and I write the following code..

select
    min_s_no-1+level missing_number
from (
    select min(s_no) min_s_no, max(s_no) max_s_no
    from test_table
) connect by level <= max_s_no-min_s_no+1
minus
select s_no from test_table
;

it gives me all the missing number as a result. But I want to select the minimum
number. Can any one help me please.
thanks in advance.

Body:
Using analytical function LEAD you can get the number from the next row in ascending order. Comparing of this value with  with the original number increased by 1 you get the missing values (if two numbers do not match).

To get the first missing value in ascending order is the same selecting the MIN value:

select
num,
lead(num) over (order by num)  num_lead,
case when num + 1 != lead(num) over (order by num)  then num + 1 end as  missing_num
from test_data
order by num;

       NUM   NUM_LEAD MISSING_NUM
---------- ---------- -----------
         4          5
         5          6
         6          9           7
         9         10
        10         13          11
        13

-- first missing number = MIN missing number
select min(missing_num)
from (
select
case when num + 1 != lead(num) over (order by num)  then num + 1 end as  missing_num
from test_data
);

MIN(MISSING_NUM)
----------------
               7

ADDENDUM

A good practice in writing SQL is to consider edge cases - here a table that contains a complete interval without holes. The first missing value will be the successor of the last number.

select nvl(min(missing_num),max(num)+1) first_missing_value
from (
select
num,
case when num + 1 != lead(num) over (order by num)  then num + 1 end as  missing_num
from test_data
);

A complete table return no MISSING_NUM, so the original query return NULL. Using the NVL the expected result is provided.


问:
Updating MathJax CDN
MathJax is shutting down its CDN, as officially announced on the MathJax website and on StackExchange's Meta. The official announcement recommends several alternatives, including using an alternative CDN and self-hosting. What is the best way to accomplish this process for a site with a large number of references to the MathJax CDN?

On my tiny little website, for example, I can count the number of files that I have that point to the MathJax CDN using the following unix command:

```<code>grep -rl 'cdn\.mathjax\.org/mathjax/latest/MathJax\.js' . | grep '\.html$' | wc -l
</code>```

I find that I have 382 such files. What's the best (safest) way to go automate the process of going through these files and modifying the source to point to the new CDN, rather than the old CDN?

Note: I can use Python to traverse the directory tree and do search and replace pretty easily. I'm interested in robust techniques. In fact, I've already post a self-answer that uses BeautifulSoup to find and replace MathJax src links. This is the way that I usually use MathJax, but there are other ways, of course.

答: Here's the first approach I whipped up in Python; not sure how safe or inclusive it is. I first write a function called update_mathjax. This uses BeautifulSoup to find the , and then searches for a

Title: Updating MathJax CDN

Body:
MathJax is shutting down its CDN, as officially announced on the MathJax website and on StackExchange's Meta. The official announcement recommends several alternatives, including using an alternative CDN and self-hosting. What is the best way to accomplish this process for a site with a large number of references to the MathJax CDN?

On my tiny little website, for example, I can count the number of files that I have that point to the MathJax CDN using the following unix command:

grep -rl 'cdn\.mathjax\.org/mathjax/latest/MathJax\.js' . | grep '\.html$' | wc -l

I find that I have 382 such files. What's the best (safest) way to go automate the process of going through these files and modifying the source to point to the new CDN, rather than the old CDN?

Note: I can use Python to traverse the directory tree and do search and replace pretty easily. I'm interested in robust techniques. In fact, I've already post a self-answer that uses BeautifulSoup to find and replace MathJax src links. This is the way that I usually use MathJax, but there are other ways, of course.

Body:
Here's the first approach I whipped up in Python; not sure how safe or inclusive it is. I first write a function called update_mathjax. This uses BeautifulSoup to find the <head>, and then searches for a <script> whose src attribute points to the MathJax CDN. If it finds it, it replaces src with an updated src and rewrites the file.

from bs4 import BeautifulSoup as bs
old_cdn = 'https://cdn.mathjax.org/mathjax/latest/MathJax.js'
new_cdn = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.0/MathJax.js'
def update_mathjax(filename):
    with open(filename, 'r+') as file_handle:
        file_contents = file_handle.read()
        soup = bs(file_contents, "html5lib")
        scripts = soup.find('head').find_all('script')
        for script in scripts:
            if script.attrs and 'src' in script.attrs:
                if script.attrs['src'][:49] == old_cdn:
                        q = script.attrs['src'][49:]
                        new_src = new_cdn + q
                        script.attrs['src'] = new_src
                        file_handle.seek(0)
                        file_handle.write(soup.prettify())
                        file_handle.truncate()
                        print('udated ' + filename)

With that, it's reasonably easy to traverse the directory tree and apply the function.

import os
for directory_name, subdirectory_list, filename_list in os.walk(os.getcwd()):
    for filename in filename_list:
        if filename[-5:] == ".html":
            update_mathjax(os.path.join(directory_name, filename))


问:
Label ranges and colors in Python plot
In the following I'm trying to plot points with color and label that changes for every j. What I'm getting is different color and one label in the legend for every couple (i, j):

```<code>import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

primes = (139,149,151,157,163,167)
for j in range(50, 300, 10):
    col = next(g)
    for k in (primes):
        for l in range(10000, 20000, 500):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            plt.plot(l, end - start, linewidth = 2, marker='o', color=col)
</code>```

Edit: Updated the code with my original problem as I couldn't figure out if the solution from Ernest + Arya can work in this case.

答:
Isn't the second loop over i pretty useless?

```<code>import numpy as np
import matplotlib.pyplot as plt

for j in range (0, 2):
    x = np.arange(0,9,2)
    y = np.ones_like(x)*j + 0.5
    plt.plot(x,y, marker='o', label='$n = {j}$'.format(j=j))

plt.legend()
plt.show()
</code>```

Solution for updated question:

```<code>import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

for j in range (0, 2):
    col = next(g)
    x = np.arange(0,9,2)
    y = np.ones_like(x)*j + 0.5
    plt.plot(x,y, marker='o', color=col, label='$n = {j}$'.format(j=j))
plt.legend()
plt.show()
</code>```

Solution for second update; the idea is always the same: use as many calls to plt.plot() as you want to have different colors/legend entries.

```<code>import numpy as np
import matplotlib.pyplot as plt
import time

def generator(j,k,l):
    #some operation that takes a little time
    a = np.random.rand(k % 7, l-1000, j%13 )
    return a

color_list = ["blue", "brown", "red", "black"]

primes = (139,149,151,157,163,167)
for j in range(50, 300, 25):
    x = []; y = []
    for k in (primes):
        for l in range(10000, 20000, 1000):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            x.append(l); y.append(end - start)
    plt.plot(x,y, ls="", marker='o', label='$n = {j}$'.format(j=j))

plt.legend()
plt.show()
</code>```

Title: Label ranges and colors in Python plot

Body:
In the following I'm trying to plot points with color and label that changes for every j. What I'm getting is different color and one label in the legend for every couple (i, j):

import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

primes = (139,149,151,157,163,167)
for j in range(50, 300, 10):
    col = next(g)
    for k in (primes):
        for l in range(10000, 20000, 500):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            plt.plot(l, end - start, linewidth = 2, marker='o', color=col)

Edit: Updated the code with my original problem as I couldn't figure out if the solution from Ernest + Arya can work in this case.

Body:
Isn't the second loop over i pretty useless?

import numpy as np
import matplotlib.pyplot as plt

for j in range (0, 2):
    x = np.arange(0,9,2)
    y = np.ones_like(x)*j + 0.5
    plt.plot(x,y, marker='o', label='$n = {j}$'.format(j=j))

plt.legend()
plt.show()

Solution for updated question:

import itertools
import numpy as np
import matplotlib.pyplot as plt

color_list = ["blue", "brown", "red", "black"]
g = itertools.cycle(color_list)

for j in range (0, 2):
    col = next(g)
    x = np.arange(0,9,2)
    y = np.ones_like(x)*j + 0.5
    plt.plot(x,y, marker='o', color=col, label='$n = {j}$'.format(j=j))
plt.legend()
plt.show()

Solution for second update; the idea is always the same: use as many calls to plt.plot() as you want to have different colors/legend entries.

import numpy as np
import matplotlib.pyplot as plt
import time

def generator(j,k,l):
    #some operation that takes a little time
    a = np.random.rand(k % 7, l-1000, j%13 )
    return a

color_list = ["blue", "brown", "red", "black"]

primes = (139,149,151,157,163,167)
for j in range(50, 300, 25):
    x = []; y = []
    for k in (primes):
        for l in range(10000, 20000, 1000):
            start = time.time()
            generator(j, k, l)
            end = time.time()
            x.append(l); y.append(end - start)
    plt.plot(x,y, ls="", marker='o', label='$n = {j}$'.format(j=j))

plt.legend()
plt.show()


问:
How to do if-else in Thymeleaf?
What's the best way to do a simple if-else in Thymeleaf?

I want to achieve in Thymeleaf the same effect as

```<code><c:choose>
  <c:when test="${potentially_complex_expression}">
     <h2>Hello!</h2>
  </c:when>
  <c:otherwise>
     <span class="xxx">Something else</span>
  </c:otherwise>
</c:choose>
</code>```

in JSTL.

What I've figured so far:

Hello!

    Something else

```

I don't want to evaluate potentially_complex_expression twice. That's why I introduced local variable condition. Still I don't like using both th:if="${condition} and th:unless="${condition}".

An important thing is that I use two different HTML tags: let's say h2 and span.

Can you suggest a better way to achieve it?

答:
In simpler case (when html tags is the same):</p>

```<code><h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>
</code>```

Title: How to do if-else in Thymeleaf?

Body:
What's the best way to do a simple if-else in Thymeleaf?

I want to achieve in Thymeleaf the same effect as

<c:choose>
  <c:when test="${potentially_complex_expression}">

Hello!

  </c:when>
  <c:otherwise>
     Something else
  </c:otherwise>
</c:choose>

in JSTL.

What I've figured so far:

Hello!

    Something else

I don't want to evaluate potentially_complex_expression twice. That's why I introduced local variable condition. Still I don't like using both th:if="${condition} and th:unless="${condition}".

An important thing is that I use two different HTML tags: let's say h2 and span.

Can you suggest a better way to achieve it?

Body:
In simpler case (when html tags is the same):

<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>


问:
Retain Count Of Objects
I have a query in MRC in iOS & I am a little bit confuse. Suppose I have two objects ObjectA  & ObjectB of the same type with below retain count

ObjectA : retain count is 1

ObjectB : reatin count 0

Now I am performing operation

```<code>ObjectB = [ObjectA retain];
</code>```

Can anyone tell me what would be retained count of ObjectA & ObjectB?

As per my knowledge retain count of ObjectA = 2 & ObjectB = 1.

Please correct if I am wrong. If we are going to perform the copy operation, then what should be retained count.

答:
First of all you have to understand, that objectA and objectB are not (Objective-C) objects. They are references to objects. (Objects have retain counts, not references to objects.)

So, your situation is correctly:

objectA points to an object that has a RC of 1.

objectB points to an object that has a RC of 0.

The second sentence is a paradox: There is never an object with RC 0, because reaching a RC 0 would deallocate the object. So there is no object anymore. (In practice a RC of 0 is never reached, because the object is deallocated when the RC is going to be 0. But this is an implementation detail and therefore not important.)

The statement …

```<code>objectB = [objectA retain];
</code>```

… increases the RC of the object*, objectA points to. The return value of -retain is the value of the receiver pointer (objectA). This reference is then assigned to objectB. Therefore objectB – still being a reference – points to the same object, objectA points to. Since RCs are owned by the object, there is only one object and only one RC. It is 2.

Remark* Even it is documented that -retain increments the RC, this is not always that way. There are objects with eternal liefe time, having a virtual marker RC. However, I will keep the answer simple, so we assume that every execution of -retain increments the RC. But try this:

```<code>    id ref = @"RC";
    NSLog(@"%lu", [ref retainCount]);
    [ref retain];
    NSLog(@"%lu", [ref retainCount]);
</code>```

You get:

```<code>2017-04-01 22:09:21.214 reftest[74967:8550738] 18446744073709551615
2017-04-01 22:09:21.215 reftest[74967:8550738] 18446744073709551615
</code>```

Something increased? No.

But for the same reason you should never think in absolute values of RC ("a RC of 1"), but in changing a value at a location in source code: After a retain the RC is usually greater by 1 than it has been before. After a release the RC is usually less than 1 it has been before. Calculating a absolute value you have to consider all strong references to that object, what is impossible. And it is meaningless, because it is the strength of RC, that you think reference by reference instead of all references together.

Title: Retain Count Of Objects

Body:
I have a query in MRC in iOS & I am a little bit confuse. Suppose I have two objects ObjectA  & ObjectB of the same type with below retain count

ObjectA : retain count is 1

ObjectB : reatin count 0

Now I am performing operation

ObjectB = [ObjectA retain];

Can anyone tell me what would be retained count of ObjectA & ObjectB?

As per my knowledge retain count of ObjectA = 2 & ObjectB = 1.

Please correct if I am wrong. If we are going to perform the copy operation, then what should be retained count.

Body:
First of all you have to understand, that objectA and objectB are not (Objective-C) objects. They are references to objects. (Objects have retain counts, not references to objects.)

So, your situation is correctly:

objectA points to an object that has a RC of 1.

objectB points to an object that has a RC of 0.

The second sentence is a paradox: There is never an object with RC 0, because reaching a RC 0 would deallocate the object. So there is no object anymore. (In practice a RC of 0 is never reached, because the object is deallocated when the RC is going to be 0. But this is an implementation detail and therefore not important.)

The statement …

objectB = [objectA retain];

… increases the RC of the object*, objectA points to. The return value of -retain is the value of the receiver pointer (objectA). This reference is then assigned to objectB. Therefore objectB – still being a reference – points to the same object, objectA points to. Since RCs are owned by the object, there is only one object and only one RC. It is 2.

Remark* Even it is documented that -retain increments the RC, this is not always that way. There are objects with eternal liefe time, having a virtual marker RC. However, I will keep the answer simple, so we assume that every execution of -retain increments the RC. But try this:

    id ref = @"RC";
    NSLog(@"%lu", [ref retainCount]);
    [ref retain];
    NSLog(@"%lu", [ref retainCount]);

You get:

2017-04-01 22:09:21.214 reftest[74967:8550738] 18446744073709551615
2017-04-01 22:09:21.215 reftest[74967:8550738] 18446744073709551615

Something increased? No.

But for the same reason you should never think in absolute values of RC ("a RC of 1"), but in changing a value at a location in source code: After a retain the RC is usually greater by 1 than it has been before. After a release the RC is usually less than 1 it has been before. Calculating a absolute value you have to consider all strong references to that object, what is impossible. And it is meaningless, because it is the strength of RC, that you think reference by reference instead of all references together.


问:
How to display one row at a time ,when i click next display next row in php?
I created a page (exam.php) where I want to show questions one by one.

When a student clicks next after submitting an answer I want it to display the next question.

```<code> <?php
    if(!isset($_SESSION['qno']))
        $_SESSION['qno'] = 1;
    else{

        if(isset($_POST['next']))
        {
                $_SESSION['qno'] += 1;
        }

    }

    $sql ="select  * from question where question_id= ' ".$_SESSION['qno']." '  ";
    $query=mysql_query($sql);
    while($row = mysql_fetch_assoc($query))
    {
        $question =$row['question'];
        $op1 = $row['option1'];
        $op2 = $row['option2'];
        $op3 = $row['option3'];
        $op4 = $row['option4'];

    }

    ?>
</code>```

It works, but in this code I am using question_id to display data. The problem comes after, when admin deletes some questions it is not working due to question_id gap.

I initialize question_id =1; so what is best solution for this problem?

答:
You could use LIMIT to pick the question rather than question ID.</p>

```<code>select *
from `question`
ORDER BY `question_id`
LIMIT $SESSION[$q_no],1;
</code>```

Body:
I created a page (exam.php) where I want to show questions one by one.

When a student clicks next after submitting an answer I want it to display the next question.

 <?php
    if(!isset($_SESSION['qno']))
        $_SESSION['qno'] = 1;
    else{

        if(isset($_POST['next']))
        {
                $_SESSION['qno'] += 1;
        }

    }

    $sql ="select  * from question where question_id= ' ".$_SESSION['qno']." '  ";
    $query=mysql_query($sql);
    while($row = mysql_fetch_assoc($query))
    {
        $question =$row['question'];
        $op1 = $row['option1'];
        $op2 = $row['option2'];
        $op3 = $row['option3'];
        $op4 = $row['option4'];

    }

    ?>

It works, but in this code I am using question_id to display data. The problem comes after, when admin deletes some questions it is not working due to question_id gap.

I initialize question_id =1; so what is best solution for this problem?

Body:
You could use LIMIT to pick the question rather than question ID.

select *
from `question`
ORDER BY `question_id`
LIMIT $SESSION[$q_no],1;