问:
tcomb - validation error message custom formatting
Currently I have a t.Number field.

When I call t.validate() on it, it gives me the following result.errors:

```<code>{
    "actual": "James King",
    "message": "Invalid value \"James King\" supplied to /user_id: Number",
    "path": ["user_id"]
}
</code>```

Is it possible to modify the output of the t.Number validation to have:

```<code>{
    "actual": "James King",
    "message": "Oops! The value is invalid",
    "path": ["user_id"]
}
</code>```

Also, am I getting that results.errors because I am in NODE_ENV "development"? If so, what results.errors will I get if I am in "production"?

答:
I figured it out in the end.

As per: https://github.com/gcanti/tcomb-validation#customise-error-messages

Attach a getValidationErrorMessage() function to the 'type'.
i.e.

```<code>Number.getValidationErrorMessage = (value, path, context) => {
  return '"'+value+'" is invalid. It must be a number.';
}
</code>```

Then made the call to tcomb-validate's validate():

const result = t.validate('s', Number);

It gave the result with the customized error message:

```<code>result Struct {
  errors:
   [ Struct {
       message: '"s" is invalid. It must be a number.',
       actual: 's',
       expected: [Object],
       path: [] } ],
  value: 's' }
</code>```

Body:
Currently I have a t.Number field.

When I call t.validate() on it, it gives me the following result.errors:

{
    "actual": "James King",
    "message": "Invalid value \"James King\" supplied to /user_id: Number",
    "path": ["user_id"]
}

Is it possible to modify the output of the t.Number validation to have:

{
    "actual": "James King",
    "message": "Oops! The value is invalid",
    "path": ["user_id"]
}

Also, am I getting that results.errors because I am in NODE_ENV "development"? If so, what results.errors will I get if I am in "production"?

Body:
I figured it out in the end.

As per: https://github.com/gcanti/tcomb-validation#customise-error-messages

Attach a getValidationErrorMessage() function to the 'type'.
i.e.

Number.getValidationErrorMessage = (value, path, context) => {
  return '"'+value+'" is invalid. It must be a number.';
}

Then made the call to tcomb-validate's validate():

const result = t.validate('s', Number);

It gave the result with the customized error message:

result Struct {
  errors:
   [ Struct {
       message: '"s" is invalid. It must be a number.',
       actual: 's',
       expected: [Object],
       path: [] } ],
  value: 's' }


来源: stackexchange

问:
How to set a DynamoDB Map property value, when the map doesn't exist yet
How do you "upsert" a property to a DynamoDB row. E.g. SET address.state = "MA" for some item, when address does not yet exist?

I feel like I'm having a chicken-and-egg problem because DynamoDB doesn't let you define a sloppy schema in advance.

If address DID already exist on that item, of type M (for Map), the internet tells me I could issue an UpdateExpression like:

SET #address.#state = :value

with #address, #state, and :value appropriately mapped to address, state, and MA, respectively.

But if the address property does not already exist, this gives an error:

'''
ValidationException: The document path provided in the update expression is invalid for update
'''

So.. it appears I either need to:

Figure out a way to "upsert" address.state (e.g., SET address = {}; SET address.state = 'MA' in a single command)

or

Issue three (!!!) roundtrips in which I try it, SET address = {}; on failure, and then try it again.

If the latter.... how do I set a blank map?!?

Ugh.. I like Dynamo, but unless I'm missing something obvious this is a bit crazy..

答:
You can do it with two round trips, the first conditionally sets an empty map for address if it doesn't already exist, and the second sets the state:

```<code>db.update({
    UpdateExpression: 'SET #a = :value',
    ConditionExpression: 'attribute_not_exists(#a)',
    ExpressionAttributeValues: {
        ":value": {},
    },
    ExpressionAttributeNames: {
        '#a': 'address'
    }
}, ...);
</code>```

Then:

```<code>db.update({
    UpdateExpression: 'SET #a.#b = :v',
    ExpressionAttributeNames: {
        '#a': 'address',
        '#b': 'state'
    },
    ExpressionAttributeValues: {
        ':v': 'whatever'
    }
}, ...);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You can do it with two round trips, the first conditionally sets an empty map for address if it doesn't already exist, and the second sets the state:

db.update({
    UpdateExpression: 'SET #a = :value',
    ConditionExpression: 'attribute_not_exists(#a)',
    ExpressionAttributeValues: {
        ":value": {},
    },
    ExpressionAttributeNames: {
        '#a': 'address'
    }
}, ...);

Then:

db.update({
    UpdateExpression: 'SET #a.#b = :v',
    ExpressionAttributeNames: {
        '#a': 'address',
        '#b': 'state'
    },
    ExpressionAttributeValues: {
        ':v': 'whatever'
    }
}, ...);

ContentLicense: CC BY-SA 4.0


问:
How to remove unwanted space below scrollview in android?
When I run this code on my device, additional space appears below the imageView. In the end, I would like my images to fulfill the greatest amount of space on the screen without distorting their dimensions. Any help would be greatly appreciated. I have attached the code for my elements and their attributes. Thanks!
    </p>

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ch0_example_problems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:clipToPadding="false"
android:fillViewport="false"
android:scrollbarStyle="insideOverlay"
tools:context="com.example.android.chsalgebra.Ch0ExampleProblems">

<Button
    android:id="@+id/prevBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="6dp"
    android:layout_marginLeft="6dp"
    android:onClick="displayProblemMinus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Previous"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<Button
    android:id="@+id/nextBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="6dp"
    android:layout_marginRight="6dp"
    android:onClick="displayProblemPlus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Next"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/prevBut1"
    android:layout_alignLeft="@+id/prevBut1"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/prevBut1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/ex1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:paddingTop="12dp"
            android:scaleType="fitStart"
            app:srcCompat="@drawable/ch0ex1" />
    </LinearLayout>
</ScrollView>
</RelativeLayout>
</code>```

答: you can set the ImageView`XML (android:scaleType="centerInside or fitCenter")</p>

Body:
When I run this code on my device, additional space appears below the imageView. In the end, I would like my images to fulfill the greatest amount of space on the screen without distorting their dimensions. Any help would be greatly appreciated. I have attached the code for my elements and their attributes. Thanks!

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_ch0_example_problems"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:clipToPadding="false"
android:fillViewport="false"
android:scrollbarStyle="insideOverlay"
tools:context="com.example.android.chsalgebra.Ch0ExampleProblems">

<Button
    android:id="@+id/prevBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_marginBottom="6dp"
    android:layout_marginLeft="6dp"
    android:onClick="displayProblemMinus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Previous"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<Button
    android:id="@+id/nextBut1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="6dp"
    android:layout_marginRight="6dp"
    android:onClick="displayProblemPlus"
    android:paddingLeft="20dp"
    android:paddingRight="20dp"
    android:text="Next"
    android:textAllCaps="false"
    android:textColor="#769ecd" />

<ScrollView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/prevBut1"
    android:layout_alignLeft="@+id/prevBut1"
    android:layout_alignParentTop="true"
    android:layout_alignStart="@+id/prevBut1">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <ImageView
            android:id="@+id/ex1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentTop="true"
            android:paddingTop="12dp"
            android:scaleType="fitStart"
            app:srcCompat="@drawable/ch0ex1" />
    </LinearLayout>
</ScrollView>
</RelativeLayout>


问:
How do we know what Cucumber jar files are needed to run Selenium Java in BDD approach?
I learn from some tutorial websites, if we want to integrate Cucumber into our Selenium Java project, we need to download all these jar files and add it into the project :

cucumber-core

cucumber-java

cucumber-junit

cucumber-jvm-deps

cucumber-reporting

gherkin

junit

mockito-all

cobertura

My question, is there any official website that show us what jar files are needed? Just like Selenium official website has download section to download all needed jar files in one zip package, so we don't miss any important jar.

I checked in Cucumber official website, there is no download section.

In this repository site , there are so many files available to download and if we don't know which one is needed, then we may get lost. How do we know what jar do we need?  Thanks a lot.

答:
It depends on what are all the libraries that you are referencing in your code.

For running basic cucumber test with junit, you need below dependencies

Cucumber-java

junit

Cucumber-junit

Selenium-java

```<code>  <dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.5</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.4</version>
    </dependency>
</dependencies>
</code>```

below is the official link for reference.
https://cucumber.io/docs/reference/jvm

cucumber-java will load most of the dependencies that you mentioned above no need to write them again.

Below is the internal dependency list of cucumber-java

```<code>  <parent>
  <groupId>info.cukes</groupId>
  <artifactId>cucumber-jvm</artifactId>
  <relativePath>../pom.xml</relativePath>
  <version>1.2.5</version>
  </parent>

   <artifactId>cucumber-java</artifactId>
   <packaging>jar</packaging>
   <name>Cucumber-JVM: Java</name>

 <dependencies>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-core</artifactId>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-jvm-deps</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>gherkin</artifactId>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>net.sourceforge.cobertura</groupId>
    <artifactId>cobertura</artifactId>
    <scope>test</scope>
