问:
React Native render white screen when use Context API
I have an issue.
When I don't wrap AuthProvider everything OK. Dont have any problems.
But when I wrap AuthProvider, my Application render white screen @@.
So I check terminal, and see Bundle not running ( normally when render we can see Bundle Loading and Running...) .
How I fix this problem ?
Thank you so much.

createDataContext.js

```<code>   import React, { useReducer } from 'react';

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ chilrden }) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {chilrden}
      </Context.Provider>
    );
  };
  return { Context, Provider };
};
</code>```

AuthContext.js

```<code>import createDataContext from './createDataContext';

const authReducer = (state, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

export const { Provider, Context } = createDataContext(
  authReducer,
  {},
  { isSignedIn: true }
);
</code>```

App.js

```<code>import React from 'react';
import {Provider as AuthProvider} from './src/context/AuthContext';
import {
  createAppContainer,
  createSwitchNavigator,
} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {createStackNavigator} from 'react-navigation-stack';

import AccountScreen from './src/screens/AccountScreen';
import TrackDetailScreen from './src/screens/TrackDetailScreen';
import TrackListScreen from './src/screens/TrackListScreen';
import SigninScreen from './src/screens/SigninScreen';
import SignupScreen from './src/screens/SignupScreen';
import TrackCreateScreen from './src/screens/TrackCreateScreen';

const switchNavigator = createSwitchNavigator({
  loginFlow: createStackNavigator({
    Signup:SignupScreen,
    Signin:SigninScreen
  }),
  mainFlow: createBottomTabNavigator({
    trackListFlow:createStackNavigator({
      TrackList:TrackListScreen,
      TrackDetail:TrackDetailScreen
    }),
    TrackCreate:TrackCreateScreen,
    Account:AccountScreen,
  })
});

const App = createAppContainer(switchNavigator);

export default () => {
  return(
    <AuthProvider>
      <App/>
    </AuthProvider>
  );
};
</code>```

答: I believe boundActions is re-created every time the app render that cause the problem. You should try to use useMemo to cache boundActions. It may help

Body:
I have an issue.
When I don't wrap AuthProvider everything OK. Dont have any problems.
But when I wrap AuthProvider, my Application render white screen @@.
So I check terminal, and see Bundle not running ( normally when render we can see Bundle Loading and Running...) .
How I fix this problem ?
Thank you so much.

createDataContext.js

   import React, { useReducer } from 'react';

export default (reducer, actions, defaultValue) => {
  const Context = React.createContext();

  const Provider = ({ chilrden }) => {
    const [state, dispatch] = useReducer(reducer, defaultValue);

    const boundActions = {};

    for (let key in actions) {
      boundActions[key] = actions[key](dispatch);
    }

    return (
      <Context.Provider value={{ state, ...boundActions }}>
        {chilrden}
      </Context.Provider>
    );
  };
  return { Context, Provider };
};

AuthContext.js

import createDataContext from './createDataContext';

const authReducer = (state, action) => {
  switch (action.type) {
    default:
      return state;
  }
};

export const { Provider, Context } = createDataContext(
  authReducer,
  {},
  { isSignedIn: true }
);

App.js

import React from 'react';
import {Provider as AuthProvider} from './src/context/AuthContext';
import {
  createAppContainer,
  createSwitchNavigator,
} from 'react-navigation';
import {createBottomTabNavigator} from 'react-navigation-tabs';
import {createStackNavigator} from 'react-navigation-stack';

import AccountScreen from './src/screens/AccountScreen';
import TrackDetailScreen from './src/screens/TrackDetailScreen';
import TrackListScreen from './src/screens/TrackListScreen';
import SigninScreen from './src/screens/SigninScreen';
import SignupScreen from './src/screens/SignupScreen';
import TrackCreateScreen from './src/screens/TrackCreateScreen';

const switchNavigator = createSwitchNavigator({
  loginFlow: createStackNavigator({
    Signup:SignupScreen,
    Signin:SigninScreen
  }),
  mainFlow: createBottomTabNavigator({
    trackListFlow:createStackNavigator({
      TrackList:TrackListScreen,
      TrackDetail:TrackDetailScreen
    }),
    TrackCreate:TrackCreateScreen,
    Account:AccountScreen,
  })
});

const App = createAppContainer(switchNavigator);

export default () => {
  return(
    <AuthProvider>
      <App/>
    </AuthProvider>
  );
};


来源: stackexchange

问:
How to use I-Value in for-loop
Hi I am playing around with javascript and firebase but running into an issue.

I want to sent the same email to every email listed in my datebase after the database entry hast been created:

If I use the code without the for-loop everything works fine:

```<code>to: snap.data().email,
</code>```

I tried a few ways to use the i-value as an argument - one of them not working is in the code below:

```<code>to: snap.data().email.concat(i.toString()),
</code>```

```<code>exports.sendEmail = functions.firestore
    .document('user/{userId}')
    .onCreate((snap, context) => {

      for(var i = 1; i <= snap.data().number; i++) {
        const mailOptions = {

            from: `***********`,
            to: snap.data().email.concat(i.toString()),
            subject: `From ${snap.data().name}`,
            html: `<h1>Me ${snap.data().name} </h1>
                                <p>
                                   <b>Hallo - </b>${snap.data().content}<br>
                                </p>`
      };
      return transporter.sendMail(mailOptions, (error, data) => {
          if (error) {
              console.log(error)
              return
          }
          console.log("sent")
      });
    };

    });
</code>```

I would really appreciate if you could help me out :-)

答:
if you want to get email1, and email2 , ... properties, you can do as below

```<code>to: snap.data()['email'+i],
</code>```

also to have better code, you can store snap.data() into a variable like

```<code>const data = snap.data();
</code>```

and use it over and over like

```<code>to: data['email'+i]
</code>```

Also you have return in your loop, it means after first one it will exit loop

Suggestion

You can store emails as an array, instead of one by one, then you can simply loop through and send emails, also then you don't need number, so you shape of data will be like

```<code>{
  content: string;
  name: string;
  emails: string[];
}
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to use I-Value in for-loop

Body:
Hi I am playing around with javascript and firebase but running into an issue.

I want to sent the same email to every email listed in my datebase after the database entry hast been created:

If I use the code without the for-loop everything works fine:

to: snap.data().email,

I tried a few ways to use the i-value as an argument - one of them not working is in the code below:

to: snap.data().email.concat(i.toString()),

exports.sendEmail = functions.firestore
    .document('user/{userId}')
    .onCreate((snap, context) => {

      for(var i = 1; i <= snap.data().number; i++) {
        const mailOptions = {

            from: `***********`,
            to: snap.data().email.concat(i.toString()),
            subject: `From ${snap.data().name}`,
            html: `
Me ${snap.data().name}

                                   Hallo - ${snap.data().content}

`
      };
      return transporter.sendMail(mailOptions, (error, data) => {
          if (error) {
              console.log(error)
              return
          }
          console.log("sent")
      });
    };

    });

I would really appreciate if you could help me out :-)

Body:
if you want to get email1, and email2 , ... properties, you can do as below

to: snap.data()['email'+i],

also to have better code, you can store snap.data() into a variable like

const data = snap.data();

and use it over and over like

to: data['email'+i]

Also you have return in your loop, it means after first one it will exit loop

Suggestion

You can store emails as an array, instead of one by one, then you can simply loop through and send emails, also then you don't need number, so you shape of data will be like

{
  content: string;
  name: string;
  emails: string[];
}


问:
Finding the Stats.max for each hierarchical index in Deedle
If I have a dataset that contains [City, Dealership, Total Cars Sold]. How would I get the top dealer in each city and the number of cars they sold?

The results should look like

```<code>City1 Dealership A 2000
City2 Dealership X 1000
etc.
</code>```

I'm sure it's possible, but I'm not having any luck and it might because i'm approaching the problem the wrong way.

Currently i'm grouping by Dealership and City which creates a Frame<(string*string*int), int> and that gets me

```<code>City1 Dealership A 1 -> 2000
City1 Dealership B 2 -> 1000
City2 Dealership X 3 -> 1000
City2 Dealership Y 4 -> 500
etc.
</code>```

But trying to then get the dealership that does the most deals is where i'm stumped.

Thanks.

答:
You can do this using the Series.applyLevel function. It takes a series together with a key selector and then it applies a given aggregation to all rows that have the given key. In your case, the key selector just needs to project the dealership from the composed key of the series. Given your sample data:

```<code>let data = series [
  ("City1", "Dealership A") => 2000
  ("City1", "Dealership B") => 1000
  ("City2", "Dealership X") => 1000
  ("City2", "Dealership Y") => 500 ]
</code>```

You can get the result by using:

```<code>data
|> Series.applyLevel (fun (c, d) -> d) Stats.max
</code>```

Note that Stats.max returns option (which is None for empty series). You can get a series with just numbers using:

```<code>data
|> Series.applyLevel (fun (c, d) -> d) (Stats.max >> Option.get)
</code>```

Body:
If I have a dataset that contains [City, Dealership, Total Cars Sold]. How would I get the top dealer in each city and the number of cars they sold?

The results should look like

City1 Dealership A 2000
City2 Dealership X 1000
etc.

I'm sure it's possible, but I'm not having any luck and it might because i'm approaching the problem the wrong way.

Currently i'm grouping by Dealership and City which creates a Frame<(string*string*int), int> and that gets me

City1 Dealership A 1 -> 2000
City1 Dealership B 2 -> 1000
City2 Dealership X 3 -> 1000
City2 Dealership Y 4 -> 500
etc.

But trying to then get the dealership that does the most deals is where i'm stumped.

Thanks.

Body:
You can do this using the Series.applyLevel function. It takes a series together with a key selector and then it applies a given aggregation to all rows that have the given key. In your case, the key selector just needs to project the dealership from the composed key of the series. Given your sample data:

let data = series [
  ("City1", "Dealership A") => 2000
  ("City1", "Dealership B") => 1000
  ("City2", "Dealership X") => 1000
  ("City2", "Dealership Y") => 500 ]

You can get the result by using:

data
|> Series.applyLevel (fun (c, d) -> d) Stats.max

Note that Stats.max returns option (which is None for empty series). You can get a series with just numbers using:

data
|> Series.applyLevel (fun (c, d) -> d) (Stats.max >> Option.get)


问:
mat-tab-label disable keyboard interaction
I have a material tab component (mat-tab-gruop), and i needed a search bar inside the mat-tab-header, so i added a disabled tab containing only a mat-tab-label, and placed it inside it my search bar component.

Like this:

```<code><mat-tab-group>
  <mat-tab disabled>
    <ng-template mat-tab-label>
      <search-bar></search-bar>
    </ng-template>
  </mat-tab>
