问:
Why can't I see any changes in my "Place" tab
I want each tab to to show something different.  To start things off, I want to make changes to the Place tab.  The problem is, none of the changes are being reflected in the Android Simulator.

Image of what I'm referring to

In this case, I want the text something to show up, but it's not.  What am I doing wrong?  I've also included code that might be relevant to this issue.

Here's MainActivity.java:

```<code>import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity implements Place.OnFragmentInteractionListener, Profile.OnFragmentInteractionListener, Take.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("Place"));
        tabLayout.addTab(tabLayout.newTab().setText("Take"));
        tabLayout.addTab(tabLayout.newTab().setText("Profile"));

        final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}
</code>```

Here's fragment_place.xml:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Place"
        android:layout_centerInParent="true"
        android:textSize="30dp"
        android:id="@+id/textView" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="41dp"
        android:layout_marginStart="41dp"
        android:layout_marginTop="80dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Something" />

</RelativeLayout>
</code>```

Here's PagerAdapter.java:

```<code>import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int mNoOfTabs;

    public PagerAdapter(FragmentManager fm, int NumberOfTabs) {
        super(fm);
        this.mNoOfTabs = NumberOfTabs; // set global number of tabs to local number of tabs
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                Place place = new Place();
                return place;
            case 1:
                Profile profile = new Profile();
                return profile;
            case 2:
                Take take = new Take();
                return take;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 0;
    }
}
</code>```

答:
Change the lines to given code.

```<code> @Override
 public int getCount() {
    return mNoOfTabs ;
 }
</code>```

Also make sure you inflate the layout belong to Place (Fragment) onViewCreated() method

Body:
I want each tab to to show something different.  To start things off, I want to make changes to the Place tab.  The problem is, none of the changes are being reflected in the Android Simulator.

Image of what I'm referring to

In this case, I want the text something to show up, but it's not.  What am I doing wrong?  I've also included code that might be relevant to this issue.

Here's MainActivity.java:

import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity implements Place.OnFragmentInteractionListener, Profile.OnFragmentInteractionListener, Take.OnFragmentInteractionListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TabLayout tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        tabLayout.addTab(tabLayout.newTab().setText("Place"));
        tabLayout.addTab(tabLayout.newTab().setText("Take"));
        tabLayout.addTab(tabLayout.newTab().setText("Profile"));

        final ViewPager viewPager = (ViewPager)findViewById(R.id.pager);
        final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(),tabLayout.getTabCount());
        viewPager.setAdapter(adapter);
        viewPager.setOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));

        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onFragmentInteraction(Uri uri) {

    }
}

Here's fragment_place.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Place"
        android:layout_centerInParent="true"
        android:textSize="30dp"
        android:id="@+id/textView" />

    <EditText
        android:id="@+id/editText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="41dp"
        android:layout_marginStart="41dp"
        android:layout_marginTop="80dp"
        android:ems="10"
        android:inputType="textPersonName"
        android:text="Something" />

</RelativeLayout>

Here's PagerAdapter.java:

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

public class PagerAdapter extends FragmentStatePagerAdapter {

    int mNoOfTabs;

    public PagerAdapter(FragmentManager fm, int NumberOfTabs) {
        super(fm);
        this.mNoOfTabs = NumberOfTabs; // set global number of tabs to local number of tabs
    }

    @Override
    public Fragment getItem(int position) {
        switch(position) {
            case 0:
                Place place = new Place();
                return place;
            case 1:
                Profile profile = new Profile();
                return profile;
            case 2:
                Take take = new Take();
                return take;
            default:
                return null;
        }
    }

    @Override
    public int getCount() {
        return 0;
    }
}

Body:
Change the lines to given code.

 @Override
 public int getCount() {
    return mNoOfTabs ;
 }

Also make sure you inflate the layout belong to Place (Fragment) onViewCreated() method


来源: stackexchange

问:
Webpack and AWS Lambda issue - handler missing on module
I'm using ES6, babel and Webpack 2 to bundle an AWS Lambda. I am then running/testing it using AWS SAM local. I get the following error when I hit the api -

```<code>Handler 'handler' missing on module 'dist/main'
</code>```

Here is my webpack.config.js -

```<code>const path = require('path');

module.exports = {
  entry: './index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    libraryTarget: 'commonjs'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: [require('babel-plugin-transform-flow-strip-types')],
          presets: [
            [
              'env',
              {
                target: { node: 6.10 }, // Node version on AWS Lambda
                useBuiltIns: false,
                loose: false,
                exclude: [],
                debug: false
              },
            ],
          ],
        },
      }
    ],
  }
};
</code>```

And here is a snippet of the compiled main.js -

```<code>/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.handler = handler;

var _amazonCognitoIdentityJs = __webpack_require__(60);

var _aws_profile = __webpack_require__(290);

// A signin Lambda function
function handler(event, context, callback) {
        switch (event.httpMethod) {
        case "GET":
</code>```

A little background.... this is a Lambda I initially wrote NOT in ES6 and not bundling using Webpack and it was working. I now need for it to be in ES6 and work with Webpack. N.B. this is Webpack 2

Much thanks...

答:
To fix this issue I had to specify a library property and change the libraryTarget to commonjs2. The webpack.config.js file output now looks like this -</p>

```<code>output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    library: 'main',
    libraryTarget: 'commonjs2'
  },
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm using ES6, babel and Webpack 2 to bundle an AWS Lambda. I am then running/testing it using AWS SAM local. I get the following error when I hit the api -

Handler 'handler' missing on module 'dist/main'

Here is my webpack.config.js -

const path = require('path');

module.exports = {
  entry: './index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    libraryTarget: 'commonjs'
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'babel-loader',
        options: {
          plugins: [require('babel-plugin-transform-flow-strip-types')],
          presets: [
            [
              'env',
              {
                target: { node: 6.10 }, // Node version on AWS Lambda
                useBuiltIns: false,
                loose: false,
                exclude: [],
                debug: false
              },
            ],
          ],
        },
      }
    ],
  }
};

And here is a snippet of the compiled main.js -

