问:
Replace multiple strings without overlapping
I have PHP application in which I have to replace a whole bunch of strings with their respective links. Basically I get a list of possible replacements that looks something like that:

```<code>"Table 1" => "<a href='SOME_LINK'>Table 1</a>"
"Table 2" => "<a href='SOME_LINK'>Table 2</a>"
...
"Table 10" => "<a href='SOME_LINK'>Table 10</a>"
"Table 11" => "<a href='SOME_LINK'>Table 11</a>"
</code>```

I go through each pair and I call str_replace which each couple of values. The problem is that even on the first pass I catch the Table 10 strings as well as the Table 1 strings and I replace both which is wrong. So I end up with result that has something like Table 10. Table 10 should not be replaced at all (unless later there's another pair that actually takes care of Table 10).

Any ideas for a work around? I though of adding a blank space after the search part of the string however it's possible to have something in the text like Table 1, which would then not match at all. I also considered using regular expressions to replace but not sure if there's a syntax there that would fix the issue above.

EDIT:
To improve the reading comprehension, here's expected input and output for this problem.
CONDITION:

```<code>"Table 1" => "<a href='SOME_LINK'>Table 1</a>"
"Table 10" => "<a href='SOME_LINK'>Table 10</a>"
</code>```

INPUT:

```<code>We have some text here.
It has words like Table 1, Table 2 and also Table 10.
Those need to be replaced.
</code>```

OUTPUT:

```<code>We have some text here.
It has words like <a href='SOME_LINK'>Table 1</a>, Table 2 and also <a href='SOME_LINK'>Table 10</a>.
Those need to be replaced.
</code>```

答:
Modifying the answer again because of the comment with more information.

You can search for the table with regex, for example, as PHP code:

```<code>$input = "We have some text here.
It haswords like Table 1, Table 2 and also Table 10.
Those need to be replaced.";

$output = preg_replace("/(Table 1)(?![\d])/U", "<a href=\"LINK HERE\">LINK TEXT</a>", $input);

echo "Input:<br>".$input."<br><br>Output:<br>".$output;
</code>```

It seems PHP handles some regex options differently than I personally expected. This code worked for me in a test server (replacing "Table 1" with 2 or 10 replaced just the correct parts). If you want case-insensitive search, add i next to the U in the regex.

Body:
I have PHP application in which I have to replace a whole bunch of strings with their respective links. Basically I get a list of possible replacements that looks something like that:

"Table 1" => "Table 1"
"Table 2" => "Table 2"
...
"Table 10" => "Table 10"
"Table 11" => "Table 11"

I go through each pair and I call str_replace which each couple of values. The problem is that even on the first pass I catch the Table 10 strings as well as the Table 1 strings and I replace both which is wrong. So I end up with result that has something like Table 10. Table 10 should not be replaced at all (unless later there's another pair that actually takes care of Table 10).

Any ideas for a work around? I though of adding a blank space after the search part of the string however it's possible to have something in the text like Table 1, which would then not match at all. I also considered using regular expressions to replace but not sure if there's a syntax there that would fix the issue above.

EDIT:
To improve the reading comprehension, here's expected input and output for this problem.
CONDITION:

"Table 1" => "Table 1"
"Table 10" => "Table 10"

INPUT:

We have some text here.
It has words like Table 1, Table 2 and also Table 10.
Those need to be replaced.

OUTPUT:

We have some text here.
It has words like Table 1, Table 2 and also Table 10.
Those need to be replaced.

Body:
Modifying the answer again because of the comment with more information.

You can search for the table with regex, for example, as PHP code:

$input = "We have some text here.
It haswords like Table 1, Table 2 and also Table 10.
Those need to be replaced.";

$output = preg_replace("/(Table 1)(?![\d])/U", "<a href=\"LINK HERE\">LINK TEXT</a>", $input);

echo "Input:<br>".$input."<br><br>Output:<br>".$output;

It seems PHP handles some regex options differently than I personally expected. This code worked for me in a test server (replacing "Table 1" with 2 or 10 replaced just the correct parts). If you want case-insensitive search, add i next to the U in the regex.


来源: stackexchange

问:
How long does RDD remain in memory?
Considering memory being limited, I had a feeling that spark automatically removes RDD from each node. I'd like to know is this time configurable? How does spark decide when to evict an RDD from memory

Note: I'm not talking about rdd.cache()

答:
I'd like to know is this time configurable? How does spark decide when
  to evict an RDD from memory

An RDD is an object just like any other. If you don't persist/cache it, it will act as any other object under a managed language would and be collected once there are no alive root objects pointing to it.

The "how" part, as @Jacek points out is the responsibility of an object called ContextCleaner. Mainly, if you want the details, this is what the cleaning method looks like:

```<code>private def keepCleaning(): Unit = Utils.tryOrStopSparkContext(sc) {
  while (!stopped) {
    try {
      val reference = Option(referenceQueue.remove(ContextCleaner.REF_QUEUE_POLL_TIMEOUT))
          .map(_.asInstanceOf[CleanupTaskWeakReference])
      // Synchronize here to avoid being interrupted on stop()
      synchronized {
        reference.foreach { ref =>
          logDebug("Got cleaning task " + ref.task)
          referenceBuffer.remove(ref)
          ref.task match {
            case CleanRDD(rddId) =>
              doCleanupRDD(rddId, blocking = blockOnCleanupTasks)
            case CleanShuffle(shuffleId) =>
              doCleanupShuffle(shuffleId, blocking = blockOnShuffleCleanupTasks)
            case CleanBroadcast(broadcastId) =>
              doCleanupBroadcast(broadcastId, blocking = blockOnCleanupTasks)
            case CleanAccum(accId) =>
              doCleanupAccum(accId, blocking = blockOnCleanupTasks)
            case CleanCheckpoint(rddId) =>
              doCleanCheckpoint(rddId)
            }
          }
        }
      } catch {
        case ie: InterruptedException if stopped => // ignore
        case e: Exception => logError("Error in cleaning thread", e)
    }
  }
}
</code>```

If you want to learn more, I suggest browsing Sparks source or even better, reading @Jacek book called "Mastering Apache Spark" (This points to an explanation regarding ContextCleaner)

ContentLicense: CC BY-SA 3.0

Title: How long does RDD remain in memory?

Body:
I'd like to know is this time configurable? How does spark decide when
  to evict an RDD from memory

An RDD is an object just like any other. If you don't persist/cache it, it will act as any other object under a managed language would and be collected once there are no alive root objects pointing to it.

The "how" part, as @Jacek points out is the responsibility of an object called ContextCleaner. Mainly, if you want the details, this is what the cleaning method looks like:

private def keepCleaning(): Unit = Utils.tryOrStopSparkContext(sc) {
  while (!stopped) {
    try {
      val reference = Option(referenceQueue.remove(ContextCleaner.REF_QUEUE_POLL_TIMEOUT))
          .map(_.asInstanceOf[CleanupTaskWeakReference])
      // Synchronize here to avoid being interrupted on stop()
      synchronized {
        reference.foreach { ref =>
          logDebug("Got cleaning task " + ref.task)
          referenceBuffer.remove(ref)
          ref.task match {
            case CleanRDD(rddId) =>
              doCleanupRDD(rddId, blocking = blockOnCleanupTasks)
            case CleanShuffle(shuffleId) =>
              doCleanupShuffle(shuffleId, blocking = blockOnShuffleCleanupTasks)
            case CleanBroadcast(broadcastId) =>
              doCleanupBroadcast(broadcastId, blocking = blockOnCleanupTasks)
            case CleanAccum(accId) =>
              doCleanupAccum(accId, blocking = blockOnCleanupTasks)
            case CleanCheckpoint(rddId) =>
              doCleanCheckpoint(rddId)
            }
          }
        }
      } catch {
        case ie: InterruptedException if stopped => // ignore
        case e: Exception => logError("Error in cleaning thread", e)
    }
  }
}

If you want to learn more, I suggest browsing Sparks source or even better, reading @Jacek book called "Mastering Apache Spark" (This points to an explanation regarding ContextCleaner)

ContentLicense: CC BY-SA 4.0


问:
Failed to find configured root that contains /storage/emulated/0/Android/data/com.example
I know that there are a lot of questions of this problem but I cannot resolve my problem with the other posts.

I don't understand why I see this message.

MainActivity

```<code>alert = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

public class MainActivity extends AppCompatActivity {

    ImageView iv_foto;
    static final int REQUEST_TAKE_PHOTO = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_foto = (ImageView) findViewById(R.id.iv_foto);

    }

    public void sacarFoto(View v){
        dispatchTakePictureIntent();
    }
    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.josemiguelrodriguez.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TAKE_PHOTO){
            iv_foto.setImageURI(Uri.parse(mCurrentPhotoPath));
        }
    }
}
</code>```

AndroidManifest

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

    <uses-feature android:name="android.hardware.camera"
        android:required="true"
        />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.josemiguelrodriguez.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

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

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

</manifest>
</code>```

file_paths.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-file-path name="my_images" path="Pictures" />
</paths>
</code>```

Error:

```<code>03-31 13:39:14.292 30787-30787/com.example.josemiguelrodriguez.pruebacamara E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.josemiguelrodriguez.pruebacamara, PID: 30787
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_133914_-2001489715.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.dispatchTakePictureIntent(MainActivity.java:67)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.sacarFoto(MainActivity.java:33)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
</code>```

Many Thanks!! :D

UPDATE
The error is solved with the first response of @CommonsWare but now I have the following error:

Error

```<code>resolveUri failed on bad bitmap uri: /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_140455_-2001489715.png
</code>```

答: Change external-file-path to external-files-path (note the s).

Body:
I know that there are a lot of questions of this problem but I cannot resolve my problem with the other posts.

I don't understand why I see this message.

MainActivity

alert = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

public class MainActivity extends AppCompatActivity {

    ImageView iv_foto;
    static final int REQUEST_TAKE_PHOTO = 1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        iv_foto = (ImageView) findViewById(R.id.iv_foto);

    }

    public void sacarFoto(View v){
        dispatchTakePictureIntent();
    }
    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.josemiguelrodriguez.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_TAKE_PHOTO){
            iv_foto.setImageURI(Uri.parse(mCurrentPhotoPath));
        }
    }
}

