问:
KieBuilderImpl.buildAll fails with NullPointerException
I have been struggling since many days to resolve the below NullPointerException. are there any configuration that I am missing?

```<code>Caused by: java.lang.NullPointerException
        at org.kie.internal.io.ResourceFactory.newByteArrayResource(ResourceFactory.java:66)
        at org.drools.compiler.kie.builder.impl.AbstractKieModule.getResource(AbstractKieModule.java:303)
        at org.drools.compiler.kie.builder.impl.AbstractKieModule.addResourceToCompiler(AbstractKieModule.java:268)
        at org.drools.compiler.kie.builder.impl.AbstractKieModule.addResourceToCompiler(AbstractKieModule.java:263)
        at org.drools.compiler.kie.builder.impl.AbstractKieProject.buildKnowledgePackages(AbstractKieProject.java:243)
        at org.drools.compiler.kie.builder.impl.AbstractKieProject.verify(AbstractKieProject.java:74)
        at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildKieProject(KieBuilderImpl.java:353)
        at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildAll(KieBuilderImpl.java:265)
        at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildAll(KieBuilderImpl.java:209)
</code>```

Below are steps I am following, program fails at kieBuilder.buildAll() line:

```<code>           KieServices kieServices = KieServices.Factory.get();
            KieResources kieResources = kieServices.getResources();
            KieFileSystem kfs = kieServices.newKieFileSystem();
            KieRepository kr = kieServices.getRepository();
 Resource res = kieResources.newByteArrayResource(drlFile.getBytes()).setResourceType(ResourceType.DRL).setSourcePath("test.drl");

kfs.write(res);

 KieBuilder kieBuilder = kieServices.newKieBuilder(kfs,this.getClass().getClassLoader());
            kieBuilder.buildAll();
</code>```

Maven dependency:

```<code>   <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-core</artifactId>
        <version>7.7.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-compiler</artifactId>
        <version>7.7.0.Final</version>
    </dependency>
</code>```

Thanks! Appreicate your help.

答:
We found that this issue comes when kie.conf in 7.X series Drools, when you are creating a fat jar , eg: using shadowJar task in gradle, the kie.conf file does not get merged.

The way to resolve it is update the shadowJar task:

```<code> apply plugin: 'com.github.johnrengelman.shadow'
shadowJar {
    zip64 true
    mergeServiceFiles {
        path = 'META-INF'
    }

}
</code>```

Body:
I have been struggling since many days to resolve the below NullPointerException. are there any configuration that I am missing?

Caused by: java.lang.NullPointerException
        at org.kie.internal.io.ResourceFactory.newByteArrayResource(ResourceFactory.java:66)
        at org.drools.compiler.kie.builder.impl.AbstractKieModule.getResource(AbstractKieModule.java:303)
        at org.drools.compiler.kie.builder.impl.AbstractKieModule.addResourceToCompiler(AbstractKieModule.java:268)
        at org.drools.compiler.kie.builder.impl.AbstractKieModule.addResourceToCompiler(AbstractKieModule.java:263)
        at org.drools.compiler.kie.builder.impl.AbstractKieProject.buildKnowledgePackages(AbstractKieProject.java:243)
        at org.drools.compiler.kie.builder.impl.AbstractKieProject.verify(AbstractKieProject.java:74)
        at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildKieProject(KieBuilderImpl.java:353)
        at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildAll(KieBuilderImpl.java:265)
        at org.drools.compiler.kie.builder.impl.KieBuilderImpl.buildAll(KieBuilderImpl.java:209)

Below are steps I am following, program fails at kieBuilder.buildAll() line:

           KieServices kieServices = KieServices.Factory.get();
            KieResources kieResources = kieServices.getResources();
            KieFileSystem kfs = kieServices.newKieFileSystem();
            KieRepository kr = kieServices.getRepository();
 Resource res = kieResources.newByteArrayResource(drlFile.getBytes()).setResourceType(ResourceType.DRL).setSourcePath("test.drl");

kfs.write(res);

 KieBuilder kieBuilder = kieServices.newKieBuilder(kfs,this.getClass().getClassLoader());
            kieBuilder.buildAll();

Maven dependency:

   <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-core</artifactId>
        <version>7.7.0.Final</version>
    </dependency>

    <dependency>
        <groupId>org.drools</groupId>
        <artifactId>drools-compiler</artifactId>
        <version>7.7.0.Final</version>
    </dependency>

Thanks! Appreicate your help.

Body:
We found that this issue comes when kie.conf in 7.X series Drools, when you are creating a fat jar , eg: using shadowJar task in gradle, the kie.conf file does not get merged.

The way to resolve it is update the shadowJar task:

 apply plugin: 'com.github.johnrengelman.shadow'
shadowJar {
    zip64 true
    mergeServiceFiles {
        path = 'META-INF'
    }

}


来源: stackexchange

问:
DL4J UI: How to display cost error of the validation test?
I use DL4J and I attach the UI.
How can I display on UI the cost error of the validation set?
What have I to configure?

I have to check if there is overfitting but the UI display only the cost error of the training set. See the image attached below

DL4J version: 1.0.0-beta3

答:
The separation of the training and test set has to be taken care of by the developer, so you have to provide the validation set just like you provided the training set. </p>

<p>The process is pretty much the same after that. </p>

ContentLicense: CC BY-SA 4.0

Body:
The separation of the training and test set has to be taken care of by the developer, so you have to provide the validation set just like you provided the training set.

The process is pretty much the same after that.


问:
Api-platform: corsAllowOrigin doesn't set *
Oke so back to https://api-platform.com :)

So I currently have corsAllowOrigin: "*" #to allow all origins in my helm values file (as per docs). To make sure that the propper headers are bieng set on return values.

Now I would expect (as per docs) that the Access-Control-Allow-Origin: would now go to "*" however it goes to Access-Control-Allow-Origin: null. That's of course a bit annoying because it prevent react native apps of accessing the API.

Question here, is this a bug? Am I using the wrong values? Or overlooking something?

答:
Sets .env file with:</p>

```<code>###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=['*']
###< nelmio/cors-bundle ###
</code>```

Body:
Sets .env file with:

###> nelmio/cors-bundle ###
CORS_ALLOW_ORIGIN=['*']
###< nelmio/cors-bundle ###


问:
Postgresql get first True value for the aggregated variable
Let's say I have the following table. Please consider all three versions:

Version 1:

```<code>Aggr_ID     ID      boolean_value
123         123     False
123         124     True
123         125     False
123         126     True
</code>```

Version 2:

```<code>Aggr_ID     ID      boolean_value
123         123     True
123         124     False
123         125     False
123         126     False
</code>```

Version 3:

```<code>Aggr_ID     ID      boolean_value
123         123     False
123         124     False
123         125     False
123         126     False
</code>```

What I would like to get is the following table for cases 1 and 2:

```<code>Aggr_ID     boolean_value
123         True
</code>```

and the following table for the case no. 3:

```<code>Aggr_ID     boolean_value
123         False
</code>```

The idea is that if there's at least one True in the boolean_value column the aggregated ID should be associated with True.

I truly don't know how to approach this problem so please excuse me for the lack of my code.

答:
You can use bool_or() when you group by Aggr_ID:

```<code>select
  Aggr_ID,
  bool_or(boolean_value) boolean_value
from tablename
group by Aggr_ID
</code>```

Body:
Let's say I have the following table. Please consider all three versions:

Version 1:

Aggr_ID     ID      boolean_value
123         123     False
123         124     True
123         125     False
123         126     True

Version 2:

Aggr_ID     ID      boolean_value
123         123     True
123         124     False
123         125     False
123         126     False

Version 3:

Aggr_ID     ID      boolean_value
123         123     False
123         124     False
123         125     False
123         126     False

What I would like to get is the following table for cases 1 and 2:

Aggr_ID     boolean_value
123         True

and the following table for the case no. 3:

Aggr_ID     boolean_value
123         False

The idea is that if there's at least one True in the boolean_value column the aggregated ID should be associated with True.

I truly don't know how to approach this problem so please excuse me for the lack of my code.

Body:
You can use bool_or() when you group by Aggr_ID:

select
  Aggr_ID,
  bool_or(boolean_value) boolean_value
from tablename
group by Aggr_ID


问:
Squash Git Branch Commits in Android Studio
I prefer to use the Android Studio VCS UI as much as possible. Currently when I have to squash commits, I have to go through the command line and even open up a command line editor (with the git rebase -i command).

I was hoping that there was a clean way to do this through a Visual Studio UI. Is there one?

答:
I am adding the whole process for squashing commit here, just in case.

Click on the version control on the bottom toolbar(cmd+9)

Select log tab

Select the base commit and right click on it.

Select Interactively Rebase from here as shown by @Crain

In the next window, select squash from the drop down for the commits you want to squash.

ContentLicense: CC BY-SA 3.0


问:
Find the number of days using date picker and current date
I am Trying to get the difference between the number of days. using date picker dialog with the current date

```<code>datepicker = findViewById(R.id.date_picker_date);
        textView=findViewById(R.id.textView);

        datepicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar cldr = Calendar.getInstance();
                int day = cldr.get(Calendar.DAY_OF_MONTH);
                int month = cldr.get(Calendar.MONTH);
                int year = cldr.get(Calendar.YEAR);

                String date = day + "/" + (month+1) + "/" + year;

                TextView textView=findViewById(R.id.textView);
                textView.setText(date);

                datepicker.setInputType(InputType.TYPE_NULL);
                datepicker.setShowSoftInputOnFocus(false);

                // date picker dialog
                picker = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                            {
                                datepicker.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                picker.show();
</code>```

Not getting the difference between the picking date and current date

答:
I have used below code and it works fine for me. Works for lower versions as well. Try this

```<code>public static DateBean getDateDifferenceInDDMMYYYY(Date from, Date to)
{
    Calendar fromDate=Calendar.getInstance();
    Calendar toDate=Calendar.getInstance();
    fromDate.setTime(from);
    toDate.setTime(to);
    int increment = 0;
    int year,month,day;

    System.out.println(fromDate.getActualMaximum(Calendar.DAY_OF_MONTH));

    if (fromDate.get(Calendar.DAY_OF_MONTH) > toDate.get(Calendar.DAY_OF_MONTH))
    {
        increment =fromDate.getActualMaximum(Calendar.DAY_OF_MONTH);
    }
    System.out.println("increment"+increment);

    // DAY CALCULATION
    if (increment != 0) {
        day = (toDate.get(Calendar.DAY_OF_MONTH) + increment) - fromDate.get(Calendar.DAY_OF_MONTH);
        increment = 1;
    } else {
        day = toDate.get(Calendar.DAY_OF_MONTH) - fromDate.get(Calendar.DAY_OF_MONTH);
    }

    // MONTH CALCULATION
    if ((fromDate.get(Calendar.MONTH) + increment) > toDate.get(Calendar.MONTH)) {
        month = (toDate.get(Calendar.MONTH) + 12) - (fromDate.get(Calendar.MONTH) + increment);
        increment = 1;
    } else {
        month = (toDate.get(Calendar.MONTH)) - (fromDate.get(Calendar.MONTH) + increment);
        increment = 0;
    }

    // YEAR CALCULATION
    year = toDate.get(Calendar.YEAR) - (fromDate.get(Calendar.YEAR) + increment);

    DateBean dateDifference = new DateBean(""+year, ""+month, ""+day);

    System.out.println(year+"\tYears\t\t"+month+"\tMonths\t\t"+day+"Days");
    return dateDifference;
}
</code>```