/***/ (function(module, exports, __webpack_require__) {

"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.handler = handler;

var _amazonCognitoIdentityJs = __webpack_require__(60);

var _aws_profile = __webpack_require__(290);

// A signin Lambda function
function handler(event, context, callback) {
        switch (event.httpMethod) {
        case "GET":

A little background.... this is a Lambda I initially wrote NOT in ES6 and not bundling using Webpack and it was working. I now need for it to be in ES6 and work with Webpack. N.B. this is Webpack 2

Much thanks...

Body:
To fix this issue I had to specify a library property and change the libraryTarget to commonjs2. The webpack.config.js file output now looks like this -

output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'main.js',
    library: 'main',
    libraryTarget: 'commonjs2'
  },


问:
Spring MVC service worker for progressive webapps
I have an application with this structure:

```<code>- webapp
- - resources
- - - js
- - - - main.js
- - WEB-INF
- - - views
- - - - index.jsp
</code>```

I'm starting to work with progressive webapp, and I just want to make index.jsp work to follow with the other views.

index.jsp

```<code><head>
    <script defer src="resources/js/main.js"></script>
</head>
</code>```

main.js

navigator.serviceWorker && navigator.serviceWorker.register('resources/js/sw.js').then(function(registration) {
  console.log('Excellent, registered with scope: ', registration.scope);
}).catch(function(error) {
    console.log('Service worker registration failed, error:', error);
    alert(error);
});```
</div>
</div>
</p>

<p><br>
sw.js <br></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/** An empty service worker! */
self.addEventListener('fetch', function(event) {
  /** An empty fetch handler! */
});</code>```

AppWebConfiguration.java

```<code>@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
    .addResourceLocations("/resources/");
}
</code>```

I got the following message from console on Chrome: Excellent, registered with scope:  http://localhost:8080/MyProject/resources/js/.

I need the service worker to be created using the root application http://localhost:8080/MyProject, but if I put my sw.js in the root I have not access.

Is there any way to access the sw.js on root or configure to use the root of the application as scope?

I've tried  to use navigator.serviceWorker.register('resources/js/sw.js', { scope: './' }) but it didn't work.

答:
I solved my problem mapping the service-worker to the root of the application, as suggested, using the ResourceHandlers of the Spring.

AppWebConfiguration.java

```<code>@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    registry.addResourceHandler("/**")
        .addResourceLocations("/resources/js/sw.js");
}
</code>```

With the following, I can access the sw.js at the root of the application with the following script:

main.js

navigator.serviceWorker && navigator.serviceWorker.register('./sw.js').then(function(registration) {
  console.log('Excellent, registered with scope: ', registration.scope);
}).catch(function(error) {
    console.log('Service worker registration failed, error:', error);
    alert(error);
});```

Body:
I have an application with this structure:

- webapp
- - resources
- - - js
- - - - main.js
- - WEB-INF
- - - views
- - - - index.jsp

I'm starting to work with progressive webapp, and I just want to make index.jsp work to follow with the other views.

index.jsp

main.js

navigator.serviceWorker && navigator.serviceWorker.register('resources/js/sw.js').then(function(registration) {
  console.log('Excellent, registered with scope: ', registration.scope);
}).catch(function(error) {
    console.log('Service worker registration failed, error:', error);
    alert(error);
});

sw.js

/** An empty service worker! */
self.addEventListener('fetch', function(event) {
  /** An empty fetch handler! */
});

AppWebConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/resources/**")
    .addResourceLocations("/resources/");
}

I got the following message from console on Chrome: Excellent, registered with scope:  http://localhost:8080/MyProject/resources/js/.

I need the service worker to be created using the root application http://localhost:8080/MyProject, but if I put my sw.js in the root I have not access.

Is there any way to access the sw.js on root or configure to use the root of the application as scope?

I've tried  to use navigator.serviceWorker.register('resources/js/sw.js', { scope: './' }) but it didn't work.

Body:
I solved my problem mapping the service-worker to the root of the application, as suggested, using the ResourceHandlers of the Spring.

AppWebConfiguration.java

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**")
        .addResourceLocations("/resources/");
    registry.addResourceHandler("/**")
        .addResourceLocations("/resources/js/sw.js");
}

With the following, I can access the sw.js at the root of the application with the following script:

main.js

navigator.serviceWorker && navigator.serviceWorker.register('./sw.js').then(function(registration) {
  console.log('Excellent, registered with scope: ', registration.scope);
}).catch(function(error) {
    console.log('Service worker registration failed, error:', error);
    alert(error);
});


问:
Pass key prop into React component from map
G'Day.  Having a bit of trouble getting the correct was yo pass this key prop into the component creattion.  Here is the code:

```<code>//--------
render() {

    const that = this;                                                  // Javascript scope voodoo
    const CS = that.parse(this.props.form);                             // CS, or CODE STACK, is the result of a parser that
                                                                        // acts on a JSON description of the form.
                                                                        // It is not QUITE true as CS is a stack of objects
                                                                        // that contain data one WOULD push onto the STACK
                                                                        // SEGMENT in a proper compiler.
    //console.log(CS);

    return(
            <div>
                <h2>SmartForm Parser</h2>
                {CS.map(function(op, CI) {                              // traverse the CODE SEGMENT and use the CODE INDEX
                    console.log(op);                                    // see what we re mapping to
                    switch (op.component) {                             // what type of operation is this
                        case 'Accordion': {                             // Accordion in a FORM, OK
                            let children = that.pages(op);              // build the children
                            console.log("About to create accordion");   // debugging
                            console.log("with children");               // debugging
                            console.log(children);                      // debugging
                            console.log(op.props);
                            React.createElement(Accordion,              // construct the parent with ALL nested CHILDREN after
                                                {key: CI},              // doing a TDSR evaluation of the OPERAND
                                                children);              // N ACCORDION pages, N2 input fields
                            break;

                        }
                        case 'Workflow': {
                            let children = that.pages(op);              // build the children
                            React.createElement(Workflow,               // and create the complex sheet element
                                                {classname: workflow},
                                                children);              // N SLIDING pages, N2 input fields
                            break;
                        }
                        case 'Simple': {
                            let children = that.pages(op);              // build the children
                            React.createElement(Simple,
                                                {classname: simple},
                                                children);              // One page, N input fields
                            break;
                        }
                    }
                })}
            </div>
    );
}
</code>```

I get a warning from the console that the key is missing and none of my pages are rendered.

Hints appreciated.

答:
You have passed a key prop to the Accordion component that you have created but not to any other element. You need to pass that to Workflow and Simple component as well

```<code>React.createElement(Accordion,
                 {key: CI},
                 children);

React.createElement(Workflow,
                 {classname: Workflow, key: CI},
                 children);

React.createElement(Simple,
                 {classname: simple, key: CI},
                 children);
</code>```

Body:
G'Day.  Having a bit of trouble getting the correct was yo pass this key prop into the component creattion.  Here is the code:

//--------
render() {

    const that = this;                                                  // Javascript scope voodoo
    const CS = that.parse(this.props.form);                             // CS, or CODE STACK, is the result of a parser that
                                                                        // acts on a JSON description of the form.
                                                                        // It is not QUITE true as CS is a stack of objects
                                                                        // that contain data one WOULD push onto the STACK
                                                                        // SEGMENT in a proper compiler.
    //console.log(CS);

    return(

SmartForm Parser

                {CS.map(function(op, CI) {                              // traverse the CODE SEGMENT and use the CODE INDEX
                    console.log(op);                                    // see what we re mapping to
                    switch (op.component) {                             // what type of operation is this
                        case 'Accordion': {                             // Accordion in a FORM, OK
                            let children = that.pages(op);              // build the children
                            console.log("About to create accordion");   // debugging
                            console.log("with children");               // debugging
                            console.log(children);                      // debugging
                            console.log(op.props);
                            React.createElement(Accordion,              // construct the parent with ALL nested CHILDREN after
                                                {key: CI},              // doing a TDSR evaluation of the OPERAND
                                                children);              // N ACCORDION pages, N2 input fields
                            break;

                        }
                        case 'Workflow': {
                            let children = that.pages(op);              // build the children
                            React.createElement(Workflow,               // and create the complex sheet element
                                                {classname: workflow},
                                                children);              // N SLIDING pages, N2 input fields
                            break;
                        }
                        case 'Simple': {
                            let children = that.pages(op);              // build the children
                            React.createElement(Simple,
                                                {classname: simple},
                                                children);              // One page, N input fields
                            break;
                        }
                    }
                })}

    );
}

I get a warning from the console that the key is missing and none of my pages are rendered.

Hints appreciated.

Body:
You have passed a key prop to the Accordion component that you have created but not to any other element. You need to pass that to Workflow and Simple component as well

React.createElement(Accordion,
                 {key: CI},
                 children);

React.createElement(Workflow,
                 {classname: Workflow, key: CI},
                 children);

React.createElement(Simple,
                 {classname: simple, key: CI},
                 children);


问:
How to Convert between Interface derived types?
In the most simplest for here is what I want to do:

```<code>interface InterfaceA
{
    string var1 { get; set; }
    string var2 { get; set; }
}

public class DerivedA : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DoEverything
{
    InterfaceA A = new DerivedA();
    InterfaceA B = new DerivedB();

    A.var1 = "Test1";
    A.var2 = "Test2";

    B = ConvertObject<DerivedB>(A);

    write(B.var1 + ", " + B.var2);

    // This doesn't work, I would like it to though.
    public T ConvertObject<T>(object obj)
    {
        T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });

        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            if (propertyInfo.CanRead)
            {
                try
                {
                    object value = propertyInfo.GetValue(obj, null);
                    propertyInfo.SetValue(result, value, null);
                }
                catch { }
            }
        }

        return result;
    }
}
</code>```

Right now I have to manually convert each property in my objects and when a new property is added I have to remember to go the conversion methods and add it. I would much prefer that this be done automatically.

Any help would be greatly appreciated.

thanks in advance

答:
You could add a constructor to, say, DerivedB, that takes InterfaceA as an argument.

E.g.

```<code>public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
    public DerivedB(InterfaceA original)
    {
       var1 = original.var1;
       var2 = original.var2;
    }
}
</code>```

Then you can use it as such:

```<code>public class DoEverything
{
    InterfaceA A = new DerivedA();

    A.var1 = "Test1";
    A.var2 = "Test2";

    InterfaceA B = new DerivedB(A);
    write(B.var1 + ", " + B.var2);
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In the most simplest for here is what I want to do:

interface InterfaceA
{
    string var1 { get; set; }
    string var2 { get; set; }
}

public class DerivedA : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
}

public class DoEverything
{
    InterfaceA A = new DerivedA();
    InterfaceA B = new DerivedB();

    A.var1 = "Test1";
    A.var2 = "Test2";

    B = ConvertObject<DerivedB>(A);

    write(B.var1 + ", " + B.var2);

    // This doesn't work, I would like it to though.
    public T ConvertObject<T>(object obj)
    {
        T result = (T)typeof(T).GetConstructor(new Type[] { }).Invoke(new object[] { });

        foreach (PropertyInfo propertyInfo in obj.GetType().GetProperties())
        {
            if (propertyInfo.CanRead)
            {
                try
                {
                    object value = propertyInfo.GetValue(obj, null);
                    propertyInfo.SetValue(result, value, null);
                }
                catch { }
            }
        }

        return result;
    }
}

Right now I have to manually convert each property in my objects and when a new property is added I have to remember to go the conversion methods and add it. I would much prefer that this be done automatically.

Any help would be greatly appreciated.

thanks in advance

Body:
You could add a constructor to, say, DerivedB, that takes InterfaceA as an argument.

E.g.

public class DerivedB : InterfaceA
{
    public string var1 { get; set; }
    public string var2 { get; set; }
    public DerivedB(InterfaceA original)
    {
       var1 = original.var1;
       var2 = original.var2;
    }
}

Then you can use it as such:

public class DoEverything
{
    InterfaceA A = new DerivedA();

    A.var1 = "Test1";
    A.var2 = "Test2";

    InterfaceA B = new DerivedB(A);
    write(B.var1 + ", " + B.var2);
}


问:
why can't urlEncoder.encode work like everyone else?
I am having to do stupid s**t like this to get urlEncoding to work like other libraries (iOS, Javascript..) because java.net.URLEncoder is buggy or not written to standard encoding:

```<code>URLEncoder.encode(normalizeString(str), StandardCharsets.UTF_8.displayName())
                    .replace("+", "%20")
                    .replace("%40", "@")
                    .replace("*", "%2A");
</code>```

+ and * are not percent encoded while @ is. and...now it's encoding forward slash /. wtf! is there a good explanation for this? Am I using the wrong Charset?

答:
I think you misunderstood the role of the URLEncoder. The UrlEncoder implements the HTML Specifications for how to encode URLs in HTML forms.

In your case, I think, the library org.apache.commons.text could be a better solution. It offer to you methods to escape characters like you want.

Body:
I am having to do stupid s**t like this to get urlEncoding to work like other libraries (iOS, Javascript..) because java.net.URLEncoder is buggy or not written to standard encoding:

URLEncoder.encode(normalizeString(str), StandardCharsets.UTF_8.displayName())
                    .replace("+", "%20")
                    .replace("%40", "@")
                    .replace("*", "%2A");

+ and * are not percent encoded while @ is. and...now it's encoding forward slash /. wtf! is there a good explanation for this? Am I using the wrong Charset?


问:
url not found - Django
I'm getting "URL not found error" on my website. These are my files:

myapp.urls:

```<code>url(r'^produkty/', include('supplement.urls', namespace='supplements')),
</code>```

supplement.urls:

```<code>urlpatterns = [
url(r'^(?P<slug>[-\w]+)/$', SupplementDetailView.as_view(), name='detail'),
url(r'^$', SupplementListView.as_view(), name='list'),]
</code>```

supplement.views:

```<code>class SupplementListView(ListView):
    def get_queryset(self):
        return Supplement.objects.all()

class SupplementDetailView(DetailView):
    queryset = Supplement.objects.all()
</code>```

NOTE: Both queryset = Supplement.objects.all() and get_queryset(self): return Supplement.objects.all() don't work in SupplementDetailView

supplement.models:

```<code>class Supplement(models.Model):
    name = models.CharField(blank=False, null=False, help_text=_("product's name"), max_length=50)
    price = models.IntegerField(blank=True, null=True)
    portion = models.CharField(max_length=100, blank=True, null=True, help_text=_("portion"))
    img = models.ImageField(default='kitchen/No-image-available.jpg', upload_to='products/', blank=True, null=True)
    description = RichTextField()
    contains = models.CharField(blank=True, null=True, max_length=3000, help_text=_("contains"))
    slug = models.SlugField(max_length=150, blank=True, null=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('supplements:detail', kwargs={"slug": self.slug})

    class Meta:
        ordering = ['-name']
        verbose_name = _('supplement')
        verbose_name_plural = _('supplements')

def rl_pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = unique_slug_generator(instance)

pre_save.connect(rl_pre_save_receiver, sender=Supplement)
</code>```

Templates for SupplementListView and SupplementDetailView are placed in BASE_DIR/supplement/templates/supplement.

NOTE: SupplementDetailView works like a charm. It loads the information about product passed in a  in url (for example: myapp.pl/produkty/product-slug), but the list of products (myapp.pl/produkty) returns "URL not found error"

Thank You for your help in advance, I've been struggling with that error for quite a while now.

答:
I've finally found the answer: I had this in my myapp.urls file:

```<code>url(r'^', include('opinions.urls', namespace='home')),
url(r'^produkty/', include('supplement.urls', namespace='supplements')),
</code>```

so whenever I entered "myapp.pl/produkty/" Django was convinced, that "produkty" is a slug for opinion model. I switched both url patterns (so the pattern for namespace='supplements' is loaded first) and everything works great.

Title: url not found - Django

Body:
I'm getting "URL not found error" on my website. These are my files:

myapp.urls:

url(r'^produkty/', include('supplement.urls', namespace='supplements')),

supplement.urls:

urlpatterns = [
url(r'^(?P<slug>[-\w]+)/$', SupplementDetailView.as_view(), name='detail'),
url(r'^$', SupplementListView.as_view(), name='list'),]

supplement.views:

class SupplementListView(ListView):
    def get_queryset(self):
        return Supplement.objects.all()

class SupplementDetailView(DetailView):
    queryset = Supplement.objects.all()

NOTE: Both queryset = Supplement.objects.all() and get_queryset(self): return Supplement.objects.all() don't work in SupplementDetailView

supplement.models:

class Supplement(models.Model):
    name = models.CharField(blank=False, null=False, help_text=_("product's name"), max_length=50)
    price = models.IntegerField(blank=True, null=True)
    portion = models.CharField(max_length=100, blank=True, null=True, help_text=_("portion"))
    img = models.ImageField(default='kitchen/No-image-available.jpg', upload_to='products/', blank=True, null=True)
    description = RichTextField()
    contains = models.CharField(blank=True, null=True, max_length=3000, help_text=_("contains"))
    slug = models.SlugField(max_length=150, blank=True, null=True)

    def __str__(self):
        return self.name

    def get_absolute_url(self):
        return reverse('supplements:detail', kwargs={"slug": self.slug})

    class Meta:
        ordering = ['-name']
        verbose_name = _('supplement')
        verbose_name_plural = _('supplements')

def rl_pre_save_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = unique_slug_generator(instance)

pre_save.connect(rl_pre_save_receiver, sender=Supplement)

Templates for SupplementListView and SupplementDetailView are placed in BASE_DIR/supplement/templates/supplement.

NOTE: SupplementDetailView works like a charm. It loads the information about product passed in a  in url (for example: myapp.pl/produkty/product-slug), but the list of products (myapp.pl/produkty) returns "URL not found error"

Thank You for your help in advance, I've been struggling with that error for quite a while now.

Body:
I've finally found the answer: I had this in my myapp.urls file:

url(r'^', include('opinions.urls', namespace='home')),
url(r'^produkty/', include('supplement.urls', namespace='supplements')),

so whenever I entered "myapp.pl/produkty/" Django was convinced, that "produkty" is a slug for opinion model. I switched both url patterns (so the pattern for namespace='supplements' is loaded first) and everything works great.


问:
How to make mercurial sort the output of `hg log` by commit date?
How can I make mercurial order the output of hg log by commit date?

The output seems to be ordered by the date I pull the commits into my repository instead of when they were committed.

答:
You need to use a revset:

```<code>$ hg log -r 'sort(all(), date)'
</code>```

If you want to see the most recent commits first, do:

```<code>$ hg log -r 'sort(all(), -date)'
</code>```

See hg help -v revsets for more details.

Body:
You need to use a revset:

$ hg log -r 'sort(all(), date)'

If you want to see the most recent commits first, do:

$ hg log -r 'sort(all(), -date)'

See hg help -v revsets for more details.


问:
PowerShell get unknown number of characters from file

Problem

I am writing a script that automates the Version Control for a series of projects. What I am trying to achieve is to store the current value of the AssemblyVersion found within the AssemblyInfo.cs file into a variable.

E.G.: The line is [assembly: AssemblyVersion("1.0.0.0")] and I want to extract/store whatever value is between AssemblyVersion(" and ")]

I understand that regular expressions will most likely be needed here, but I am having trouble understanding how to target values between two specific values. I attempted to read through the Regular-Expression.info website in hopes of understanding this better. In this, I read through Lookahead and Lookbehind as one such possibility, but didn't understand how to combine these expressions and there were little to no examples to get a strong grasp on how to these are used. I also thumbed through matching Complete Lines, but this also seemed to put me in a position where I would have use two separate equations to try and get the results I desire...

In my research, I found one similar approach at: Match everything between two words in PowerShell. Unfortunately, despite the mini explanation provided, I could not modify and duplicate the results to suite my need. I often encountered an error stating: 'cannot convert to regex'. I was not able to figure out what I was doing wrong and it didn't help that there was no explanation as to what the $subject variable was referring to.

Continuing my research, the other similar variants that others asked of the above have very case specific answers that I have not been able to utilize.

I am hoping that someone here could help me to answer my question with an answer in which each piece is understandable enough to modify the answer to fit future similar problems.

Question

How can I get the value, despite the value type, that is between two strings so that I can reliably grab the AssemblyVersion value with a single equation that is scalable enough to not care about the length of characters found? Could you also be kind enough to explain the pieces of the answer so that I can understand how you came to it?

答:
Not always necessary to use regex. In your case, you can use split with double-quote like delimiter, like it:</p>

```<code>$str='[assembly: AssemblyVersion = ''[assembly: AssemblyVersion("1.0.0.0")] AssemblyVersion("")]'
($str -split '"')[1]
</code>```

Body:
Not always necessary to use regex. In your case, you can use split with double-quote like delimiter, like it:

$str='[assembly: AssemblyVersion = ''[assembly: AssemblyVersion("1.0.0.0")] AssemblyVersion("")]'
($str -split '"')[1]


问:
UDF to Concatenate Arrays of Undefined Case Class Buried in a Row Object
I have a dataframe, called sessions, with columns that may change over time. (Edit to Clarify: I do not have a case class for the columns - only a reflected schema.) I will consistently have a uuid and clientId in the outer scope with some other inner and outer scope columns that might constitute a tracking event so ... something like:

```<code>root
 |-- runtimestamp: long (nullable = true)
 |-- clientId: long (nullable = true)
 |-- uuid: string (nullable = true)
 |-- oldTrackingEvents: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- timestamp: long (nullable = true)
 |    |    |-- actionid: integer (nullable = true)
 |    |    |-- actiontype: string (nullable = true)
 |    |    |-- <tbd ... maps, arrays and other stuff matches sibling> section
 ...
 |-- newTrackingEvents: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- timestamp: long (nullable = true)
 |    |    |-- actionid: integer (nullable = true)
 |    |    |-- actiontype: string (nullable = true)
 |    |    |-- <tbd ... maps, arrays and other stuff matches sibling>
 ...
</code>```

I'd like to now merge oldTrackingEvents and newTrackingEvents with a UDF containing these parameters and yet-to-be resolved code logic:

```<code>val mergeTEs = udf((oldTEs : Seq[Row], newTEs :  Seq[Row]) =>
        // do some stuff - figure best way
        //    - to merge both groups of tracking events
        //    - remove duplicates tracker events structures
        //    - limit total tracking events < 500
        return result // same type as UDF input params
    )
</code>```

The UDF return result would be an array of of the structure that is the resulting List of the concatenated two fields.

QUESTION:
My question is how to construct such a UDF - (1) use of correct passed-in parameter types, (2) a way to manipulate these collections within a UDF and (3) a clear way to return a value that doesn't have a compiler error. I unsuccessfully tested Seq[Row] for the input / output (with val testUDF = udf((trackingEvents : Seq[Row]) => trackingEvents) and received the error java.lang.UnsupportedOperationException: Schema for type org.apache.spark.sql.Row is not supported for a direct return of trackingEvents. However, I get no error for returning Some(1) instead of trackingEvents ... What is the best way to manipulate the collections so that I can concatenate 2 lists of identical structures as suggested by the schema above with the UDF using the activity in the comments section. The goal is to use this operation:

```<code>sessions.select(mergeTEs('oldTrackingEvents, 'newTrackingEvents).as("cleanTrackingEvents"))
</code>```