</dependency>
</dependencies>
</code>```

Let me know if you have any queries

Body:
It depends on what are all the libraries that you are referencing in your code.

For running basic cucumber test with junit, you need below dependencies

Cucumber-java

junit

Cucumber-junit

Selenium-java

  <dependencies>
    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>2.53.1</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-java</artifactId>
        <version>1.2.5</version>
    </dependency>

    <dependency>
        <groupId>info.cukes</groupId>
        <artifactId>cucumber-junit</artifactId>
        <version>1.2.4</version>
    </dependency>
</dependencies>

below is the official link for reference.
https://cucumber.io/docs/reference/jvm

cucumber-java will load most of the dependencies that you mentioned above no need to write them again.

Below is the internal dependency list of cucumber-java

  <parent>
  <groupId>info.cukes</groupId>
  <artifactId>cucumber-jvm</artifactId>
  <relativePath>../pom.xml</relativePath>
  <version>1.2.5</version>
  </parent>

   <artifactId>cucumber-java</artifactId>
   <packaging>jar</packaging>
   <name>Cucumber-JVM: Java</name>

 <dependencies>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-core</artifactId>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-jvm-deps</artifactId>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>gherkin</artifactId>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>info.cukes</groupId>
    <artifactId>cucumber-junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <scope>test</scope>
</dependency>
<dependency>
    <groupId>net.sourceforge.cobertura</groupId>
    <artifactId>cobertura</artifactId>
    <scope>test</scope>
</dependency>
</dependencies>

Let me know if you have any queries


问:
Text in Textfield starts in Middle of TextField IOS
Hello the placeholder text, and the text the user inputs, starts in the middle of my textfield. I have the textfield as 30% of the screen height, so I can't simply make the textfield smaller.
How do I make the text start in the top left corner?</p>

答:
What you want to do is both a horizontal and vertical alignment like this:

```<code>textField.textAlignment = .left
textField.contentVerticalAlignment = .top
</code>```

Result:

Body:
What you want to do is both a horizontal and vertical alignment like this:

textField.textAlignment = .left
textField.contentVerticalAlignment = .top

Result:


问:
Form transition over image
I am basically trying to recreate the the Directions, Availability and Resident Login section about half way down this website http://www.livewestvillage.com/. I haven't had the chance to learn css all to well so if somebody could show me an example or a site that's good to learn this type of thing from I would appreciate it.

I've just been swamped at work so I don't really get as much time for personal projects like this anymore.

答:
Create a form tag with an id reg

Absolutely positioned the form tag in the div with class slider

Apply a transform scale property to 0x0

Apply a hover property to slider container to make the form show

click here for pen

Edit:Another approach

Create a form tag with an id reg

Absolutely positioned the form tag in the div with class slider

position the element top:100% to push it down and hide it

apply a :hover pseudo on the slider to show the form

Here is another example  click here for pen

Title: Form transition over image


问:
How to determine if a process runs inside lxc/Docker?
Is there any way to determine if a process (script) runs inside an lxc container (~ Docker runtime)? I know that some programs are able to detect whether they run inside a virtual machine, is something similar available for lxc/docker?</p>

答:
This SO Q&A: "Find out if the OS is running in a virtual environment"; though not the same as the OP's question, it does indeed answer common cases of finding which container you're in (if at all).

In particular, install and read the code of this bash script which seems to work pretty well:

virt-what :

```<code>sudo apt install virt-what
</code>```

Body:
This SO Q&A: "Find out if the OS is running in a virtual environment"; though not the same as the OP's question, it does indeed answer common cases of finding which container you're in (if at all).

In particular, install and read the code of this bash script which seems to work pretty well:

virt-what :

sudo apt install virt-what


问:
How can I implement 2 x axis in D3 version 4
I'm trying to implement two x axis (Major and minor axis) using D3.
I already have both of them been displayed, but my second axis is not displayng the domain properly.

Here's the code on codepen: http://codepen.io/wendelcosta/pen/QpzzgJ

```<code>g.append("g")
.attr("class", "axis axis--x2")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x2));
</code>```

I need to display the days for the months as minor ticks in between the major ticks (Months), it should looks like the following image.

Click Here for Image Preview

答:
You should use two time scales for the x axis.

In the "day" axis, you can set the axis generator using d3.timeDay:

```<code>call(d3.axisBottom(x2)
    .ticks(d3.timeDay.every(6))
    .tickFormat(d => d3.timeFormat("%d")(d)));
</code>```

And in the "month" axis, you increase the tick size:

```<code>call(d3.axisBottom(x)
    .tickSizeInner(20)
    .tickFormat(d3.timeFormat("%b %y")));
</code>```

Here is your updated codepen: http://codepen.io/anon/pen/bqOPRg?editors=0010

I'm printing just one on every 6 days, still the "day" axis is terribly crowded. Now it's up to you reducing the text size or reducing the number of ticks.

EDIT: Since OP asked in the comments to show only values present in the data array, here is another CodePen: http://codepen.io/anon/pen/qrvdWq?editors=0010

Body:
I'm trying to implement two x axis (Major and minor axis) using D3.
I already have both of them been displayed, but my second axis is not displayng the domain properly.

Here's the code on codepen: http://codepen.io/wendelcosta/pen/QpzzgJ

g.append("g")
.attr("class", "axis axis--x2")
.attr("transform", "translate(0," + height + ")")
.call(d3.axisBottom(x2));

I need to display the days for the months as minor ticks in between the major ticks (Months), it should looks like the following image.

Click Here for Image Preview

Body:
You should use two time scales for the x axis.

In the "day" axis, you can set the axis generator using d3.timeDay:

call(d3.axisBottom(x2)
    .ticks(d3.timeDay.every(6))
    .tickFormat(d => d3.timeFormat("%d")(d)));

And in the "month" axis, you increase the tick size:

call(d3.axisBottom(x)
    .tickSizeInner(20)
    .tickFormat(d3.timeFormat("%b %y")));

Here is your updated codepen: http://codepen.io/anon/pen/bqOPRg?editors=0010

I'm printing just one on every 6 days, still the "day" axis is terribly crowded. Now it's up to you reducing the text size or reducing the number of ticks.

EDIT: Since OP asked in the comments to show only values present in the data array, here is another CodePen: http://codepen.io/anon/pen/qrvdWq?editors=0010


问:
Hosting ASP.NET Core as Windows service
As I get it in RC2 there's a support for hosting applications within Windows Services. I tried to test it on a simple web api project (using .NET Framework 4.6.1).

Here's my Program.cs code:

```<code>using System;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;

namespace WebApplication4
{
  public class Program : ServiceBase
  {
    public static void Main(string[] args)
    {
      if (args.Contains("--windows-service"))
      {
        Run(new Program());
        return;
      }

      var program = new Program();
      program.OnStart(null);
      Console.ReadLine();
      program.OnStop();
    }

    protected override void OnStart(string[] args)
    {
      var host = new WebHostBuilder()
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseStartup<Startup>()
      .Build();

      host.RunAsService();
    }

    protected override void OnStop() {}
  }
}
</code>```

All the other stuff are basically from .NET Core template (though I changed framework to net461 and added some dependencies in project.json).

After publishing it with dotnet publish and creating Windows Service with sc create I can succesfully start my service, but I can't reach any of my controllers (ports are not listeting). I assume I'm doing something wrong.

So I guess the main question is how to make self hosted web api and run it as Windows Service. All found solutions don't work after RC2 update.

答:
Windows Services can be easily created with Visual Studio 2017. You will need to move your .NET Core code to a class library that targets NetStandard that can then be referenced. Your Windows Service project will have to target the full .NET Framework but can reference your shared library.

By putting all of your code in the class library you would then have portability between the Windows Service and other non Windows apps.

With VS 2015 you couldn't make a Windows Service project and reference a .NET Core xproj. Visual Studio 2017 fixes that once you convert all your projects to csproj.

This blog walks through it in more detail: How to Create .NET Core Windows Services With Visual Studio 2017

Title: Hosting ASP.NET Core as Windows service

Body:
As I get it in RC2 there's a support for hosting applications within Windows Services. I tried to test it on a simple web api project (using .NET Framework 4.6.1).

Here's my Program.cs code:

using System;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;

namespace WebApplication4
{
  public class Program : ServiceBase
  {
    public static void Main(string[] args)
    {
      if (args.Contains("--windows-service"))
      {
        Run(new Program());
        return;
      }

      var program = new Program();
      program.OnStart(null);
      Console.ReadLine();
      program.OnStop();
    }

    protected override void OnStart(string[] args)
    {
      var host = new WebHostBuilder()
      .UseKestrel()
      .UseContentRoot(Directory.GetCurrentDirectory())
      .UseStartup<Startup>()
      .Build();

      host.RunAsService();
    }

    protected override void OnStop() {}
  }
}

All the other stuff are basically from .NET Core template (though I changed framework to net461 and added some dependencies in project.json).

After publishing it with dotnet publish and creating Windows Service with sc create I can succesfully start my service, but I can't reach any of my controllers (ports are not listeting). I assume I'm doing something wrong.

So I guess the main question is how to make self hosted web api and run it as Windows Service. All found solutions don't work after RC2 update.


问:
Plot a row in Panda/Python
I know it can look basic but I didnt find anything about it...

In panda I have a dataframe with one row only. the index is a date and the columns are the date, the data are regular figures...

I want to plot all the row... any idea?

```<code>            2017-03-23  2017-03-22  2017-03-21  2017-03-20  2017-03-17  2017-03-16
maturity
2020-04-30       41       -20         15.3         21.21       -0.86        61.2
</code>```

答:
You have to select a row by it index and then plot:

```<code>row = df.iloc[0]
row.plot()
</code>```

Title: Plot a row in Panda/Python

Body:
I know it can look basic but I didnt find anything about it...

In panda I have a dataframe with one row only. the index is a date and the columns are the date, the data are regular figures...

I want to plot all the row... any idea?

            2017-03-23  2017-03-22  2017-03-21  2017-03-20  2017-03-17  2017-03-16
maturity
2020-04-30       41       -20         15.3         21.21       -0.86        61.2

Body:
You have to select a row by it index and then plot:

row = df.iloc[0]
row.plot()


答:
Another totally different method is to simply create the address node when creating the parent document in the first place.  For example assuming you have a hash key of id, you might do:

```<code>db.put({
    Item: {
        id: 42,
        address: {}
    }
}, ...);
</code>```

This will allow you to simply set the address.state value as the address map already exists:

```<code>db.update({
    UpdateExpression: 'SET #a.#b = :v',
    AttributeExpressionNames: {
        '#a': 'address',
        '#b': 'state'
    },
    AttributeExpressionValues: {
        ':v': 'whatever'
    }
}, ...);
</code>```

Title: How to set a DynamoDB Map property value, when the map doesn't exist yet

Body:
How do you "upsert" a property to a DynamoDB row. E.g. SET address.state = "MA" for some item, when address does not yet exist?

I feel like I'm having a chicken-and-egg problem because DynamoDB doesn't let you define a sloppy schema in advance.

If address DID already exist on that item, of type M (for Map), the internet tells me I could issue an UpdateExpression like:

SET #address.#state = :value

with #address, #state, and :value appropriately mapped to address, state, and MA, respectively.

But if the address property does not already exist, this gives an error:

'''
ValidationException: The document path provided in the update expression is invalid for update
'''

So.. it appears I either need to:

Figure out a way to "upsert" address.state (e.g., SET address = {}; SET address.state = 'MA' in a single command)

or

Issue three (!!!) roundtrips in which I try it, SET address = {}; on failure, and then try it again.

If the latter.... how do I set a blank map?!?

Ugh.. I like Dynamo, but unless I'm missing something obvious this is a bit crazy..

Body:
Another totally different method is to simply create the address node when creating the parent document in the first place.  For example assuming you have a hash key of id, you might do:

db.put({
    Item: {
        id: 42,
        address: {}
    }
}, ...);

This will allow you to simply set the address.state value as the address map already exists:

db.update({
    UpdateExpression: 'SET #a.#b = :v',
    AttributeExpressionNames: {
        '#a': 'address',
        '#b': 'state'
    },
    AttributeExpressionValues: {
        ':v': 'whatever'
    }
}, ...);


问:
Showing all current visitors cursors live
What would be the best way of showing all the current visitors cursors live in each browser window?

Is this achievable at all, without too much lag?

This is my attempt with meteor js:

http://meteorpad.com/pad/rCSsroc4G4gYQGkAY/Leaderboard (mind the name, can't change it?)

http://allofthecursors.meteor.com/

cursors.js:

```<code>Cursors = new Mongo.Collection("Cursors");