and your DateBean as below

```<code>public class DateBean
{
    String year, months, days;

    public DateBean(String year, String months, String days)
    {
        this.year = year;
        this.months = months;
        this.days = days;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getMonths() {
        return months;
    }

    public void setMonths(String months) {
        this.months = months;
    }

    public String getDays() {
        return days;
    }

    public void setDays(String days) {
        this.days = days;
    }
}
</code>```

Body:
I am Trying to get the difference between the number of days. using date picker dialog with the current date

datepicker = findViewById(R.id.date_picker_date);
        textView=findViewById(R.id.textView);

        datepicker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar cldr = Calendar.getInstance();
                int day = cldr.get(Calendar.DAY_OF_MONTH);
                int month = cldr.get(Calendar.MONTH);
                int year = cldr.get(Calendar.YEAR);

                String date = day + "/" + (month+1) + "/" + year;

                TextView textView=findViewById(R.id.textView);
                textView.setText(date);

                datepicker.setInputType(InputType.TYPE_NULL);
                datepicker.setShowSoftInputOnFocus(false);

                // date picker dialog
                picker = new DatePickerDialog(MainActivity.this,
                        new DatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
                            {
                                datepicker.setText(dayOfMonth + "/" + (monthOfYear + 1) + "/" + year);
                            }
                        }, year, month, day);
                picker.show();

Not getting the difference between the picking date and current date

Body:
I have used below code and it works fine for me. Works for lower versions as well. Try this

public static DateBean getDateDifferenceInDDMMYYYY(Date from, Date to)
{
    Calendar fromDate=Calendar.getInstance();
    Calendar toDate=Calendar.getInstance();
    fromDate.setTime(from);
    toDate.setTime(to);
    int increment = 0;
    int year,month,day;

    System.out.println(fromDate.getActualMaximum(Calendar.DAY_OF_MONTH));

    if (fromDate.get(Calendar.DAY_OF_MONTH) > toDate.get(Calendar.DAY_OF_MONTH))
    {
        increment =fromDate.getActualMaximum(Calendar.DAY_OF_MONTH);
    }
    System.out.println("increment"+increment);

    // DAY CALCULATION
    if (increment != 0) {
        day = (toDate.get(Calendar.DAY_OF_MONTH) + increment) - fromDate.get(Calendar.DAY_OF_MONTH);
        increment = 1;
    } else {
        day = toDate.get(Calendar.DAY_OF_MONTH) - fromDate.get(Calendar.DAY_OF_MONTH);
    }

    // MONTH CALCULATION
    if ((fromDate.get(Calendar.MONTH) + increment) > toDate.get(Calendar.MONTH)) {
        month = (toDate.get(Calendar.MONTH) + 12) - (fromDate.get(Calendar.MONTH) + increment);
        increment = 1;
    } else {
        month = (toDate.get(Calendar.MONTH)) - (fromDate.get(Calendar.MONTH) + increment);
        increment = 0;
    }

    // YEAR CALCULATION
    year = toDate.get(Calendar.YEAR) - (fromDate.get(Calendar.YEAR) + increment);

    DateBean dateDifference = new DateBean(""+year, ""+month, ""+day);

    System.out.println(year+"\tYears\t\t"+month+"\tMonths\t\t"+day+"Days");
    return dateDifference;
}

and your DateBean as below

public class DateBean
{
    String year, months, days;

    public DateBean(String year, String months, String days)
    {
        this.year = year;
        this.months = months;
        this.days = days;
    }

    public String getYear() {
        return year;
    }

    public void setYear(String year) {
        this.year = year;
    }

    public String getMonths() {
        return months;
    }

    public void setMonths(String months) {
        this.months = months;
    }

    public String getDays() {
        return days;
    }

    public void setDays(String days) {
        this.days = days;
    }
}


问:
Promise.all getting Unhandled rejection
I'm using Promise.all and catch error but still getting Unhandled rejection

```<code>const Promise = require('bluebird');

function sleep(milis) {
return new Promise(function(resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
});
}

function test() {

try {
    let lists = [2000, 1000, 3000]
    Promise.all(
            lists.map(record => {
                try {
                    sleep(record)
                } catch (err) {
                    console.log('Error inside catch block1', err)
                    throw err
                }
            })
        ).then(data => {
            console.log('Resolved', data)
        })
        .catch(err => {
            console.log('Error inside catch block2', err)
            throw err

        });

} catch (err) {
    console.log('Error inside catch block3', err)
}
}

test();
</code>```

After using catch block why still getting Unhandled rejection. Any help appreciated. But if I use async await not getting Unhandled rejection.

答:
TL;DR: throw err inside .catch handlers are not caught by any other catch in your code, so you get unhandled promise rejections.

First of all, in this code snippet

lists.map(record => {
  try {
    sleep(record)
  } catch (err) {
    console.log('Error inside catch block1', err)
    throw err
  }
})
```

the result of the .map will be [undefined, undefined, undefined], since the function does not return any value. You need to write return sleep(record) if you want it to return a promise for each list element.

Then, please note that the main catch block is executed before .then/.catch handlers of Promise.all. If you add console.log after your main catch block, you'll see it. That means that the exceptions you are re-throwing in your .catch handlers are not caught by anything, and are shown as unhandled.

Title: Promise.all getting Unhandled rejection

Body:
I'm using Promise.all and catch error but still getting Unhandled rejection

const Promise = require('bluebird');

function sleep(milis) {
return new Promise(function(resolve, reject) {
    if (milis == 1000) {
        console.log('Rejecting millis', milis)
        setTimeout(() => {
            reject('Got error')
        }, milis);

    } else {
        console.log('Processing millis', milis)
        setTimeout(() => {
            resolve(milis);
        }, milis);

    }
});
}

function test() {

try {
    let lists = [2000, 1000, 3000]
    Promise.all(
            lists.map(record => {
                try {
                    sleep(record)
                } catch (err) {
                    console.log('Error inside catch block1', err)
                    throw err
                }
            })
        ).then(data => {
            console.log('Resolved', data)
        })
        .catch(err => {
            console.log('Error inside catch block2', err)
            throw err

        });

} catch (err) {
    console.log('Error inside catch block3', err)
}
}

test();

After using catch block why still getting Unhandled rejection. Any help appreciated. But if I use async await not getting Unhandled rejection.

Body:
TL;DR: throw err inside .catch handlers are not caught by any other catch in your code, so you get unhandled promise rejections.

First of all, in this code snippet

lists.map(record => {
  try {
    sleep(record)
  } catch (err) {
    console.log('Error inside catch block1', err)
    throw err
  }
})

the result of the .map will be [undefined, undefined, undefined], since the function does not return any value. You need to write return sleep(record) if you want it to return a promise for each list element.

Then, please note that the main catch block is executed before .then/.catch handlers of Promise.all. If you add console.log after your main catch block, you'll see it. That means that the exceptions you are re-throwing in your .catch handlers are not caught by anything, and are shown as unhandled.


问:
The push & reveal type of ion-menu does not work
I've been trying the ion-menu of Ionic 3. The "type=overlay" function works properly as the side menu overlays the screen, yet neither "push" nor "reveal" values for "type" attribute seem to be working.

When I click the button, nothing happens, but the button is sure clicked as I've checked. I have not tried them in an emulator/phone if they work. But the ionic-documents on it shows it can be tested on browser.

```<code><ion-menu side="start" menuId="first" [content]="content" type="push">
  <ion-header>
    <ion-toolbar color="primary">
      <ion-title>Start Menu</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content #content>
    <ion-list>
      <ion-item>Menu Item</ion-item>
      <ion-item>Menu Item</ion-item>
    </ion-list>
  </ion-content>
</ion-menu>

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
    <ion-buttons end>
      <button ion-button menuToggle (click)="openFirst()"><ion-icon name="add"></ion-icon></button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>
  content
</ion-content>
</code>```

.

```<code>import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,
    private menu: MenuController) {

  }

  openFirst() {
    this.menu.enable(true, 'first');
    this.menu.open('first');
  }
}
</code>```

I expect this code the push the entire page and reveal the side bar menu, but it does nothing.

答:
Button click function is not required as menuToggle is used :

```<code><ion-header>
  <ion-navbar>
     <ion-title>Home</ion-title>
     <ion-buttons end>
       <button ion-button menuToggle ><ion-icon name="add">
         </ion-icon></button>
     </ion-buttons>
 </ion-navbar>