And in each row, ... get back a single array of 'trackingEvents' structure in a memory / speed efficient manner.

SUPPLEMENTAL:

Looking at a question shown to me ... There's a possible hint, if relevancy exists ...  Defining a UDF that accepts an Array of objects in a Spark DataFrame? ... To create struct function passed to udf has to return Product type (Tuple* or case class), not Row.
Perhaps ... this other post is relevant / useful.

答:
I think that the question you've linked explains it all, so just to reiterate. When working with udf:

Input representation for the StructType is weakly typed Row object.

Output type for StructType has to be Scala Product. You cannot return Row object.

If this is to much burden, you should use strongly typed Dataset

```<code>val f: T => U
sessions.as[T].map(f): Dataset[U]
</code>```

where T is an algebraic data type representing Session schema, and U is algebraic data type representing the result.

Body:
I have a dataframe, called sessions, with columns that may change over time. (Edit to Clarify: I do not have a case class for the columns - only a reflected schema.) I will consistently have a uuid and clientId in the outer scope with some other inner and outer scope columns that might constitute a tracking event so ... something like:

root
 |-- runtimestamp: long (nullable = true)
 |-- clientId: long (nullable = true)
 |-- uuid: string (nullable = true)
 |-- oldTrackingEvents: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- timestamp: long (nullable = true)
 |    |    |-- actionid: integer (nullable = true)
 |    |    |-- actiontype: string (nullable = true)
 |    |    |-- <tbd ... maps, arrays and other stuff matches sibling> section
 ...
 |-- newTrackingEvents: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- timestamp: long (nullable = true)
 |    |    |-- actionid: integer (nullable = true)
 |    |    |-- actiontype: string (nullable = true)
 |    |    |-- <tbd ... maps, arrays and other stuff matches sibling>
 ...

I'd like to now merge oldTrackingEvents and newTrackingEvents with a UDF containing these parameters and yet-to-be resolved code logic:

val mergeTEs = udf((oldTEs : Seq[Row], newTEs :  Seq[Row]) =>
        // do some stuff - figure best way
        //    - to merge both groups of tracking events
        //    - remove duplicates tracker events structures
        //    - limit total tracking events < 500
        return result // same type as UDF input params
    )

The UDF return result would be an array of of the structure that is the resulting List of the concatenated two fields.

QUESTION:
My question is how to construct such a UDF - (1) use of correct passed-in parameter types, (2) a way to manipulate these collections within a UDF and (3) a clear way to return a value that doesn't have a compiler error. I unsuccessfully tested Seq[Row] for the input / output (with val testUDF = udf((trackingEvents : Seq[Row]) => trackingEvents) and received the error java.lang.UnsupportedOperationException: Schema for type org.apache.spark.sql.Row is not supported for a direct return of trackingEvents. However, I get no error for returning Some(1) instead of trackingEvents ... What is the best way to manipulate the collections so that I can concatenate 2 lists of identical structures as suggested by the schema above with the UDF using the activity in the comments section. The goal is to use this operation:

sessions.select(mergeTEs('oldTrackingEvents, 'newTrackingEvents).as("cleanTrackingEvents"))

And in each row, ... get back a single array of 'trackingEvents' structure in a memory / speed efficient manner.

SUPPLEMENTAL:

Looking at a question shown to me ... There's a possible hint, if relevancy exists ...  Defining a UDF that accepts an Array of objects in a Spark DataFrame? ... To create struct function passed to udf has to return Product type (Tuple* or case class), not Row.
Perhaps ... this other post is relevant / useful.

Body:
I think that the question you've linked explains it all, so just to reiterate. When working with udf:

Input representation for the StructType is weakly typed Row object.

Output type for StructType has to be Scala Product. You cannot return Row object.

If this is to much burden, you should use strongly typed Dataset

val f: T => U
sessions.as[T].map(f): Dataset[U]

where T is an algebraic data type representing Session schema, and U is algebraic data type representing the result.


问:
How to copy a directory structure but only include certain files (using windows batch files)
As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:

```<code>folder1
  folder2
    folder3
      data.zip
      info.txt
      abc.xyz
    folder4
    folder5
      data.zip
      somefile.exe
      someotherfile.dll
</code>```

The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?

The resulting directory structure should look like this:

```<code>copy_of_folder1
  folder2
    folder3
      data.zip
      info.txt
    folder4
    folder5
      data.zip
</code>```

答:
You don't mention if it has to be batch only, but if you can use ROBOCOPY, try this:

```<code>ROBOCOPY C:\Source C:\Destination data.zip info.txt /E
</code>```

EDIT: Changed the /S parameter to /E to include empty folders.

OwnerDisplayName: Martin

Body:
As the title says, how can I recursively copy a directory structure but only include some files. E.g given the following directory structure:

folder1
  folder2
    folder3
      data.zip
      info.txt
      abc.xyz
    folder4
    folder5
      data.zip
      somefile.exe
      someotherfile.dll

The files data.zip and info.txt can appear everywhere in the directory structure. How can I copy the full directory structure, but only include files named data.zip and info.txt (all other files should be ignored)?

The resulting directory structure should look like this:

copy_of_folder1
  folder2
    folder3
      data.zip
      info.txt
    folder4
    folder5
      data.zip

Body:
You don't mention if it has to be batch only, but if you can use ROBOCOPY, try this:

ROBOCOPY C:\Source C:\Destination data.zip info.txt /E

EDIT: Changed the /S parameter to /E to include empty folders.

OwnerDisplayName: aphoria

LastEditorDisplayName: aphoria


问:
MySQL cache and date functions
I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?

example:

```<code>$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';
</code>```

vs

```<code>$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';
</code>```

答:
It's quite simple actually. The MySQL server does not see your PHP code so it'll receive one of these:

```<code>SELECT id FROM table WHERE publish_date = '2010-01-18';
SELECT id FROM table WHERE publish_date = CURDATE();
</code>```

It will not read your intentions either. For MySQL, '2010-01-18' is a string and is deterministic: its value is always '2010-01-18'. However, CURDATE() is not deterministic: its value varies depending on the date when you run it. Thus the first one is cacheable and the second one is not.

Title: MySQL cache and date functions

Body:
I once read in a performance blog that it is better to use PHP's date functions to set dates in a MySQL query instead of using mysql date functions like curdate() because mysql can then cache the query or the result or something like that. Does anyone have any insight into this? Does it hold any water or is it baseless?

example:

$query = 'SELECT id FROM table WHERE publish_date = \''.date('Y-m-d').'\'';

vs

$query = 'SELECT id FROM table WHERE publish_date = CURDATE()';

Body:
It's quite simple actually. The MySQL server does not see your PHP code so it'll receive one of these:

SELECT id FROM table WHERE publish_date = '2010-01-18';
SELECT id FROM table WHERE publish_date = CURDATE();

It will not read your intentions either. For MySQL, '2010-01-18' is a string and is deterministic: its value is always '2010-01-18'. However, CURDATE() is not deterministic: its value varies depending on the date when you run it. Thus the first one is cacheable and the second one is not.


问:
How guarantee the fingerprint value was not faked in the request from client side
A JS fingerprint is calculated in client side using a library like fingerprint2.

My question is, If i send this value through ajax, the user can fake this value with a minor effort, and just make a fake post request that will be interpreted by server code like legit.

My question is, if this can happen, this library can be easily bypassed without even change any property in browser (that will change the browser fingerprint).

My interpretation is right? How can i ensure the integrity of that value?

答:
How can i ensure the integrity of that value?

To answer you very briefly, whenever you want to protect your integrity, you must provide the digest of the sent message too.

Here I explain the defense of integrity using Alice (FrontEnd), Bob (BackEnd), and Trudy (malicious user)

Assumption:

Alice wants to send a package contains PLAIN_TEXT (here your fingerprint) to Bob, and Trudy is the malicious person who wishes to intercept the package and change the PLAIN_TEXT.

Threats against integrity :

Trudy can capture the PLAIN_TEXT and change it to whatever she wants. (In reality there could be more threats against integrity, but I wish to keep the story short.)

Here are the steps which Alice must take to protect the integrity of package:

Alice obtains the digest of PLAIN_TEXT (called text_digest).

Alice attaches the digest to the PLAIN_TEXT, and obtain a new package (package=PLAIN_TEXT+text_digest)

Alice encrypts the package

Alice obtains the digest of the encrypted package (whole_package_digest)

Alice attaches the whole_package_digest to the encrypted package, and send it to Bob

What Trudy can do after inteception:

Option 1. Try to break the encryption of the package

Option 2. Try to omit the encrypted package and attach her own package.

On Bob's side:

He decrypts the package, and obtains the PLAIN_TEXT. (he makes sure Alice has send this package, because no one else has the key )

