问:
Multiple transactions to same document failure in flutter firestore
I am been trying to implement multiple transactions to the same document in flutter application which is using firestore as a its database, but it is crashing the application. The same thing when it was implemented in native apps of Xcode or android studio this issue didn't occur for even once.

Is there any guide how to make multiple transactions successful in flutter firestore.

For Instance, if more than 1 user from different devices is making the transaction to the same document at the same time, the transaction fails and the app crashes.

How could this be resolved?

```<code>Firestore.instance.runTransaction((Transaction tx) async {
      DocumentSnapshot postSnapshot = await tx.get(docRef);
      if (postSnapshot.exists) {
        await tx.update(docRef, <String, dynamic>{'likes': postSnapshot.data['likes'] + 1});
       // print("transaction completed");
      }
    })
</code>```

ERROR LOGS

2020-05-27 18:43:14.529 1022-1344/dev.jideguru.social_app_ui
  E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4 Process:
  dev.jideguru.social_app_ui, PID: 1022 java.lang.RuntimeException: An
  error occurred while executing doInBackground() at
  android.os.AsyncTask$3.done(AsyncTask.java:353) at
  java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
  at java.util.concurrent.FutureTask.run(FutureTask.java:271) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764) Caused by:
  java.lang.AssertionError: INTERNAL ASSERTION FAILED: A transaction
  object cannot be used after its update callback has been invoked. at
  com.google.firebase.firestore.util.Assert.fail(com.google.firebase:firebase-firestore@@21.3.0:46)
  at
  com.google.firebase.firestore.util.Assert.hardAssert(com.google.firebase:firebase-firestore@@21.3.0:31)
  at
  com.google.firebase.firestore.core.Transaction.ensureCommitNotCalled(com.google.firebase:firebase-firestore@@21.3.0:246)
  at
  com.google.firebase.firestore.core.Transaction.lookup(com.google.firebase:firebase-firestore@@21.3.0:81)
  at
  com.google.firebase.firestore.Transaction.getAsync(com.google.firebase:firebase-firestore@@21.3.0:191)
  at
  com.google.firebase.firestore.Transaction.get(com.google.firebase:firebase-firestore@@21.3.0:228)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:613)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:608)
  at android.os.AsyncTask$2.call(AsyncTask.java:333) at
  java.util.concurrent.FutureTask.run(FutureTask.java:266) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764)  2020-05-27 18:43:14.529
  1022-1346/dev.jideguru.social_app_ui E/AndroidRuntime: FATAL
  EXCEPTION: AsyncTask #6 Process: dev.jideguru.social_app_ui, PID: 1022
  java.lang.RuntimeException: An error occurred while executing
  doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:353) at
  java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
  at java.util.concurrent.FutureTask.run(FutureTask.java:271) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764) Caused by:
  java.lang.AssertionError: INTERNAL ASSERTION FAILED: A transaction
  object cannot be used after its update callback has been invoked. at
  com.google.firebase.firestore.util.Assert.fail(com.google.firebase:firebase-firestore@@21.3.0:46)
  at
  com.google.firebase.firestore.util.Assert.hardAssert(com.google.firebase:firebase-firestore@@21.3.0:31)
  at
  com.google.firebase.firestore.core.Transaction.ensureCommitNotCalled(com.google.firebase:firebase-firestore@@21.3.0:246)
  at
  com.google.firebase.firestore.core.Transaction.lookup(com.google.firebase:firebase-firestore@@21.3.0:81)
  at
  com.google.firebase.firestore.Transaction.getAsync(com.google.firebase:firebase-firestore@@21.3.0:191)
  at
  com.google.firebase.firestore.Transaction.get(com.google.firebase:firebase-firestore@@21.3.0:228)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:613)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:608)
  at android.os.AsyncTask$2.call(AsyncTask.java:333) at
  java.util.concurrent.FutureTask.run(FutureTask.java:266) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764)

Link To the Issue

答:
Caused by: java.lang.AssertionError: INTERNAL ASSERTION FAILED: A transaction object cannot be used after its update callback has been invoked.

It looks like the transaction is being used after it's been committed/canceled.

This is a known issue in the FlutterFire library, as recorded in this issue on the open-source repo.

There is a workaround mentioned in this comment. So you can either try to apply that to your case, propose a PR that fixes the bug, or wait until somebody else fixes it.

Body:
I am been trying to implement multiple transactions to the same document in flutter application which is using firestore as a its database, but it is crashing the application. The same thing when it was implemented in native apps of Xcode or android studio this issue didn't occur for even once.

Is there any guide how to make multiple transactions successful in flutter firestore.

For Instance, if more than 1 user from different devices is making the transaction to the same document at the same time, the transaction fails and the app crashes.

How could this be resolved?

Firestore.instance.runTransaction((Transaction tx) async {
      DocumentSnapshot postSnapshot = await tx.get(docRef);
      if (postSnapshot.exists) {
        await tx.update(docRef, <String, dynamic>{'likes': postSnapshot.data['likes'] + 1});
       // print("transaction completed");
      }
    })

ERROR LOGS

2020-05-27 18:43:14.529 1022-1344/dev.jideguru.social_app_ui
  E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4 Process:
  dev.jideguru.social_app_ui, PID: 1022 java.lang.RuntimeException: An
  error occurred while executing doInBackground() at
  android.os.AsyncTask$3.done(AsyncTask.java:353) at
  java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
  at java.util.concurrent.FutureTask.run(FutureTask.java:271) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764) Caused by:
  java.lang.AssertionError: INTERNAL ASSERTION FAILED: A transaction
  object cannot be used after its update callback has been invoked. at
  com.google.firebase.firestore.util.Assert.fail(com.google.firebase:firebase-firestore@@21.3.0:46)
  at
  com.google.firebase.firestore.util.Assert.hardAssert(com.google.firebase:firebase-firestore@@21.3.0:31)
  at
  com.google.firebase.firestore.core.Transaction.ensureCommitNotCalled(com.google.firebase:firebase-firestore@@21.3.0:246)
  at
  com.google.firebase.firestore.core.Transaction.lookup(com.google.firebase:firebase-firestore@@21.3.0:81)
  at
  com.google.firebase.firestore.Transaction.getAsync(com.google.firebase:firebase-firestore@@21.3.0:191)
  at
  com.google.firebase.firestore.Transaction.get(com.google.firebase:firebase-firestore@@21.3.0:228)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:613)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:608)
  at android.os.AsyncTask$2.call(AsyncTask.java:333) at
  java.util.concurrent.FutureTask.run(FutureTask.java:266) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764)  2020-05-27 18:43:14.529
  1022-1346/dev.jideguru.social_app_ui E/AndroidRuntime: FATAL
  EXCEPTION: AsyncTask #6 Process: dev.jideguru.social_app_ui, PID: 1022
  java.lang.RuntimeException: An error occurred while executing
  doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:353) at
  java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:383)
  at java.util.concurrent.FutureTask.setException(FutureTask.java:252)
  at java.util.concurrent.FutureTask.run(FutureTask.java:271) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245) at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764) Caused by:
  java.lang.AssertionError: INTERNAL ASSERTION FAILED: A transaction
  object cannot be used after its update callback has been invoked. at
  com.google.firebase.firestore.util.Assert.fail(com.google.firebase:firebase-firestore@@21.3.0:46)
  at
  com.google.firebase.firestore.util.Assert.hardAssert(com.google.firebase:firebase-firestore@@21.3.0:31)
  at
  com.google.firebase.firestore.core.Transaction.ensureCommitNotCalled(com.google.firebase:firebase-firestore@@21.3.0:246)
  at
  com.google.firebase.firestore.core.Transaction.lookup(com.google.firebase:firebase-firestore@@21.3.0:81)
  at
  com.google.firebase.firestore.Transaction.getAsync(com.google.firebase:firebase-firestore@@21.3.0:191)
  at
  com.google.firebase.firestore.Transaction.get(com.google.firebase:firebase-firestore@@21.3.0:228)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:613)
  at
  io.flutter.plugins.firebase.cloudfirestore.CloudFirestorePlugin$5.doInBackground(CloudFirestorePlugin.java:608)
  at android.os.AsyncTask$2.call(AsyncTask.java:333) at
  java.util.concurrent.FutureTask.run(FutureTask.java:266) at
  android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)  at
  java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
  at
  java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
  at java.lang.Thread.run(Thread.java:764)

Link To the Issue


来源: stackexchange

问:
How to start an application with SCDF in a defined port
How do I start an application with SCDF in a defined port. I tried passing the property "deployer.myapp.local.javaOpts":"-Dserver.port=11111", but the pipeline is not being deployed now.</p>

答:
You don't have to use the javaOpts option to set the server.port. It can be set as an application property.

Something like "app.myapp.server.port= 11111" when deploying the stream.

ContentLicense: CC BY-SA 4.0


问:
How to call a TYPO3 custom viewhelper from a typoscript (.ts) file and receive a response from viewhelper?
I tried to call a custom viewhelper in TYPO3 9.5.9 from a typoscript file. But it is not working.
An example for viewhelper is given below:

```<code><?php
namespace MyVendor\BlogExample\ViewHelpers;

use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GravatarViewHelper extends AbstractViewHelper
{
   use CompileWithRenderStatic;

   public static function renderStatic(
       array $arguments,
       \Closure $renderChildrenClosure,
       RenderingContextInterface $renderingContext
   ) {
       return 'World';
   }
}
</code>```

How can I call this custom viewhelper from a typoscript (.ts) file and get a response ?

答:
You can use a FLUIDTEMPLATE cObject with a minimal template (e.g. via template property):

```<code>10 = FLUIDTEMPLATE
10 {
   template.cObject = TEXT
   template.cObject.value(
      <html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" xmlns:mv="http://typo3.org/ns/MyVendor/BlogExample/ViewHelpers" data-namespace-typo3-fluid="true">
      <mv:GravatarViewHelper />
   )
}
</code>```

It seems to be possible. But as Bernd already asked: Why would one do that?

Body:
I tried to call a custom viewhelper in TYPO3 9.5.9 from a typoscript file. But it is not working.
An example for viewhelper is given below:

<?php
namespace MyVendor\BlogExample\ViewHelpers;

use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\Traits\CompileWithRenderStatic;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class GravatarViewHelper extends AbstractViewHelper
{
   use CompileWithRenderStatic;

   public static function renderStatic(
       array $arguments,
       \Closure $renderChildrenClosure,
       RenderingContextInterface $renderingContext
   ) {
       return 'World';
   }
}

How can I call this custom viewhelper from a typoscript (.ts) file and get a response ?

Body:
You can use a FLUIDTEMPLATE cObject with a minimal template (e.g. via template property):

10 = FLUIDTEMPLATE
10 {
   template.cObject = TEXT
   template.cObject.value(
      <html xmlns:f="http://typo3.org/ns/TYPO3/CMS/Fluid/ViewHelpers" xmlns:mv="http://typo3.org/ns/MyVendor/BlogExample/ViewHelpers" data-namespace-typo3-fluid="true">
      <mv:GravatarViewHelper />
   )
}

It seems to be possible. But as Bernd already asked: Why would one do that?


问:
Vuex : How to check if an action exists before dispatching it?
I am getting this error : "Unknown local action type..." when I'm dispatching my action, which happens to be in other modules. The action which I'm dispatching does not exist in certain cases. So, I need to apply a condition which will check if this action exists and dispatches the action only if the condition is met. How do I do this ?</p>

答:
I do this all the time. @Khasanov72 has it right from outside the store, but you can do it even simpler if you're dispatching an action from another action:</p>

```<code>//From module action
if (this._actions['module/action']) {
  dispatch('module/action', data)
}
</code>```

Body:
I do this all the time. @Khasanov72 has it right from outside the store, but you can do it even simpler if you're dispatching an action from another action:

//From module action
if (this._actions['module/action']) {
  dispatch('module/action', data)
}


问:
Javascript: Proper way to separate metadata from HTML?
What is the proper way of separating my meta-data from the HTML? As my projects grow bigger and bigger tying up meta-data with HTML becomes more and more messy. Any good alternatives?

Meta Data: Everything the JS needs to know about an HTML element which isn't straight-forwardly encoded in the HTML elements and their attributes. E.g. a geolocation, enabled, disabled action.

Example: Say I have a list of places I want to show up on a map whenever I click on one of them. How do I identify that exact same place in JS so I could tell the map 'hey, move to that location'? Easiest way, that becomes messy in the end, is to tie it into the HTML, say the li id will be the geolocation. That's easy, but it is a code smell. How do I do this properly? .data() in jQuery also becomes horrible to maintain soon afterwards.

Conclusion: that's it, I'm going to find/write good MVC for JS.

答:
If you want to attach metadata to DOM elements then use HTML5 data- attributes or use jQuery's .data() method to do it programmatically.

Here's a real world example I just used it on that really helped.  I sent a request to the server to upload a file and I get a JSON response with the File Name, Content Type, Size and a GUID.  On the response I want to add a list item to show the file but I want to preserve the JSON data.  Here's how I did it in the callback:

```<code>function(response) {
  $('<li>').text(response.fileName).data('metadata', response).appendTo('ul');
}
</code>```

What's great about this is now the list item HAS all my metadata attached to it.

So I could do something like this and know everything about it:

```<code>var metadata = $('ul li:eq(1)').data('metadata');

alert(metadata.contentType);
alert(metadata.size);

//etc..
</code>```

The implementations are really limitless.

ALSO, as of jQuery 1.4.3 .data() will automatically pick up the data- attributes in your HTML.  So

 can be immediately accessed in code using $('div').data('foo') //bar

ContentLicense: CC BY-SA 3.0

Body:
If you want to attach metadata to DOM elements then use HTML5 data- attributes or use jQuery's .data() method to do it programmatically.

Here's a real world example I just used it on that really helped.  I sent a request to the server to upload a file and I get a JSON response with the File Name, Content Type, Size and a GUID.  On the response I want to add a list item to show the file but I want to preserve the JSON data.  Here's how I did it in the callback:

function(response) {
  $('<li>').text(response.fileName).data('metadata', response).appendTo('ul');
}

What's great about this is now the list item HAS all my metadata attached to it.

So I could do something like this and know everything about it:

var metadata = $('ul li:eq(1)').data('metadata');

alert(metadata.contentType);
alert(metadata.size);

//etc..

The implementations are really limitless.

ALSO, as of jQuery 1.4.3 .data() will automatically pick up the data- attributes in your HTML.  So <div data-foo="bar"></div> can be immediately accessed in code using $('div').data('foo') //bar


问:
Why my code does not write the results to the file?
I am writing a code that reads the characters from a file, and then if one of these characters is 'A' it should be changed to 'Z', after these changes are made it should write it back to the file (not append, but write), but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me (since I tried correcting it by making some changes, here is the code I have so far:</p>

```<code>int main(){
    char variable1[2000000];
    FILE *filePointer1;
    FILE *filePointer2;
    int counter;
    int exact_char_numb;

    filePointer1 = fopen("File.txt", "r");
    filePointer2 = fopen("File.txt", "w");
    fread(variable1,2000000,sizeof(char), filePointer1);

    for(counter = 0; counter<= 2000000 ; counter ++){
        if(variable1[counter] == 'A'){
            variable1[counter] = 'Z';
        }
        if(variable1[counter] == '+'){
            exact_char_numb = counter; // I am using '+' to mark the end of
        }                              // the file (for now)
    }

    fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);

    printf("%s\n", variable1);
    printf("%d\n", exact_char_numb);

    return 0;
}
</code>```

答:
In this call:

```<code>fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);
</code>```

the variable exact_char_numb is likely equal to zero, so you don't get any output. You should turn on all warnings and the compiler will complain to you about the variables that can be used without initializing them first.

Body:
I am writing a code that reads the characters from a file, and then if one of these characters is 'A' it should be changed to 'Z', after these changes are made it should write it back to the file (not append, but write), but whenever I open the file after running the code or it is empty, corrupted, or the compiler shouts at me (since I tried correcting it by making some changes, here is the code I have so far:

int main(){
    char variable1[2000000];
    FILE *filePointer1;
    FILE *filePointer2;
    int counter;
    int exact_char_numb;

    filePointer1 = fopen("File.txt", "r");
    filePointer2 = fopen("File.txt", "w");
    fread(variable1,2000000,sizeof(char), filePointer1);

    for(counter = 0; counter<= 2000000 ; counter ++){
        if(variable1[counter] == 'A'){
            variable1[counter] = 'Z';
        }
        if(variable1[counter] == '+'){
            exact_char_numb = counter; // I am using '+' to mark the end of
        }                              // the file (for now)
    }

    fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);

    printf("%s\n", variable1);
    printf("%d\n", exact_char_numb);

    return 0;
}

Body:
In this call:

fwrite(variable1,sizeof(char),exact_char_numb,filePointer2);

the variable exact_char_numb is likely equal to zero, so you don't get any output. You should turn on all warnings and the compiler will complain to you about the variables that can be used without initializing them first.


问:
How to combine two composed applicative functors?
I have two composed applicative functors Maybe [Integer] and want to combine them with <$>/<*> but I am stuck with applying the applicative operation. The following does not typecheck:

```<code>(<*>) (<*>) ((<$>) ((+) <$>) $ Just [1,2,3]) $ Just [4,5,6]
</code>```

Expected result:

```<code>Just [5,6,7,6,7,8,7,8,9]
</code>```

The functor part works, i.e. the intermediate value passed to <*> as the first argument is Just [Integer -> Integer]. I am used to S-expressions so I have a hard time with the Haskell syntax. I know of Compose but I am interested in the mere composition wihtout abstraction.

答:
liftA2 might be less confusing for this than (<*>).

```<code>(+) :: Int -> Int -> Int
liftA2 (+) :: [Int] -> [Int] -> [Int]
liftA2 (liftA2 (+)) :: Maybe [Int] -> Maybe [Int] -> Maybe [Int]

liftA2 (liftA2 (+)) (Just [1,2,3]) (Just [4,5,6])
</code>```

Body:
I have two composed applicative functors Maybe [Integer] and want to combine them with <$>/<*> but I am stuck with applying the applicative operation. The following does not typecheck:

(<*>) (<*>) ((<$>) ((+) <$>) $ Just [1,2,3]) $ Just [4,5,6]

Expected result:

Just [5,6,7,6,7,8,7,8,9]

The functor part works, i.e. the intermediate value passed to <*> as the first argument is Just [Integer -> Integer]. I am used to S-expressions so I have a hard time with the Haskell syntax. I know of Compose but I am interested in the mere composition wihtout abstraction.

Body:
liftA2 might be less confusing for this than (<*>).

(+) :: Int -> Int -> Int
liftA2 (+) :: [Int] -> [Int] -> [Int]
liftA2 (liftA2 (+)) :: Maybe [Int] -> Maybe [Int] -> Maybe [Int]

liftA2 (liftA2 (+)) (Just [1,2,3]) (Just [4,5,6])


问:
pandas load csv file ValueError
The purpose of this script is to read a csv file and create a pandas data frame then print the first 5 raws using OOP style.

Here is the code:

```<code>import pandas as pd
import talib

class Data:
    def __init__(self):
        self.df = pd.DataFrame()
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
        self.file(self)

    def file(self, file):
        df = pd.read_csv(file, names=self.names,
                         parse_dates={'Release Date': ['Date', 'Time']})
        print(df.head())

x = Data()
x.file(file=r"D:\Projects\Project Forex\EURUSD.csv")
</code>```

Here is the error:

```<code>Traceback (most recent call last):

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 15, in <module>
    x = Data()

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 9, in __init__
    self.file(self)

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 13, in file
    parse_dates={'Release Date': ['Date', 'Time']})

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\parsers.py", line 676, in parser_f
    return _read(filepath_or_buffer, kwds)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\parsers.py", line 431, in _read
    filepath_or_buffer, encoding, compression

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\common.py", line 200, in get_filepath_or_buffer

    raise ValueError(msg)
ValueError: Invalid file path or buffer object type: <class '__main__.Data'>
</code>```

答:
The culprit is the last line of __init__: self.file(self). When it is called in __init__, self is a Data object, while the file method has to be called with a string containing the path of the csv file.

The fix is trivial: remove that line:

```<code>class Data:
    def __init__(self):
        self.df = pd.DataFrame()
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']

    def file(self, file):
        ...
</code>```

but it is still not consistent: self.df is initialized as an empty dataframe, which is fine, but the file method does not update it and use instead a local variable df (distinct from self.df in Python). You should do:

```<code>def file(self, file):
    self.df = pd.read_csv(file, names=self.names,
                     parse_dates={'Release Date': ['Date', 'Time']})
    print(self.df.head())
</code>```

Title: pandas load csv file ValueError

Body:
The purpose of this script is to read a csv file and create a pandas data frame then print the first 5 raws using OOP style.

Here is the code:

import pandas as pd
import talib

class Data:
    def __init__(self):
        self.df = pd.DataFrame()
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']
        self.file(self)

    def file(self, file):
        df = pd.read_csv(file, names=self.names,
                         parse_dates={'Release Date': ['Date', 'Time']})
        print(df.head())

x = Data()
x.file(file=r"D:\Projects\Project Forex\EURUSD.csv")

Here is the error:

Traceback (most recent call last):

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 15, in <module>
    x = Data()

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 9, in __init__
    self.file(self)

  File "C:/Users/Sayed/PycharmProjects/project/Technical Analysis.py", line 13, in file
    parse_dates={'Release Date': ['Date', 'Time']})

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\parsers.py", line 676, in parser_f
    return _read(filepath_or_buffer, kwds)

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\parsers.py", line 431, in _read
    filepath_or_buffer, encoding, compression

  File "C:\Users\Sayed\miniconda3\lib\site-packages\pandas\io\common.py", line 200, in get_filepath_or_buffer

    raise ValueError(msg)