</ion-header>
</code>```

Also check this link.
I have implemented menu type.

https://stackblitz.com/edit/ionic-4j3yqp?file=app/app.html

Body:
I've been trying the ion-menu of Ionic 3. The "type=overlay" function works properly as the side menu overlays the screen, yet neither "push" nor "reveal" values for "type" attribute seem to be working.

When I click the button, nothing happens, but the button is sure clicked as I've checked. I have not tried them in an emulator/phone if they work. But the ionic-documents on it shows it can be tested on browser.

<ion-menu side="start" menuId="first" [content]="content" type="push">
  <ion-header>
    <ion-toolbar color="primary">
      <ion-title>Start Menu</ion-title>
    </ion-toolbar>
  </ion-header>
  <ion-content #content>
    <ion-list>
      <ion-item>Menu Item</ion-item>
      <ion-item>Menu Item</ion-item>
    </ion-list>
  </ion-content>
</ion-menu>

<ion-header>
  <ion-navbar>
    <ion-title>Home</ion-title>
    <ion-buttons end>
      <button ion-button menuToggle (click)="openFirst()"><ion-icon name="add"></ion-icon></button>
    </ion-buttons>
  </ion-navbar>
</ion-header>

<ion-content>
  content
</ion-content>

.

import { Component } from '@angular/core';
import { NavController, MenuController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(public navCtrl: NavController,
    private menu: MenuController) {

  }

  openFirst() {
    this.menu.enable(true, 'first');
    this.menu.open('first');
  }
}

I expect this code the push the entire page and reveal the side bar menu, but it does nothing.

Body:
Button click function is not required as menuToggle is used :

<ion-header>
  <ion-navbar>
     <ion-title>Home</ion-title>
     <ion-buttons end>
       <button ion-button menuToggle ><ion-icon name="add">
         </ion-icon></button>
     </ion-buttons>
 </ion-navbar>
</ion-header>

Also check this link.
I have implemented menu type.

https://stackblitz.com/edit/ionic-4j3yqp?file=app/app.html


问:
file merge logic: scala
For scala experts this might be a silly question but me as a beginner facing hard time to identify the solution. Any pointers would help.

I've set of 3 files in HDFS location by the names:

```<code>fileFirst.dat
fileSecond.dat
fileThird.dat
</code>```

Not necessarily they'll be stored in any order. fileFirst.dat could be created at very last so a ls every time would show different ordering of the files.

My task is to combine all files in a single file in the order:
fileFirst contents, then fileSecond contents & finally fileThird contents; with newline as the separator, no spaces.

I tried some ideas but couldn't come up with something working. Every time the order of combination messes up.

Below is my function to merge whatever is coming in:

```<code>  def writeFile(): Unit = {
    val in: InputStream = fs.open(files(i).getPath)
    try {
      IOUtils.copyBytes(in, out, conf, false)
      if (addString != null) out.write(addString.getBytes("UTF-8"))
    } finally in.close()
}
</code>```

Files is defined like this:

```<code>val files: Array[FileStatus] = fs.listStatus(srcPath)
</code>```

This is part of a bigger function where I'm passing all the arguments used in this method. After everything is done, I'll do the out.close() to close the output stream.

Any ideas welcome, even if it goes against the file write logic I'm trying to do; just understand that I'm not that good in scala; for now :)

答:
If you can enumerate your Paths directly, you don't really need to use listStatus. You could try something like this (untested):

```<code>val relativePaths = Array("fileFirst.dat", "fileSecond.dat", "fileThird.dat")
val paths = relativePaths.map(new Path(srcDirectory, _))
try {
    val output = fs.create(destinationFile)
    for (path <- paths) {
        try {
            val input = fs.open(path)
            IOUtils.copyBytes(input, output, conf, false)
        } catch {
            case ex => throw ex // Feel free to do some error handling here
        } finally {
            input.close()
        }
    }
} catch {
    case ex => throw ex // Feel free to do some error handling here
} finally {
    output.close()
}
</code>```

Title: file merge logic: scala

Body:
For scala experts this might be a silly question but me as a beginner facing hard time to identify the solution. Any pointers would help.

I've set of 3 files in HDFS location by the names:

fileFirst.dat
fileSecond.dat
fileThird.dat

Not necessarily they'll be stored in any order. fileFirst.dat could be created at very last so a ls every time would show different ordering of the files.

My task is to combine all files in a single file in the order:
fileFirst contents, then fileSecond contents & finally fileThird contents; with newline as the separator, no spaces.

I tried some ideas but couldn't come up with something working. Every time the order of combination messes up.

Below is my function to merge whatever is coming in:

  def writeFile(): Unit = {
    val in: InputStream = fs.open(files(i).getPath)
    try {
      IOUtils.copyBytes(in, out, conf, false)
      if (addString != null) out.write(addString.getBytes("UTF-8"))
    } finally in.close()
}

Files is defined like this:

val files: Array[FileStatus] = fs.listStatus(srcPath)

This is part of a bigger function where I'm passing all the arguments used in this method. After everything is done, I'll do the out.close() to close the output stream.

Any ideas welcome, even if it goes against the file write logic I'm trying to do; just understand that I'm not that good in scala; for now :)

Body:
If you can enumerate your Paths directly, you don't really need to use listStatus. You could try something like this (untested):

val relativePaths = Array("fileFirst.dat", "fileSecond.dat", "fileThird.dat")
val paths = relativePaths.map(new Path(srcDirectory, _))
try {
    val output = fs.create(destinationFile)
    for (path <- paths) {
        try {
            val input = fs.open(path)
            IOUtils.copyBytes(input, output, conf, false)
        } catch {
            case ex => throw ex // Feel free to do some error handling here
        } finally {
            input.close()
        }
    }
} catch {
    case ex => throw ex // Feel free to do some error handling here
} finally {
    output.close()
}


问:
How to make video loop properly?
I want to play this video in a loop https://www.nicovideo.jp/watch/sm16617386 . I want to play an mp4 file in such a way, that whenever it gets to some point in the video (let's say, 30.3 seconds), it will loop back (to for example 5.85 seconds).

I tried to add this code in ffplay.c , it didn't work well enough, I can hear the transition. I guess seeking isn't fast enough, or audio needs to be looped in an independant way somehow.

```<code>static void video_refresh(void *opaque, double *remaining_time)
{
   (original code here...)
    time = get_master_clock(is);
    if (isnan(time))
        time = (double)is->seek_pos / AV_TIME_BASE;
    if (time > jump_when) {
        stream_seek(is, (int64_t)(6.0 * AV_TIME_BASE), (int64_t)(0.0 * AV_TIME_BASE), 0);
    }
}
</code>```

My current plan is to just dig into ffmpeg, understand how video and audio decoders work, and savestate/loadstate the decoders.

答:
"I want to play an mp4 file in such a way, that whenever it gets to some point in the video (eg: 30.3 seconds), it will loop back to earlier time (eg: 5.85 seconds)."

"I can hear the transition. I guess seeking isn't fast enough, or audio needs to be looped in an independent way somehow."

Your linked video has a keyframe every 2 seconds (precisely 2.023).
So you can only seek to seconds like 2.023, 4.023, 6.023, 8.023, etc.

If you want 5.850 seconds You need to first seek to the keyframe at 4 secs, then decode every next following frame up to required timestamp of 5.850. At this point you can then display video.

The solution I've used in the past was to simply adjust the timestamps (PTS) of the P/B frames to same as the keyframe before feeding their bytes to an H264 decoder. (This way the decoder is forced to fast-forward through the video to keep synchronization). I've used FFmpeg only within command line, so not sure how you can change display times in your shown code.

Why?:

In MPEG compression, you can only seek to keyframes. Every audio frame is a keyframe, but video has 3 types of frame: I (which is a keyframe or complete picture), there is also P and B frames (which have only small differences from main picture over time). These P/B frames need a nearest previous keyframe to be decoded first so they too have pixel data to show. P/B frames cannot be decoded by just themselves (since they're not complete image data).

Title: How to make video loop properly?

Body:
I want to play this video in a loop https://www.nicovideo.jp/watch/sm16617386 . I want to play an mp4 file in such a way, that whenever it gets to some point in the video (let's say, 30.3 seconds), it will loop back (to for example 5.85 seconds).

I tried to add this code in ffplay.c , it didn't work well enough, I can hear the transition. I guess seeking isn't fast enough, or audio needs to be looped in an independant way somehow.

static void video_refresh(void *opaque, double *remaining_time)
{
   (original code here...)
    time = get_master_clock(is);
    if (isnan(time))
        time = (double)is->seek_pos / AV_TIME_BASE;
    if (time > jump_when) {
        stream_seek(is, (int64_t)(6.0 * AV_TIME_BASE), (int64_t)(0.0 * AV_TIME_BASE), 0);
    }
}

My current plan is to just dig into ffmpeg, understand how video and audio decoders work, and savestate/loadstate the decoders.


问:
How to create multiple files based on multiple records using php suppose i have 100 record create 1 file for every 10 record
This code is not working i want to print file for every 10 record.</p>

```<code>if($con=mysqli_connect("localhost","root","","fileDemo")){
    //echo "DB CONEECTED";
    $sql = "select id from news order by id desc";
    $data_query=mysqli_query($con,$sql);
    while($data=mysqli_fetch_assoc($data_query)){
        $id=$data['id'];
        if(!file_exists("demo_file"."-".trim($id).".txt")){
            $file_c=fopen("demo_file"."-".trim($id).".txt", 'a');
            fwrite($file_c,$id);
            fclose($file_c);
        }
        // $stringData.="Name: ".$data['name']." Age:".$data['age']."\n";
    }
}else{
    echo "CONNECTION FAILD";
}
</code>```

答:
```<code>//open first file
$handle = fopen('filename.txt', 'w');
foreach ($records as $i => $record) {
   //if record is 10th then close prev file and open new
   if ($i % 10 == 0) {
       fclose($handle);
       $handle = fopen("filename_$i.txt", 'w');
   }
   //your logic here. Write to file I suppose
   fwrite($handle, $record);
}
//close file
fclose($handle);
</code>```

Body:
This code is not working i want to print file for every 10 record.

if($con=mysqli_connect("localhost","root","","fileDemo")){
    //echo "DB CONEECTED";
    $sql = "select id from news order by id desc";
    $data_query=mysqli_query($con,$sql);
    while($data=mysqli_fetch_assoc($data_query)){
        $id=$data['id'];
        if(!file_exists("demo_file"."-".trim($id).".txt")){
            $file_c=fopen("demo_file"."-".trim($id).".txt", 'a');
            fwrite($file_c,$id);
            fclose($file_c);
        }
        // $stringData.="Name: ".$data['name']." Age:".$data['age']."\n";
    }
}else{
    echo "CONNECTION FAILD";
}


问:
JavaScript Slot Machine: What Is A Simple Algorithm For Picking A Winner?
I'm developing a slot machine in JavaScript, and this slot machine has 3 reels.

Each reel is identical and contains 4 symbols: A bar, a 7, a bell, and a grape. The bar is displayed on the reel one time, the 7 two times, the bell three times, and the grape four times - for a total of 10 symbols per reel. And each symbol corresponds with a number from 0 - 9:

```<code>| bar | -> 9
|  7  | -> 8
|  7  | -> 7
| bell| -> 6
| bell| -> 5
| bell| -> 4
|grape| -> 3
|grape| -> 2
|grape| -> 1
|grape| -> 0
</code>```

I'm then randomly generating a number from 0 - 999, and based on that number I would like to potentially select a winner. For example, if the number is 999 that is three bars and the first jackpot, if the number is 210 that is three grapes and the fourth jackpot. If the number is 359 that is grape/bell/bar and no jackpot.

I had created an if/else to select the winner but realized it does not take into account the second winning situation of 210:

```<code>if (number == 999) {
    // Jackpot 1
} else if (number == 888) {
    // Jackpot 2
} else if (number == 777) {
    // Jackpot 2
} else if (number == 666) {
    // Jackpot 3
} else if (number == 555) {
    // Jackpot 3
} else if (number == 444) {
    // Jackpot 3
} else if (number == 333) {
    // Jackpot 4
} else if (number == 222) {
    // Jackpot 4
} else if (number == 111) {
    // Jackpot 4
} else if (number == 0) {
    // Jackpot 4
} else {
    // No jackpot
}
</code>```

Does anyone have any ideas for how I might devise a simple algorithm for selecting a winner, as opposed to a bunch of if/else's? Also, there needs to be a total of 10 possible outcomes per reel, as the top jackpot should have a probability of 10^3 => 1 in 1,000.

答:
I think doing the arithmetic with a numeric lookup-table will be the most efficient:

function isJackPot(number) {
    const symbols = [4,4,4,4,3,3,3,2,2,1];
    const winner = symbols[number % 10]; // get symbol for rightmost digit
    for (let i = 0; i < 2; i++) {
        number = Math.floor(number/10); // shift digits to get next symbol
        if (symbols[number % 10] !== winner) return 0; // bail out when not the same
    }
    return winner;
}

const tests = [999, 210, 359];
for (const test of tests) {
    console.log(`${test} gives jackpot ${isJackPot(test)}`);
}```