AndroidManifest

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

    <uses-feature android:name="android.hardware.camera"
        android:required="true"
        />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.josemiguelrodriguez.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"></meta-data>
        </provider>

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

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

</manifest>

file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-file-path name="my_images" path="Pictures" />
</paths>

Error:

03-31 13:39:14.292 30787-30787/com.example.josemiguelrodriguez.pruebacamara E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.josemiguelrodriguez.pruebacamara, PID: 30787
java.lang.IllegalStateException: Could not execute method for android:onClick
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:293)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalArgumentException: Failed to find configured root that contains /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_133914_-2001489715.jpg
at android.support.v4.content.FileProvider$SimplePathStrategy.getUriForFile(FileProvider.java:711)
at android.support.v4.content.FileProvider.getUriForFile(FileProvider.java:400)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.dispatchTakePictureIntent(MainActivity.java:67)
at com.example.josemiguelrodriguez.pruebacamara.MainActivity.sacarFoto(MainActivity.java:33)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:288)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5001)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)

Many Thanks!! :D

UPDATE
The error is solved with the first response of @CommonsWare but now I have the following error:

Error

resolveUri failed on bad bitmap uri: /storage/emulated/0/Android/data/com.example.josemiguelrodriguez.pruebacamara/files/Pictures/JPEG_20170331_140455_-2001489715.png


问:
Plone: custom variable in content rule
I have defined a dexterity content type myaddon.subscriber (subscriber = participant at an event).

I added a Content rule to send an email when a subscriber is approved (workflow state change to this one).

Each subscriber has an email address (email - field).

In Edit Mail Action form I see I can use variables like ${user_email} in Email recipients (Required)
The email where you want to send this message. To send it to different email addresses, just separate them with ,

This is working. In my case user_email is the email of logged in user - the person who approve the participant. The messages are sent when the state is changed. Perfect.

I need to define a variable ${subscriber_email} that will have the myaddon.subscriber.email value. How can I do this? I'm trying to find an example. So, how to use an field (email) of current changed object (subscriber) as variable in this Mail Action?

答:
You can use IContextWrapper from plone.stringinterp 1.0.14+:

```<code>>>> new_context = IContextWrapper(context)(
...     email=u"subscriber@example.com"
... )

>>> class SubscriberEmailSubstitution(BaseSubstitution):
...     def safe_call(self):
...         return self.wrapper.email

>>> sm = getGlobalSiteManager()
>>> sm.registerAdapter(SubscriberEmailSubstitution, (Interface, ), IStringSubstitution, name=u"subscriber_email")

>>> getAdapter(new_context, IStringSubstitution, 'subscriber_email')()
u'subscriber@example.com'
</code>```

Imports:

```<code>>>> from zope.interface import Interface
>>> from plone.stringinterp.interfaces import IStringSubstitution
>>> from plone.stringinterp.interfaces import IStringSubstitutionInfo
>>> from zope.component import getGlobalSiteManager, getAdapter
>>> from plone.stringinterp.adapters import BaseSubstitution
>>> from plone.stringinterp.interfaces import IContextWrapper
</code>```

See more stringinterp doctests.

Also see a fully working example within eea.pdf add-on.

Title: Plone: custom variable in content rule

Body:
You can use IContextWrapper from plone.stringinterp 1.0.14+:

>>> new_context = IContextWrapper(context)(
...     email=u"subscriber@example.com"
... )

>>> class SubscriberEmailSubstitution(BaseSubstitution):
...     def safe_call(self):
...         return self.wrapper.email

>>> sm = getGlobalSiteManager()
>>> sm.registerAdapter(SubscriberEmailSubstitution, (Interface, ), IStringSubstitution, name=u"subscriber_email")

>>> getAdapter(new_context, IStringSubstitution, 'subscriber_email')()
u'subscriber@example.com'

Imports:

>>> from zope.interface import Interface
>>> from plone.stringinterp.interfaces import IStringSubstitution
>>> from plone.stringinterp.interfaces import IStringSubstitutionInfo
>>> from zope.component import getGlobalSiteManager, getAdapter
>>> from plone.stringinterp.adapters import BaseSubstitution
>>> from plone.stringinterp.interfaces import IContextWrapper

See more stringinterp doctests.

Also see a fully working example within eea.pdf add-on.


问:
create function mysql error
Here is my function

```<code>DELIMITER //
CREATE FUNCTION specialUser(user INT) RETURNS user_id INT
BEGIN
    DECLARE user_id INT DEFAULT 0;
    CASE
     WHEN user = 1556 THEN SET user_id = 1001;
     WHEN user = 1018 THEN SET user_id = 1002;
     WHEN user = 3658 THEN SET user_id = 1003;
         ELSE SET user_id = user;
    END CASE;
 RETURN user_id;
END//
</code>```

I get error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'user_id INT
    BEGIN
        DECLARE user_id INT DEFAULT 0;
        CASE
        ' at line 1

答:
You can only state the type of the result, there's no use in giving an identifier, so:

```<code>CREATE FUNCTION specialUser(user INT) RETURNS INT
</code>```

instead of

```<code>CREATE FUNCTION specialUser(user INT) RETURNS user_id INT
</code>```

ContentLicense: CC BY-SA 2.5

Title: create function mysql error

Body:
Here is my function

DELIMITER //
CREATE FUNCTION specialUser(user INT) RETURNS user_id INT
BEGIN
    DECLARE user_id INT DEFAULT 0;
    CASE
     WHEN user = 1556 THEN SET user_id = 1001;
     WHEN user = 1018 THEN SET user_id = 1002;
     WHEN user = 3658 THEN SET user_id = 1003;
         ELSE SET user_id = user;
    END CASE;
 RETURN user_id;
END//

I get error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'user_id INT
    BEGIN
        DECLARE user_id INT DEFAULT 0;
        CASE
        ' at line 1

Body:
You can only state the type of the result, there's no use in giving an identifier, so:

CREATE FUNCTION specialUser(user INT) RETURNS INT

instead of

CREATE FUNCTION specialUser(user INT) RETURNS user_id INT


问:
Rounding lambda function
I'm trying to create a lambda function that will round a value passed onto it, with an amount of decimal places also specified

I made the following

```<code>c = lambda x: round(x, dp)
</code>```

where dp was already specified