ValueError: Invalid file path or buffer object type: <class '__main__.Data'>

Body:
The culprit is the last line of __init__: self.file(self). When it is called in __init__, self is a Data object, while the file method has to be called with a string containing the path of the csv file.

The fix is trivial: remove that line:

class Data:
    def __init__(self):
        self.df = pd.DataFrame()
        self.names = ['Date', 'Time', 'Open', 'High', 'Low', 'Close', 'Volume']

    def file(self, file):
        ...

but it is still not consistent: self.df is initialized as an empty dataframe, which is fine, but the file method does not update it and use instead a local variable df (distinct from self.df in Python). You should do:

def file(self, file):
    self.df = pd.read_csv(file, names=self.names,
                     parse_dates={'Release Date': ['Date', 'Time']})
    print(self.df.head())


问:
Not compatible with your operating system or architecture: fsevents@2.1.3
I am using ubuntu 18.04.4 LTS
I was trying to learn admin sdk tutorials from google codelab, and was trying to setup the defined project in this

While setting up, the following command gives an error.
npm -g install firebase-tools
and error: "No firebase command found" on command firebase --version

I have tried setting npm settings globally as described here, but nothing works.

Can anyone help me with this, as I am new to firebase admin SDK.

答:
Shouldn't you first install firebase itself?

npm i -g firebase
```


问:
t sql records that contain part of another record
Using SQL Server 2014.  Is there a way to select records where the string value partially exists in another field?

e.g.:

```<code>RowID   Field1     Field2
1       ABC        ABC DEF
2       XYZ        WERQ
3       MNB        MNB RTW
</code>```

From the above, I would want Rows 1 and 3 as they have ABC and MNB that matches.

```<code>SELECT RowID FROM MY TABLE
WHERE CONTAINS(Field1, Field2);
</code>```

I have tried the above, however, this does not work as you cannot specify a 2nd field name in the CONTAINS function.

What am I missing?

答:
You can use like:

```<code>select t.*
from t
where field2 like concat('%', field1, '%')
</code>```

If you want only complete "words" to match -- well, you should fix your data model.  You shouldn't be storing lists of things in a string.  But, if you must, you can use delimiters:

```<code>select t.*
from t
where concat(' ', field2, ' ') like concat('% ', field1, ' %')
</code>```

Body:
Using SQL Server 2014.  Is there a way to select records where the string value partially exists in another field?

e.g.:

RowID   Field1     Field2
1       ABC        ABC DEF
2       XYZ        WERQ
3       MNB        MNB RTW

From the above, I would want Rows 1 and 3 as they have ABC and MNB that matches.

SELECT RowID FROM MY TABLE
WHERE CONTAINS(Field1, Field2);

I have tried the above, however, this does not work as you cannot specify a 2nd field name in the CONTAINS function.

What am I missing?

Body:
You can use like:

select t.*
from t
where field2 like concat('%', field1, '%')

If you want only complete "words" to match -- well, you should fix your data model.  You shouldn't be storing lists of things in a string.  But, if you must, you can use delimiters:

select t.*
from t
where concat(' ', field2, ' ') like concat('% ', field1, ' %')


问:
Printing selenium search results
I've written the following code to search the UNSPSC search page.  This script works, but I'm having difficulty extracting the actual results.  Adding to the code below, it should then extract "Toy balloons or balls" </p>

```<code>from selenium import webdriver

# from selenium.common import exceptions

from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.keys import Keys

opts = Options()
#opts.add_argument("--headless")

driver = webdriver.Firefox(
    firefox_options=opts,
    firefox_binary='path/Firefox/firefox.exe',
    executable_path='./geckodriver.exe',
    )
driver.get("https://www.unspsc.org/search-code/")
search = driver.find_element_by_id("dnn_ctr1535_UNSPSCSearch_txtsearchCode")
search.send_keys("60141001")
search.send_keys(Keys.ENTER)
</code>```

答:
To Extract the text induce WebDriverWait  and wait for visibility_of_element_located() and use the following xpath

```<code>driver.get("https://www.unspsc.org/search-code/")
search = driver.find_element_by_id("dnn_ctr1535_UNSPSCSearch_txtsearchCode")
search.send_keys("60141001")
search.send_keys(Keys.ENTER)
print(WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH,"//table[@id='dnn_ctr1535_UNSPSCSearch_gvDetailsSearchView']/tbody/tr[2]/td[2]"))).text)
</code>```

You need to import following libraries.

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
</code>```

Title: Printing selenium search results

Body:
I've written the following code to search the UNSPSC search page.  This script works, but I'm having difficulty extracting the actual results.  Adding to the code below, it should then extract "Toy balloons or balls"

from selenium import webdriver

# from selenium.common import exceptions

from selenium.webdriver.firefox.options import Options
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
from selenium.webdriver.common.keys import Keys

opts = Options()
#opts.add_argument("--headless")

driver = webdriver.Firefox(
    firefox_options=opts,
    firefox_binary='path/Firefox/firefox.exe',
    executable_path='./geckodriver.exe',
    )
driver.get("https://www.unspsc.org/search-code/")
search = driver.find_element_by_id("dnn_ctr1535_UNSPSCSearch_txtsearchCode")
search.send_keys("60141001")
search.send_keys(Keys.ENTER)

Body:
To Extract the text induce WebDriverWait  and wait for visibility_of_element_located() and use the following xpath

driver.get("https://www.unspsc.org/search-code/")
search = driver.find_element_by_id("dnn_ctr1535_UNSPSCSearch_txtsearchCode")
search.send_keys("60141001")
search.send_keys(Keys.ENTER)
print(WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH,"//table[@id='dnn_ctr1535_UNSPSCSearch_gvDetailsSearchView']/tbody/tr[2]/td[2]"))).text)

You need to import following libraries.

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By


问:
Pandas DataFrame concatenate along new axis
I have a directory with 1000+ csv files, which I want to read in and store in a dataframe, to then save that to a file. I would like the dataframe dimensions to be [file, line in file, content of line]. This is what I have come up with so far:

import pandas as pd
import glob

csv_files = glob.glob("data/*sample.csv")
df = (pd.read_csv(f) for f in csv_files)
dataset = pd.concat(df, ignore_index=True)
```

This gives me a dataframe with the shape [line, content of line] but I can no longer see which file the line is from. Can somebody help me here?

答:
A little bit more long-winded that jezrael's solution, but this is what I've used for ages. It's probably time to make it more concise though.  </p>

```<code>os.chdir('C:/')
file_list = []
for file in os.listdir():
    df = pd.read_csv(file)
    df['Filename'] = file
    file_list.append(df)
    df = pd.concat(file_list, ignore_index=True)
</code>```

Body:
I have a directory with 1000+ csv files, which I want to read in and store in a dataframe, to then save that to a file. I would like the dataframe dimensions to be [file, line in file, content of line]. This is what I have come up with so far:

import pandas as pd
import glob

csv_files = glob.glob("data/*sample.csv")
df = (pd.read_csv(f) for f in csv_files)
dataset = pd.concat(df, ignore_index=True)

This gives me a dataframe with the shape [line, content of line] but I can no longer see which file the line is from. Can somebody help me here?

Body:
A little bit more long-winded that jezrael's solution, but this is what I've used for ages. It's probably time to make it more concise though.

os.chdir('C:/')
file_list = []
for file in os.listdir():
    df = pd.read_csv(file)
    df['Filename'] = file
    file_list.append(df)
    df = pd.concat(file_list, ignore_index=True)


问:
Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean
I have a new springboot application I am attempting to get started.

The error I receive is

```<code>org.springframework.context.ApplicationContextException: Unable to start reactive web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean.
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:76) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
</code>```

src/main/java/bubbleshadow/RootController.java

```<code>package bubbleshadow;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class RootController {
  public RootController() {

  }

  @GetMapping("/")
  public Mono<HttpStatus> returnOk() {
    return Mono.just(HttpStatus.OK);
  }
}
</code>```

src/test/java/test/bubbleshadow/RootControllerTest.java

```<code>package test.bubbleshadow;
import bubbleshadow.RootController;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes=RootController.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class RootControllerTest {
  @Autowired
  WebTestClient webTestClient;

  @Test
  public void baseRouteShouldReturnStatusOK() {
    webTestClient.head().uri("/").exchange().expectStatus().isOk();
  }
}
</code>```

答: You actually just need to change webEnvironment = WebEnvironment.RANDOM_PORT to webEnvironment = WebEnvironment.MOCK in your @SpringBootTest annotation.

Body:
I have a new springboot application I am attempting to get started.

The error I receive is

org.springframework.context.ApplicationContextException: Unable to start reactive web server; nested exception is org.springframework.context.ApplicationContextException: Unable to start ReactiveWebApplicationContext due to missing ReactiveWebServerFactory bean.
    at org.springframework.boot.web.reactive.context.ReactiveWebServerApplicationContext.onRefresh(ReactiveWebServerApplicationContext.java:76) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]

src/main/java/bubbleshadow/RootController.java

package bubbleshadow;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import reactor.core.publisher.Mono;

@RestController
public class RootController {
  public RootController() {

  }

  @GetMapping("/")
  public Mono<HttpStatus> returnOk() {
    return Mono.just(HttpStatus.OK);
  }
}

src/test/java/test/bubbleshadow/RootControllerTest.java

package test.bubbleshadow;
import bubbleshadow.RootController;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
// import org.springframework.boot.test.autoconfigure.web.reactive.WebFluxTest;
import org.springframework.boot.test.autoconfigure.web.reactive.AutoConfigureWebTestClient;
import org.springframework.test.web.reactive.server.WebTestClient;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.boot.test.context.SpringBootTest.WebEnvironment;

@ExtendWith(SpringExtension.class)
@SpringBootTest(classes=RootController.class, webEnvironment = WebEnvironment.RANDOM_PORT)
@AutoConfigureWebTestClient
public class RootControllerTest {
  @Autowired
  WebTestClient webTestClient;

  @Test
  public void baseRouteShouldReturnStatusOK() {
    webTestClient.head().uri("/").exchange().expectStatus().isOk();
  }
}


问:
Save functionality in Excel Addin using OfficeJs and ReactJS
Background: I am developing an excel Add-in using OfficeJS library. The addin is using the ReactJS components and Office Fabric UI. The Add-in is successfully created and using OfficeJS library we can bring the user selection to the Excel sheet.

Problem: The problem is that I want to get the event in OfficeJS to Save the sheet using the Excel Native capability i.e., once user clicks on Save then the Save Dialogue box will appear(as per Native excel behavior)and on that I want to invoke my ReactJS business rules(some functionalities). In order to do that I want to use Save event for the same in OfficeJS which should be triggered automatically.

Code Sample:

```<code>Office.initialize = () => {
    Excel.run(function (context) {
        var sheet = context.workbook.worksheets.getItem("Sheet1");
        context.workbook.load(["save"]);
        context.sync().then(() => {
        context.workbook.save(Excel.SaveBehavior.prompt);
        //OR
        context.workbook.save(Excel.SaveBehavior.save);
        });
    }).catch(function(error) {
        console.log(error.debugInfo);
    });
}
</code>```

Research: The above two functions which I have tried are from the Microsoft Documentation where it is mentioned as:

Workbook.save saves the workbook to persistent storage. The save method takes a single, optional saveBehavior parameter that can be one
  of the following values:

Excel.SaveBehavior.save (default): The file is saved without prompting the user to specify file name and save location. If the file
  has not been saved previously, it's saved to the default location. If
  the file has been saved previously, it's saved to the same location.
  Excel.SaveBehavior.prompt: If file has not been saved previously, the
  user will be prompted to specify file name and save location. If the
  file has been saved previously, it will be saved to the same location
  and the user will not be prompted.

System Configurations: I am using Windows 10, Excel 2016 Desktop and Office 365 Online version. I am using IE-10 and Google Chrome for Online version of Excel. Additionally I have checked the same using Windows-7 and Excel-2016 and same browsers.

Do let me know if the above functionality can be achieved?

答:
Unfortunately, Office JS Excel API currently doesn't support onSaved event. one of the reasons was that Excel has an autosave feature, which triggers save action frequently. So we worry to provide onSaved event may fire too many event notifications to customers.

But I would suggest that you could submit the request and upvote this request at uservoice

Body:
Background: I am developing an excel Add-in using OfficeJS library. The addin is using the ReactJS components and Office Fabric UI. The Add-in is successfully created and using OfficeJS library we can bring the user selection to the Excel sheet.

Problem: The problem is that I want to get the event in OfficeJS to Save the sheet using the Excel Native capability i.e., once user clicks on Save then the Save Dialogue box will appear(as per Native excel behavior)and on that I want to invoke my ReactJS business rules(some functionalities). In order to do that I want to use Save event for the same in OfficeJS which should be triggered automatically.

Code Sample:

Office.initialize = () => {
    Excel.run(function (context) {
        var sheet = context.workbook.worksheets.getItem("Sheet1");
        context.workbook.load(["save"]);
        context.sync().then(() => {
        context.workbook.save(Excel.SaveBehavior.prompt);
        //OR
        context.workbook.save(Excel.SaveBehavior.save);
        });
    }).catch(function(error) {
        console.log(error.debugInfo);
    });
}

Research: The above two functions which I have tried are from the Microsoft Documentation where it is mentioned as:

Workbook.save saves the workbook to persistent storage. The save method takes a single, optional saveBehavior parameter that can be one
  of the following values:

Excel.SaveBehavior.save (default): The file is saved without prompting the user to specify file name and save location. If the file
  has not been saved previously, it's saved to the default location. If
  the file has been saved previously, it's saved to the same location.
  Excel.SaveBehavior.prompt: If file has not been saved previously, the
  user will be prompted to specify file name and save location. If the
  file has been saved previously, it will be saved to the same location
  and the user will not be prompted.

System Configurations: I am using Windows 10, Excel 2016 Desktop and Office 365 Online version. I am using IE-10 and Google Chrome for Online version of Excel. Additionally I have checked the same using Windows-7 and Excel-2016 and same browsers.

Do let me know if the above functionality can be achieved?


问:
How to remove the first character of a variable
HI All,

In my js file i am getting an array of records (negetive values ) like this

```<code>deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });
</code>```

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

答:
The correct way would be to use Math.abs:

```<code>$.map(eformDetailIds, function(e) {
    return e < 0 ? Math.abs(e) : null;
});
</code>```

You could also multiply with -1.

You are dealing with numbers. Only the string representation contains a - to indicate the negative value, so you cannot really remove the first character here.

Body:
HI All,

In my js file i am getting an array of records (negetive values ) like this

deletedDetailIds = $.map(eformDetailIds, function(e) { return e < 0 ? e : null; });

For example the deletedDetailIds = -1234,-1235,-1256 like this.

Now i have to create an array and add these values with out negetive symbols. like

newArray = 1234,1235,1256.

Please help me in this

Body:
The correct way would be to use Math.abs:

$.map(eformDetailIds, function(e) {
    return e < 0 ? Math.abs(e) : null;
});

You could also multiply with -1.

You are dealing with numbers. Only the string representation contains a - to indicate the negative value, so you cannot really remove the first character here.


问:
calculate the mean of every nth list in a list of lists using a loop
I am trying to calculate the mean of every nth list in a list of lists using a loop.
I have been able to do so without a loop, but this will prove laborious to do when the list of lists gets longer.

Im struggling to explain this so heres the code

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

list = []
t_r = np.arange(0,8)
i = 0
a =[[0.98,1.93,2.99,4.01,4.92,6.00,7.08,7.67, 8.00],[0,0,0,1,2,3,3,2,3],[0.93,1.99,2.99,3.91,4.82,6.03,7.01,8.00],[0,1,2,3,4,5,5,6],[0.88,2.09,3.01,4.11,5.65,7.12,8.00],[4,5,6,7,8,7,6]]
#########################
for t in t_r:
    b1 = np.array(a[0]) <= t
    b2 = np.array(a[2]) <= t
    b3 = np.array(a[4]) <= t

    ind1 = [(np.count_nonzero(b1))]
    ind2 = [(np.count_nonzero(b2))]
    ind3 = [(np.count_nonzero(b3))]

    x1 = np.array(a[1])
    x_mean1 = x1[ind1]
    x2 = np.array(a[3])
    x_mean2 = x2[ind2]
    x3 = np.array(a[5])
    x_mean3 = x3[ind2]

    x_mean_list = [x_mean1, x_mean2, x_mean3]
    x_average = np.mean(x_mean_list)
    list.append(x_average)
#########################

no_of_sim = 3
counter = 0
while counter <= ((no_of_sim*2)-1):
    plt.plot(a[counter],a[counter+1], lw = 0.5)
    plt.plot(list, color = "black")
    plt.plot(x_average)
    plt.xlabel('Time (s)')
    plt.ylabel('copy no.')
    counter += 2
plt.show()
</code>```

The bit inbetween the hashtags is the bit I'm trying to write a loop for so I don't have to manually change it when the list if lists gets much longer

Body:
I am trying to calculate the mean of every nth list in a list of lists using a loop.
I have been able to do so without a loop, but this will prove laborious to do when the list of lists gets longer.

Im struggling to explain this so heres the code

import numpy as np
import matplotlib.pyplot as plt

list = []
t_r = np.arange(0,8)
i = 0
a =[[0.98,1.93,2.99,4.01,4.92,6.00,7.08,7.67, 8.00],[0,0,0,1,2,3,3,2,3],[0.93,1.99,2.99,3.91,4.82,6.03,7.01,8.00],[0,1,2,3,4,5,5,6],[0.88,2.09,3.01,4.11,5.65,7.12,8.00],[4,5,6,7,8,7,6]]
#########################
for t in t_r:
    b1 = np.array(a[0]) <= t
    b2 = np.array(a[2]) <= t
    b3 = np.array(a[4]) <= t

    ind1 = [(np.count_nonzero(b1))]
    ind2 = [(np.count_nonzero(b2))]
    ind3 = [(np.count_nonzero(b3))]

    x1 = np.array(a[1])
    x_mean1 = x1[ind1]
    x2 = np.array(a[3])
    x_mean2 = x2[ind2]
    x3 = np.array(a[5])
    x_mean3 = x3[ind2]

    x_mean_list = [x_mean1, x_mean2, x_mean3]
    x_average = np.mean(x_mean_list)
    list.append(x_average)
#########################

no_of_sim = 3
counter = 0
while counter <= ((no_of_sim*2)-1):
    plt.plot(a[counter],a[counter+1], lw = 0.5)
    plt.plot(list, color = "black")
    plt.plot(x_average)
    plt.xlabel('Time (s)')
    plt.ylabel('copy no.')
    counter += 2
plt.show()

The bit inbetween the hashtags is the bit I'm trying to write a loop for so I don't have to manually change it when the list if lists gets much longer

Body:
check out this code:

a =[[0.98,1.93,2.99,4.01,4.92,6.00,7.08,7.67, 8.00],[0,0,0,1,2,3,3,2,3],[0.93,1.99,2.99,3.91,4.82,6.03,7.01,8.00],[0,1,2,3,4,5,5,6],[0.88,2.09,3.01,4.11,5.65,7.12,8.00],[4,5,6,7,8,7,6]]

i = 0
for li in a:
    print("Mean of list at index", i, "is:", sum(li)/len(li))
    i += 1


问:
Change color of plot in R
I'm trying to find out why I'm not able to change the color of my bars. Hope you can help, I'm kinda new to this.

```<code>ggplot2(data, aes(x = data$Crop, y = data$"2018"))+
    geom_bar(color="black", fill="red") +
    theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
    main="Production value per crop in 2018" +
    ylab("Production value in 2018")+
    xlab("Crop")+
</code>```

Hope to hear from you.

答:
A little tweak of your code:

```<code>library(tidyverse)
data <- data.frame(Crop = c("East","West","North","South"),
                   Y2018 = c(1000,2000,3000,400),
                      stringsAsFactors = TRUE)

ggplot(data, aes(x = data$Crop, y = data$Y2018)) +
  geom_col(color="black", fill="red") +
  theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
  labs(
    title = "Production value per crop in 2018",
    ylab = "Production value in 2018",
    xlab = "Crop"
  )
</code>```

Hope it helps

Title: Change color of plot in R

Body:
I'm trying to find out why I'm not able to change the color of my bars. Hope you can help, I'm kinda new to this.

ggplot2(data, aes(x = data$Crop, y = data$"2018"))+
    geom_bar(color="black", fill="red") +
    theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
    main="Production value per crop in 2018" +
    ylab("Production value in 2018")+
    xlab("Crop")+

Hope to hear from you.

Body:
A little tweak of your code:

library(tidyverse)
data <- data.frame(Crop = c("East","West","North","South"),
                   Y2018 = c(1000,2000,3000,400),
                      stringsAsFactors = TRUE)

ggplot(data, aes(x = data$Crop, y = data$Y2018)) +
  geom_col(color="black", fill="red") +
  theme(axis.text.x = element_text(angle = 60, vjust = 1, hjust = 1)) +
  labs(
    title = "Production value per crop in 2018",
    ylab = "Production value in 2018",
    xlab = "Crop"
  )

Hope it helps


问:
How can I convert an XML without attributes to C# properties?
I'm having trouble converting my XML to a C# object.

My XML looks like this:

```<code><metadata>
<item name="Date" type="xs:date"/>
<item name="Hour" type="xs:time"/>
<item name="Group" type="xs:string" length="12"/>
<item name="Status" type="xs:string" length="18"/>
</metadata>
<data>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>A</value>
<value>Active</value>
</row>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>B</value>
<value>Inactive</value>
</row>
</data>
</metadata>
</code>```

I want to map the XML to a c# object that looks like this

```<code>public class GroupDto

    {
        public string Date { get; set; }
        public string Hour { get; set; }
        public string Group { get; set; }
        public string Status { get; set; }
    }
</code>```

(the date and hour can be a string, no problem)
 I'm using JsonConvert.SerializeXmlNode(doc), but it's giving me this result:

```<code>   "data": {
      "row": [
         {
            "value": [
               "2020-05-08",
               "14:00:01",
               "A",
               "Active"
            ]
         },
....
</code>```

I like to map the "values" to the corresponding properties of the C# object.
Is there a propper way to achieve this with an XML in this weird format?

答:
You will have to make some rules for the deserialization, if there is no way to differenciate values from values.

Assuming that you simply don't trust the properties to be in the right order, you can use the following group of rules :

Date and Hour are both parsable into DateTime

Hour contains ':' and Date do not.

either Group is only letter or Status match a list of known Status

```<code>foreach(var row in data.Row){
    var temp = new GroupDto();
    foreach(var val in row.Value){

        if( DateTime.TryParse(val, out DateTime date) )
        {
            if(val.Contains(':')) //it should be a time
            {
                temp.Hour = date.ToShortTimeString(); //or keep the datetime format
            }
            else
            {
                temp.Hour = date.ToShortDateString();
            }
        }

        //either based status on a list of know status
        else if(knowStatus.Contains(val))
        {
            temp.Status = val;
        }
        //or base Group detection on string lenght and default the remaining possibility to status
        else if(val.lenght>1)
        {
            temp.Status = val;
        }

        else {
            temp.Group  = val;
        }
    }
    // return temp/ yeild return temp/ Add it to a list of result etc
}
</code>```

Note that this is more or less pseudo code based on an invalid Xml.
That look like once you add a common root and remove the last closing meta at the end...:

```<code>[XmlRoot(ElementName="row")]
public class Row {
    [XmlElement(ElementName="value")]
    public List<string> Value { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="row")]
    public List<Row> Row { get; set; }
}
</code>```

If you trust the properties order you can simply

```<code>Data.Row.Select(x => new GroupDto{
                Date = x.Value[0],
                Hour = x.Value[1],
                Group = x.Value[2],
                Status = x.Value[3],
            } )
</code>```

Body:
I'm having trouble converting my XML to a C# object.

My XML looks like this:

<metadata>
<item name="Date" type="xs:date"/>
<item name="Hour" type="xs:time"/>
<item name="Group" type="xs:string" length="12"/>
<item name="Status" type="xs:string" length="18"/>
</metadata>
<data>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>A</value>
<value>Active</value>
</row>
<row>
<value>2020-05-08</value>
<value>14:00:01</value>
<value>B</value>
<value>Inactive</value>
</row>
</data>
</metadata>

I want to map the XML to a c# object that looks like this

public class GroupDto

    {
        public string Date { get; set; }
        public string Hour { get; set; }
        public string Group { get; set; }
        public string Status { get; set; }
    }

(the date and hour can be a string, no problem)
 I'm using JsonConvert.SerializeXmlNode(doc), but it's giving me this result:

   "data": {
      "row": [
         {
            "value": [
               "2020-05-08",
               "14:00:01",
               "A",
               "Active"
            ]
         },
....

I like to map the "values" to the corresponding properties of the C# object.
Is there a propper way to achieve this with an XML in this weird format?

Body:
You will have to make some rules for the deserialization, if there is no way to differenciate values from values.

Assuming that you simply don't trust the properties to be in the right order, you can use the following group of rules :

Date and Hour are both parsable into DateTime

Hour contains ':' and Date do not.

either Group is only letter or Status match a list of known Status

foreach(var row in data.Row){
    var temp = new GroupDto();
    foreach(var val in row.Value){

        if( DateTime.TryParse(val, out DateTime date) )
        {
            if(val.Contains(':')) //it should be a time
            {
                temp.Hour = date.ToShortTimeString(); //or keep the datetime format
            }
            else
            {
                temp.Hour = date.ToShortDateString();
            }
        }

        //either based status on a list of know status
        else if(knowStatus.Contains(val))
        {
            temp.Status = val;
        }
        //or base Group detection on string lenght and default the remaining possibility to status
        else if(val.lenght>1)
        {
            temp.Status = val;
        }

        else {
            temp.Group  = val;
        }
    }
    // return temp/ yeild return temp/ Add it to a list of result etc
}

Note that this is more or less pseudo code based on an invalid Xml.
That look like once you add a common root and remove the last closing meta at the end...:

[XmlRoot(ElementName="row")]
public class Row {
    [XmlElement(ElementName="value")]
    public List<string> Value { get; set; }
}

[XmlRoot(ElementName="data")]
public class Data {
    [XmlElement(ElementName="row")]
    public List<Row> Row { get; set; }
}

If you trust the properties order you can simply

Data.Row.Select(x => new GroupDto{
                Date = x.Value[0],
                Hour = x.Value[1],
                Group = x.Value[2],
                Status = x.Value[3],
            } )


问:
Multiple logging files with specific log type in Serilog
I have implemented Serilog in .net core,I wanted to achieve multiple logging files for each log type.
For example Error.log file will only contain error,Trace.log file will only contain Trace log, Warning.log will only contain warning messages and not error messages.
I have used Serilog.Sinks.RollingFile and restrictedToMinimumLevel, i am able to generate multiple files but due to restrictedToMinimumLevel, it logs above defined level as well.
Is there any option/way to set logOnlyLevel kind of thing. I can use filter but is there any better option.

```<code>"Serilog": {
"Using": ["Serilog.Sinks.RollingFile"],
"MinimumLevel": {
    "Default": "Verbose",
    "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
    }
},
"WriteTo": [{
        "Name": "RollingFile",
        "Args": {
            "pathFormat": "Logs/Information.txt",
            "rollingInterval": "Day",
            "fileSizeLimitBytes": "2000000",
            "retainedFileCountLimit": "10",
            "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}|{EventId}|{Message}|{Scope} {NewLine}",
            "restrictedToMinimumLevel": "Information"
        }
    }, {
        "Name": "RollingFile",
        "Args": {
            "pathFormat": "Logs/Warning.txt",
            "rollingInterval": "Day",
            "fileSizeLimitBytes": "2000000",
            "retainedFileCountLimit": "10",
            "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}|{EventId}|{Message}|{Scope} {NewLine}",
            "restrictedToMinimumLevel": "Warning"
        }
    }
}
</code>```

答:
Thread from Serilog multiple files appsettings.json.
My findings after a while of errors, retry and nearly giving up based on lack of documentation about Serilog. They have a tread on GitHub: https://github.com/serilog/serilog-filters-expressions/issues/27. Nearly every thread goes to the same conclusion that you have to create a SUBLOGGER. This is my implementation. For this implementation you need the following plugins:

Serilog Filter

Serilog Sink

Serilog Async

```<code>"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
  "Default": "Information",
  "Override": {
    "Microsoft": "Warning",
    "System": "Warning"
  }
},
"WriteTo:Information": { //this name here can be changed
  "Name": "Logger", //this name here is essential
  "Args": {
    "configureLogger": {
      "Filter": [
        {
          "Name": "ByIncludingOnly",
          "Args": {
            "expression": "@Level = 'Information'"
          }
        }
      ],
      "WriteTo": [
        {
          "Name": "Async", //i use async plugin from serilog
          "Args": {
            "configure": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/Log_.txt",
                  "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      ]
    }
  }
},
</code>```

Body:
I have implemented Serilog in .net core,I wanted to achieve multiple logging files for each log type.
For example Error.log file will only contain error,Trace.log file will only contain Trace log, Warning.log will only contain warning messages and not error messages.
I have used Serilog.Sinks.RollingFile and restrictedToMinimumLevel, i am able to generate multiple files but due to restrictedToMinimumLevel, it logs above defined level as well.
Is there any option/way to set logOnlyLevel kind of thing. I can use filter but is there any better option.

"Serilog": {
"Using": ["Serilog.Sinks.RollingFile"],
"MinimumLevel": {
    "Default": "Verbose",
    "Override": {
        "Microsoft": "Warning",
        "System": "Warning"
    }
},
"WriteTo": [{
        "Name": "RollingFile",
        "Args": {
            "pathFormat": "Logs/Information.txt",
            "rollingInterval": "Day",
            "fileSizeLimitBytes": "2000000",
            "retainedFileCountLimit": "10",
            "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}|{EventId}|{Message}|{Scope} {NewLine}",
            "restrictedToMinimumLevel": "Information"
        }
    }, {
        "Name": "RollingFile",
        "Args": {
            "pathFormat": "Logs/Warning.txt",
            "rollingInterval": "Day",
            "fileSizeLimitBytes": "2000000",
            "retainedFileCountLimit": "10",
            "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz}|{EventId}|{Message}|{Scope} {NewLine}",
            "restrictedToMinimumLevel": "Warning"
        }
    }
}

Body:
Thread from Serilog multiple files appsettings.json.
My findings after a while of errors, retry and nearly giving up based on lack of documentation about Serilog. They have a tread on GitHub: https://github.com/serilog/serilog-filters-expressions/issues/27. Nearly every thread goes to the same conclusion that you have to create a SUBLOGGER. This is my implementation. For this implementation you need the following plugins:

Serilog Filter

Serilog Sink

Serilog Async

"Serilog": {
"Using": [ "Serilog.Sinks.File" ],
"MinimumLevel": {
  "Default": "Information",
  "Override": {
    "Microsoft": "Warning",
    "System": "Warning"
  }
},
"WriteTo:Information": { //this name here can be changed
  "Name": "Logger", //this name here is essential
  "Args": {
    "configureLogger": {
      "Filter": [
        {
          "Name": "ByIncludingOnly",
          "Args": {
            "expression": "@Level = 'Information'"
          }
        }
      ],
      "WriteTo": [
        {
          "Name": "Async", //i use async plugin from serilog
          "Args": {
            "configure": [
              {
                "Name": "File",
                "Args": {
                  "path": "Logs/Log_.txt",
                  "formatter": "Serilog.Formatting.Json.JsonFormatter, Serilog",
                  "rollingInterval": "Day",
                  "retainedFileCountLimit": 7
                }
              }
            ]
          }
        }
      ]
    }
  }
},


问:
Convert CSVwriter to inputstream
I have the following code where I want to write a list of objects onto a csv where I have defined the attributes and items. I want to convert the writer into a input stream so I read the values and do some performed computations. I also want to store this s3 file in a datastore like Amazon S3.

How do I convert the writer into a inputstream. I see no defined api. Can I read the file somehow like CSVReader reader = new CSVReader(csvWriter)?

```<code> public CSVWriter convertModelToObject(List attributes, final Class classType) throws IOException {
    CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), com.opencsv.CSVParser.DEFAULT_SEPARATOR,
            com.opencsv.CSVParser.DEFAULT_QUOTE_CHARACTER);
    BeanToCsv bean = new BeanToCsv();
    HeaderColumnNameMappingStrategy<T> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
    mappingStrategy.setType(classType);
    bean.write(mappingStrategy, writer, attributes);
    return writer;
</code>```

答:
Yes, you can.

The solution is to use InputStreamReader to read the file and pass that stream to Buffered reader and read line by line or as you want.

You can refer to this for more methods: https://www.geeksforgeeks.org/different-ways-reading-text-file-java/

Title: Convert CSVwriter to inputstream

Body:
I have the following code where I want to write a list of objects onto a csv where I have defined the attributes and items. I want to convert the writer into a input stream so I read the values and do some performed computations. I also want to store this s3 file in a datastore like Amazon S3.

How do I convert the writer into a inputstream. I see no defined api. Can I read the file somehow like CSVReader reader = new CSVReader(csvWriter)?

 public CSVWriter convertModelToObject(List attributes, final Class classType) throws IOException {
    CSVWriter writer = new CSVWriter(new FileWriter("yourfile.csv"), com.opencsv.CSVParser.DEFAULT_SEPARATOR,
            com.opencsv.CSVParser.DEFAULT_QUOTE_CHARACTER);
    BeanToCsv bean = new BeanToCsv();
    HeaderColumnNameMappingStrategy<T> mappingStrategy = new HeaderColumnNameMappingStrategy<>();
    mappingStrategy.setType(classType);
    bean.write(mappingStrategy, writer, attributes);
    return writer;


问:
Why can't java find my method?
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?

What is the reason code such as the example below does not compile?

Thank you,

```<code>class a {
  public static void myMethod(Object myObj) {
    myObj.testing();
  }
}

class b {
  public void testing() {
    System.out.println ("TESTING!!!");
  }
}

class c {
  public static void main (String[] args) {
    b myB = new b();
    a.myMethod(myB);
  }
}
</code>```

Edit: The reason I have left the parameter in myMethod as type Object, is because I would like to be able to pass in a variety of object types, each having a testing() method.

答:
Why can’t java find my method?

Because of the way Java was designed.

Java is "statically typed" that means objects types are checked during compilation.

In Java you can invoke a method only if that method belongs to that type.

Since this verification is made during compilation and the Object type does not have the "testing()" method, the compilation fails ( even though if at runtime the objects do have that method". This is primarily for safety.

The workaround as described by others will require you to create a new type, where you can tell the compiler

"Hey, the instances of this type will respond the the testing method"

If you want to pass a variety of objects and keep it very generic, one way is having those objects to implement and interface.

```<code>public interface Testable {
    public void testing();
}

class A implements Testable { // here this class commits to respond to "testing" message
    public void testing() {
    }
}

class B implements Testable { // B "is" testable
    public void testing() {
        System.out.println("Testing from b");
    }
}

class C implements Testable { // C is... etc.
    public void testing() {
        //....
    }
}
</code>```

Later somewhere else

```<code>public void doTest( Testable object ) {
    object.testing();
}

doTest( new A() );
doTest( new B() );
doTest( new C() );
</code>```

The "OTHER" way to do this, in java is invoking the methods reflectively, but I'm not sure if that's what you need, for the code is much more abstract when you do it that way, but that's how automated testing frameworks (and a lot of other frameworks such as Hibernate) do actually work.

I hope this help you to clarify the reason.

OwnerDisplayName: barfoon

ContentLicense: CC BY-SA 2.5

Title: Why can't java find my method?

Body:
I am trying to wrap my mind around something in java. When I pass an object to another class' method, can I not just call any methods inherent to that object class?

What is the reason code such as the example below does not compile?

Thank you,

class a {
  public static void myMethod(Object myObj) {
    myObj.testing();
  }
}

class b {
  public void testing() {
    System.out.println ("TESTING!!!");
  }
}

class c {
  public static void main (String[] args) {
    b myB = new b();
    a.myMethod(myB);
  }
}

Edit: The reason I have left the parameter in myMethod as type Object, is because I would like to be able to pass in a variety of object types, each having a testing() method.

LastEditorDisplayName: barfoon

Body:
Why can’t java find my method?

Because of the way Java was designed.

Java is "statically typed" that means objects types are checked during compilation.

In Java you can invoke a method only if that method belongs to that type.

Since this verification is made during compilation and the Object type does not have the "testing()" method, the compilation fails ( even though if at runtime the objects do have that method". This is primarily for safety.

The workaround as described by others will require you to create a new type, where you can tell the compiler

"Hey, the instances of this type will respond the the testing method"

If you want to pass a variety of objects and keep it very generic, one way is having those objects to implement and interface.

public interface Testable {
    public void testing();
}

class A implements Testable { // here this class commits to respond to "testing" message
    public void testing() {
    }
}

class B implements Testable { // B "is" testable
    public void testing() {
        System.out.println("Testing from b");
    }
}

class C implements Testable { // C is... etc.
    public void testing() {
        //....
    }
}

Later somewhere else

public void doTest( Testable object ) {
    object.testing();
}

doTest( new A() );
doTest( new B() );
doTest( new C() );

The "OTHER" way to do this, in java is invoking the methods reflectively, but I'm not sure if that's what you need, for the code is much more abstract when you do it that way, but that's how automated testing frameworks (and a lot of other frameworks such as Hibernate) do actually work.

I hope this help you to clarify the reason.

OwnerDisplayName: Oscar Reyes


问:
JQuery How to add a Accordion inside a Dialog
I have a dialog hidden by default that when the user clicks in a button in the page, the dialog appears and inside the dialog there is a accordion. The accordion appears BUT each section of the accordion does not appear complete. It does not show the text inside each accordion section completely. It just shows the first line.

```<code>$('#helpx').hide();
$('#accord').accordion({ header: 'h3' });

$('#helpbutton').click(function() {
    if ( $('#helpx').is(':visible') == false ) {
        $('#helpx').show().dialog({height: 600, width:550, dialogClass: 'shadowme', position: [390,130]});
            }
    else { $('#helpx').dialog('close'); }
});
</code>```

Remember that the accordion is inside the tags of the dialog in the html. For instance

```<code><div id="helpx" title="Sistema de Ayuda">
    <div id="accord">
</code>```

答:
this seems seems to work fine for me but we really need to see your code

```<code>$( "#accordion" ).accordion();
$('#dialog').dialog({autoOpen:false});
$('#mybutton').click(function(){
    $('#dialog').dialog('open');
})
</code>```

here is a working demo

Body:
I have a dialog hidden by default that when the user clicks in a button in the page, the dialog appears and inside the dialog there is a accordion. The accordion appears BUT each section of the accordion does not appear complete. It does not show the text inside each accordion section completely. It just shows the first line.

$('#helpx').hide();
$('#accord').accordion({ header: 'h3' });

$('#helpbutton').click(function() {
    if ( $('#helpx').is(':visible') == false ) {
        $('#helpx').show().dialog({height: 600, width:550, dialogClass: 'shadowme', position: [390,130]});
            }
    else { $('#helpx').dialog('close'); }
});

Remember that the accordion is inside the tags of the dialog in the html. For instance

Body:
this seems seems to work fine for me but we really need to see your code

$( "#accordion" ).accordion();
$('#dialog').dialog({autoOpen:false});
$('#mybutton').click(function(){
    $('#dialog').dialog('open');
})

here is a working demo


问:
You are using the runtime-only build of Vue where the template compiler is not available
I'm trying to compile my Vue.js app with webpack but I get this warning in the browser.

You are using the runtime-only build of Vue where the template compiler is not available. Either pre-compile the templates into render functions, or use the compiler-included build.

What does this mean? How do I resolve the error?

答:
If you compile your app with vue-cli-service add the following code to vue.config.js depending upon compiler:

```<code>  configureWebpack: {
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm.js'
      }
    }
  }
</code>```

If you compile your app with webpack add the following code to webpack.config.js:

```<code>
    resolve: {
      alias: {
         vue: 'vue/dist/vue.js'
      }
    }

</code>```

Body:
If you compile your app with vue-cli-service add the following code to vue.config.js depending upon compiler:

  configureWebpack: {
    resolve: {
      alias: {
        'vue$': 'vue/dist/vue.esm.js'
      }
    }
  }

If you compile your app with webpack add the following code to webpack.config.js:

    resolve: {
      alias: {
         vue: 'vue/dist/vue.js'
      }
    }


问:
MSBuildProjectExtensionsPath MSBuild Property Could Not be Found When trying to Manage Nuget Packages
I've encountered a weird error today when trying to manage nuget packages on a unit test project in my solution:

I took a look at the documentation for this property: https://learn.microsoft.com/en-us/visualstudio/msbuild/customize-your-build?view=vs-2019 and it mentions that this property is part of a props or a target file. My solution does not have one of these. I went ahead and modified the csproj to add the property:
<MSBuildProjectExtensionsPath /> to the appropriate build propertygroup, and it didn't detect it either. I looked at another project that lets me work with nuget packages successfully and it doesn't have the property at all.

Anyone know what's going on?

答:
You probably accidentally removed the following line from your project file:</p>

```<code>  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</code>```

Body:
You probably accidentally removed the following line from your project file:

  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />


问:
Regex for use with PHP's preg_match() to find a newline
I'm fairly new/rusty with regular expressions.  I'm collecting a block of text from a textarea element and I want to check to see if the person who filled it used any paragraphs, amongst other things.

I'm using the following and I know it's wrong.

```<code>preg_match('/\r\n|\n|\r/', $_GET['text']);
</code>```

答:
Assuming:

This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.

And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another.

You could just do:

```<code>if (str_replace("\r\n\r\n", '', $str) != $str)
  // the input contains at least two paragraphs
</code>```

Body:
I'm fairly new/rusty with regular expressions.  I'm collecting a block of text from a textarea element and I want to check to see if the person who filled it used any paragraphs, amongst other things.

I'm using the following and I know it's wrong.

preg_match('/\r\n|\n|\r/', $_GET['text']);

Body:
Assuming:

This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph. This is a paragraph.

And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another. And this is another.

You could just do:

if (str_replace("\r\n\r\n", '', $str) != $str)
  // the input contains at least two paragraphs


问:
Is negative_mean_squared greater the more accuracy or less computes to more accuracy?
-0.567
-4.235

Which of the above negative_mean_squared error value computes to more accuracy?

答: Higher the value better it is. So in your case -0.567 is better. A per the documentation sklearn scoring functions maintain the following convention higher return values are better than lower return values.  But when you look at mean_squared_error or for that matter even mean_absolute_error lower the value better it is. So they just flip the sign of the value to make sure it follows the convention. For your example, -0.567 results in a mean_squared_error of just 0.567 whereas, -4.235 has a mean_squared_error of 4.235 which is much higher than the former.


问:
Variable Not In Scope for Lambda
I'm trying to diagnose a timing issue on a multi-core processor [Xeon Silver].  I think that the clocks have not been configured or synced between the processor.  I'm using Eli Bendersky's [credited in the code snippet] threading examples to build a test instrument.  I have made three changes.  I made made the sleep occur first, and I added a call to std::chrono::system_clock::now() and tried to print it out.  I'm building with gcc 4.8.5 on CentOS 7.5.

The code is as follows:

```<code>// // Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <pthread.h>

int main(int argc, const char** argv) {
  unsigned num_cpus = std::thread::hardware_concurrency();
  std::cout << "Launching " << num_cpus << " threads\n";

  // A mutex ensures orderly access to std::cout from multiple threads.
  std::mutex iomutex;
  std::vector<std::thread> threads(num_cpus);
  for (unsigned i = 0; i < num_cpus; ++i)
  {
    threads[i] = std::thread([&iomutex, i]
    {
       // Simulate important work done by the tread by sleeping for a bit...
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      {
         std::chrono::time_point ti = std::chrono::system_clock::now();
         // Use a lexical scope and lock_guard to safely lock the mutex only for
         // the duration of std::cout usage.
         std::lock_guard<std::mutex> iolock(iomutex);
         std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
       }
    });
  }

  for (auto& t : threads) {
      t.join();
  }
  return 0;
}
</code>```

I build with make:

```<code>CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3 -g -DNDEBUG -pthread
LDFLAGS = -lpthread -pthread

clock-check: clock-check.cpp
    $(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)
</code>```

GCC gives me the following error:

```<code>[user@sbc1 concur]$ make clock-check
g++ -std=c++11 -Wall -O3 -g -DNDEBUG -pthread clock-check.cpp -o clock-check -lpthread -pthread
clock-check.cpp: In lambda function:
clock-check.cpp:32:67: error: ‘ti’ was not declared in this scope
      std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
                                                               ^
make: *** [clock-check] Error 1
</code>```

ti is clearly in the same block scope as the print statement, and I'm baffled why the compiler is complaining.  I have not found any restrictions on variables local to the lambda.  Most of what I have found has been references to captures.

答:
Your problem lies in this line:

```<code>std::chrono::time_point ti = std::chrono::system_clock::now();
</code>```

std::chrono::time_point expect a type argument (e.g. std::chrono::time_point<std::chrono::system_clock>)

Prefer to use auto in this case:

```<code>auto ti = std::chrono::system_clock::now();
</code>```

Then, you'll have an error since you try to output a std::chrono::duration in an output stream.

You should do:

```<code>std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch().count() << "\n";
</code>```

Title: Variable Not In Scope for Lambda

Body:
I'm trying to diagnose a timing issue on a multi-core processor [Xeon Silver].  I think that the clocks have not been configured or synced between the processor.  I'm using Eli Bendersky's [credited in the code snippet] threading examples to build a test instrument.  I have made three changes.  I made made the sleep occur first, and I added a call to std::chrono::system_clock::now() and tried to print it out.  I'm building with gcc 4.8.5 on CentOS 7.5.

The code is as follows:

// // Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
#include <algorithm>
#include <chrono>
#include <iostream>
#include <mutex>
#include <thread>
#include <vector>
#include <pthread.h>

int main(int argc, const char** argv) {
  unsigned num_cpus = std::thread::hardware_concurrency();
  std::cout << "Launching " << num_cpus << " threads\n";

  // A mutex ensures orderly access to std::cout from multiple threads.
  std::mutex iomutex;
  std::vector<std::thread> threads(num_cpus);
  for (unsigned i = 0; i < num_cpus; ++i)
  {
    threads[i] = std::thread([&iomutex, i]
    {
       // Simulate important work done by the tread by sleeping for a bit...
      std::this_thread::sleep_for(std::chrono::milliseconds(200));
      {
         std::chrono::time_point ti = std::chrono::system_clock::now();
         // Use a lexical scope and lock_guard to safely lock the mutex only for
         // the duration of std::cout usage.
         std::lock_guard<std::mutex> iolock(iomutex);
         std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
       }
    });
  }

  for (auto& t : threads) {
      t.join();
  }
  return 0;
}

I build with make:

CXX = g++
CXXFLAGS = -std=c++11 -Wall -O3 -g -DNDEBUG -pthread
LDFLAGS = -lpthread -pthread

clock-check: clock-check.cpp
    $(CXX) $(CXXFLAGS) $^ -o $@ $(LDFLAGS)

GCC gives me the following error:

[user@sbc1 concur]$ make clock-check
g++ -std=c++11 -Wall -O3 -g -DNDEBUG -pthread clock-check.cpp -o clock-check -lpthread -pthread
clock-check.cpp: In lambda function:
clock-check.cpp:32:67: error: ‘ti’ was not declared in this scope
      std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch() << "\n";
                                                               ^
make: *** [clock-check] Error 1

ti is clearly in the same block scope as the print statement, and I'm baffled why the compiler is complaining.  I have not found any restrictions on variables local to the lambda.  Most of what I have found has been references to captures.

Body:
Your problem lies in this line:

std::chrono::time_point ti = std::chrono::system_clock::now();

std::chrono::time_point expect a type argument (e.g. std::chrono::time_point<std::chrono::system_clock>)

Prefer to use auto in this case:

auto ti = std::chrono::system_clock::now();

Then, you'll have an error since you try to output a std::chrono::duration in an output stream.

You should do:

std::cout << "Thread #" << i << " hit its clock at: " << ti.time_since_epoch().count() << "\n";


问:
How to make User Input (STDIN) to move left and right in PERL - Unix Env
i'm a newbie in PERL. Whenever i tried to move left or right to delete characters in terminal it shows "^[[D^[[C^[[C^[[D". Is there a way to make User Input (STDIN) to scroll left and right to delete the data in PERL ?

i am looking for user to use keyboard arrows for example, to edit or correct what has just been typed without deleting the last entered characters with backspace.

Example code:
print  "What is your Fav Food?; $food= STDIN;

i want the readline to be flexible to delete the user entries.

答: What you want is known as input line editing. For that, You can either user some terminal aware perl module for getting user Input ( https://metacpan.org/search?q=module%3ATerm%3A%3AReadline). Or run your perl script under  rlwrap (https://linux.die.net/man/1/rlwrap) command.


问:
How to access and store a particular object from a json file in c#
I am trying to make a multi-subject quiz game for children using unity3D and questions and answers are stored in a json file. Now i want to create an object named "science" and "maths" and want to store their respective questions in them and when i want to access science i could loop and find and just store the science question in my string instead of reading the whole json file.

here is my json file.

```<code>    Science ={
    "CourseName":"Science",
    "No_Of_Ques":4,
    "Ques_Data":[
                  { "Quesion":"which is the biggest planet in the solar system?",
                    "Answer":"jupiter",
                    "options":["mars","earth","venus","jupiter"]
                  },

                  { "Quesion":"How many planets are there in solar system?",
                    "Answer":"Eight",
                    "options":["Seven","Nine","Five","Eight"]
                  },

                  { "Quesion":"which is the closest planet to the sun?",
                    "Answer":"mercury",
                    "options":["mars","saturn","venus","mercury"]
                  },

                  { "Quesion":"How many moons does jupiter have?",
                    "Answer":"12",
                    "options":["5","13","9","12"]
                  }
                ]
}
</code>```

and this is how i have been acessing it so far

```<code>path = Application.dataPath + "/QnA.json";
    string json = File.ReadAllText(path);
    Course c1 = JsonUtility.FromJson<Course>(json);

    return c1;
</code>```

Course and needed serializable Classes:

```<code>[Serializable] public class Course
{
    public string CourseName;
    public string No_Of_Ques;
    public QnA[] Ques_Data;
}

[Serializable]
public class QnA
{
    public string Quesion;
    public string Answer;
    public string[] options;
}
</code>```

i have tried so many things like Deserialization and Jobject asset but none of them seem to work and every implementation that i have found on the internet has the json data in the same file as the c# code but i can not do that as my json contains hundreds of lines of data. kindly help me out a little.

答:
Using Science={...} to define your object is where you get confused about object definitions. It is not a Science object. It is a Course object.

It should be more like

```<code>{
    "Courses" :
    [
        {
            "CourseName" : "Science",
            ...
        },
        {
            "CourseName" : "Maths",
            ...
        }
    ]
}`.
</code>```

Wrap it with:

```<code>"Quiz" :
{
    "Courses" :
    [
        {
            "CourseName" : "Science",
            ...
        },
        {
            "CourseName" : "Maths",
            ...
        }
    ]
}
</code>```

and use

```<code>[Serializable]
public class Quiz
{
    public Course[] courses;
}
</code>```

To hold it as  a C# object.

From here you can access your courses by quiz.Courses[0].Questions[17] or write helper methods in Quiz class to call courses by enums like quiz.GetCourse(CourseCategory.Science).Questions[8].

I also suggest using Questions instead of Question_Data. That is more object friendly and helps you semantically.

As an additional suggestion, instead of dumping all of the quiz in a single JSON, you may consider sending a single Course object depending on the course, requested using a query like http://myquizserver.com/quiz.php?course=science. Since you mentioned hundreds of lines of JSON, you may also consider getting data question by question.

Body:
I am trying to make a multi-subject quiz game for children using unity3D and questions and answers are stored in a json file. Now i want to create an object named "science" and "maths" and want to store their respective questions in them and when i want to access science i could loop and find and just store the science question in my string instead of reading the whole json file.

here is my json file.

    Science ={
    "CourseName":"Science",
    "No_Of_Ques":4,
    "Ques_Data":[
                  { "Quesion":"which is the biggest planet in the solar system?",
                    "Answer":"jupiter",
                    "options":["mars","earth","venus","jupiter"]
                  },

                  { "Quesion":"How many planets are there in solar system?",
                    "Answer":"Eight",
                    "options":["Seven","Nine","Five","Eight"]
                  },

                  { "Quesion":"which is the closest planet to the sun?",
                    "Answer":"mercury",
                    "options":["mars","saturn","venus","mercury"]
                  },

                  { "Quesion":"How many moons does jupiter have?",
                    "Answer":"12",
                    "options":["5","13","9","12"]
                  }
                ]
}

and this is how i have been acessing it so far

path = Application.dataPath + "/QnA.json";
    string json = File.ReadAllText(path);
    Course c1 = JsonUtility.FromJson<Course>(json);

    return c1;

Course and needed serializable Classes:

[Serializable] public class Course
{
    public string CourseName;
    public string No_Of_Ques;
    public QnA[] Ques_Data;
}

[Serializable]
public class QnA
{
    public string Quesion;
    public string Answer;
    public string[] options;
}

i have tried so many things like Deserialization and Jobject asset but none of them seem to work and every implementation that i have found on the internet has the json data in the same file as the c# code but i can not do that as my json contains hundreds of lines of data. kindly help me out a little.

Body:
Using Science={...} to define your object is where you get confused about object definitions. It is not a Science object. It is a Course object.

It should be more like

{
    "Courses" :
    [
        {
            "CourseName" : "Science",
            ...
        },
        {
            "CourseName" : "Maths",
            ...
        }
    ]
}`.

Wrap it with:

"Quiz" :
{
    "Courses" :
    [
        {
            "CourseName" : "Science",
            ...
        },
        {
            "CourseName" : "Maths",
            ...
        }
    ]
}

and use

[Serializable]
public class Quiz
{
    public Course[] courses;
}

To hold it as  a C# object.

From here you can access your courses by quiz.Courses[0].Questions[17] or write helper methods in Quiz class to call courses by enums like quiz.GetCourse(CourseCategory.Science).Questions[8].

I also suggest using Questions instead of Question_Data. That is more object friendly and helps you semantically.

As an additional suggestion, instead of dumping all of the quiz in a single JSON, you may consider sending a single Course object depending on the course, requested using a query like http://myquizserver.com/quiz.php?course=science. Since you mentioned hundreds of lines of JSON, you may also consider getting data question by question.


问:
Multi-tenant socks
So I have a this awesome multi-tenant project I made with Django. I have it deployed on heroku and everything is good to go. BUT its multi-tenant so I need things like customer1.site.com and customer2.site.com

I got this working on my side because my computer has a static IP address so I can just route *.site.com to my IP address and then everything works.

Heroku doesn't have this ability of static ip addresses. So how can I get past this? I need a cost effective way to solve this. The solutions I see are mainly addons for outbound traffic only. I simply need to route all traffic to *.site.com to an ip address that will show my application on heroku.

I in theory can do something like *.app.site.com and route all that traffic to app.herokuapp.com but customer.app.site.com seems way to much honestly. Plus it looks tacky. Has anyone does anything to figure this out?strong text

答:
You can route wildcard domain to Heroku as shown in its documentation

heroku domains:add *.example.com

Use the * wildcard subdomain notation to add a CNAME record to
  encircled-magnolia-9265.herokudns.com. with your DNS provider.

Title: Multi-tenant socks


问:
zsh and parallel: How to use functions. It says command not found
I have a script file

filename: test_sem_zsh.sh

```<code>main() {
    echo "Happy day"
}
export -f main
sem --id testing --fg main
</code>```

I am trying to run it using zsh

```<code>$ zsh test_sem_zsh.sh
test_sem_zsh.sh:export:4: invalid option(s)
zsh:1: command not found: main
</code>```

It says two error's 1) main command not found and 2) export:4: invalid option(s)

Where as when i try with bash it works

```<code>$ sh test_sem_zsh.sh
Happy day
</code>```

So how to get this script working with zsh also

答:
sem is just a shorthand for parallel --semaphore.

You can use env_parallel:

```<code>#!/usr/bin/zsh

# activate env_parallel (if not already done)
. =env_parallel.zsh

env_parallel --semaphore --id testing --fg main
</code>```

Or if your environment is too big:

```<code>#!/usr/bin/zsh

# activate env_parallel (if not already done)
. =env_parallel.zsh

env_parallel --session

main() {
    echo "Happy day"
}
env_parallel --semaphore --id testing --fg main

env_parallel --end-session
</code>```

Body:
I have a script file

filename: test_sem_zsh.sh

main() {
    echo "Happy day"
}
export -f main
sem --id testing --fg main

I am trying to run it using zsh

$ zsh test_sem_zsh.sh
test_sem_zsh.sh:export:4: invalid option(s)
zsh:1: command not found: main

It says two error's 1) main command not found and 2) export:4: invalid option(s)

Where as when i try with bash it works

$ sh test_sem_zsh.sh
Happy day

So how to get this script working with zsh also

Body:
sem is just a shorthand for parallel --semaphore.

You can use env_parallel:

#!/usr/bin/zsh

# activate env_parallel (if not already done)
. =env_parallel.zsh

env_parallel --semaphore --id testing --fg main

Or if your environment is too big:

#!/usr/bin/zsh

# activate env_parallel (if not already done)
. =env_parallel.zsh

env_parallel --session

main() {
    echo "Happy day"
}
env_parallel --semaphore --id testing --fg main

env_parallel --end-session