NB: a return value 0 means there is no jackpot. Any other number (1..4) denotes the kind of jackpot.

Body:
I'm developing a slot machine in JavaScript, and this slot machine has 3 reels.

Each reel is identical and contains 4 symbols: A bar, a 7, a bell, and a grape. The bar is displayed on the reel one time, the 7 two times, the bell three times, and the grape four times - for a total of 10 symbols per reel. And each symbol corresponds with a number from 0 - 9:

| bar | -> 9
|  7  | -> 8
|  7  | -> 7
| bell| -> 6
| bell| -> 5
| bell| -> 4
|grape| -> 3
|grape| -> 2
|grape| -> 1
|grape| -> 0

I'm then randomly generating a number from 0 - 999, and based on that number I would like to potentially select a winner. For example, if the number is 999 that is three bars and the first jackpot, if the number is 210 that is three grapes and the fourth jackpot. If the number is 359 that is grape/bell/bar and no jackpot.

I had created an if/else to select the winner but realized it does not take into account the second winning situation of 210:

if (number == 999) {
    // Jackpot 1
} else if (number == 888) {
    // Jackpot 2
} else if (number == 777) {
    // Jackpot 2
} else if (number == 666) {
    // Jackpot 3
} else if (number == 555) {
    // Jackpot 3
} else if (number == 444) {
    // Jackpot 3
} else if (number == 333) {
    // Jackpot 4
} else if (number == 222) {
    // Jackpot 4
} else if (number == 111) {
    // Jackpot 4
} else if (number == 0) {
    // Jackpot 4
} else {
    // No jackpot
}

Does anyone have any ideas for how I might devise a simple algorithm for selecting a winner, as opposed to a bunch of if/else's? Also, there needs to be a total of 10 possible outcomes per reel, as the top jackpot should have a probability of 10^3 => 1 in 1,000.

Body:
I think doing the arithmetic with a numeric lookup-table will be the most efficient:

function isJackPot(number) {
    const symbols = [4,4,4,4,3,3,3,2,2,1];
    const winner = symbols[number % 10]; // get symbol for rightmost digit
    for (let i = 0; i < 2; i++) {
        number = Math.floor(number/10); // shift digits to get next symbol
        if (symbols[number % 10] !== winner) return 0; // bail out when not the same
    }
    return winner;
}

const tests = [999, 210, 359];
for (const test of tests) {
    console.log(`${test} gives jackpot ${isJackPot(test)}`);
}

NB: a return value 0 means there is no jackpot. Any other number (1..4) denotes the kind of jackpot.


问:
what I need to change in my code to get my output like this [None, 2, None, 4,None].I am using lambd function to do this
I am trying to do this :

```<code>evenList = ((lambda x : x if x%2==0 else None), [1,2,3,4,5,6])
</code>```

Expected output :

```<code>[None,2,None,4,None,6]
</code>```

I am getting :

```<code>(<function __main__.<lambda>>, [1,2,3,4,5,6])
</code>```

答:
Why not simply using:</p>

```<code>>>> [x if x%2==0 else None for x in range(1,7)]
[None, 2, None, 4, None, 6]
</code>```

Body:
I am trying to do this :

evenList = ((lambda x : x if x%2==0 else None), [1,2,3,4,5,6])

Expected output :

[None,2,None,4,None,6]

I am getting :

(<function __main__.<lambda>>, [1,2,3,4,5,6])

Body:
Why not simply using:

>>> [x if x%2==0 else None for x in range(1,7)]
[None, 2, None, 4, None, 6]


问:
How can I convert numpy.ndarray having type object to torch.tensor?
I'm trying to work on lstm in pytorch. It takes only tensors as the input. The data that I have is in the form of a numpy.object_ and if I convert this to a numpy.float, then it can be converted to tensor.

I checked the data type using print(type(array)) it gives class 'numpy.ndarray' as output and print(arr.dtype.type) gives class 'numpy.object_' as output.

Or is there any way to convert tuple directly to torch.tensor?

答:
The pytorch LSTM returns a tuple. So you get this error as your second LSTM layer self.seq2 can not handle this tuple. So,
change

```<code>prefix1=self.seq1(input1)
suffix1=self.seq1(input2)
</code>```

to something like this:

```<code>prefix1_out, prefix1_states = self.seq1(input1)
suffix1_out, suffix1_states = self.seq1(input2)
</code>```

and then pass prefix1_out and suffix1_out tensors to the next LSTM layers as

```<code>prefix2_out, prefix2_states = self.seq2(prefix1_out)
suffix2_out, suffix2_states = self.seq2(suffix1_out)
</code>```

And, concat prefix1_out and suffix1_out tensors like this

```<code>result = torch.cat([out1,out2],1)
</code>```

Also, change

```<code>r1=F.sigmoid(self.fc1(result))
r2=self.fc2(r1)
</code>```

to something like this:

```<code>out_ll = self.fc1(result)
r1 = nn.Sigmoid()
r2 = self.fc2(r1(out_ll))
</code>```

Body:
The pytorch LSTM returns a tuple. So you get this error as your second LSTM layer self.seq2 can not handle this tuple. So,
change

prefix1=self.seq1(input1)
suffix1=self.seq1(input2)

to something like this:

prefix1_out, prefix1_states = self.seq1(input1)
suffix1_out, suffix1_states = self.seq1(input2)

and then pass prefix1_out and suffix1_out tensors to the next LSTM layers as

prefix2_out, prefix2_states = self.seq2(prefix1_out)
suffix2_out, suffix2_states = self.seq2(suffix1_out)

And, concat prefix1_out and suffix1_out tensors like this

result = torch.cat([out1,out2],1)

Also, change

r1=F.sigmoid(self.fc1(result))
r2=self.fc2(r1)

to something like this:

out_ll = self.fc1(result)
r1 = nn.Sigmoid()
r2 = self.fc2(r1(out_ll))


问:
C++ - Why static member function can't be created with 'const' qualifier
Today I got a problem. I am in the need of a static member function, const is not a must but a better. But, I didn't succeed in my efforts. Can anybody say why or how?

答:
A 'const member function' is not
allowed to modify the object it is called on, but static member
functions are not called on any object.
It is used directly by scope resolution operator.
Thus having a const static member function makes no sense, hence it is illegal.</p>


问:
MS Access Automatically Generate Random Number
I want to generate a 6-digit random number in a table row in MS Access, is it possible?

I've tried to make a random number for a user's unique ID in a table, but sometimes it generates a negative number like -43543435.

答:
sometimes it generates a negative number like -43543435

That's by design. A random autonumber can take any value within the range of a Long.

It should make no difference to you, as the value of the ID in any case should be meaningless as its only purpose is to identify the record uniquely and doesn't have to be displayed for the user.

If you wish to apply random numbers to the records for the purpose of sorting, you can study the methods in my article:

Random Rows in Microsoft Access

If you don't have an account, browse to the link: Read the full article.


问:
Does Device admin deprecation means that we will no longer be able to disable camera?
As Android Device Administration is going to be deprecated. It will be replaced with Android Enterprise Mobility Manager(EMM), and as shown in the feature list disabling of camera is not supported in work profile. Work managed device would require a factory reset in order to setup.

So will we no longer be able to disable cameras for BYOD? Or are there other methods to disable camera for all profiles/entire device like Samsung KNOX does?

答:
Work profile is not a solution as it will disable camera only for apps under this profile and not for personal apps.

You should use the legacy mode with old sdk and Google may prevent you to publish updates at Play store.

I think that BYOD will be a real issue at Android 10.


问:
React native App gets crashed on release mode with the following error null is not an object (evaluating 's.drawer._root')
I have used native base drawer which works fine in debug mode but when i created an release apk the app gets crashed with the following error.

```<code>AndroidRuntime: com.facebook.react.common.JavascriptException: null is
not an object (evaluating 's.drawer._root')
</code>```

code:

```<code> closeDrawer = () => {
 this.drawer._root && this.drawer._root.close();
};

openDrawer = () => {
this.drawer._root && this.drawer._root.open();
};

<Drawer
      ref={(ref) => {
        this.drawer = ref;
      }}
      type="overlay"
      side={'left'}
      openDrawerOffset={0.2}
      panOpenMask={0.2}
      tapToClose={true}
      content={
        <SideBar
          navigator={this.navigator}
          closeDrawer={() => this.closeDrawer()}
          {...this.props}
        />
      }
      tweenHandler={(ratio) => ({
        main: { opacity: (2 - ratio) / 2 }
      })}
      onClose={() => this.closeDrawer()}
    >
</code>```

答:
take a look at the react document about ref

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element

in your closeDrawer  and openDrawer callback, this.drawer  might be null, maybe you should add some codes like

```<code>this.drawer && this.drawer._root && this.drawer._root.close();
this.drawer && this.drawer._root && this.drawer._root.open();
</code>```

Body:
I have used native base drawer which works fine in debug mode but when i created an release apk the app gets crashed with the following error.

AndroidRuntime: com.facebook.react.common.JavascriptException: null is
not an object (evaluating 's.drawer._root')

code:

 closeDrawer = () => {
 this.drawer._root && this.drawer._root.close();
};

openDrawer = () => {
this.drawer._root && this.drawer._root.open();
};

<Drawer
      ref={(ref) => {
        this.drawer = ref;
      }}
      type="overlay"
      side={'left'}
      openDrawerOffset={0.2}
      panOpenMask={0.2}
      tapToClose={true}
      content={
        <SideBar
          navigator={this.navigator}
          closeDrawer={() => this.closeDrawer()}
          {...this.props}
        />
      }
      tweenHandler={(ratio) => ({
        main: { opacity: (2 - ratio) / 2 }
      })}
      onClose={() => this.closeDrawer()}
    >

Body:
take a look at the react document about ref

If the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element

in your closeDrawer  and openDrawer callback, this.drawer  might be null, maybe you should add some codes like

this.drawer && this.drawer._root && this.drawer._root.close();
this.drawer && this.drawer._root && this.drawer._root.open();


问:
UIUserInterfaceIdiomPad in ios
UIUserInterfaceIdiomPad in ios why it is used ?

in my mac book pro ipad stimulator

```<code>  BOOL isIPad2 = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad &&
                        [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]);
</code>```

答:
UIUserInterfaceIdiomPad  Is used to know what the current device is. From Apple doc