</mat-tab-group>
</code>```

My problem is when I press an arrow key, instead of moving the cursor between characters, the focus changes to the other headers.

That happened because angular-meterial use Keyboard interaction to move focus between tabs.

I want to disable this Keyboard interactions behaviour, and keep focus on my search bar. I know I can move back focus after losing it to another tab header, then back to the search tab-header, using binding to (selectedTabChanged) and move focus back. I want the focus to always stay on the search bar input, so I’ll be able use arrows to move between charcters.

stackbiltz Example

my code:

```<code><mat-tab-group [selectedIndex]="'1'">

  <mat-tab disabled>
    <ng-template mat-tab-label>
      <div>
        <mat-form-field>
          <input matInput class="search" [value]="searchText">
        </mat-form-field>
      </div>
    </ng-template>
  </mat-tab>

  <mat-tab label="tab1">
    <p>some content</p>
  </mat-tab>

  <mat-tab label="tab2">
    <p>some content</p>
  </mat-tab>

</mat-tab-group>

</code>```

答:
Stop the key events propagating from the input field to stop them reaching the tab widget

```<code><mat-form-field>
          <input matInput class="search" [value]="searchText" (keydown)="suppressKeyEvent($event)">
        </mat-form-field>
</code>```

and

```<code>export class TabGroupAnimationsExample {
  suppressKeyEvent (event:any) {
    event.stopPropagation();
  }
}
</code>```

https://stackblitz.com/edit/angular-xufnk7-keqvdt

Just picking up angular and had to do something similar to above, so if anyone knows of a more 'angurly' way to do it (i.e. can you write the key suppression as some kind of imported module/directive?) that'd be kewl.

Body:
I have a material tab component (mat-tab-gruop), and i needed a search bar inside the mat-tab-header, so i added a disabled tab containing only a mat-tab-label, and placed it inside it my search bar component.

Like this:

<mat-tab-group>
  <mat-tab disabled>
    <ng-template mat-tab-label>
      <search-bar></search-bar>
    </ng-template>
  </mat-tab>
</mat-tab-group>

My problem is when I press an arrow key, instead of moving the cursor between characters, the focus changes to the other headers.

That happened because angular-meterial use Keyboard interaction to move focus between tabs.

I want to disable this Keyboard interactions behaviour, and keep focus on my search bar. I know I can move back focus after losing it to another tab header, then back to the search tab-header, using binding to (selectedTabChanged) and move focus back. I want the focus to always stay on the search bar input, so I’ll be able use arrows to move between charcters.

stackbiltz Example

my code:

<mat-tab-group [selectedIndex]="'1'">

  <mat-tab disabled>
    <ng-template mat-tab-label>

        <mat-form-field>
          <input matInput class="search" [value]="searchText">
        </mat-form-field>

    </ng-template>
  </mat-tab>

  <mat-tab label="tab1">

some content

  </mat-tab>

  <mat-tab label="tab2">

some content

  </mat-tab>

</mat-tab-group>

Body:
Stop the key events propagating from the input field to stop them reaching the tab widget

<mat-form-field>
          <input matInput class="search" [value]="searchText" (keydown)="suppressKeyEvent($event)">
        </mat-form-field>

and

export class TabGroupAnimationsExample {
  suppressKeyEvent (event:any) {
    event.stopPropagation();
  }
}

https://stackblitz.com/edit/angular-xufnk7-keqvdt

Just picking up angular and had to do something similar to above, so if anyone knows of a more 'angurly' way to do it (i.e. can you write the key suppression as some kind of imported module/directive?) that'd be kewl.


问:
Workers in javascript not so fast
I am giving a try to workers in js and I tried to make a simple sort using the same js sort function. The comparison i am making is just using an async function which will sort 60000 random numbers. The first will sort the random numbers as traditionally we are used to do it.

```<code>async function normalSort(arr) {
    return new Promise((res) => {
        let copy = arr;
        copy.sort((a, b) => a > b ? 1 : -1);
        return res(copy)
    })
}
</code>```

the other is a normal function which will be called for a workersHandler function

```<code>const { Worker, parentPort, workerData } = require('worker_threads');

function sort(data) {
    let copy = data;
    copy.sort((a, b) => a > b ? 1 : -1);
    parentPort.postMessage(copy)
    process.exit();
}

sort(workerData);

</code>```

the workers handler function

```<code>const os = require('os');
const path = require('path');
const { Worker } = require('worker_threads');

async function workersHandler(arr) {
    const startTime = Date.now();
    const cpusAmount = os.cpus().length;
    const chSize = Math.ceil(arr.length / cpusAmount)
    let promises = [];
    for (let i = 0; i < arr.length; i += chSize) {
        const end = i + chSize;
        const currentChunk = arr.slice(i, end);
        const promise = new Promise((res, rej) => {
            //@ts-ignore
            const worker = new Worker(path.join(__dirname, '..', '/utils/sort.js'), { workerData: currentChunk })

            worker.on('message', res)
            worker.on('error', rej)
        })
        promises.push(promise);
    }
    let result = await Promise.all(promises)
    return result;
}

</code>```

and the main function which will call the others functions

```<code>function main() {
    let arr = new Array(60000).fill(0).map((_, i) => Math.round(Math.random() * 100));
    const startTime = Date.now();

    workersHandler(arr).then(r => console.log('workers sort', Date.now() - startTime + ' ms'))
    normalSort(arr).then(r => console.log('normal sort', Date.now() - startTime + ' ms'))
}
main();
</code>```

Surprisingly the normal sort function is way faster and is working in one thread.
I am receiving for the workers function 101 ms
for the normal sort function 53 ms
Someone could explain me why these weird results?. Are workers not so fast or I am making a wrong implementation?.

答:
60000 may not be enough, IPC times matter

btw IPC: generic JavaScript datatypes, including generic JS arrays are heavy when copied to workers, but there are binary array types, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

postMessage() has a transfer argument, but it applies to a limited number of types only.

https://nodejs.org/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist and https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage:

postMessage(value[, transferList])

  node: transferList may be a list of ArrayBuffer and MessagePort objects. After transferring, they will not be usable on the sending side of the channel anymore (even if they are not contained in value).
  MDN: An optional array of Transferable objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to. Transferable objects are instances of classes like ArrayBuffer, MessagePort or ImageBitmap objects that can be transferred.

Effect of types:

let typ=prompt("Type: 0/1/2/3 (Array/Float64Array/Float32Array/Uint32Array)");
let len=parseInt(prompt("Length"));
let basearray;
switch(typ){
  case "1":basearray=new Float64Array(len);break;
  case "2":basearray=new Float32Array(len);break;
  case "3":basearray=new Uint32Array(len);break;
  default: basearray=new Array(len);break;
}
for(let i=0;i<basearray.length;i++)
  basearray[i]=Math.random()*0x1000000;

let cpus=4,
    chunksize=basearray.length/cpus,
    chunks=[],chunksw=[];
for(let i=0;i<cpus;i++)
  chunksw[i]=(chunks[i]=basearray.slice(i*chunksize,(i+1)*chunksize)).slice();

let start=Date.now();
for(let i=0;i<cpus;i++)
  chunks[i].sort((a,b)=>a-b);
console.log("Seq:",Date.now()-start);

let code="onmessage=event=>postMessage(event.data.sort((a,b)=>a-b));";
let ws=[],cnt=0;
for(let i=0;i<cpus;i++){
  ws[i]=new Worker("data:text/plain,"+escape(code));
  let j=i;
  ws[i].onmessage=event=>{
    chunksw[j]=event.data;
    if(++cnt===cpus){
      console.log("Par:",Date.now()-start);
      if(len<=20)
        for(let i=0;i<cpus;i++)
          console.log(chunks[i],chunksw[i]);
    }
  };
}
start=Date.now();
for(let i=0;i<cpus;i++)
  ws[i].postMessage(chunksw[i]);```
</div>
</div>
</p>

<p>Specify a length divisible by 4. If length is 20 or less, the resulting sorted chunks are going to be logged too for verification purposes. JS <code>Array</code>-s are reliably slower for me when passed around (compared to the thread-less run), regardless of containing 20 or 6000000 elements (while a 6-million-element JS array runs for 8 seconds for me on an older laptop, it still may be safer to start with something less). The other types are faster when threaded, Uint being the fastest.<br>
Actually anything which is not 1/2/3 is going to result in a JS <code>Array</code> (the slowest one), including the empty string.</p>

<p>Effect of transfer is not that spectacular, but already appears from the beginning (with 4 elements it is 59-69 ms vs 20-22 ms on my PC):</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>let typ=prompt("Type: 0/1/2 (Float64Array/Float32Array/Uint32Array)");
let len=parseInt(prompt("Length"));
let basearray;
switch(typ){
  case "1":basearray=new Float32Array(len);break;
  case "2":basearray=new Uint32Array(len);break;
  default:basearray=new Float64Array(len);
}
for(let i=0;i<basearray.length;i++)
  basearray[i]=Math.random()*0x1000000;

let cpus=4,
    chunksize=basearray.length/cpus,
    chunksw=[],chunkswt=[];
for(let i=0;i<cpus;i++)
  chunkswt[i]=(chunksw[i]=basearray.slice(i*chunksize,(i+1)*chunksize)).slice();

let start;
let code="onmessage=event=>postMessage(event.data.sort((a,b)=>a-b));";
let ws=[],cnt=0;
for(let i=0;i<cpus;i++){
  ws[i]=new Worker("data:text/plain,"+escape(code));
  let j=i;
  ws[i].onmessage=event=>{
    chunksw[j]=event.data;
    if(++cnt===cpus){
      console.log("Non-transfer:",Date.now()-start);
      // launch transfer measurement
      cnt=0;start=Date.now();
      for(let i=0;i<cpus;i++)
        wst[i].postMessage(chunkswt[i].buffer,[chunkswt[i].buffer]);    }
  };
}

let codet;
switch(typ){
  case "1":
    codet="onmessage=event=>{"+
          "let arr=new Float32Array(event.data);"+
          "arr.sort((a,b)=>a-b);"+
          "postMessage(event.data,[event.data]);};";
    break;
  case "2":
    codet="onmessage=event=>{"+
          "let arr=new Uint32Array(event.data);"+
          "arr.sort((a,b)=>a-b);"+
          "postMessage(event.data,[event.data]);};";
    break;
  default:
    codet="onmessage=event=>{"+
          "let arr=new Float64Array(event.data);"+
          "arr.sort((a,b)=>a-b);"+
          "postMessage(event.data,[event.data]);};";
}
let wst=[];
for(let i=0;i<cpus;i++){
  wst[i]=new Worker("data:text/plain,"+escape(codet));
  let j=i;
  wst[i].onmessage=event=>{
    switch(typ){
      case "1":chunkswt[j]=new Float32Array(event.data);break;
      case "2":chunkswt[j]=new Uint32Array(event.data);break;
      default:chunkswt[j]=new Float64Array(event.data);
    }
    if(++cnt===cpus){
      console.log("Transfer:",Date.now()-start);
      if(len<=20)
        for(let i=0;i<cpus;i++)
          console.log(chunksw[i],chunkswt[i]);
    }
  };
}