He obtains the the digest of the PLAIN_TEXT using the same method (let's call this obtained_digest), and he compares the obtained_digest with the text_digest, and if they are equal then it means the PLAIN_TEXT is not manipulated.

At the end, he obtains the digest of the received package, and compares it with whole_package_digest. If they are equal it means Trudy has failed with her second option.

Notice that in above scenario, the integrity is highly dependent on confidentiality. But, you can use both symmetric, and asymmetric method for encryption.

In the below image, I tried to explain what I wanted to say more clearly:


问:
SQL: Update Column Value with Value from Another Column ONLY if the Column Value is Equal to Certain Values
This is the logic I'm trying to implement in SQL code:

Replace values from Req column with values from Phase column ONLY IF

The value in Phase column is equivalent to a predetermined list of values OTHERWISE

Keep the original value in Req column

I only want to replace the value in Req column if the value in Phase column is equal to C1, C2, C3, or C4

Below shows a sample of the table I'm trying to create:

I've successfully achieved the above in Python code (see below).  But now I need to do the same with SQL and I'm stuck.

```<code>phasename_dictionary = {'C1':'C1', 'C2':'C2', 'C3':'C3', 'C4':'C4'}
df.loc[df['phase'].isin(phasename_dictionary.keys()), 'req'] = df['phase'].map(phasename_dictionary)
</code>```

答:
You can achieve this with a simple update statement with a where clause:

```<code>UPDATE mytable
SET    req = phase
WHERE  phase IN ('C1', 'C2', 'C3', 'C4')
</code>```

Body:
This is the logic I'm trying to implement in SQL code:

Replace values from Req column with values from Phase column ONLY IF

The value in Phase column is equivalent to a predetermined list of values OTHERWISE

Keep the original value in Req column

I only want to replace the value in Req column if the value in Phase column is equal to C1, C2, C3, or C4

Below shows a sample of the table I'm trying to create:

I've successfully achieved the above in Python code (see below).  But now I need to do the same with SQL and I'm stuck.

phasename_dictionary = {'C1':'C1', 'C2':'C2', 'C3':'C3', 'C4':'C4'}
df.loc[df['phase'].isin(phasename_dictionary.keys()), 'req'] = df['phase'].map(phasename_dictionary)

Body:
You can achieve this with a simple update statement with a where clause:

UPDATE mytable
SET    req = phase
WHERE  phase IN ('C1', 'C2', 'C3', 'C4')


问:
Spring data query limit as parameter
I'm trying to do something like this using native query:

```<code>@Query(value = "select * from systems where UPPER(system_name) like UPPER('%?1%') ORDER BY system_name LIMIT '?2'", nativeQuery = true)
List<System> findAllBySystemNameWithLimit(String systemName, int limit);
</code>```

But it doesn't work. Is it possible to use limit as parameter? Thanks for answer.

答:
When you use ?1 or :paramname you don't have to use them between two quotes like you do
'%?1%' and '?2' so instead your query should look like :

```<code>select * from systems
   where UPPER(system_name) like UPPER(CONCAT('%', ?1, '%')) ORDER BY system_name LIMIT ?2
   //------------------------------^-----^-----^----^---^-------------------------------^^
</code>```

Title: Spring data query limit as parameter

Body:
I'm trying to do something like this using native query:

@Query(value = "select * from systems where UPPER(system_name) like UPPER('%?1%') ORDER BY system_name LIMIT '?2'", nativeQuery = true)
List<System> findAllBySystemNameWithLimit(String systemName, int limit);

But it doesn't work. Is it possible to use limit as parameter? Thanks for answer.

Body:
When you use ?1 or :paramname you don't have to use them between two quotes like you do
'%?1%' and '?2' so instead your query should look like :

select * from systems
   where UPPER(system_name) like UPPER(CONCAT('%', ?1, '%')) ORDER BY system_name LIMIT ?2
   //------------------------------^-----^-----^----^---^-------------------------------^^


问:
Including functions from another internal .c file?
I made some program using structures and functions and now I have to split my work into 3 files as follows:

```<code>header.h - declaring data types, functions, #define
func.c - function definition,
main.c - structure array initialization and calling functions
</code>```

Does it make sense to do it like that? I did that, added #include "header.h" in both .c files but it does not compile, seems there is something wrong with func.c. I'm using VS 2017.

答:
Lets consider below example,

header.h : Normally user-defined  header file consist common information like MACRO, Structure, predefined header files which will be used by most of files in multiple file compilation.

```<code>#include<stdio.h>
#include<malloc.h>
int n;
#define MAX 5
void call();

typedef enum legends {
        L_GANDHI,
        L_MARTIN_LUTHER_KING
}legends_e;
</code>```

main.c :

```<code>#include"header.h"
int main()
{
        printf("in main() : %d \n",L_GANDHI);
        call();// defined in other file
        return 0;
}
</code>```

fun.c :

```<code>#include"header.h"
void call()
{
        printf("In call() function : %d \n",L_MARTIN_LUTHER_KING);
}
</code>```

for compiling all files,

```<code>xyz@xyz-PC:~/s_flow/john$ gcc main.c func.c
</code>```

Remember that in multiple file compilation you should have only one main() function. I hope above information will give helps to solve your problem.

Body:
I made some program using structures and functions and now I have to split my work into 3 files as follows:

header.h - declaring data types, functions, #define
func.c - function definition,
main.c - structure array initialization and calling functions

Does it make sense to do it like that? I did that, added #include "header.h" in both .c files but it does not compile, seems there is something wrong with func.c. I'm using VS 2017.

Body:
Lets consider below example,

header.h : Normally user-defined  header file consist common information like MACRO, Structure, predefined header files which will be used by most of files in multiple file compilation.

#include<stdio.h>
#include<malloc.h>
int n;
#define MAX 5
void call();

typedef enum legends {
        L_GANDHI,
        L_MARTIN_LUTHER_KING
}legends_e;

main.c :

#include"header.h"
int main()
{
        printf("in main() : %d \n",L_GANDHI);
        call();// defined in other file
        return 0;
}

fun.c :

#include"header.h"
void call()
{
        printf("In call() function : %d \n",L_MARTIN_LUTHER_KING);
}

for compiling all files,

xyz@xyz-PC:~/s_flow/john$ gcc main.c func.c

Remember that in multiple file compilation you should have only one main() function. I hope above information will give helps to solve your problem.


问:
File Filter Search in Java
I'm trying to implement a class, which responsibility is to search for files in an exact directory. The class accepts a list of parameters from the user (e.g. extension, name, size, last modified date, etc.), then filters the directory with all these parameters. Doing that, using the Chain Responsibility pattern, i.e. I have different filters, each responsible for an exact filter operation (all operations are done with Java Stream API).
The problem is:
Where to store all these String parameters that i get from the user and is it correctly to pass this whole pack through my filters?

Moreover, if you have some comments or remarks on the approach I have chosen for copying with my task, and if there is a better one, will be very grateful.

答:
You don't store them anywhere to me, just create the predicates and pass those, your method could accept a List of these Predicates and you can reduce them to a single one, something along the lines:

```<code>private <T> Predicate<T> reduced(List<Predicate<T>> nameAndExtension) {
    return nameAndExtension
            .stream()
            .reduce(s -> true,
                    (left, right) -> left.and(right));
}

private void test(List<Predicate<String>> nameAndExtension, List<Predicate<Long>> sizeAndDateAsLong) {

    Predicate<String> first = reduced(nameAndExtension);
    Predicate<Long> second = reduced(sizeAndDateAsLong);

    // apply the above

}
</code>```

Title: File Filter Search in Java

Body:
You don't store them anywhere to me, just create the predicates and pass those, your method could accept a List of these Predicates and you can reduce them to a single one, something along the lines:

private <T> Predicate<T> reduced(List<Predicate<T>> nameAndExtension) {
    return nameAndExtension
            .stream()
            .reduce(s -> true,
                    (left, right) -> left.and(right));
}

private void test(List<Predicate<String>> nameAndExtension, List<Predicate<Long>> sizeAndDateAsLong) {

    Predicate<String> first = reduced(nameAndExtension);
    Predicate<Long> second = reduced(sizeAndDateAsLong);

    // apply the above

}


问:
How to append data from one CSV to another using Export-CSV
I have a script like the following:

```<code>$in_file = "C:\Data\Need-Info.csv"
$out_file = "C:\Data\Need-Info_Updated.csv"
$list = Import-Csv $in_file
ForEach ( $user in $list ) {
    $zID = $user.zID
    ForEach-Object {
        Get-QADUser -Service 'domain.local' -SearchRoot 'OU=Users,DC=domain,DC=local' -SizeLimit 75000 -LdapFilter "(&(objectCategory=person)(objectClass=user)(PersonzID=$zID))" | Select-Object DisplayName,samAccountName,@{Name="zID";expression={$zID}} | Export-Csv $out_file -NoTypeInformation -Force
    }
}
</code>```

However, I am not able to get it to output all of the results to the $out_file since it does not seem to append the data to the csv file.

Is there a way to make this append the data to a file?

答:
After version 3 you can use:</p>

```<code>Export-Csv $out_file -append -notypeinformation -encoding "unicode"
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a script like the following:

$in_file = "C:\Data\Need-Info.csv"
$out_file = "C:\Data\Need-Info_Updated.csv"
$list = Import-Csv $in_file
ForEach ( $user in $list ) {
    $zID = $user.zID
    ForEach-Object {
        Get-QADUser -Service 'domain.local' -SearchRoot 'OU=Users,DC=domain,DC=local' -SizeLimit 75000 -LdapFilter "(&(objectCategory=person)(objectClass=user)(PersonzID=$zID))" | Select-Object DisplayName,samAccountName,@{Name="zID";expression={$zID}} | Export-Csv $out_file -NoTypeInformation -Force
    }
}

However, I am not able to get it to output all of the results to the $out_file since it does not seem to append the data to the csv file.

Is there a way to make this append the data to a file?

Body:
After version 3 you can use:

Export-Csv $out_file -append -notypeinformation -encoding "unicode"


问:
TYPO3 database analyzer utf8_general_ci server settings
I upgraded my development machine to High Sierra so I needed to reinstall Apache and PHP with Brew.

Now my local sites still work but on 8.7.8 installations the Database analyzer in the Install tool wants to alter a lot of fields in the same way, for example:

```<code> ALTER TABLE `tt_content` CHANGE `header` `header` VARCHAR(255) DEFAULT '' NOT NULL
 Current value: header VARCHAR(255) DEFAULT '''' NOT NULL COLLATE utf8_general_ci
</code>```

It looks like something has changed with utf8. On my testing server this is not happening, so I suspect it is a missing setting somewhere.

In Apache vhost.conf I have AddDefaultCharset utf-8

In php.ini default_charset = "UTF-8"

In mysql command

```<code>show variables like 'char%'; show variables like 'collation%';
</code>```

shows all as utf-8 and collation_connection, collation_database and collation_server as utf8_general_ci

What could cause the result of the database analyser?

答:
Duplicate of TYPO3 lists all tables in DB compare because of COLLATE

https://forge.typo3.org/issues/82023

In the process MariaDb was upgraded by Brew to 10.2.x.

I ended up removing MariaDB in Brew and installing MySQL, that fixed the problem.

I guess downgrading MariaDB to 10.1 also works.

Body:
I upgraded my development machine to High Sierra so I needed to reinstall Apache and PHP with Brew.

Now my local sites still work but on 8.7.8 installations the Database analyzer in the Install tool wants to alter a lot of fields in the same way, for example:

 ALTER TABLE `tt_content` CHANGE `header` `header` VARCHAR(255) DEFAULT '' NOT NULL
 Current value: header VARCHAR(255) DEFAULT '''' NOT NULL COLLATE utf8_general_ci

It looks like something has changed with utf8. On my testing server this is not happening, so I suspect it is a missing setting somewhere.

In Apache vhost.conf I have AddDefaultCharset utf-8

In php.ini default_charset = "UTF-8"

In mysql command

show variables like 'char%'; show variables like 'collation%';

shows all as utf-8 and collation_connection, collation_database and collation_server as utf8_general_ci

What could cause the result of the database analyser?


问:
Grails createCriteria() used inside Domain classes
Just got to know about the capability of createCriteria() method. Just wanna know that other than applying it on the Controller, is there a way to apply onto the domain classes as well? Probably on its own mapping to a property like:</p>

```<code>static mapping = {
      additionalInfo: Page.createCriteria().list()
}
</code>```

答:
Just wanna know that other than applying it on the Controller, is
  there a way to apply onto the domain classes as well?

Criteria queries are not limited to controllers, you can apply them elsewhere using the same syntax that you would in a controller.  However, the particular example you show there is probably going to be problematic because you are trying to use GORM inside of the mapping block which is used to configure GORM.

Body:
Just got to know about the capability of createCriteria() method. Just wanna know that other than applying it on the Controller, is there a way to apply onto the domain classes as well? Probably on its own mapping to a property like:

static mapping = {
      additionalInfo: Page.createCriteria().list()
}


问:
Why is git mentioning an Untracked file outside my current directory?
git is tracking a bunch of files:

```<code>git ls-tree --full-tree -r HEAD
100644 blob a-sha1  .gitignore
100644 blob b-sha1  my/file
</code>```

however when I do a git status I get:

```<code># Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   ../../../.project
</code>```

Why is ../../../.project being listed as an untracked file?

答:
This would be due to it being present inside the directory where your git repository is initialized.

To stop it being tracked you could add that directory to your .gitignore

Body:
git is tracking a bunch of files:

git ls-tree --full-tree -r HEAD
100644 blob a-sha1  .gitignore
100644 blob b-sha1  my/file

however when I do a git status I get:

# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#   ../../../.project

Why is ../../../.project being listed as an untracked file?


问:
Intellij IDEA unable to resolve appengine-maven-plugin dependency
I created a new google appengine java project using mvn archetype:generate, as specified in this page.

I executed mvn clean install and project got successfully built.

But, when I opened the project with Intellij IDEA, it indefinitely keeps on resolving dependencies. Only when I comment out the appengine-maven-plugin plugin dependency, IDEA completes the dependency resolution.

What could be the cause for IDEA being unable to resolve appengine-maven-plugin dependency?

答:
Not sure what fixed the issue, but after following commands, it worked.</p>

```<code>mvn dependency:resolve-plugins
mvn appengine:devserver
</code>```

Body:
Not sure what fixed the issue, but after following commands, it worked.

mvn dependency:resolve-plugins
mvn appengine:devserver


问:
Python elegant assignment based on True/False values
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

```<code>if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'
</code>```

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

```<code>name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]
</code>```

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

```<code>name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')
</code>```

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

答:
You can think of a, b, and c as three bits that when put together form a number between 0 and 7.  Then, you can have an array of the values ['first', 'second', ... 'eighth'] and use the bit value as an offset into the array.  This would just be two lines of code (one to assemble the bits into a value from 0-7, and one to lookup the value in the array).

Here's the code:

```<code>nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]
</code>```

Body:
I have a variable I want to set depending on the values in three booleans. The most straight-forward way is an if statement followed by a series of elifs:

if a and b and c:
    name = 'first'
elif a and b and not c:
    name = 'second'
elif a and not b and c:
    name = 'third'
elif a and not b and not c:
    name = 'fourth'
elif not a and b and c:
    name = 'fifth'
elif not a and b and not c:
    name = 'sixth'
elif not a and not b and c:
    name = 'seventh'
elif not a and not b and not c:
    name = 'eighth'

This is a bit awkward, and I'm wondering if there's a more Pythonic way to handle this problem. A couple of ideas come to mind.

Dictionary hack:

name = {a and b and c: 'first',
        a and b and not c: 'second',
        a and not b and c: 'third',
        a and not b and not c: 'fourth',
        not a and b and c: 'fifth',
        not a and b and not c: 'sixth',
        not a and not b and c: 'seventh',
        not a and not b and not c: 'eighth'}[True]

I call it a hack because I'm not too wild about seven of the keys being False and overriding each other.

And/or magic

name = (a and b and c and 'first' or
        a and b and not c and 'second' or
        a and not b and c and 'third' or
        a and not b and not c and 'fourth' or
        not a and b and c and 'fifth' or
        not a and b and not c and 'sixth' or
        not a and not b and c and 'seventh' or
        not a and not b and not c and 'eighth')

This works because Python ands and ors return the last value to be evaluated, but you have to know that in order to understand this otherwise bizarre code.

None of these three options is very satisfying. What do you recommend?

Body:
You can think of a, b, and c as three bits that when put together form a number between 0 and 7.  Then, you can have an array of the values ['first', 'second', ... 'eighth'] and use the bit value as an offset into the array.  This would just be two lines of code (one to assemble the bits into a value from 0-7, and one to lookup the value in the array).

Here's the code:

nth = ['eighth', 'seventh', 'sixth', 'fifth', 'fourth', 'third', 'second', 'first']
nth[(a and 4 or 0) | (b and 2 or 0) | (c and 1 or 0)]


问:
Django Modelform OneToOneFielld
I'm currently writing a system in Django where I'd like to save a user at the same time i'm creating another model.

Model Code:

```<code>class MyModel(models.Model):
    user = models.OneToOneField(User,related_name="profile",primary_key=True)
    custom_field = models.CharField(...)
</code>```

The model is more elaborate of course, but it shows the setup of the whole thing.

Example form:

```<code>First name: [input]
Last name: [input]
Email: [input]
Password: [pass_input]
Custom Text: [text_input]
</code>```

Is this at all possible using a ModelForm?

答:
Yes; you could create a ModelForm that corresponds to MyModel:

```<code>class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['custom_field']
</code>```

Then in your view, you could interrupt the save of this form using commit=False (https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#the-save-method) and set the user value of your new object manually. For example, you could set user = request.user like so:

```<code>if form.is_valid():
    instance = form.save(commit = False)
    instance.user = request.user
    instance.save()
    form.save_m2m() #if your form has any m2m data to save
</code>```

Title: Django Modelform OneToOneFielld

Body:
I'm currently writing a system in Django where I'd like to save a user at the same time i'm creating another model.

Model Code:

class MyModel(models.Model):
    user = models.OneToOneField(User,related_name="profile",primary_key=True)
    custom_field = models.CharField(...)

The model is more elaborate of course, but it shows the setup of the whole thing.

Example form:

First name: [input]
Last name: [input]
Email: [input]
Password: [pass_input]
Custom Text: [text_input]

Is this at all possible using a ModelForm?

Body:
Yes; you could create a ModelForm that corresponds to MyModel:

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        fields = ['custom_field']

Then in your view, you could interrupt the save of this form using commit=False (https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#the-save-method) and set the user value of your new object manually. For example, you could set user = request.user like so:

if form.is_valid():
    instance = form.save(commit = False)
    instance.user = request.user
    instance.save()
    form.save_m2m() #if your form has any m2m data to save


问:
Version conflict detected for Microsoft.IdentityModel.Clients.ActiveDirectory
Creating an Azure function that uses nuget packages  Microsoft.Rest.ClientRuntime.Azure.Authentication for authenticating to DataLake as well as Microsoft.IdentityModel.Clients.ActiveDirectory for authenticating to HDInsight.  Getting the following error when I try to install both in the function project:

uninstall-package : Version conflict detected for Microsoft.IdentityModel.Clients.ActiveDirectory. Reference the package directly from the project to resolve this
  issue. MyProject.Functions (>= 1.0.0) -> Microsoft.Rest.ClientRuntime.Azure.Authentication (>= 2.3.1) -> Microsoft.IdentityModel.Clients.ActiveDirectory (>= 2.28.3)
  MyProject.Functions (>= 1.0.0) -> Microsoft.Azure.Common.Authentication (>= 1.7.0-preview) -> Microsoft.IdentityModel.Clients.ActiveDirectory (>=2.18.206251556).

It looks like Microsoft.Azure.Common.Authentication 1.7.0-preview has a constraint on referencing Microsoft.IdentityModel.Clients.ActiveDirectory 2.18.206251556 only.  Unfortunately this library has not been updated since February 2016 and I'm not sure of another way of authenticating non-interactively with HDInsight besides the steps outlined at https://learn.microsoft.com/en-us/azure/hdinsight/hdinsight-create-non-interactive-authentication-dotnet-applications

答: After attempting to resolve the dependency a few different ways I took Bruce's suggestion, removed all references to Microsoft.Azure.Common.Authentication and used Microsoft.IdentityModel.Clients.ActiveDirectory to get the token instead.</p>


问:
Typescript Definitions can't be imported Angular2
I have been trying to use a typescript definition file from definitely typed and I am having trouble referencing or importing it into the files I want to use it in. The definitions from definitely typed are the fhir definitions. I get errors saying that fhir isn't a namespace or module and I can't reference it in my files. I don't know if I have no idea what I am doing or if it's an angular/typescript problem. Any help would be appreciated. Thanks!</p>

答:
There are definitions available via

```<code>npm install --save @types/fhir
</code>```

More Infos on npm @types/fhir

Body:
There are definitions available via

npm install --save @types/fhir

More Infos on npm @types/fhir


问:
How do I serialize this object with JSON .NET?
I have the following object that I want to serialize to a JSON string:

```<code>public class Zone
{
    public string id;
    public string name;
    public Size size;
    public Point offset;
    public List<Label> zoneLabels;
}
</code>```

I was able to use the following just fine before adding:

```<code> public List<Label> zoneLabels;
 string json;
 json = JsonConvert.SerializeObject(zn);
</code>```

When I add in the:

```<code> public List<Label> zoneLabels;
</code>```

and run json = JsonConvert.SerializeObject(zn);
I get the following error:

{"Self referencing loop detected for property 'Owner' with type
  'System.Windows.Forms.Label'. Path
  'zoneLabels[0].AccessibilityObject'."}

Basically my Zone object contains some properties as shown and a List of Label Controls. I need to serialize this to a JSON string and recover later to the same Zone object (DeserializeObject to Zone). What do I need to do different?

答:
After some research and other responses here on SO I found the best way to probably handle this problem is make your own label object for example:

```<code>public class Zone
{
    public string id;
    public string name;
    public Size size;
    public Point offset;
    public List<ZoneLabels> zoneLabels;
}

public class ZoneLabels
{
    public string text;
    public string name;
    public Point location;
}
</code>```

You can then easily do the following to serialize to a JSON string using JSON.NET

```<code>List<ZoneLabels> labels_list = new List<ZoneLabels>();
foreach (Label zl in znLabels)
{
    labels_list.Add(new ZoneLabels { name = zl.Name, text = zl.Text, location = zl.Location });
}

Zone zn = new Zone();
zn.name = "Zone";
zn.size = new Size(464, 128);
zn.offset = new Point(x, y);
zn.id = id_new;
zn.zoneLabels = labels_list;

//serialize the object to a JSON string
string json = JsonConvert.SerializeObject(zn);
</code>```

This produces a JSON string that will deserialize back into the Zone object.

In my case I was only setting a few properties of the Label but even if you need to set several Control object properties this would could be one of the clearest ways to handle serializing a list of Form Control objects to a JSON string.

Body:
I have the following object that I want to serialize to a JSON string:

public class Zone
{
    public string id;
    public string name;
    public Size size;
    public Point offset;
    public List zoneLabels;
}

I was able to use the following just fine before adding:

 public List zoneLabels;
 string json;
 json = JsonConvert.SerializeObject(zn);

When I add in the:

 public List zoneLabels;

and run json = JsonConvert.SerializeObject(zn);
I get the following error:

{"Self referencing loop detected for property 'Owner' with type
  'System.Windows.Forms.Label'. Path
  'zoneLabels[0].AccessibilityObject'."}

Basically my Zone object contains some properties as shown and a List of Label Controls. I need to serialize this to a JSON string and recover later to the same Zone object (DeserializeObject to Zone). What do I need to do different?

Body:
After some research and other responses here on SO I found the best way to probably handle this problem is make your own label object for example:

public class Zone
{
    public string id;
    public string name;
    public Size size;
    public Point offset;
    public List<ZoneLabels> zoneLabels;
}

public class ZoneLabels
{
    public string text;
    public string name;
    public Point location;
}

You can then easily do the following to serialize to a JSON string using JSON.NET

List<ZoneLabels> labels_list = new List<ZoneLabels>();
foreach (Label zl in znLabels)
{
    labels_list.Add(new ZoneLabels { name = zl.Name, text = zl.Text, location = zl.Location });
}

Zone zn = new Zone();
zn.name = "Zone";
zn.size = new Size(464, 128);
zn.offset = new Point(x, y);
zn.id = id_new;
zn.zoneLabels = labels_list;

//serialize the object to a JSON string
string json = JsonConvert.SerializeObject(zn);

This produces a JSON string that will deserialize back into the Zone object.

In my case I was only setting a few properties of the Label but even if you need to set several Control object properties this would could be one of the clearest ways to handle serializing a list of Form Control objects to a JSON string.


问:
A class containing 3 objects, which have pointers to each other, and an initialisation list to pass references to those objects. ERROR
Agent.h:  //#include "Genetics.h" "Sensors.h" "Effectors.h"

```<code>class C_Agent
{
public:

    C_Agent();

    C_Genome Genome;
    C_Sensors Sensors;
    C_Effectors Effectors;
    s_agentParameters parameters;
};
</code>```

Agent.cpp: //#include "Agent.h"

```<code>C_Agent::C_Agent()
: parameters(), Sensors(& parameters), Effectors(& parameters),
  Genome(& Sensors, & Effectors)
{
    //setup parameters
    Effectors.p_Genome = & Genome;
}
</code>```

Sensors.h: //#include "Genetics.h"

```<code>class C_Sensors
{
  public:
    s_agentParameters * p_parameters;
    C_sensors(s_agentParameters * p_parametersRef);
};
</code>```

Sensors.cpp: //#include "Sensors.h"

```<code>C_Sensors::C_Sensors(s_agentParameters * p_parametersRef)
: p_parameters(p_parametersRef) {}
</code>```

Effectors.h //#include "Genetics.h"

```<code>class C_Effectors
{
public:
    s_agentParameters * p_parameters;
    C_Genome * p_Genome;                               //forbids declaration w/ no type
    C_Effectors(s_agentParameters * p_parametersRef);
};
</code>```

Effectors.cpp: //#include "Effectors.h"

```<code>C_Effectors::C_Effectors(s_agentParameters * p_parametersRef)
: p_parameters(p_parametersRef) {}
</code>```

Genetics.h: //#include "Sensors.h" "Effectors.h"

```<code>class C_Genome
{
public:
    C_Sensors * p_Sensors;                             //forbids declaration w/ no type
    C_Effectors * p_Effectors;                         //forbids declaration w/ no type
    C_Genome(C_Sensors * p_C_SensorsRef, C_Effectors * p_C_EffectorsRef);
};
</code>```

Genetics.cpp: //#include "Genetics.h" "Sensors.h" "Effectors.h"

```<code>C_Genome::C_Genome(C_Sensors * p_C_SensorsRef, C_Effectors * p_C_EffectorsRef)
: p_Sensors (p_C_SensorsRef),  p_Effectors (p_C_EffectorsRef) {}
</code>```

When I try to compile this, I get 6 errors of "'class_name' does not name a type" and 6 errors of " ISO c++ forbids declaration of 'class_name' with no type". I also have code in main that attempts to initialize some C_Agent objects.

答: If you have a circular dependency, you will need a forward declaration of at least one of the class names somewhere.</p>

Body:
Agent.h:  //#include "Genetics.h" "Sensors.h" "Effectors.h"

class C_Agent
{
public:

    C_Agent();

    C_Genome Genome;
    C_Sensors Sensors;
    C_Effectors Effectors;
    s_agentParameters parameters;
};

Agent.cpp: //#include "Agent.h"

C_Agent::C_Agent()
: parameters(), Sensors(& parameters), Effectors(& parameters),
  Genome(& Sensors, & Effectors)
{
    //setup parameters
    Effectors.p_Genome = & Genome;
}

Sensors.h: //#include "Genetics.h"

class C_Sensors
{
  public:
    s_agentParameters * p_parameters;
    C_sensors(s_agentParameters * p_parametersRef);
};

Sensors.cpp: //#include "Sensors.h"

C_Sensors::C_Sensors(s_agentParameters * p_parametersRef)
: p_parameters(p_parametersRef) {}

Effectors.h //#include "Genetics.h"

class C_Effectors
{
public:
    s_agentParameters * p_parameters;
    C_Genome * p_Genome;                               //forbids declaration w/ no type
    C_Effectors(s_agentParameters * p_parametersRef);
};

Effectors.cpp: //#include "Effectors.h"

C_Effectors::C_Effectors(s_agentParameters * p_parametersRef)
: p_parameters(p_parametersRef) {}

Genetics.h: //#include "Sensors.h" "Effectors.h"

class C_Genome
{
public:
    C_Sensors * p_Sensors;                             //forbids declaration w/ no type
    C_Effectors * p_Effectors;                         //forbids declaration w/ no type
    C_Genome(C_Sensors * p_C_SensorsRef, C_Effectors * p_C_EffectorsRef);
};

Genetics.cpp: //#include "Genetics.h" "Sensors.h" "Effectors.h"

C_Genome::C_Genome(C_Sensors * p_C_SensorsRef, C_Effectors * p_C_EffectorsRef)
: p_Sensors (p_C_SensorsRef),  p_Effectors (p_C_EffectorsRef) {}

When I try to compile this, I get 6 errors of "'class_name' does not name a type" and 6 errors of " ISO c++ forbids declaration of 'class_name' with no type". I also have code in main that attempts to initialize some C_Agent objects.


问:
Create users server-side Firebase Functions
I am trying to create a login GET request to the server side using the Firebase cloud functions.

Is it possible to auth using firebase functions? I tried npm i firebase inside the functions folder, but it fails to work.

Is there an option to create users using server-side code?

答:
To create Firebase Authentication users from within Cloud Functions you use the Firebase Admin SDK for Node.js.

To install it, follow the instructions in the documentation. Mostly it's:

```<code>$ npm install firebase-admin --save
</code>```

And then import it into your index.js using:

```<code>var admin = require("firebase-admin");
</code>```

To create a user follow the instructions in this documentation:

```<code>admin.auth().createUser({
  email: "user@example.com",
  emailVerified: false,
  phoneNumber: "+11234567890",
  password: "secretPassword",
  displayName: "John Doe",
  photoURL: "http://www.example.com/12345678/photo.png",
  disabled: false
})
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log("Successfully created new user:", userRecord.uid);
  })
  .catch(function(error) {
    console.log("Error creating new user:", error);
  });
</code>```

Body:
To create Firebase Authentication users from within Cloud Functions you use the Firebase Admin SDK for Node.js.

To install it, follow the instructions in the documentation. Mostly it's:

$ npm install firebase-admin --save

And then import it into your index.js using:

var admin = require("firebase-admin");

To create a user follow the instructions in this documentation:

admin.auth().createUser({
  email: "user@example.com",
  emailVerified: false,
  phoneNumber: "+11234567890",
  password: "secretPassword",
  displayName: "John Doe",
  photoURL: "http://www.example.com/12345678/photo.png",
  disabled: false
})
  .then(function(userRecord) {
    // See the UserRecord reference doc for the contents of userRecord.
    console.log("Successfully created new user:", userRecord.uid);
  })
  .catch(function(error) {
    console.log("Error creating new user:", error);
  });


问:
Camera Freezes on starting emotion detector
Hey I am using Affectiva Affdex ios SDK. Now I have 2 views.

UIView -> Where i run a camera stream. Code for the same is here:

```<code>func allConfig(withCamView cams:UIView) {

let captureDevice = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInDualCamera, .builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified)

for device in (captureDevice?.devices)! {

    if device.position == .front{

        do {
            let input = try AVCaptureDeviceInput(device: device)

            if session.canAddInput(input) {
                session.addInput(input)
            }

            if session.canAddOutput(previewOutput) {
                session.addOutput(previewOutput)
            }

            previewLayer = AVCaptureVideoPreviewLayer(session: session)
            previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            previewLayer.connection.videoOrientation = .portrait

            cams.layer.addSublayer(previewLayer)

            previewLayer.position = CGPoint(x: cams.frame.width/2, y: cams.frame.height/2)
            previewLayer.bounds = cams.frame

            session.startRunning()

        } catch let avError {
            print(avError)
        }
    }
}

}
</code>```

another UICollectionView Cell where I am starting a detector. Code for that is here:

```<code> func createDetector() {
destroyDetector()
let captureDevice = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInDualCamera, .builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified)
for device in (captureDevice?.devices)! {

    if device.position == .front{
        EMDetector = AFDXDetector(delegate: self, using: device, maximumFaces: 2, face: LARGE_FACES)
        EMDetector.maxProcessRate = 5

        // turn on all classifiers (emotions, expressions, and emojis)
        EMDetector.setDetectAllExpressions(true)
        EMDetector.setDetectAllEmotions(true)
        EMDetector.setDetectAllAppearances(true)
        EMDetector.setDetectEmojis(true)

        // turn on gender and glasses
        EMDetector.gender = true
        EMDetector.glasses = true

        // start the detector and check for failure
        let error: Error? = EMDetector.start()
        if nil != error {
            print("Some Faliure in detector")
            print("root cause of error ------------------------- > \(error.debugDescription)")
        }
    }
}

}
</code>```

These View take 50-50 screen space.

Issue:

Whenever I try and run the app, the camera stream freezes after one second. And that is because the detector starts.
Now, if you check there github sample app (https://github.com/Affectiva/affdexme-ios/tree/master/apps/AffdexMe), also available on app store. the camera view is still on even when they are detecting the emotion.

I even tried merging the 2 functions and then calling the function, but somehow one function cancels the other.

what is the way around to this?

Thanks

答:
The problem is that you're creating a capture session for your first view and the SDK creates another session to process the camera input. You can't have multiple sessions running at the same time.

One way to fix this is to use the image returned from the delegate method func detector(_ detector: AFDXDetector!, hasResults faces: NSMutableDictionary!, for image: UIImage!, atTime time: TimeInterval) in both views.

Another way is to create your camera session then pass the images to the detector yourself.

initialize your detector like this

EMDetector = AFDXDetector(delegate: self, discreteImages: false, maximumFaces: 2, face: LARGE_FACES)

Then pass images from your capture session to the detector using

EMDetector.processImage(UIImage!, atTime: TimeInterval)

Body:
Hey I am using Affectiva Affdex ios SDK. Now I have 2 views.

UIView -> Where i run a camera stream. Code for the same is here:

func allConfig(withCamView cams:UIView) {

let captureDevice = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInDualCamera, .builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified)

for device in (captureDevice?.devices)! {

    if device.position == .front{

        do {
            let input = try AVCaptureDeviceInput(device: device)

            if session.canAddInput(input) {
                session.addInput(input)
            }

            if session.canAddOutput(previewOutput) {
                session.addOutput(previewOutput)
            }

            previewLayer = AVCaptureVideoPreviewLayer(session: session)
            previewLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
            previewLayer.connection.videoOrientation = .portrait

            cams.layer.addSublayer(previewLayer)

            previewLayer.position = CGPoint(x: cams.frame.width/2, y: cams.frame.height/2)
            previewLayer.bounds = cams.frame

            session.startRunning()

        } catch let avError {
            print(avError)
        }
    }
}

}

another UICollectionView Cell where I am starting a detector. Code for that is here:

 func createDetector() {
destroyDetector()
let captureDevice = AVCaptureDeviceDiscoverySession(deviceTypes: [.builtInDualCamera, .builtInWideAngleCamera], mediaType: AVMediaTypeVideo, position: .unspecified)
for device in (captureDevice?.devices)! {

    if device.position == .front{
        EMDetector = AFDXDetector(delegate: self, using: device, maximumFaces: 2, face: LARGE_FACES)
        EMDetector.maxProcessRate = 5

        // turn on all classifiers (emotions, expressions, and emojis)
        EMDetector.setDetectAllExpressions(true)
        EMDetector.setDetectAllEmotions(true)
        EMDetector.setDetectAllAppearances(true)
        EMDetector.setDetectEmojis(true)

        // turn on gender and glasses
        EMDetector.gender = true
        EMDetector.glasses = true

        // start the detector and check for failure
        let error: Error? = EMDetector.start()
        if nil != error {
            print("Some Faliure in detector")
            print("root cause of error ------------------------- > \(error.debugDescription)")
        }
    }
}

}

These View take 50-50 screen space.

Issue:

Whenever I try and run the app, the camera stream freezes after one second. And that is because the detector starts.
Now, if you check there github sample app (https://github.com/Affectiva/affdexme-ios/tree/master/apps/AffdexMe), also available on app store. the camera view is still on even when they are detecting the emotion.

I even tried merging the 2 functions and then calling the function, but somehow one function cancels the other.

what is the way around to this?

Thanks


问:
Top 1 & Top 1 1 ( Expr1000 1 ) typical output
```<code>SELECT TOP 1 * FROM Customers;
</code>```

This gives me all customer details of first row

```<code>( customerid, customer name etc..,)
</code>```

```<code>SELECT TOP 1 1 FROM Customers;
</code>```

I got o/p as

```<code>  Expr1000
 ------------
     1
</code>```

But I genuinely don't understand above output, and I searched for it but couldn't get the clear understanding of it.

答:
The second "1" is not considered as a column, it's just a constant. So with this query, you ask to write down one (TOP 1) row with one column with the constant "1". Same thing will happen if you write something like this :

```<code>SELECT TOP 1 'Hey you', 1 as valueone ,2 ,3, customerid
FROM Customers ;
</code>```

You'll have one row with the values 'Hey you' , '1' in column "valueone", '2', '3' then your customerid from the first row

Body:
SELECT TOP 1 * FROM Customers;

This gives me all customer details of first row

( customerid, customer name etc..,)

SELECT TOP 1 1 FROM Customers;

I got o/p as

  Expr1000
 ------------
     1

But I genuinely don't understand above output, and I searched for it but couldn't get the clear understanding of it.

Body:
The second "1" is not considered as a column, it's just a constant. So with this query, you ask to write down one (TOP 1) row with one column with the constant "1". Same thing will happen if you write something like this :

SELECT TOP 1 'Hey you', 1 as valueone ,2 ,3, customerid
FROM Customers ;

You'll have one row with the values 'Hey you' , '1' in column "valueone", '2', '3' then your customerid from the first row


问:
How can I add multiple classes to a Rails form input with erb?
So this is what I want to do:

```<code><% for x in 6..10 %>
  <%= form_for(current_user.responses.new, html:{class: 'col-xs-2 col-md-1 col-lg-1 vcenter center'}) do |f, index| %>
    <%= f.text_field :response_value, label: false, :class => "my-width <%= x %>" %>
  <% end %>
<% end %>
</code>```

But it doesn't work. I want to have two classes on the input field, one being a normal css class using html. The other using an erb variable, in this case 'x'.

I've tried

```<code><%= f.text_field :response_value, label: false, :class => "my-width center vcenter", :class => x %>
</code>```

Which only assigns the second :class, and overrides the first.

How can I assign both these classes ("my-width" and x) to the form input field?

答:
Posting a new answer since Rails4 has a much better way of doing this:</p>

```<code><%= f.text_field :response_value, label: false, class: ["my-width", x] %>
</code>```

Body:
So this is what I want to do:

<% for x in 6..10 %>
  <%= form_for(current_user.responses.new, html:{class: 'col-xs-2 col-md-1 col-lg-1 vcenter center'}) do |f, index| %>
    <%= f.text_field :response_value, label: false, :class => "my-width <%= x %>" %>
  <% end %>
<% end %>

But it doesn't work. I want to have two classes on the input field, one being a normal css class using html. The other using an erb variable, in this case 'x'.

I've tried

<%= f.text_field :response_value, label: false, :class => "my-width center vcenter", :class => x %>

Which only assigns the second :class, and overrides the first.

How can I assign both these classes ("my-width" and x) to the form input field?

Body:
Posting a new answer since Rails4 has a much better way of doing this:

<%= f.text_field :response_value, label: false, class: ["my-width", x] %>