For universal applications, you can use this property to tailor the
  behavior of your application for a specific type of device. For
  example, iPhone and iPad devices have different screen sizes, so you
  might want to create different views and controls based on the type of
  the current device.

Title: UIUserInterfaceIdiomPad in ios

Body:
UIUserInterfaceIdiomPad in ios why it is used ?

in my mac book pro ipad stimulator

  BOOL isIPad2 = (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad &&
                        [UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera]);


问:
MVC2: SQL Server table --> Excel Spreadsheet
is there an easy way to export a SQL Server table into a xls spreadsheet?

Thanks

答: NPoi or EPPlus. You should create the spredsheet in memory and send it via the File action result.</p>


问:
what is difference in 'The MAC is invalid' and 'The Payload is invalid' laravel?
I running two laravel 5.7 app, both have different app key.

```<code> -->app 1 key 1,
 -->app 2 key 2
</code>```

[This point is less imp] These are two app (different module based on user roles. uses different app keys, but accessing same db).

When encrypting some data in app 1 with key 1, now decrypt encrypted data in app 1 with key 1, Working properly.

But I change in encrypted data string (app 1, key 1) and trying to again decrypt in app 1 with key 1, it gives error "The payload is invalid". I digest this.

Now, the second thing is, I encrypt data in app 1 with key 1, and passed this encrypted data string in app 2 with key 2 for decryption it give another error "The MAC is invalid.".

Now my question is why laravel give two different error? why not it gives same error, because we send another data with another app (means this is wrong for second app).

Can you please differentiate. May it be cause to any security loop whole.

Thanks.

答:
Laravel encode and decode with base64 the playload. Here take a look :

```<code>/**
 * Get the JSON array from the given payload.
 *
 * @param  string  $payload
 * @return array
 *
 * @throws \Illuminate\Contracts\Encryption\DecryptException
 */
protected function getJsonPayload($payload)
{
    $payload = json_decode(base64_decode($payload), true);

    // If the payload is not valid JSON or does not have the proper keys set we will
    // assume it is invalid and bail out of the routine since we will not be able
    // to decrypt the given value. We'll also check the MAC for this encryption.
    if (! $this->validPayload($payload)) {
        throw new DecryptException('The payload is invalid.');
    }

    if (! $this->validMac($payload)) {
        throw new DecryptException('The MAC is invalid.');
    }

    return $payload;
}

/**
 * Verify that the encryption payload is valid.
 *
 * @param  mixed  $payload
 * @return bool
 */
protected function validPayload($payload)
{
    return is_array($payload) && isset($payload['iv'], $payload['value'], $payload['mac']) &&
           strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length($this->cipher);
}

/**
 * Determine if the MAC for the given payload is valid.
 *
 * @param  array  $payload
 * @return bool
 */
protected function validMac(array $payload)
{
    $calculated = $this->calculateMac($payload, $bytes = random_bytes(16));

    return hash_equals(
        hash_hmac('sha256', $payload['mac'], $bytes, true), $calculated
    );
}
</code>```

Illuminate/Encryption/Encrypter.php

As you can see there is a double check, if you modify manually the payload it won't necessarily have the correct structure and will return The payload is invalid.

Then, when the payload is valid, it will try with the MAC. When the content doesn't match, it will return The MAC is invalid.

Body:
I running two laravel 5.7 app, both have different app key.

 -->app 1 key 1,
 -->app 2 key 2

[This point is less imp] These are two app (different module based on user roles. uses different app keys, but accessing same db).

When encrypting some data in app 1 with key 1, now decrypt encrypted data in app 1 with key 1, Working properly.

But I change in encrypted data string (app 1, key 1) and trying to again decrypt in app 1 with key 1, it gives error "The payload is invalid". I digest this.

Now, the second thing is, I encrypt data in app 1 with key 1, and passed this encrypted data string in app 2 with key 2 for decryption it give another error "The MAC is invalid.".

Now my question is why laravel give two different error? why not it gives same error, because we send another data with another app (means this is wrong for second app).

Can you please differentiate. May it be cause to any security loop whole.

Thanks.

Body:
Laravel encode and decode with base64 the playload. Here take a look :

/**
 * Get the JSON array from the given payload.
 *
 * @param  string  $payload
 * @return array
 *
 * @throws \Illuminate\Contracts\Encryption\DecryptException
 */
protected function getJsonPayload($payload)
{
    $payload = json_decode(base64_decode($payload), true);

    // If the payload is not valid JSON or does not have the proper keys set we will
    // assume it is invalid and bail out of the routine since we will not be able
    // to decrypt the given value. We'll also check the MAC for this encryption.
    if (! $this->validPayload($payload)) {
        throw new DecryptException('The payload is invalid.');
    }

    if (! $this->validMac($payload)) {
        throw new DecryptException('The MAC is invalid.');
    }

    return $payload;
}

/**
 * Verify that the encryption payload is valid.
 *
 * @param  mixed  $payload
 * @return bool
 */
protected function validPayload($payload)
{
    return is_array($payload) && isset($payload['iv'], $payload['value'], $payload['mac']) &&
           strlen(base64_decode($payload['iv'], true)) === openssl_cipher_iv_length($this->cipher);
}

/**
 * Determine if the MAC for the given payload is valid.
 *
 * @param  array  $payload
 * @return bool
 */
protected function validMac(array $payload)
{
    $calculated = $this->calculateMac($payload, $bytes = random_bytes(16));

    return hash_equals(
        hash_hmac('sha256', $payload['mac'], $bytes, true), $calculated
    );
}

Illuminate/Encryption/Encrypter.php

As you can see there is a double check, if you modify manually the payload it won't necessarily have the correct structure and will return The payload is invalid.

Then, when the payload is valid, it will try with the MAC. When the content doesn't match, it will return The MAC is invalid.


问:
Need replace html string text from react component
Issue : -
we are facing the shortcode issue. we use shortcode {{email}} for email subscription in content and the server provides content as HTML string on the frontend side. we render string to HTML on the frontend side from dengerouslySetInnerHTML react function..

Example : -
let description = '
contect here {{email}} content here {{email}} content here
';

we use react dengerouslySetInnerHTML function that convert HTML string to  actual HTML.

I'm doing -
replacing {{email}} text from react email component but we are not able to insert react component in the string.

Like -  description.replace('{{email}}', <EmailComponent />)

答:
i think you can convert <EmailComponent /> to string

```<code>import { renderToString } from 'react-dom/server'

console.log(description.replace('{{email}}', renderToString(<EmailComponent />)))
</code>```

Body:
i think you can convert <EmailComponent /> to string

import { renderToString } from 'react-dom/server'

console.log(description.replace('{{email}}', renderToString(<EmailComponent />)))


问:
Missing blame information for the following files SonarQube Error
I couldnt run my maven project in sonarqube using command mvn sonar:sonar.
It results with the error : Missing blame information for the following files.
But a normal helloworld program run successfully and it got added in the projects tab of sonarqubes.

Kindly help me to sort out this error.

答:
If you have no commited file, you can't run command mvn sonar:sonar.
You need commit any change into your branch and after run mvn sonar:sonar.
This fix me.</p>


问:
Gluon application got problem when MousePressed fast click or double, tripple click
I have develop the gluon application which use uuid to generate the BarCode and QRCODE. The use could switch between Barcode and Qrcode based on shop. The Barcode will show only in the portrait screen mode when use click on QRCODE (Image). So the screen will auto rotate based when the user click on Image (Barcode/QRcode).

```<code>this.img.setOnMousePressed(event -> {
//Rotate Screen
        Services.get( CMOrientationService.class ).ifPresent( o -> {
            Orientation orientation = Services.get( OrientationService.class )
                    .flatMap(OrientationService::getOrientation)
                    .orElse(Orientation.HORIZONTAL);

            Services.get(LogService.class).ifPresent(service -> service.log("orientation="+orientation.toString()));

            if (orientation == Orientation.VERTICAL) {
                Services.get(LogService.class).ifPresent(service -> service.log("Currently="+orientation.toString()));
                //Change to Barcode
                //GenerateBarQRCode(orientation == Orientation.VERTICAL);
                o.coerceOrientation( Orientation.HORIZONTAL );
            } else {
                Services.get(LogService.class).ifPresent(service -> service.log("Currently="+orientation.toString()));
                //Change to QRCode
                //GenerateBarQRCode(orientation == Orientation.VERTICAL);
                o.coerceOrientation( Orientation.VERTICAL );
            }
            GenerateBarQRCode(orientation == Orientation.VERTICAL);
        } );
});
</code>```

The problems occurs when user trying to click fast on the image (double, triple click) it will generate wrong.

You can check this video for more understanding (Look at 6 sec in the video).

Noted. It error only in Android.

答:
You can use synchronization like this

```<code>// At class level
private Object mutex;
//initialize this object in constructor like this
mutex = this;

this.img.setOnMousePressed(event -> {
//Rotate Screen
synchronized(mutex){
// your code here
       ....
}
});
</code>```

However in above instance, multiple click events will be executed in serial fashion. If you want that multiple clicks should be ignored until execution then you can use following code snippet

```<code>// At class level
private boolean mutex = true;

this.img.setOnMousePressed(event -> {
   if(mutex){
     mutex = false;

        // your code here
               ....
     mutex = true;
   }
});
</code>```

Body:
I have develop the gluon application which use uuid to generate the BarCode and QRCODE. The use could switch between Barcode and Qrcode based on shop. The Barcode will show only in the portrait screen mode when use click on QRCODE (Image). So the screen will auto rotate based when the user click on Image (Barcode/QRcode).

this.img.setOnMousePressed(event -> {
//Rotate Screen
        Services.get( CMOrientationService.class ).ifPresent( o -> {
            Orientation orientation = Services.get( OrientationService.class )
                    .flatMap(OrientationService::getOrientation)
                    .orElse(Orientation.HORIZONTAL);

            Services.get(LogService.class).ifPresent(service -> service.log("orientation="+orientation.toString()));

            if (orientation == Orientation.VERTICAL) {
                Services.get(LogService.class).ifPresent(service -> service.log("Currently="+orientation.toString()));
                //Change to Barcode
                //GenerateBarQRCode(orientation == Orientation.VERTICAL);
                o.coerceOrientation( Orientation.HORIZONTAL );
            } else {
                Services.get(LogService.class).ifPresent(service -> service.log("Currently="+orientation.toString()));
                //Change to QRCode
                //GenerateBarQRCode(orientation == Orientation.VERTICAL);
                o.coerceOrientation( Orientation.VERTICAL );
            }
            GenerateBarQRCode(orientation == Orientation.VERTICAL);
        } );
});

The problems occurs when user trying to click fast on the image (double, triple click) it will generate wrong.

You can check this video for more understanding (Look at 6 sec in the video).

Noted. It error only in Android.

Body:
You can use synchronization like this

// At class level
private Object mutex;
//initialize this object in constructor like this
mutex = this;