if (Meteor.isClient) {
  Meteor.startup(function () {
      if(!Session.get('cursorId')) {
        // todo: not unique enough!
        var cursorId = new Date();

        Session.set('cursorId', cursorId);
        Meteor.call('initCursor', cursorId);
      }
  });

  Template.cursor.helpers({
    cursor: function() {
      return Cursors.findOne({ cursorId: Session.get('cursorId') });
    },
    cursors: function() {
      return Cursors.find({ cursorId: { $ne: Session.get('cursorId') } });
    }
  });

  Template.cursor.events({
    "mousemove": function(event) {
      var x = event.pageX,
          y = event.pageY,
          cursorId = Session.get('cursorId');

      Meteor.call('updateCursor', cursorId, x, y);
    }
  });
}

if (Meteor.isServer) {

  Meteor.methods({
    'initCursor': function(cursorId) {
        Cursors.insert({
          cursorId: cursorId,
          x: 0,
          y: 0
        });
    },
    'updateCursor': function(cursorId, x, y) {
      Cursors.update(
        { cursorId: cursorId },
        { $set: { x: x, y: y }}
      );
    }
  });
}
</code>```

cursors.html

```<code><head>
  <title>cursors</title>
</head>
<body>

    {{> cursor}}

</body>

<template name="cursor">
    <div class="cursors-area">
        {{#each cursors}}
            <div class="cursor" style="top: {{y}}px; left: {{x}}px;"></div>
        {{/each}}

        <div class="my-cursor">
            {{cursor.cursorId}}: {{cursor.x}}, {{cursor.y}}
        </div>
    </div>
</template>
</code>```

cursors.css

```<code>html, body {
    margin: 0;
    padding: 0;
}

.cursors-area {
    height: 100vh;
}

.cursor {
    position: fixed;
    width: 11px;
    height: 17px;
    background-image: url(cursor.png);
}
</code>```

Thanks for the response evrybady. Here's an updated version.

Added the streams package:
$ meteor add lepozepo:streams

The client side collection is only used to access the reactive capabilities.

cursors_2.js

```<code>Stream = new Meteor.Stream('public');

if( Meteor.isClient ) {

  Cursors = new Mongo.Collection(null);

  Template.cursor.events({
    'mousemove': function(event) {

      if (Meteor.status().connected) {
        Stream.emit('p', {
          _id: Meteor.connection._lastSessionId,
          x: event.pageX,
          y: event.pageY
        });
      }

    }
  });

  Stream.on('p', function(p) {

    // how can I change this?

    if( Cursors.findOne(p._id) === undefined ) {

      Cursors.insert({
        _id: p._id,
        x: p.x,
        y: p.y
      });

    } else {

      Cursors.update(p._id, {
          $set: {
            x: p.x,
            y: p.y
          }
        }
      );
    }

  });

  function getCursors() {
    return Cursors.find();
  }
  var throttledGetCursors = _.throttle(getCursors, 50);

  Template.cursor.helpers({
    cursors: throttledGetCursors
  });
}
</code>```

答:
Use WebRTC for this. Google for it. </p>

<p>Essentially you're going to use some JavaScript to connect your two browsers together, Meteor will send the handshake, then the two browsers can talk. From here, you can do all sorts of data intensive stuff without blowing up Meteor or your clients. Ez. Pz. </p>

Body:
What would be the best way of showing all the current visitors cursors live in each browser window?

Is this achievable at all, without too much lag?

This is my attempt with meteor js:

http://meteorpad.com/pad/rCSsroc4G4gYQGkAY/Leaderboard (mind the name, can't change it?)

http://allofthecursors.meteor.com/

cursors.js:

Cursors = new Mongo.Collection("Cursors");

if (Meteor.isClient) {
  Meteor.startup(function () {
      if(!Session.get('cursorId')) {
        // todo: not unique enough!
        var cursorId = new Date();

        Session.set('cursorId', cursorId);
        Meteor.call('initCursor', cursorId);
      }
  });

  Template.cursor.helpers({
    cursor: function() {
      return Cursors.findOne({ cursorId: Session.get('cursorId') });
    },
    cursors: function() {
      return Cursors.find({ cursorId: { $ne: Session.get('cursorId') } });
    }
  });

  Template.cursor.events({
    "mousemove": function(event) {
      var x = event.pageX,
          y = event.pageY,
          cursorId = Session.get('cursorId');

      Meteor.call('updateCursor', cursorId, x, y);
    }
  });
}

if (Meteor.isServer) {

  Meteor.methods({
    'initCursor': function(cursorId) {
        Cursors.insert({
          cursorId: cursorId,
          x: 0,
          y: 0
        });
    },
    'updateCursor': function(cursorId, x, y) {
      Cursors.update(
        { cursorId: cursorId },
        { $set: { x: x, y: y }}
      );
    }
  });
}

cursors.html

  <title>cursors</title>

    {{> cursor}}

<template name="cursor">

        {{#each cursors}}

        {{/each}}

            {{cursor.cursorId}}: {{cursor.x}}, {{cursor.y}}

</template>

cursors.css

html, body {
    margin: 0;
    padding: 0;
}

.cursors-area {
    height: 100vh;
}

.cursor {
    position: fixed;
    width: 11px;
    height: 17px;
    background-image: url(cursor.png);
}

Thanks for the response evrybady. Here's an updated version.

Added the streams package:
$ meteor add lepozepo:streams

The client side collection is only used to access the reactive capabilities.

cursors_2.js

Stream = new Meteor.Stream('public');

if( Meteor.isClient ) {

  Cursors = new Mongo.Collection(null);

  Template.cursor.events({
    'mousemove': function(event) {

      if (Meteor.status().connected) {
        Stream.emit('p', {
          _id: Meteor.connection._lastSessionId,
          x: event.pageX,
          y: event.pageY
        });
      }

    }
  });

  Stream.on('p', function(p) {

    // how can I change this?

    if( Cursors.findOne(p._id) === undefined ) {

      Cursors.insert({
        _id: p._id,
        x: p.x,
        y: p.y
      });

    } else {

      Cursors.update(p._id, {
          $set: {
            x: p.x,
            y: p.y
          }
        }
      );
    }

  });

  function getCursors() {
    return Cursors.find();
  }
  var throttledGetCursors = _.throttle(getCursors, 50);

  Template.cursor.helpers({
    cursors: throttledGetCursors
  });
}

Body:
Use WebRTC for this. Google for it.

Essentially you're going to use some JavaScript to connect your two browsers together, Meteor will send the handshake, then the two browsers can talk. From here, you can do all sorts of data intensive stuff without blowing up Meteor or your clients. Ez. Pz.


问:
simultaneously exec multiple shell_exec() commands?
Hi so i am wondering if somebody can offer me a solution..

I have multiple instances of a php script i would like to run at once, I can semi achieve this using shell_exec() and not waiting for a response apart from the pid. This works wonderfully. However when doing this with the method below it works well for 100 or so executes but I need it to execute around 1000 times and it is taking too long to loop around the foreach and execute 1 by one.

Example:

```<code> $items = $array(daatabase entries);

   foreach($items as $i){
    $pid = shell_exec("execute the process.php");
   }
</code>```

Now assuming there are < 100 this will take around 1 second or so to exec which is OK however i need to run loads of these and this will take 10-20 seconds.

Is there any way of sending the commands in bulk rather than 1 at a time?

Thanks

答:
You can execute process.php in background without waiting for execution completion. So it will be faster. Also shell_exec() function returns only output, not pid. If you need pid you have to use exec() function.

```<code>   $items = $array(daatabase entries);
   foreach($items as $i){
      shell_exec("execute the process.php > /dev/null 2>&1");
   }
</code>```

Body:
Hi so i am wondering if somebody can offer me a solution..

I have multiple instances of a php script i would like to run at once, I can semi achieve this using shell_exec() and not waiting for a response apart from the pid. This works wonderfully. However when doing this with the method below it works well for 100 or so executes but I need it to execute around 1000 times and it is taking too long to loop around the foreach and execute 1 by one.

Example:

 $items = $array(daatabase entries);

   foreach($items as $i){
    $pid = shell_exec("execute the process.php");
   }

Now assuming there are < 100 this will take around 1 second or so to exec which is OK however i need to run loads of these and this will take 10-20 seconds.

Is there any way of sending the commands in bulk rather than 1 at a time?

Thanks

Body:
You can execute process.php in background without waiting for execution completion. So it will be faster. Also shell_exec() function returns only output, not pid. If you need pid you have to use exec() function.

   $items = $array(daatabase entries);
   foreach($items as $i){
      shell_exec("execute the process.php > /dev/null 2>&1");
   }


问:
Batch file txt transformation
I have a convert request, need to transform a txt file to show up only the distincted folders in BATCH.

So here is an example file:

```<code>zpaq v7.15 journaling archiver, compiled Aug 17 2016
zpaq_m1.zpaq: 1 versions, 14 files, 125 fragments, 4.521800 MB

- 2017-03-31 21:22:24      9025719 D     c:/2/testdata/
- 2016-09-26 13:26:07         9149 A     c:/2/testdata/test.txt
- 2017-03-31 21:22:48      9014621 D     c:/2/testdata/Subfolder/
- 2017-03-31 21:22:59        11856 D     c:/2/testdata/Subfolder/History/
- 2017-03-31 21:22:24        11856 D     c:/2/testdata/Subfolder/History/2016-03-12/
- 2016-03-11 23:31:49         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h31m49s  v1.9.m3p
- 2016-03-11 23:36:47         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h36m47s  v1.9.m3p
- 2016-03-11 23:37:09         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h37m09s  v1.9.m3p
- 2016-03-11 23:38:34         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h38m34s  v1.9.m3p
- 2016-03-11 23:40:00         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h40m00s  v1.9.m3p
- 2016-03-11 23:40:25         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h40m25s  v1.9.m3p
- 2016-03-11 23:39:43      9001472 A     c:/2/testdata/Subfolder/test.exe
- 2017-03-28 10:45:03         1293 A     c:/2/testdata/Subfolder/test.ini
- 2016-09-26 14:04:43         1949 A     c:/2/testdata/todo.txt

9.025719 MB of 9.025719 MB (14 files) shown
  -> 9.017815 MB (129 refs to 125 of 125 frags) after dedupe
  -> 4.521800 MB compressed.
</code>```

So here are the steps which I want to transform the file:

Remove the first three lines

Remove the last four lines

Cut the first 41 letters of each line

Replace Forward slash to Backslash

Remove everything after the last Backslash (so the filenames)

Distinct the file, so that each Folder is only be there once

So the final Result should be:

```<code>c:\2\testdata\
c:\2\testdata\Subfolder\
c:\2\testdata\Subfolder\History\
c:\2\testdata\Subfolder\History\2016-03-12\
</code>```

Thanks a lot for your help

Here is my current status:

```<code>::delete first 2 lines
for /f "skip=1 delims=*" %%a in (Listing.txt) do (
echo %%a >>Listing2.txt
)

::delete last 3 lines
@echo off
setlocal enabledelayedexpansion
set count=
for /f %%x in ('type Listing2.txt ^| find /c /v ""') do set /a lines=%%x-3
copy /y nul %tmp%\tmp.zzz > nul
for /f "tokens=*" %%x in ('type Listing2.txt ^| find /v ""') do (
  set /a count=count+1
  if !count! leq %lines% echo %%x>>%tmp%\tmp.zzz
)
move /y %tmp%\tmp.zzz Listing2.txt > nul

::Delete last cr flag at the end of the file
::@echo off
setlocal DisableDelayedExpansion
set "firstLineReady="
(
    for /F "eol=$ delims=" %%a in (Listing2.txt) DO (
        if defined firstLineReady (echo()
        set "firstLineReady=1"
        <nul set /p "=%%a"
    )
) > Listing_Final.txt
del Listing2.txt /f /q

::take everything after line 1 und each line after character41
for /f "skip=1 usebackq delims=" %%i in ("Listing_Final.txt") do call :ProcessLine "%%i"
:PROCESSLINE
set "Zeile=%~1"
::put everything after 41
(echo %Zeile:~41%)>>"Listing_Final_Folder_Files_temp.txt"

del Listing_Final.txt /f /q

::Remove double entries
::@ECHO OFF
SETLOCAL
:: remove variables starting $
FOR  /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="

FOR /f "delims=" %%a IN (Listing_Final_Folder_Files_temp.txt) DO SET $%%a=Y
(FOR  /F "delims=$=" %%a In ('set $ 2^>Nul') DO ECHO %%a)>Listing_Final_Folder_Files_temp2.txt

::del Listing_Final_Folder_Files_temp.txt /f /q
</code>```

Now I am trying to convert the slash to backslash but with this code it is not working:

```<code>::Replace / to \
echo off
setlocal enabledelayedexpansion
FOR %%f IN ("Listing_Final.txt") DO (
 set old=%%f
 echo !old!
 set new=!old:/=\!
 echo !new!>tesss.txt
 echo.
)
</code>```

The last step is to remove everything after the last \ but I did not find anything.

答:
May I suggest you to use an entirely different method?

Instead of remove the first three and last four lines, you may process just the lines that start with "-"; this allows to process any file with more or less lines.

Instead of cut the first 41 characters of each line, you may process just the 6th space-delimited token of each line.

Instead of remove everything after the last Backslash, you may get the drive and path of such a token. This also automatically converts any Forward slash to Backslash.

Finally, you may use such a value as subscript to define array elements, so just elements with unique subscripts remains, instead of look for and delete duplicate elements.

.

```<code>@echo off
setlocal EnableDelayedExpansion

rem Processing lines that have a dash in first column, get the sixth token
for /F "tokens=6" %%a in ('findstr "^-" Listing.txt') do (

   rem Get just the drive and path of sixth token
   rem at same time, convert Forward slash to Backslash
   rem and use it as the subscript of an array,
   rem so just unique elements are stored:

   set "folder[%%~DPa]=1"
)

rem Show the result
for /F "tokens=2 delims=[]" %%a in ('set folder[') do echo %%a
</code>```

Output:

```<code>c:\2\testdata\Subfolder\History\2016-03-12\
c:\2\testdata\Subfolder\History\
c:\2\testdata\Subfolder\
c:\2\testdata\
</code>```

Title: Batch file txt transformation

Body:
I have a convert request, need to transform a txt file to show up only the distincted folders in BATCH.

So here is an example file:

zpaq v7.15 journaling archiver, compiled Aug 17 2016
zpaq_m1.zpaq: 1 versions, 14 files, 125 fragments, 4.521800 MB

- 2017-03-31 21:22:24      9025719 D     c:/2/testdata/
- 2016-09-26 13:26:07         9149 A     c:/2/testdata/test.txt
- 2017-03-31 21:22:48      9014621 D     c:/2/testdata/Subfolder/
- 2017-03-31 21:22:59        11856 D     c:/2/testdata/Subfolder/History/
- 2017-03-31 21:22:24        11856 D     c:/2/testdata/Subfolder/History/2016-03-12/
- 2016-03-11 23:31:49         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h31m49s  v1.9.m3p
- 2016-03-11 23:36:47         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h36m47s  v1.9.m3p
- 2016-03-11 23:37:09         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h37m09s  v1.9.m3p
- 2016-03-11 23:38:34         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h38m34s  v1.9.m3p
- 2016-03-11 23:40:00         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h40m00s  v1.9.m3p
- 2016-03-11 23:40:25         1976 A     c:/2/testdata/Subfolder/History/2016-03-12/00h40m25s  v1.9.m3p
- 2016-03-11 23:39:43      9001472 A     c:/2/testdata/Subfolder/test.exe
- 2017-03-28 10:45:03         1293 A     c:/2/testdata/Subfolder/test.ini
- 2016-09-26 14:04:43         1949 A     c:/2/testdata/todo.txt

9.025719 MB of 9.025719 MB (14 files) shown
  -> 9.017815 MB (129 refs to 125 of 125 frags) after dedupe
  -> 4.521800 MB compressed.

So here are the steps which I want to transform the file:

Remove the first three lines

Remove the last four lines

Cut the first 41 letters of each line

Replace Forward slash to Backslash

Remove everything after the last Backslash (so the filenames)

Distinct the file, so that each Folder is only be there once

So the final Result should be:

c:\2\testdata\
c:\2\testdata\Subfolder\
c:\2\testdata\Subfolder\History\
c:\2\testdata\Subfolder\History\2016-03-12\

Thanks a lot for your help

Here is my current status:

::delete first 2 lines
for /f "skip=1 delims=*" %%a in (Listing.txt) do (
echo %%a >>Listing2.txt
)

::delete last 3 lines
@echo off
setlocal enabledelayedexpansion
set count=
for /f %%x in ('type Listing2.txt ^| find /c /v ""') do set /a lines=%%x-3
copy /y nul %tmp%\tmp.zzz > nul
for /f "tokens=*" %%x in ('type Listing2.txt ^| find /v ""') do (
  set /a count=count+1
  if !count! leq %lines% echo %%x>>%tmp%\tmp.zzz
)
move /y %tmp%\tmp.zzz Listing2.txt > nul

::Delete last cr flag at the end of the file
::@echo off
setlocal DisableDelayedExpansion
set "firstLineReady="
(
    for /F "eol=$ delims=" %%a in (Listing2.txt) DO (
        if defined firstLineReady (echo()
        set "firstLineReady=1"
        <nul set /p "=%%a"
    )
) > Listing_Final.txt
del Listing2.txt /f /q

::take everything after line 1 und each line after character41
for /f "skip=1 usebackq delims=" %%i in ("Listing_Final.txt") do call :ProcessLine "%%i"
:PROCESSLINE
set "Zeile=%~1"
::put everything after 41
(echo %Zeile:~41%)>>"Listing_Final_Folder_Files_temp.txt"

del Listing_Final.txt /f /q

::Remove double entries
::@ECHO OFF
SETLOCAL
:: remove variables starting $
FOR  /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="

FOR /f "delims=" %%a IN (Listing_Final_Folder_Files_temp.txt) DO SET $%%a=Y
(FOR  /F "delims=$=" %%a In ('set $ 2^>Nul') DO ECHO %%a)>Listing_Final_Folder_Files_temp2.txt

::del Listing_Final_Folder_Files_temp.txt /f /q

Now I am trying to convert the slash to backslash but with this code it is not working:

::Replace / to \
echo off
setlocal enabledelayedexpansion
FOR %%f IN ("Listing_Final.txt") DO (
 set old=%%f
 echo !old!
 set new=!old:/=\!
 echo !new!>tesss.txt
 echo.
)

The last step is to remove everything after the last \ but I did not find anything.

Body:
May I suggest you to use an entirely different method?

Instead of remove the first three and last four lines, you may process just the lines that start with "-"; this allows to process any file with more or less lines.

Instead of cut the first 41 characters of each line, you may process just the 6th space-delimited token of each line.

Instead of remove everything after the last Backslash, you may get the drive and path of such a token. This also automatically converts any Forward slash to Backslash.

Finally, you may use such a value as subscript to define array elements, so just elements with unique subscripts remains, instead of look for and delete duplicate elements.

.

@echo off
setlocal EnableDelayedExpansion

rem Processing lines that have a dash in first column, get the sixth token
for /F "tokens=6" %%a in ('findstr "^-" Listing.txt') do (

   rem Get just the drive and path of sixth token
   rem at same time, convert Forward slash to Backslash
   rem and use it as the subscript of an array,
   rem so just unique elements are stored:

   set "folder[%%~DPa]=1"
)

rem Show the result
for /F "tokens=2 delims=[]" %%a in ('set folder[') do echo %%a

Output:

c:\2\testdata\Subfolder\History\2016-03-12\
c:\2\testdata\Subfolder\History\
c:\2\testdata\Subfolder\
c:\2\testdata\


问:
crystal report & sub report
am developing a payroll project in vb.net with SQL server, in this am using SEAGATE crystal report for taking reports, if i use more than 10 sub reports in single report weather it affect my project efficiency or it will take more time </p>

答:
Yes, it will take more time since you're in effect probably running 10 different queries and the reporting tool is probably having to link the results of all of those queries.

I've written reports with 3 or 4 subreports, but usually more is unnecessary.  I would try to think of a workaround for that many subreports - usually there's a way.  (For example, use a column as a toggle for showing/hiding or grouping data.)

ContentLicense: CC BY-SA 2.5

Title: crystal report & sub report


问:
Initialising AVAudioSessionModeMeasurement
Hey there I'm definitely out of my depth here, however unfortunately its too late to turn back as I was provided the project by a lecturer.

I'm trying to disable the system supplied signal processing applied to my input by using AVAudioSessionModeMeasurement within my project.

However I'm struggling to find any sources on doing this.

My desired outcome is that by enabling this I will be able to make more accurate readings within my application.

Here is the code:

```<code>#import "ViewController.h"

@import AudioToolbox;
@import AVFoundation;

#define kOutputBus 0
#define kInputBus 1

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UILabel *dBSPLView2;

@end

@implementation ViewController

static AudioComponentInstance audioUnit;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self setupAudio];
}

- (void) setupAudio {

    AudioComponentDescription desc;

    desc.componentType = kAudioUnitType_Output;
    desc.componentSubType = kAudioUnitSubType_RemoteIO;
    desc.componentManufacturer = kAudioUnitManufacturer_Apple;
    desc.componentFlags = 0;
    desc.componentFlagsMask = 0;

    AudioComponent comp = AudioComponentFindNext(NULL, &desc);

    OSStatus status = AudioComponentInstanceNew(comp, &audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    AudioStreamBasicDescription audioFormat;

    audioFormat.mSampleRate = 96000.00;
    audioFormat.mFormatID = kAudioFormatLinearPCM;
    audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
    audioFormat.mFramesPerPacket = 1;
    audioFormat.mChannelsPerFrame = 1;
    audioFormat.mBitsPerChannel = 16;
    audioFormat.mBytesPerFrame = audioFormat.mChannelsPerFrame * sizeof(SInt16);
    audioFormat.mBytesPerPacket = audioFormat.mFramesPerPacket * audioFormat.mBytesPerFrame;

    UInt32 flag = 1;
    status = AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, kInputBus, &flag, sizeof(flag));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    flag = 0;
    status = AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, kOutputBus, &flag, sizeof(flag));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    status = AudioUnitSetProperty(audioUnit , kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kInputBus, &audioFormat, sizeof(audioFormat));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    AURenderCallbackStruct callbackStruct;
    callbackStruct.inputProc = recordingCallback;
    callbackStruct.inputProcRefCon = (__bridge void*)self;

    status = AudioUnitSetProperty(audioUnit , kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, kInputBus, &callbackStruct, sizeof(callbackStruct));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    status = AudioUnitInitialize(audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

}

static OSStatus recordingCallback(

                                  void *inRefCon,
                                  AudioUnitRenderActionFlags *ioActionFlags,
                                  const AudioTimeStamp *inTimeStamp,
                                  UInt32 inBusNumber,
                                  UInt32 inNumberFrames,
                                  AudioBufferList *ioData

                            ) {

    AudioBuffer buffer;

    buffer.mNumberChannels = 1;
    buffer.mDataByteSize = inNumberFrames * sizeof(SInt16);
    buffer.mData = malloc(buffer.mDataByteSize);

    AudioBufferList bufferList;
    bufferList.mNumberBuffers = 1;
    bufferList.mBuffers[0] = buffer;

    OSStatus status = AudioUnitRender(audioUnit , ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, &bufferList);
    if (status != noErr) {
        printf("Error\n");
        return -1;
    }

    SInt16 *frameBuffer = buffer.mData;

    double totalAmplitude = 0;

    for (int i = 0; i < inNumberFrames; i++) {
       // printf("%i\n",frameBuffer[i]);

        totalAmplitude += frameBuffer[i] * frameBuffer[i];
    }

    totalAmplitude /= inNumberFrames;

    totalAmplitude = sqrt(totalAmplitude);

    //Creates a negative number that goes no higher than zero
    //float SPLFloat = totalAmplitude / (float)SHRT_MAX * 2;

    float dBFloat = (20 * log10(totalAmplitude)) + 11;

    dispatch_async(dispatch_get_main_queue(), ^{
        ViewController *viewController = (__bridge ViewController*)inRefCon;
        viewController.dBSPLView2.text = [NSString stringWithFormat:@"%.f", dBFloat];
    });

    return noErr;
}

- (IBAction)recordButtonPressed:(id)sender {
    NSError *error;
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    if (error != nil) {
        NSAssert(error == nil, @"Error");
    }
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error];
    if (error != nil) {
        NSAssert(error == nil, @"Error");
    }

    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        if (granted) {
            OSStatus status = AudioOutputUnitStart(audioUnit);
            if (status != noErr) {
                NSAssert(status == noErr,@"Error");
            }
        } else {
            NSAssert(NO, @"Error");
        }
    }];
}