// launch non-transfer measurement
start=Date.now();
for(let i=0;i<cpus;i++)
  ws[i].postMessage(chunksw[i]);</code>```

This code is a bit messy because it is the buffer which can be transferred, not the typed arrays themselves, and also, while the second measurement is initialized as a direct copy-paste (which already isn't that pretty), it is then launched from inside the completion function of the first one.

(I do not wish to provide exact measurement results because my PC is doing some other things too. Just run the snippets a couple times with varied or even repeated parameters)

Title: Workers in javascript not so fast

Body:
I am giving a try to workers in js and I tried to make a simple sort using the same js sort function. The comparison i am making is just using an async function which will sort 60000 random numbers. The first will sort the random numbers as traditionally we are used to do it.

async function normalSort(arr) {
    return new Promise((res) => {
        let copy = arr;
        copy.sort((a, b) => a > b ? 1 : -1);
        return res(copy)
    })
}

the other is a normal function which will be called for a workersHandler function

const { Worker, parentPort, workerData } = require('worker_threads');

function sort(data) {
    let copy = data;
    copy.sort((a, b) => a > b ? 1 : -1);
    parentPort.postMessage(copy)
    process.exit();
}

sort(workerData);

the workers handler function

const os = require('os');
const path = require('path');
const { Worker } = require('worker_threads');

async function workersHandler(arr) {
    const startTime = Date.now();
    const cpusAmount = os.cpus().length;
    const chSize = Math.ceil(arr.length / cpusAmount)
    let promises = [];
    for (let i = 0; i < arr.length; i += chSize) {
        const end = i + chSize;
        const currentChunk = arr.slice(i, end);
        const promise = new Promise((res, rej) => {
            //@ts-ignore
            const worker = new Worker(path.join(__dirname, '..', '/utils/sort.js'), { workerData: currentChunk })

            worker.on('message', res)
            worker.on('error', rej)
        })
        promises.push(promise);
    }
    let result = await Promise.all(promises)
    return result;
}

and the main function which will call the others functions

function main() {
    let arr = new Array(60000).fill(0).map((_, i) => Math.round(Math.random() * 100));
    const startTime = Date.now();

    workersHandler(arr).then(r => console.log('workers sort', Date.now() - startTime + ' ms'))
    normalSort(arr).then(r => console.log('normal sort', Date.now() - startTime + ' ms'))
}
main();

Surprisingly the normal sort function is way faster and is working in one thread.
I am receiving for the workers function 101 ms
for the normal sort function 53 ms
Someone could explain me why these weird results?. Are workers not so fast or I am making a wrong implementation?.

Body:
60000 may not be enough, IPC times matter

btw IPC: generic JavaScript datatypes, including generic JS arrays are heavy when copied to workers, but there are binary array types, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray

postMessage() has a transfer argument, but it applies to a limited number of types only.

https://nodejs.org/api/worker_threads.html#worker_threads_port_postmessage_value_transferlist and https://developer.mozilla.org/en-US/docs/Web/API/Worker/postMessage:

postMessage(value[, transferList])

  node: transferList may be a list of ArrayBuffer and MessagePort objects. After transferring, they will not be usable on the sending side of the channel anymore (even if they are not contained in value).
  MDN: An optional array of Transferable objects to transfer ownership of. If the ownership of an object is transferred, it becomes unusable (neutered) in the context it was sent from and becomes available only to the worker it was sent to. Transferable objects are instances of classes like ArrayBuffer, MessagePort or ImageBitmap objects that can be transferred.

Effect of types:

let typ=prompt("Type: 0/1/2/3 (Array/Float64Array/Float32Array/Uint32Array)");
let len=parseInt(prompt("Length"));
let basearray;
switch(typ){
  case "1":basearray=new Float64Array(len);break;
  case "2":basearray=new Float32Array(len);break;
  case "3":basearray=new Uint32Array(len);break;
  default: basearray=new Array(len);break;
}
for(let i=0;i<basearray.length;i++)
  basearray[i]=Math.random()*0x1000000;

let cpus=4,
    chunksize=basearray.length/cpus,
    chunks=[],chunksw=[];
for(let i=0;i<cpus;i++)
  chunksw[i]=(chunks[i]=basearray.slice(i*chunksize,(i+1)*chunksize)).slice();

let start=Date.now();
for(let i=0;i<cpus;i++)
  chunks[i].sort((a,b)=>a-b);
console.log("Seq:",Date.now()-start);

let code="onmessage=event=>postMessage(event.data.sort((a,b)=>a-b));";
let ws=[],cnt=0;
for(let i=0;i<cpus;i++){
  ws[i]=new Worker("data:text/plain,"+escape(code));
  let j=i;
  ws[i].onmessage=event=>{
    chunksw[j]=event.data;
    if(++cnt===cpus){
      console.log("Par:",Date.now()-start);
      if(len<=20)
        for(let i=0;i<cpus;i++)
          console.log(chunks[i],chunksw[i]);
    }
  };
}
start=Date.now();
for(let i=0;i<cpus;i++)
  ws[i].postMessage(chunksw[i]);

Specify a length divisible by 4. If length is 20 or less, the resulting sorted chunks are going to be logged too for verification purposes. JS Array-s are reliably slower for me when passed around (compared to the thread-less run), regardless of containing 20 or 6000000 elements (while a 6-million-element JS array runs for 8 seconds for me on an older laptop, it still may be safer to start with something less). The other types are faster when threaded, Uint being the fastest.

Actually anything which is not 1/2/3 is going to result in a JS Array (the slowest one), including the empty string.

Effect of transfer is not that spectacular, but already appears from the beginning (with 4 elements it is 59-69 ms vs 20-22 ms on my PC):

let typ=prompt("Type: 0/1/2 (Float64Array/Float32Array/Uint32Array)");
let len=parseInt(prompt("Length"));
let basearray;
switch(typ){
  case "1":basearray=new Float32Array(len);break;
  case "2":basearray=new Uint32Array(len);break;
  default:basearray=new Float64Array(len);
}
for(let i=0;i<basearray.length;i++)
  basearray[i]=Math.random()*0x1000000;

let cpus=4,
    chunksize=basearray.length/cpus,
    chunksw=[],chunkswt=[];
for(let i=0;i<cpus;i++)
  chunkswt[i]=(chunksw[i]=basearray.slice(i*chunksize,(i+1)*chunksize)).slice();

let start;
let code="onmessage=event=>postMessage(event.data.sort((a,b)=>a-b));";
let ws=[],cnt=0;
for(let i=0;i<cpus;i++){
  ws[i]=new Worker("data:text/plain,"+escape(code));
  let j=i;
  ws[i].onmessage=event=>{
    chunksw[j]=event.data;
    if(++cnt===cpus){
      console.log("Non-transfer:",Date.now()-start);
      // launch transfer measurement
      cnt=0;start=Date.now();
      for(let i=0;i<cpus;i++)
        wst[i].postMessage(chunkswt[i].buffer,[chunkswt[i].buffer]);    }
  };
}

let codet;
switch(typ){
  case "1":
    codet="onmessage=event=>{"+
          "let arr=new Float32Array(event.data);"+
          "arr.sort((a,b)=>a-b);"+
          "postMessage(event.data,[event.data]);};";
    break;
  case "2":
    codet="onmessage=event=>{"+
          "let arr=new Uint32Array(event.data);"+
          "arr.sort((a,b)=>a-b);"+
          "postMessage(event.data,[event.data]);};";
    break;
  default:
    codet="onmessage=event=>{"+
          "let arr=new Float64Array(event.data);"+
          "arr.sort((a,b)=>a-b);"+
          "postMessage(event.data,[event.data]);};";
}
let wst=[];
for(let i=0;i<cpus;i++){
  wst[i]=new Worker("data:text/plain,"+escape(codet));
  let j=i;
  wst[i].onmessage=event=>{
    switch(typ){
      case "1":chunkswt[j]=new Float32Array(event.data);break;
      case "2":chunkswt[j]=new Uint32Array(event.data);break;
      default:chunkswt[j]=new Float64Array(event.data);
    }
    if(++cnt===cpus){
      console.log("Transfer:",Date.now()-start);
      if(len<=20)
        for(let i=0;i<cpus;i++)
          console.log(chunksw[i],chunkswt[i]);
    }
  };
}

// launch non-transfer measurement
start=Date.now();
for(let i=0;i<cpus;i++)
  ws[i].postMessage(chunksw[i]);

This code is a bit messy because it is the buffer which can be transferred, not the typed arrays themselves, and also, while the second measurement is initialized as a direct copy-paste (which already isn't that pretty), it is then launched from inside the completion function of the first one.

(I do not wish to provide exact measurement results because my PC is doing some other things too. Just run the snippets a couple times with varied or even repeated parameters)


问:
PHP search array for a value between two numbers
What's the best way of searching an array for a number within a range? e.g. between 1000 and 1500.

```<code><?php
$numbers = array(1105,2140,3170);

$needle = **value between 1000 and 1500**;

if (in_array($needle, $numbers)) {
  echo "Match found";
} else {
  echo "Match not found";
}
?>
</code>```

In this case, this would return 'Match found' as 1105 is between 1000 and 1500.

Can I set a range for the $needle variable?

答:
There is no built-in function for these purpose. So create a function that will help you.</p>

```<code>function searchOnRange(array $stack, $min=0, $max=0)
{
    // Loop through each value of array
    foreach($stack as $value){
        // CHeck value is between the given range
        if(($value >= $min) && ($value <= $max)){
            echo "Match found - ".$value;
        } else {
            echo "Match not found - ".$value;
        }
    }
}

$numbers = array(1105,2140,3170);
searchOnRange($numbers, 1000, 1500);
</code>```

Body:
What's the best way of searching an array for a number within a range? e.g. between 1000 and 1500.

<?php
$numbers = array(1105,2140,3170);

$needle = **value between 1000 and 1500**;

if (in_array($needle, $numbers)) {
  echo "Match found";
} else {
  echo "Match not found";
}
?>

In this case, this would return 'Match found' as 1105 is between 1000 and 1500.

Can I set a range for the $needle variable?

Body:
There is no built-in function for these purpose. So create a function that will help you.

function searchOnRange(array $stack, $min=0, $max=0)
{
    // Loop through each value of array
    foreach($stack as $value){
        // CHeck value is between the given range
        if(($value >= $min) && ($value <= $max)){
            echo "Match found - ".$value;
        } else {
            echo "Match not found - ".$value;
        }
    }
}

$numbers = array(1105,2140,3170);
searchOnRange($numbers, 1000, 1500);


问:
How do I decode HTML that was encoded in JS using encodeURIComponent()?
I tried :

```<code>string decodedHtml = HttpUtility.HtmlDecode(html);
</code>```

Where html is the encoded html. It seems that this does not alter the string at all. The html is still encoded.

答:
```<code>string s = System.Uri.UnescapeDataString(html);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I tried :