this.img.setOnMousePressed(event -> {
//Rotate Screen
synchronized(mutex){
// your code here
       ....
}
});

However in above instance, multiple click events will be executed in serial fashion. If you want that multiple clicks should be ignored until execution then you can use following code snippet

// At class level
private boolean mutex = true;

this.img.setOnMousePressed(event -> {
   if(mutex){
     mutex = false;

        // your code here
               ....
     mutex = true;
   }
});


问:
How to handle parallel requests to different URLs on Citrus server?
I'm doing integration testing for a couple microservices with the Citrus framework. The test setup is roughly this:

Send a request from a Citrus HTTP client to one of the microservices

Several microservices send requests to the same remote host (which I want to mock away with a Citrus HTTP server) concurrently, calling different URLs on that remote host (e.g. "http://server.com/A/" and "http://server.com/Z/E/F/") or the same URL with different query parameters (e.g. "http://server.com/A?param=1" and "http://server.com/A?param=great")

The Citrus server should return different responses dynamically calculated from the specific URL call that it's responding to

All subsequent verification steps require no interaction with the Citrus server.

I can't figure out how to set this up such that the test is not vulnerable to race conditions. I've tried the variations on the solutions suggested in this github thread that I could think of, but can't figure out how to adjust it to my use case. I'm trying to put the different request-response pairs into separate async()-containers, but the responses end up getting switched under the wrong race conditions and my tests fail frequently. I try to mock each request-response-pair like this:

```<code>private void serverReceiveCallAndRespond(String path, Resource response) {
    async().actions(
        http().server(citrusHttpServer)
            .receive()
            .get(path),
        http().server(citrusHttpServer)
            .send()
            .response(HttpStatus.OK)
            .contentType("application/json")
            .messageType(JSON)
            .payload(response)
    );
}
</code>```

TLDR: how can I tell a Citrus server to respond to calls to different URLs with different responses asynchronously?

答:
I suggest to use message selectors to solve this. The Citrus server pushes all incoming requests to an internal message channel. You can pick a message explicitly form that channel using message selectors.

http().server(citrusHttpServer)
            .receive()
            .get(path)
            .selector(Collections.singletonMap(HttpMessageHeader.HTTP_REQUEST_URI, "/Z/E/F/"))
```

This way you can always receive the request on /Z/E/F/ first in your test and respond to that with proper response. After that you can add a 2nd receive using another selector and provide a proper response to that call.

The sequence of incoming requests is then not bound to racing conditions anymore.

Not sure about the HttpMessageHeader.HTTP_REQUEST_URI header though. You might need to use the complete request URI here as value.

Body:
I'm doing integration testing for a couple microservices with the Citrus framework. The test setup is roughly this:

Send a request from a Citrus HTTP client to one of the microservices

Several microservices send requests to the same remote host (which I want to mock away with a Citrus HTTP server) concurrently, calling different URLs on that remote host (e.g. "http://server.com/A/" and "http://server.com/Z/E/F/") or the same URL with different query parameters (e.g. "http://server.com/A?param=1" and "http://server.com/A?param=great")

The Citrus server should return different responses dynamically calculated from the specific URL call that it's responding to

All subsequent verification steps require no interaction with the Citrus server.

I can't figure out how to set this up such that the test is not vulnerable to race conditions. I've tried the variations on the solutions suggested in this github thread that I could think of, but can't figure out how to adjust it to my use case. I'm trying to put the different request-response pairs into separate async()-containers, but the responses end up getting switched under the wrong race conditions and my tests fail frequently. I try to mock each request-response-pair like this:

private void serverReceiveCallAndRespond(String path, Resource response) {
    async().actions(
        http().server(citrusHttpServer)
            .receive()
            .get(path),
        http().server(citrusHttpServer)
            .send()
            .response(HttpStatus.OK)
            .contentType("application/json")
            .messageType(JSON)
            .payload(response)
    );
}

TLDR: how can I tell a Citrus server to respond to calls to different URLs with different responses asynchronously?

Body:
I suggest to use message selectors to solve this. The Citrus server pushes all incoming requests to an internal message channel. You can pick a message explicitly form that channel using message selectors.

http().server(citrusHttpServer)
            .receive()
            .get(path)
            .selector(Collections.singletonMap(HttpMessageHeader.HTTP_REQUEST_URI, "/Z/E/F/"))

This way you can always receive the request on /Z/E/F/ first in your test and respond to that with proper response. After that you can add a 2nd receive using another selector and provide a proper response to that call.

The sequence of incoming requests is then not bound to racing conditions anymore.

Not sure about the HttpMessageHeader.HTTP_REQUEST_URI header though. You might need to use the complete request URI here as value.


问:
How to do conditional processing in a bulk collect loop?
we have Oracle 11G and i'm trying to move data from one table to another using bulk collect. Problem is when I tried to evaluate if one field from origin is empty my package got invalidated. What I have:

Declaration:

```<code>CREATE OR REPLACE PACKAGE MYSCHEMA.MYPKG AS
CURSOR CUR_MYDATA IS
        SELECT
            o.name,
            o.last_name,
            o.id,
            o.socnum
        FROM
            origin o
        WHERE
            1=1
            AND o.name like upper ('a%');

        TYPE t_name IS TABLE OF origin.name%TYPE;
        TYPE t_lastname IS TABLE OF origin.last_name%TYPE;
        TYPE t_id IS TABLE OF origin.id%TYPE;
        TYPE t_socnum IS TABLE OF origin.socnum%TYPE;

        l_name t_name;
        l_lastname t_lastname;
        l_id t_id;
        l_socnum t_socnum;

PROCEDURE MYPROCEDURE;

END MYPKG;
</code>```

Body:

```<code>CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS

    BEGIN
        OPEN CUR_MYDATA;
        LOOP
        FETCH CUR_MYDATA BULK COLLECT INTO l_name,l_lastname,l_id,l_socnum;
            forall i IN 1 .. l_name.COUNT
            IF ( l_socnum(i) IS NULL)
                THEN (select oo.socnum from other_origin where oo.id=l_id(i))
            END IF;
                INSERT INTO destiny (
                    d_name,
                    d_lastname,
                    d_id,
                    d_socnum)
                VALUES (
                    l_name(i),
                    l_lastname(i),
                    l_id(i),
                    l_socnum(i),
            EXIT WHEN l_name.count = 0;
        END LOOP;
    END MYPROCEDURE;

END MYPKG;
</code>```

but when I check body status it is INVALID

any thoughs?

答:
IF condition is not allowed inside FOR ALL.

FOR ALL can execute a single DML: INSERT, UPDATE, or DELETE statement which is written following it. It is not normal for loop.

You can try the following code:

Package:

```<code>CREATE OR REPLACE PACKAGE MYSCHEMA.MYPKG AS
    CURSOR CUR_MYDATA IS
    SELECT
        O.NAME,
        O.LAST_NAME,
        O.ID,
        -- ADDED THIS CASE STATEMENT
        CASE
            WHEN O.SOCNUM IS NOT NULL THEN O.SOCNUM
            ELSE OO.SOCNUM
        END AS SOCNUM
    FROM
        -- ADDED THIS LEF JOIN
        ORIGIN O
        LEFT JOIN OTHER_ORIGIN OO ON ( OO.ID = O.ID )
    WHERE
        1 = 1
        AND O.NAME LIKE UPPER('a%');

    TYPE T_NAME IS
        TABLE OF ORIGIN.NAME%TYPE;
    TYPE T_LASTNAME IS
        TABLE OF ORIGIN.LAST_NAME%TYPE;
    TYPE T_ID IS
        TABLE OF ORIGIN.ID%TYPE;
    TYPE T_SOCNUM IS
        TABLE OF ORIGIN.SOCNUM%TYPE;
    L_NAME T_NAME;
    L_LASTNAME T_LASTNAME;
    L_ID T_ID;
    L_SOCNUM T_SOCNUM;
    PROCEDURE MYPROCEDURE;

END MYPKG;
</code>```

Package Body

```<code>CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS
    BEGIN
        OPEN CUR_MYDATA;
        FETCH CUR_MYDATA BULK COLLECT INTO
            L_NAME,
            L_LASTNAME,
            L_ID,
            L_SOCNUM
        LIMIT 1000;
        FORALL I IN 1..L_NAME.COUNT
--
-- REMOVED THIS CONDITION
--
--            IF ( l_socnum(i) IS NULL)
--                THEN (select oo.socnum from other_origin where oo.id=l_id(i))
--            END IF;
            INSERT INTO DESTINY (
                D_NAME,
                D_LASTNAME,
                D_ID,
                D_SOCNUM
            ) VALUES (
                L_NAME(I),
                L_LASTNAME(I),
                L_ID(I),
                L_SOCNUM(I)
            );

        CLOSE CUR_MYDATA;
    END MYPROCEDURE;

END MYPKG;
</code>```

Body:
we have Oracle 11G and i'm trying to move data from one table to another using bulk collect. Problem is when I tried to evaluate if one field from origin is empty my package got invalidated. What I have:

Declaration:

CREATE OR REPLACE PACKAGE MYSCHEMA.MYPKG AS
CURSOR CUR_MYDATA IS
        SELECT
            o.name,
            o.last_name,
            o.id,
            o.socnum
        FROM
            origin o
        WHERE
            1=1
            AND o.name like upper ('a%');

        TYPE t_name IS TABLE OF origin.name%TYPE;
        TYPE t_lastname IS TABLE OF origin.last_name%TYPE;
        TYPE t_id IS TABLE OF origin.id%TYPE;
        TYPE t_socnum IS TABLE OF origin.socnum%TYPE;

        l_name t_name;
        l_lastname t_lastname;
        l_id t_id;
        l_socnum t_socnum;

PROCEDURE MYPROCEDURE;

END MYPKG;

Body:

CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS

    BEGIN
        OPEN CUR_MYDATA;
        LOOP
        FETCH CUR_MYDATA BULK COLLECT INTO l_name,l_lastname,l_id,l_socnum;
            forall i IN 1 .. l_name.COUNT
            IF ( l_socnum(i) IS NULL)
                THEN (select oo.socnum from other_origin where oo.id=l_id(i))
            END IF;
                INSERT INTO destiny (
                    d_name,
                    d_lastname,
                    d_id,
                    d_socnum)
                VALUES (
                    l_name(i),
                    l_lastname(i),
                    l_id(i),
                    l_socnum(i),
            EXIT WHEN l_name.count = 0;
        END LOOP;
    END MYPROCEDURE;

END MYPKG;

but when I check body status it is INVALID

any thoughs?

Body:
IF condition is not allowed inside FOR ALL.

FOR ALL can execute a single DML: INSERT, UPDATE, or DELETE statement which is written following it. It is not normal for loop.

You can try the following code:

Package:

CREATE OR REPLACE PACKAGE MYSCHEMA.MYPKG AS
    CURSOR CUR_MYDATA IS
    SELECT
        O.NAME,
        O.LAST_NAME,
        O.ID,
        -- ADDED THIS CASE STATEMENT
        CASE
            WHEN O.SOCNUM IS NOT NULL THEN O.SOCNUM
            ELSE OO.SOCNUM
        END AS SOCNUM
    FROM
        -- ADDED THIS LEF JOIN
        ORIGIN O
        LEFT JOIN OTHER_ORIGIN OO ON ( OO.ID = O.ID )
    WHERE
        1 = 1
        AND O.NAME LIKE UPPER('a%');

    TYPE T_NAME IS
        TABLE OF ORIGIN.NAME%TYPE;
    TYPE T_LASTNAME IS
        TABLE OF ORIGIN.LAST_NAME%TYPE;
    TYPE T_ID IS
        TABLE OF ORIGIN.ID%TYPE;
    TYPE T_SOCNUM IS
        TABLE OF ORIGIN.SOCNUM%TYPE;
    L_NAME T_NAME;
    L_LASTNAME T_LASTNAME;
    L_ID T_ID;
    L_SOCNUM T_SOCNUM;
    PROCEDURE MYPROCEDURE;

END MYPKG;

Package Body

CREATE OR REPLACE PACKAGE BODY MYSCHEMA.MYPKG AS

    PROCEDURE MYPROCEDURE IS
    BEGIN
        OPEN CUR_MYDATA;
        FETCH CUR_MYDATA BULK COLLECT INTO
            L_NAME,
            L_LASTNAME,
            L_ID,
            L_SOCNUM
        LIMIT 1000;
        FORALL I IN 1..L_NAME.COUNT
--
-- REMOVED THIS CONDITION
--
--            IF ( l_socnum(i) IS NULL)
--                THEN (select oo.socnum from other_origin where oo.id=l_id(i))
--            END IF;
            INSERT INTO DESTINY (
                D_NAME,
                D_LASTNAME,
                D_ID,
                D_SOCNUM
            ) VALUES (
                L_NAME(I),
                L_LASTNAME(I),
                L_ID(I),
                L_SOCNUM(I)
            );

        CLOSE CUR_MYDATA;
    END MYPROCEDURE;

END MYPKG;


问:
How to retrieve entities with a subset of related entities?
I have two entities in a one-to-many relation:
Meter (1) -> (n) Reading

I believe my two entities are set up correctly to provide the relation, so assume that.

I wish to retrieve Meters with related Readings but because there may be many Readings per Meter, I wish to limit it by eg Reading.Date. Another option could be to read at most X Readings per Meter.

How can I do that in EF.Core?

答:
If your tables are designed correctly i.e. key in Meter is mapped with Reading (see foreign key constraints), then EF automatically gives related records when you access its POCO class.
Make sure Reading has foreign key for Meter table in database.</p>


问:
What are the differences between the different Map implementations in Dart?
Dart has a Map type, with implementations like HashMap, LinkedHashMap, and SplayTreeMap. What's the difference between those different Map implementations?</p>

答:
There is an alternative.

Multimap

```<code>import 'package:quiver/collection.dart';

algorithms() {
  var ordered = new ListMultimap();
  ordered.add('32352', 'Alice');
  ordered.add('95594', 'Bob');
  ordered.add('32352', 'Alice2');

  for (var key in ordered.keys) {
    print(key);
  }

  for (var value in ordered.values) {
    print(value);
  }

  // print in ascending order
  // flutter: 32352
  // flutter: 95594
  // flutter: Alice
  // flutter: Alice2
  // flutter: Bob
}
</code>```

Body:
There is an alternative.

Multimap

import 'package:quiver/collection.dart';

algorithms() {
  var ordered = new ListMultimap();
  ordered.add('32352', 'Alice');
  ordered.add('95594', 'Bob');
  ordered.add('32352', 'Alice2');

  for (var key in ordered.keys) {
    print(key);
  }

  for (var value in ordered.values) {
    print(value);
  }

  // print in ascending order
  // flutter: 32352
  // flutter: 95594
  // flutter: Alice
  // flutter: Alice2
  // flutter: Bob
}


问:
Woocommerce add image after add to cart button
It seems weird,  but am trying to add a background image after an element(button) but for some reason, the image does not show.

    .single_add_to_cart_button:after {
        content: '';
        width: 50px;
        height: 9px;
        display: inline-block;
        background: url(/images/arrow.png);
        background-position: 50%;
        background-size: cover;
        background-repeat: no-repeat;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="submit" class="single_add_to_cart_button button alt disabled wc-variation-selection-needed">Place order</button></code>```

For some reason, the image does not show and I even tried using a live URL

Note: If I try using a paragraph it works as you can see in my pen here

How can I add an image from the template directory after my add to cart button?

In a simpler solution, I tried using a hook but I am also struggling to access the image using bloginfo:

```<code>add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );

function add_content_after_addtocart_button_func() {
    echo '<img src="<?php bloginfo("template_directory")/images/logo/logo.png">';
}
</code>```

答:
There is a syntax error as you are using <?php in a echo statement as well as bloginfo($option) echos out a value so request you to use get_template_directory_uri() to get the path to the template directory which will returns a string

your code will look like below snippet:

```<code>add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );

function add_content_after_addtocart_button_func() {
    echo '<img src="'.get_template_directory_uri().'/images/logo/logo.png">';
}
</code>```

Body:
It seems weird,  but am trying to add a background image after an element(button) but for some reason, the image does not show.

    .single_add_to_cart_button:after {
        content: '';
        width: 50px;
        height: 9px;
        display: inline-block;
        background: url(/images/arrow.png);
        background-position: 50%;
        background-size: cover;
        background-repeat: no-repeat;
    }

<button type="submit" class="single_add_to_cart_button button alt disabled wc-variation-selection-needed">Place order</button>

For some reason, the image does not show and I even tried using a live URL

Note: If I try using a paragraph it works as you can see in my pen here

How can I add an image from the template directory after my add to cart button?

In a simpler solution, I tried using a hook but I am also struggling to access the image using bloginfo:

add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );

function add_content_after_addtocart_button_func() {
    echo '<img src="<?php bloginfo("template_directory")/images/logo/logo.png">';
}

Body:
There is a syntax error as you are using <?php in a echo statement as well as bloginfo($option) echos out a value so request you to use get_template_directory_uri() to get the path to the template directory which will returns a string

your code will look like below snippet:

add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart_button_func' );

function add_content_after_addtocart_button_func() {
    echo '<img src="'.get_template_directory_uri().'/images/logo/logo.png">';
}


问:
Cruisecontrol.Net reporting incorrectly reporting build status
We've been having some issues with CCnet 1.5.7256.1 recently where some builds are running and failing but being reported as Successful builds. The build logs show the exception/failure status but the dashboard is still displaying green ticks and Success.

Obviously this is a concern as failed builds are going unnoticed.

Has anyone else had this problem?

I've posted on the ccnet-user google group here - http://groups.google.com.ag/group/ccnet-user/browse_thread/thread/4190a19b0fee57b3

答:
give the errorlevel command to your builds.
if its a batch file give a command of finding errorlevel after every build command. This will return the cruise control failed status which will make the CC build status failed.

Command is:
If %Errorlevel% is neq 0 than exit /b errorlevel

ContentLicense: CC BY-SA 2.5


问:
Installing dependencies from downloaded folder with Windows CMD
I'll try to make this as concise as possible.

I have got a Python project on a Mac that I want to distribute to multiple Windows computers. Before I distribute the zipped (that's what I do now at least) files, I'm downloading all dependencies to a folder named "dependencies" with the following command:
pip download -r requirements.txt -d "./dependencies"

I then zip the contents of the entire project folder using:
zip -r everything.zip .

I then (manually, for now) transfer the file to the Windows computer, where i unzip the contents of the zip-file using:
“%ProgramFiles%\WinRAR\winrar.exe” x -ibck C:\Users\xxx\Downloads\test_env\everything.zip *.* C:\Users\xxx\Downloads\test_env\

So far, so good. However, when I navigate into the dependencies-folder and try to install the dependencies offline using:
pip install * -f ./ --no-index

I get the following error:
ERROR: Invalid requirement: '*'

The same command works perfectly fine on my Mac, but I can't seem to find the equivalent for Windows CMD.

Any input?

PS! If anyone has any tips on how to best distribute the zip file, unzip it and install the dependencies to x number of computers, it would be greatly appreciated.

I have tried multiple commands, but end up getting different errors.

```<code>zip -r everything.zip .
“%ProgramFiles%\WinRAR\winrar.exe” x -ibck C:\Users\xxx\Downloads\test_env\everything.zip *.* C:\Users\xxx\Downloads\test_env\
pip install * -f ./ --no-index
</code>```

I expected pip install * -f ./ --no-index to work, but it gave me the following error message: ERROR: Invalid requirement: '*'

答:
This should work:-

```<code>$ pip install -r requirements.txt --no-index --find-links file:///path/to/packages/folder
</code>```

If you want to do it through a code.

```<code>import pip

def install(package_name):
   pip.main(["install", "--upgrade", "--no-index", "--find-links=.", package_name])

if __name__ == "__main__":
list_of_dependencies= [" Dep1","dep2"]
for dependency in list_of_dependencies:
     install(dependency)
</code>```

Body:
I'll try to make this as concise as possible.

I have got a Python project on a Mac that I want to distribute to multiple Windows computers. Before I distribute the zipped (that's what I do now at least) files, I'm downloading all dependencies to a folder named "dependencies" with the following command:
pip download -r requirements.txt -d "./dependencies"

I then zip the contents of the entire project folder using:
zip -r everything.zip .

I then (manually, for now) transfer the file to the Windows computer, where i unzip the contents of the zip-file using:
“%ProgramFiles%\WinRAR\winrar.exe” x -ibck C:\Users\xxx\Downloads\test_env\everything.zip *.* C:\Users\xxx\Downloads\test_env\

So far, so good. However, when I navigate into the dependencies-folder and try to install the dependencies offline using:
pip install * -f ./ --no-index

I get the following error:
ERROR: Invalid requirement: '*'

The same command works perfectly fine on my Mac, but I can't seem to find the equivalent for Windows CMD.

Any input?

PS! If anyone has any tips on how to best distribute the zip file, unzip it and install the dependencies to x number of computers, it would be greatly appreciated.

I have tried multiple commands, but end up getting different errors.

zip -r everything.zip .
“%ProgramFiles%\WinRAR\winrar.exe” x -ibck C:\Users\xxx\Downloads\test_env\everything.zip *.* C:\Users\xxx\Downloads\test_env\
pip install * -f ./ --no-index

I expected pip install * -f ./ --no-index to work, but it gave me the following error message: ERROR: Invalid requirement: '*'

Body:
This should work:-

$ pip install -r requirements.txt --no-index --find-links file:///path/to/packages/folder

If you want to do it through a code.

import pip

def install(package_name):
   pip.main(["install", "--upgrade", "--no-index", "--find-links=.", package_name])

if __name__ == "__main__":
list_of_dependencies= [" Dep1","dep2"]
for dependency in list_of_dependencies:
     install(dependency)


问:
How to work out the average from a set of columns based on multiple conditions in pandas?
I want to create a new column which shows the average based on multiple conditions. For the most part the new column should calculate the mean of the 3 columns. However, if the difference between A and B or B and C is greater than 10 then it should only use 2 values with the smallest difference.

For example if A = 2, B = 15 and C= 13 then the mean column should show 14. Because the difference between A and B is greater than 10 so the column should use B and C because they have the smallest difference to work out the mean.

I tried adding additional columns which determine the difference between A and B and for B and C. After that I used a conditional statement to create a list which appends the mean calculations based on the conditions and to then add the list as a column. However I get the error "Length of values does not match length of index".

This is the code used to create my dataframe:

```<code>df = pd.DataFrame(np.random.randint(0,20,size=(50, 3)),
columns=list('ABC'))
</code>```

My attempt at finding a solution:

```<code>df['diff_1'] = df['A'] - df['B']
df['diff_2'] = df['B'] - df['C']

average = []
for i in df['diff_1']:
    if i < -5:
        average.append(df[['A','B']].mean(axis=1))
    if i > 5:
        average.append(df[['A','B']].mean(axis=1))
    else:
        average.append(df[['A','B','C']].mean(axis=1))

df['average'] = average
</code>```

I would then have repeated for diff_2 and remove duplicates however this gives me the aforementioned error:
"Length of values does not match length of index". So am I wondering if there is a more appropriate method.

I am expecting a column which shows the average of all three columns except for when the difference between A and B or B and C is greater than 10. If that is the case it should then calculate the mean using only 2 numbers with the lowest difference.

答:
Use numpy.select for seelct values by conditions:

```<code>np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,20,size=(50, 3)),
columns=list('ABC'))

df['diff_ab'] = (df['A'] - df['B']).abs()
df['diff_bc'] = (df['B'] - df['C']).abs()
mindiff = df[['diff_ab','diff_bc']].min(axis=1)

ab = df[['A','B']].mean(axis=1)
bc = df[['B','C']].mean(axis=1)
abc = df[['A','B','C']].mean(axis=1)

N = 10
df['average1'] = np.select([(df['diff_ab'] > N) & mindiff.eq(df['diff_bc']),
                      (df['diff_bc'] > N) & mindiff.eq(df['diff_ab'])],
                      [bc, ab],
                      default=abc)
</code>```

Solution if need mean of minimal difference of any values per rows if any difference is less like 10:

```<code>#https://stackoverflow.com/a/54861589
x = df[['A','B','C']].values
x.sort()
mask = np.any(np.diff(x) > 10, axis=1)
a = ((x[:, 1:] + x[:, :-1])/2)[np.arange(len(x)), np.diff(x).argmin(axis=1)]
df["average2"] = np.where(mask, a, x.mean(axis=1))

print (df.head(10))

    A   B   C  diff_ab  diff_bc   average1   average2
0  13   2   2       11        0   2.000000   2.000000
1   6  17  19       11        2  18.000000  18.000000
2  10   1   0        9        1   3.666667   3.666667
3  17  15   9        2        6  13.666667  13.666667
4   0  14   0       14       14   7.000000   0.000000
5  15  19  14        4        5  16.000000  16.000000
6   4   0  16        4       16   2.000000   2.000000
7   4  17   3       13       14  10.500000   3.500000
8   2   7   2        5        5   3.666667   3.666667
9  15  16   7        1        9  12.666667  12.666667
</code>```

Solution with check all columns used for count for verify/debug:

```<code>np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,20,size=(50, 3)),
columns=list('ABC'))

df['diff_ab'] = df['A'] - df['B']
df['diff_bc'] = df['B'] - df['C']
#if need difference in absolute values
#df['diff_ab'] = (df['A'] - df['B']).abs()
#df['diff_bc'] = (df['B'] - df['C']).abs()
df['mindiff'] = df[['diff_ab','diff_bc']].min(axis=1)

df['ab'] = df[['A','B']].mean(axis=1)
df['bc'] = df[['B','C']].mean(axis=1)
df['abc'] = df[['A','B','C']].mean(axis=1)

N = 10
df['average'] = np.select([(df['diff_ab'] > N) & df['mindiff'].eq(df['diff_bc']),
                           (df['diff_bc'] > N) & df['mindiff'].eq(df['diff_ab'])],
                          [df['bc'], df['ab']], default=df['abc'])
</code>```

Body:
I want to create a new column which shows the average based on multiple conditions. For the most part the new column should calculate the mean of the 3 columns. However, if the difference between A and B or B and C is greater than 10 then it should only use 2 values with the smallest difference.

For example if A = 2, B = 15 and C= 13 then the mean column should show 14. Because the difference between A and B is greater than 10 so the column should use B and C because they have the smallest difference to work out the mean.

I tried adding additional columns which determine the difference between A and B and for B and C. After that I used a conditional statement to create a list which appends the mean calculations based on the conditions and to then add the list as a column. However I get the error "Length of values does not match length of index".

This is the code used to create my dataframe:

df = pd.DataFrame(np.random.randint(0,20,size=(50, 3)),
columns=list('ABC'))

My attempt at finding a solution:

df['diff_1'] = df['A'] - df['B']
df['diff_2'] = df['B'] - df['C']

average = []
for i in df['diff_1']:
    if i < -5:
        average.append(df[['A','B']].mean(axis=1))
    if i > 5:
        average.append(df[['A','B']].mean(axis=1))
    else:
        average.append(df[['A','B','C']].mean(axis=1))

df['average'] = average

I would then have repeated for diff_2 and remove duplicates however this gives me the aforementioned error:
"Length of values does not match length of index". So am I wondering if there is a more appropriate method.

I am expecting a column which shows the average of all three columns except for when the difference between A and B or B and C is greater than 10. If that is the case it should then calculate the mean using only 2 numbers with the lowest difference.

Body:
Use numpy.select for seelct values by conditions:

np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,20,size=(50, 3)),
columns=list('ABC'))

df['diff_ab'] = (df['A'] - df['B']).abs()
df['diff_bc'] = (df['B'] - df['C']).abs()
mindiff = df[['diff_ab','diff_bc']].min(axis=1)

ab = df[['A','B']].mean(axis=1)
bc = df[['B','C']].mean(axis=1)
abc = df[['A','B','C']].mean(axis=1)

N = 10
df['average1'] = np.select([(df['diff_ab'] > N) & mindiff.eq(df['diff_bc']),
                      (df['diff_bc'] > N) & mindiff.eq(df['diff_ab'])],
                      [bc, ab],
                      default=abc)

Solution if need mean of minimal difference of any values per rows if any difference is less like 10:

#https://stackoverflow.com/a/54861589
x = df[['A','B','C']].values
x.sort()
mask = np.any(np.diff(x) > 10, axis=1)
a = ((x[:, 1:] + x[:, :-1])/2)[np.arange(len(x)), np.diff(x).argmin(axis=1)]
df["average2"] = np.where(mask, a, x.mean(axis=1))

print (df.head(10))

    A   B   C  diff_ab  diff_bc   average1   average2
0  13   2   2       11        0   2.000000   2.000000
1   6  17  19       11        2  18.000000  18.000000
2  10   1   0        9        1   3.666667   3.666667
3  17  15   9        2        6  13.666667  13.666667
4   0  14   0       14       14   7.000000   0.000000
5  15  19  14        4        5  16.000000  16.000000
6   4   0  16        4       16   2.000000   2.000000
7   4  17   3       13       14  10.500000   3.500000
8   2   7   2        5        5   3.666667   3.666667
9  15  16   7        1        9  12.666667  12.666667

Solution with check all columns used for count for verify/debug:

np.random.seed(123)
df = pd.DataFrame(np.random.randint(0,20,size=(50, 3)),
columns=list('ABC'))

df['diff_ab'] = df['A'] - df['B']
df['diff_bc'] = df['B'] - df['C']
#if need difference in absolute values
#df['diff_ab'] = (df['A'] - df['B']).abs()
#df['diff_bc'] = (df['B'] - df['C']).abs()
df['mindiff'] = df[['diff_ab','diff_bc']].min(axis=1)

df['ab'] = df[['A','B']].mean(axis=1)
df['bc'] = df[['B','C']].mean(axis=1)
df['abc'] = df[['A','B','C']].mean(axis=1)

N = 10
df['average'] = np.select([(df['diff_ab'] > N) & df['mindiff'].eq(df['diff_bc']),
                           (df['diff_bc'] > N) & df['mindiff'].eq(df['diff_ab'])],
                          [df['bc'], df['ab']], default=df['abc'])


问:
How to use @Input() correctly in an Angular 5 app?
I have the following template in the parent component:

```<code><my-table (loaded)="onTableLoaded()" [objId]="objId"></my-table>
</code>```

The problem I have is that the objId is null when loading the child component.
I can add api call in the child but I want to avoid it. Any idea how to allow
the value from api call in the parent can be transfer to child ?

答:
if you want to pass data between components in angular you should use Input and Output properties that they are from @Angular/core library. in order to pass data you should use @Input() and after that bring the name of the property that you want. for example in ts in child component you can write:

```<code>  @Input() dataEntry:boolean;
</code>```

and in your host component you use this input as a property on child component while the data is in host component:

in the host component HTML you can write :

```<code>    <child [dataEntry]="....."></child>
</code>```

but for more information you can read the documentation here:

https://angular.io/guide/component-interaction

Body:
I have the following template in the parent component:

<my-table (loaded)="onTableLoaded()" [objId]="objId"></my-table>

The problem I have is that the objId is null when loading the child component.
I can add api call in the child but I want to avoid it. Any idea how to allow
the value from api call in the parent can be transfer to child ?

Body:
if you want to pass data between components in angular you should use Input and Output properties that they are from @Angular/core library. in order to pass data you should use @Input() and after that bring the name of the property that you want. for example in ts in child component you can write:

  @Input() dataEntry:boolean;

and in your host component you use this input as a property on child component while the data is in host component:

in the host component HTML you can write :

    <child [dataEntry]="....."></child>

but for more information you can read the documentation here:

https://angular.io/guide/component-interaction


问:
How can I see if there's an available and active network connection in Python?
I want to see if I can access an online API, but for that, I need to have Internet access.

How can I see if there's a connection available and active using Python?

答:
Here's my version

```<code>import requests

try:
    if requests.get('https://google.com').ok:
        print("You're Online")
except:
    print("You're Offline")
</code>```

LastEditorDisplayName: Roger Pate

Body:
Here's my version

import requests

try:
    if requests.get('https://google.com').ok:
        print("You're Online")
except:
    print("You're Offline")