However, trying to call this gave the following error

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: 'int' object is not callable
</code>```

when I typed

```<code>c(23.2323332345435)
</code>```

I may be half asleep, but I'm pretty sure that's how a simple lambda function is created, and I can't understand why it won't work.

I tried encasing in parens to no avail

答:
It seems like you shadowed round.

```<code>>>> c = lambda x: round(x)
>>> c(13.4)
13
>>> round = 5
>>> c = lambda x: round(x)
>>> c(13.4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: 'int' object is not callable
</code>```

Check your code for anywhere you've assigned an object the name round. Once you've found it, replace it with another name. You can read more about shadowing here.

Title: Rounding lambda function

Body:
I'm trying to create a lambda function that will round a value passed onto it, with an amount of decimal places also specified

I made the following

c = lambda x: round(x, dp)

where dp was already specified

However, trying to call this gave the following error

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
TypeError: 'int' object is not callable

when I typed

c(23.2323332345435)

I may be half asleep, but I'm pretty sure that's how a simple lambda function is created, and I can't understand why it won't work.

I tried encasing in parens to no avail

Body:
It seems like you shadowed round.

>>> c = lambda x: round(x)
>>> c(13.4)
13
>>> round = 5
>>> c = lambda x: round(x)
>>> c(13.4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 1, in <lambda>
TypeError: 'int' object is not callable

Check your code for anywhere you've assigned an object the name round. Once you've found it, replace it with another name. You can read more about shadowing here.


答:
That's what happens if you accidentally override round, before or after defining the lambda:

```<code>>>> c = lambda x: round(x, 5)
>>> c(34.44)
34.44
>>> round=12
>>> c(34.44)
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
  File "<interactive input>", line 1, in <lambda>
TypeError: 'int' object is not callable
>>>
</code>```

Title: Rounding lambda function

Body:
That's what happens if you accidentally override round, before or after defining the lambda:

>>> c = lambda x: round(x, 5)
>>> c(34.44)
34.44
>>> round=12
>>> c(34.44)
Traceback (most recent call last):
  File "<string>", line 301, in runcode
  File "<interactive input>", line 1, in <module>
  File "<interactive input>", line 1, in <lambda>
TypeError: 'int' object is not callable
>>>


问:
Run animation when UIApplicationWillEnterForeground
I have problems running a animation when the application WillEnterForeground again. I have the animation running on viewdidload and it works.

The animations looks like this:

```<code>UIView.animate(withDuration: 30.0, delay: 2.0, options: .repeat, animations: {
        self.littleSunnyCloud.center.x += self.view.bounds.width + 80
    }, completion: nil)
</code>```

The idea is to keep that animation repeating throughout the app.
But since something is happening when you multitask and go back to the app. Iv'e set up a notification for this like this:

```<code>NotificationCenter.default.addObserver(self, selector:#selector(ViewController.doYourStuff), name:
    NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
</code>```

This works and The method doYourStuff() looks like this, and it prints out when I get back to the app from multitask but clouds() which is the function with animation doesn't run

```<code>func doYourStuff(){
    print("reload animation")
    clouds()
    getData()
}
</code>```

I have tried to put self. but didn't work either.
So how come this is happening? Why can't you run a animation
like this, what I'm I doing wrong?

答:
Try to continue animation on UIApplicationDidBecomeActive.

From documentation:

UIApplicationWillEnterForegroundNotification

Posted shortly before
  an app leaves the background state on its way to becoming the active
  app.

Apple does not tell what's happening under the hood but I think runloop "shuts down" when application goes to background and does not exist on WillEnterForeground when app restores it's state so it's not the right moment to do UI refreshing/resume animations.

From documentation:

applicationDidBecomeActive(_:)

You should use this method to restart any tasks that were paused (or
  not yet started) while the app was inactive. For example, you could
  use it to restart timers or throttle up OpenGL ES frame rates. If your
  app was previously in the background, you could also use it to refresh
  your app’s user interface.

Body:
I have problems running a animation when the application WillEnterForeground again. I have the animation running on viewdidload and it works.

The animations looks like this:

UIView.animate(withDuration: 30.0, delay: 2.0, options: .repeat, animations: {
        self.littleSunnyCloud.center.x += self.view.bounds.width + 80
    }, completion: nil)

The idea is to keep that animation repeating throughout the app.
But since something is happening when you multitask and go back to the app. Iv'e set up a notification for this like this:

NotificationCenter.default.addObserver(self, selector:#selector(ViewController.doYourStuff), name:
    NSNotification.Name.UIApplicationWillEnterForeground, object: nil)

This works and The method doYourStuff() looks like this, and it prints out when I get back to the app from multitask but clouds() which is the function with animation doesn't run

func doYourStuff(){
    print("reload animation")
    clouds()
    getData()
}

I have tried to put self. but didn't work either.
So how come this is happening? Why can't you run a animation
like this, what I'm I doing wrong?


问:
C - How to extract different columns from one string?
I had a CSV file. I have managed to convert all the commas to spaces, and have put the entire thing in one massive string.
When I print out the string I get data like this:

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA2 STUFF2 20 0.1 250 250 200 0.022

DATA3 STUFF3 30 0.1 120 330 10 0.064

DATA4 STUFF4 40 0.1 920 380 10 0.193

etc

I'm currently having a problem in that when I scan the data into my stuct array that is meant to hold this data, it just produces the first line over and over again, ignoring the rest. So when I print it out, I just get

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

```<code>i=0;
while(i<MAX)
{
    sscanf(str, "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);
    i++;
}
</code>```

MAX is the number of records in the CSV file, datas is my array of structures, str is the string that i have stored all the data without spaces and i is just an integer.

The actual structure:

```<code>struct data{
    char c1[10], c2[10];
    int n1, n3, n4, n5;
    float n2, n6;
};
struct data datas[MAX];
</code>```

Anyone got a solution? New to C so please explain like I'm 5.

答:
Through the multiple iterations of the loop, you are passing the same string (i.e. the string points to the same location - beginning of the string) which results in same values getting parsed.

You need advance the string to point to the correct location within the string for the subsequent scanf operations.

You can probably have some delimiter in the string at the end of "one set" of data and use strtok or similar such functions to move within the string.

Body:
I had a CSV file. I have managed to convert all the commas to spaces, and have put the entire thing in one massive string.
When I print out the string I get data like this:

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA2 STUFF2 20 0.1 250 250 200 0.022

DATA3 STUFF3 30 0.1 120 330 10 0.064

DATA4 STUFF4 40 0.1 920 380 10 0.193

etc

I'm currently having a problem in that when I scan the data into my stuct array that is meant to hold this data, it just produces the first line over and over again, ignoring the rest. So when I print it out, I just get

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

DATA1 STUFF1 10 0.1 550 120 140 0.121

i=0;
while(i<MAX)
{
    sscanf(str, "%s %s %d %f %d %d %d %f", &datas[i].c1, &datas[i].c2,
    &datas[i].n1, &datas[i].n2, &datas[i].n3, &datas[i].n4,
    &datas[i].n5, &datas[i].n6);
    i++;
}

MAX is the number of records in the CSV file, datas is my array of structures, str is the string that i have stored all the data without spaces and i is just an integer.

The actual structure:

struct data{
    char c1[10], c2[10];
    int n1, n3, n4, n5;
    float n2, n6;
};
struct data datas[MAX];

Anyone got a solution? New to C so please explain like I'm 5.


问:
How to resize the remaining divs based on the div with large Text in (Created by Template in custom directive)
Hi I am having a custom directive which has template in which there is a ng-repeat.
This ng-repeat creates DIV's and fills data within these div's
Now problem is I want o resize all the remaining Div's based on the largest height of the DIV.(more text in div more height)
So please help me how to resize/set the height of other divs based on the div with larger height(containing more text)

app.directive("dbsSummry", ["$window","$timeout", "Service",
function ($window,$timeout, Service) {
    return {
        restrict: "E",
        replace: true,
        scope: {},
        controllerAs: "data",
        templateUrl: "../RsSummary.html"
        link:function ($scope, element, attrs){
        }
        }
        }

        //this directive is used at another places```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-repeat="(key, value) in data.dataInfo[0]" class="row padding-make-vertical ys-padding" style="text-align: left !important;" ng-class="data.bodyCss">
 <span>{{key | titleCase}}</span>
</div>

     <div ng-repeat="(key, value) in data.dataInfo[1]"  class="row padding-make-vertical ys-padding" class="data.bodyCss">
                            <span>{{value | textCurrency}}</span>
                        </div>

//This is RsSummary.html</code>```

答:
[

function blockheight(){
var first_block = $(".block1").innerHeight();
$(".block2, .block3").css("height",first_block);
};

$(document).ready(function (){
  blockheight();
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.block1{
  background: red;
}
.block2{
  background: yellow;
}
.block3{
  background: green;
}</code>```

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

Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai

hai

hai

```

Div Height will same acording to large content in first div

Body:
Hi I am having a custom directive which has template in which there is a ng-repeat.
This ng-repeat creates DIV's and fills data within these div's
Now problem is I want o resize all the remaining Div's based on the largest height of the DIV.(more text in div more height)
So please help me how to resize/set the height of other divs based on the div with larger height(containing more text)

app.directive("dbsSummry", ["$window","$timeout", "Service",
function ($window,$timeout, Service) {
    return {
        restrict: "E",
        replace: true,
        scope: {},
        controllerAs: "data",
        templateUrl: "../RsSummary.html"
        link:function ($scope, element, attrs){
        }
        }
        }

        //this directive is used at another places

 {{key | titleCase}}

                            {{value | textCurrency}}

//This is RsSummary.html

Body:
[

function blockheight(){
var first_block = $(".block1").innerHeight();
$(".block2, .block3").css("height",first_block);
};

$(document).ready(function (){
  blockheight();
});

.block1{
  background: red;
}
.block2{
  background: yellow;
}
.block3{
  background: green;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-xs-4">
<div class="block1">
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
Hai
</div>
</div>
<div class="col-xs-4">
<div class="block2">
hai
</div>
</div>
<div class="col-xs-4">
<div class="block3">
hai
</div>
</div>

Div Height will same acording to large content in first div


问:
Sending email alert from excel to Outlook
I am trying to send a test mail from excel to Outlook, However I am getting error message : Run Time Error 287 in the following line :

```<code>OutMail.Send
</code>```

Please find below my code:

```<code>Sub sendds()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
     Dim myInspector As Outlook.Inspector

Set outlookapp = CreateObject("Outlook.application")
Set OutMail = outlookapp.CreateItem(olMailItem)

With OutMail

    .To = "email address"
    .Subject = "test mail"
    .Body = "Hi this is test email"

    OutMail.Send 'Getting error on this line

    End With

 Set outlookapp = Nothing
Set OutMail = Nothing

End Sub
</code>```

答:
try the below:</p>

```<code>Public Sub emailUsFeature()
Set outApp = CreateObject("Outlook.Application")
Set outMail = outApp.CreateItem(olMailItem)
With outMail
      .To = "abc@xyz.com; def@xyz.com"
      .CC = "ghi@xyz.com"
      .BCC = "jkl@xyz.com"
      .Subject = "This is the subject."
End With
outMail.display
End Sub
</code>```

Body:
I am trying to send a test mail from excel to Outlook, However I am getting error message : Run Time Error 287 in the following line :

OutMail.Send

Please find below my code:

Sub sendds()

    Dim OutMail As MailItem
    Dim outlookapp As Outlook.Application
     Dim myInspector As Outlook.Inspector

Set outlookapp = CreateObject("Outlook.application")
Set OutMail = outlookapp.CreateItem(olMailItem)

With OutMail

    .To = "email address"
    .Subject = "test mail"
    .Body = "Hi this is test email"

    OutMail.Send 'Getting error on this line

    End With

 Set outlookapp = Nothing
Set OutMail = Nothing

End Sub

Body:
try the below:

Public Sub emailUsFeature()
Set outApp = CreateObject("Outlook.Application")
Set outMail = outApp.CreateItem(olMailItem)
With outMail
      .To = "abc@xyz.com; def@xyz.com"
      .CC = "ghi@xyz.com"
      .BCC = "jkl@xyz.com"
      .Subject = "This is the subject."
End With
outMail.display
End Sub


问:
iOS Firebase Crash reporting and mixed project (Objective-C + Swift) - reports are always for "main" function, so non-informative
I've discovered this issue in several projects:

Steps to reproduce:

Create a new Xcode project with Objective-C language (BitCode disabled)

Go to
Firebase console and create a new iOS app

Setup Firebase Crash
Reporting using Cocoapods

Add some Swift code, for example
ViewController.swift

Then, make a crash somwhere in swift code
(for example, inside a button action)

Foe example:

```<code>let array = [42]
let outOfBounds = array[100500]
</code>```

or just

fatalError("error")

it doesn't matter.

6) Few minutes later you will got a crash report named:

main (main.m:14)

I mean, it always says "main(): %some line% and [NSObject(NSObject) doesNotRecognizeSelector:]" , despite file/line where exception has been raised (and despite the type of error, it always "doesNotRecognizeSelector")

As you can see, symbol files were uploaded successfully (report is symbolicated)
I've checked build options and compiler flags - no luck.

Here are code samples if needed:

AppDelegate.m:

```<code>- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [FIRApp configure];

    return YES;
}
</code>```

ViewController.swift:

```<code>@IBAction func buttonTap(_ sender: Any) {

    let array = [42]
    let outOfBounds = array[100500]

}
</code>```

Notice
If you create the same Xcode project, but using Swift only - reports will be "more informative":

And same for clean Objective-C project:

答:
What you're seeing is the stack trace of the process when it crashed.

I mean, it always says "main(): %some line%", despite file/line where
  exception has been raised

The process has to start at main. See line number 3 and you will know that the crash is caused because of an unrecognized selector. You can also see the screen where it crashed like this

I don't think you can get more information than this. If your app is on TestFlight or Appstore you can check the crash from Xcode directly. Make sure the account from which you uploaded is added to Xcode. Go to Windows->Organizer and click on the Crashes tab. Select your application from the list in the left side. Now you'll have a list of crashes. Click on the crash you want to analyze, click on Open in project and select your project. Xcode will open the line where your code crashed.

Check this link to learn more about reading error logs.

Body:
I've discovered this issue in several projects:

Steps to reproduce:

Create a new Xcode project with Objective-C language (BitCode disabled)

Go to
Firebase console and create a new iOS app

Setup Firebase Crash
Reporting using Cocoapods

Add some Swift code, for example
ViewController.swift

Then, make a crash somwhere in swift code
(for example, inside a button action)

Foe example:

let array = [42]
let outOfBounds = array[100500]

or just

fatalError("error")

it doesn't matter.

6) Few minutes later you will got a crash report named:

main (main.m:14)

I mean, it always says "main(): %some line% and [NSObject(NSObject) doesNotRecognizeSelector:]" , despite file/line where exception has been raised (and despite the type of error, it always "doesNotRecognizeSelector")

As you can see, symbol files were uploaded successfully (report is symbolicated)
I've checked build options and compiler flags - no luck.

Here are code samples if needed:

AppDelegate.m:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    [FIRApp configure];

    return YES;
}

ViewController.swift:

@IBAction func buttonTap(_ sender: Any) {

    let array = [42]
    let outOfBounds = array[100500]

}

Notice
If you create the same Xcode project, but using Swift only - reports will be "more informative":

And same for clean Objective-C project:


问:
Register user name with apostrophe (') Android
I have an app in Android where users have to register, and they have to intruduce a name. The problem is that when a user introduce the apostrophe (') in his name (eg Satck'developers). Then in the app I have problems with the database SQLite.

UPDATE user SET name='othername' WHERE name='Stack'developers'`)

This causes a SQLiteException.

How  can I manage this situation in Android? How can I not to allow user to put apostrophe (')?

Thank you very much.

答:
You need to escape reserved characters to avoid SQL injections. There are built-in methods which do that automatically.</p>

```<code>int update(SQLiteDatabase db, String originalName, String newName) {
    ContentValues values = new ContentValues();
    values.put("name", newName);
    return db.update("user", values, "name = ?", new String[]{originalName});
}
</code>```

Body:
You need to escape reserved characters to avoid SQL injections. There are built-in methods which do that automatically.

int update(SQLiteDatabase db, String originalName, String newName) {
    ContentValues values = new ContentValues();
    values.put("name", newName);
    return db.update("user", values, "name = ?", new String[]{originalName});
}


问:
What does gs protocol mean?
I'm playing with Google Speech Recognition API

After a successfully Getting started I'm trying to understand and made some changes in this first example but I don't know what "gs" protocol is and how to set it to use my own audio file.

sync-request.json

```<code>{
  "config": {
      "encoding":"FLAC",
      "sample_rate": 16000
  },
  "audio": {
      "uri":"gs://cloud-samples-tests/speech/brooklyn.flac"
  }
}
</code>```

I tried to change gs protocol to http protocol but doesn't work.

Thanks in advance.

答:
This is what Google's API docs says:

https://cloud.google.com/speech/reference/rpc/google.cloud.speech.v1beta1#audioencoding

URI that points to a file that contains audio data bytes as specified
  in RecognitionConfig. Currently, only Google Cloud Storage URIs are
  supported, which must be specified in the following format:
  gs://bucket_name/object_name (other URI formats return
  google.rpc.Code.INVALID_ARGUMENT).

Title: What does gs protocol mean?

Body:
I'm playing with Google Speech Recognition API

After a successfully Getting started I'm trying to understand and made some changes in this first example but I don't know what "gs" protocol is and how to set it to use my own audio file.

sync-request.json

{
  "config": {
      "encoding":"FLAC",
      "sample_rate": 16000
  },
  "audio": {
      "uri":"gs://cloud-samples-tests/speech/brooklyn.flac"
  }
}

I tried to change gs protocol to http protocol but doesn't work.

Thanks in advance.


问:
jQuery Unrecognised Expression in Safari Only
I have the following code causing an Unrecognised Expression error in Safari only. The error occurs on both OSX and iOS versions of Safari but does not happen in any other browser.

The console says:-

```<code>Error: Syntax error, unrecognized expression: li[data-page-step="1"
</code>```

The HTMl code to match this selector is:-

```<code>    <li style=""
      data-page-step="1"
      data-page-label-previous="< Back"
      data-page-label-next="Next"
      data-page-label-number-text="{page} / {total}"
      data-page-disabled="false"
      data-page-hidden="false"
      data-page-fid="f21"

    >
</code>```

And the JS code which is failing this selector expression is as below, which I assume must be correct, because it works everywhere else (other browsers).

```<code>        v = function(b) {
        var c = {
                step: 1,
                fid: "",
                hidden: !1,
                labelPrevious: "Previous",
                labelNext: "Next",
                progressText: "",
                labelNumberText: "",
                disabled: !1
            },
            d = a('li[data-page-step="' + b + '"');
        if (!d.length) return c;
        for (var e in c) {
            var f = d.data("page" + u(e));
            c[e] = f ? f : ""
        }
        return c.$e = d, c
    }
</code>```

Any ideas why this would fail only on Safari? The [data-next-step...] escaping looks correct - and presumably is correct by other browsers standards.

答:
It shouldn't just be Safari, as this is clearly missing a ]:

```<code>d = a('li[data-page-step="' + b + '"]');
// here ----------------------------^
</code>```

...but I can't help but notice that this works just fine on Chrome v56 and Firefox v51, so apparently they're just more tolerant:

console.log(document.querySelectorAll('div[data-foo="bar"').length);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-foo="bar"></div></code>```

Body:
I have the following code causing an Unrecognised Expression error in Safari only. The error occurs on both OSX and iOS versions of Safari but does not happen in any other browser.

The console says:-

Error: Syntax error, unrecognized expression: li[data-page-step="1"

The HTMl code to match this selector is:-

    <li style=""
      data-page-step="1"
      data-page-label-previous="< Back"
      data-page-label-next="Next"
      data-page-label-number-text="{page} / {total}"
      data-page-disabled="false"
      data-page-hidden="false"
      data-page-fid="f21"

    >

And the JS code which is failing this selector expression is as below, which I assume must be correct, because it works everywhere else (other browsers).

        v = function(b) {
        var c = {
                step: 1,
                fid: "",
                hidden: !1,
                labelPrevious: "Previous",
                labelNext: "Next",
                progressText: "",
                labelNumberText: "",
                disabled: !1
            },
            d = a('li[data-page-step="' + b + '"');
        if (!d.length) return c;
        for (var e in c) {
            var f = d.data("page" + u(e));
            c[e] = f ? f : ""
        }
        return c.$e = d, c
    }

Any ideas why this would fail only on Safari? The [data-next-step...] escaping looks correct - and presumably is correct by other browsers standards.

Body:
It shouldn't just be Safari, as this is clearly missing a ]:

d = a('li[data-page-step="' + b + '"]');
// here ----------------------------^

...but I can't help but notice that this works just fine on Chrome v56 and Firefox v51, so apparently they're just more tolerant:

console.log(document.querySelectorAll('div[data-foo="bar"').length);

<div data-foo="bar"></div>


问:
How can I do a recursive find/replace of a string with awk or sed?
How do I find and replace every occurrence of:

```<code>subdomainA.example.com
</code>```

with

```<code>subdomainB.example.com
</code>```

in every text file under the /home/www/ directory tree recursively?

答:
just to avoid to change also

NearlysubdomainA.example.com

subdomainA.example.comp.other

but still

subdomainA.example.com.IsIt.good

(maybe not good in the idea behind domain root)

```<code>find /home/www/ -type f -exec sed -i 's/\bsubdomainA\.example\.com\b/\1subdomainB.example.com\2/g' {} \;
</code>```

Body:
How do I find and replace every occurrence of:

subdomainA.example.com

with

subdomainB.example.com

in every text file under the /home/www/ directory tree recursively?

Body:
just to avoid to change also

NearlysubdomainA.example.com

subdomainA.example.comp.other

but still

subdomainA.example.com.IsIt.good

(maybe not good in the idea behind domain root)

find /home/www/ -type f -exec sed -i 's/\bsubdomainA\.example\.com\b/\1subdomainB.example.com\2/g' {} \;


问:
why is data not inserted in mysql database no error comes on the screen?
I make a author_create_post.php for a News Agency Portal and Insert the data entries into mysql database. php script and form relies on same page. Form also used validation rules. After fill all form entries finally when I hit submit I got no any error but when I checked my database there is no insert entry, what is the problemb? How to solve it? Here is my complete code...</p>

```<code><?php
include "../tools/db.php";
include "../tools/functions.php";
include "../tools/jdf.php";
FetchPage("check_permission.php");
Permission("author");
if(isset($_POST["save"])){
    if($_POST["title"]!="" && $_POST["text"]!="" && $_POST["category"]!="" && $_POST["slider"]!="" && $_POST["important"]!=""){
        $title = ($_POST["title"]);
        $text = addslashes($_POST["text"]);
        $date = jdate('c');
        $time = time();
        $author_id = $_SESSION["user_id"];
        $cat_id=($_POST["category"]);
        $slider=($_POST["slider"]);
        $important=($_POST["important"]);

            switch($cat_id){
                case 0:
                    $cat_id = 0;
                    break;
                case 1:
                    $cat_id = 1;
                    break;
                case 2:
                    $cat_id = 2;
                    break;
                case 3:
                    $cat_id = 3;
                    break;
                default :
                    $cat_id = 4;
            }
            $s = "SELECT `title` FROM `$tbl_posts` WHERE `title`=:title";
            $res = $connect->prepare($s);
            $res->bindParam(":title",$title);
            $res->execute();
            if($res->rowCount()>=1){
                $exist ="عنوان پست تکراری می باشد!";
        }else{
            $r = $connect->query("SELECT * FROM `$tbl_posts` WHERE `important`=1");
            if($r->rowCount()>=5){
                $imp_count = "درحال حاضر بخش اخبار مهم تکمیل میباشد حداکثر ظرفیت این بخش 4 خبر است!";
            }else{
            $sql = "INSERT INTO `$tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";
            $result = $connect->prepare($sql);
            $result->execute( array(':author_id'=>$author_id, ':title'=>$title, ':category_id'=>$cat_id, ':time'=>$time, ':text'=>$text, ':date'=>$date, ':slider'=>$slider, ':important'=>$important));
            if(isset($result)){
                $success =" پست ".$title." در سایت منتشر شد ✓ ";
            }else{
                echo "<script>alert('Wrong!');</script>";
            }
        }
    }
    }else{
        if($_POST["title"]=="") $titleerr = "عنوان مطلب را درج نمایید!";
        if($_POST["text"]=="") $texterr = "متن پست خالی میباشد!";

    }
}
?>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="mahdi">
    <script type="text/javascript" src="http://dl.20script.ir/img/website.js"></script>
    <meta name="keyword" content="FlatLab, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">
    <link rel="shortcut icon" href="img/favicon.html">

    <title>ارسال مطلب جدید</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-reset.css" rel="stylesheet">
    <!--external css-->
    <link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
    <link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
    <link rel="stylesheet" href="css/owl.carousel.css" type="text/css">
    <!-- Custom styles for this template -->
    <link href="css/style.css" rel="stylesheet">
    <link href="css/style-responsive.css" rel="stylesheet" />

    <!-- HTML5 shim and Respond.js IE8 support of HTML5 tooltipss and media queries -->
    <!--[if lt IE 9]>
      <script src="js/html5shiv.js"></script>
      <script src="js/respond.min.js"></script>
    <![endif]-->
    <script type="text/javascript" src="editor/nicEdit.js"></script>
    <script type="text/javascript">bkLib.onDomLoaded(function() { nicEditors.allTextAreas() });</script>
  </head>

  <body>

  <section id="container" class="">
      <!--header start-->
        <?php FetchPage("top.php"); ?>
      <!--header end-->

      <!--sidebar start-->
      <aside>
        <?php FetchPage("right.php"); ?>
      </aside>
      <!--sidebar end-->
      <!--main content start-->
      <section id="main-content">
            <section class="wrapper">
                <!-- page start-->
                <div class="row">
                    <aside class="profile-info col-lg-9">
                        <?php
                            if(isset($success) && $success!=""){
                        ?>
                        <div class="alert alert-success fade in">
                            <button data-dismiss="alert" class="close close-sm" type="button">
                                <i class="icon-remove"></i>
                            </button>
                            <center><strong>تبریک ! </strong><?=$success;?></center>
                        </div>
                        <?php
                        }
                        ?>

                        <?php
                            if(isset($titleerr) && $titleerr!=""){
                        ?>
                            <div class="alert alert-block alert-danger fade in">
                                <button data-dismiss="alert" class="close close-sm" type="button">
                                    <i class="icon-remove"></i>
                                </button>
                                <center><strong>اخطار ! </strong> <?=$titleerr;?></center>
                            </div>
                        <?php
                        }
                        ?>

                        <?php
                            if(isset($imp_count) && $imp_count!=""){
                        ?>
                            <div class="alert alert-block alert-danger fade in">
                                <button data-dismiss="alert" class="close close-sm" type="button">
                                    <i class="icon-remove"></i>
                                </button>
                                <center><strong>اخطار ! </strong> <?=$imp_count;?></center>
                            </div>
                        <?php
                        }
                        ?>

                        <?php
                            if(isset($texterr) && $texterr!=""){
                        ?>
                            <div class="alert alert-block alert-danger fade in">
                                <button data-dismiss="alert" class="close close-sm" type="button">
                                    <i class="icon-remove"></i>
                                </button>
                                <center><strong>اخطار ! </strong> <?=$texterr;?></center>
                            </div>
                        <?php
                        }
                        ?>
                        <section class="panel">
                            <div class="bio-graph-heading">ارسال مطلب جدید</div>
                            <div class="panel-body bio-graph-info">
                                <form class="form-horizontal" role="form" method="POST">
                                    <div class="form-group">
                                        <label class="col-lg-2 control-label">عنوان مطلب</label>
                                        <div class="col-lg-6">
                                            <input type="text" class="form-control" style="width: 620px;" name="title" placeholder=" ">
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="col-lg-2 control-label">متن پست</label>
                                        <div class="col-lg-6">
                                                <textarea name = "text" style="width: 620px; height: 200px;"></textarea>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="col-lg-2 control-label">دسته بندی</label>
                                        <div class="col-lg-6">
                                            <select name="category">
                                                <?php
                                                $sql = "SELECT * FROM `$tbl_category` ORDER BY `id` DESC";
                                                $result = $connect->query($sql);
                                                while($rows = $result->fetch(PDO::FETCH_ASSOC)){
                                                ?>
                                                <option value="<?=$rows["id"];?>"><?=$rows["title"];?></option>
                                                <?php
                                                }
                                                ?>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="col-lg-2 control-label">نمایش در اسلایدر</label>
                                        <div class="col-lg-6">
                                            <select name="slider">
                                                <option value="0">غیرفعال</option>
                                                <option value="1">فعال</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <label class="col-lg-2 control-label">نمایش در اخبار مهم</label>
                                        <div class="col-lg-6">
                                            <select name="important">
                                                <option value="0">غیرفعال</option>
                                                <option value="1">فعال</option>
                                            </select>
                                        </div>
                                    </div>

                                    <div class="form-group">
                                        <div class="col-lg-offset-2 col-lg-10">
                                            <input type="submit" name="save" class="btn btn-success" value="ثبت">
                                            <button type="reset" class="btn btn-default">انصراف</button>
                                        </div>
                                    </div>
                                </form>
                            </div>
                        </section>
                    </aside>
                </div>

                <!-- page end-->
            </section>
        </section>
        <!--main content end-->
    </section>

    <!-- js placed at the end of the document so the pages load faster -->
    <script src="js/jquery.js"></script>
    <script src="js/jquery-1.8.3.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/jquery.scrollTo.min.js"></script>
    <script src="js/jquery.nicescroll.js" type="text/javascript"></script>
    <script src="js/jquery.sparkline.js" type="text/javascript"></script>
    <script src="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.js"></script>
    <script src="js/owl.carousel.js" ></script>
    <script src="js/jquery.customSelect.min.js" ></script>

    <!--common script for all pages-->
    <script src="js/common-scripts.js"></script>

    <!--script for this page-->
    <script src="js/sparkline-chart.js"></script>
    <script src="js/easy-pie-chart.js"></script>

  <script>

      //owl carousel

      $(document).ready(function() {
          $("#owl-demo").owlCarousel({
              navigation : true,
              slideSpeed : 300,
              paginationSpeed : 400,
              singleItem : true

          });
      });

      //custom select box

      $(function(){
          $('select.styled').customSelect();
      });

  </script>

  </body>
</html>
</code>```

答:
change this:

```<code>$sql = "INSERT INTO `$tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";
</code>```

to

```<code>$sql = "INSERT INTO `tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";
</code>```

You had a $ sign before your table name

Also when verifying the success or failure of the execute function, do this

```<code>    if ($result === true) {
        $success =" پست ".$title." در سایت منتشر شد ✓ ";
    } else {
        echo "<script>alert('Wrong!');</script>";
    }
</code>```

isset does not verify that the query was successfully executed. And remember execute() returns true or false So you need to check based on the boolean values(true or false)

Body:
I make a author_create_post.php for a News Agency Portal and Insert the data entries into mysql database. php script and form relies on same page. Form also used validation rules. After fill all form entries finally when I hit submit I got no any error but when I checked my database there is no insert entry, what is the problemb? How to solve it? Here is my complete code...

<?php
include "../tools/db.php";
include "../tools/functions.php";
include "../tools/jdf.php";
FetchPage("check_permission.php");
Permission("author");
if(isset($_POST["save"])){
    if($_POST["title"]!="" && $_POST["text"]!="" && $_POST["category"]!="" && $_POST["slider"]!="" && $_POST["important"]!=""){
        $title = ($_POST["title"]);
        $text = addslashes($_POST["text"]);
        $date = jdate('c');
        $time = time();
        $author_id = $_SESSION["user_id"];
        $cat_id=($_POST["category"]);
        $slider=($_POST["slider"]);
        $important=($_POST["important"]);

            switch($cat_id){
                case 0:
                    $cat_id = 0;
                    break;
                case 1:
                    $cat_id = 1;
                    break;
                case 2:
                    $cat_id = 2;
                    break;
                case 3:
                    $cat_id = 3;
                    break;
                default :
                    $cat_id = 4;
            }
            $s = "SELECT `title` FROM `$tbl_posts` WHERE `title`=:title";
            $res = $connect->prepare($s);
            $res->bindParam(":title",$title);
            $res->execute();
            if($res->rowCount()>=1){
                $exist ="عنوان پست تکراری می باشد!";
        }else{
            $r = $connect->query("SELECT * FROM `$tbl_posts` WHERE `important`=1");
            if($r->rowCount()>=5){
                $imp_count = "درحال حاضر بخش اخبار مهم تکمیل میباشد حداکثر ظرفیت این بخش 4 خبر است!";
            }else{
            $sql = "INSERT INTO `$tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";
            $result = $connect->prepare($sql);
            $result->execute( array(':author_id'=>$author_id, ':title'=>$title, ':category_id'=>$cat_id, ':time'=>$time, ':text'=>$text, ':date'=>$date, ':slider'=>$slider, ':important'=>$important));
            if(isset($result)){
                $success =" پست ".$title." در سایت منتشر شد ✓ ";
            }else{
                echo "";
            }
        }
    }
    }else{
        if($_POST["title"]=="") $titleerr = "عنوان مطلب را درج نمایید!";
        if($_POST["text"]=="") $texterr = "متن پست خالی میباشد!";

    }
}
?>
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="mahdi">

    <meta name="keyword" content="FlatLab, Dashboard, Bootstrap, Admin, Template, Theme, Responsive, Fluid, Retina">
    <link rel="shortcut icon" href="img/favicon.html">

    <title>ارسال مطلب جدید</title>

    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-reset.css" rel="stylesheet">

    <link href="assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
    <link href="assets/jquery-easy-pie-chart/jquery.easy-pie-chart.css" rel="stylesheet" type="text/css" media="screen"/>
    <link rel="stylesheet" href="css/owl.carousel.css" type="text/css">

    <link href="css/style.css" rel="stylesheet">
    <link href="css/style-responsive.css" rel="stylesheet" />

        <?php FetchPage("top.php"); ?>

        <?php FetchPage("right.php"); ?>

                        <?php
                            if(isset($success) && $success!=""){
                        ?>

                            <button data-dismiss="alert" class="close close-sm" type="button">

                            </button>
                            تبریک ! <?=$success;?>

                        <?php
                        }
                        ?>

                        <?php
                            if(isset($titleerr) && $titleerr!=""){
                        ?>

                                <button data-dismiss="alert" class="close close-sm" type="button">

                                </button>
                                اخطار !  <?=$titleerr;?>

                        <?php
                        }
                        ?>

                        <?php
                            if(isset($imp_count) && $imp_count!=""){
                        ?>

                                <button data-dismiss="alert" class="close close-sm" type="button">

                                </button>
                                اخطار !  <?=$imp_count;?>

                        <?php
                        }
                        ?>

                        <?php
                            if(isset($texterr) && $texterr!=""){
                        ?>

                                <button data-dismiss="alert" class="close close-sm" type="button">

                                </button>
                                اخطار !  <?=$texterr;?>

                        <?php
                        }
                        ?>

ارسال مطلب جدید

                                <form class="form-horizontal" role="form" method="POST">

                                        عنوان مطلب

                                            <input type="text" class="form-control" style="width: 620px;" name="title" placeholder=" ">

                                        متن پست

                                                <textarea name = "text" style="width: 620px; height: 200px;"></textarea>

                                        دسته بندی

                                            <select name="category">
                                                <?php
                                                $sql = "SELECT * FROM `$tbl_category` ORDER BY `id` DESC";
                                                $result = $connect->query($sql);
                                                while($rows = $result->fetch(PDO::FETCH_ASSOC)){
                                                ?>
                                                <option value="<?=$rows["id"];?>"><?=$rows["title"];?></option>
                                                <?php
                                                }
                                                ?>
                                            </select>

                                        نمایش در اسلایدر

                                            <select name="slider">
                                                <option value="0">غیرفعال</option>
                                                <option value="1">فعال</option>
                                            </select>

                                        نمایش در اخبار مهم

                                            <select name="important">
                                                <option value="0">غیرفعال</option>
                                                <option value="1">فعال</option>
                                            </select>

                                            <input type="submit" name="save" class="btn btn-success" value="ثبت">
                                            <button type="reset" class="btn btn-default">انصراف</button>

                                </form>

Body:
change this:

$sql = "INSERT INTO `$tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";

to

$sql = "INSERT INTO `tbl_posts` ( `author_id`, `title`, `category_id`, `time`, `text`, `date`, `slider`, `important` ) VALUES ( :author_id, :title, :category_id, :time, :text, :date, :slider, :important )";

You had a $ sign before your table name

Also when verifying the success or failure of the execute function, do this

    if ($result === true) {
        $success =" پست ".$title." در سایت منتشر شد ✓ ";
    } else {
        echo "<script>alert('Wrong!');</script>";
    }

isset does not verify that the query was successfully executed. And remember execute() returns true or false So you need to check based on the boolean values(true or false)


问:
Could not resolve SpecInfo from Sputnik Runner
I am trying to run Arquillian Tests using spock arquillian container

```<code><dependency>
    <groupId>org.jboss.arquillian.spock</groupId>
    <artifactId>arquillian-spock-container</artifactId>
    <version>1.0.0.Beta3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.4.3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.spockframework</groupId>
    <artifactId>spock-core</artifactId>
    <version>0.7-groovy-2.0</version>
    <scope>test</scope>
</dependency>
</code>```

and I am getting the following error:

Could not resolve SpecInfo from Sputnik Runner

What can cause this problem?

答:
You can always build a test jar (with dependencies preferrably):

using maven assembly plugin (see maven assembly docs, also How can I make the test jar include dependencies in Maven?),

maven-jar-plugin with test-jar goal (but then you will have to add all dependencies manually, see maven jar plugin docs)

or create a fat jar with any other method you like (shade, onejar-maven-plugin, etc).

After that just run your tests like this:

java -cp xxx-test-with-dependencies.jar org.junit.runner.JUnitCore full.pkg.of.testSpec

It works because Sputnik is a JUnit test runner, so you need to start from there.

Add any options you like, -Xms, -Danything that is needed (for example Geb needs reporting dir to be set).
Add additional classpath elements (-cp) it your jar does not contain all dependencies.

Body:
I am trying to run Arquillian Tests using spock arquillian container

<dependency>
    <groupId>org.jboss.arquillian.spock</groupId>
    <artifactId>arquillian-spock-container</artifactId>
    <version>1.0.0.Beta3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.codehaus.groovy</groupId>
    <artifactId>groovy-all</artifactId>
    <version>2.4.3</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.spockframework</groupId>
    <artifactId>spock-core</artifactId>
    <version>0.7-groovy-2.0</version>
    <scope>test</scope>
</dependency>

and I am getting the following error:

Could not resolve SpecInfo from Sputnik Runner

What can cause this problem?


问:
ruby on rails using fixtures
I am using fixtures in testing.

For example:

```<code>post bookings_path, params: { journal: { from_account_number: "1",
                                         from_account: "Test",
                                         from_amount: "12",
                                         to_account_number: "2",
                                         to_account: "Test2",
                                         to_amount: "12"
      } }
</code>```

Is it possible to replace

```<code>from_account_number: "1",
from_account: "Test",
from_amount: "12",
to_account_number: "2",
to_account: "Test2",
to_amount: "12"
</code>```

with one fixture call?

答:
Of course, assuming all that params are from one object and use rspec with it, you can do this:

```<code>describe '#POST to bookings_path' do
  before do
    @booking = bookings(:one)
  end

  it 'should be successful' do
    post bookings_path, params: { journal: @booking.attributes }

    expect(response.status).to eq(201)
  end
end
</code>```

If for example they are from one same model but from 2 different objects (like account_1 and account_2), then just substitute with this:

```<code>    data = @account_1.attributes
    post bookings_path, params: { journal: data.merge(@account_2.attributes) }
</code>```

Title: ruby on rails using fixtures

Body:
I am using fixtures in testing.

For example:

post bookings_path, params: { journal: { from_account_number: "1",
                                         from_account: "Test",
                                         from_amount: "12",
                                         to_account_number: "2",
                                         to_account: "Test2",
                                         to_amount: "12"
      } }

Is it possible to replace

from_account_number: "1",
from_account: "Test",
from_amount: "12",
to_account_number: "2",
to_account: "Test2",
to_amount: "12"

with one fixture call?

Body:
Of course, assuming all that params are from one object and use rspec with it, you can do this:

describe '#POST to bookings_path' do
  before do
    @booking = bookings(:one)
  end

  it 'should be successful' do
    post bookings_path, params: { journal: @booking.attributes }

    expect(response.status).to eq(201)
  end
end

If for example they are from one same model but from 2 different objects (like account_1 and account_2), then just substitute with this:

    data = @account_1.attributes
    post bookings_path, params: { journal: data.merge(@account_2.attributes) }


问:
Sql Query Between Different Databases like Oracle and SQL Server in C#
I have two databases Sql Server and Oracle databases, example:

tableA sql server

tableB sql server

tableC Oracle

tableD Oracle

tableE Oracle

tableF Oracle

答:
You will need to install the Oracle Client first.  Google "Oracle Database Client windows" to find the download from Oracle's site.

1) Install the 64-bit package first.  (VERY important as there is a bug that messes things up if you install the x86 package first)

2) Change the install path to "C:\oracle\x64"

3) Once installed install the 32-bit package

4) Change the install path to "C:\oracle\x86"