- (IBAction)stopButtonPressed:(id)sender {
    OSStatus status = AudioOutputUnitStop(audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }
    NSError *error;
    [[AVAudioSession sharedInstance] setActive:NO error:&error];
    if (error != nil) {
        NSAssert(error == nil, @"Error");
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) dealloc {
    OSStatus status = AudioComponentInstanceDispose(audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }
}

@end
</code>```

答:
After you configure the category for the session:

```<code>[[AVAudioSession sharedInstance] setMode:AVAudioSessionModeMeasurement error:&error];
if (error != nil) {
    NSAssert(error == nil, @"Error");
}
</code>```

Also, your error handling doesn't follow the established pattern. You should check the return value of setMode:error:. The error in/out parameter is only guaranteed to be valid when the return value from the method is NO. (In practice, checking that error is nil probably works fine in most cases, but it's not documented to work that way - so you shouldn't rely on it.)

Body:
Hey there I'm definitely out of my depth here, however unfortunately its too late to turn back as I was provided the project by a lecturer.

I'm trying to disable the system supplied signal processing applied to my input by using AVAudioSessionModeMeasurement within my project.

However I'm struggling to find any sources on doing this.

My desired outcome is that by enabling this I will be able to make more accurate readings within my application.

Here is the code:

#import "ViewController.h"

@import AudioToolbox;
@import AVFoundation;

#define kOutputBus 0
#define kInputBus 1

@interface ViewController ()

@property (nonatomic, weak) IBOutlet UILabel *dBSPLView2;

@end

@implementation ViewController

static AudioComponentInstance audioUnit;

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self setupAudio];
}

- (void) setupAudio {

    AudioComponentDescription desc;

    desc.componentType = kAudioUnitType_Output;
    desc.componentSubType = kAudioUnitSubType_RemoteIO;
    desc.componentManufacturer = kAudioUnitManufacturer_Apple;
    desc.componentFlags = 0;
    desc.componentFlagsMask = 0;

    AudioComponent comp = AudioComponentFindNext(NULL, &desc);

    OSStatus status = AudioComponentInstanceNew(comp, &audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    AudioStreamBasicDescription audioFormat;

    audioFormat.mSampleRate = 96000.00;
    audioFormat.mFormatID = kAudioFormatLinearPCM;
    audioFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
    audioFormat.mFramesPerPacket = 1;
    audioFormat.mChannelsPerFrame = 1;
    audioFormat.mBitsPerChannel = 16;
    audioFormat.mBytesPerFrame = audioFormat.mChannelsPerFrame * sizeof(SInt16);
    audioFormat.mBytesPerPacket = audioFormat.mFramesPerPacket * audioFormat.mBytesPerFrame;

    UInt32 flag = 1;
    status = AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, kInputBus, &flag, sizeof(flag));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    flag = 0;
    status = AudioUnitSetProperty(audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Output, kOutputBus, &flag, sizeof(flag));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    status = AudioUnitSetProperty(audioUnit , kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, kInputBus, &audioFormat, sizeof(audioFormat));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    AURenderCallbackStruct callbackStruct;
    callbackStruct.inputProc = recordingCallback;
    callbackStruct.inputProcRefCon = (__bridge void*)self;

    status = AudioUnitSetProperty(audioUnit , kAudioOutputUnitProperty_SetInputCallback, kAudioUnitScope_Global, kInputBus, &callbackStruct, sizeof(callbackStruct));
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

    status = AudioUnitInitialize(audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }

}

static OSStatus recordingCallback(

                                  void *inRefCon,
                                  AudioUnitRenderActionFlags *ioActionFlags,
                                  const AudioTimeStamp *inTimeStamp,
                                  UInt32 inBusNumber,
                                  UInt32 inNumberFrames,
                                  AudioBufferList *ioData

                            ) {

    AudioBuffer buffer;

    buffer.mNumberChannels = 1;
    buffer.mDataByteSize = inNumberFrames * sizeof(SInt16);
    buffer.mData = malloc(buffer.mDataByteSize);

    AudioBufferList bufferList;
    bufferList.mNumberBuffers = 1;
    bufferList.mBuffers[0] = buffer;

    OSStatus status = AudioUnitRender(audioUnit , ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, &bufferList);
    if (status != noErr) {
        printf("Error\n");
        return -1;
    }

    SInt16 *frameBuffer = buffer.mData;

    double totalAmplitude = 0;

    for (int i = 0; i < inNumberFrames; i++) {
       // printf("%i\n",frameBuffer[i]);

        totalAmplitude += frameBuffer[i] * frameBuffer[i];
    }

    totalAmplitude /= inNumberFrames;

    totalAmplitude = sqrt(totalAmplitude);

    //Creates a negative number that goes no higher than zero
    //float SPLFloat = totalAmplitude / (float)SHRT_MAX * 2;

    float dBFloat = (20 * log10(totalAmplitude)) + 11;

    dispatch_async(dispatch_get_main_queue(), ^{
        ViewController *viewController = (__bridge ViewController*)inRefCon;
        viewController.dBSPLView2.text = [NSString stringWithFormat:@"%.f", dBFloat];
    });

    return noErr;
}

- (IBAction)recordButtonPressed:(id)sender {
    NSError *error;
    [[AVAudioSession sharedInstance] setActive:YES error:&error];
    if (error != nil) {
        NSAssert(error == nil, @"Error");
    }
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryRecord error:&error];
    if (error != nil) {
        NSAssert(error == nil, @"Error");
    }

    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        if (granted) {
            OSStatus status = AudioOutputUnitStart(audioUnit);
            if (status != noErr) {
                NSAssert(status == noErr,@"Error");
            }
        } else {
            NSAssert(NO, @"Error");
        }
    }];
}

- (IBAction)stopButtonPressed:(id)sender {
    OSStatus status = AudioOutputUnitStop(audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }
    NSError *error;
    [[AVAudioSession sharedInstance] setActive:NO error:&error];
    if (error != nil) {
        NSAssert(error == nil, @"Error");
    }

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void) dealloc {
    OSStatus status = AudioComponentInstanceDispose(audioUnit);
    if (status != noErr) {
        NSAssert(status == noErr,@"Error");
    }
}

@end

Body:
After you configure the category for the session:

[[AVAudioSession sharedInstance] setMode:AVAudioSessionModeMeasurement error:&error];
if (error != nil) {
    NSAssert(error == nil, @"Error");
}

Also, your error handling doesn't follow the established pattern. You should check the return value of setMode:error:. The error in/out parameter is only guaranteed to be valid when the return value from the method is NO. (In practice, checking that error is nil probably works fine in most cases, but it's not documented to work that way - so you shouldn't rely on it.)


问:
Problems while trying to implement a cross validated out of core learning model?
I am working on text classification and after the feature extraction step I got pretty matrices, for that reason I tried to use incremental learning as follows:

```<code>import xgboost as xgb
from sklearn.model_selection import ShuffleSplit, train_test_split
from sklearn.metrics import accuracy_score as acc

def incremental_learning2(X, y):
    # split data into training and testing sets
    # then split training set in half

    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y, test_size=0.1,
                                                        random_state=0)

    X_train_1, X_train_2, y_train_1, y_train_2 = train_test_split(X_train,
                                                     y_train,
                                                     test_size=0.5,
                                                     random_state=0)

    xg_train_1 = xgb.DMatrix(X_train_1, label=y_train_1)
    xg_train_2 = xgb.DMatrix(X_train_2, label=y_train_2)
    xg_test = xgb.DMatrix(X_test, label=y_test)

    #params = {'objective': 'reg:linear', 'verbose': False}
    params = {}

    model_1 = xgb.train(params, xg_train_1, 30)
    model_1.save_model('model_1.model')

    # ================= train two versions of the model =====================#
    model_2_v1 = xgb.train(params, xg_train_2, 30)
    model_2_v2 = xgb.train(params, xg_train_2, 30, xgb_model='model_1.model')

    #Predictions
    y_pred = model_2_v2.predict(X_test)

    kfold = StratifiedKFold(n_splits=10, random_state=1).split(X_train, y_train)
    scores = []

    for k, (train, test) in enumerate(kfold):
        model_2_v2.fit(X_train[train], y_train[train])
        score = model_2_v2.score(X_train[test], y_train[test])
        scores.append(score)

        print('Fold: %s, Class dist.: %s, Acc: %.3f' % (k+1, np.bincount(y_train[train]), score))
    print('\nCV accuracy: %.3f +/- %.3f' % (np.mean(scores), np.std(scores)))