string decodedHtml = HttpUtility.HtmlDecode(html);

Where html is the encoded html. It seems that this does not alter the string at all. The html is still encoded.


问:
WebView in ListView without assigning its dimensions
Is there any possibility to put WebView (webview_flutter) inside a ListView without assigning its dimensions but automatically adopt its height. Only working solution I found is to put WebView in Container by assigning its height but I dont want to assign any height I just want it to occupy height according to its content..

I have tried so many solutions including Expanded for this but getting error about infinite height . Any solution?

答:
I am sorry it's late but now it's working properly.

I wrapped WebView into a SizedBox and assigned it's height like this:

```<code>              _webViewController
                  .evaluateJavascript("document.body.clientHeight")
                  .then((height) {
                print("Height of Page is: $height}");
                setState(() {
                      sizedBoxHeight = double.parse(height);
                    });
              });
</code>```

For a more advanced solution we can use JavascriptChannels like this:

```<code>            javascriptChannels: Set.from([
              JavascriptChannel(
                  name: 'RenderedWebViewHeight',
                  onMessageReceived: (JavascriptMessage message) {
                      setState(() {
                        sizedBoxHeight = double.parse(message.message);
                      });

            ]),
</code>```

In JavaScript, we can do something like this.

```<code>onload="RenderedWebViewHeight.postMessage(document.body.clientHeight);"
</code>```

Now we can see it's dynamically calculating the height of WebView which is wrapped in a SizedBox with the height WebView so we can put it into a ListView.

For a more detailed solution, you can look at webview_flutter_plus.

Edit:

```<code> document.documentElement.scrollHeight
</code>```

is the most accurate way of doing things. This works with both body margins and margins of stuff inside the body pushing it downwards.
More info in How to get height of entire document with JavaScript

Body:
I am sorry it's late but now it's working properly.

I wrapped WebView into a SizedBox and assigned it's height like this:

              _webViewController
                  .evaluateJavascript("document.body.clientHeight")
                  .then((height) {
                print("Height of Page is: $height}");
                setState(() {
                      sizedBoxHeight = double.parse(height);
                    });
              });