5) Once installation is finish navigate to
"C:\oracle\x86\11.2.0\client_1\network\admin"

Create or edit a file named "sqlnet.ora" in the folder from #5.  Put the following in the file:

```<code># This file is actually generated by netca. But if customers choose to
# install "Software Only", this file wont exist and without the native
# authentication, they will not be able to connect to the database on NT.

SQLNET.AUTHENTICATION_SERVICES = (NTS)
</code>```

6) Create or edit a file named "TNSNAMES.ora" in this directory. Put in your normal TNS connection string (your Oracle DBA probably knows this).  An example is below:

```<code>ServerInstanceName =
 (DESCRIPTION=
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL =TCP) (PORT=1529) (HOST=192.168.1.100))
    )
    (CONNECT_DATA=
    (SID=ServerInstanceName)
    )
)
</code>```

where ServerInstanceName is the SID of your Oracle server

7) Update TNSNAMES.ora with any servers you need to connect to

8) Copy these files to "C:\oracle\x64\11.2.0\client_1\network\admin"

9) Reboot the machine

Now you should have the Oracle client installed and you can set up a linked server for SQL Server to connect with.  Open SSMS and connect to your server.  Expand Server Objects and then right click "Linked Servers" and click "New Linked Server"

1) Set linked server name to whatever you want to call the server when querying i.e. OracleSvr

2) Change Provider to "Oracle Provider for OLE DB"

3) For Product Name put in "OraOLEDB.Oracle.1"

4) For Data source put in the same value you used for the server name in the TNS file i.e. ServerInstanceName in our example.

5) Go to Security on the left.

6) Set however you want logins to be made.  If not sure how to do this google it

7) Go to Server Options on the left.

8) Make sure Data Access, RPC, RPC Out, Use Remote Collation are all set to True.

9) Click OK.

10) Open Server Objects --> Linked Servers --> Providers

11) Right Click OraOLEDB.Oracle and click properties

12) Click Enable under "Allow inprocess"  Click OK.

You should now be able to query the server from within SQL server.

```<code>select * from OracleSvr..SchemaName.TableName
</code>```

Body:
You will need to install the Oracle Client first.  Google "Oracle Database Client windows" to find the download from Oracle's site.

1) Install the 64-bit package first.  (VERY important as there is a bug that messes things up if you install the x86 package first)

2) Change the install path to "C:\oracle\x64"

3) Once installed install the 32-bit package

4) Change the install path to "C:\oracle\x86"

5) Once installation is finish navigate to
"C:\oracle\x86\11.2.0\client_1\network\admin"

Create or edit a file named "sqlnet.ora" in the folder from #5.  Put the following in the file:

# This file is actually generated by netca. But if customers choose to
# install "Software Only", this file wont exist and without the native
# authentication, they will not be able to connect to the database on NT.

SQLNET.AUTHENTICATION_SERVICES = (NTS)

6) Create or edit a file named "TNSNAMES.ora" in this directory. Put in your normal TNS connection string (your Oracle DBA probably knows this).  An example is below:

ServerInstanceName =
 (DESCRIPTION=
    (ADDRESS_LIST =
    (ADDRESS = (PROTOCOL =TCP) (PORT=1529) (HOST=192.168.1.100))
    )
    (CONNECT_DATA=
    (SID=ServerInstanceName)
    )
)

where ServerInstanceName is the SID of your Oracle server

7) Update TNSNAMES.ora with any servers you need to connect to

8) Copy these files to "C:\oracle\x64\11.2.0\client_1\network\admin"

9) Reboot the machine

Now you should have the Oracle client installed and you can set up a linked server for SQL Server to connect with.  Open SSMS and connect to your server.  Expand Server Objects and then right click "Linked Servers" and click "New Linked Server"

1) Set linked server name to whatever you want to call the server when querying i.e. OracleSvr

2) Change Provider to "Oracle Provider for OLE DB"

3) For Product Name put in "OraOLEDB.Oracle.1"

4) For Data source put in the same value you used for the server name in the TNS file i.e. ServerInstanceName in our example.

5) Go to Security on the left.

6) Set however you want logins to be made.  If not sure how to do this google it

7) Go to Server Options on the left.

8) Make sure Data Access, RPC, RPC Out, Use Remote Collation are all set to True.

9) Click OK.

10) Open Server Objects --> Linked Servers --> Providers

11) Right Click OraOLEDB.Oracle and click properties

12) Click Enable under "Allow inprocess"  Click OK.

You should now be able to query the server from within SQL server.

select * from OracleSvr..SchemaName.TableName


问:
Rails - fill form field with value from database
Scenario:
I have a simple_form with a field called "Port". The user should be able to select the lowest free port, or override this selection. All reserved ports are saved in the "port"-model. That means every port that is not in that model is available.

Port Pattern:
The range is 8080-65080. The step is 100 (8080, 8180, 8280...).

Env:

- Rails 5

- sqlite3

- simple_forms

- html.erb

Question:
I have absolutely no idea, how to approach this task. I hope for a good tip. I've been searching the web all day long for this task, but I didn't find anything.

答:
Assuming that your Port model has an integer field called value for the port number, go to your port.rb file and create the following method:

```<code>def self.available_ports
    unavailable_ports = Port.order(value: :asc).pluck(:value)
    first_port = 8080
    last_port = 65080
    step = 100
    all_ports = (first_port..last_port).step(step).collect { |n| n }
    all_ports - unavailable_ports
end
</code>```

Call Port.available_ports and you'll get an array with all available ports with the lowest port being the first port the in array. Then, in your form, display that to the user.

Body:
Assuming that your Port model has an integer field called value for the port number, go to your port.rb file and create the following method:

def self.available_ports
    unavailable_ports = Port.order(value: :asc).pluck(:value)
    first_port = 8080
    last_port = 65080
    step = 100
    all_ports = (first_port..last_port).step(step).collect { |n| n }
    all_ports - unavailable_ports
end

Call Port.available_ports and you'll get an array with all available ports with the lowest port being the first port the in array. Then, in your form, display that to the user.


问:
How to hide div when click on anywhere on the display
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div>
  <input type="button" id="Btn1" value="BtnClick" />
</div>
<div id="PopupDiv">
  <p>Hello Popup Grid</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> </code>```

答:
You can check following code hope it helps: - </p>

```<code><html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $('#PopupDiv').hide();
            $('body').click(function(evt) {
            if(evt.target.id == "Btn1")
            {
            $('#PopupDiv').show();
            }else {
             $('#PopupDiv').hide();
             }
})
        })
    </script>
</head>
<body>
    <div>
        <input type="button" id="Btn1" value="BtnClick" />
    </div>

    <div id="PopupDiv">
        <p>Hello Popup Grid</p>
    </div>
</body>
</html>
</code>```

Body:
Here My Div #PopupDiv by dafault its in hiding when i click on #Btn1 its display #PopupDiv but whenevere user click anywhere on the display it should be hide

       $(document).ready(function () {
          $('#PopupDiv').hide();
          $('#Btn1').click(function () {
             alert()
             $('#PopupDiv').show();
          })
          $(document).click(function () {
             alert('o')
             if ($('#PopupDiv').is(':visible')) {
                alert('vis');
             }
          })
       })

  <input type="button" id="Btn1" value="BtnClick" />

Hello Popup Grid

Body:
You can check following code hope it helps: -

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $('#PopupDiv').hide();
            $('body').click(function(evt) {
            if(evt.target.id == "Btn1")
            {
            $('#PopupDiv').show();
            }else {
             $('#PopupDiv').hide();
             }
})
        })
    </script>
</head>
<body>
    <div>
        <input type="button" id="Btn1" value="BtnClick" />
    </div>

    <div id="PopupDiv">
        <p>Hello Popup Grid</p>
    </div>
</body>
</html>


问:
Handling NULL values in Hive
I am trying to create a table (table 2) in Hive from another table (table 1). I am trying to exclude certain rows with NULL values and tried the following condition.

```<code>    insert overwrite table table2 partition (date = '2013-06-01')
    select column1, column 2....
    from table1
    where column1 is not NULL or column1 <> '';
</code>```

However, when I try this following query with the new table I get 300+ rows with NULL vaues:

```<code>    select count(*) from table2 where column1 is NULL;
</code>```

Could someone point to what is causing these NULL values?

Thank you.

Ravi

答:
To check for the NULL data for column1 and consider your datatype of it is String, you could use below command :

```<code>select * from tbl_name where column1 is null or column1 <> '';
</code>```

Title: Handling NULL values in Hive

Body:
I am trying to create a table (table 2) in Hive from another table (table 1). I am trying to exclude certain rows with NULL values and tried the following condition.

    insert overwrite table table2 partition (date = '2013-06-01')
    select column1, column 2....
    from table1
    where column1 is not NULL or column1 <> '';

However, when I try this following query with the new table I get 300+ rows with NULL vaues:

    select count(*) from table2 where column1 is NULL;

Could someone point to what is causing these NULL values?

Thank you.

Ravi

Body:
To check for the NULL data for column1 and consider your datatype of it is String, you could use below command :

select * from tbl_name where column1 is null or column1 <> '';


问:
IllegalStateException: PWC3990: getWriter() has already been called for this response
```<code>java.lang.IllegalStateException: PWC3990: getWriter() has already been called for this response
</code>```

How to solve this error? I run a simple servlet code to display the bar graph.

答: You cannot call both getOutputStream() and getWriter() on the same response. Keep in mind that JSP implicitly uses getWriter().

Body:
java.lang.IllegalStateException: PWC3990: getWriter() has already been called for this response

How to solve this error? I run a simple servlet code to display the bar graph.


问:
How can I create a deep neural network which has a capability to take a decision for hypothesis?
Basically, I am interested in solving a hypothesis problem, where I am only aware of the data distribution of a null hypothesis and don't know anything about the alternative case.

My concern is how should I train my deep neural network so that it can classify or recognise whether a particular sample data has a similar distribution as in null hypothesis case or it's from another class(An alternative Hypothesis case).

According to my understanding, It's different from a binary classification (one vs all case), because in that case, we know what data we are going to tackle, but here in my case alternative hypothesis case can follow any data distribution.

Here I am giving you an example situation, what I want exactly

Suppose I want to predict that a person is likely to have cancer or not

e.g

I have a data set of the factors that cause cancer like,

Parameter A=1,Parameter B=3.87,Parameter C=5.6,Has cancer = yes

But I don't have a data set where

Parameter A=2,Parameter B=1.87,Parameter C=2.6,Has cancer = No

Can be anything like this

Means I don't know about anything which leads to a conclusion of not having cancer, can I still train my model to recognise whether a person has cancer?

答:
The Answer is kind of Yes and No...

If you don't know anything about the distribution of data points in alternative hypotheses they could in principle be indistinguishably close to your known distribution, therefor you would always classify them (wrongly) as "myHypothesis". That was the No part.

For the Yes part: What you can do is excluding data-sets that are sufficiently different from your hypothesis to make it unlikely that they are generated by the same distribution. This means in principle you can then make a statement like "the probability of myDistribution generating the given data is less then some value".

However I don't think that a neural-net is necessarily the best way to make such a statement. It could be sufficient, to fit a model (ideally a known model... so if you know what exact distribution you have you should use that and fit the parameters rather than using a neural net) to your training-data and then just calculate the probability (for instance using Bayesian Inference) of observing your test data given your model. For more info you can check out something like this