</code>```

With regards to the above code. I tried to to do a cross validation and predict some instances. However, it is not working. How can I fix the above code in order to get cross validated metrics and predictions after fitting and updating the GBM model on a very large dataset?.

答:
This is the solution I came up with. First we import the necessary modules and define a simple function to calculate the root square mean error:

```<code>import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split as tts
from sklearn.model_selection import StratifiedKFold

def rmse(a, b):
    return np.sqrt(((a - b) ** 2).mean())
</code>```

The root mean square error can be calculated differently (look into this thread for details) but for clarity purposes I have chosen an explicit formulation.

And here's a quick and dirty version of your function. I tried to keep the structure of your code the same, but for the sake of readability I have performed some refactoring.

```<code>def incremental_learning2(X, y, n_splits=10, params = {}):
    # Initialize score arrays
    sc_1, sc_2_v1, sc_2_v2 = (np.zeros(n_splits) for i in range(3))
    # Create cross-validator
    kfold = StratifiedKFold(n_splits=n_splits, random_state=0).split(X, y)
    # Iterate through folds
    for k, (train, test) in enumerate(kfold):
        # Split data
        X_test, y_test = X[test], y[test]
        splits = tts(X[train], y[train], test_size=0.5, random_state=0)
        X_train_1, X_train_2, y_train_1, y_train_2 = splits
        # Create data matrices
        xg_train_1 = xgb.DMatrix(X_train_1, label=y_train_1)
        xg_train_2 = xgb.DMatrix(X_train_2, label=y_train_2)
        xg_test = xgb.DMatrix(X_test, label=y_test)
        # Fit models
        model_1 = xgb.train(params, xg_train_1, 30)
        model_1.save_model('model_1.model')
        model_2_v1 = xgb.train(params, xg_train_2, 30)
        model_2_v2 = xgb.train(params, xg_train_2, 30, xgb_model='model_1.model')
        # Make predictions and compute scores
        preds = (m.predict(xg_test) for m in [model_1, model_2_v1, model_2_v2])
        sc_1[k], sc_2_v1[k], sc_2_v2[k] = (rmse(p, y_test) for p in preds)
    # Return scores
    return sc_1, sc_2_v1, sc_2_v2
</code>```

I have also improved the output format to display results in the form of a table. This functionality is implemented in a separate function:

```<code>def display_results(a, b, c):
    def hline():
        print('-'*50)
    print('Cross-validation root mean square error\n')
    print('Fold\tmodel_v1\tmodel_2_v1\tmodel_2_v2')
    hline()
    for k, (ak, bk, ck) in enumerate(zip(a, b, c)):
        print('%s\t%.3f\t\t%.3f\t\t%.3f' % (k+1, ak, bk, ck))
    hline()
    print('Avg\t%.3f\t\t%.3f\t\t%.3f' % tuple(np.mean(s) for s in [a, b, c]))
    print('Std\t%.3f\t\t%.3f\t\t%.3f' % tuple(np.std(s) for s in [a, b, c]))
</code>```

Demo

As you didn't share your dataset I had to generate mock data in order to test my code.

```<code>from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=500000, centers=50, random_state=0)

scores_1, scores_2_v1, scores2_v2 = incremental_learning2(X, y)
display_results(scores_1, scores_2_v1, scores2_v2)
</code>```

The code above runs without errors and the output looks like this:

```<code>Cross-validation root mean square error

Fold    model_v1        model_2_v1      model_2_v2
--------------------------------------------------
1       9.127           9.136           9.116
2       9.168           9.155           9.128
3       9.117           9.095           9.080
4       9.107           9.113           9.089
5       9.122           9.126           9.109
6       9.096           9.099           9.084
7       9.148           9.163           9.145
8       9.089           9.090           9.069
9       9.128           9.122           9.108
10      9.185           9.162           9.160
--------------------------------------------------
Avg     9.129           9.126           9.109
Std     0.029           0.026           0.028
</code>```

Remarks

For comparison purposes I have also cross-validated model_1.

In the sample run model_1 and model_2_v1 have roughly the same accuracy, whereas model_2_v2 performs slightly better, as one could reasonably expect.

I played around with the size of the dataset (n_samples) and the number of classes (centers) and interestingly enough, when the values of those parameters are reduced model_2_v2 is the least accurate of the three.

Hopefully, using a different configuration, i.e. properly setting the named function argument params, should make things work as expected.

Body:
I am working on text classification and after the feature extraction step I got pretty matrices, for that reason I tried to use incremental learning as follows:

import xgboost as xgb
from sklearn.model_selection import ShuffleSplit, train_test_split
from sklearn.metrics import accuracy_score as acc

def incremental_learning2(X, y):
    # split data into training and testing sets
    # then split training set in half

    X_train, X_test, y_train, y_test = train_test_split(X,
                                                        y, test_size=0.1,
                                                        random_state=0)

    X_train_1, X_train_2, y_train_1, y_train_2 = train_test_split(X_train,
                                                     y_train,
                                                     test_size=0.5,
                                                     random_state=0)

    xg_train_1 = xgb.DMatrix(X_train_1, label=y_train_1)
    xg_train_2 = xgb.DMatrix(X_train_2, label=y_train_2)
    xg_test = xgb.DMatrix(X_test, label=y_test)

    #params = {'objective': 'reg:linear', 'verbose': False}
    params = {}

    model_1 = xgb.train(params, xg_train_1, 30)
    model_1.save_model('model_1.model')

    # ================= train two versions of the model =====================#
    model_2_v1 = xgb.train(params, xg_train_2, 30)
    model_2_v2 = xgb.train(params, xg_train_2, 30, xgb_model='model_1.model')

    #Predictions
    y_pred = model_2_v2.predict(X_test)

    kfold = StratifiedKFold(n_splits=10, random_state=1).split(X_train, y_train)
    scores = []

    for k, (train, test) in enumerate(kfold):
        model_2_v2.fit(X_train[train], y_train[train])
        score = model_2_v2.score(X_train[test], y_train[test])
        scores.append(score)

        print('Fold: %s, Class dist.: %s, Acc: %.3f' % (k+1, np.bincount(y_train[train]), score))
    print('\nCV accuracy: %.3f +/- %.3f' % (np.mean(scores), np.std(scores)))

With regards to the above code. I tried to to do a cross validation and predict some instances. However, it is not working. How can I fix the above code in order to get cross validated metrics and predictions after fitting and updating the GBM model on a very large dataset?.

Body:
This is the solution I came up with. First we import the necessary modules and define a simple function to calculate the root square mean error:

import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split as tts
from sklearn.model_selection import StratifiedKFold

def rmse(a, b):
    return np.sqrt(((a - b) ** 2).mean())

The root mean square error can be calculated differently (look into this thread for details) but for clarity purposes I have chosen an explicit formulation.

And here's a quick and dirty version of your function. I tried to keep the structure of your code the same, but for the sake of readability I have performed some refactoring.

def incremental_learning2(X, y, n_splits=10, params = {}):
    # Initialize score arrays
    sc_1, sc_2_v1, sc_2_v2 = (np.zeros(n_splits) for i in range(3))
    # Create cross-validator
    kfold = StratifiedKFold(n_splits=n_splits, random_state=0).split(X, y)
    # Iterate through folds
    for k, (train, test) in enumerate(kfold):
        # Split data
        X_test, y_test = X[test], y[test]
        splits = tts(X[train], y[train], test_size=0.5, random_state=0)
        X_train_1, X_train_2, y_train_1, y_train_2 = splits
        # Create data matrices
        xg_train_1 = xgb.DMatrix(X_train_1, label=y_train_1)
        xg_train_2 = xgb.DMatrix(X_train_2, label=y_train_2)
        xg_test = xgb.DMatrix(X_test, label=y_test)
        # Fit models
        model_1 = xgb.train(params, xg_train_1, 30)
        model_1.save_model('model_1.model')
        model_2_v1 = xgb.train(params, xg_train_2, 30)
        model_2_v2 = xgb.train(params, xg_train_2, 30, xgb_model='model_1.model')
        # Make predictions and compute scores
        preds = (m.predict(xg_test) for m in [model_1, model_2_v1, model_2_v2])
        sc_1[k], sc_2_v1[k], sc_2_v2[k] = (rmse(p, y_test) for p in preds)
    # Return scores
    return sc_1, sc_2_v1, sc_2_v2

I have also improved the output format to display results in the form of a table. This functionality is implemented in a separate function:

def display_results(a, b, c):
    def hline():
        print('-'*50)
    print('Cross-validation root mean square error\n')
    print('Fold\tmodel_v1\tmodel_2_v1\tmodel_2_v2')
    hline()
    for k, (ak, bk, ck) in enumerate(zip(a, b, c)):
        print('%s\t%.3f\t\t%.3f\t\t%.3f' % (k+1, ak, bk, ck))
    hline()
    print('Avg\t%.3f\t\t%.3f\t\t%.3f' % tuple(np.mean(s) for s in [a, b, c]))
    print('Std\t%.3f\t\t%.3f\t\t%.3f' % tuple(np.std(s) for s in [a, b, c]))

Demo

As you didn't share your dataset I had to generate mock data in order to test my code.

from sklearn.datasets import make_blobs
X, y = make_blobs(n_samples=500000, centers=50, random_state=0)

scores_1, scores_2_v1, scores2_v2 = incremental_learning2(X, y)
display_results(scores_1, scores_2_v1, scores2_v2)

The code above runs without errors and the output looks like this:

Cross-validation root mean square error

Fold    model_v1        model_2_v1      model_2_v2
--------------------------------------------------
1       9.127           9.136           9.116
2       9.168           9.155           9.128
3       9.117           9.095           9.080
4       9.107           9.113           9.089
5       9.122           9.126           9.109
6       9.096           9.099           9.084
7       9.148           9.163           9.145
8       9.089           9.090           9.069
9       9.128           9.122           9.108
10      9.185           9.162           9.160
--------------------------------------------------
Avg     9.129           9.126           9.109
Std     0.029           0.026           0.028

Remarks

For comparison purposes I have also cross-validated model_1.

In the sample run model_1 and model_2_v1 have roughly the same accuracy, whereas model_2_v2 performs slightly better, as one could reasonably expect.

I played around with the size of the dataset (n_samples) and the number of classes (centers) and interestingly enough, when the values of those parameters are reduced model_2_v2 is the least accurate of the three.

Hopefully, using a different configuration, i.e. properly setting the named function argument params, should make things work as expected.


问:
Basic arrow keys and page up/down usage in intellij on mac
What are the equivalent keys for page up/ page down in intellij on os x? Option arrow up/down is not doing anything AFAICT.</p>

答:
It was annoying for me to find out which keys to get the cursor or caret up or down quickly or may be to the end or beginning of current line till I figured out the following shortcuts that might help:

Fn+Left arrow or Ctrl+A move the cursor to the end of current line.

Fn+Right arrow or Ctrl+E move the cursor to the beginning of current line.

Fn+Up arrow or Fn+Cmd+Left move the cursor to the beginning of the file.

Fn+Down arrow or Fn+Cmd+Right move the cursor to the end of the file.


问:
Joining two dataframes
I have a dataframe that looks like this:

```<code>RIC | base
AAPL| AA
IBM |
AMD |
</code>```

and another table with same fields but different values:

```<code>RIC | base
AAPL | AA
IBM |
AMD | AM
</code>```

I would like to join the two tables to get this resultant table:

```<code>RIC | base
AAPL | AA
IBM |
AMD | AM
</code>```

How can I do that?

答: you try : pd.concat([df1, df2], axis=1)</p>

Title: Joining two dataframes

Body:
I have a dataframe that looks like this:

RIC | base
AAPL| AA
IBM |
AMD |

and another table with same fields but different values:

RIC | base
AAPL | AA
IBM |
AMD | AM

I would like to join the two tables to get this resultant table:

RIC | base
AAPL | AA
IBM |
AMD | AM

How can I do that?

Body: you try : pd.concat([df1, df2], axis=1)


问:
How do I change the Start and End marker image in Google Maps v3 API for Directions
I have a route plotted fine on using DirectionsRender but I cannot find out how to replace the generic Google markers with my own.

I know and use this in a normal Google Map situation but finding it difficult to do this with the directions markers for start and end.

Thanks for any advice, pointers or gentle mocking if this is a silly question :D

Michael

答:
this is how you need to approach it

Declare all your image icons as shown below

```<code>var movingIcon = new google.maps.MarkerImage('/img/icon_moving.jpg');
var startIcon = new google.maps.MarkerImage('/img/icon_start.png');
</code>```

Then while creating the marker, use the icon option to set the specific image to that marker

```<code>marker = new google.maps.Marker({
            position: point,
            map: map,
            icon: movingIcon
            });