For a more advanced solution we can use JavascriptChannels like this:

            javascriptChannels: Set.from([
              JavascriptChannel(
                  name: 'RenderedWebViewHeight',
                  onMessageReceived: (JavascriptMessage message) {
                      setState(() {
                        sizedBoxHeight = double.parse(message.message);
                      });

            ]),

In JavaScript, we can do something like this.

onload="RenderedWebViewHeight.postMessage(document.body.clientHeight);"

Now we can see it's dynamically calculating the height of WebView which is wrapped in a SizedBox with the height WebView so we can put it into a ListView.

For a more detailed solution, you can look at webview_flutter_plus.

Edit:

 document.documentElement.scrollHeight

is the most accurate way of doing things. This works with both body margins and margins of stuff inside the body pushing it downwards.
More info in How to get height of entire document with JavaScript


问:
Install XDEBUG in Catalina OSX
I found this page

https://bbqsoftwares.com/blog/xdebug-catalina

that help to install Xdebug in Macosx Catalina, after Apple has changed Xcode installation, the headers of php are in another location. But I cannot save phpize file due to readonly permissions and so I cannot change the headers file location.

And so I cannot make the Xdebug.so.

Any help?

答:
Here is the solution :
[Solution for Mac Catalina and Xcode 11][1]https://profilingviewer.com/installing-xdebug-on-catalina.html#build</p>

Title: Install XDEBUG in Catalina OSX


问:
How to control the orientation of the angular mat-icon
Angular version: v9

I have a button whose mat-icon is an arrow pointing towards the left.  I would like to know if there is any attribute for the mat-icon element tag to allow me to control the orientation of the arrow so that it points upward instead.

For the sake of learning purpose, instead of looking for another icon which achieves what I want, I prefer to learn how to do it via attribute in angular.

I search online, but could not find a solution. Hence this question. Help appreciated. Thanks

答:
Manage to achieve it by doing this</p>

```<code><mat-icon style="transform: rotate(90deg)">unfold_more</mat-icon>
</code>```

Body:
Manage to achieve it by doing this

<mat-icon style="transform: rotate(90deg)">unfold_more</mat-icon>


问:
fullcalendar, deleting event on button click
i am trying delete events when i click in button "x", but not work, and not getting any error.

I assign the function click in parameter "eventRender".

This is my code with JavaScript:

```<code>$('#calendar').fullCalendar({
        locale: 'es',
        weekends: false, //ocultar fines de semana
        defaultView: 'agendaWeek',
        allDaySlot: false,
        header: {
            left: 'month,agendaWeek,agendaDay,listDay',
            center: 'title',
            right: 'prev,next today'
        },
        height: 'auto',
        minTime: "10:00:00",
        maxTime: "20:00:00",
        editable: true,
        //droppable: true, // this allows things to be dropped onto the calendar
        dayClick: function(date, jsEvent, view) {
            console.log('Clicked on: ' + date.format());
            console.log('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
            console.log('Current view: ' + view.name);
            var hoy = moment();
            if(date.format("YYYY-MM-DD HH:mm") >= hoy.format("YYYY-MM-DD HH:mm")){
                asignarCita(date);
            }else{
                swal({
                    title: "Cita no disponible",
                    text: "La fecha u hora seleccionada ya ha pasado."
                });
            }
        },
        eventRender: function(event, element) {
            element.prepend( "<div class='ibox-tools'><a style='background-color: transparent; margin-right: 10px' class='pull-left'><i class='fa fa-times closeon'></i></a></div>" );
            //element.append( "<span class='closeon'>X</span>" );
            console.log(element.find('closeon'));
            element.find(".closeon").click(function() {
                $('#calendar').fullCalendar('removeEvents',event._id);
            });
        },
        events: [
            {
                title: 'All Day Event',
                start: '2014-10-01'
            },
            {
                title: 'Long Event',
                start: '2014-10-07',
                end: '2014-10-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2014-10-09T16:00:00'
            },
        ],
    });
</code>```

Where is the problem?

答:
The current version of FullCalendar has different API</p>

```<code>eventRender: function(info) {
      $(info.el).append("<span class='removebtn'>X</span>");
      $(info.el).find(".removebtn").click(function() {
        info.event.remove();
      });
    }
</code>```

Body:
i am trying delete events when i click in button "x", but not work, and not getting any error.

I assign the function click in parameter "eventRender".

This is my code with JavaScript:

$('#calendar').fullCalendar({
        locale: 'es',
        weekends: false, //ocultar fines de semana
        defaultView: 'agendaWeek',
        allDaySlot: false,
        header: {
            left: 'month,agendaWeek,agendaDay,listDay',
            center: 'title',
            right: 'prev,next today'
        },
        height: 'auto',
        minTime: "10:00:00",
        maxTime: "20:00:00",
        editable: true,
        //droppable: true, // this allows things to be dropped onto the calendar
        dayClick: function(date, jsEvent, view) {
            console.log('Clicked on: ' + date.format());
            console.log('Coordinates: ' + jsEvent.pageX + ',' + jsEvent.pageY);
            console.log('Current view: ' + view.name);
            var hoy = moment();
            if(date.format("YYYY-MM-DD HH:mm") >= hoy.format("YYYY-MM-DD HH:mm")){
                asignarCita(date);
            }else{
                swal({
                    title: "Cita no disponible",
                    text: "La fecha u hora seleccionada ya ha pasado."
                });
            }
        },
        eventRender: function(event, element) {
            element.prepend( "

" );
            //element.append( "X" );
            console.log(element.find('closeon'));
            element.find(".closeon").click(function() {
                $('#calendar').fullCalendar('removeEvents',event._id);
            });
        },
        events: [
            {
                title: 'All Day Event',
                start: '2014-10-01'
            },
            {
                title: 'Long Event',
                start: '2014-10-07',
                end: '2014-10-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2014-10-09T16:00:00'
            },
        ],
    });

Where is the problem?

Body:
The current version of FullCalendar has different API

eventRender: function(info) {
      $(info.el).append("<span class='removebtn'>X</span>");
      $(info.el).find(".removebtn").click(function() {
        info.event.remove();
      });
    }


问:
Comparing each rows in 2 dataframes using Spark and storing result in new column
Please I need help on comparing 2 data-frames with the desired output like shown in the last image below. I have 2 data-frames with column ID as the joining key. Now I want to compare columns N_1 with N_2, same as N_3 with N_4 and N_5 with N_6. Then the result of each comparison would be in a separate column indicating "Y" if the compared columns are matching and a "N" if they are not.
Ultimately, I want to create a last column where if any Compared columns in each row is "Y", the matching is "Y". Please see the last image for my desired output.
I cannot come upi with the scala code to do this. I'm using Spark. Please help

答:
Repeat calling withColumn to generate columns N_1=N_2，N_3=N_4，N_5=N_6，MATCHING

```<code>df1.join(df2, df1.col("ID") === df2.col("ID"))
   .withColumn("N_1=N_2", when(df1.col("N_1") === df1.col("N_2"), lit("Y")).otherwise(lit("N")))
   .withColumn("N_3=N_4", when(df1.col("N_3") === df2.col("N_4"), lit("Y")).otherwise(lit("N")))
   .withColumn("N_5=N_6", when(df2.col("N_5") === df2.col("N_6"), lit("Y")).otherwise(lit("N")))
   .withColumn("MATCHING", when(col("N_1=N_2") === "Y" || col("N_3=N_4") === "Y" || col("N_5=N_6") === "Y", lit("Y")).otherwise(lit("N")))
</code>```

Body:
Repeat calling withColumn to generate columns N_1=N_2，N_3=N_4，N_5=N_6，MATCHING

df1.join(df2, df1.col("ID") === df2.col("ID"))
   .withColumn("N_1=N_2", when(df1.col("N_1") === df1.col("N_2"), lit("Y")).otherwise(lit("N")))
   .withColumn("N_3=N_4", when(df1.col("N_3") === df2.col("N_4"), lit("Y")).otherwise(lit("N")))
   .withColumn("N_5=N_6", when(df2.col("N_5") === df2.col("N_6"), lit("Y")).otherwise(lit("N")))
   .withColumn("MATCHING", when(col("N_1=N_2") === "Y" || col("N_3=N_4") === "Y" || col("N_5=N_6") === "Y", lit("Y")).otherwise(lit("N")))


问:
How to get back a signed string (e.g. md5 hash) using a public-key (x509 certificate)
I'm very new with cryptographic and stuck for 2 days with this problem, I hope you can help me with.

I try to sign a md5 digest string with the private key of a X509 certificate. As far as I can see, this works fine.
Now I try to get back that string using the public key of that x509 certificate, but I have no idea how to do this.

First I created a x509 certificate and a private-Keyfile using OpenSSL:

openssl req -newkey rsa:1024 -nodes -x509 -days 365 -out signer.pem

Here's the example code I tried:

```<code>import M2Crypto
import hashlib

def empty_callback ():
 return

# md5 hash of params
params = "0045KIABCDEFG"

m = hashlib.md5()
m.update(params)
md = m.digest()
print m.hexdigest()

M2Crypto.Rand.rand_seed (os.urandom (1024))

# sign md5 hash with private key
SignEVP = M2Crypto.EVP.load_key ('privkey.pem')
#Begin signing
SignEVP.sign_init ()
#Tell it to sign our string
SignEVP.sign_update (md)
#Get the final result
StringSignature = SignEVP.sign_final ()
#print the final result
print StringSignature.encode ('base64')
</code>```

I get the public key with this, but don't know how to use it then.

objX509 = M2Crypto.X509.load_cert ('signer.pem')
PubKey = objX509.get_pubkey()

I only found how to verify the signed string, but that's not what I need.
Is there a method to get back the origin md5 digest (md) by using the signer.pem (the public key)?

I'm using M2Cyrpto-0.21.1 and OpenSSL 1.0.0d, and programming with Python27, 32bit on Windows7.

kind regards,
Falko

答:
Technically, you are not supposed to "decrypt" the signature. If you really want to decrypt it, do something like this:

```<code>cert = X509.load_cert("signer.pem")
decrypted = cert.get_pubkey().get_rsa().public_decrypt(StringSignature, 1)
</code>```

but this will not give you what you are expecting, I guess.

If you want to pull out the message digest that was signed using the code above, you would have to decode the ASN.1 sequence in the decrypted. You can do this with PyCrypto, of course, but what for?

```<code>from Crypto.Util import asn1
seq = asn1.DerSequence()
seq.decode(decrypted)
obj = asn1.DerObject()
obj.decode(seq[1])
# now this is the original message digest that was signed
original_message_md = obj.payload
</code>```

Body:
I'm very new with cryptographic and stuck for 2 days with this problem, I hope you can help me with.

I try to sign a md5 digest string with the private key of a X509 certificate. As far as I can see, this works fine.
Now I try to get back that string using the public key of that x509 certificate, but I have no idea how to do this.

First I created a x509 certificate and a private-Keyfile using OpenSSL:

openssl req -newkey rsa:1024 -nodes -x509 -days 365 -out signer.pem

Here's the example code I tried:

import M2Crypto
import hashlib

def empty_callback ():
 return

# md5 hash of params
params = "0045KIABCDEFG"

m = hashlib.md5()
m.update(params)
md = m.digest()
print m.hexdigest()

M2Crypto.Rand.rand_seed (os.urandom (1024))

# sign md5 hash with private key
SignEVP = M2Crypto.EVP.load_key ('privkey.pem')
#Begin signing
SignEVP.sign_init ()
#Tell it to sign our string
SignEVP.sign_update (md)
#Get the final result
StringSignature = SignEVP.sign_final ()
#print the final result
print StringSignature.encode ('base64')

I get the public key with this, but don't know how to use it then.

objX509 = M2Crypto.X509.load_cert ('signer.pem')
PubKey = objX509.get_pubkey()

I only found how to verify the signed string, but that's not what I need.
Is there a method to get back the origin md5 digest (md) by using the signer.pem (the public key)?

I'm using M2Cyrpto-0.21.1 and OpenSSL 1.0.0d, and programming with Python27, 32bit on Windows7.

kind regards,
Falko

Body:
Technically, you are not supposed to "decrypt" the signature. If you really want to decrypt it, do something like this:

cert = X509.load_cert("signer.pem")
decrypted = cert.get_pubkey().get_rsa().public_decrypt(StringSignature, 1)

but this will not give you what you are expecting, I guess.

If you want to pull out the message digest that was signed using the code above, you would have to decode the ASN.1 sequence in the decrypted. You can do this with PyCrypto, of course, but what for?

from Crypto.Util import asn1
seq = asn1.DerSequence()
seq.decode(decrypted)
obj = asn1.DerObject()
obj.decode(seq[1])
# now this is the original message digest that was signed
original_message_md = obj.payload


问:
Convert RTP/UDP Stream to HTTP with ffmpeg
As you may know, Android uses a strange implementation of RTP - It can only play low bitrate RTP streams. On the other hand, it can play Full HD HTTP stream flawlessly.

I'm trying a workaround for this problem: As stated in the title, using ffmpeg to convert the RTP/UDP stream to HTTP.

I've already compile ffmpeg for android, but I'm having difficulties configuring the ffserver.conf.

Is it possible to achieve what I want with ffmpeg?

I dont need any transcoding, will it use lots of the processor/memory?

Can you help me with these configurations?

I receive a udp/rtp multicast stream:

udp://@239.192.1.31:1234 or rtp://@239.192.1.31:1234 - TV channels

I want to output to HTTP:

http://127.0.0.1:8090/stream.mp4

Thank you in advance

inversus

Body:
#LOKAL
#EXTINF:-1 ,Lokal-100 TVRI
rtp://@239.1.1.37:8196
#EXTINF:-1 ,Lokal-101 METROTV
rtp://@239.1.1.19:8088
#EXTINF:-1 ,Lokal-102 CNN INDONESIA
rtp://@239.1.1.241:9362
#EXTINF:-1 ,Lokal-103 TVONE
rtp://@239.1.1.31:8160
#EXTINF:-1 ,Lokal-104 TRANSTV
rtp://@239.1.1.27:8136
#EXTINF:-1 ,Lokal-105 TRANS7
rtp://@239.1.1.29:8148
#EXTINF:-1 ,Lokal-106 SCTV
rtp://@239.1.1.21:8100
#EXTINF:-1 ,Lokal-107 INDOSIAR
rtp://@239.1.1.17:8076
#EXTINF:-1 ,Lokal-108 ANTV
rtp://@239.1.1.15:8064
#EXTINF:-1 ,Lokal-109 RCTI
rtp://@239.1.1.23:8112
#EXTINF:-1 ,Lokal-110 GLOBAL TV
rtp://@239.1.1.13:8052
#EXTINF:-1 ,Lokal-111 MNCTV
rtp://@239.1.1.25:8124
#EXTINF:-1 ,Lokal- Kompas TV
rtp://@239.1.1.197:9156
#EXTINF:-1 ,Lokal- NET TV
rtp://@239.1.1.119:8688


问:
Access Google Calendar API using Application-Specific Password
I'm working on a cron script to check my Google calendar on a daily basis.
I'd like to know if it's possible to use Application-Specific Passwords
(see: https://support.google.com/accounts/answer/185833?hl=it)
and insert the generated password in my script.
The OAUTH requires the user interaction and since I'm working on a script I cannot follow that way.
I've also read about the "service accounts", but hope I could avoid it just by using Application-Specific Passwords. What's the difference? Any hint?

Many thanks
Francesco

EDIT1: The code I'm trying with:

```<code><?php
require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$calendarList = $service->calendarList->listCalendarList();
</code>```

EDIT2: $service->calendarList->listCalendarList() gives empty list use:

```<code><?php
require __DIR__ . '/vendor/autoload.php';

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$listEvents = $service->events->listEvents("...@group.calendar.google.com");// taken from sharing calendar settings
$events = $listEvents->getItems();
print_r($events);

</code>```

答:
You seem to be running into this situation, which is mentioned in this Calendar help page.

Keep in mind it also applies to service accounts.

The accepted answer to this question...

Explains well that you can use the CalendarList: insert method to add the calendar to the calendar list.

Body:
I'm working on a cron script to check my Google calendar on a daily basis.
I'd like to know if it's possible to use Application-Specific Passwords
(see: https://support.google.com/accounts/answer/185833?hl=it)
and insert the generated password in my script.
The OAUTH requires the user interaction and since I'm working on a script I cannot follow that way.
I've also read about the "service accounts", but hope I could avoid it just by using Application-Specific Passwords. What's the difference? Any hint?

Many thanks
Francesco

EDIT1: The code I'm trying with:

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

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$calendarList = $service->calendarList->listCalendarList();

EDIT2: $service->calendarList->listCalendarList() gives empty list use:

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

$client = new Google_Client();
//The json file you got after creating the service account
putenv('GOOGLE_APPLICATION_CREDENTIALS=test-calendario-268115-5452ff6f57e8.json');
$client->useApplicationDefaultCredentials();
$client->setApplicationName("test_calendar");
$client->setScopes(Google_Service_Calendar::CALENDAR);
$client->setAccessType('offline');

$service = new Google_Service_Calendar($client);

$listEvents = $service->events->listEvents("...@group.calendar.google.com");// taken from sharing calendar settings
$events = $listEvents->getItems();
print_r($events);


问:
How to change Display Template Page url for Blog post in Liferay?
I'm using the Blogs portlet (Liferay 7.2 GA1) to list all blog posts in a page example.com/web/guest/blog and I use the Display Template Page for blog details.

The problem is that when I open a post the URL changes to:
http://localhost:8080/web/guest/b/blog-post-example

The friendly url for Blog is changed from:

http://localhost:8080/web/guest/blog/

to

http://localhost:8080/web/guest/b/

Is there a way to avoid changing the url?

答:
If you want to change the friendly url for blogs you should create a new InfoDisplayContributor, you can copy BlogsEntryInfoDisplayContributor.java file and then change the

public String getInfoURLSeparator()

Currently, it returns '/b/'.


问:
NodeJs:- Take values from the first dropdown and populate the values in the second dropdown dynamically
I was working on a dropdown list and wanted the results shown in the second dropdown to be filtered according to the option selected in the first dropdown.

My EJS file is as follows:-

```<code> <div class="form-group">
        <label for="">Category</label>
        <select id="list" name="mainCategory" id="maincategory-dropdown" onchange="getSelectValue()" class="form-control">
            <% mainCategories.forEach(function(cat){ %>
                <option value="<%= cat.slug %>"
                <% if (cat.slug == mainCategory) { %>
                selected="selected"
                <% } %>
                ><%= cat.title %></option>
            <% }); %>
        </select>
    </div>

    <div class="form-group">
        <label for="">Subcategory</label>
        <select name="category" id="category-dropdown" class="form-control">
            <% categories.forEach(function(cat){ %>
                <option value="<%= cat.slug %>"
                <% if (cat.slug == category) { %>
                selected="selected"
                <% } %>
                ><%= cat.title %></option>
            <% }); %>
        </select>
    </div>
</code>```

I want the values in the subcategory dropdown to be shown as per the option selected in the category dropdown.

I am getting the values from the backend. The JS file is as follows:-

```<code>router.get('/edit-product/:id',ensureAuthenticated, function (req, res) {

    MainCategory.find(function(err,mainCategories){

        Category.find(function (err, categories) {

            Product.findById(req.params.id, function (err, p) {
                if (err) {
                    console.log(err);
                    res.redirect('/admin/products');
                } else {
                    var galleryDir = 'public/assets/img/products/' + p._id + '/gallery';
                //  var recommendationDir = 'public/assets/img/products/' + p._id + '/recommendation';
                    var galleryImages = null;
                //  var recommendationImages = null;

                    fs.readdir(galleryDir, function (err, files) {
                        if (err) {
                            console.log(err);
                        } else {
                            galleryImages = files;
                           // console.log("The gallery image is" + galleryImages)
                           //console.log(p);
                            res.render('admin/edit_product', {

                                product:p,
                                title: p.title,
                                description: p.description,
                                categories: categories,
                                category: p.category.replace(/\s+/g, '-').toLowerCase(),
                                mainCategories: mainCategories,
                                mainCategory: p.mainCategory.replace(/\s+/g, '-').toLowerCase(),
                                mainImage: p.mainImage,
                                thumbImage1 : p.thumbImage1,
                                thumbImage2 : p.thumbImage2,
                                thumbImage3: p.thumbImage3,
                                recommendationImage1: p.recommendationImage1,
                                recommendationImage2: p.recommendationImage2,
                                recommendationImage3: p.recommendationImage3,
                                recommendationUrl1: p.recommendationUrl1,
                                recommendationUrl2: p.recommendationUrl2,
                                recommendationUrl3: p.recommendationUrl3,
                                galleryImages: galleryImages,
                                id: p._id,
                                productID:p.productID
                            });
                        }
                    });
                }
            });

        });
    })
});
</code>```

I am stuck in it a bit. Please help me out

答:
const categories = ['a', 'b', 'c'];
const subCategories = {
  a: ['a-1', 'a-2', 'a-3'],
  b: ['b-1', 'b-2', 'b-3'],
  c: ['c-1', 'c-2', 'c-3'],
};
const catSelect = document.getElementById('cat');
const subCatSelect = document.getElementById('subcat');

catSelect.innerHTML = categories.map(cat => `<option val=${cat}>${cat}</option>`).join('');
catSelect.addEventListener('change', setSubcategories);
setSubcategories();

function setSubcategories() {
  subCatSelect.innerHTML = subCategories[catSelect.value].map(cat => `<option val=${cat}>${cat}</option>`).join('');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select id="cat"></select>
<select id="subcat"></select></code>```

Body:
I was working on a dropdown list and wanted the results shown in the second dropdown to be filtered according to the option selected in the first dropdown.

My EJS file is as follows:-

        Category
        <select id="list" name="mainCategory" id="maincategory-dropdown" onchange="getSelectValue()" class="form-control">
            <% mainCategories.forEach(function(cat){ %>
                <option value="<%= cat.slug %>"
                <% if (cat.slug == mainCategory) { %>
                selected="selected"
                <% } %>
                ><%= cat.title %></option>
            <% }); %>
        </select>

        Subcategory
        <select name="category" id="category-dropdown" class="form-control">
            <% categories.forEach(function(cat){ %>
                <option value="<%= cat.slug %>"
                <% if (cat.slug == category) { %>
                selected="selected"
                <% } %>
                ><%= cat.title %></option>
            <% }); %>
        </select>

I want the values in the subcategory dropdown to be shown as per the option selected in the category dropdown.

I am getting the values from the backend. The JS file is as follows:-

router.get('/edit-product/:id',ensureAuthenticated, function (req, res) {

    MainCategory.find(function(err,mainCategories){

        Category.find(function (err, categories) {

            Product.findById(req.params.id, function (err, p) {
                if (err) {
                    console.log(err);
                    res.redirect('/admin/products');
                } else {
                    var galleryDir = 'public/assets/img/products/' + p._id + '/gallery';
                //  var recommendationDir = 'public/assets/img/products/' + p._id + '/recommendation';
                    var galleryImages = null;
                //  var recommendationImages = null;

                    fs.readdir(galleryDir, function (err, files) {
                        if (err) {
                            console.log(err);
                        } else {
                            galleryImages = files;
                           // console.log("The gallery image is" + galleryImages)
                           //console.log(p);
                            res.render('admin/edit_product', {

                                product:p,
                                title: p.title,
                                description: p.description,
                                categories: categories,
                                category: p.category.replace(/\s+/g, '-').toLowerCase(),
                                mainCategories: mainCategories,
                                mainCategory: p.mainCategory.replace(/\s+/g, '-').toLowerCase(),
                                mainImage: p.mainImage,
                                thumbImage1 : p.thumbImage1,
                                thumbImage2 : p.thumbImage2,
                                thumbImage3: p.thumbImage3,
                                recommendationImage1: p.recommendationImage1,
                                recommendationImage2: p.recommendationImage2,
                                recommendationImage3: p.recommendationImage3,
                                recommendationUrl1: p.recommendationUrl1,
                                recommendationUrl2: p.recommendationUrl2,
                                recommendationUrl3: p.recommendationUrl3,
                                galleryImages: galleryImages,
                                id: p._id,
                                productID:p.productID
                            });
                        }
                    });
                }
            });

        });
    })
});

I am stuck in it a bit. Please help me out

Body:
const categories = ['a', 'b', 'c'];
const subCategories = {
  a: ['a-1', 'a-2', 'a-3'],
  b: ['b-1', 'b-2', 'b-3'],
  c: ['c-1', 'c-2', 'c-3'],
};
const catSelect = document.getElementById('cat');
const subCatSelect = document.getElementById('subcat');

catSelect.innerHTML = categories.map(cat => `<option val=${cat}>${cat}</option>`).join('');
catSelect.addEventListener('change', setSubcategories);
setSubcategories();

function setSubcategories() {
  subCatSelect.innerHTML = subCategories[catSelect.value].map(cat => `<option val=${cat}>${cat}</option>`).join('');
}

<select id="cat"></select>
<select id="subcat"></select>


问:
SQL Join on the same table
```<code>Table T
P_ID | Name | Status
1      ABC    Ordered
1      ABC    Processing
1      ABC    Imported
2      PQR    Ordered
2      PQR    Failed
3      LMN    Ordered
</code>```

Expected Result

```<code>Table T
P_ID | Name | Status
2      PQR    Ordered
2      PQR    Failed
3      LMN    Ordered
</code>```

I am not getting the correct result with the following query. I want to find all the records that have status Ordered but do not have the status "Imported".

```<code>select c1.P_ID,c1.Name,c2.Status
from T c1, T c2
where c1.P_ID = c2.P_ID
c1.Status="Ordered" and c2.status != "Imported"
</code>```

Using Oracle 11g database

答:
```<code>select c1.P_ID, c1.Name, c1.Status
from T c1
where c1.Status = 'Ordered' and
      NOT EXISTS (SELECT 1
                  FROM T c2
                  WHERE c1.P_ID = c2.P_ID and c2.status = 'Imported'
                 );
</code>```

Title: SQL Join on the same table

Body:
Table T
P_ID | Name | Status
1      ABC    Ordered
1      ABC    Processing
1      ABC    Imported
2      PQR    Ordered
2      PQR    Failed
3      LMN    Ordered

Expected Result

Table T
P_ID | Name | Status
2      PQR    Ordered
2      PQR    Failed
3      LMN    Ordered

I am not getting the correct result with the following query. I want to find all the records that have status Ordered but do not have the status "Imported".

select c1.P_ID,c1.Name,c2.Status
from T c1, T c2
where c1.P_ID = c2.P_ID
c1.Status="Ordered" and c2.status != "Imported"

Using Oracle 11g database


问:
Count all possible combinations no matter the column order
I have a dataset which looks like

```<code>df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2
</code>```

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

```<code>     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....
</code>```

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

答:
Here is a base R solution

```<code>l <- Map(function(x) c(na.omit(x)),data.frame(t(df[1:6]),stringsAsFactors = FALSE))
lout <- Map(function(x) c(na.omit(x)),data.frame(t(dfout),stringsAsFactors = FALSE))

dfout$N <- sapply(lout, function(x) sum(as.numeric(df$X7)[sapply(l, function(v) all(x %in% v))]))
</code>```

such that

```<code>> dfout
   X1   X2   X3   X4   X5   X6  N
1   A <NA> <NA> <NA> <NA> <NA> 15
2   B <NA> <NA> <NA> <NA> <NA> 15
3   C <NA> <NA> <NA> <NA> <NA>  8
4   D <NA> <NA> <NA> <NA> <NA> 11
5   E <NA> <NA> <NA> <NA> <NA>  7
6   F <NA> <NA> <NA> <NA> <NA>  2
7   A    B <NA> <NA> <NA> <NA> 15
8   A    B    C <NA> <NA> <NA>  8
9   A    B    C    D <NA> <NA>  8
10  A    B    C    D    E <NA>  7
11  A    B    C    D    E    F  2
12  B    C <NA> <NA> <NA> <NA>  8
</code>```

DATA

```<code>df <- structure(list(X1 = structure(c(1L, 2L, 2L, 1L, 1L), .Label = c("A",
"B"), class = "factor"), X2 = structure(c(2L, 1L, 3L, 2L, 2L), .Label = c("A",
"B", "C"), class = "factor"), X3 = structure(c(2L, 2L, 3L, NA,
1L), .Label = c("C", "D", "E"), class = "factor"), X4 = structure(c(NA,
2L, 1L, NA, 3L), .Label = c("A", "C", "D"), class = "factor"),
    X5 = structure(c(NA, NA, 1L, NA, 2L), .Label = c("D", "E"
    ), class = "factor"), X6 = structure(c(NA, NA, NA, NA, 1L
    ), .Label = "F", class = "factor"), X7 = structure(c(3L,
    1L, 5L, 4L, 2L), .Label = c("1", "2", "3", "4", "5"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))

dfout <- structure(list(X1 = c("A", "B", "C", "D", "E", "F", "A", "A",
"A", "A", "A", "B"), X2 = c(NA, NA, NA, NA, NA, NA, "B", "B",
"B", "B", "B", "C"), X3 = c(NA, NA, NA, NA, NA, NA, NA, "C",
"C", "C", "C", NA), X4 = c(NA, NA, NA, NA, NA, NA, NA, NA, "D",
"D", "D", NA), X5 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, "E",
"E", NA), X6 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "F",
NA)), row.names = c(NA, -12L), class = "data.frame")
</code>```

Body:
I have a dataset which looks like

df <- data.frame(rbind(c("A","B","D",NA,NA,NA,3),
c("B","A","D","C",NA,NA,1),
c("B","C","E","A","D",NA,5),
c("A","B",NA,NA,NA,NA,4),
c("A","B","C","D","E","F",2)))

    X1      X2       X3        X4       X5        X6    N
    A        B        D        NA       NA        NA    3
    B        A        D        C        NA        NA    1
    B        C        E        A         D        NA    5
    A        B        NA       NA       NA        NA    4
    A        B        C        D         E         F    2

Where the column N is the number of times that combination happens.

and I want like to have a cumulative sum by unordered columns (no matter on which column the letter is located) such that:

     X1      X2       X3        X4       X5        X6     N
    A       NA        NA       NA        NA        NA     15
    B       NA        NA       NA        NA        NA     15
    C       NA        NA       NA        NA        NA     8
    D       NA        NA       NA        NA        NA     11
    E       NA        NA       NA        NA        NA     7
    F       NA        NA       NA        NA        NA     2
    A        B        NA       NA        NA        NA     15
    A        B        C        NA        NA        NA     8
    A        B        C        D         NA        NA     8
    A        B        C        D         E         NA     7
    A        B        C        D         E         F      1
    B        C        NA       NA        NA        NA     8
    ....

So the idea is to have all possible combinations and the frequency but taking into account that the order of appearance in Column is not relevant.

Body:
Here is a base R solution

l <- Map(function(x) c(na.omit(x)),data.frame(t(df[1:6]),stringsAsFactors = FALSE))
lout <- Map(function(x) c(na.omit(x)),data.frame(t(dfout),stringsAsFactors = FALSE))

dfout$N <- sapply(lout, function(x) sum(as.numeric(df$X7)[sapply(l, function(v) all(x %in% v))]))

such that

> dfout
   X1   X2   X3   X4   X5   X6  N
1   A <NA> <NA> <NA> <NA> <NA> 15
2   B <NA> <NA> <NA> <NA> <NA> 15
3   C <NA> <NA> <NA> <NA> <NA>  8
4   D <NA> <NA> <NA> <NA> <NA> 11
5   E <NA> <NA> <NA> <NA> <NA>  7
6   F <NA> <NA> <NA> <NA> <NA>  2
7   A    B <NA> <NA> <NA> <NA> 15
8   A    B    C <NA> <NA> <NA>  8
9   A    B    C    D <NA> <NA>  8
10  A    B    C    D    E <NA>  7
11  A    B    C    D    E    F  2
12  B    C <NA> <NA> <NA> <NA>  8

DATA

df <- structure(list(X1 = structure(c(1L, 2L, 2L, 1L, 1L), .Label = c("A",
"B"), class = "factor"), X2 = structure(c(2L, 1L, 3L, 2L, 2L), .Label = c("A",
"B", "C"), class = "factor"), X3 = structure(c(2L, 2L, 3L, NA,
1L), .Label = c("C", "D", "E"), class = "factor"), X4 = structure(c(NA,
2L, 1L, NA, 3L), .Label = c("A", "C", "D"), class = "factor"),
    X5 = structure(c(NA, NA, 1L, NA, 2L), .Label = c("D", "E"
    ), class = "factor"), X6 = structure(c(NA, NA, NA, NA, 1L
    ), .Label = "F", class = "factor"), X7 = structure(c(3L,
    1L, 5L, 4L, 2L), .Label = c("1", "2", "3", "4", "5"), class = "factor")), class = "data.frame", row.names = c(NA,
-5L))

dfout <- structure(list(X1 = c("A", "B", "C", "D", "E", "F", "A", "A",
"A", "A", "A", "B"), X2 = c(NA, NA, NA, NA, NA, NA, "B", "B",
"B", "B", "B", "C"), X3 = c(NA, NA, NA, NA, NA, NA, NA, "C",
"C", "C", "C", NA), X4 = c(NA, NA, NA, NA, NA, NA, NA, NA, "D",
"D", "D", NA), X5 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, "E",
"E", NA), X6 = c(NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, "F",
NA)), row.names = c(NA, -12L), class = "data.frame")


问:
How to filter GitHub issue search by linked pull request?
I am trying to participate more in open source projects so I find myself looking at the issues tab a lot. I would like to filter issues but make sure there is no linked pr that would resolve the issue. I find that I click on an issue and find there is already a PR in review. Is there a way to specify that filter?</p>

答:
From the GitHub help page:

repo:desktop/desktop is:open -linked:pr matches open issues in the desktop/desktop repository that are not linked to a pull request by a closing reference.

So, use -linked:pr in your search.


问:
Laravel Valiadtion array must have one element with a certain value
Imaging having the following input for a form request validation.

```<code>[
    'relations' =>
        [
            [
                'primary' => true,
            ],
            [
                'primary' => false,
            ],
        ],
],
</code>```

Is there any validation that makes it possible to secure that at least one of the relations models have primary set to true? More perfect if it could secure only one element is true. This problem seems like it could have existed before.

So if we only see the input for relations, this should pass.

```<code>[
    'primary' => true,
],
[
    'primary' => false,
],
</code>```

This should fail in validation.

```<code>[
    'primary' => false,
],
[
    'primary' => false,
],
</code>```

答:
Try an inline custom rule:

```<code>public function rules()
{
    return [
        'relations' => function ($attribute, $relations, $fail) {
            $hasPrimary = collect($relations)
                ->filter(function ($el) {
                    return $el['primary'];
                })
                ->isNotEmpty();

            if ( ! $hasPrimary)
            {
                $fail($attribute . ' need to have at least one element set as primary.');
            }
        },

        // the rest of your validation rules..
    ];
}
</code>```

Of course, you could extract this to a dedicated Rule object, but you get the idea.

Body:
Imaging having the following input for a form request validation.

[
    'relations' =>
        [
            [
                'primary' => true,
            ],
            [
                'primary' => false,
            ],
        ],
],

Is there any validation that makes it possible to secure that at least one of the relations models have primary set to true? More perfect if it could secure only one element is true. This problem seems like it could have existed before.

So if we only see the input for relations, this should pass.

[
    'primary' => true,
],
[
    'primary' => false,
],

This should fail in validation.

[
    'primary' => false,
],
[
    'primary' => false,
],

Body:
Try an inline custom rule:

public function rules()
{
    return [
        'relations' => function ($attribute, $relations, $fail) {
            $hasPrimary = collect($relations)
                ->filter(function ($el) {
                    return $el['primary'];
                })
                ->isNotEmpty();

            if ( ! $hasPrimary)
            {
                $fail($attribute . ' need to have at least one element set as primary.');
            }
        },

        // the rest of your validation rules..
    ];
}

Of course, you could extract this to a dedicated Rule object, but you get the idea.


答:
You can use the following code:</p>

```<code>select c1.P_ID,c1.Name,c1.Status
  from T c1
 where exists (select 1
                 from T
                where P_ID = c1.P_ID
                  and Status="Ordered"
                  and rownum = 1)
   and not exists (select 1
                     from T
                    where P_ID = c1.P_ID
                      and Status="Imported"
                      and rownum = 1)
</code>```

Title: SQL Join on the same table

Body:
You can use the following code:

select c1.P_ID,c1.Name,c1.Status
  from T c1
 where exists (select 1
                 from T
                where P_ID = c1.P_ID
                  and Status="Ordered"
                  and rownum = 1)
   and not exists (select 1
                     from T
                    where P_ID = c1.P_ID
                      and Status="Imported"
                      and rownum = 1)


问:
iterate array of object and save values
I have this objects in Javascript:

```<code>products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}
</code>```

I want to group the articles_ids in the same family.
I want get this result:

```<code>grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}
</code>```

I try with forEach and filter methods, but I dont know how to make this with perform mode.

答:
let grouped_products = {};

products.forEach(p => {
    grouped_products[p.family] = [...grouped_products[p.family], p.article_id];
})

// to make an array of object by family, as you wish
grouped_products =
    Object.keys(grouped_products).map(k => { family: k, articles_ids: grouped_products[k] });
```

Title: iterate array of object and save values

Body:
I have this objects in Javascript:

products = {
    {
      family : 'mugs', name :'black mug' , article_id : 1728
    },
    {
      family : 'tees', name :'red t-shirt' , article_id : 1332
    },
    {
      family : 'mugs', name :'tea white mug' , article_id : 2748
    },
    {
      family : 'tees', name :'green woman t-shirt' , article_id : 1332
    },
}

I want to group the articles_ids in the same family.
I want get this result:

grouped_products = {
    {
      family : 'mugs', articles_ids : '1728,2748' //only mugs articles ids
    },
    {
      family : 'tees', articles_ids : '1332,1332' //only tees articles ids
    },
}

I try with forEach and filter methods, but I dont know how to make this with perform mode.


问:
StringWriter or StringBuilder
What is the difference between StringWriter and StringBuilder and when should I use one or the other?

答: StringBuilder is used to mass string concatenation. It's more effective for more then 5 string, As far as i know, then String.Concat(). Also it can be used with specific format (.AppendFormat())

OwnerDisplayName: MAC

Title: StringWriter or StringBuilder

OwnerDisplayName: abatishchev


问:
Customize permissions of unpacked WAR in Tomcat
I can't seem to find this on here but it seems like it would be somewhat typical.
I am running Tomcat 6 on RHEL5

I want Tomcat to unpack my WAR with 774 permissions rather than the 754 permissions it uses by default.  Is there a way to specify this?  I looked though catalina.policy but did not see anything that related to this.

答:
This isn't controlled by Tomcat itself, it's controlled by the umask permissions of the user under which Tomcat runs.

See this forum thread for discussion of how to control that. For more clarification, superuser.com is a better place to ask.


问:
How to parse a string into a Java Date?
How do I parse a string like "Fri Feb 14 09:58:21 EST 2020" into a Date in Java ?

The closest example I can find is :

```<code>SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";

try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

}
catch (ParseException e) {
    e.printStackTrace();
}
</code>```

But it doesn't have the " EST " part, what's the right way to do it ?

答:
Your pattern is not correct, it contain many problems :

EEEE replace with EEE

, remove this because your string not have comma

, same thing for the second comma

replace the position of yyyy and put in the end

a remove as it is not used at all, and instead use z to match ETC

If you are using java-time you can parse your date using this pattern EEE MMM dd HH:mm:ss z yyyy :

```<code>DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss z yyyy",
        Locale.US);
ZonedDateTime zdt = ZonedDateTime.parse(str, formatter);
</code>```

Title: How to parse a string into a Java Date?

Body:
How do I parse a string like "Fri Feb 14 09:58:21 EST 2020" into a Date in Java ?

The closest example I can find is :

SimpleDateFormat formatter = new SimpleDateFormat("EEEE, MMM dd, yyyy HH:mm:ss a");
String dateInString = "Friday, Jun 7, 2013 12:10:56 PM";

try {

    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));

}
catch (ParseException e) {
    e.printStackTrace();
}

But it doesn't have the " EST " part, what's the right way to do it ?

Body:
Your pattern is not correct, it contain many problems :

EEEE replace with EEE

, remove this because your string not have comma

, same thing for the second comma

replace the position of yyyy and put in the end

a remove as it is not used at all, and instead use z to match ETC

If you are using java-time you can parse your date using this pattern EEE MMM dd HH:mm:ss z yyyy :

DateTimeFormatter formatter = DateTimeFormatter.ofPattern(
        "EEE MMM dd HH:mm:ss z yyyy",
        Locale.US);
ZonedDateTime zdt = ZonedDateTime.parse(str, formatter);


问:
c# save resources file as .resx xml file error
In my application i have a bunch of string definitions.
I have put them as within the resources of visual studio with the idea so that it would save as an xml .resx file. The reason for this, is that after deployment i would be able to change some string definitions when i need to for some reason.

So, i have set the resources properties build action to be "XamlAppDef" and the Custom tool is automatically set to "PublicResXFileCodeGenerator" by visual studio.
Furthermore i linked system.xaml in my project references.

Although the .resx file is automatically generated, i now get an error during compile:
The XAML MSBuild task only processes files that contain an '{http://schemas.microsoft.com/winfx/2006/xaml}Class' directive. Please refer to documentation for usage of ‘{http://schemas.microsoft.com/winfx/2006/xaml}Class’

i tried figuring out how to fix this, but i cant really seem to figure it out. Any thoughts ?

答: The XamlAppDef is exactly only for XAML, not RESX resources. Use the Content build action instead.


问:
How can I implement a class template function with a std::enable_if metafunction?
I have used the std::enable_if metafunction in my class template to specify that it is only allowed to generate classes for variables that have GameCard as a base class. This works fine on its own when I implement the functions inline. However, if I want to implement the template functions outside the header body I run into the issue that I can't figure out how to correctly specify the function that I want to implement.

Cut down example code:

```<code>#include <string>
#include <memory>
#include <vector>

struct GameCard {};

template<class T, class = std::enable_if_t<std::is_base_of<GameCard, T>::value>>
struct CardStack {
  std::vector<T> cards;
  bool Test();
};
</code>```

My IDE generates this as the function specification:

```<code>template<class T, class>
bool CardStack<T, <unnamed>>::Test() {
  return false;
}
</code>```

This is obviously wrong since I'm getting compiler errors. But I don't have a clue on how to do it right. Do any of you know how to do this right?

答:
The function member definition should be something like:

```<code>template <class T, class U>
bool CardStack<T, U>::Test() {
    // body of function
}
</code>```

Live example

The explanation is pretty straightforward, there is no back magic here.
Just follow the normal syntactic rules of C++.

The definition of your class is a template class with two template parameters:

```<code>template<class, class>
struct CardStack { /* ... */ };
</code>```

T is the name of the first one.
On the other hand, the second does not have any type-name, but only a default type (= ...).
Default type (similarly to default arguments for functions) does not have to be specified in the definition.

Therefore, the each method definition should be in the form:

```<code>template <class T, class U>
bool CardStack<T, U>::MethodName() {}
</code>```

Body:
I have used the std::enable_if metafunction in my class template to specify that it is only allowed to generate classes for variables that have GameCard as a base class. This works fine on its own when I implement the functions inline. However, if I want to implement the template functions outside the header body I run into the issue that I can't figure out how to correctly specify the function that I want to implement.

Cut down example code:

#include <string>
#include <memory>
#include <vector>

struct GameCard {};

template<class T, class = std::enable_if_t<std::is_base_of<GameCard, T>::value>>
struct CardStack {
  std::vector<T> cards;
  bool Test();
};

My IDE generates this as the function specification:

template<class T, class>
bool CardStack<T, <unnamed>>::Test() {
  return false;
}

This is obviously wrong since I'm getting compiler errors. But I don't have a clue on how to do it right. Do any of you know how to do this right?

Body:
The function member definition should be something like:

template <class T, class U>
bool CardStack<T, U>::Test() {
    // body of function
}

Live example

The explanation is pretty straightforward, there is no back magic here.
Just follow the normal syntactic rules of C++.

The definition of your class is a template class with two template parameters:

template<class, class>
struct CardStack { /* ... */ };

T is the name of the first one.
On the other hand, the second does not have any type-name, but only a default type (= ...).
Default type (similarly to default arguments for functions) does not have to be specified in the definition.

Therefore, the each method definition should be in the form:

template <class T, class U>
bool CardStack<T, U>::MethodName() {}


问:
Parse stdout of containers in Openshift
I'm a bit of a noob when it comes to Openshift/Kubernetes, so I hope that I can explain my use case well enough.

I have a Docker image of a small "program", it can be summarised as the following: it tails -f a log file, and when something that matches a regex specified in config is found, it sends an email to someone. Something like monitoring a production log of an application and sending an email with a stacktrace to the Ops team if one is printed in the application log.

This works fine when my application log is produced via let's say a Java EE on Weblogic app running on the host, or a log produced by another docker container but saved to a bind mounted filesystem, therefore accessible (if mounted) by the "monitoring" container.

Now I need to deploy this image to monitor 2-3 microservices running in Openshift. These microservices log to stdout, and I do not have privileges to mount a path owned by root like /var/lib/docker/containers/[container-id]/[container-id]-json.log to the "monitoring" container.

What is the best way to be able to parse the microservices logs? I am allowed to change their logback config to have them log to stdout AND to an emptyDir volume for example, and create a Pod with the microservice+volume+monitoring container.

Thank you everyone for your suggestions,
Roberto

答:
There's fluentd for Docker as log agreggator. However, you cannot install only fluentd with openshift's ansible installer (see deploying-efk). You can install fluentd logging driver on docker host manually (see fluentd-logging-driver). There's 'getting started' about docker host configuration.
Then you can use any output plugin to store logs</p>

Title: Parse stdout of containers in Openshift


问:
Remove old project dbs from macbook
During my time in school and creating my own applications, I've had to delete projects from my laptop to free up space. Is there a way to remove the db from said deleted projects if the project is no longer on my computer? I've had an issue before , when I was starting out that I had to delete my project and start over. But I had forgotten to drop the db. So when I went to create the project again with the same name, it told me the db already exists.

So is there a way to remove stale dbs that do not correspond to a project anymore?

EDIT Sorry, I may need to clarfy. I am trying to clear up space on my laptop by remove old dbs that I forgot to drop before deleting the project folder. I no longer remember the names of the deleted projects

答:
If you use postgres just log in as your Postgres user and run \l
You are going to see all the DBs you have, and then could drop them with: dropdb 'database name'.

More info: https://stackoverflow.com/a/7073852/7611168

Title: Remove old project dbs from macbook


问:
RMarkdown - Is there a way to easily add space after each tabset?
I'm using R Markdown to create reports, and I use tabsets (.{tabset}) to show several results, without having to print them one below the other. Like this:

```<code># First session {.tabset}

## A
First result

## B
Second result

# Next session
</code>```

Now, let's say I want 4 line breaks before my second session, as I used tabset, I have to specify the line breaks after each tabset. Like this:

```<code># First session {.tabset}

## A
First result
<br /><br /><br /><br />

## B
Second result
<br /><br /><br /><br />

# Next session
</code>```

With 2 tabsets, it's ok, but sometimes I have 10 or more. Q/ Is there a way to add the line breaks only once, before the next session, without having to repeat the specification under each tabset ?

答:
You can address this using CSS.
By adding bottom margin on the tab-content HTML element, you systematically create white space there. To do this, add the style part on top of your markdown file. You may choose the optimal amount of pixels for your need</p>

```<code><style>
.tab-content{
    margin-bottom: 50px;
}
</style>
# First session {.tabset}

## A
First result

## B
Second result

# Next session
</code>```

Body:
I'm using R Markdown to create reports, and I use tabsets (.{tabset}) to show several results, without having to print them one below the other. Like this:

# First session {.tabset}

## A
First result

## B
Second result

# Next session

Now, let's say I want 4 line breaks before my second session, as I used tabset, I have to specify the line breaks after each tabset. Like this:

# First session {.tabset}

## A
First result

## B
Second result

# Next session

With 2 tabsets, it's ok, but sometimes I have 10 or more. Q/ Is there a way to add the line breaks only once, before the next session, without having to repeat the specification under each tabset ?

Body:
You can address this using CSS.
By adding bottom margin on the tab-content HTML element, you systematically create white space there. To do this, add the style part on top of your markdown file. You may choose the optimal amount of pixels for your need

<style>
.tab-content{
    margin-bottom: 50px;
}
</style>
# First session {.tabset}

## A
First result

## B
Second result

# Next session


问:
javascript how insert "empty" to array?

var array = new Array(5);
array[0] = 1;
array[1] = 1;
array[3] = 1;
array[4] = 1;
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //false
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true```
</div>
</div>
</p>

<p>I want to insert array that have unsetted element.</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>var array = [1,1]
var arrayToInsert = new Array(3);
arrayToInsert[0] = 1;
arrayToInsert[2] = 1;
array.splice(1, 0, ...arrayToInsert);
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //true, I want to make it false.
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true</code>```

How keep unsetted element after I splice(insert) array that have unsetted element?

答:
If you want to insert a value meaning "empty" into an array, simply assign the special value of undefined to your chosen position in the array.

var array = ['a','b', 'c', 'd', 'e']
var arrayToInsert = ['', undefined, '⛱']

array.splice(1, 0, ...arrayToInsert)

console.log(array)
console.log(Object.keys(array))
console.log(array.length)```

When you see the word "empty" written in the console, is used by Chrome to indicate the absence of a property corresponding to an index.

Note that the printing of the word "empty" to the console is a peculiarity of Chrome and is not part of the JavaScript standard.

To remove one of the index properties from an array, you use the delete keyword.

Note how doing so looks different in the consoles of Chrome, Safari and Firefox:

Title: javascript how insert "empty" to array?

Body:
var array = new Array(5);
array[0] = 1;
array[1] = 1;
array[3] = 1;
array[4] = 1;
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //false
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true

I want to insert array that have unsetted element.

var array = [1,1]
var arrayToInsert = new Array(3);
arrayToInsert[0] = 1;
arrayToInsert[2] = 1;
array.splice(1, 0, ...arrayToInsert);
console.log(array.hasOwnProperty(0)); //true
console.log(array.hasOwnProperty(1)); //true
console.log(array.hasOwnProperty(2)); //true, I want to make it false.
console.log(array.hasOwnProperty(3)); //true
console.log(array.hasOwnProperty(4)); //true

How keep unsetted element after I splice(insert) array that have unsetted element?

Body:
If you want to insert a value meaning "empty" into an array, simply assign the special value of undefined to your chosen position in the array.

var array = ['a','b', 'c', 'd', 'e']
var arrayToInsert = ['', undefined, '⛱']

array.splice(1, 0, ...arrayToInsert)

console.log(array)
console.log(Object.keys(array))
console.log(array.length)

When you see the word "empty" written in the console, is used by Chrome to indicate the absence of a property corresponding to an index.

Note that the printing of the word "empty" to the console is a peculiarity of Chrome and is not part of the JavaScript standard.

To remove one of the index properties from an array, you use the delete keyword.

Note how doing so looks different in the consoles of Chrome, Safari and Firefox: