问:
JSON schema - validate sum of object properties
I have the following schema for a PUT network request body:

```<code>{
  title: "Character",
  description: "PUT character request body parameters",
  type: "object",
  properties: {
    _id: {
      description:
        "ObjectID string for updating an existing character. Should not be present when a new character is created.",
      type: "string"
    },
    name: {
      description: "User input character name.",
      type: "string"
    },
    description: {
      description: "User input character description.",
      type: "string"
    },
    weaponId: {
      description: "ObjectID string for the equiped character weapon",
      type: "string"
    },
    armorId: {
      description: "ObjectID string for the equiped character weapon",
      type: "string"
    },
    shieldId: {
      description: "ObjectID string for the equiped character weapon",
      type: "string"
    },
    stats: {
      description: "Base character stats input by user",
      type: "object",
      properties: {
        str: {
          description: "Character strength stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        stam: {
          description: "Character stamina stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        wp: {
          description: "Character willpower stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        dex: {
          description: "Character dexterity stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        spd: {
          description: "Character speed stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        }
      }
    }
  },
  required: ["name", "description", "stats"]
}
</code>```

I would like to validate that the sum of the keys on the stats object does not exceed 1000. Is this possible with JSON schema - I did not find any mention of it in the documentation.

Thanks

答:
No this is not possible with JSON Schema.

You will need to write your own business logic code to perform such calculations.

Body:
I have the following schema for a PUT network request body:

{
  title: "Character",
  description: "PUT character request body parameters",
  type: "object",
  properties: {
    _id: {
      description:
        "ObjectID string for updating an existing character. Should not be present when a new character is created.",
      type: "string"
    },
    name: {
      description: "User input character name.",
      type: "string"
    },
    description: {
      description: "User input character description.",
      type: "string"
    },
    weaponId: {
      description: "ObjectID string for the equiped character weapon",
      type: "string"
    },
    armorId: {
      description: "ObjectID string for the equiped character weapon",
      type: "string"
    },
    shieldId: {
      description: "ObjectID string for the equiped character weapon",
      type: "string"
    },
    stats: {
      description: "Base character stats input by user",
      type: "object",
      properties: {
        str: {
          description: "Character strength stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        stam: {
          description: "Character stamina stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        wp: {
          description: "Character willpower stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        dex: {
          description: "Character dexterity stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        },
        spd: {
          description: "Character speed stat.",
          type: "number",
          minimum: 100,
          maximum: 500
        }
      }
    }
  },
  required: ["name", "description", "stats"]
}

I would like to validate that the sum of the keys on the stats object does not exceed 1000. Is this possible with JSON schema - I did not find any mention of it in the documentation.

Thanks


来源: stackexchange

问:
ERROR: could not stat file "XX.csv": Unknown error
I run this command:

```<code>COPY XXX FROM 'D:/XXX.csv'  WITH (FORMAT CSV, HEADER TRUE, NULL 'NULL')
</code>```

In Windows 7, it successfully imports CSV files of less than 1GB.

If the file is more then 1GB big, I get an “unknown error”.

```<code>[Code: 0, SQL State: XX000]  ERROR: could not stat file "'D:/XXX.csv'  Unknown error
</code>```

How can I fix this issue?

答:
It seems this is not a database problem, but a problem of psql / pgadmin. The workaround is using an admin software from the previous psql versions:

Use the existing PostgreSQL 11 database

Install psql or pgadmin from the PostgreSQL 10 installation and use it to upload the file (with the command shown in the question)

Hope this helps anyone coming across the same problem.

ContentLicense: CC BY-SA 4.0

Body:
I run this command:

COPY XXX FROM 'D:/XXX.csv'  WITH (FORMAT CSV, HEADER TRUE, NULL 'NULL')

In Windows 7, it successfully imports CSV files of less than 1GB.

If the file is more then 1GB big, I get an “unknown error”.

[Code: 0, SQL State: XX000]  ERROR: could not stat file "'D:/XXX.csv'  Unknown error

How can I fix this issue?


问:
Cannot send function to Electron Renderer process from Main Process
I would like to send a function from my main to renderer process

I have an function which I export from the db.services.js module

```<code>// db.services.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert')

var DatabaseService = (function () {
    "use strict";
    var instance; //prevent modification of "instance" variable
    function Singleton() {
        if (instance) {
            return instance;
        }
        instance = this;
    }

    Singleton.create = function (db_uri) {
        //Singleton initialization code
        this.db_uri = db_uri
        this.db = undefined
        this.a = 0 // debugging async behavior
    }

    //instance accessor
    Singleton.getInstance = function () {
        return instance || new Singleton();
    };

    Singleton.getDB = function () {
        return this.db.db('xFilterDB') // directly return the used DB
    }

    Singleton.establishConnection = function (callback) {
        ...
    }

    return Singleton;
}());

// exporting a "singleton" object to use with all views
DatabaseService.getInstance();

module.exports = DatabaseService;
</code>```

I 'import' the function into my main electron process app.js

```<code>// app.js

const {
    app,
    BrowserWindow,
    ipcMain
} = require('electron');

const isDev = require('electron-is-dev');
const DatabaseService = require('./services/db.services');
app.on('ready', function () {
    DatabaseService.getInstance();
    DatabaseService.create("mongodb://localhost:27017");

    mainWindow = new BrowserWindow({
        width: 1024,
        height: 768,
        webPreferences: {
            nodeIntegration: true
        }
    })
    let url = 'file://' + __dirname + '/views/main.html'
    mainWindow.loadURL(url)
    mainWindow.webContents.on('did-finish-load', () => {
        console.log(DatabaseService);

        //
        // [Function: Singleton] {
        //   create: [Function],
        //   getInstance: [Function],
        //   getDB: [Function],
        //   establishConnection: [Function],
        //   db_uri: 'mongodb://localhost:27017',
        //   db: undefined,
        //   a: 0
        // }

        mainWindow.webContents.send('database-service',
            DatabaseService);  // <-- I am sending the function here
    });
    windows.push(mainWindow)
}
</code>```

In main.html I do

```<code><script>
        require('./main.js')
</script>
</code>```

And in main.js

```<code>//main.js

ipcRenderer.on('database-service', (event, args) => {
    // ----- mongo connection ESTABLISH REGION START----
    // implicit async
    console.log(args); // <-- args is null here
    ...
}
</code>```

Any idea what is going wrong here?

Also, apparently this webContents.send('database-service', DatabaseService) is deprecated. So a better solution will be doubly appreciated.

答:
You cannot send Function via IPC channel, becasue it cannot be serialized.

From docs:

Send an asynchronous message to the renderer process via channel,
  along with arguments. Arguments will be serialized with the Structured
  Clone Algorithm, just like postMessage, so prototype chains will not
  be included. Sending Functions, Promises, Symbols, WeakMaps, or
  WeakSets will throw an exception.

Body:
I would like to send a function from my main to renderer process

I have an function which I export from the db.services.js module

// db.services.js
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert')

var DatabaseService = (function () {
    "use strict";
    var instance; //prevent modification of "instance" variable
    function Singleton() {
        if (instance) {
            return instance;
        }
        instance = this;
    }

    Singleton.create = function (db_uri) {
        //Singleton initialization code
        this.db_uri = db_uri
        this.db = undefined
        this.a = 0 // debugging async behavior
    }

    //instance accessor
    Singleton.getInstance = function () {
        return instance || new Singleton();
    };

    Singleton.getDB = function () {
        return this.db.db('xFilterDB') // directly return the used DB
    }

    Singleton.establishConnection = function (callback) {
        ...
    }

    return Singleton;
}());

// exporting a "singleton" object to use with all views
DatabaseService.getInstance();

module.exports = DatabaseService;

I 'import' the function into my main electron process app.js

// app.js

const {
    app,
    BrowserWindow,
    ipcMain
} = require('electron');

const isDev = require('electron-is-dev');
const DatabaseService = require('./services/db.services');
app.on('ready', function () {
    DatabaseService.getInstance();
    DatabaseService.create("mongodb://localhost:27017");

    mainWindow = new BrowserWindow({
        width: 1024,
        height: 768,
        webPreferences: {
            nodeIntegration: true
        }
    })
    let url = 'file://' + __dirname + '/views/main.html'
    mainWindow.loadURL(url)
    mainWindow.webContents.on('did-finish-load', () => {
        console.log(DatabaseService);

        //
        // [Function: Singleton] {
        //   create: [Function],
        //   getInstance: [Function],
        //   getDB: [Function],
        //   establishConnection: [Function],
        //   db_uri: 'mongodb://localhost:27017',
        //   db: undefined,
        //   a: 0
        // }

        mainWindow.webContents.send('database-service',
            DatabaseService);  // <-- I am sending the function here
    });
    windows.push(mainWindow)
}

In main.html I do

And in main.js

//main.js

ipcRenderer.on('database-service', (event, args) => {
    // ----- mongo connection ESTABLISH REGION START----
    // implicit async
    console.log(args); // <-- args is null here
    ...
}

Any idea what is going wrong here?

Also, apparently this webContents.send('database-service', DatabaseService) is deprecated. So a better solution will be doubly appreciated.


问:
DAO, SERVICE layer what for
What for this two layers? Why we must execute dao-method in service? Why we should use @Transactional only in Service method fields. Why we can't use @Transactional on the dao methods directly and don't use the services?</p>

答:
beacuase there is many ways to manage the transactions called transaction Propagation

TransactionDefinition.PROPAGATION_MANDATORY : Supports a current transaction; throws an exception if no current transaction exists.

TransactionDefinition.PROPAGATION_NESTED : Executes within a nested transaction if a current transaction exists.

TransactionDefinition.PROPAGATION_NEVER : Does not support a current transaction; throws an exception if a current transaction exists.

TransactionDefinition.PROPAGATION_NOT_SUPPORTED : Does not support a current transaction; rather always execute nontransactionally.

TransactionDefinition.PROPAGATION_REQUIRED : Supports a current transaction; creates a new one if none exists.

TransactionDefinition.PROPAGATION_REQUIRES_NEW : Creates a new transaction, suspending the current transaction if one exists.

TransactionDefinition.PROPAGATION_SUPPORTS : Supports a current transaction; executes non-transactionally if none exists.

TransactionDefinition.TIMEOUT_DEFAULT : Uses the default timeout of the underlying transaction system, or none if timeouts are not supported.

Title: DAO, SERVICE layer what for


问:
The console application code I wrote in Dev-C ++ runs smoothly in the compiler but seems missing when running the .exe application?
I just started learning C++. I made a small console application using the scanf function, when I say compile and run in DevC++ environment, it opens smoothly (even I tried it in the online C++ compiler, there is no problem in the console) but when I close and run the program with the .exe extension I compiled, the last part is missing. It does not appear on the console after a certain location and the console turns off directly. What error, what warning, why might it be, and how can I fix it?

#include <iostream>
#include <stdio.h>

int main() {

    char isminiz[15];
    char soyisminiz[15];
    char yasiniz[3];

    printf ("Isminizi yaziniz: ");
    scanf("%s",isminiz);
    printf ("Soyisminizi yaziniz: ");
    scanf ("%s",soyisminiz);
    printf ("Yasiniz: ");
    scanf("%s",yasiniz);

    return 0;
}
```

答:
Since you are trying to do it on C.
Use getchar() before the return function.

#include <stdio.h>

int main() {

    printf ("Uyari: Turkce karakter kullanmayiniz ve sorulari tek kelime ile cevaplandiriniz.\n\n");

    char isminiz[15];
    char soyisminiz[15];
    char yasiniz[3];
    char mutlu[15];
    char sanat[30];
    char fb[20];
    char kim[20];

    printf ("Isminizi yaziniz: ");
    scanf("%s",isminiz);
    printf ("Soyisminizi yaziniz: ");
    scanf ("%s",soyisminiz);
    printf ("Yasiniz: ");
    scanf("%s",yasiniz);
    printf ("Mutluluk nedir: ");
    scanf("%s",mutlu);
    printf ("Peki sanat nedir desek: ");
    scanf("%s",sanat);
    printf ("Fb nin uykusu gelmis midir: ");
    scanf("%s",fb);
    printf ("Isim: %s - Soyisim: %s \n",isminiz,soyisminiz);
    printf ("Mutluluk: %s\n",mutlu);
    printf ("Sanat: %s\n",sanat);
    printf ("Gelmis mi: %s\n\n",fb);
    printf ("Fb seni cok seviyor dostum hayirli geceler :) \n");
    printf("Devam etmek için herhangi bir tuşa basın\n");

    getchar();

    return 0;
}
```

I have compiled and executed it on Linux terminal and the window will remain open. Basically the getchar() function will wait for the user to press a key. This works like system.pause() except that it is for C and it will only close when the user will press a button. I don't know what it was asking for in the input so I entered strings since %s was the required input in scanf.

Body:
Since you are trying to do it on C.
Use getchar() before the return function.

#include <stdio.h>

int main() {

    printf ("Uyari: Turkce karakter kullanmayiniz ve sorulari tek kelime ile cevaplandiriniz.\n\n");

    char isminiz[15];
    char soyisminiz[15];
    char yasiniz[3];
    char mutlu[15];
    char sanat[30];
    char fb[20];
    char kim[20];

    printf ("Isminizi yaziniz: ");
    scanf("%s",isminiz);
    printf ("Soyisminizi yaziniz: ");
    scanf ("%s",soyisminiz);
    printf ("Yasiniz: ");
    scanf("%s",yasiniz);
    printf ("Mutluluk nedir: ");
    scanf("%s",mutlu);
    printf ("Peki sanat nedir desek: ");
    scanf("%s",sanat);
    printf ("Fb nin uykusu gelmis midir: ");
    scanf("%s",fb);
    printf ("Isim: %s - Soyisim: %s \n",isminiz,soyisminiz);
    printf ("Mutluluk: %s\n",mutlu);
    printf ("Sanat: %s\n",sanat);
    printf ("Gelmis mi: %s\n\n",fb);
    printf ("Fb seni cok seviyor dostum hayirli geceler :) \n");
    printf("Devam etmek için herhangi bir tuşa basın\n");

    getchar();

    return 0;
}

I have compiled and executed it on Linux terminal and the window will remain open. Basically the getchar() function will wait for the user to press a key. This works like system.pause() except that it is for C and it will only close when the user will press a button. I don't know what it was asking for in the input so I entered strings since %s was the required input in scanf.


问:
Specifying vocabulary input in LDA
I am trying to understand how to use LDA in my case. I have a corpus of many documents and I want to see how a very specific set of words and ngrams are distributed across topics. Is there a way to specify a list of specific words as a vocabulary for topic modeling?

I have been working with the gensim implementation and I believe the argument id2word handles this, but the documentation is not clear to me. Is my understanding correct?

答:
you can use the Scikit learn Countvectorizer for this

```<code>from sklearn.feature_extraction.text import CountVectorizer
from gensim import matutils
from gensim.models.ldamodel import LdaModel

text = ['computer time graph', 'survey response eps', 'human system computer','machinelearning is very hot topic','python win the race for simplicity as compared to other programming language']

# suppose this are the word that you want to be used in your vocab
vocabulary = ['machine','python','learning','human', 'system','hot','time']

vect = CountVectorizer(vocabulary = vocabulary)
x = vect.fit_transform(text)

feature_name = vect.get_feature_names()

# now you can use matutils helper function of gensim
model = LdaModel(matutils.Sparse2Corpus(x),num_topic=3,id2word=dict([(i, s) for i, s in enumerate(feature_name)]))

#printing the topic
model.show_topics()
</code>```

```<code> #to see the vocab that use being used
 print(vect.get_feature_names())
  ['machine', 'python', 'learning', 'human', 'system', 'hot', 'time'] # you will get the feature that you want include
</code>```

Title: Specifying vocabulary input in LDA

Body:
you can use the Scikit learn Countvectorizer for this

from sklearn.feature_extraction.text import CountVectorizer
from gensim import matutils
from gensim.models.ldamodel import LdaModel

text = ['computer time graph', 'survey response eps', 'human system computer','machinelearning is very hot topic','python win the race for simplicity as compared to other programming language']

# suppose this are the word that you want to be used in your vocab
vocabulary = ['machine','python','learning','human', 'system','hot','time']

vect = CountVectorizer(vocabulary = vocabulary)
x = vect.fit_transform(text)

feature_name = vect.get_feature_names()

# now you can use matutils helper function of gensim
model = LdaModel(matutils.Sparse2Corpus(x),num_topic=3,id2word=dict([(i, s) for i, s in enumerate(feature_name)]))

#printing the topic
model.show_topics()

 #to see the vocab that use being used
 print(vect.get_feature_names())
  ['machine', 'python', 'learning', 'human', 'system', 'hot', 'time'] # you will get the feature that you want include


问:
This script is always returning unknown. Even if there are files and directory inside my root folder?
```<code>for item in os.listdir("/root"):
    if os.path.isfile(item):
        print(item + "is a file")
    elif os.path.isdir(item):
        print(item + "is a dir")
    else:
        print("Unknown")
</code>```

答:
Your condition is wrong, you want to do:</p>

```<code>if os.path.isfile('/root/' + item):
</code>```

Body:
Your condition is wrong, you want to do:

if os.path.isfile('/root/' + item):


问:
Associative array response to variables with wpdb get results
I am doing a ajax request which calls a php file which uses wpdb get results.

```<code>$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM t39b_felderkonfig WHERE user_id= %d ",  $user_id), ARRAY_A);
echo json_encode($result);
</code>```

It returns the following array:

```<code>[{"felderkonfig_id":"7","felderkonfig_kategorie":"1","felderkonfig_kategorie2":"1"]
</code>```

How can i now get the array into variables? I tried:

```<code>success: function (response) {
    var kategorie = response['felderkonfig_kategorie'];
    var kategorie2 = response['felderkonfig_kategorie2'];
    var industriesparte = response['felderkonfig_industriesparte'];
</code>```

But that doesnt work.

Solution:
$wpdb get results returns a multidimensional array. To access the array correctly:

```<code>var kategorie = response[0]['felderkonfig_kategorie'];
</code>```

Maybe this helps other wordpress developers.

答:
You need to parse the date using JSON.parse(). So the response will be passed like this:

var parseResponse = JSON.parse(response);
var kategorie = parseResponse['felderkonfig_kategorie']

Body:
I am doing a ajax request which calls a php file which uses wpdb get results.

$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM t39b_felderkonfig WHERE user_id= %d ",  $user_id), ARRAY_A);
echo json_encode($result);

It returns the following array:

[{"felderkonfig_id":"7","felderkonfig_kategorie":"1","felderkonfig_kategorie2":"1"]

How can i now get the array into variables? I tried:

success: function (response) {
    var kategorie = response['felderkonfig_kategorie'];
    var kategorie2 = response['felderkonfig_kategorie2'];
    var industriesparte = response['felderkonfig_industriesparte'];

But that doesnt work.

Solution:
$wpdb get results returns a multidimensional array. To access the array correctly:

var kategorie = response[0]['felderkonfig_kategorie'];

Maybe this helps other wordpress developers.


问:
How to Create an Array with Same Element repeated multiple times in Arduino?
```<code>**array=[symbol,count,symbol,count.....]
for eg: array=[3,2,5,4..]
new_array=[3,3,5,5,5,5...]**

      int array[]={25,6,10,2,4,3,9,5};
       int value1[16]={0};
        Serial.print("\n RLE decoded");
       for(i=0;i<len;i++)
       {
         if(i%2==0)
         {
           value[i] = array[i];
           i=i+1;
           count=array[i];
         }
         for(j=0; j<count;j++)
         {

           Serial.print(value[i]);
           Serial.print('\t');
         }
</code>```

How to Create an Array with Same Element repeated multiple times in Arduino?
This code is working properly and we are able to print repeatedly the symbols but the problem with this code is :: the repeated the values are not getting stored to a new array. we tried with declaring a new array to store the repeated values but it is not working!!

答:
An array is a collection of the same elements, but symbol and count are obviously different things. To group different things together, struct was invented in the earliest days of C

```<code>struct {char symbol;  byte count;} input[] = {
  {'a', 2}, {'X' ,3} ,{'!', 1}
};

const byte inputcount = sizeof(input)/sizeof(input[0]); // 3 in this test
char expanded[20]; // will get the result

void setup() {
   Serial.begin(9600);
   char* resultpos = expanded;
   for (auto& elem:input) {
      for (byte p = 0; p < elem.count; p++) {
         *resultpos++ = elem.symbol;
      }
   }
   *resultpos = 0; // to make it a printable char array
   Serial.println(expanded); // should give "aaXXX!"
}
void loop() {}
</code>```

If you prefer, you can use the classic type of for loop as well. But this for each is really nice, IMO.

Body:
**array=[symbol,count,symbol,count.....]
for eg: array=[3,2,5,4..]
new_array=[3,3,5,5,5,5...]**

      int array[]={25,6,10,2,4,3,9,5};
       int value1[16]={0};
        Serial.print("\n RLE decoded");
       for(i=0;i<len;i++)
       {
         if(i%2==0)
         {
           value[i] = array[i];
           i=i+1;
           count=array[i];
         }
         for(j=0; j<count;j++)
         {

           Serial.print(value[i]);
           Serial.print('\t');
         }

How to Create an Array with Same Element repeated multiple times in Arduino?
This code is working properly and we are able to print repeatedly the symbols but the problem with this code is :: the repeated the values are not getting stored to a new array. we tried with declaring a new array to store the repeated values but it is not working!!

Body:
An array is a collection of the same elements, but symbol and count are obviously different things. To group different things together, struct was invented in the earliest days of C

struct {char symbol;  byte count;} input[] = {
  {'a', 2}, {'X' ,3} ,{'!', 1}
};

const byte inputcount = sizeof(input)/sizeof(input[0]); // 3 in this test
char expanded[20]; // will get the result

void setup() {
   Serial.begin(9600);
   char* resultpos = expanded;
   for (auto& elem:input) {
      for (byte p = 0; p < elem.count; p++) {
         *resultpos++ = elem.symbol;
      }
   }
   *resultpos = 0; // to make it a printable char array
   Serial.println(expanded); // should give "aaXXX!"
}
void loop() {}

If you prefer, you can use the classic type of for loop as well. But this for each is really nice, IMO.


问:
Selenium: How to disable image loading with firefox and python?
I have read similar questions and one was supposed to be the answer, but when I tried it, it only gave a partial solution.
I refer to this question: Disable images in Selenium Python

My problem is that I tried the solution and some of the images do not appear, but images that arrive from:

```<code><img href="www.xxx.png">
</code>```

Are being loaded.
Is there a way to tell firefox/selenium not to get it?
If not, is there a way to discard it from the dom element that I get back, via:

```<code>self._browser.get(url)
content=self._browser.page_source
</code>```

for example by doing some kind of find replace on the dom tree?
The browser configuration is the same browser from the previous question:

```<code>    firefox_profile = webdriver.FirefoxProfile()
    # Disable CSS
    firefox_profile.set_preference('permissions.default.stylesheet', 2)
    # Disable images
    firefox_profile.set_preference('permissions.default.image', 2)
    # Disable Flash
    firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
    # Set the modified profile while creating the browser object
    self._browser = webdriver.Firefox(firefox_profile=firefox_profile)
</code>```

Update:

I kept on digging and what I learned is that if I inspect the text document that the selenium/firefox combo did I see that, it didn't bring the images and kept them as links.
But when I did:

```<code>self._browser.save_screenshot("info.png")
</code>```

I got a 24 mega file with all the img links loaded.

Can anyone explain to me this matter?

Thanks!

答: In the latest Firefox versions permissions.default.image can't be changed. To disable the images, either switch to ChromDriver or use alternative extentions as suggested here.

Body:
I have read similar questions and one was supposed to be the answer, but when I tried it, it only gave a partial solution.
I refer to this question: Disable images in Selenium Python

My problem is that I tried the solution and some of the images do not appear, but images that arrive from:

Are being loaded.
Is there a way to tell firefox/selenium not to get it?
If not, is there a way to discard it from the dom element that I get back, via:

self._browser.get(url)
content=self._browser.page_source

for example by doing some kind of find replace on the dom tree?
The browser configuration is the same browser from the previous question:

    firefox_profile = webdriver.FirefoxProfile()
    # Disable CSS
    firefox_profile.set_preference('permissions.default.stylesheet', 2)
    # Disable images
    firefox_profile.set_preference('permissions.default.image', 2)
    # Disable Flash
    firefox_profile.set_preference('dom.ipc.plugins.enabled.libflashplayer.so', 'false')
    # Set the modified profile while creating the browser object
    self._browser = webdriver.Firefox(firefox_profile=firefox_profile)

Update:

I kept on digging and what I learned is that if I inspect the text document that the selenium/firefox combo did I see that, it didn't bring the images and kept them as links.
But when I did:

self._browser.save_screenshot("info.png")

I got a 24 mega file with all the img links loaded.

Can anyone explain to me this matter?

Thanks!


问:
append guid to hyperlink using xslt
I have some xml being returned in sharepoint,
Im using xslt to create the hyperlink like so.

```<code><a href="{substring-before(Sign-up-Link,',')}">
    Sign up for event
</a>
</code>```

I also have an element <guid>1234</guid> being returned in the xml,
an I'd like it so that the link will be with the guid appended as a querystring

e.g. http://www.foo.com/signup.aspx?guid=1234

how do i append the guid?

thanks

答:
Depends where the guid appears in the xml but I would imagine concat() would do the trick e.g.</p>

```<code><a href="{concat(substring-before(Sign-up-Link,','),'?guid=',guid)}"/>
</code>```

OwnerDisplayName: raklos

ContentLicense: CC BY-SA 2.5

Title: append guid to hyperlink using xslt

Body:
I have some xml being returned in sharepoint,
Im using xslt to create the hyperlink like so.

    Sign up for event

I also have an element <guid>1234</guid> being returned in the xml,
an I'd like it so that the link will be with the guid appended as a querystring

e.g. http://www.foo.com/signup.aspx?guid=1234

how do i append the guid?

thanks

LastEditorDisplayName: raklos

Body:
Depends where the guid appears in the xml but I would imagine concat() would do the trick e.g.

<a href="{concat(substring-before(Sign-up-Link,','),'?guid=',guid)}"/>

OwnerDisplayName: Nick Allen - Tungle139


问:
random number generator without doing refresh
Hello
I want to create a web page which can continually sending random value to data base without doing refresh .

For example

```<code><html>
  <HEAD>
    <TITLE>HTML Title</TITLE>
  </HEAD>
  <BODY>

    <H3 ALIGN="CENTER">
      Ramdom number from 0 to 10 :
      <FONT COLOR="RED">
        <%= (int) (Math.random() * 10) %>
      </FONT>
    </H3>
    <H4 ALIGN="CENTER">Refresh the page to see if the number changes...</H4>
  </BODY>
</HTML>
</code>```

in which direction i should go either of using applets or something which can easily be adopted . Thanks

答:
I want to create a web page which can continually sending random value to data base without doing refresh .

I wonder why do you need view for this. You can do it using some scheduled job , explore Quartz

If still you want to do that.. go for DWR

ContentLicense: CC BY-SA 3.0

Body:
Hello
I want to create a web page which can continually sending random value to data base without doing refresh .

For example

    <TITLE>HTML Title</TITLE>

      Ramdom number from 0 to 10 :

        <%= (int) (Math.random() * 10) %>

Refresh the page to see if the number changes...

in which direction i should go either of using applets or something which can easily be adopted . Thanks


问:
how to get String from Observable<any> in Angular
I have a backend Rest service that returns a string:

```<code>@GetMapping("/role/{id}")
    public String trouverRole (@PathVariable("id") String username) {
    User u= userrepository.findByUsername(username);
    return u.getRoles().get(0).getName();

    }
</code>```

I'm trying to get the string and use it in angular .ts file:
My service code:

```<code>getrole(name: string): Observable<any> {

    return this.http.get('http://localhost:8080/api/role/'+name);

  }
</code>```

My .ts code:

```<code>login(){
    this.loginService.authentificate(this.credentials,()=>{

     this.loginService.getrole(this.credentials.username).subscribe(
      data => {
      this.role=JSON.stringify(data);
   });

      if ( this.role=="ROLE_ADMIN" )
          { this.router.navigateByUrl('/home/(contentOutlet:produit)');}

          else console.log(this.role);
          /*
      else
      { this.router.navigateByUrl('/home/(contentOutlet:dashboard)')}*/
    })

  }
</code>```

I'm getting this error:

"Unexpected token R in JSON at position 0"

答:
I solved the problem.
So I was  supposed to specify the return type  by adding:
 {responseType: 'text'}

My service after changes:

```<code>    getrole(name: string): Observable<any> {

        return this.http.get('http://localhost:8080/api/role/'+name,{responseType:
   'text'});

      }
</code>```

And no need to use JSON.stringify, writing this.role=data; is the correct thing to do

Body:
I have a backend Rest service that returns a string:

@GetMapping("/role/{id}")
    public String trouverRole (@PathVariable("id") String username) {
    User u= userrepository.findByUsername(username);
    return u.getRoles().get(0).getName();

    }

I'm trying to get the string and use it in angular .ts file:
My service code:

getrole(name: string): Observable<any> {

    return this.http.get('http://localhost:8080/api/role/'+name);

  }

My .ts code:

login(){
    this.loginService.authentificate(this.credentials,()=>{

     this.loginService.getrole(this.credentials.username).subscribe(
      data => {
      this.role=JSON.stringify(data);
   });

      if ( this.role=="ROLE_ADMIN" )
          { this.router.navigateByUrl('/home/(contentOutlet:produit)');}

          else console.log(this.role);
          /*
      else
      { this.router.navigateByUrl('/home/(contentOutlet:dashboard)')}*/
    })

  }

I'm getting this error:

"Unexpected token R in JSON at position 0"

Body:
I solved the problem.
So I was  supposed to specify the return type  by adding:
 {responseType: 'text'}

My service after changes:

    getrole(name: string): Observable<any> {

        return this.http.get('http://localhost:8080/api/role/'+name,{responseType:
   'text'});

      }

And no need to use JSON.stringify, writing this.role=data; is the correct thing to do


问:
python lmfit [nan] values
I am trying to use lmfit for a global fit problem (schild analysis). I have some shared parameters and some that are calculated based on these shared. At one point the function encounters log for a negative number and throws a [nan] list causing it to fail. How do I prevent that? Thank you. </p>

```<code>def g1(params,xdata,ydata):

    hillSlope = params['hillSlope'].value
    schildSlope = params['SchildSlope'].value
    top = params['top'].value
    bottom = params['bottom'].value
    pA2 = params['pA2'].value

    EC50_1 = params['ec50_2'].value
    B_1 = params['B_2'].value
    Antag_1 = 1+(B_1/(10**(-1*pA2)))**schildSlope
    LogEC_1=np.log10(EC50_1*Antag_1)
    y_model_1 = y_model_1 = bottom + (top-bottom)/(1+10**((LogEC_1-xdata)*hillSlope))
</code>```

答: You can set the nan_policy in the lmfit to 'omit'! More info here https://lmfit.github.io/lmfit-py/model.html</p>

Title: python lmfit [nan] values

Body:
I am trying to use lmfit for a global fit problem (schild analysis). I have some shared parameters and some that are calculated based on these shared. At one point the function encounters log for a negative number and throws a [nan] list causing it to fail. How do I prevent that? Thank you.

def g1(params,xdata,ydata):

    hillSlope = params['hillSlope'].value
    schildSlope = params['SchildSlope'].value
    top = params['top'].value
    bottom = params['bottom'].value
    pA2 = params['pA2'].value

    EC50_1 = params['ec50_2'].value
    B_1 = params['B_2'].value
    Antag_1 = 1+(B_1/(10**(-1*pA2)))**schildSlope
    LogEC_1=np.log10(EC50_1*Antag_1)
    y_model_1 = y_model_1 = bottom + (top-bottom)/(1+10**((LogEC_1-xdata)*hillSlope))


问:
Unity Project doesn't have solution file
I just started learning unity and I created a project. But my project doesn't have a sln file included in. Every time I create a C# script and open it in Xamarin Studio I can't have any intellisense.

Is it normal not to have sln file in unity project?

If not, how can I add solution file to project?

Why that happened?

答:
If "Open C# Project" doesnt create the .sln file, try updating your external tools first.

In Unity, go to Edit > Preferences, and make sure that Visual Studio is selected as your preferred external editor.

This created the sln file for me.


问:
all? method behavior with ampersand (&) and a block
I have a method to check if a coordinate is valid.

```<code>def valid_coordinate?(coordinate)
  valid_latitude?(coordinate['lat']) && valid_longitude?(coordinate['lng'])
end
</code>```

When I try to use it with all? for an array of hashes (An example hash is {"lat" => 63, "lng" => -24}), it works with a block but it does not work with an ampersand.

Working version:

coordinates.all? { |c| valid_coordinate?(c) }

Non-working version:

coordinates.all?(&:valid_coordinate?)

I get the following error:

NoMethodError: undefined method `valid_coordinate?' for {"lat"=>63, "lng"=>-24}:Hash

I also checked the documentation page for my Ruby version but could not find an explanation. As far as I know, an ampersand can be used with this method ([1,3,5].all?(&:odd?)).

答:
Adding to what Marek said

& is shorthand for to_proc
: is just a symbol notation (Read on ruby symbols)

Now, as per the definition of to_proc the symbol is called upon the object itself.

Which means, a proc object is created and that is called on the object which we would get inside the block.

Elaborating with example.

```<code>irb(main):009:0> [1,2,3].map(&:fn)
Traceback (most recent call last):
        5: from /Users/manu/.rbenv/versions/2.6.3/bin/irb:23:in `<main>'
        4: from /Users/manu/.rbenv/versions/2.6.3/bin/irb:23:in `load'
        3: from /Users/manu/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        2: from (irb):9
        1: from (irb):9:in `map'
NoMethodError (undefined method `fn' for 1:Integer)
</code>```

In the snippet above, Integer doesn't have fn method, hence it fails.
An integer has an odd? method though, let's try that.

```<code>irb(main):011:0> [1,2,3].map(&:odd?)
=> [true, false, true]
</code>```

In your case what is happening is that, you are trying to call your custom method on the hash object itself, which would obviously fail because hash does not have that method.

Hope this clears up.

As a side note, if you are wondering how to pass such custom methods, I wrote a bit about it here

Body:
I have a method to check if a coordinate is valid.

def valid_coordinate?(coordinate)
  valid_latitude?(coordinate['lat']) && valid_longitude?(coordinate['lng'])
end

When I try to use it with all? for an array of hashes (An example hash is {"lat" => 63, "lng" => -24}), it works with a block but it does not work with an ampersand.

Working version:

coordinates.all? { |c| valid_coordinate?(c) }

Non-working version:

coordinates.all?(&:valid_coordinate?)

I get the following error:

NoMethodError: undefined method `valid_coordinate?' for {"lat"=>63, "lng"=>-24}:Hash

I also checked the documentation page for my Ruby version but could not find an explanation. As far as I know, an ampersand can be used with this method ([1,3,5].all?(&:odd?)).

Body:
Adding to what Marek said

& is shorthand for to_proc
: is just a symbol notation (Read on ruby symbols)

Now, as per the definition of to_proc the symbol is called upon the object itself.

Which means, a proc object is created and that is called on the object which we would get inside the block.

Elaborating with example.

irb(main):009:0> [1,2,3].map(&:fn)
Traceback (most recent call last):
        5: from /Users/manu/.rbenv/versions/2.6.3/bin/irb:23:in `<main>'
        4: from /Users/manu/.rbenv/versions/2.6.3/bin/irb:23:in `load'
        3: from /Users/manu/.rbenv/versions/2.6.3/lib/ruby/gems/2.6.0/gems/irb-1.0.0/exe/irb:11:in `<top (required)>'
        2: from (irb):9
        1: from (irb):9:in `map'
NoMethodError (undefined method `fn' for 1:Integer)

In the snippet above, Integer doesn't have fn method, hence it fails.
An integer has an odd? method though, let's try that.

irb(main):011:0> [1,2,3].map(&:odd?)
=> [true, false, true]

In your case what is happening is that, you are trying to call your custom method on the hash object itself, which would obviously fail because hash does not have that method.

Hope this clears up.

As a side note, if you are wondering how to pass such custom methods, I wrote a bit about it here


问:
what is the replacement for gtk.gdk.get_default_root_window().get_pointer() which is now deprecated
I am using Python 3 and GTK 3, running Debian Buster. I need to find the mouse pointer location on the screen globally, not just within the application's own windows.

I used to use gtk.gdk.get_default_root_window().get_pointer() and it works, but this was marked as deprecated in an error message. I searched all over the place and found references in GTK 3 documentation to "devices" but got lost pretty fast. Experimenting, I was not able to find out how to do this. I might have succeeded if I had understood how to get a "device," - not a specific device, but just the "device" representing the mouse pointer as it appears on the screen. I do not care what device is putting the pointer there. For now, I did what I needed to do using XWindows calls, but this seems too specific to the OS and I would like to stick with GTK for this.

答:
Absolutely obvious:

GdkDisplay * gdk_display_get_default (void);
// then pass it to
GdkSeat * gdk_display_get_default_seat (GdkDisplay *display);
// then pass it to
GdkDevice * gdk_seat_get_pointer (GdkSeat *seat);
// and finally, pass it to
void gdk_device_get_position (GdkDevice *device, ... );
```

Honestly, IDK what I'm doing and GDK documentation doesn't have a single place to describe all those Screens, Displays, Monitors etc, but try this.

Body:
Absolutely obvious:

GdkDisplay * gdk_display_get_default (void);
// then pass it to
GdkSeat * gdk_display_get_default_seat (GdkDisplay *display);
// then pass it to
GdkDevice * gdk_seat_get_pointer (GdkSeat *seat);
// and finally, pass it to
void gdk_device_get_position (GdkDevice *device, ... );

Honestly, IDK what I'm doing and GDK documentation doesn't have a single place to describe all those Screens, Displays, Monitors etc, but try this.


问:
Oracle SQL time difference in HH:MM:SS
I am trying to get time difference in Oracle database. The time difference for all the rows is okay except for one row. Here is the query

```<code>SELECT MAX(REGEXP_SUBSTR (CAST(TO_DATE(call_end, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP) - CAST(TO_DATE(call_start, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP), '\d{2}:\d{2}:\d{2}')) AS call_time
FROM calls
</code>```

The time difference occurs with the following row:

call_end: '2020-02-20 13:00:20'

call_start: '2020-02-20 12:56:03'

The returned result is '11:55:43' which is wrong. As the correct answer should be '00:04:17'

答:
Assuming your data types are strings (you really should store them as DATE data types), you can use:

SELECT SUBSTR(
         MAX(
           ( TO_DATE( call_end,   'YYYY-MM-DD HH24:MI:SS' )
           - TO_DATE( call_start, 'YYYY-MM-DD HH24:MI:SS' )
           ) DAY(1) TO SECOND
         ),
         4,
         8
       ) AS call_time
FROM   calls
```

<p>If they are already <code>DATE</code> data types then, in the <code>MAX</code> aggregation, just use:</p>

<pre class="lang-sql prettyprint-override"><code>( call_end - call_start ) DAY(1) TO SECOND
</code>```

So for your data:

CREATE TABLE calls ( call_end, call_start ) AS
SELECT '2020-02-20 13:00:20', '2020-02-20 12:56:03' FROM DUAL
```

<p>This outputs:</p>

<blockquote>
```
| CALL_TIME |
| :-------- |
| 00:04:17  |
```

db<>fiddle here

Title: Oracle SQL time difference in HH:MM:SS

Body:
I am trying to get time difference in Oracle database. The time difference for all the rows is okay except for one row. Here is the query

SELECT MAX(REGEXP_SUBSTR (CAST(TO_DATE(call_end, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP) - CAST(TO_DATE(call_start, 'YYYY/MM/DD HH24:MI:SS') AS TIMESTAMP), '\d{2}:\d{2}:\d{2}')) AS call_time
FROM calls

The time difference occurs with the following row:

call_end: '2020-02-20 13:00:20'

call_start: '2020-02-20 12:56:03'

The returned result is '11:55:43' which is wrong. As the correct answer should be '00:04:17'

Body:
Assuming your data types are strings (you really should store them as DATE data types), you can use:

SELECT SUBSTR(
         MAX(
           ( TO_DATE( call_end,   'YYYY-MM-DD HH24:MI:SS' )
           - TO_DATE( call_start, 'YYYY-MM-DD HH24:MI:SS' )
           ) DAY(1) TO SECOND
         ),
         4,
         8
       ) AS call_time
FROM   calls

If they are already DATE data types then, in the MAX aggregation, just use:

( call_end - call_start ) DAY(1) TO SECOND

So for your data:

CREATE TABLE calls ( call_end, call_start ) AS
SELECT '2020-02-20 13:00:20', '2020-02-20 12:56:03' FROM DUAL

This outputs:

| CALL_TIME |
| :-------- |
| 00:04:17  |

db<>fiddle here


问:
How do I concatenate two lists inside nested list Python?
How do I concatenate two lists inside the nested list Python?

I have this list

```<code>lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
</code>```

And my expected output is

```<code>lists_of_lists =[[1,2],[3,5],[6,6]]
</code>```

I tried this way

```<code>new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)
</code>```

But I got

```<code>[1, 2, 3, 5, 6, 6]
</code>```

Thank you for any suggestions

答:
You are going completely to the low level. Just go one level less deep and flatten the list there.</p>

```<code>lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in lists_of_lists:
    flat_list = [item for sublist in i for item in sublist]
    new.append(flat_list)
print(new)
</code>```

Body:
How do I concatenate two lists inside the nested list Python?

I have this list

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]

And my expected output is

lists_of_lists =[[1,2],[3,5],[6,6]]

I tried this way

new = []
lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in range(len(lists_of_lists)):
    for list in  lists_of_lists[i]:
        for element in list:
            new.append(element)
print(new)

But I got

[1, 2, 3, 5, 6, 6]

Thank you for any suggestions

Body:
You are going completely to the low level. Just go one level less deep and flatten the list there.

lists_of_lists =[[[1],[2]],[[3],[5]],[[6],[6]]]
for i in lists_of_lists:
    flat_list = [item for sublist in i for item in sublist]
    new.append(flat_list)
print(new)


问:
difference in using sklearn.utils.resample with stratify and without stratify
What is difference in using sklearn.utils.resample with stratify and without stratify?

https://scikit-learn.org/stable/modules/generated/sklearn.utils.resample.html

```<code>import numpy
from sklearn.utils import resample

y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
res = resample(y, n_samples=5, replace=False, random_state=0)
print (res)
[1, 1, 0, 1, 1]

res = resample(y, n_samples=5, replace=False, stratify=y, random_state=0)
print (res)

[1, 1, 1, 0, 1]
</code>```

答:
Stratify means the distribution in your original classes is preserved.

See the frequencies in original distribution:

```<code>from sklearn.utils import resample
seed=42
np.random.seed(seed)
y = np.random.choice([0,1],size=100000, p=[.5,.5])
np.unique(y,return_counts=True)
(array([0, 1]), array([49934, 50066]))
</code>```

Then, the resample without stratify:

```<code>res = resample(y, n_samples=10000, replace=True, stratify=None, random_state=seed)
np.unique(res,return_counts=True)
(array([0, 1]), array([5049, 4951]))
</code>```

And finally with stratification:

```<code>res = resample(y, n_samples=10000, replace=True, stratify=y,random_state=seed)
np.unique(res,return_counts=True)
(array([0, 1]), array([4993, 5007]))
</code>```

Body:
What is difference in using sklearn.utils.resample with stratify and without stratify?

https://scikit-learn.org/stable/modules/generated/sklearn.utils.resample.html

import numpy
from sklearn.utils import resample

y = [0, 0, 1, 1, 1, 1, 1, 1, 1]
res = resample(y, n_samples=5, replace=False, random_state=0)
print (res)
[1, 1, 0, 1, 1]

res = resample(y, n_samples=5, replace=False, stratify=y, random_state=0)
print (res)

[1, 1, 1, 0, 1]

Body:
Stratify means the distribution in your original classes is preserved.

See the frequencies in original distribution:

from sklearn.utils import resample
seed=42
np.random.seed(seed)
y = np.random.choice([0,1],size=100000, p=[.5,.5])
np.unique(y,return_counts=True)
(array([0, 1]), array([49934, 50066]))

Then, the resample without stratify:

res = resample(y, n_samples=10000, replace=True, stratify=None, random_state=seed)
np.unique(res,return_counts=True)
(array([0, 1]), array([5049, 4951]))

And finally with stratification:

res = resample(y, n_samples=10000, replace=True, stratify=y,random_state=seed)
np.unique(res,return_counts=True)
(array([0, 1]), array([4993, 5007]))


答: If I understand your question correctly, I would personally probably use usort(). In my callback I would compare $a[15.00] and $b[15.00].

Title: Sort an array that has highest point?

Body:
How do I sort array that has highest point from 15.00 key?

I have an array look like this:

Array
(

    [9] => Array
        (
            [15.00] => 3.0
            [20.00] => 8.0
            [25.00] => 10.5
        )

    [2] => Array
        (
            [15.00] => 2.0
            [20.00] => 5.0
            [25.00] => 2.5
        )

    [4] => Array
        (
            [15.00] => 6.0
            [25.00] => 4.0
            [30.00] => 6.0
        )
)

In order it should be: 4, 9 and 2


问:
Strapi.io- How to throw alert message to contentmanager ui from beforeupdate/beforesave function in controller
Want to add a Validation Logic in Before Save / Before Create Values in Controller.

Want to throw the Error to the Admin Panel User. Hence they can correct the same value and resubmit the Form

BeforeSave : I am able to add the logic. But i dont know how to throw the Error Message as a Alert to the Content Manager panel . (This form has Errors)

Code snippets
Tried this ...but not working

errors.push({ id: 'content-manager.error.validation.json' });
strapi.notification.error('settings-manager.strapi.notification.error')

答:
In case you're still struggling with this: using model lifecycle callbacks, throwing an Error should suffice.

For example, in ./api/user/models/User.js, you can do this:

'use strict';

module.exports = {
  beforeSave: async (model, attrs, options) => {
    if (someValidationFails(model)) {
      throw new Error('Custom error message.');
    }
  },
};
```

Other than the error message showing up in green for some reason, this should work.

Body:
In case you're still struggling with this: using model lifecycle callbacks, throwing an Error should suffice.

For example, in ./api/user/models/User.js, you can do this:

'use strict';

module.exports = {
  beforeSave: async (model, attrs, options) => {
    if (someValidationFails(model)) {
      throw new Error('Custom error message.');
    }
  },
};

Other than the error message showing up in green for some reason, this should work.


问:
Multi-permission Firestore security rules
My website has multiple accounts with different permissions.

I use custom claims inside the Firestore token to give the right access to the user.

So far it has worked perfect with this setup:

The claims for User 1 with access to 1 location looks like this: {"companyLocation": "testLocation1"}

Soon I will have users who can access one or more locations. For example User 2 can access "testLocation2" & "testLocation3" without having access to "testLocation1".

User 2 claims can for example have a seperator (" ¤ ") and look something like this: {"companyLocation": "testLocation2 ¤ testLocation3"}

How would I achieve this with security rules? I tried:

```<code>function checkMultipleLocations(){
  return request.auth.token.companyLocation.contains('testLocation2');
}
</code>```

This gives me an error stating:

Invalid function name: contains

In the docs it states you can use in: v in x (Checks if value v is in list x), but this does not work for lists (does not return true), works only for objects/maps (tried by splitting the user claim string into array, without luck).

Any ideas?

答:
The in operator works on a list only. The value of this claim {"companyLocation": "testLocation2 ¤ testLocation3"} is not a list, but a string. So the in operator won't work here.

For a list of supported operators, see the documentation for the string type in security rules. This doesn't mention a contains method, but does have a matches method, which allows you to accomplish this use case.

```<code>request.auth.token.companyLocation.matches('.*testLocation2.*')
</code>```

You could also try to store the claim as an array:

```<code>{"companyLocation": ["testLocation2", "testLocation3"]}
</code>```

If setting a claim like this works, the in operator should work. I'm saying should here, because recently somebody was having trouble setting claims like this, and I haven't tested it myself.

Body:
My website has multiple accounts with different permissions.

I use custom claims inside the Firestore token to give the right access to the user.

So far it has worked perfect with this setup:

The claims for User 1 with access to 1 location looks like this: {"companyLocation": "testLocation1"}

Soon I will have users who can access one or more locations. For example User 2 can access "testLocation2" & "testLocation3" without having access to "testLocation1".

User 2 claims can for example have a seperator (" ¤ ") and look something like this: {"companyLocation": "testLocation2 ¤ testLocation3"}

How would I achieve this with security rules? I tried:

function checkMultipleLocations(){
  return request.auth.token.companyLocation.contains('testLocation2');
}

This gives me an error stating:

Invalid function name: contains

In the docs it states you can use in: v in x (Checks if value v is in list x), but this does not work for lists (does not return true), works only for objects/maps (tried by splitting the user claim string into array, without luck).

Any ideas?

Body:
The in operator works on a list only. The value of this claim {"companyLocation": "testLocation2 ¤ testLocation3"} is not a list, but a string. So the in operator won't work here.

For a list of supported operators, see the documentation for the string type in security rules. This doesn't mention a contains method, but does have a matches method, which allows you to accomplish this use case.

request.auth.token.companyLocation.matches('.*testLocation2.*')

You could also try to store the claim as an array:

{"companyLocation": ["testLocation2", "testLocation3"]}

If setting a claim like this works, the in operator should work. I'm saying should here, because recently somebody was having trouble setting claims like this, and I haven't tested it myself.


问:
How can I find all of the distinct file extensions in a folder hierarchy?
On a Linux machine I would like to traverse a folder hierarchy and get a list of all of the distinct file extensions within it.

What would be the best way to achieve this from a shell?

答:
I've found it simple and fast...</p>

```<code>   # find . -type f -exec basename {} \; | awk -F"." '{print $NF}' > /tmp/outfile.txt
   # cat /tmp/outfile.txt | sort | uniq -c| sort -n > tmp/outfile_sorted.txt
</code>```

Body:
I've found it simple and fast...

   # find . -type f -exec basename {} \; | awk -F"." '{print $NF}' > /tmp/outfile.txt
   # cat /tmp/outfile.txt | sort | uniq -c| sort -n > tmp/outfile_sorted.txt


问:
How to delete specific columns(not entirely) in excel vba
I am trying to delete columns when column T,U,V has 0 value at the same row. However, the code that i am using only deletes some of them and as shown below, there are still 0s at column T,U,V for some rows even though I already specify them to be deleted at specific cells that i have assigned. Which part of my code have i done wrong?

```<code>Dim j As Long

Dim lr As Long
lr = Sheets(1).Cells(Rows.Count, "U").End(xlUp).Row

For j = 1 To lr

   If Sheets(1).Cells(j, 21).Value = 0 And Sheets(1).Cells(j, 22).Value = 0 And Sheets(1).Cells(j, 23).Value = 0 Then
   Sheets(1).Range("T" & j & ":W" & j).Delete
      j = j + 1
      End If
      Next
</code>```

After applying my code, there are still left overs rows with zeros.

so eventually i want it to be

答:
You can union all ranges in a single range and then delete all at once:

```<code>Sub CLEAR_ZERO_ROWS()

Dim BigRange As Range
Dim MyArray As Variant
Dim i As Long

With ThisWorkbook.Sheets(1)
    MyArray = .Range("B2:D" & .Range("A" & .Rows.Count).End(xlUp).Row).Value 'values into array

    For i = 1 To UBound(MyArray) Step 1
        If MyArray(i, 1) + MyArray(i, 2) + MyArray(i, 3) = 0 Then
            If BigRange Is Nothing Then
                Set BigRange = .Range("A" & i + 1 & ":D" & i + 1)
            Else
                Set BigRange = Union(BigRange, .Range("A" & i + 1 & ":D" & i + 1))
            End If
        End If
    Next i

End With

'we delete all at once is bigrange is not nothing

If Not BigRange Is Nothing Then BigRange.Delete xlUp

Erase MyArray
Set BigRange = Nothing

End Sub
</code>```

By the way, the code is adapted to a fake dataset I did on columns A:D, so you need to adapt that part. Before executing code I had:

After code I got:

Note that in both cases, the consecutive numbers in column F have not been deleted. The code just deletes the 4 cells of data and shifts up.

Body:
I am trying to delete columns when column T,U,V has 0 value at the same row. However, the code that i am using only deletes some of them and as shown below, there are still 0s at column T,U,V for some rows even though I already specify them to be deleted at specific cells that i have assigned. Which part of my code have i done wrong?

Dim j As Long

Dim lr As Long
lr = Sheets(1).Cells(Rows.Count, "U").End(xlUp).Row

For j = 1 To lr

   If Sheets(1).Cells(j, 21).Value = 0 And Sheets(1).Cells(j, 22).Value = 0 And Sheets(1).Cells(j, 23).Value = 0 Then
   Sheets(1).Range("T" & j & ":W" & j).Delete
      j = j + 1
      End If
      Next

After applying my code, there are still left overs rows with zeros.

so eventually i want it to be

Body:
You can union all ranges in a single range and then delete all at once:

Sub CLEAR_ZERO_ROWS()

Dim BigRange As Range
Dim MyArray As Variant
Dim i As Long

With ThisWorkbook.Sheets(1)
    MyArray = .Range("B2:D" & .Range("A" & .Rows.Count).End(xlUp).Row).Value 'values into array

    For i = 1 To UBound(MyArray) Step 1
        If MyArray(i, 1) + MyArray(i, 2) + MyArray(i, 3) = 0 Then
            If BigRange Is Nothing Then
                Set BigRange = .Range("A" & i + 1 & ":D" & i + 1)
            Else
                Set BigRange = Union(BigRange, .Range("A" & i + 1 & ":D" & i + 1))
            End If
        End If
    Next i

End With

'we delete all at once is bigrange is not nothing

If Not BigRange Is Nothing Then BigRange.Delete xlUp

Erase MyArray
Set BigRange = Nothing

End Sub

By the way, the code is adapted to a fake dataset I did on columns A:D, so you need to adapt that part. Before executing code I had:

After code I got:

Note that in both cases, the consecutive numbers in column F have not been deleted. The code just deletes the 4 cells of data and shifts up.


答:
The stratify option makes it so that the distribution of classes present in the full data will be kept in the sample. The fact that it didn't seem to matter in your example (as the same amount of 1s and 0s was getting returned) was simply a matter of coincidence. You can see that that is not always the case, by changing the random_state and noticing that the ratio of 1s to 0s doesn't always stay the same for non-stratified samples, whereas for the stratified ones it always follows that of your input data (4/5 are 1s):</p>

```<code>In [1]: import numpy
   ...: from sklearn.utils import resample

In [2]: y = [0, 0, 1, 1, 1, 1, 1, 1, 1]

In [3]: resample(y, n_samples=5, replace=False, random_state=10)
Out[3]: [1, 1, 1, 1, 1]

In [4]: resample(y, n_samples=5, replace=False, stratify=y, random_state=10)
Out[4]: [1, 1, 1, 1, 0]

In [5]: resample(y, n_samples=5, replace=False, random_state=42)
Out[5]: [1, 0, 1, 0, 1]

In [6]: resample(y, n_samples=5, replace=False, stratify=y, random_state=42)
Out[6]: [1, 0, 1, 1, 1]

In [7]: resample(y, n_samples=5, replace=False, random_state=0)
Out[7]: [1, 1, 0, 1, 1]

In [8]: resample(y, n_samples=5, replace=False, stratify=y, random_state=0)
Out[8]: [1, 1, 1, 0, 1]

</code>```

Title: difference in using sklearn.utils.resample with stratify and without stratify

Body:
The stratify option makes it so that the distribution of classes present in the full data will be kept in the sample. The fact that it didn't seem to matter in your example (as the same amount of 1s and 0s was getting returned) was simply a matter of coincidence. You can see that that is not always the case, by changing the random_state and noticing that the ratio of 1s to 0s doesn't always stay the same for non-stratified samples, whereas for the stratified ones it always follows that of your input data (4/5 are 1s):

In [1]: import numpy
   ...: from sklearn.utils import resample

In [2]: y = [0, 0, 1, 1, 1, 1, 1, 1, 1]

In [3]: resample(y, n_samples=5, replace=False, random_state=10)
Out[3]: [1, 1, 1, 1, 1]

In [4]: resample(y, n_samples=5, replace=False, stratify=y, random_state=10)
Out[4]: [1, 1, 1, 1, 0]

In [5]: resample(y, n_samples=5, replace=False, random_state=42)
Out[5]: [1, 0, 1, 0, 1]

In [6]: resample(y, n_samples=5, replace=False, stratify=y, random_state=42)
Out[6]: [1, 0, 1, 1, 1]

In [7]: resample(y, n_samples=5, replace=False, random_state=0)
Out[7]: [1, 1, 0, 1, 1]

In [8]: resample(y, n_samples=5, replace=False, stratify=y, random_state=0)
Out[8]: [1, 1, 1, 0, 1]


问:
How to publish custom object to DLQ queue using camel OnException
I have something like below:

```<code>    onException(Exception.class)
        .maximumRedeliveries(2).redeliveryDelay(1000L).asyncDelayedRedelivery()
        .log(LoggingLevel.ERROR, LOGGER, "Body before process ->> \"${body}\" for the cause of ->  \"${exception.message}\"")
        .process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                JSONObject obj = new JSONObject();
                obj.put("body", exchange.getIn().getBody());
                obj.put("errMsg", "testErrorMsg");
                exchange.getIn().setBody(obj);
            }
        })
        .log(LoggingLevel.ERROR, LOGGER, "Body after process ->> \"${body}\" for the cause of ->  \"${exception.message}\"")
        .setExchangePattern(ExchangePattern.InOnly).setFaultBody(constant(true))
        .setHeader(RabbitMQConstants.REQUEUE, constant(Boolean.FALSE)).handled(false);
</code>```

Original message:

```<code>{"key" : "123" }
</code>```

and I am expecting custom message as below while sending to DLQ:

```<code>{
  "body": {
    "key": "123"
  },
  "errMsg": "testErrorMsg"
}
</code>```

In logs, I can see body is converted as per my expectation but in DLQ queue it showing the original message.

It is possible to modify message before sending to DLQ?

答:
Welcome to StackOverflow!
You may use Deal Letter Channel EIP, with its onPrepareFailure to add a custom Processor, to modify the Exchange before delivering it to the DLQ.

Body:
I have something like below:

    onException(Exception.class)
        .maximumRedeliveries(2).redeliveryDelay(1000L).asyncDelayedRedelivery()
        .log(LoggingLevel.ERROR, LOGGER, "Body before process ->> \"${body}\" for the cause of ->  \"${exception.message}\"")
        .process(new Processor() {
            @Override
            public void process(Exchange exchange) throws Exception {
                JSONObject obj = new JSONObject();
                obj.put("body", exchange.getIn().getBody());
                obj.put("errMsg", "testErrorMsg");
                exchange.getIn().setBody(obj);
            }
        })
        .log(LoggingLevel.ERROR, LOGGER, "Body after process ->> \"${body}\" for the cause of ->  \"${exception.message}\"")
        .setExchangePattern(ExchangePattern.InOnly).setFaultBody(constant(true))
        .setHeader(RabbitMQConstants.REQUEUE, constant(Boolean.FALSE)).handled(false);

Original message:

{"key" : "123" }

and I am expecting custom message as below while sending to DLQ:

{
  "body": {
    "key": "123"
  },
  "errMsg": "testErrorMsg"
}

In logs, I can see body is converted as per my expectation but in DLQ queue it showing the original message.

It is possible to modify message before sending to DLQ?


问:
Can't understand exactly the pointers in 2d array
I have done something by looking to the internet but something is missing here is my code

```<code>void draw_way(int *arr,int lenght_row,int lenght_column) {
int s1 = 0, s2 = 0;
for (s1 = 0; s1 < lenght_row; s1++)
{
    for (s2 = 0; s2 < lenght_column; s2++) {
        if (*((arr + s1 * lenght_row) + s2) == 1)
        {
            printf("S");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 2)
        {
            printf("G");
        }
        else if(*((arr + s1 * lenght_row) + s2) == 3)
        {
            printf("#");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 4)
        {
            printf(".");
        }
    }
    printf("\n");
}
</code>```

it is actually printing a maze but is is not important. The thing I want to understand is why ı had to use *((arr + s1 * lenght_row) + s2) why this is not working if ı use *(*(arr+s1)+s2) what 'lenght_row' does.

答:
For starters the expression in if-else statements like this

```<code>if (*((arr + s1 * lenght_row) + s2) == 1)
</code>```

is incorrect. There should be

```<code>if (*((arr + s1 * lenght_column) + s2) == 1)
</code>```

The parameter arr declared like

```<code>int *arr
</code>```

has the type int *. So dereferencing the pointer like *arr you will get an object of the type int for which you may not apply the dereferncing operator.

So this expression

```<code>*(*(arr+s1)+s2)
</code>```

is incorrect. The sub-expression *(arr+s1) has the type int. So the second use of the operator * produce a compilation error.

In the shown function there is emulated a two dimensional array using a pointer to a one-dimensional array. That is the one-dimensional array is logically split into  chunks by length_column elements.

Here is a demonstrative program.

```<code>#include <stdio.h>

#define ROW_LENGTH      2
#define COLUMN_LENGTH   3

void display( const int *arr, size_t row_length, size_t column_length )
{
    for ( size_t i = 0; i < row_length; i++ )
    {
        for ( size_t j = 0; j < column_length; j++ )
        {
            printf( "%d ", *( arr + i * column_length + j ) );
        }
        putchar( '\n' );
    }
}

int main(void)
{
    int arr[ROW_LENGTH * COLUMN_LENGTH] = { 1, 2, 3, 4, 5, 6 };

    display( arr, ROW_LENGTH, COLUMN_LENGTH );

    return 0;
}
</code>```

Its output is

```<code>1 2 3
4 5 6
</code>```

Body:
I have done something by looking to the internet but something is missing here is my code

void draw_way(int *arr,int lenght_row,int lenght_column) {
int s1 = 0, s2 = 0;
for (s1 = 0; s1 < lenght_row; s1++)
{
    for (s2 = 0; s2 < lenght_column; s2++) {
        if (*((arr + s1 * lenght_row) + s2) == 1)
        {
            printf("S");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 2)
        {
            printf("G");
        }
        else if(*((arr + s1 * lenght_row) + s2) == 3)
        {
            printf("#");
        }
        else if (*((arr + s1 * lenght_row) + s2) == 4)
        {
            printf(".");
        }
    }
    printf("\n");
}

it is actually printing a maze but is is not important. The thing I want to understand is why ı had to use *((arr + s1 * lenght_row) + s2) why this is not working if ı use *(*(arr+s1)+s2) what 'lenght_row' does.

Body:
For starters the expression in if-else statements like this

if (*((arr + s1 * lenght_row) + s2) == 1)

is incorrect. There should be

if (*((arr + s1 * lenght_column) + s2) == 1)

The parameter arr declared like

int *arr

has the type int *. So dereferencing the pointer like *arr you will get an object of the type int for which you may not apply the dereferncing operator.

So this expression

*(*(arr+s1)+s2)

is incorrect. The sub-expression *(arr+s1) has the type int. So the second use of the operator * produce a compilation error.

In the shown function there is emulated a two dimensional array using a pointer to a one-dimensional array. That is the one-dimensional array is logically split into  chunks by length_column elements.

Here is a demonstrative program.

#include <stdio.h>

#define ROW_LENGTH      2
#define COLUMN_LENGTH   3

void display( const int *arr, size_t row_length, size_t column_length )
{
    for ( size_t i = 0; i < row_length; i++ )
    {
        for ( size_t j = 0; j < column_length; j++ )
        {
            printf( "%d ", *( arr + i * column_length + j ) );
        }
        putchar( '\n' );
    }
}

int main(void)
{
    int arr[ROW_LENGTH * COLUMN_LENGTH] = { 1, 2, 3, 4, 5, 6 };

    display( arr, ROW_LENGTH, COLUMN_LENGTH );

    return 0;
}

Its output is

1 2 3
4 5 6


问:
How to sort this 3D data in python?
I have the following data:

Groups

inside every group there are widths

and every width has a meter

for example:

```<code> Group 1:
|Width|Meters|
--------------
|144  |500   |
--------------
|142  | 450  |

Group 2:
|Width|Meters|
--------------
|140  |500   |
--------------
|156  | 450  |
</code>```

Now i need to create a sorting algorithm which will first pick the Group with greater sum of meters and then sort the width in descending
I am clueless how to store this data ? should it be a dictionary or a 3d array ? or three lists ?
and with the right data structure how can i actually sort it. I am not asking for the full code even if you guide me towards the right path i will find my way .Thanks

答:
Using numpy:

```<code>#                 Width Meters
data = np.array([[[144, 500],    # Group 1
                  [142, 450]],

                 [[140, 500],    # Group 2
                  [156, 460]]])

# Pick the group with the largest sum of Meters
group_index = np.argmax(data.sum(1)[:,1])
print(f'Group with the largest sum of Meters: Group {group_index + 1}')

result = data[group_index]

# sort by Width in descending order
result = result[np.argsort(result[:,0])[::-1]]
</code>```

Result:

```<code>array([[156, 460],
       [140, 500]])
</code>```

EDIT:

```<code>data = np.array([[[144, 500],
                  [142, 450],
                  [150, 300]],

                 [[140, 500],
                  [156, 460],
                  [145, 300]],

                 [[170, 500],
                  [180, 455],
                  [160, 300]]])

# Sort Groups by the sum of Meters
group_inds = np.argsort(data.sum(1)[:, 1])[::-1]
result = data[group_inds]

# Sort by Width in each group
result = result[np.arange(data.shape[0])[:, None],
                np.argsort(result[..., 0], axis=1)[:,::-1]]
</code>```

Result:

```<code>array([[[156, 460],
        [145, 300],
        [140, 500]],

       [[180, 455],
        [170, 500],
        [160, 300]],

       [[150, 300],
        [144, 500],
        [142, 450]]])
</code>```

Title: How to sort this 3D data in python?

Body:
I have the following data:

Groups

inside every group there are widths

and every width has a meter

for example:

 Group 1:
|Width|Meters|
--------------
|144  |500   |
--------------
|142  | 450  |

Group 2:
|Width|Meters|
--------------
|140  |500   |
--------------
|156  | 450  |

Now i need to create a sorting algorithm which will first pick the Group with greater sum of meters and then sort the width in descending
I am clueless how to store this data ? should it be a dictionary or a 3d array ? or three lists ?
and with the right data structure how can i actually sort it. I am not asking for the full code even if you guide me towards the right path i will find my way .Thanks

Body:
Using numpy:

#                 Width Meters
data = np.array([[[144, 500],    # Group 1
                  [142, 450]],

                 [[140, 500],    # Group 2
                  [156, 460]]])

# Pick the group with the largest sum of Meters
group_index = np.argmax(data.sum(1)[:,1])
print(f'Group with the largest sum of Meters: Group {group_index + 1}')

result = data[group_index]

# sort by Width in descending order
result = result[np.argsort(result[:,0])[::-1]]

Result:

array([[156, 460],
       [140, 500]])

EDIT:

data = np.array([[[144, 500],
                  [142, 450],
                  [150, 300]],

                 [[140, 500],
                  [156, 460],
                  [145, 300]],

                 [[170, 500],
                  [180, 455],
                  [160, 300]]])

# Sort Groups by the sum of Meters
group_inds = np.argsort(data.sum(1)[:, 1])[::-1]
result = data[group_inds]

# Sort by Width in each group
result = result[np.arange(data.shape[0])[:, None],
                np.argsort(result[..., 0], axis=1)[:,::-1]]

Result:

array([[[156, 460],
        [145, 300],
        [140, 500]],

       [[180, 455],
        [170, 500],
        [160, 300]],

       [[150, 300],
        [144, 500],
        [142, 450]]])


问:
How to draw a checkmark / tick using CSS?
How to draw the tick symbol using CSS? The symbols I find using Unicode isn't aesthetically-pleasing.

EDIT
Icon fonts are a great suggestion. I was looking for something like this.

答:
only css, quite simple I find it:

.checkmark {
      display: inline-block;
      transform: rotate(45deg);
      height: 25px;
      width: 12px;
      margin-left: 60%;
      border-bottom: 7px solid #78b13f;
      border-right: 7px solid #78b13f;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="checkmark"></div></code>```

Body:
only css, quite simple I find it:

.checkmark {
      display: inline-block;
      transform: rotate(45deg);
      height: 25px;
      width: 12px;
      margin-left: 60%;
      border-bottom: 7px solid #78b13f;
      border-right: 7px solid #78b13f;
    }

<div class="checkmark"></div>


问:
How to create a column for each level of another column in R?
The goal I am trying to achieve is an expanded data frame in which I will have created a new column for each level of a specific column in R. Here is a sample of the initial data frame and the data frame I am trying to achieve:

Original Data Frame:

```<code>record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5
</code>```

Goal Data Frame:

```<code>crop_land.BiocapPerCap     crop_land.Consumption     fishing_ground.BiocapPerCap      fishing_ground.Consumption
1.5                        2.3                       3.4                              0.5
</code>```

答:
We can use pivot_wider from the tidyr package as follows.

```<code>library(tidyr)
library(magrittr)

dat2 <- dat %>%
  pivot_wider(names_from = "record", values_from = c("crop_land", "fishing_ground"),
              names_sep = ".")
dat2
# # A tibble: 1 x 4
#   crop_land.BiocapPerCap crop_land.Consumption fishing_ground.BiocapPer~ fishing_ground.Consumpti~
#                    <dbl>                 <dbl>                     <dbl>                     <dbl>
# 1                    1.5                   2.3                       3.4                       0.5
</code>```

DATA

```<code>dat <- read.table(text = "record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5",
                  header = TRUE, stringsAsFactors = FALSE)
</code>```

Body:
The goal I am trying to achieve is an expanded data frame in which I will have created a new column for each level of a specific column in R. Here is a sample of the initial data frame and the data frame I am trying to achieve:

Original Data Frame:

record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5

Goal Data Frame:

crop_land.BiocapPerCap     crop_land.Consumption     fishing_ground.BiocapPerCap      fishing_ground.Consumption
1.5                        2.3                       3.4                              0.5

Body:
We can use pivot_wider from the tidyr package as follows.

library(tidyr)
library(magrittr)

dat2 <- dat %>%
  pivot_wider(names_from = "record", values_from = c("crop_land", "fishing_ground"),
              names_sep = ".")
dat2
# # A tibble: 1 x 4
#   crop_land.BiocapPerCap crop_land.Consumption fishing_ground.BiocapPer~ fishing_ground.Consumpti~
#                    <dbl>                 <dbl>                     <dbl>                     <dbl>
# 1                    1.5                   2.3                       3.4                       0.5

DATA

dat <- read.table(text = "record           crop_land     fishing_ground
BiocapPerCap     1.5           3.4
Consumption      2.3           0.5",
                  header = TRUE, stringsAsFactors = FALSE)


问:
How do I generate ctags for CoffeeScript?
Is it possible to generate a ctags file for CoffeeScript in vim/MacVim?</p>

答:
There is no native support for Exuberant ctags, but if you just want to gather some variable and function definitions, you can create your own rules.

Here is an example that appeared in a google search.


问:
CORS header ‘Access-Control-Allow-Origin’ missing for json POST using API
Installed fruitcake/laravel-cors on Laravel 5.8

My testserver uses php artisan serve on 127.0.0.1:8000 using routes/api.php
client (nuxt) is running on 127.0.0.1:3000

I'm able to send data to the server using the POSTMAN tool

I've configured fruitcake/laravel-cors

```<code>protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];
</code>```

and config/cors.php

```<code><?php

return [

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => [],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];
</code>```

Still getting:

Access to XMLHttpRequest at
  'http://127.0.0.1:8000/api/customerFeedbackStore' from origin
  'http://127.0.0.1:3000' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

in browser.

答:
It seems Cors was configured correctly but var_dump() and dd() before the return triggered the message anyway. Also not returning anything causes the cors message..

```<code>        var_dump($request);
        dd($request);
</code>```

return with a json response (as I'm using Json) worked fine.  (any other return suggestions?)

```<code>        return response()->json([
            'data-received' => true
        ]);
</code>```

Body:
Installed fruitcake/laravel-cors on Laravel 5.8

My testserver uses php artisan serve on 127.0.0.1:8000 using routes/api.php
client (nuxt) is running on 127.0.0.1:3000

I'm able to send data to the server using the POSTMAN tool

I've configured fruitcake/laravel-cors

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

and config/cors.php

<?php

return [

    /*
     * You can enable CORS for 1 or multiple paths.
     * Example: ['api/*']
     */
    'paths' => [],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,
];

Still getting:

Access to XMLHttpRequest at
  'http://127.0.0.1:8000/api/customerFeedbackStore' from origin
  'http://127.0.0.1:3000' has been blocked by CORS policy: No
  'Access-Control-Allow-Origin' header is present on the requested
  resource.

in browser.

Body:
It seems Cors was configured correctly but var_dump() and dd() before the return triggered the message anyway. Also not returning anything causes the cors message..

        var_dump($request);
        dd($request);

return with a json response (as I'm using Json) worked fine.  (any other return suggestions?)

        return response()->json([
            'data-received' => true
        ]);


问:
How can I get JQuery to replace the non URL parts of the string when fetching the background images url
I have this code which extracts the element for the background image, however it pulls in the " url' " parts of the code too. I just need the actual image address

I have tried to use the replace function but it doesn't do anything to the string when i check the output.

```<code>var jsonData =
{ "image": jQuery('#block-content').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(jsonData);
jQuery("head").append(script);
</code>```

The image inside the element is //imageaddress.jpg so it's extracting it as

```<code>https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)
</code>```

How can i fix this so that it just gives me

```<code>https://example.com/sites/image.jpg?itok=jfzYQHZx
</code>```

答:
Replace image property with this</p>

```<code> "image": jQuery('#block-content').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""),
</code>```

Body:
I have this code which extracts the element for the background image, however it pulls in the " url' " parts of the code too. I just need the actual image address

I have tried to use the replace function but it doesn't do anything to the string when i check the output.

var jsonData =
{ "image": jQuery('#block-content').css('background-image').replace(/^url\(['"](.+)['"]\)/, '$1'),
var script = document.createElement('script');
script.type = 'application/ld+json';
script.text = JSON.stringify(jsonData);
jQuery("head").append(script);

The image inside the element is //imageaddress.jpg so it's extracting it as

https://example.com/recipes/url(https://example.com/sites/image.jpg?itok=jfzYQHZx)

How can i fix this so that it just gives me

https://example.com/sites/image.jpg?itok=jfzYQHZx

Body:
Replace image property with this

 "image": jQuery('#block-content').css('background-image').replace('url(','').replace(')','').replace(/\"/gi, ""),


问:
How to unlock a file from someone else in Team Foundation Server
We have a project that is stored within our TFS server and some files were Checked-Out by me from another computer and another user (both of which are not used anymore). Is there a way to force the unlocking of the file (no changes were made to it so it's safe to do so if I can only do it).</p>

答:
In my case, I tried unlocking the file with tf lock but was told I couldn't because the stale workspace on an old computer that no longer existed was a local workspace. I then tried deleting the workspace with tf workspace /delete, but deleting the workspace did not remove the lock (and then I couldn't try to unlock it again because I just got an error saying the workspace no longer existed).

I ended up tf destroying the file and checking it in again, which was pretty silly and had the undesirable effect of removing\ it from previous changesets, but at least got us working again. It wasn't that big a deal in this case since the file had never been changed since being checked in.


问:
continuous log file processing and extract required data using python
I have to analyze a log file which will generate continuously 24*7. So, the data will be huge. I will have credentials to where log file is generating. But how can I get that streaming data ( I mean like any free tools or processes) so that I can use it in my python code to extract some required information from that log stream and will have to prepare a real time dashboard with that data. please tell some possibilities to achieve above task.</p>

答:
Just a suggestion

You could try with ELK:

ELK, short for Elasticsearch (ES), Logstash, and Kibana, is the most popular open source log aggregation tool. Es is a NoSQL. Logstash is a log pipeline system that can ingest data, transform it, and load it into a store like Elasticsearch. Kibana is a visualization layer on top of Elasticsearch.

or

you could use Mongo DB to handle such huge amount of data:

MongoDB is an open-source document database and leading NoSQL. Mongo DB stores data in a json format. Process the logs and store it in a json format and retrieve it for any further use.

Basically its not a simple question to explain, it depends on the scenarios.


问:
OpenGL: How to implement an "eraser" tool?
I'm working on a game for the iPhone that has a drawing/paint mechanic involved and I'm having problems trying to create a tool that would erase things already painted.

The main problem is that the background being painted on is not a solid color but a static image or animation. I've tried using different blending options and logical operations in drawing but nothing seemed to work. I'm new to OpenGL so I must be missing something.

Any tips?

EDIT: To give a little more information, I'm using textures for my brushes and using glVertexPointer() and glDrawArrays() to render them. For example:

```<code>glBindTexture(GL_TEXTURE_2D, circleBrush);
glVertexPointer(3, GL_FLOAT, 0, verts);
glTexCoordPointer(2, GL_FLOAT, 0, coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);
</code>```

EDIT 2: Unfortunately, stencil buffers are not available on the iPhone. : (

EDIT 3: Framebuffer objects are available on the iPhone and that is the road I took. I haven't fully implemented it yet, but so far it looks like it works the way I wanted it to. Thanks everyone!

答:
Stencil Buffer is the best way to approach this for sure...You'll save time, cpu, and potential problems..,They are available on Iphone, you just have to created an OpenGlES 2.0 surface (not gles 1.0 or 1.1).

```<code>        //Turn off writing to the Color Buffer and Depth Buffer
        //We want to draw to the Stencil Buffer only
        glColorMask(false, false, false, false);
        glDepthMask(false);

        //Enable the Stencil Buffer
        glEnable(GL_STENCIL_TEST);

        //Set 1 into the stencil buffer
        glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

        //CALL YOUR DRAWING METHOD HERE

        //Turn on Color Buffer and Depth Buffer
        glColorMask(true, true, true, true);
        glDepthMask(true);

        //Only write to the Stencil Buffer where 1 is set
        glStencilFunc(GL_EQUAL, 1, 0xFFFFFFFF);
        //Keep the content of the Stencil Buffer
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

        //CALL OUR DRAWING METHOD AGAIN
</code>```

Lookup this example :
http://www.opengl.org/resources/code/samples/glut_examples/examples/stenciltst.c

Here's the visual result :
http://www.opengl.org/resources/code/samples/glut_examples/examples/stenciltst.jpg

I've implented the same kind of eraser tool with this, on both android and iPhone and it works like a charm !

Good luck !

Cheers !

Body:
I'm working on a game for the iPhone that has a drawing/paint mechanic involved and I'm having problems trying to create a tool that would erase things already painted.

The main problem is that the background being painted on is not a solid color but a static image or animation. I've tried using different blending options and logical operations in drawing but nothing seemed to work. I'm new to OpenGL so I must be missing something.

Any tips?

EDIT: To give a little more information, I'm using textures for my brushes and using glVertexPointer() and glDrawArrays() to render them. For example:

glBindTexture(GL_TEXTURE_2D, circleBrush);
glVertexPointer(3, GL_FLOAT, 0, verts);
glTexCoordPointer(2, GL_FLOAT, 0, coords);
glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

EDIT 2: Unfortunately, stencil buffers are not available on the iPhone. : (

EDIT 3: Framebuffer objects are available on the iPhone and that is the road I took. I haven't fully implemented it yet, but so far it looks like it works the way I wanted it to. Thanks everyone!

LastEditorDisplayName: Rijnd

Body:
Stencil Buffer is the best way to approach this for sure...You'll save time, cpu, and potential problems..,They are available on Iphone, you just have to created an OpenGlES 2.0 surface (not gles 1.0 or 1.1).

        //Turn off writing to the Color Buffer and Depth Buffer
        //We want to draw to the Stencil Buffer only
        glColorMask(false, false, false, false);
        glDepthMask(false);

        //Enable the Stencil Buffer
        glEnable(GL_STENCIL_TEST);

        //Set 1 into the stencil buffer
        glStencilFunc(GL_ALWAYS, 1, 0xFFFFFFFF);
        glStencilOp(GL_REPLACE, GL_REPLACE, GL_REPLACE);

        //CALL YOUR DRAWING METHOD HERE

        //Turn on Color Buffer and Depth Buffer
        glColorMask(true, true, true, true);
        glDepthMask(true);

        //Only write to the Stencil Buffer where 1 is set
        glStencilFunc(GL_EQUAL, 1, 0xFFFFFFFF);
        //Keep the content of the Stencil Buffer
        glStencilOp(GL_KEEP, GL_KEEP, GL_KEEP);

        //CALL OUR DRAWING METHOD AGAIN

Lookup this example :
http://www.opengl.org/resources/code/samples/glut_examples/examples/stenciltst.c

Here's the visual result :
http://www.opengl.org/resources/code/samples/glut_examples/examples/stenciltst.jpg

I've implented the same kind of eraser tool with this, on both android and iPhone and it works like a charm !

Good luck !

Cheers !


问:
Remove gap between widget
I want to close the gap between the lists but its just not working. the only option i have is to increase the gap : Sizedbox,spacer,divider

screenshot of my problem

code:

body: Container(
        child: Column(
          children: <Widget>[
            _mainList(Icon(Icons.cached), "Erste", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Zweite", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Dritte", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Vierte", "21:13 pm"),
          ]
        )
  )```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>  Widget _mainList(Icon symbol, String name, String time){
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: ListTile(
        leading: symbol,
        title: Text(name, textScaleFactor: 1.2),
        trailing: Text(time, textScaleFactor: 1.3),
      ),
    );
  }</code>```

答:
```<code>class MyWidget extends StatelessWidget {
  final List<String> _names = ["Erste","Zweite","Dritte","Vierte"];
  final List<String> _dates = ["21:13 pm","21:13 pm","21:13 pm","21:13 pm"];
  @override
  Widget build(BuildContext context) {
    return Container(
        child: ListView.builder(
          shrinkWrap: true,
          itemBuilder: (BuildContext context, int index){
            return ListTile(
            contentPadding: EdgeInsets.symmetric(vertical:0.0),
            title: Text(_names[index]),
            leading: Icon(Icons.cached),
            trailing: Text(_dates[index]),
            );
          }
        )
    );
  }
}
</code>```

Title: Remove gap between widget

Body:
I want to close the gap between the lists but its just not working. the only option i have is to increase the gap : Sizedbox,spacer,divider

screenshot of my problem

code:

body: Container(
        child: Column(
          children: <Widget>[
            _mainList(Icon(Icons.cached), "Erste", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Zweite", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Dritte", "21:13 pm"),
            _mainList(Icon(Icons.cached), "Vierte", "21:13 pm"),
          ]
        )
  )

  Widget _mainList(Icon symbol, String name, String time){
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 30),
      child: ListTile(
        leading: symbol,
        title: Text(name, textScaleFactor: 1.2),
        trailing: Text(time, textScaleFactor: 1.3),
      ),
    );
  }