</code>```

Body:
this is how you need to approach it

Declare all your image icons as shown below

var movingIcon = new google.maps.MarkerImage('/img/icon_moving.jpg');
var startIcon = new google.maps.MarkerImage('/img/icon_start.png');

Then while creating the marker, use the icon option to set the specific image to that marker

marker = new google.maps.Marker({
            position: point,
            map: map,
            icon: movingIcon
            });


问:
Using WP_Query() to check if a post exists by slug
I am writing a 404.php for wordpress. I have the plugin 'rolescoper' installed, and some pages require the user be logged in to view.  Rolescoper doesn't offer any way to distinguish between a page not found (404) and a permission denied (403).

I've been able to build this functionality into my pages using the following code:

```<code>$the_query = new WP_Query ( 'pagename=' . $_SERVER['REQUEST_URI'] );
$is_valid_page = ! empty ( $the_query -> queried_object -> post_title );
</code>```

But, surprisingly, the same method does does not work for posts:

```<code>$args = array (
   'post_type' => 'post',
   'name' => str_replace ( "/", "", $_SERVER['REQUEST_URI'] )
);

$the_post_query = new WP_Query ( $args );
$is_valid_post = ! empty ( $the_post_query -> queried_object -> post_title );
</code>```

When I do a var_dump on $the_post_query i get something that shows 0 results found. I am sure that the page I'm checking for exists.

Any idea how to use wp_query() to query for a post by slug?

Thanks!

答:
After digging through the docs, I found that Rolescoper provided a nice function, is_restricted_rs(), for solving this problem:

```<code>//get the slug requested
$slug = $_SERVER [ 'REQUEST_URI' ];

//First check if it's a page and restricted
$page_id = get_page_by_path ( $slug )->ID;
$page_restricted = is_restricted_rs ( $page_id );

//Then check if it's a post and restricted
$args = array(
  'name'        => $slug,
  'post_type'   => 'post',
  'post_status' => 'publish',
  'numberposts' => 1
);

$my_posts = get_posts($args);

if ( $my_posts ) {
   $post_id = $my_posts[0]->ID;
}

$post_restricted = is_restricted_rs ( $post_id );

//then set $content_restricted for use below
$content_restricted = $post_restricted || $page_restricted;
</code>```

Body:
I am writing a 404.php for wordpress. I have the plugin 'rolescoper' installed, and some pages require the user be logged in to view.  Rolescoper doesn't offer any way to distinguish between a page not found (404) and a permission denied (403).

I've been able to build this functionality into my pages using the following code:

$the_query = new WP_Query ( 'pagename=' . $_SERVER['REQUEST_URI'] );
$is_valid_page = ! empty ( $the_query -> queried_object -> post_title );

But, surprisingly, the same method does does not work for posts:

$args = array (
   'post_type' => 'post',
   'name' => str_replace ( "/", "", $_SERVER['REQUEST_URI'] )
);

$the_post_query = new WP_Query ( $args );
$is_valid_post = ! empty ( $the_post_query -> queried_object -> post_title );

When I do a var_dump on $the_post_query i get something that shows 0 results found. I am sure that the page I'm checking for exists.

Any idea how to use wp_query() to query for a post by slug?

Thanks!

Body:
After digging through the docs, I found that Rolescoper provided a nice function, is_restricted_rs(), for solving this problem:

//get the slug requested
$slug = $_SERVER [ 'REQUEST_URI' ];

//First check if it's a page and restricted
$page_id = get_page_by_path ( $slug )->ID;
$page_restricted = is_restricted_rs ( $page_id );

//Then check if it's a post and restricted
$args = array(
  'name'        => $slug,
  'post_type'   => 'post',
  'post_status' => 'publish',
  'numberposts' => 1
);

$my_posts = get_posts($args);

if ( $my_posts ) {
   $post_id = $my_posts[0]->ID;
}

$post_restricted = is_restricted_rs ( $post_id );

//then set $content_restricted for use below
$content_restricted = $post_restricted || $page_restricted;


问:
How to add custom-fields (First and Last Name) in django-registration 2.2 (HMAC activation Workflow)?
There are already some question on this but most of their answers are using models based workflow which is not a recommended way anymore according to django-registration. I am just frustrated from last week, trying to figure out how to add first and last name fields in registration form in HMAC Workflow.</p>

答:
I am not intimately familiar with django, but an easy solution would be to follow the default registration workflow to let your user register. Then when your user tries to login for the first time you present them with a form to fill with all the extra information you might need.

In this way you also decouple the actual account creation from asking the user for more information, creating for them an extra incentive to actually go through with this process ("Oh man why do I need to provide my name, let's not sign up" vs "Oh well, I have already registered and given them an email might as well go through with it")

If you would prefer to have them in one step, then providing what code you have already would help us provide better feedback


问:
Put the variables that returned false in their own array
My code prints "zach" into a separate array. My "isNonStopWord" looks to see if any of the words in skoal appear in "zach". If they do it returns false next to these words that appear in both and true next to every word in "zach" that is not in "skoal" all I am trying to do now is to put all of the words that returned false into their own array and I cannot figure out how to do it. If you have an idea please let me know.   </p>

```<code>  package zk;

 import java.util.Arrays;
 public class Class {

 public boolean isNonStopWord(String x, String[] y) {

    if (Arrays.asList(y).contains(x)) {
        return false;
    }
    return true;
}

public static void main(String [] args) {
    Class cs = new Class();

    String zach = ("Amazon offered up more answers Thursday about what"
            + " caused a bunch of websites to fail two days ago. According "
            + "to a postmortem by the company's cloud services business, "
            + "around 9:37 a.m. PT Tuesday an Amazon worker incorrectly"
            + " punched in a command while trying to debug an issue. "
            + "That command shut down a large set of servers at Amazon Web "
            + "Services' Northern Virginia site, causing a domino effect of"
            + " problems. Other services that relied on those S3 cloud"
            + " storage servers were disrupted. Also, removing so much "
            + "server capacity required a full system restart, which then "
            + "took longer than expected, AWS said. The sites affected "
            + "included Quora, Imgur, IFTTT, Giphy and Slack. Amazon was "
            + "able to fix the issue by about 2 p.m. PT.");

    String [] skoal = {"THE", "BE", "TO", "OF", "AND", "A", "IN",
            "THAT", "I", "IT", "ON", "IN", "BUT", "IS", "WITH"};

    zach = zach.replace(",","");
    zach = zach.replace(".","");
    zach = zach.toUpperCase();
    String [] strings = zach.split(" ");

int july = 0;

    for (String s1: strings)
    {
        boolean answer = cs.isNonStopWord(s1,skoal);
        System.out.println((s1) + "  " + (answer));
        if(answer==false){
            july++;
    }
  }

    System.out.println("There are " + july +" " + "non-stop words");
    zach = "...";

 }
</code>```

答:
I'd recommend a List, because you can dynamically add Elements.

```<code>ArrayList<String> fooList = new ArrayList<>();
    for (String s1: strings)
    {
        boolean answer = cs.isNonStopWord(s1,skoal);
        System.out.println((s1) + "  " + (answer));
        if(answer==false){
            july++;
fooList.add(s1);

    }
</code>```

Otherwise I'd take the count of july
And instanciate an Array with this size.

```<code>String[] foo = new String[july]
</code>```

Then you need another for each Loop to fill the Array:(Outside of the other one)

```<code>int count=0; For ( x: xx) ... if(answer==false){
foo[count] = x;
        count++; }
</code>```

Using a List might be way cleaner and if you need an Array, you can convert the list to one.

```<code>String [] fooArray = fooList.toArray(new String[july]);
</code>```

Body:
My code prints "zach" into a separate array. My "isNonStopWord" looks to see if any of the words in skoal appear in "zach". If they do it returns false next to these words that appear in both and true next to every word in "zach" that is not in "skoal" all I am trying to do now is to put all of the words that returned false into their own array and I cannot figure out how to do it. If you have an idea please let me know.

  package zk;

 import java.util.Arrays;
 public class Class {

 public boolean isNonStopWord(String x, String[] y) {

    if (Arrays.asList(y).contains(x)) {
        return false;
    }
    return true;
}

public static void main(String [] args) {
    Class cs = new Class();

    String zach = ("Amazon offered up more answers Thursday about what"
            + " caused a bunch of websites to fail two days ago. According "
            + "to a postmortem by the company's cloud services business, "
            + "around 9:37 a.m. PT Tuesday an Amazon worker incorrectly"
            + " punched in a command while trying to debug an issue. "
            + "That command shut down a large set of servers at Amazon Web "
            + "Services' Northern Virginia site, causing a domino effect of"
            + " problems. Other services that relied on those S3 cloud"
            + " storage servers were disrupted. Also, removing so much "
            + "server capacity required a full system restart, which then "
            + "took longer than expected, AWS said. The sites affected "
            + "included Quora, Imgur, IFTTT, Giphy and Slack. Amazon was "
            + "able to fix the issue by about 2 p.m. PT.");

    String [] skoal = {"THE", "BE", "TO", "OF", "AND", "A", "IN",
            "THAT", "I", "IT", "ON", "IN", "BUT", "IS", "WITH"};

    zach = zach.replace(",","");
    zach = zach.replace(".","");
    zach = zach.toUpperCase();
    String [] strings = zach.split(" ");

int july = 0;

    for (String s1: strings)
    {
        boolean answer = cs.isNonStopWord(s1,skoal);
        System.out.println((s1) + "  " + (answer));
        if(answer==false){
            july++;
    }
  }

    System.out.println("There are " + july +" " + "non-stop words");
    zach = "...";

 }

Body:
I'd recommend a List, because you can dynamically add Elements.

ArrayList<String> fooList = new ArrayList<>();
    for (String s1: strings)
    {
        boolean answer = cs.isNonStopWord(s1,skoal);
        System.out.println((s1) + "  " + (answer));
        if(answer==false){
            july++;
fooList.add(s1);

    }

Otherwise I'd take the count of july
And instanciate an Array with this size.

String[] foo = new String[july]

Then you need another for each Loop to fill the Array:(Outside of the other one)

int count=0; For ( x: xx) ... if(answer==false){
foo[count] = x;
        count++; }

Using a List might be way cleaner and if you need an Array, you can convert the list to one.

String [] fooArray = fooList.toArray(new String[july]);


问:
How to embed a UINavigationController in prepareForSegue?
Currently I have a VC1 of type UITableViewController that is embedded in UINavigationController. When the user selects a cell, it performs a push segue to VC2 also of type UITableViewController. That is fine because the navigation bar is still present.

However in VC1, there is a UIBarButtonItem in the navigation bar, that upon tapped, also segues to VC2 and performs different things, but it uses all the same menu layout.

Using the UIBarButtonItem to segue to VC2, I like to perform a modal segue to distinguish between the two actions.

I know that modal segues encompasses the whole screen, and any top bars will be removed.

I followed this question: Modal segue, navigation bar dissapears

One of the answers provided shows how to embed a UINavigationController in prepareForSegue, so I followed it and implemented:

```<code>override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "AddSegue"
    {
        let navigationController: UINavigationController = segue.destination as! UINavigationController

        var addVC: VC2 = VC2()

        addVC = navigationController.viewControllers[0] as! VC2

    }
}
</code>```

However, I get the error:

Could not cast value of type 'VC2' to
  'UINavigationController'

How can I properly embed a UINavigationController in prepareForSegue because I need to pass data between different view controllers.

Here's my storyboard:

答:
The segue you're intersecting is to your VC2, not a navigation controller. You're going to need to update the "AddSegue" segue to point to a navigation controller, then link your VC2 as the root view controller of the navigation controller.

If you post your storyboard, I can give you more details on how to do this.

EDIT: Here's how you should set up your storyboard. It might get a bit weird, since VC2 has two parent navigation controllers, but it should be fine.

Body:
Currently I have a VC1 of type UITableViewController that is embedded in UINavigationController. When the user selects a cell, it performs a push segue to VC2 also of type UITableViewController. That is fine because the navigation bar is still present.

However in VC1, there is a UIBarButtonItem in the navigation bar, that upon tapped, also segues to VC2 and performs different things, but it uses all the same menu layout.

Using the UIBarButtonItem to segue to VC2, I like to perform a modal segue to distinguish between the two actions.

I know that modal segues encompasses the whole screen, and any top bars will be removed.

I followed this question: Modal segue, navigation bar dissapears

One of the answers provided shows how to embed a UINavigationController in prepareForSegue, so I followed it and implemented:

override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
    if segue.identifier == "AddSegue"
    {
        let navigationController: UINavigationController = segue.destination as! UINavigationController

        var addVC: VC2 = VC2()

        addVC = navigationController.viewControllers[0] as! VC2

    }
}

However, I get the error:

Could not cast value of type 'VC2' to
  'UINavigationController'

How can I properly embed a UINavigationController in prepareForSegue because I need to pass data between different view controllers.

Here's my storyboard:


问:
Add elements in xts
I'm in the process of converting my script to use xts rather than a data frame, but getting stuck with doing calculations across elements in different rows / columns.

In reality I'm iterating through the df rows using a for loop, and using if-elses based on the calculation.

But, to simplify the problem, I can add say Col A Row 1 with Col B Row 2 just fine in a df, but not in an xts.... here's some example code:

```<code>> df <- data.frame(c(1:3),c(4:6))
> names(df) <- c('colA','colB')
> df
  colA colB
1    1    4
2    2    5
3    3    6
> df$colA[1] + df$colB[2]
[1] 6
>
>
> library(xts)
> x <- xts(df, order.by=as.Date(1:3))
> x
           colA colB
1970-01-02    1    4
1970-01-03    2    5
1970-01-04    3    6
> x$colA[1] + x$colB[2]
Data:
integer(0)

Index:
numeric(0)
>
</code>```

Any ideas how I can get this to work?

答:
When two xts objects are added they are merged to align the times and then added.  Row 1 and Row 2 have no common indexes so the merge produces an empty object.

Here are some alternatives:

1) [[ A single [ will return another xts object but [[ will not thereby avoiding the problem:

```<code>x$colA[[1]] + x$colB[[2]]
## [1] 6
</code>```

2) coredata  Try explicitly converting to ordinary vectors before adding:

```<code>coredata(x$colA)[1] + coredata(x$colB)[2]
## [1] 6
</code>```

3) c Here we concantenate the two values into a new xts object and then sum the values in that new object.

```<code>sum(c(x$colA[1], x$colB[2]))
## [1] 6
</code>```

Title: Add elements in xts

Body:
I'm in the process of converting my script to use xts rather than a data frame, but getting stuck with doing calculations across elements in different rows / columns.

In reality I'm iterating through the df rows using a for loop, and using if-elses based on the calculation.

But, to simplify the problem, I can add say Col A Row 1 with Col B Row 2 just fine in a df, but not in an xts.... here's some example code:

> df <- data.frame(c(1:3),c(4:6))
> names(df) <- c('colA','colB')
> df
  colA colB
1    1    4
2    2    5
3    3    6
> df$colA[1] + df$colB[2]
[1] 6
>
>
> library(xts)
> x <- xts(df, order.by=as.Date(1:3))
> x
           colA colB
1970-01-02    1    4
1970-01-03    2    5
1970-01-04    3    6
> x$colA[1] + x$colB[2]
Data:
integer(0)

Index:
numeric(0)
>

Any ideas how I can get this to work?

Body:
When two xts objects are added they are merged to align the times and then added.  Row 1 and Row 2 have no common indexes so the merge produces an empty object.

Here are some alternatives:

1) [[ A single [ will return another xts object but [[ will not thereby avoiding the problem:

x$colA[[1]] + x$colB[[2]]
## [1] 6

2) coredata  Try explicitly converting to ordinary vectors before adding:

coredata(x$colA)[1] + coredata(x$colB)[2]
## [1] 6

3) c Here we concantenate the two values into a new xts object and then sum the values in that new object.

sum(c(x$colA[1], x$colB[2]))
## [1] 6