问:
Express - How to validate file input with express-validator?
I am using express-validator for validation. In my controller I have a method for adding new pictures to the database. Here is my code:

```<code>function createPicture(req, res) {

req.checkBody('title', `The title can't be empty.`).notEmpty();
req.checkBody('image', 'You must select an image.').notEmpty();

let errors = req.validationErrors();

if (errors) {
    res.json({errors: errors});
} else { ... }
</code>```

The code works for the title field however no matter if I select an image or not - I still get a validation error about it. How can I validate file input? I just want it to be required.

答:
I had the same problem, the below code will not work since express-validator only validates strings

```<code>req.checkBody('title', 'The title can't be empty.').notEmpty();

req.checkBody('image', 'You must select an image.').notEmpty();
</code>```

You'll need to write a custom validator, express-validator allows for this, okay this is an example of one

```<code>//requiring the validator
var expressValidator = require('express-validator');
//the app use part
app.use(expressValidator({
customValidators: {
    isImage: function(value, filename) {

        var extension = (path.extname(filename)).toLowerCase();
        switch (extension) {
            case '.jpg':
                return '.jpg';
            case '.jpeg':
                return '.jpeg';
            case  '.png':
                return '.png';
            default:
                return false;
        }
    }
}}));
</code>```

To use the custom validator, do this first to make sure empty files will not throw undefined error:

```<code>restLogo = typeof req.files['rest_logo'] !== "undefined" ? req.files['rest_logo'][0].filename : '';
</code>```

Finally to use your custom validator:

```<code>req.checkBody('rest_logo', 'Restaurant Logo - Please upload an image Jpeg, Png or Gif').isImage(restLogo);
</code>```

Thanks for your question, hope this will help someone

Body:
I am using express-validator for validation. In my controller I have a method for adding new pictures to the database. Here is my code:

function createPicture(req, res) {

req.checkBody('title', `The title can't be empty.`).notEmpty();
req.checkBody('image', 'You must select an image.').notEmpty();

let errors = req.validationErrors();

if (errors) {
    res.json({errors: errors});
} else { ... }

The code works for the title field however no matter if I select an image or not - I still get a validation error about it. How can I validate file input? I just want it to be required.

Body:
I had the same problem, the below code will not work since express-validator only validates strings

req.checkBody('title', 'The title can't be empty.').notEmpty();

req.checkBody('image', 'You must select an image.').notEmpty();

You'll need to write a custom validator, express-validator allows for this, okay this is an example of one

//requiring the validator
var expressValidator = require('express-validator');
//the app use part
app.use(expressValidator({
customValidators: {
    isImage: function(value, filename) {

        var extension = (path.extname(filename)).toLowerCase();
        switch (extension) {
            case '.jpg':
                return '.jpg';
            case '.jpeg':
                return '.jpeg';
            case  '.png':
                return '.png';
            default:
                return false;
        }
    }
}}));

To use the custom validator, do this first to make sure empty files will not throw undefined error:

restLogo = typeof req.files['rest_logo'] !== "undefined" ? req.files['rest_logo'][0].filename : '';

Finally to use your custom validator:

req.checkBody('rest_logo', 'Restaurant Logo - Please upload an image Jpeg, Png or Gif').isImage(restLogo);

Thanks for your question, hope this will help someone

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
How to access classes with on one instance?
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

```<code>generalService.AbcService.MethodName();
generalService.AbcService.MethodName();
</code>```

How do I do this in the best possible way?

答:
Create service layer so that other componentns can access easily.</p>

```<code>public class Program
{
    static void Main(string[] args)
    {
        Global.ServiceABC.MethodA();
        Global.ServiceXYZ.MethodB();
    }
}

public class Global
{
    private static ABC serviceABC;
    public static ABC ServiceABC  { get
        {
            if (serviceABC == null)
            {
                serviceABC = new ABC();
            }
            return serviceABC;
        }
    }

    private static XYZ serviceXYZ;
    public static XYZ ServiceXYZ
    {
        get
        {
            if (serviceXYZ == null)
            {
                serviceXYZ = new XYZ();
            }
            return serviceXYZ;
        }
    }
}

public class ABC
{
    public void MethodA() { }
}

public class XYZ
{
    public void MethodB() { }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have multiple classes in the service layer of my app.
Let's say I need to access some method from AbcService.cs in my controller. Then, I need to access some method from XyzService.cs in the same controller. Then another.......For this, I would need to create an object of each Service class separately in the constructor. Also, if I needed to access these methods in another cntroller I would again have to create objects of AbcService, XyzService, etc. I want to have one instance that can give me access to methods of all service classes.
Something like:

generalService.AbcService.MethodName();
generalService.AbcService.MethodName();

How do I do this in the best possible way?

Body:
Create service layer so that other componentns can access easily.

public class Program
{
    static void Main(string[] args)
    {
        Global.ServiceABC.MethodA();
        Global.ServiceXYZ.MethodB();
    }
}

public class Global
{
    private static ABC serviceABC;
    public static ABC ServiceABC  { get
        {
            if (serviceABC == null)
            {
                serviceABC = new ABC();
            }
            return serviceABC;
        }
    }

    private static XYZ serviceXYZ;
    public static XYZ ServiceXYZ
    {
        get
        {
            if (serviceXYZ == null)
            {
                serviceXYZ = new XYZ();
            }
            return serviceXYZ;
        }
    }
}

public class ABC
{
    public void MethodA() { }
}

public class XYZ
{
    public void MethodB() { }
}


问:
How to properly insert an object into a List in Java?
In this code, are there any differences between these two ways to insert an element into a list in Java?  If so, what are they? And what way should I use when inserting an element into a list?

```<code>List<MyClass>myList=new ArrayList<MyClass>();

myList.add(new MyClass());

MyClass foo=new MyClass();
myList.add(foo);
</code>```

I'm a beginner in Java. I'm really sorry if you find this question obvious or non-sense.

答:
No, there is no difference. You should do what you find the most readable. The second one is necessary when you need to do something with the object in addition to adding it to the list.

Note that Java is case-sensitive, and that classes conventionally start with an uppercase letter.

Body:
In this code, are there any differences between these two ways to insert an element into a list in Java?  If so, what are they? And what way should I use when inserting an element into a list?

List<MyClass>myList=new ArrayList<MyClass>();

myList.add(new MyClass());

MyClass foo=new MyClass();
myList.add(foo);

I'm a beginner in Java. I'm really sorry if you find this question obvious or non-sense.


问:
Spark 1.6 vs spark 2.0 productivity
Databricks team has talked a lot about why spark 2.x is faster than 1.6.
But why operating on DataFrames in spark 2.x it can produce lower level bytecode? Why was it impossible with RDD API?

Also why is it so important to make Tungsten only from 2.0? What's wrong with doing it in spark 1.6?

Spark 2.0 impruvments

答:
For starters the first "Tungsten" optimizations have been introduced in Spark 1.4 and extended in 1.5 and 1.6.

Spark 2.0 introduces backward incompatible changes which wouldn't be acceptable in 1.x due to project management policy.

Structured data and restricted language requires simpler optimization rules. This is why linear algebra libraries or relational databases feature very aggressive optimizations, and your-arbitrary-code doesn't.

It is impossible with RDD API for the same reason why your-favorite-compiler™ doesn't apply the same optimizations out-of-the-box. It is close to mpossible to do it right (have you noticed that code used with Dataframe has to be deterministic and has to contribute to execution plan, otherwise will be eliminated?).

Title: Spark 1.6 vs spark 2.0 productivity


问:
How to convert sql limit query to linq lambda?
Here's an example that I want to convert to lambda query:</p>

```<code>SELECT TOP(5) Pbschedules.s_id, Pbschedules.date, Pbworth2.worth, Pbschedules.pb_id
FROM Pbschedules INNER JOIN Pbworth2 ON Pbschedules.pb_id = Pbworth2.pb_id
ORDER BY s_id desc
</code>```

答:
```<code>var myData = (from valuesPbs in Pbschedules join valuesPbw in Pbworth2
              on valuesPbs.pb_id equals valuesPbw.pb_id
              orderby valuesPbs.s_id descending
              select valuesPbs
             ).Take(5);
</code>```

Body:
Here's an example that I want to convert to lambda query:

SELECT TOP(5) Pbschedules.s_id, Pbschedules.date, Pbworth2.worth, Pbschedules.pb_id
FROM Pbschedules INNER JOIN Pbworth2 ON Pbschedules.pb_id = Pbworth2.pb_id
ORDER BY s_id desc


问:
Cannot add activity in Android Studio
I completed the Firebase Friendly Chat tutorial (https://codelabs.developers.google.com/codelabs/firebase-android/#0) and the chat runs fine. I am trying to expand it by adding a new activity: app, New, Activity, Empty Activity. Immediately after the activity is added I get this gradle build error:

```<code>Error:(46, 0) Could not get unknown property 'compile' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
<a href="openFile:C:\Users\apand\AndroidStudioProjects\android-startPure\play\app\build.gradle">Open File</a>
</code>```

This also error also occurs with the beginning tutorial code (android-start). How do I fix this so that another activity can be added to this code?

Here is the build.gradle code from the module:

```<code>apply plugin: 'com.android.application'
repositories {
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
    applicationId "com.google.firebase.codelab.friendlychat"
    minSdkVersion 14
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile
    'com.android.support:design:25.1.1'compile
    'com.github.bumptech.glide:glide:3.7.0'compile
    'de.hdodenhof:circleimageview:1.3.0'compile
    'com.android.support:appcompat-v7:25.1.1'compile
    'com.google.android.gms:play-services-auth:10.2.0'compile
'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-config:10.2.0'
    compile 'com.google.android.gms:play-services-appinvite:10.2.0'
    compile 'com.google.firebase:firebase-messaging:10.2.0'
    compile 'com.google.android.gms:play-services-ads:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-appindexing:10.2.0'
    compile 'com.firebaseui:firebase-ui-database:0.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support:support-annotations:25.1.1'
}
apply plugin: 'com.google.gms.google-services'
</code>```

答:
The problem is in the dependencies block of the build.gradle.

Try replacing it with

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:design:25.1.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-config:10.2.0'
    compile 'com.google.android.gms:play-services-appinvite:10.2.0'
    compile 'com.google.firebase:firebase-messaging:10.2.0'
    compile 'com.google.android.gms:play-services-ads:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-appindexing:10.2.0'
    compile 'com.firebaseui:firebase-ui-database:0.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    androidTestCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support:support-annotations:25.1.1'
}
</code>```

Title: Cannot add activity in Android Studio

Body:
I completed the Firebase Friendly Chat tutorial (https://codelabs.developers.google.com/codelabs/firebase-android/#0) and the chat runs fine. I am trying to expand it by adding a new activity: app, New, Activity, Empty Activity. Immediately after the activity is added I get this gradle build error:

Error:(46, 0) Could not get unknown property 'compile' for object of type org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.
Open File

This also error also occurs with the beginning tutorial code (android-start). How do I fix this so that another activity can be added to this code?

Here is the build.gradle code from the module:

apply plugin: 'com.android.application'
repositories {
    mavenLocal()
    flatDir {
        dirs 'libs'
    }
}
android {
compileSdkVersion 25
buildToolsVersion "25.0.0"
defaultConfig {
    applicationId "com.google.firebase.codelab.friendlychat"
    minSdkVersion 14
    targetSdkVersion 25
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE-FIREBASE.txt'
        exclude 'META-INF/NOTICE'
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile
    'com.android.support:design:25.1.1'compile
    'com.github.bumptech.glide:glide:3.7.0'compile
    'de.hdodenhof:circleimageview:1.3.0'compile
    'com.android.support:appcompat-v7:25.1.1'compile
    'com.google.android.gms:play-services-auth:10.2.0'compile
'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-config:10.2.0'
    compile 'com.google.android.gms:play-services-appinvite:10.2.0'
    compile 'com.google.firebase:firebase-messaging:10.2.0'
    compile 'com.google.android.gms:play-services-ads:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-appindexing:10.2.0'
    compile 'com.firebaseui:firebase-ui-database:0.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support:support-annotations:25.1.1'
}
apply plugin: 'com.google.gms.google-services'

Body:
The problem is in the dependencies block of the build.gradle.

Try replacing it with

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:design:25.1.1'
    compile 'com.github.bumptech.glide:glide:3.7.0'
    compile 'de.hdodenhof:circleimageview:1.3.0'
    compile 'com.android.support:appcompat-v7:25.1.1'
    compile 'com.google.android.gms:play-services-auth:10.2.0'
    compile 'com.google.firebase:firebase-database:10.2.0'
    compile 'com.google.firebase:firebase-storage:10.2.0'
    compile 'com.google.firebase:firebase-auth:10.2.0'
    compile 'com.google.firebase:firebase-config:10.2.0'
    compile 'com.google.android.gms:play-services-appinvite:10.2.0'
    compile 'com.google.firebase:firebase-messaging:10.2.0'
    compile 'com.google.android.gms:play-services-ads:10.2.0'
    compile 'com.google.firebase:firebase-crash:10.2.0'
    compile 'com.google.firebase:firebase-appindexing:10.2.0'
    compile 'com.firebaseui:firebase-ui-database:0.4.0'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    testCompile 'junit:junit:4.12'
    androidTestCompile 'junit:junit:4.12'
    androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
    androidTestCompile 'com.android.support.test:runner:0.5'
    androidTestCompile 'com.android.support:support-annotations:25.1.1'
}


问:
Passing data to input tag in bootstrap modal
I'm working in a J2EE project and I had a problem that ruined my life :v I already worked with bootstrap and I already used bootstrap modal and passing data to modal, but this time, when I use the same code, it doesn't work.

PS: in the snippet it works, it means the code is right, but in my project it doesn't. what does it mean.

$(".modal-link").click(function() {
  $("#descr").attr('value', $(this).attr('descr'));
  $($(this).attr('href')).modal('show');
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>

<div class='modal small fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
  <div class='modal-dialog'>
    <div class='modal-content'>
      <div class='modal-header'>
        <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
        <h3 id='myModalLabel'>Detail</h3>
      </div>
      <div class='modal-body' id="Details">
        <input id="descr" name="descr" value="" />
      </div>
      <div class='modal-footer'>
        <button class='btn btn-default' data-dismiss='modal' aria-hidden='true'>Fermer</button>
      </div>
    </div>
  </div>
</div>

<div class="row">
  <c:forEach items='${liste}' var='p'>
    <div class="col-sm-6 col-md-4">
      <div class="media services-wrap wow fadeInDown">
        <div class="pull-left">

        </div>
        <div class="media-body">
          <h3 class="media-heading">${p.getMarque()}</h3>
          <p id="des">${p.getDescr()}</p>
        </div>

          <i class="glyphicon glyphicon-eye-open">View</i>

      </div>
    </div>
  </c:forEach>
</div></code>```

答:
EDIT: Never mind my post. You already figured out the issue is not with your javascript or mark up.

Your code seems to be working fine so the issue apparently is else where.
I only took out the foreach loop and variables and hard coded the descriptions. The input inside the modal are populated with different description depending on link pressed. By the way you don't need to explicitly open the modal with .show().

$(".modal-link").click(function() {

  $("#descr").attr("value", $(this).attr('descr'));
  //$($(this).attr('href')).modal('show');

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class='modal small fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
  <div class='modal-dialog'>
    <div class='modal-content'>
      <div class='modal-header'>
        <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
        <h3 id='myModalLabel'>Detail</h3>
      </div>
      <div class='modal-body' id="Details">
        <input id="descr" name="descr" value="" />
      </div>
      <div class='modal-footer'>
        <button class='btn btn-default' data-dismiss='modal' aria-hidden='true'>Fermer</button>

      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-6 col-md-4">
    <div class="media services-wrap wow fadeInDown">
      <div class="pull-left">

      </div>
      <div class="media-body">

      </div>

        <i class="glyphicon glyphicon-eye-open">View</i>

    </div>
  </div>
<div class="col-sm-6 col-md-4">
    <div class="media services-wrap wow fadeInDown">
      <div class="pull-left">

      </div>
      <div class="media-body">

      </div>

        <i class="glyphicon glyphicon-eye-open">View</i>

    </div>
  </div>

</div></code>```

Body:
I'm working in a J2EE project and I had a problem that ruined my life :v I already worked with bootstrap and I already used bootstrap modal and passing data to modal, but this time, when I use the same code, it doesn't work.

PS: in the snippet it works, it means the code is right, but in my project it doesn't. what does it mean.

$(".modal-link").click(function() {
  $("#descr").attr('value', $(this).attr('descr'));
  $($(this).attr('href')).modal('show');
});

<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />

        <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>

Detail

        <input id="descr" name="descr" value="" />

        <button class='btn btn-default' data-dismiss='modal' aria-hidden='true'>Fermer</button>

  <c:forEach items='${liste}' var='p'>

${p.getMarque()}

${p.getDescr()}

          View

  </c:forEach>

Body:
EDIT: Never mind my post. You already figured out the issue is not with your javascript or mark up.

Your code seems to be working fine so the issue apparently is else where.
I only took out the foreach loop and variables and hard coded the descriptions. The input inside the modal are populated with different description depending on link pressed. By the way you don't need to explicitly open the modal with .show().

$(".modal-link").click(function() {

  $("#descr").attr("value", $(this).attr('descr'));
  //$($(this).attr('href')).modal('show');

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

<div class='modal small fade' id='myModal' tabindex='-1' role='dialog' aria-labelledby='myModalLabel' aria-hidden='true'>
  <div class='modal-dialog'>
    <div class='modal-content'>
      <div class='modal-header'>
        <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>
        <h3 id='myModalLabel'>Detail</h3>
      </div>
      <div class='modal-body' id="Details">
        <input id="descr" name="descr" value="" />
      </div>
      <div class='modal-footer'>
        <button class='btn btn-default' data-dismiss='modal' aria-hidden='true'>Fermer</button>

      </div>
    </div>
  </div>
</div>

<div class="row">
  <div class="col-sm-6 col-md-4">
    <div class="media services-wrap wow fadeInDown">
      <div class="pull-left">

      </div>
      <div class="media-body">

      </div>
      <a href="#myModal" class="modal-link" var descr="Description 1" role='button' data-toggle='modal'>
        <i class="glyphicon glyphicon-eye-open">View</i>
      </a>
    </div>
  </div>
<div class="col-sm-6 col-md-4">
    <div class="media services-wrap wow fadeInDown">
      <div class="pull-left">

      </div>
      <div class="media-body">

      </div>
      <a href="#myModal" class="modal-link" var descr="Description 2" role='button' data-toggle='modal'>
        <i class="glyphicon glyphicon-eye-open">View</i>
      </a>
    </div>
  </div>

</div>


答:
There's not any difference to the list.

The only difference is that in the second version, the following code has a reference to the added object, so you can do something with it (eg pass it to some other code or call methods on the object etc).

Title: How to properly insert an object into a List in Java?


问:
Rails ActiveAdmin modify resource object
I've currently got a user object but to avoid redundancy, I'd like to wrap it into a presenter object called MerchantUser/ProviderUser. However, with ActiveAdmin, I'm a little confused on how to do this. I've tried using before_create to change the user into the corresponding presenters but in index...do, I'm still seeing that user.class is equal to User and not the wrapper classes that I've defined.

I've looked into scoping_collection but unfortunately that only works on collections and not individual objects?

```<code> ActiveAdmin.register User, as: "Companies" do # rubocop:disable Metrics/BlockLength
  before_create do |user|
    if user.merchant?
      user = MerchantUser.new(user)
    else
      user = ProviderUser.new(user)
    end
  end

  actions :all, except: [:destroy]
  permit_params :name, :email, contract_attributes: [:id, :flat_rate, :percentage]

  filter :role, as: :select
  index do # rubocop:disable Metrics/BlockLength
    column :name do |user|
      user.name <---I want it so I can just do this without the if/else blocks like below.
    end
    column :role
    column :contact_phone
    column :email
    column :website do |user|
      if user.merchant?
        user.company.website
      else
        user.provider.website
      end
    end

    column :flat_rate do |user|
      money_without_cents_and_with_symbol(user.contract.flat_rate)
    end
    column :percentage do |user|
      number_to_percentage(user.contract.percentage, precision: 0)
    end
    actions
  end
</code>```

答: Are you sure you want/need a presenter here?  You can register the same Rails model multiple times as ActiveAdmin resources with different names and customizations (filters, index page, forms, etc).  You can also use Rails STI or just subclass Rails models, perhaps with different Rails default_scope and then register the subclasses.</p>

Body:
I've currently got a user object but to avoid redundancy, I'd like to wrap it into a presenter object called MerchantUser/ProviderUser. However, with ActiveAdmin, I'm a little confused on how to do this. I've tried using before_create to change the user into the corresponding presenters but in index...do, I'm still seeing that user.class is equal to User and not the wrapper classes that I've defined.

I've looked into scoping_collection but unfortunately that only works on collections and not individual objects?

 ActiveAdmin.register User, as: "Companies" do # rubocop:disable Metrics/BlockLength
  before_create do |user|
    if user.merchant?
      user = MerchantUser.new(user)
    else
      user = ProviderUser.new(user)
    end
  end

  actions :all, except: [:destroy]
  permit_params :name, :email, contract_attributes: [:id, :flat_rate, :percentage]

  filter :role, as: :select
  index do # rubocop:disable Metrics/BlockLength
    column :name do |user|
      user.name <---I want it so I can just do this without the if/else blocks like below.
    end
    column :role
    column :contact_phone
    column :email
    column :website do |user|
      if user.merchant?
        user.company.website
      else
        user.provider.website
      end
    end

    column :flat_rate do |user|
      money_without_cents_and_with_symbol(user.contract.flat_rate)
    end
    column :percentage do |user|
      number_to_percentage(user.contract.percentage, precision: 0)
    end
    actions
  end


问:
more intuitive way to fill up three elements right of diagonal vectors
I need to fill up the matrix in the figure. My way is to use the loop which is not east to read. When the dimension is large, it not efficient too.
Is there any way to make it easier to read and probably quicker (say using vectorization or some function I don't know?)

```<code># The code is in python, but I am open to R as well.
    S=6
    p=[0.1,0.3,0.6] # the pi in the figure
    # The reason I use loop for p is that it handles a flexible dimension of p
    mat = np.zeros((S, S))
    p = np.array(p)
    for i in range(S):
        for j, x in enumerate(p):
                if i + j < S-1:
                    mat[i+j][i] = x

                elif i + j == S-1:
                    mat[S-1][i] = p[j:].sum()
                else:
                    pass

    mat.T
</code>```

Body:
I need to fill up the matrix in the figure. My way is to use the loop which is not east to read. When the dimension is large, it not efficient too.
Is there any way to make it easier to read and probably quicker (say using vectorization or some function I don't know?)

# The code is in python, but I am open to R as well.
    S=6
    p=[0.1,0.3,0.6] # the pi in the figure
    # The reason I use loop for p is that it handles a flexible dimension of p
    mat = np.zeros((S, S))
    p = np.array(p)
    for i in range(S):
        for j, x in enumerate(p):
                if i + j < S-1:
                    mat[i+j][i] = x

                elif i + j == S-1:
                    mat[S-1][i] = p[j:].sum()
                else:
                    pass

    mat.T

Body:
Here is an example - fill in the values you need (and adjust the final column)...

mat <- matrix(0,nrow=10,ncol=10)
diag(mat) <- 1
diag(mat[1:(ncol(mat)-1),-1]) <- 2
diag(mat[1:(ncol(mat)-2),-(1:2)]) <- 3

mat
      [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
 [1,]    1    2    3    0    0    0    0    0    0     0
 [2,]    0    1    2    3    0    0    0    0    0     0
 [3,]    0    0    1    2    3    0    0    0    0     0
 [4,]    0    0    0    1    2    3    0    0    0     0
 [5,]    0    0    0    0    1    2    3    0    0     0
 [6,]    0    0    0    0    0    1    2    3    0     0
 [7,]    0    0    0    0    0    0    1    2    3     0
 [8,]    0    0    0    0    0    0    0    1    2     3
 [9,]    0    0    0    0    0    0    0    0    1     2
[10,]    0    0    0    0    0    0    0    0    0     1


问:
Rotating a CAShapeLayer arc about its center using CABasicAnimation
I have an arc that I have drawn using CAShapeLayer and I want it to rotate around the circle's center. I am trying to get this animation using a CABasicAnimation on the 'transform.rotation' property. But the rotation seems is happening about a point that is not the same as the circle's center.

```<code>-(void)drawRect:(CGRect)rect{
 int radius = 100;
 CAShapeLayer *circle = [CAShapeLayer layer];
 circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
 circle.fillColor = [UIColor orangeColor].CGColor;
 circle.strokeColor = [UIColor blueColor].CGColor;
 circle.lineWidth = 5;
 circle.strokeStart = 0.0f;
 circle.strokeEnd = 0.1f;
 [self.layer addSublayer:circle];

 CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
 spinAnimation.byValue = [NSNumber numberWithFloat:2.0f*M_PI];
 spinAnimation.duration = 4;
 spinAnimation.repeatCount = INFINITY;
 [circle addAnimation:spinAnimation forKey:@"indeterminateAnimation"];
}
</code>```

I know its an old problem, but whats the way out. I have tinkered a lot by setting the layer's bounds or the anchor point but it doesn't rotate about the center yet.

```<code>circle.bounds = self.frame;
</code>```

Here is how I add the view to the view controller.

```<code>[self.view addSubview:[[ProgressIndicator alloc] initWithFrame:CGRectMake(50, 50, 200, 200)]];
</code>```

答:
Think is better to do something like this)

```<code>CGFloat center = CGRectGetWidth(frame) / 2;
CGFloat lineWidth = 5;
CGFloat radius = center - lineWidth / 2;
CGRect bounds = frame;
bounds.origin = CGPointZero;

CAShapeLayer *spinLayer = [CAShapeLayer layer];
spinLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(center, center) radius:radius startAngle:0 endAngle:0.2 clockwise:YES].CGPath;
spinLayer.fillColor = [UIColor clearColor].CGColor;
spinLayer.strokeColor = [UIColor blueColor].CGColor;
spinLayer.lineWidth = 5;
spinLayer.lineCap = kCALineCapRound;
spinLayer.bounds = bounds;
spinLayer.position = CGPointMake(center, center);
[self.layer insertSublayer:spinLayer above:nil];
</code>```

And animation:

```<code>CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
animation.byValue = [NSNumber numberWithFloat:2.f * M_PI];
animation.duration = 1.5f;
animation.repeatCount = INFINITY;
[spinLayer addAnimation:animation forKey:@"lineRotation"];
[self setNeedsLayout];
</code>```

Swift 3

```<code>        var bounds = frame
        bounds.origin = CGPoint.zero
        let center: CGFloat = frame.size.width
        let lineWidth: CGFloat = 5
        let radius = center - lineWidth / 2

        let spinLayer = CAShapeLayer()
        spinLayer.path = UIBezierPath(arcCenter: CGPoint(x: center, y: center),
                                 radius: radius,
                                 startAngle: 0,
                                 endAngle: 0.2,
                                 clockwise: true).cgPath

        spinLayer.strokeColor = UIColor.blue.cgColor
        spinLayer.fillColor = UIColor.clear.cgColor
        spinLayer.lineWidth = lineWidth
        spinLayer.lineCap = kCALineCapRound
        spinLayer.bounds = bounds
        spinLayer.position = CGPoint(x: center, y: center)

        view.layer.insertSublayer(spinLayer, above: nil)

        let rotation = CABasicAnimation(keyPath: "transform.rotation")
        rotation.byValue = NSNumber(value: 2*M_PI as Double)
        rotation.duration = 1
        rotation.repeatCount = Float.infinity

        spinLayer.add(rotation, forKey: "lineRotation")
</code>```

Body:
I have an arc that I have drawn using CAShapeLayer and I want it to rotate around the circle's center. I am trying to get this animation using a CABasicAnimation on the 'transform.rotation' property. But the rotation seems is happening about a point that is not the same as the circle's center.

-(void)drawRect:(CGRect)rect{
 int radius = 100;
 CAShapeLayer *circle = [CAShapeLayer layer];
 circle.path = [UIBezierPath bezierPathWithRoundedRect:CGRectMake(0, 0, 2.0*radius, 2.0*radius) cornerRadius:radius].CGPath;
 circle.fillColor = [UIColor orangeColor].CGColor;
 circle.strokeColor = [UIColor blueColor].CGColor;
 circle.lineWidth = 5;
 circle.strokeStart = 0.0f;
 circle.strokeEnd = 0.1f;
 [self.layer addSublayer:circle];

 CABasicAnimation *spinAnimation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
 spinAnimation.byValue = [NSNumber numberWithFloat:2.0f*M_PI];
 spinAnimation.duration = 4;
 spinAnimation.repeatCount = INFINITY;
 [circle addAnimation:spinAnimation forKey:@"indeterminateAnimation"];
}

I know its an old problem, but whats the way out. I have tinkered a lot by setting the layer's bounds or the anchor point but it doesn't rotate about the center yet.

circle.bounds = self.frame;

Here is how I add the view to the view controller.

[self.view addSubview:[[ProgressIndicator alloc] initWithFrame:CGRectMake(50, 50, 200, 200)]];

Body:
Think is better to do something like this)

CGFloat center = CGRectGetWidth(frame) / 2;
CGFloat lineWidth = 5;
CGFloat radius = center - lineWidth / 2;
CGRect bounds = frame;
bounds.origin = CGPointZero;

CAShapeLayer *spinLayer = [CAShapeLayer layer];
spinLayer.path = [UIBezierPath bezierPathWithArcCenter:CGPointMake(center, center) radius:radius startAngle:0 endAngle:0.2 clockwise:YES].CGPath;
spinLayer.fillColor = [UIColor clearColor].CGColor;
spinLayer.strokeColor = [UIColor blueColor].CGColor;
spinLayer.lineWidth = 5;
spinLayer.lineCap = kCALineCapRound;
spinLayer.bounds = bounds;
spinLayer.position = CGPointMake(center, center);
[self.layer insertSublayer:spinLayer above:nil];

And animation:

CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
animation.byValue = [NSNumber numberWithFloat:2.f * M_PI];
animation.duration = 1.5f;
animation.repeatCount = INFINITY;
[spinLayer addAnimation:animation forKey:@"lineRotation"];
[self setNeedsLayout];

Swift 3

        var bounds = frame
        bounds.origin = CGPoint.zero
        let center: CGFloat = frame.size.width
        let lineWidth: CGFloat = 5
        let radius = center - lineWidth / 2

        let spinLayer = CAShapeLayer()
        spinLayer.path = UIBezierPath(arcCenter: CGPoint(x: center, y: center),
                                 radius: radius,
                                 startAngle: 0,
                                 endAngle: 0.2,
                                 clockwise: true).cgPath

        spinLayer.strokeColor = UIColor.blue.cgColor
        spinLayer.fillColor = UIColor.clear.cgColor
        spinLayer.lineWidth = lineWidth
        spinLayer.lineCap = kCALineCapRound
        spinLayer.bounds = bounds
        spinLayer.position = CGPoint(x: center, y: center)

        view.layer.insertSublayer(spinLayer, above: nil)

        let rotation = CABasicAnimation(keyPath: "transform.rotation")
        rotation.byValue = NSNumber(value: 2*M_PI as Double)
        rotation.duration = 1
        rotation.repeatCount = Float.infinity

        spinLayer.add(rotation, forKey: "lineRotation")


问:
remove specific string in python2.7
I have a list as follows:

```<code>>>> header
['Id', ["['GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']"]]
>>> type(header)
list
</code>```

And, how can I change it to a string as follows;

```<code>['Id','GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']
</code>```

I'm try used re.split('\[|\]|\"',str(header)) . But the resulted is not I want to get.

```<code>['',
 "'Id', ",
 '',
 '',
 "'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt'",
 '',
 '',
 '',
 '']
</code>```

So, any suggestion is hope.

答:
How about using regular expressions?</p>

```<code>In [1]: import re
In [2]: re.findall("[A-Za-z0-9_\.]+", str(header))
Out[2]: ['Id', 'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']
</code>```

Title: remove specific string in python2.7

Body:
I have a list as follows:

>>> header
['Id', ["['GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']"]]
>>> type(header)
list

And, how can I change it to a string as follows;

['Id','GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']

I'm try used re.split('\[|\]|\"',str(header)) . But the resulted is not I want to get.

['',
 "'Id', ",
 '',
 '',
 "'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt'",
 '',
 '',
 '',
 '']

So, any suggestion is hope.

Body:
How about using regular expressions?

In [1]: import re
In [2]: re.findall("[A-Za-z0-9_\.]+", str(header))
Out[2]: ['Id', 'GSM1172844_184A1.txt', 'GSM1384316_MDAMB453.txt']


答:
You are incorrectly using attr() method. Use prop().

```<code>$(".modal-link").click(function() {
  $("#descr").prop('value', $(this).attr('descr'));
  $($(this).attr('href')).modal('show');
});
</code>```

Read more on attr(). The most important part is:

Nevertheless, the most important concept to remember about the checked
  attribute is that it does not correspond to the checked property. The
  attribute actually corresponds to the defaultChecked property and
  should be used only to set the initial value of the checkbox. The
  checked attribute value does not change with the state of the
  checkbox, while the checked property does. Therefore, the
  cross-browser-compatible way to determine if a checkbox is checked is
  to use the property

The same is true for other dynamic attributes, such as selected and value.

In other words attr() method only changes default value of the attribute (value in this case). If you change input value and try to use attr() method to change it, it won't work because default value != current value. To change current value you have to use prop() or val() methods.

Title: Passing data to input tag in bootstrap modal

Body:
You are incorrectly using attr() method. Use prop().

$(".modal-link").click(function() {
  $("#descr").prop('value', $(this).attr('descr'));
  $($(this).attr('href')).modal('show');
});

Read more on attr(). The most important part is:

Nevertheless, the most important concept to remember about the checked
  attribute is that it does not correspond to the checked property. The
  attribute actually corresponds to the defaultChecked property and
  should be used only to set the initial value of the checkbox. The
  checked attribute value does not change with the state of the
  checkbox, while the checked property does. Therefore, the
  cross-browser-compatible way to determine if a checkbox is checked is
  to use the property

The same is true for other dynamic attributes, such as selected and value.

In other words attr() method only changes default value of the attribute (value in this case). If you change input value and try to use attr() method to change it, it won't work because default value != current value. To change current value you have to use prop() or val() methods.


问:
Graphing with GUI
Using

```<code>x=-10:0.1:10
f=x+2
</code>```

in basic m-file works fine.

But now I am trying to draw a plot using GUI, and by inputing a function.
It gives me bunch of errors. Could anyone explain how I can give values to the y when I have the range of x set?

```<code>% --- Executes on button press in zimet.
function zimet_Callback(hObject, eventdata, handles)
% hObject    handle to zimet (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=-10:0.1:10;
f=inline(get(handles.vdj,'string'))
y(x)=f

axes(handles.axes)
plot(x,y)

color=get(handles.listbox, 'value')
switch color
    case 2
       set(plot(x,y),'color', 'r')
    case 3
        set(plot(x,y),'color', 'g')
    case 4
        set(plot(x,y),'color', 'b')
end

style=get(handles.popupmenu, 'value')
switch style
    case 2
        set(plot(x,y), 'linestyle','--')
    case 3
        set(plot(x,y), 'linestyle','-.')
    case 4
        set(plot(x,y), 'linestyle',':')
end
rezgis=get(handles.grid, 'value')
switch rezgis
    case 1
        grid on
    case 2
        grid off
end
</code>```

答:
Notice that according to the inline function documentation this function will be removed in future release; you can use, instead, anonymous functions (see below).

The inline function require, as input a string of characters while the get function returns the text of the edit box as a cellarray, therefore you have to convert it using the char function.

Also, once you have generated the inline object, it is you function, so you have to use it directly.

Using inline

You have to change your code this way:

```<code>x=-10:0.1:10;
% f=inline(get(handles.vdj,'string'))
% y(x)=f
f=inline(char(get(handles.vdj,'string')))
y=f(x)
axes(handles.axes)
ph=plot(x,y)
</code>```

Using an anonymous function

You can achieve the same result by using anonymous functions this way:

```<code>x=-10:0.1:10;
% Get the function as string
f_str=char(get(handles.vdj,'string'))
% add @(x) to the string you've got
f_str=['@(x) ' f_str ];
% Create the anonymous function
fh = str2func(f_str)
% Evaluate the anonymous function
y=fh(x)

axes(handles.axes)
ph=plot(x,y)
</code>```

Edit

You can fix the problem with the setting of the line color and style this way:

modify the call to plot by adding the return value (it is the handle to the plot (see above: ph=plot(x,y))

chance the calls to set by replacing the call to plot with the handle of the plot itself (the ph variable as above)

So, to change the color and the line style, in your switch section:

```<code>set(ph,'color','r')
set(ph,'linestyle','--')
</code>```

Hope this helps,

Qapla'

Title: Graphing with GUI

Body:
Using

x=-10:0.1:10
f=x+2

in basic m-file works fine.

But now I am trying to draw a plot using GUI, and by inputing a function.
It gives me bunch of errors. Could anyone explain how I can give values to the y when I have the range of x set?

% --- Executes on button press in zimet.
function zimet_Callback(hObject, eventdata, handles)
% hObject    handle to zimet (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
x=-10:0.1:10;
f=inline(get(handles.vdj,'string'))
y(x)=f

axes(handles.axes)
plot(x,y)

color=get(handles.listbox, 'value')
switch color
    case 2
       set(plot(x,y),'color', 'r')
    case 3
        set(plot(x,y),'color', 'g')
    case 4
        set(plot(x,y),'color', 'b')
end

style=get(handles.popupmenu, 'value')
switch style
    case 2
        set(plot(x,y), 'linestyle','--')
    case 3
        set(plot(x,y), 'linestyle','-.')
    case 4
        set(plot(x,y), 'linestyle',':')
end
rezgis=get(handles.grid, 'value')
switch rezgis
    case 1
        grid on
    case 2
        grid off
end

Body:
Notice that according to the inline function documentation this function will be removed in future release; you can use, instead, anonymous functions (see below).

The inline function require, as input a string of characters while the get function returns the text of the edit box as a cellarray, therefore you have to convert it using the char function.

Also, once you have generated the inline object, it is you function, so you have to use it directly.

Using inline

You have to change your code this way:

x=-10:0.1:10;
% f=inline(get(handles.vdj,'string'))
% y(x)=f
f=inline(char(get(handles.vdj,'string')))
y=f(x)
axes(handles.axes)
ph=plot(x,y)

Using an anonymous function

You can achieve the same result by using anonymous functions this way:

x=-10:0.1:10;
% Get the function as string
f_str=char(get(handles.vdj,'string'))
% add @(x) to the string you've got
f_str=['@(x) ' f_str ];
% Create the anonymous function
fh = str2func(f_str)
% Evaluate the anonymous function
y=fh(x)

axes(handles.axes)
ph=plot(x,y)

Edit

You can fix the problem with the setting of the line color and style this way:

modify the call to plot by adding the return value (it is the handle to the plot (see above: ph=plot(x,y))

chance the calls to set by replacing the call to plot with the handle of the plot itself (the ph variable as above)

So, to change the color and the line style, in your switch section:

set(ph,'color','r')
set(ph,'linestyle','--')

Hope this helps,

Qapla'


问:
Initialization of a Static Map: null value returned
Following the answers of this question: How can I initialise a static Map? I'm trying to create a static Map in my project.
 Below a code snippet:

```<code>public class MyClass {

    public static final Map<String, String> dataMap;

    static {
        Map<String, String> tempMap = new HashMap<String, String>();
        try {
           // Getting a string value from a file, e.g. String data
           String data = "data";
           tempMap.put("firstData", data);
        }
        catch(Exception e) {}

        dataMap = Collections.unmodifiableMap(tempMap);

        //DEBUG (I test it and it correctly prints "data")
        System.out.println(dataMap.get("firstData"));
     }
}
</code>```

Then I call the map in another class, like this:

```<code>public class AnotherClass {

   @Before
   public void MyMethod() {
      System.out.println(MyClass.dataMap.get("firstData"));
   }

   @Test
   public void testMethod() {}
}
</code>```

Now it prints null, instead of the value "data".

Why?

答:
Are you sure your map is not modified somewhere else (cleared, ...) ?
Because this code should work.

I don't think that "unmodifiableMap" is usefull when you are using "final", it just protects that the map will not be modified by reference. So values can change by an external call.

Body:
Following the answers of this question: How can I initialise a static Map? I'm trying to create a static Map in my project.
 Below a code snippet:

public class MyClass {

    public static final Map<String, String> dataMap;

    static {
        Map<String, String> tempMap = new HashMap<String, String>();
        try {
           // Getting a string value from a file, e.g. String data
           String data = "data";
           tempMap.put("firstData", data);
        }
        catch(Exception e) {}

        dataMap = Collections.unmodifiableMap(tempMap);

        //DEBUG (I test it and it correctly prints "data")
        System.out.println(dataMap.get("firstData"));
     }
}

Then I call the map in another class, like this:

public class AnotherClass {

   @Before
   public void MyMethod() {
      System.out.println(MyClass.dataMap.get("firstData"));
   }

   @Test
   public void testMethod() {}
}

Now it prints null, instead of the value "data".

Why?


问:
Optim.jl: negative inverse Hessian
I am using the Optim.jl library to minimise a function in Julia, using a BFGS algorithm. Today, I have asked a question about the same library, but to avoid confusion I decided to split it in two.

I would like also to get an estimate of the negative inverse Hessian after the optimisation, for further calculations.

In the GitHub website of the Optim library, I found the following working example:

```<code>using Optim
rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
result        = optimize(rosenbrock, zeros(2), BFGS())
</code>```

How can I get the negative inverse Hessian after the optimisation from result? Is there any field in it identifying either the Hessian, the Inverse Hessian or the negative inverse Hessian?

EDIT

Thanks for the comments. Do you think that it would be more efficient to edit "optimize.jl" so that the function would return also the inverse Hessian? See below for a working example - the edit has been introduced at line 226:

```<code> if state.method_string == "BFGS"
         return MultivariateOptimizationResults(state.method_string,
                                                initial_x,
                                                f_increased ? state.x_previous : state.x,
                                                f_increased ? state.f_x_previous : state.f_x,
                                                iteration,
                                                iteration == options.iterations,
                                                x_converged,
                                                options.x_tol,
                                                f_converged,
                                                options.f_tol,
                                                g_converged,
                                                options.g_tol,
                                                f_increased,
                                                tr,
                                                state.f_calls,
                                                state.g_calls,
                                                state.h_calls), state.invH
    else
         return MultivariateOptimizationResults(state.method_string,
                                                 initial_x,
                                                 f_increased ? state.x_previous : state.x,
                                                 f_increased ? state.f_x_previous : state.f_x,
                                                 iteration,
                                                 iteration == options.iterations,
                                                 x_converged,
                                                 options.x_tol,
                                                 f_converged,
                                                 options.f_tol,
                                                 g_converged,
                                                 options.g_tol,
                                                 f_increased,
                                                 tr,
                                                 state.f_calls,
                                                 state.g_calls,
                                                 state.h_calls)
     end
</code>```

Or just:

```<code>return MultivariateOptimizationResults(state.method_string,
                                        initial_x,
                                        f_increased ? state.x_previous : state.x,
                                        f_increased ? state.f_x_previous : state.f_x,
                                        iteration,
                                        iteration == options.iterations,
                                        x_converged,
                                        options.x_tol,
                                        f_converged,
                                        options.f_tol,
                                        g_converged,
                                        options.g_tol,
                                        f_increased,
                                        tr,
                                        state.f_calls,
                                        state.g_calls,
                                        state.h_calls), state
</code>```

To have full access to "state" after the optimization.

EDIT 2

Since this change will be introduced in the new version of the Optim.jl library, there is no need to continue this discussion. For now, the the extended_trace and the after_while! tricks work. Personally, I prefer the latter, so I will close the discussion giving @Dan Getz the correct answer.

答:
Another less than optimal approach which works is hooking up to the internal Optim function after_while! which is currently doing nothing and using it to pull the the information from the last state.

In Julia code this looks like:

```<code>julia> using Optim

julia> rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
rosenbrock (generic function with 1 method)

julia> Optim.after_while!{T}(d, state::Optim.BFGSState{T}, method::BFGS, options)
  = global invH = state.invH

julia> result        = optimize(rosenbrock, zeros(2), BFGS())
Results of Optimization Algorithm
 * Algorithm: BFGS
 * Starting Point: [0.0,0.0]
 * Minimizer: [0.9999999926033423,0.9999999852005353]
 * Minimum: 5.471433e-17
 * Iterations: 16
 * Convergence: true
   * |x - x'| < 1.0e-32: false
   * |f(x) - f(x')| / |f(x)| < 1.0e-32: false
   * |g(x)| < 1.0e-08: true
   * f(x) > f(x'): false
   * Reached Maximum Number of Iterations: false
 * Objective Function Calls: 69
 * Gradient Calls: 69

julia> invH
2×2 Array{Float64,2}:
 0.498092  0.996422
 0.996422  1.9983
</code>```

This is unattractive for using a global variable and for depending on defining the after_while! before running/compiling optimize (but maybe in v0.6 this is already solved).

As @DSM noted in his answer, it is natural to want access to last state of optimizer. If tracing is not the answer maybe this is.

Title: Optim.jl: negative inverse Hessian

Body:
I am using the Optim.jl library to minimise a function in Julia, using a BFGS algorithm. Today, I have asked a question about the same library, but to avoid confusion I decided to split it in two.

I would like also to get an estimate of the negative inverse Hessian after the optimisation, for further calculations.

In the GitHub website of the Optim library, I found the following working example:

using Optim
rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
result        = optimize(rosenbrock, zeros(2), BFGS())

How can I get the negative inverse Hessian after the optimisation from result? Is there any field in it identifying either the Hessian, the Inverse Hessian or the negative inverse Hessian?

EDIT

Thanks for the comments. Do you think that it would be more efficient to edit "optimize.jl" so that the function would return also the inverse Hessian? See below for a working example - the edit has been introduced at line 226:

 if state.method_string == "BFGS"
         return MultivariateOptimizationResults(state.method_string,
                                                initial_x,
                                                f_increased ? state.x_previous : state.x,
                                                f_increased ? state.f_x_previous : state.f_x,
                                                iteration,
                                                iteration == options.iterations,
                                                x_converged,
                                                options.x_tol,
                                                f_converged,
                                                options.f_tol,
                                                g_converged,
                                                options.g_tol,
                                                f_increased,
                                                tr,
                                                state.f_calls,
                                                state.g_calls,
                                                state.h_calls), state.invH
    else
         return MultivariateOptimizationResults(state.method_string,
                                                 initial_x,
                                                 f_increased ? state.x_previous : state.x,
                                                 f_increased ? state.f_x_previous : state.f_x,
                                                 iteration,
                                                 iteration == options.iterations,
                                                 x_converged,
                                                 options.x_tol,
                                                 f_converged,
                                                 options.f_tol,
                                                 g_converged,
                                                 options.g_tol,
                                                 f_increased,
                                                 tr,
                                                 state.f_calls,
                                                 state.g_calls,
                                                 state.h_calls)
     end

Or just:

return MultivariateOptimizationResults(state.method_string,
                                        initial_x,
                                        f_increased ? state.x_previous : state.x,
                                        f_increased ? state.f_x_previous : state.f_x,
                                        iteration,
                                        iteration == options.iterations,
                                        x_converged,
                                        options.x_tol,
                                        f_converged,
                                        options.f_tol,
                                        g_converged,
                                        options.g_tol,
                                        f_increased,
                                        tr,
                                        state.f_calls,
                                        state.g_calls,
                                        state.h_calls), state

To have full access to "state" after the optimization.

EDIT 2

Since this change will be introduced in the new version of the Optim.jl library, there is no need to continue this discussion. For now, the the extended_trace and the after_while! tricks work. Personally, I prefer the latter, so I will close the discussion giving @Dan Getz the correct answer.

Body:
Another less than optimal approach which works is hooking up to the internal Optim function after_while! which is currently doing nothing and using it to pull the the information from the last state.

In Julia code this looks like:

julia> using Optim

julia> rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
rosenbrock (generic function with 1 method)

julia> Optim.after_while!{T}(d, state::Optim.BFGSState{T}, method::BFGS, options)
  = global invH = state.invH

julia> result        = optimize(rosenbrock, zeros(2), BFGS())
Results of Optimization Algorithm
 * Algorithm: BFGS
 * Starting Point: [0.0,0.0]
 * Minimizer: [0.9999999926033423,0.9999999852005353]
 * Minimum: 5.471433e-17
 * Iterations: 16
 * Convergence: true
   * |x - x'| < 1.0e-32: false
   * |f(x) - f(x')| / |f(x)| < 1.0e-32: false
   * |g(x)| < 1.0e-08: true
   * f(x) > f(x'): false
   * Reached Maximum Number of Iterations: false
 * Objective Function Calls: 69
 * Gradient Calls: 69

julia> invH
2×2 Array{Float64,2}:
 0.498092  0.996422
 0.996422  1.9983

This is unattractive for using a global variable and for depending on defining the after_while! before running/compiling optimize (but maybe in v0.6 this is already solved).

As @DSM noted in his answer, it is natural to want access to last state of optimizer. If tracing is not the answer maybe this is.


问:
why does my program loop infinitely?
My spell checking program doesn't give any error codes, just spell-checks the same words over and over, infinitely.
Is there a way to stop this infinite loop and put a cap on how many words it checks, for example, to end the code when ten incorrect words have been corrected?

I'm almost certain that the infinite loop is a result of this method here:

```<code> public static void SpellChecker() throws IOException {
        dictionary = new Hashtable<String, String>();
        System.out.println("Searching for spelling errors ... ");

        try {
            // Read and store the words of the dictionary
            BufferedReader dictReader = new BufferedReader(new FileReader("dictionary.txt"));

            while (dictReader.ready()) {
                String dictInput = dictReader.readLine();
                String[] dict = dictInput.split("\\s"); // create an array of
                                                        // dictionary words

                for (int i = 0; i < dict.length; i++) {
                    // key and value are identical
                    dictionary.put(dict[i], dict[i]);
                }
            }
            dictReader.close();
            String user_text = "";

            // Initializing a spelling suggestion object based on probability
            SuggestSpelling suggest = new SuggestSpelling("wordprobabilityDatabase.txt");

            // get user input for correction
            while (!user_text.equalsIgnoreCase("q")) {
   // CleanString is a string full of words to be spell checked
                user_text = cleanString;
                String[] words = user_text.split(" ");

                int error = 0;

                for (String word : words) {
                    suggestWord = true;
                    String outputWord = checkWord(word);

                    if (suggestWord) {
                        System.out.println("Suggestions for " + word +
                        " are:  " + suggest.correct(outputWord) + "\n");
                        error++;
                    }
                }

                if (error == 0 & !user_text.equalsIgnoreCase("q")) {
                    System.out.println("No mistakes found");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
             System.exit(-1);
        }
    }
</code>```

答: You never ask the user if he/she wants to quit or not, from inside the while loop. So user_text is initialized with cleanString, and never changes inside the loop, hence the infinite loop.

Title: why does my program loop infinitely?

Body:
My spell checking program doesn't give any error codes, just spell-checks the same words over and over, infinitely.
Is there a way to stop this infinite loop and put a cap on how many words it checks, for example, to end the code when ten incorrect words have been corrected?

I'm almost certain that the infinite loop is a result of this method here:

 public static void SpellChecker() throws IOException {
        dictionary = new Hashtable<String, String>();
        System.out.println("Searching for spelling errors ... ");

        try {
            // Read and store the words of the dictionary
            BufferedReader dictReader = new BufferedReader(new FileReader("dictionary.txt"));

            while (dictReader.ready()) {
                String dictInput = dictReader.readLine();
                String[] dict = dictInput.split("\\s"); // create an array of
                                                        // dictionary words

                for (int i = 0; i < dict.length; i++) {
                    // key and value are identical
                    dictionary.put(dict[i], dict[i]);
                }
            }
            dictReader.close();
            String user_text = "";

            // Initializing a spelling suggestion object based on probability
            SuggestSpelling suggest = new SuggestSpelling("wordprobabilityDatabase.txt");

            // get user input for correction
            while (!user_text.equalsIgnoreCase("q")) {
   // CleanString is a string full of words to be spell checked
                user_text = cleanString;
                String[] words = user_text.split(" ");

                int error = 0;

                for (String word : words) {
                    suggestWord = true;
                    String outputWord = checkWord(word);

                    if (suggestWord) {
                        System.out.println("Suggestions for " + word +
                        " are:  " + suggest.correct(outputWord) + "\n");
                        error++;
                    }
                }

                if (error == 0 & !user_text.equalsIgnoreCase("q")) {
                    System.out.println("No mistakes found");
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
             System.exit(-1);
        }
    }


问:
remove value(s) from a comma separated list from other value(s) from one other comma separated list
How can i remove value(s) from a comma separated list from other value(s) from one other comma separated list

I have this 2 array :

```<code>$users_list = '1, 2, 3';

$users_list_2  = '1, 2';
</code>```

I would like to have this final result :

```<code>$final_users_list = '1,2';
</code>```

I use

```<code>$final_users_list = array_diff($users_list, $users_list_2);
</code>```

But the result is empty

I follow this example :
http://php.net/manual/en/function.array-diff.php

```<code>$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);

Array
(
    [1] => blue
)
</code>```

答:
First, $users_list, and $users_list_2 are not arrays. They are strings. To make'em arrays you need to explode these strings by ,.

Second - to find elements that present in both arrays - use array_intersect.

Simplified final code is:

```<code>$users_list = '1, 2, 3';
$users_list_2  = '1, 2';
$final_users_list = array_intersect(
    explode(',', $users_list),
    explode(',', $users_list_2)
);
echo'```',print_r($final_users_list),'```';
// or as a string
echo implode(',', $final_users_list);
</code>```

Finally, if you output arrays from explode with var_dump you will see that values of this arrays have spaces. These spaces can affect further comparison, so it's better to remove them with array_map and trim for example:

```<code>$users_list = '1, 2, 3';
$users_list_array = array_map('trim', explode(',', $users_list));

$users_list_2  = '1, 2';
$users_list_2_array = array_map('trim', explode(',', $users_list_2));

$final_users_list = array_intersect($users_list_array, $users_list_2_array);
echo'```',print_r($final_users_list),'```';
echo implode(',', $final_users_list);
</code>```

Body:
How can i remove value(s) from a comma separated list from other value(s) from one other comma separated list

I have this 2 array :

$users_list = '1, 2, 3';

$users_list_2  = '1, 2';

I would like to have this final result :

$final_users_list = '1,2';

I use

$final_users_list = array_diff($users_list, $users_list_2);

But the result is empty

I follow this example :
http://php.net/manual/en/function.array-diff.php

$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);

print_r($result);

Array
(
    [1] => blue
)

Body:
First, $users_list, and $users_list_2 are not arrays. They are strings. To make'em arrays you need to explode these strings by ,.

Second - to find elements that present in both arrays - use array_intersect.

Simplified final code is:

$users_list = '1, 2, 3';
$users_list_2  = '1, 2';
$final_users_list = array_intersect(
    explode(',', $users_list),
    explode(',', $users_list_2)
);
echo'<pre>',print_r($final_users_list),'</pre>';
// or as a string
echo implode(',', $final_users_list);

Finally, if you output arrays from explode with var_dump you will see that values of this arrays have spaces. These spaces can affect further comparison, so it's better to remove them with array_map and trim for example:

$users_list = '1, 2, 3';
$users_list_array = array_map('trim', explode(',', $users_list));

$users_list_2  = '1, 2';
$users_list_2_array = array_map('trim', explode(',', $users_list_2));

$final_users_list = array_intersect($users_list_array, $users_list_2_array);
echo'<pre>',print_r($final_users_list),'</pre>';
echo implode(',', $final_users_list);


问:
How can I simplify this code? (Chess game obstruction testing)
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

```<code>    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }
</code>```

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.

答:
First, write tests. Lots and lots of tests. That way you can be confident that you're simplifying without changing the meaning of the code.

Refactoring without unit tests is like walking a high wire without a safety net.

ContentLicense: CC BY-SA 2.5

Body:
I'm making a chess game in Java, and testing to make sure there are no pieces blocking the path of the piece being moved. The piece moves from (srcX,srcY) to (dstX,dstY).

I've written this code which checks if there are any obstructions for a rook:

    if(dstY == srcY) {

            // No change on Y axis, so moving east or west

            if(dstX > srcX) {
                // Moving east
                // Test every cell the piece will pass over
                for(int x = srcX+1; x < dstX; x++) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            } else {
                // Must be moving west
                // Test every cell the piece will pass over
                for(int x = srcX-1; x > dstX; x--) {
                    // Is the cell set?
                    if(isPiece(x, srcY)) {
                        return true;
                    }
                }
            }

        } else if(dstX == srcX) {

            // No change on X axis, so moving north or south

            if(dstY > srcY) {
                // Moving north
                // Test every cell the piece will pass over
                for(int y = srcY+1; y < dstY; y++) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            } else {
                // Must be moving south
                // Test every cell the piece will pass over
                for(int y = srcY-1; y > dstY; y--) {
                    // Is the cell set?
                    if(isPiece(srcX, y)) {
                        return true;
                    }
                }
            }
        }

but it's a bit big and I'm sure it can be simplied.. any ideas?

ps, this is ONLY obstruction testing. I've already validated everything else.


问:
iOS UISlider values mismatched
I have implemented Vertical Slider in one of my App which extends UISlider. when scrolling is ended/done I am sending commands to the server with the Slider values. Sometimes when I scroll fast up/down and release then slider values are getting mismatched before sending command and after sending command.

```<code>-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
   NSLog(@"Value of Slider before sending command=%f",self.value);
   [self sendCommand]; // Here value is something else
   [super touchesEnded:touches withEvent:event];
   NSLog(@"Slider value after sending command=%f",self.value); // Here value changed
}
</code>```

But if I place super call before sending command then everything works fine. Please explain if anyone knows why this is happening.

```<code>[super touchesEnded:touches withEvent:event];
</code>```

More interesting fact is if I don't call super then also everything works well.

答:
UIKit calls this method when a finger or Apple Pencil is no longer
  touching the screen. Many UIKit classes override this method and use
  it to clean up state involved in the handling of the corresponding
  touch events. The default implementation of this method forwards the
  message up the responder chain. When creating your own subclasses,
  call super to forward any events that you do not handle yourself.  For
  example,  [super touchesEnded:touches withEvent:event];

If you override this method without calling super (a common use
  pattern), you must also override the other methods for handling touch
  events, even if your implementations do nothing.

Title: iOS UISlider values mismatched

Body:
I have implemented Vertical Slider in one of my App which extends UISlider. when scrolling is ended/done I am sending commands to the server with the Slider values. Sometimes when I scroll fast up/down and release then slider values are getting mismatched before sending command and after sending command.

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
   NSLog(@"Value of Slider before sending command=%f",self.value);
   [self sendCommand]; // Here value is something else
   [super touchesEnded:touches withEvent:event];
   NSLog(@"Slider value after sending command=%f",self.value); // Here value changed
}

But if I place super call before sending command then everything works fine. Please explain if anyone knows why this is happening.

[super touchesEnded:touches withEvent:event];

More interesting fact is if I don't call super then also everything works well.


问:
How to synchronize movement between multiple QT graphics view widgets
I am trying to build a tool that can compare images side-by-side.  To do this, I have used three graphics view widgets in QT.  They all zoom at the same rate, but I cannot seem to find anything online about how to link the movement of the images (aka - the drag and drop with the mouse).  Is this feature even possible to construct?

Here is what the GUI looks like:

Image compare GUI

答:
Well, every time I used a QGraphicsView, I ended up subclassing it cause it didn't provide everything I needed "as public".

In your case though, I believe this is as simple as doing:

```<code>connect(graphicsView1->verticalScrollBar(), SIGNAL(valueChanged(int)),
        graphicsView2->verticalScrollBar(), SLOT(setValue(int)));
connect(graphicsView2->verticalScrollBar(), SIGNAL(valueChanged(int)),
        graphicsView1->verticalScrollBar(), SLOT(setValue(int)));
</code>```

If you prefer, call some slots to perform more than a 1-to-1 action:

```<code>void MyClass::scrollGraphicsView1(int value)
{
    graphicsView1->verticalScrollBar()->setValue(value);
}
void MyClass::scrollGraphicsView2(int value)
{
    graphicsView2->verticalScrollBar()->setValue(value);
}
</code>```

Body:
Well, every time I used a QGraphicsView, I ended up subclassing it cause it didn't provide everything I needed "as public".

In your case though, I believe this is as simple as doing:

connect(graphicsView1->verticalScrollBar(), SIGNAL(valueChanged(int)),
        graphicsView2->verticalScrollBar(), SLOT(setValue(int)));
connect(graphicsView2->verticalScrollBar(), SIGNAL(valueChanged(int)),
        graphicsView1->verticalScrollBar(), SLOT(setValue(int)));

If you prefer, call some slots to perform more than a 1-to-1 action:

void MyClass::scrollGraphicsView1(int value)
{
    graphicsView1->verticalScrollBar()->setValue(value);
}
void MyClass::scrollGraphicsView2(int value)
{
    graphicsView2->verticalScrollBar()->setValue(value);
}


问:
Mobile Redirect using htaccess
I have a website called

www.website.org

I have a mobile website called

m.website.org

I want to use an htaccess to automatically redirect the main website URL to the mobile version..

However, there is a link on the mobile version that points back to the main website called

www.website.org?noredirect=true

When I click the logo on the home page of the actual website it links to

www.website.org

I don't want the user to be allowed back to mobile accidentally by clicking on the logo on the main page. How can I accomplish this via htaccess without JavaSCript.

If not I am open-minded to alternate options.

EDIT

I think I am currently going to use this for sensing mobile redirect via htaccess

```<code>RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ http://m.website.com [R,L]
</code>```

答:
For Mobiles like domain.com/m/

```<code>RewriteCond %{HTTP_REFERER} !^http://(.*).domain.com/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(.*)$ /m/ [L,R=302]
</code>```

Title: Mobile Redirect using htaccess

Body:
I have a website called

www.website.org

I have a mobile website called

m.website.org

I want to use an htaccess to automatically redirect the main website URL to the mobile version..

However, there is a link on the mobile version that points back to the main website called

www.website.org?noredirect=true

When I click the logo on the home page of the actual website it links to

www.website.org

I don't want the user to be allowed back to mobile accidentally by clicking on the logo on the main page. How can I accomplish this via htaccess without JavaSCript.

If not I am open-minded to alternate options.

EDIT

I think I am currently going to use this for sensing mobile redirect via htaccess

RewriteEngine On
RewriteBase /

RewriteCond %{HTTP_USER_AGENT} android|avantgo|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge\ |maemo|midp|mmp|opera\ m(ob|in)i|palm(\ os)?|phone|p(ixi|re)\/|plucker|pocket|psp|symbian|treo|up\.(browser|link)|vodafone|wap|windows\ (ce|phone)|xda|xiino [NC,OR]
RewriteCond %{HTTP_USER_AGENT} ^(1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a\ wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r\ |s\ )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1\ u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp(\ i|ip)|hs\-c|ht(c(\-|\ |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac(\ |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt(\ |\/)|klon|kpt\ |kwc\-|kyo(c|k)|le(no|xi)|lg(\ g|\/(k|l|u)|50|54|e\-|e\/|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(di|rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-|\ |o|v)|zz)|mt(50|p1|v\ )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v\ )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-|\ )|webc|whit|wi(g\ |nc|nw)|wmlb|wonu|x700|xda(\-|2|g)|yas\-|your|zeto|zte\-) [NC]
RewriteRule ^$ http://m.website.com [R,L]

Body:
For Mobiles like domain.com/m/

RewriteCond %{HTTP_REFERER} !^http://(.*).domain.com/.*$ [NC]
RewriteCond %{REQUEST_URI} !^/m/.*$
RewriteCond %{HTTP_USER_AGENT} "android|blackberry|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC]
RewriteRule ^(.*)$ /m/ [L,R=302]


问:
Get internal byte array from ByteArrayInputStream
I want to get the internal byte array from ByteArrayInputStream. I don't want to extends that class or write it into another byte array. Is there a utility class that help me do that?

Thanks,

答: No, access to the internal array is not provided except through the toByteArray() method, which makes a copy.</p>


问:
How do Python commands, and any other commands, get automatically set up in terminal?
I was trying to set up a platform that used pip and I realized I had to install it using 'sudo easy_install'. I think easy_install is a python-enabled command that was set up in terminal after I installed Python.

How does it work that after you install something like Python, a command like easy_install is automatically activated with-in terminal that can call what easy_install does? Is there some sort of active list of commands that is updated for all terminal executions by programs that are installed?

Thanks.

答: All the places that the terminal will search for programs are in the PATH variable. To see which directories are in your path variable you can run the following in your terminal: echo $PATH. Note that paths are colon separated on most UNIX-based systems. As such, all programs contained in directories that are in the PATH variable are ones that can be run without specifying a relative/absolute path to them.


问:
How to ignore escape characters in bash script?
I am making a bash script and I need a SQL query, but It has escape characters of bash.

I want to read the SQL query without escape characters of bash, why this escape characters are of MySQL.

```<code>QUERY="SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';"
</code>```

Thanks!

答:
You can use

```<code>read -r -d '' query <<'EOF'
SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
EOF

printf "%s\n" "$query"
</code>```

output

```<code>SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
</code>```

edit, in a case that you need expand variables, remove the ' from the EOF, e.g. like:

```<code>outfile=/tmp/file
read -r -d '' query <<EOF
SELECT department_id, description FROM departments
INTO OUTFILE '$outfile'
FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
EOF
printf "%s\n" "$query"
</code>```

(note the $outfile variable) prints

```<code>SELECT department_id, description FROM departments
INTO OUTFILE '/tmp/file'
FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
</code>```

Body:
I am making a bash script and I need a SQL query, but It has escape characters of bash.

I want to read the SQL query without escape characters of bash, why this escape characters are of MySQL.

QUERY="SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';"

Thanks!

Body:
You can use

read -r -d '' query <<'EOF'
SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
EOF

printf "%s\n" "$query"

output

SELECT department_id, description FROM departments INTO OUTFILE '/var/lib/mysql-files/departaments.csv' FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';

edit, in a case that you need expand variables, remove the ' from the EOF, e.g. like:

outfile=/tmp/file
read -r -d '' query <<EOF
SELECT department_id, description FROM departments
INTO OUTFILE '$outfile'
FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';
EOF
printf "%s\n" "$query"

(note the $outfile variable) prints

SELECT department_id, description FROM departments
INTO OUTFILE '/tmp/file'
FIELDS TERMINATED BY ', ' ENCLOSED BY '"' LINES TERMINATED BY '\n';


问:
Debugging Pypy3
With the release of pypy3.5, I want to try running a python3 project in pypy. Doing so, I hit the following error:

```<code>RPython traceback:
  File "pypy_interpreter.c", line 38718, in BuiltinCodePassThroughArguments1_funcrun_obj
  File "pypy_module_cpyext_2.c", line 62299, in wrap_del
Fatal RPython error: NotImplementedError
Aborted (core dumped)
</code>```

I am unable to figure out what is causing this problem. For example, running the program in the python level pdb debugger does not break when the exception is raised.

What are technique for debugging pypy to understand what feature I'm using that's not implemented so that I can try to work around it?

答: That's a bug.  Please report it on https://bitbucket.org/pypy/pypy/issues?status=new&status=open .</p>

Title: Debugging Pypy3

Body:
With the release of pypy3.5, I want to try running a python3 project in pypy. Doing so, I hit the following error:

RPython traceback:
  File "pypy_interpreter.c", line 38718, in BuiltinCodePassThroughArguments1_funcrun_obj
  File "pypy_module_cpyext_2.c", line 62299, in wrap_del
Fatal RPython error: NotImplementedError
Aborted (core dumped)

I am unable to figure out what is causing this problem. For example, running the program in the python level pdb debugger does not break when the exception is raised.

What are technique for debugging pypy to understand what feature I'm using that's not implemented so that I can try to work around it?


问:
Unit Tests not discovered in Visual Studio 2017
I have been struggling with VS 2017 since I installed it. Now it seems Unit Tests will only run from the command line "dotnet test."

My project is .NET Core 1.1.1. I have the SDK and the framework update for 1.1.1 installed.

I have tried the sample at MSDN (https://msdn.microsoft.com/en-us/library/ms182532.aspx) which also fails exactly the same way.

All NuGet packages for the tests and the main project are current. And both the test project and the main project build without errors. An the tests run successfully from the command line.

Has anyone gotten Unit Tests to run in VS 2017, if so how?

Thanks,
John

Update - Extend

Here is an example of a simple test project that is not working on GitHub. This is an example with xUnit but I have tried NUnit and visual studio built in MS tests. No matter what testing or what changes I make I cannot get the VS test runner to find any tests.

What I've Tried

Deleting VS test cache files DEL %TEMP%\VisualStudioTestExplorerExtensions

Restarting VS

Closing/Opening test explorer

for xUnit installed Microsoft.DotNet.InternalAbstractions (see SO post)

for NUnit ensure adapter installed and same version (3) as NUnit package

test -> test settings -> default processor architecture is set to x86

The Question

Can anyone please provide a working example of a .Net Core 1.1.0 solution in VS2017 (.csproj project files) where the VS test explorer successfully finds the unit tests OR show me the issue in the example given.

答:
The Issue

The problem is that Visual Studio is getting 'confused' over the dotnet core versions on the machine. When I went to control panel -> uninstall programs I had 8 different dotnet core SDK's and Runtimes installed. This was somehow causing VS to silently have an error when trying to find tests.

Validate The Issue

You can validate the issue by going to the command line and getting the version of dotnet your on $ dotnet --version. If you see anything except the latest version you have installed then your machine has some mismatch and is not using the correct version. Example...If you have dotnet core 1.0.1 installed but when you get the version at command prompt and it says 1.0.0 thats a problem.

The Solution

Delete all the old stuff. I started with only what I though I needed to remove (the oldest dotnet rc versions) but it still gave the wrong version when testing the issue. Eventually I conceded to do a full clean. I...

Uninstalled all visual studio applications (on my machine VS2015 and VS2017)

Uninstalled all versions of dotnet core (even most recent)

After my machine was completely empty of all VS and donet I installed only VS2017 (it comes packaged with latest dotnet). I created a xUnit test project and the test explorer found the test immediately SOLVED

This may seem like overkill but I spent two weeks trying to fix this in other ways. If your having the issue just do it, even though it may take you hours to uninstall/reinstall items it will probably save you time.

References

See @epestic blog post where he gives more detail on fixing the issue.


问:
How to create and write to a txt document from a batch executable
I am making a mock operating system using .bat files and I want to be able to create and write to .txt files so I can store data, but I can't find a command that lets me do this. Any suggestions?</p>

答:
If want to export loggs to a txt file do something like

```<code>echo This text must be logged > log.txt
</code>```

if you open log.txt after it:

```<code>This text must be logged
</code>```

if you want to write in the next line or want to use a existing file,
use this

```<code>echo Next Line pls >> log.txt
</code>```

so the updated log.text file looks like this

```<code>This text must be logged
Next Line pls
</code>```

Body:
If want to export loggs to a txt file do something like

echo This text must be logged > log.txt

if you open log.txt after it:

This text must be logged

if you want to write in the next line or want to use a existing file,
use this

echo Next Line pls >> log.txt

so the updated log.text file looks like this

This text must be logged
Next Line pls