问:
Setting current_user in system tests
I'm using system tests to verify that the following flow works as expected for a user:

Sign up in a form

Get signed in

Visit account page

Update account information

However, I'm getting an error after user creation:

```<code>Puma caught this error: Couldn't find User with 'id'=16 (ActiveRecord::RecordNotFound)
/Me/MyComputer/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/activerecord-5.1.4/lib/active_record/core.rb:189:in `find'
/Me/MyComputer/Documents/my_app/app/controllers/application_controller.rb:30:in `current_user'
</code>```

The error is pointing to the code that sets current_user in application_controller:

```<code>def current_user
  if session[:user_id]
    @current_user ||= User.find(session[:user_id])
  end
end
</code>```

Is my assumption correct that it's not possible to access session in tests? And if so - how can I then set current_user so I can test my scenario above? If not so - what could be causing the error?

答: In a rails system test your application should be able to access the session, your test code however cannot. In your case I assume current_user is being called from the application code, not from test code. In that case the most common reason for DB weirdness is that your Puma instance is running in clustered mode (separate process) rather than the required single mode (same process just a different thread). Check the output of Puma when running tests and make sure it states "single mode" - If not you'll need to adjust the configuration of Puma in the test environment to use 0 processes and 1 or more threads (as needed for your testing)</p>

Title: Setting current_user in system tests

Body:
I'm using system tests to verify that the following flow works as expected for a user:

Sign up in a form

Get signed in

Visit account page

Update account information

However, I'm getting an error after user creation:

Puma caught this error: Couldn't find User with 'id'=16 (ActiveRecord::RecordNotFound)
/Me/MyComputer/.rbenv/versions/2.4.1/lib/ruby/gems/2.4.0/gems/activerecord-5.1.4/lib/active_record/core.rb:189:in `find'
/Me/MyComputer/Documents/my_app/app/controllers/application_controller.rb:30:in `current_user'

The error is pointing to the code that sets current_user in application_controller:

def current_user
  if session[:user_id]
    @current_user ||= User.find(session[:user_id])
  end
end

Is my assumption correct that it's not possible to access session in tests? And if so - how can I then set current_user so I can test my scenario above? If not so - what could be causing the error?


来源: stackexchange

问:
load multiple tables in one spreadsheet into R
I have an Excel worksheet containing multiple tables that I want to import into R (import as multiple data frame). I know how to do that if these tables are stored in different tabs, but the raw file that I'm using has several tables in one tab.

Part view of my spreadsheet

I'm wondering if it is possible to have R read each table into a separate data frame by a certain function. Say once R reads a blank row, it just stops and imports all above rows into one table, then restart the process to read the second table, for example. Or do I have to manually save each table into a separate tab/sheet to let R read them?

Note: I cannot use nrow=n in the read.table package as the row of each table might be changing. I need to find a more universal way to make the whole process automatic, regardless of the structure of each table.

答:
Could you manually copy/paste each table into it's own tab and then export each tab into a CSV or TSV? That is what I would normally do.

If that is too much work, then @joran's suggestion will probably work. You could use stringr::str_detect() to identify when a column or row is empty or not empty and then plug that information into the startRow, startCol, endRow, endCol parameters.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Read a file in a fragment and put it in a listview
I have a "Todo.txt" file where i want to read all lines and insert them to my listview. It seems like the listview is not getting any items and the problem is how i read the file in. Any suggestions?

```<code>public class MainFragment extends Fragment {
    ArrayList<String> arrayList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);

        // Set title of fragment page
        TextView textView = (TextView) v.findViewById(R.id.titleTextView);
        textView.setText(getArguments().getString("fragmentTitle"));

        ListView listView = (ListView)v.findViewById(R.id.listview);

        arrayListSetup();

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                arrayList
        );

        listView.setAdapter(arrayAdapter);

        return v;
    }

    private void arrayListSetup(){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(new MainActivity().FILENAME));
            String line;

            // add line to arraylist
            while((line = br.readLine()) != null){
                arrayList.add(line);
            }
            // close bufferedreader
            br.close();

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

The MainActivity when clicking the button, it writes the todo-activity to the file:

```<code>addTodoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Get category of to-do
                String category = spinner.getSelectedItem().toString();

                // Get the to-do text what has to be done
                String todo_text = editText.getText().toString();

                // Try to create inputfile
                try {
                    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(todo_text.getBytes());
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });
</code>```

答:
I think you should call the function arrayListSetup() in your fragment's onCreateView()

You have declared your arraylist but haven't populated it by calling the arraylistsetup() function, call it in the onCreateView()

Body:
I have a "Todo.txt" file where i want to read all lines and insert them to my listview. It seems like the listview is not getting any items and the problem is how i read the file in. Any suggestions?

public class MainFragment extends Fragment {
    ArrayList<String> arrayList = new ArrayList<String>();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_main, container, false);

        // Set title of fragment page
        TextView textView = (TextView) v.findViewById(R.id.titleTextView);
        textView.setText(getArguments().getString("fragmentTitle"));

        ListView listView = (ListView)v.findViewById(R.id.listview);

        arrayListSetup();

        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                getActivity(),
                android.R.layout.simple_list_item_1,
                arrayList
        );

        listView.setAdapter(arrayAdapter);

        return v;
    }

    private void arrayListSetup(){
        StringBuilder stringBuilder = new StringBuilder();
        try {
            BufferedReader br = new BufferedReader(new FileReader(new MainActivity().FILENAME));
            String line;

            // add line to arraylist
            while((line = br.readLine()) != null){
                arrayList.add(line);
            }
            // close bufferedreader
            br.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

The MainActivity when clicking the button, it writes the todo-activity to the file:

addTodoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Get category of to-do
                String category = spinner.getSelectedItem().toString();

                // Get the to-do text what has to be done
                String todo_text = editText.getText().toString();

                // Try to create inputfile
                try {
                    FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
                    fos.write(todo_text.getBytes());
                    fos.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        });


问:
How to depend on a test Maven jar in Bazel?
Some Maven artifacts in addition to the main jar provide a separate test jar which contains classes to aid with writing tests that use the dependency. kafka-streams is one example. In Gradle it's possible to depend on such a jar using classifier: "test" (if the test jar has -test.jar suffix) and in Maven that would be <type>test-jar</type>. How to add a test jar to a Bazel workspace?

答:
The Skylark maven_jar implementation supports this, with the artifact syntax of group:artifact:version:packaging:classifier.

```<code>load("@bazel_tools//tools/build_defs/repo:maven_rules.bzl", "maven_jar")
maven_jar(
    name = "org_apache_kafka_test",
    artifact = "org.apache.kafka:kafka-streams:1.0.0:jar:test",
    sha1 = "b275b72148aad7a59cc12f1005507d61fc0ae77b",
)
</code>```

Body:
The Skylark maven_jar implementation supports this, with the artifact syntax of group:artifact:version:packaging:classifier.

load("@bazel_tools//tools/build_defs/repo:maven_rules.bzl", "maven_jar")
maven_jar(
    name = "org_apache_kafka_test",
    artifact = "org.apache.kafka:kafka-streams:1.0.0:jar:test",
    sha1 = "b275b72148aad7a59cc12f1005507d61fc0ae77b",
)


问:
Read properties of component from within PropertyDecorator
When applying @Input() decorators to my component properties, then chaining together with my custom decorator.

I don't seem to be able to read/set any of my public properties - even though they bind correctly.

For example

```<code>  @Input()
  @Language('global.pw.current')
  public existingPasswordLabel: string;
</code>```

Then in my language decorator

```<code>export function Language(keyId: string): PropertyDecorator {
  return (target: any, key: string) => {
    setTimeout(()=>{
      console.log(target[key]); //This is never set but is on screen
      // in fact none of my public component properties are on the target
    },1000); //Plenty of delay to make sure binding has happened
  };
}
</code>```

How to read/write my component properties at this point.

答:
The target object is not an instance of your class, it is the class itself, and since the property you are trying to set is on an instance of a the class, target[key] will never be set to anything (It is in essence Class[key])

You can try to overwrite the field to be a property so you have access to when the property is get/set

```<code>export function Language(keyId: string): PropertyDecorator & MethodDecorator {
    return (target: any, key: string, desc?: PropertyDescriptor) => {
        desc = desc || {
            get: function () {
                return this["_" + key];
            },
            configurable: true,
            enumerable: true
        };

        let baseSetter = desc.set || function (value) {
            this["_" + key] = value;
        };

        desc.set = function (value) {
            console.log(`Value of ${key} is ${value} with ${keyId}`);
            baseSetter.call(this, value);
        };
        // We return the property descriptor which will be used to define the property using Object.defineProperty in the __decorate helper
        return desc;
    };
}
class ChildComponent {
    @Language('global.pw.current')
    @Input()
    public existingPasswordLabel: string;
    // Works with properties as well
    private _title: string;
    @Language('global.title')
    @Input()
    public get title(): string {
        return this._title;
    }
    public set title(value: string) {
        this._title = value;
    }
}
</code>```

Note: I did not test with the @Input decorator added, but it should work.

Edit: Tested with the @Input decorator, and everything works as expected. Also I updated code to work with both fields and properties.

Body:
When applying @Input() decorators to my component properties, then chaining together with my custom decorator.

I don't seem to be able to read/set any of my public properties - even though they bind correctly.

For example

  @Input()
  @Language('global.pw.current')
  public existingPasswordLabel: string;

Then in my language decorator

export function Language(keyId: string): PropertyDecorator {
  return (target: any, key: string) => {
    setTimeout(()=>{
      console.log(target[key]); //This is never set but is on screen
      // in fact none of my public component properties are on the target
    },1000); //Plenty of delay to make sure binding has happened
  };
}

How to read/write my component properties at this point.

Body:
The target object is not an instance of your class, it is the class itself, and since the property you are trying to set is on an instance of a the class, target[key] will never be set to anything (It is in essence Class[key])

You can try to overwrite the field to be a property so you have access to when the property is get/set

export function Language(keyId: string): PropertyDecorator & MethodDecorator {
    return (target: any, key: string, desc?: PropertyDescriptor) => {
        desc = desc || {
            get: function () {
                return this["_" + key];
            },
            configurable: true,
            enumerable: true
        };

        let baseSetter = desc.set || function (value) {
            this["_" + key] = value;
        };

        desc.set = function (value) {
            console.log(`Value of ${key} is ${value} with ${keyId}`);
            baseSetter.call(this, value);
        };
        // We return the property descriptor which will be used to define the property using Object.defineProperty in the __decorate helper
        return desc;
    };
}
class ChildComponent {
    @Language('global.pw.current')
    @Input()
    public existingPasswordLabel: string;
    // Works with properties as well
    private _title: string;
    @Language('global.title')
    @Input()
    public get title(): string {
        return this._title;
    }
    public set title(value: string) {
        this._title = value;
    }
}

Note: I did not test with the @Input decorator added, but it should work.

Edit: Tested with the @Input decorator, and everything works as expected. Also I updated code to work with both fields and properties.


问:
Python check if a value in a list exists in another list
I have a requirement, where I am trying to find if a value in a list is found in another list and then just take that value alone.

For Example

```<code>MyCountryList = ( 'United States', 'United Kingdom', 'Russia')

data = (['United States', 'IDB', 1989, Decimal('275200141')],
 ['United States', 'IDC', 1990, Decimal('282899816')],
'India', 'IDD', 1989, Decimal('275200141')],
 ['India', 'IDE', 1990, Decimal('282899816')])
</code>```

I want my output to have the United States only as this is the only country present in both the lists on this format without the word decimal and '' on the list.

```<code>MyRequiredList = (['United States', 'IDB', '1989', '275200141'],
 ['United States', 'IDC', '1990', '282899816'])

data[0] gives me this ['United States', 'IDB', 1989, Decimal('92490932')]
</code>```

答:
You can try this:

```<code>from decimal import Decimal
MyCountryList = ( 'United States', 'United Kingdom', 'Russia')

data = (['United States', 'IDB', 1989, Decimal('275200141')],
  ['United States', 'IDC', 1990, Decimal('282899816')],
    ['India', 'IDD', 1989, Decimal('275200141')],
   ['India', 'IDE', 1990, Decimal('282899816')])
final_data = [i for i in data if i[0] in MyCountryList]
</code>```

Output:

```<code>[['United States', 'IDB', 1989, Decimal('275200141')], ['United States', 'IDC', 1990, Decimal('282899816')]]
</code>```

Body:
I have a requirement, where I am trying to find if a value in a list is found in another list and then just take that value alone.

For Example

MyCountryList = ( 'United States', 'United Kingdom', 'Russia')

data = (['United States', 'IDB', 1989, Decimal('275200141')],
 ['United States', 'IDC', 1990, Decimal('282899816')],
'India', 'IDD', 1989, Decimal('275200141')],
 ['India', 'IDE', 1990, Decimal('282899816')])

I want my output to have the United States only as this is the only country present in both the lists on this format without the word decimal and '' on the list.

MyRequiredList = (['United States', 'IDB', '1989', '275200141'],
 ['United States', 'IDC', '1990', '282899816'])

data[0] gives me this ['United States', 'IDB', 1989, Decimal('92490932')]

Body:
You can try this:

from decimal import Decimal
MyCountryList = ( 'United States', 'United Kingdom', 'Russia')

data = (['United States', 'IDB', 1989, Decimal('275200141')],
  ['United States', 'IDC', 1990, Decimal('282899816')],
    ['India', 'IDD', 1989, Decimal('275200141')],
   ['India', 'IDE', 1990, Decimal('282899816')])
final_data = [i for i in data if i[0] in MyCountryList]

Output:

[['United States', 'IDB', 1989, Decimal('275200141')], ['United States', 'IDC', 1990, Decimal('282899816')]]


问:
Error in named queries
I am getting  org.hibernate.HibernateException: Errors in named queries: getPreferenceById and this is my query

```<code>@NamedQueries({
    @NamedQuery(name = "getPreferenceById",
    query = "select p from Preference p where p.profile.id=:Id") })
</code>```

and this is my preference class

```<code>@Entity(name = "perference")
public class Preference {

    @OneToOne
    @JoinColumn(name = "id", nullable = false)
    private Profile profile;

}
</code>```

The query is for fetching the preference for the given profileId, (id), but it is giving error. I have a similar named query in the Profile class, but it is not giving error.

I found this in the stacktrace,

```<code>Error in named query: getPreferenceById
org.hibernate.hql.internal.ast.QuerySyntaxException: Preference is not mapped
[select p from Preference p where p.profile.id=:Id]
</code>```

I have added the javax @Entity annotation to the preference class

What is wrong with this named query?

答:
It seems that there is a typo error, change Preference  to preference:

```<code>@NamedQueries({
    @NamedQuery(name = "getPreferenceById",
    query = "select p from preference p where p.profile.id=:Id") })
</code>```

As you're using @Entity(name = "perference") to map your class.

Title: Error in named queries

Body:
I am getting  org.hibernate.HibernateException: Errors in named queries: getPreferenceById and this is my query

@NamedQueries({
    @NamedQuery(name = "getPreferenceById",
    query = "select p from Preference p where p.profile.id=:Id") })

and this is my preference class

@Entity(name = "perference")
public class Preference {

    @OneToOne
    @JoinColumn(name = "id", nullable = false)
    private Profile profile;

}

The query is for fetching the preference for the given profileId, (id), but it is giving error. I have a similar named query in the Profile class, but it is not giving error.

I found this in the stacktrace,

Error in named query: getPreferenceById
org.hibernate.hql.internal.ast.QuerySyntaxException: Preference is not mapped
[select p from Preference p where p.profile.id=:Id]

I have added the javax @Entity annotation to the preference class

What is wrong with this named query?

Body:
It seems that there is a typo error, change Preference  to preference:

@NamedQueries({
    @NamedQuery(name = "getPreferenceById",
    query = "select p from preference p where p.profile.id=:Id") })

As you're using @Entity(name = "perference") to map your class.


问:
Java preprocess phase
I'm writing a Java application that needs a lot of static data that is stored in many enum types. Since I would like an user-friendly way to customize this data using for example xml or json files but I'm not allowed to do it directly with enums I was looking for a way to elegantly do it.

Maybe a good solution would be to have a separate java program that reads the xml files and produces the java sources that are then compiled with the remaining part of the sources. My doubs is how to automatize this process in a stand alone way (eg ant?) and how to integrate it seamlessly with eclipse so that it is autOmatically done when I'm working with the project.. Does anything similar to what I'm looking already exists? Any suggestion to solve my problem?

Thanks!

答:
You can write a maven plugin that generates the code. There are some plugins that do that. It won't work automatically, but you can connect it to the standard maven lifecycle so it gets executed just before compile.
I just did something like that recently. </p>

ContentLicense: CC BY-SA 2.5

Title: Java preprocess phase


问:
What does __flags__ in python type used for
I have been read pickle source code recently.

The following code in copy_reg make me confused:

```<code>_HEAPTYPE = 1<<9

def _reduce_ex(self, proto):
    assert proto < 2
    for base in self.__class__.__mro__:
        if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
            break
    else:
        base = object # not really reachable
    if base is object:
        state = None
</code>```

So what does __flags__ using for?

I found it is defined in type object:

```<code>type.__flags__ = 2148423147
</code>```

I was tried to search it in the official doc, but nothing was found.

But interesting thing is that __class__.__flags__ & _HEAPTYPE is always 0 when the __class__ is python internal type. And the result will be 1 when __class__ is a subclass of python internal type.

Can anyone help me to solve this puzzle?

答:
__flags__ is a wrapper, to access CPython type object structure member tp_flags, constants used to compose this flag defined in object.h, following is quoted from the source:

Type flags (tp_flags)
  These flags are used to extend the type structure in a backwards-compatible
  fashion. Extensions can use the flags to indicate (and test) when a given
  type structure contains a new feature. The Python core will use these when
  introducing new functionality between major revisions (to avoid mid-version
  changes in the PYTHON_API_VERSION).

See more detail on python document on tp_flags.

But interesting thing is that class.flags & _HEAPTYPE is always 0 when the class is a python internal type. And the result will be 1 when class is a subclass of python internal type.

Subclass of python built-in type, like other user defined type, allocated on heap with PyType_GenericAlloc().

to break down type.__flags__:

```<code>import re

def flags_to_name(type_obj):
    tp_flag_consts = {}
    with open('/path/to/Include/object.h') as f:
        for l in f:
            m = re.search(r'^#define (Py_TPFLAGS_\w+)\s+\(.+?<< (\d+)\)', l.strip())
            if m:
                tp_flag_consts[int(m.group(2))] = m.group(1)
    bin_str = bin(type_obj.__flags__)[2:][::-1]
    return ', '.join(tp_flag_consts[n] for n, c in enumerate(bin_str) if c == '1')

print(flags_to_name(type))
</code>```

yields:

```<code>Py_TPFLAGS_BASETYPE, Py_TPFLAGS_READY, Py_TPFLAGS_HAVE_GC, Py_TPFLAGS_HAVE_VERSION_TAG, Py_TPFLAGS_VALID_VERSION_TAG, Py_TPFLAGS_TYPE_SUBCLASS
</code>```

Body:
I have been read pickle source code recently.

The following code in copy_reg make me confused:

_HEAPTYPE = 1<<9

def _reduce_ex(self, proto):
    assert proto < 2
    for base in self.__class__.__mro__:
        if hasattr(base, '__flags__') and not base.__flags__ & _HEAPTYPE:
            break
    else:
        base = object # not really reachable
    if base is object:
        state = None

So what does __flags__ using for?

I found it is defined in type object:

type.__flags__ = 2148423147

I was tried to search it in the official doc, but nothing was found.

But interesting thing is that __class__.__flags__ & _HEAPTYPE is always 0 when the __class__ is python internal type. And the result will be 1 when __class__ is a subclass of python internal type.

Can anyone help me to solve this puzzle?

Body:
__flags__ is a wrapper, to access CPython type object structure member tp_flags, constants used to compose this flag defined in object.h, following is quoted from the source:

Type flags (tp_flags)
  These flags are used to extend the type structure in a backwards-compatible
  fashion. Extensions can use the flags to indicate (and test) when a given
  type structure contains a new feature. The Python core will use these when
  introducing new functionality between major revisions (to avoid mid-version
  changes in the PYTHON_API_VERSION).

See more detail on python document on tp_flags.

But interesting thing is that class.flags & _HEAPTYPE is always 0 when the class is a python internal type. And the result will be 1 when class is a subclass of python internal type.

Subclass of python built-in type, like other user defined type, allocated on heap with PyType_GenericAlloc().

to break down type.__flags__:

import re

def flags_to_name(type_obj):
    tp_flag_consts = {}
    with open('/path/to/Include/object.h') as f:
        for l in f:
            m = re.search(r'^#define (Py_TPFLAGS_\w+)\s+\(.+?<< (\d+)\)', l.strip())
            if m:
                tp_flag_consts[int(m.group(2))] = m.group(1)
    bin_str = bin(type_obj.__flags__)[2:][::-1]
    return ', '.join(tp_flag_consts[n] for n, c in enumerate(bin_str) if c == '1')

print(flags_to_name(type))

yields:

Py_TPFLAGS_BASETYPE, Py_TPFLAGS_READY, Py_TPFLAGS_HAVE_GC, Py_TPFLAGS_HAVE_VERSION_TAG, Py_TPFLAGS_VALID_VERSION_TAG, Py_TPFLAGS_TYPE_SUBCLASS


问:
Pycharm default interpreter and tmp working directory on Ubuntu
I use Pycharm for a while now and I'm getting really annoyed that my Pycharm interpreter settings always resets for some reason.

Meaning that whenever I open up a new/old project it will always tell me that:

No Python interpreter configured...

even after I change and apply the settings in

File > Settings > Project: ProjectName > Project Interpreter
or

File > Default Settings > Project Interpreter.

(These changes only apply for as long as Pycharm is open. Once it's closed I need to repeat the whole procedure, which is my problem here.)

Then I noticed that all my projects that I open for some reason end up being opened in the tmp folder.
(e.g. "/tmp/Projectname.py")

Which is also the reason why I cant open recent projects via the menu.

So my question is, how do I actually make Pycharm save my interpreter settings and stop asking me about it.

I know that there seems to be similar questions about it, but either they are not solved or the solution doesn't work. And I hope that this tmp folder thing might be of use to solve this problem.

答:
how do I actually make Pycharm save my interpreter settings and stop asking me about it.

I was having a similar issue when I used PyCharm Community 2017.3 on Ubuntu 16.04 for the first time. The solution was to open the project folder rather than a specific script.


问:
torch.nn has no attribute named upsample
Following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-perform-neural-style-transfer-with-python-3-and-pytorch#step-2-%E2%80%94-running-your-first-style-transfer-experiment

When I run the example in Jupyter notebook, I get the following:

So, I've tried troubleshooting, which eventually got me to running it as per the github example (https://github.com/zhanghang1989/PyTorch-Multi-Style-Transfer) says to via command line:

```<code>python main.py eval --content-image images/content/venice-boat.jpg --style-image images/21styles/candy.jpg --model models/21styles.model --content-size 1024 --cuda=0
</code>```

However, this gives the following error:

```<code>Traceback (most recent call last):
File "main.py", line 287, in <module>
main()
File "main.py", line 44, in main
evaluate(args)
File "main.py", line 242, in evaluate
stylemodel = Net(ngf=args.ngf)
File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 284, in init
model += [upblock(ngf*expansion, 32, 2, normlayer),
File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 127, in init
kernelsize=1, stride=1, upsample=stride)
File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 167, in init
self.upsamplelayer = torch.nn.Upsample(scalefactor=upsample)
AttributeError: module 'torch.nn' has no attribute 'Upsample'
</code>```

I can't figure out how to get past this?

答:
I think the reason maybe that you have an older version of PyTorch on your system. On my system, the pytorch version is 0.2.0, torch.nn has a module called Upsample.

You can uninstall your current version of pytorch and reinstall it.

Body:
Following this tutorial: https://www.digitalocean.com/community/tutorials/how-to-perform-neural-style-transfer-with-python-3-and-pytorch#step-2-%E2%80%94-running-your-first-style-transfer-experiment

When I run the example in Jupyter notebook, I get the following:

So, I've tried troubleshooting, which eventually got me to running it as per the github example (https://github.com/zhanghang1989/PyTorch-Multi-Style-Transfer) says to via command line:

python main.py eval --content-image images/content/venice-boat.jpg --style-image images/21styles/candy.jpg --model models/21styles.model --content-size 1024 --cuda=0

However, this gives the following error:

Traceback (most recent call last):
File "main.py", line 287, in <module>
main()
File "main.py", line 44, in main
evaluate(args)
File "main.py", line 242, in evaluate
stylemodel = Net(ngf=args.ngf)
File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 284, in init
model += [upblock(ngf*expansion, 32, 2, normlayer),
File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 127, in init
kernelsize=1, stride=1, upsample=stride)
File "/root/styletransfer/PyTorch-Style-Transfer/experiments/net.py", line 167, in init
self.upsamplelayer = torch.nn.Upsample(scalefactor=upsample)
AttributeError: module 'torch.nn' has no attribute 'Upsample'

I can't figure out how to get past this?


问:
Paramiko connection issue
I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...

```<code>#connect.py

import user, db
import paramiko, time, os

paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
    def __init__(self):
        #Call DB Functions
        database = db.Database()
        #Set Transport
        self.transport = paramiko.Transport((user.hostname, user.port))

        #User Credentials
        username = user.username
        password = user.password
        self.transport.connect(username = username, password = password)

        self.sftp = paramiko.SFTPClient.from_transport(self.transport)

        print "Set your credentials in user.py for now!"
        msg = "Connecting as: %s, on port number %d" % (user.username, user.port)
        print msg

    def disconnect(self):
        print "Closing connection..."
        self.sftp.close()
        self.transport.close()
        print "Connection closed."
</code>```

Pretty straightforward. Connect and disconnect.
This connect.py file is being imported into a main.py (which is my gui)

```<code>#main.py

import connect
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        windowWidth = 550
        windowHeight = 350

        self.establishedConnection = ""

        connectButton = self.createButton("&Connect", self.conn)
        disconnectButton = self.createButton("&Disconnect", self.disconnect)
        grid = QtGui.QGridLayout()
        grid.addWidget(connectButton, 3, 3)
        grid.addWidget(disconnectButton, 4, 3)
        grid.addWidget(self.createList(), 1, 0, 1, 4)

        self.setLayout(grid)

        self.resize(windowWidth, windowHeight)
        self.setWindowTitle("FTP Program")

    def conn(self):
        connection = connect.Connection()
        self.establishedConnection = connection

    def disconnect(self):
        self.establishedConnection.disconnect()

    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    gui = Window()
    gui.show()
    sys.exit(app.exec_())
</code>```

The issue is disconnecting.
I was thinking __init__ would create an instance of the Connection() class. If you look on main.py you can see that I tried to create the variable self.connectionEstablished in order to save the object so I could call disconnect on it later.

Where am I going wrong? I'm fairly new to python and other non-web languages(I spend most of my time writing RoR and php apps).

No errors are shown at any time and I started this app out as a terminal app so I do know that connect.py does work as intended.

Edit: So I guess Senderle got a connection closed message, which is what I'd like to see as well but I'm not. I'll mark a best answer if I see something that solves my problem.

Edit Solved: Pushed connect.py and main.py into one file to simplify things. And for some reason that solved things. So who knows whats going on. I'm still going to hold off on 'best answer'. If someone can tell me why I can't have a split file like that then I'm all ears.

答:
I tried the code and it ran fine. I made only a few changes.

First, I didn't know what "user" and "db" are, so I commented out

```<code>import user, db
</code>```

and

```<code>database = db.Database()
</code>```

and used my own data for username, password, etc.

Second, the PySide module isn't available via my package manager, so I used PyQt4 instead. It didn't like grid.addWidget(self.createList(), 1, 0, 1, 4) so I commented that out, and everything worked as expected.

Further thoughts: When there were connection errors, there was some console feedback consisting of stack traces, but nothing more, and self.establishedConnection remained a string, causing self.establishedConnection.disconnect() to fail. So perhaps there's a connection problem?

EDIT: Aaaahhhhh, I just saw this: "No errors are shown at any time." Are you running this from a terminal or double-clicking an executable? If you start it from a terminal, I bet you'll see stacktraces in the terminal. The gui doesn't close when the code hits an exception.

EDIT2: If joining the files fixes the problem, then I am certain the problem cannot have anything to do with python itself. This has to be a problem with eclipse. You say that connection.py began as a terminal app, so you must be able to run python apps from the command line. Try the following: put main.py, connect.py, etc. in a directory of their own, open a terminal, and run python main.py. If it works as expected, then the problem has something to do with eclipse.

Title: Paramiko connection issue

Body:
I'm writing my first desktop app and I'm struggling with class instances. This app is a simple ftp program using paramiko. What I've set up so far is a connection.py which looks like this...

#connect.py

import user, db
import paramiko, time, os

paramiko.util.log_to_file('paramiko-log.txt')
class Connection:
    def __init__(self):
        #Call DB Functions
        database = db.Database()
        #Set Transport
        self.transport = paramiko.Transport((user.hostname, user.port))

        #User Credentials
        username = user.username
        password = user.password
        self.transport.connect(username = username, password = password)

        self.sftp = paramiko.SFTPClient.from_transport(self.transport)

        print "Set your credentials in user.py for now!"
        msg = "Connecting as: %s, on port number %d" % (user.username, user.port)
        print msg

    def disconnect(self):
        print "Closing connection..."
        self.sftp.close()
        self.transport.close()
        print "Connection closed."

Pretty straightforward. Connect and disconnect.
This connect.py file is being imported into a main.py (which is my gui)

#main.py

import connect
from PySide import QtCore, QtGui

class Window(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Window, self).__init__(parent)
        windowWidth = 550
        windowHeight = 350

        self.establishedConnection = ""

        connectButton = self.createButton("&Connect", self.conn)
        disconnectButton = self.createButton("&Disconnect", self.disconnect)
        grid = QtGui.QGridLayout()
        grid.addWidget(connectButton, 3, 3)
        grid.addWidget(disconnectButton, 4, 3)
        grid.addWidget(self.createList(), 1, 0, 1, 4)

        self.setLayout(grid)

        self.resize(windowWidth, windowHeight)
        self.setWindowTitle("FTP Program")

    def conn(self):
        connection = connect.Connection()
        self.establishedConnection = connection

    def disconnect(self):
        self.establishedConnection.disconnect()

    def createButton(self, text, member):
        button = QtGui.QPushButton(text)
        button.clicked.connect(member)
        return button

if __name__ == '__main__':

    import sys

    app = QtGui.QApplication(sys.argv)
    gui = Window()
    gui.show()
    sys.exit(app.exec_())

The issue is disconnecting.
I was thinking __init__ would create an instance of the Connection() class. If you look on main.py you can see that I tried to create the variable self.connectionEstablished in order to save the object so I could call disconnect on it later.

Where am I going wrong? I'm fairly new to python and other non-web languages(I spend most of my time writing RoR and php apps).

No errors are shown at any time and I started this app out as a terminal app so I do know that connect.py does work as intended.

Edit: So I guess Senderle got a connection closed message, which is what I'd like to see as well but I'm not. I'll mark a best answer if I see something that solves my problem.

Edit Solved: Pushed connect.py and main.py into one file to simplify things. And for some reason that solved things. So who knows whats going on. I'm still going to hold off on 'best answer'. If someone can tell me why I can't have a split file like that then I'm all ears.

Body:
I tried the code and it ran fine. I made only a few changes.

First, I didn't know what "user" and "db" are, so I commented out

import user, db

and

database = db.Database()

and used my own data for username, password, etc.

Second, the PySide module isn't available via my package manager, so I used PyQt4 instead. It didn't like grid.addWidget(self.createList(), 1, 0, 1, 4) so I commented that out, and everything worked as expected.

Further thoughts: When there were connection errors, there was some console feedback consisting of stack traces, but nothing more, and self.establishedConnection remained a string, causing self.establishedConnection.disconnect() to fail. So perhaps there's a connection problem?

EDIT: Aaaahhhhh, I just saw this: "No errors are shown at any time." Are you running this from a terminal or double-clicking an executable? If you start it from a terminal, I bet you'll see stacktraces in the terminal. The gui doesn't close when the code hits an exception.

EDIT2: If joining the files fixes the problem, then I am certain the problem cannot have anything to do with python itself. This has to be a problem with eclipse. You say that connection.py began as a terminal app, so you must be able to run python apps from the command line. Try the following: put main.py, connect.py, etc. in a directory of their own, open a terminal, and run python main.py. If it works as expected, then the problem has something to do with eclipse.


问:
Dynamically provision global parent pom.xml
How can one manage a common project parent pom.xml for multiple github organizations and projects, without continuously releasing it to some maven repository?

答:
Now there are two maven components for that:

extension: arkon-maven-extension

plugin: flatten-maven-plugin

which can help resolve this issue.

Basic approach is to:

have single arkon repository with parent pom.xml, which is forever snapshot, and never released anywhere

use arkon-maven-extension to auto magically provision this parent pom into all projects which depend on it

use flatten-maven-plugin to erase parent information from the final project pom.xml used for deployment


问:
Generated Spring Boot project - maven dependencies without versions
I am new in the Spring and Maven so I start from Spring's starter page. When I run project, project works fine, problem is pom.xml file of that project contains dependencies without version attributes. Can you explain me what that mean? Is it ok or should I define custom versions to use?

Here is pom file:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.customApp</groupId>
    <artifactId>myApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>myApp</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>
</code>```

答:
In java world we use maven also for dependency management. Every single library’s version including different things and maven can not know which version works for you that’s why of course you should specify which version you want to use. </p>

<p>In this case your parent dependency has version that’s why maven knows which version ok for child dependencies. </p>

Body:
I am new in the Spring and Maven so I start from Spring's starter page. When I run project, project works fine, problem is pom.xml file of that project contains dependencies without version attributes. Can you explain me what that mean? Is it ok or should I define custom versions to use?

Here is pom file:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.customApp</groupId>
    <artifactId>myApp</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>myApp</name>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.BUILD-SNAPSHOT</version>
        <relativePath/>
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>

        <dependency>
            <groupId>org.hsqldb</groupId>
            <artifactId>hsqldb</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <repositories>
        <repository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </repository>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

    <pluginRepositories>
        <pluginRepository>
            <id>spring-snapshots</id>
            <name>Spring Snapshots</name>
            <url>https://repo.spring.io/snapshot</url>
            <snapshots>
                <enabled>true</enabled>
            </snapshots>
        </pluginRepository>
        <pluginRepository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </pluginRepository>
    </pluginRepositories>

</project>

Body:
In java world we use maven also for dependency management. Every single library’s version including different things and maven can not know which version works for you that’s why of course you should specify which version you want to use.

In this case your parent dependency has version that’s why maven knows which version ok for child dependencies.


问:
pygame.Surface object is not callable
```<code>for event in pygame.event.get():
    if event.type == pygame.QUIT:
        state = 2
        mouseX, mouseY = pygame.mouse.get_pos()
        leave(mouseX, mouseY)
</code>```

When I press the "x" in the top left gives me an error that reads:

```<code>leave(mouseX, mouseY)

TypeError: 'pygame.Surface' object is not callable
</code>```

答: I can't say for sure without seeing a little bit more of the code but my best guess is that you have named a surface object leave and it is conflicting with the function that you have also named leave. Try changing the name of one of them to something else.

Title: pygame.Surface object is not callable

Body:
for event in pygame.event.get():
    if event.type == pygame.QUIT:
        state = 2
        mouseX, mouseY = pygame.mouse.get_pos()
        leave(mouseX, mouseY)

When I press the "x" in the top left gives me an error that reads:

leave(mouseX, mouseY)

TypeError: 'pygame.Surface' object is not callable


问:
regex / javascript : Filter & replace groups with same values from array
I have an array like this:

```<code>var array=[
           '100000011022',
           '122339311022',
           '988881233221',
           '000130009999',
          ]
</code>```

... and I'd like to find groups with the same column (LENGTH : minimum 2, maximum 10) and replace every group element with another value (e.g. 0).

e.g ---> 988881233221 => 900001200001 (found '8888', '33', '22')

SO the result should look like this:

```<code>var result=[
           '100000000000',
           '100009300000',
           '900001200001',
           '000130000000',
           ]
</code>```

Because I have no clue how to use regex this is all that I got so far, I'm sorry!

var array=[
 '100000011022',
 '122339311022',
 '988881233221',
 '000130009999'
]

var result = array.join('\n').replace(/.{4,10}[^.]/g, function(a) {
  return a.replace(/./g,'0')
})
console.log(result)```

Body:
I have an array like this:

var array=[
           '100000011022',
           '122339311022',
           '988881233221',
           '000130009999',
          ]

... and I'd like to find groups with the same column (LENGTH : minimum 2, maximum 10) and replace every group element with another value (e.g. 0).

e.g ---> 988881233221 => 900001200001 (found '8888', '33', '22')

SO the result should look like this:

var result=[
           '100000000000',
           '100009300000',
           '900001200001',
           '000130000000',
           ]

Because I have no clue how to use regex this is all that I got so far, I'm sorry!

var array=[
 '100000011022',
 '122339311022',
 '988881233221',
 '000130009999'
]

var result = array.join('\n').replace(/.{4,10}[^.]/g, function(a) {
  return a.replace(/./g,'0')
})
console.log(result)

Body:
Use \1 to reference any matched symbol.

var array=[
 '100000011022',
 '122339311022',
 '988881233221',
 '000130009999'
]

var result = array.join('\n').replace(/(.)\1{1,9}/g, function(a) {
   return a.replace(/./g,'0')
})
console.log(result)


问:
Arrange 3 images in a row in React Native
I have just started working on a React Native project and I got stuck. I need to display a listof images from an API. The API only gives image urls that I can use like this:

```<code><Image
      style={{width: 50, height: 50}}
      source={{uri: 'https://avatars0.githubusercontent.com/u/13102253?s=460&v=4'}}
/>
</code>```

The image count is dynamic but I want to display only 3 images per row. How can I achieve this?

答:
You can use ListView in which you can style it by wrapping it into row like this
and page size will take care of arranging into row

```<code><ListView
   contentContainerStyle={styles.list}
   dataSource={this.props.yourData} //datasource either props/state only
   pageSize={3}
   renderRow={(data, rowID, sectionID) => (
<Image
  style={{width: 50, height: 50}}
  source={{uri: data.path}}/>)} //path here is url that you receive

const styles = StyleSheet.create({
list: {
flexDirection: "row",
flexWrap: "wrap"
}})
</code>```

Body:
I have just started working on a React Native project and I got stuck. I need to display a listof images from an API. The API only gives image urls that I can use like this:

<Image
      style={{width: 50, height: 50}}
      source={{uri: 'https://avatars0.githubusercontent.com/u/13102253?s=460&v=4'}}
/>

The image count is dynamic but I want to display only 3 images per row. How can I achieve this?

Body:
You can use ListView in which you can style it by wrapping it into row like this
and page size will take care of arranging into row

<ListView
   contentContainerStyle={styles.list}
   dataSource={this.props.yourData} //datasource either props/state only
   pageSize={3}
   renderRow={(data, rowID, sectionID) => (
<Image
  style={{width: 50, height: 50}}
  source={{uri: data.path}}/>)} //path here is url that you receive

const styles = StyleSheet.create({
list: {
flexDirection: "row",
flexWrap: "wrap"
}})


答:
Code

See regex in use here

```<code>(\d)\1
</code>```

Replacement: 00

Usage

const regex = /(\d)\1/g;
var array=[
  '100000011022',
  '122339311022',
  '988881233221',
  '000130009999'
]
const subst = `00`;

// The substituted value will be contained in the result variable
array.forEach(function(s, i) {
  array[i] = s.replace(regex, subst);
});

console.log(array);```

Explanation

(\d) Capture a single digit into capture group 1

\1 Match the same text as most recently matched by capture group 1

Title: regex / javascript : Filter & replace groups with same values from array

Body:
Code

See regex in use here

(\d)\1

Replacement: 00

Usage

const regex = /(\d)\1/g;
var array=[
  '100000011022',
  '122339311022',
  '988881233221',
  '000130009999'
]
const subst = `00`;

// The substituted value will be contained in the result variable
array.forEach(function(s, i) {
  array[i] = s.replace(regex, subst);
});

console.log(array);

Explanation

(\d) Capture a single digit into capture group 1

\1 Match the same text as most recently matched by capture group 1


问:
Cygwin Perl Module " use Spreadsheet::Read qw(ReadData);" stopped working
I've recently upgraded my Machine , thus installed Cygwin on new Latop
GNU bash, version 4.4.12(3)-release (x86_64-unknown-cygwin) , old release was "GNU bash, version 4.3.42(4)-release (x86_64-unknown-cygwin) "

Also Perl got updated from version v5.22.1 to v5.26.1 . Most of my script works but Excel based scripts stopped working.   Here is a basic example which is not working ..

```<code>use Spreadsheet::Read qw(ReadData);
my $book = ReadData ('simple.xlsx');
print 'A1: ' . $book->[1]{A1};
</code>```

I'm getting an error Parser for XLSX is not installed at test.pl  line 2 .

What am I'm missing ?

Thanks in advance

答: You need to install either Spreadsheet::ParseExcel or Spreadsheet::XLSX.

Body:
I've recently upgraded my Machine , thus installed Cygwin on new Latop
GNU bash, version 4.4.12(3)-release (x86_64-unknown-cygwin) , old release was "GNU bash, version 4.3.42(4)-release (x86_64-unknown-cygwin) "

Also Perl got updated from version v5.22.1 to v5.26.1 . Most of my script works but Excel based scripts stopped working.   Here is a basic example which is not working ..

use Spreadsheet::Read qw(ReadData);
my $book = ReadData ('simple.xlsx');
print 'A1: ' . $book->[1]{A1};

I'm getting an error Parser for XLSX is not installed at test.pl  line 2 .

What am I'm missing ?

Thanks in advance


问:
Run a R Model using SparkR
Thanks in advance for your input. I am a newbie to ML.
I've developed a R model (using R studio on my local) and want to deploy on the hadoop cluster having R Studio installed. I want to use SparkR to leverage high performance computing. I just want to understand the role of SparkR here.

Will SparkR enable the R model to run the algorithm within Spark ML on the Hadoop Cluster?

OR

Will SparkR enable only the data processing and still the ML algorithm will run within the context of R on the Hadoop Cluster?

Appreciate your input.

答:
These are general questions, but they actually have a very simple & straightforward answer: no (to both); SparkR wiil do neither.

From the Overview section of the SparkR docs:

SparkR is an R package that provides a light-weight frontend to use Apache Spark from R.

SparkR cannot even read native R models.

The idea behind using SparkR for ML tasks is that you develop your model specifically in SparkR (and if you try, you'll also discover that it is much more limited in comparison to the plethora of models available in R through the various packages).

Even conveniences like, say, confusionMatrix from the caret package, are not available, since they operate on R dataframes and not on Spark ones (see this question & answer).

Title: Run a R Model using SparkR


问:
How can i get the solr documents with only one value in multi valued field?
I need to get the documents from solr index, where the documents has only one value in multivauled field.

Say,following data in index.

```<code>            <doc>
            <label>
            <id ="1">1</id>
            <id ="2">2</id>
            <label>
            </doc>
            <doc>
            <label>
            <id ="3">3</id>
            <label>
            </doc>

            <doc>
            <label>
            <id ="4">4</id>
            <id ="5">5</id>
            <label>
            </doc>
            <doc>
            <label>
            <id ="6">6</id>
            <label>
            </doc>
</code>```

I need the following result,

```<code>            <doc>
            <label>
            <id ="3">3</id>
            <label>
            </doc>

            <doc>
            <label>
            <id ="6">6</id>
            <label>
            </doc>
</code>```

答:
You can add Stateless Script Update Processor in your updateRequestProcessorChain which adds a new field to the document when that document has 1 value in the multi-valued field.
Or you can use  CountFieldValuesUpdateProcessorFactory < http://lucene.apache.org/solr/4_0_0/solr-core/org/apache/solr/update/processor/CountFieldValuesUpdateProcessorFactory.html > for counting
search on basis of that field.</p>

Body:
I need to get the documents from solr index, where the documents has only one value in multivauled field.

Say,following data in index.

            <doc>

            <id ="1">1</id>
            <id ="2">2</id>

            </doc>
            <doc>

            <id ="3">3</id>

            </doc>

            <doc>

            <id ="4">4</id>
            <id ="5">5</id>

            </doc>
            <doc>

            <id ="6">6</id>

            </doc>

I need the following result,

            <doc>

            <id ="3">3</id>

            </doc>

            <doc>

            <id ="6">6</id>

            </doc>


问:
icon missing on tool bar in visual studio 2015 (VS 2015)
I have just install vs 2015, but when I open it I am not getting the icon/image on the toolbar. I have tried to reset the toolbar but that did not do the trick. I also tried to do a repair but it did not solve this problem.

I am wondering if someone experience something similar ?

For the moment, I added the text on to the button so at least I can use it, but it is far from been ideal.
I am on a corporate enviroment (no admin priviliges), one of my colleague tried and it work without problem for him.

答:
Delete the folder

%LocalAppData%\Microsoft\VisualStudio\14.0\ImageLibrary

and let VS re-generate the image cache.


问:
Get mail intent from whatsapp
I am trying to receive the sending whatsapp intent when sharing the conversation via email.I can't make my application appear in the possible applications to share.I need information on how to properly configure my androidmanifest and receive the attachment * .txt.Thanks and I hope I have expressed myself well.</p>

答:
Your application doesn't appear in the chooser because Whatsapp has whitelisted only some packages for the email applications.

For more information, see this answer

Title: Get mail intent from whatsapp


问:
Objects visibility determined by order of rendering but not by their position with respect to view point
Im using OpenGL ES to draw a cube with each side in a different color.

Each side is made up of two triangles,
I draw each side by first setting color using GLES20.glUniform4fv , and then drawing triangles using GLES20.glDrawElements .

The problem is that all the sides (triangles) are visible on the screen irrespective of if one side is behind the other.

The rendering is happening in the order I draw the sides, meaning the latest will overlap the old, but not based on the position of the side and vertices from the view point.

Please help if something has to be set prior so that objects visibility is determined by position of object and view point.

答: There are various approaches to your problem like using depth buffer or tree-based algorithms. OpenGL ES has an in-built implementation of depth buffering. You can enable it by using GLES20.glEnable( GLES20.GL_DEPTH_TEST ). Don't forget to clear or invalidate (GLES 3.x) the depth buffer before drawing. Note however that there are difficulties when using it with partially transparent surfaces. The impact on performance depends on depth precision, depth buffer size and scene complexity.


问:
Best serialization library for .net with ability to deserialize inheritance correctly
I need a serialization library for .net with better features than the default xml serializer.
The problem is that it  is not polymorphic - say you have class B : A { }, and have serialized an type B, you should be able to call A myBaseType = Deserialize(xml) on it and be returned an instance of type B in the myBaseType variable.

I have an implementation at http://refactormycode.com/codes/710-polymorphic-xml-serializer with unit tests that the serialization library should be able to deal with. This implementation will not work if an object to be serialized has a child type which is also a polymorphic serialized type, so I need something better.

thanks!

答:
If you can handle the additional verbosity going to a serializer which embeds the type information into the resulting stream is probably for the best.

.Net provides the SoapFormatter which is overly verbose and does things that you probably won't need but when you deserialize the stream it will simply give you back the appropriate objects (no need to specify a type just cast the root object to the type you know it to be).

As a fringe benefit it will correctly handle cycles and shared references within the object graph.


问:
Watir, looking for a more elegant solution for HTML element checking
I'm looking for a more elegant solution to check that a range of HTML elements are visible in the browser.

I had the idea of creating a CSV file with element type and IDs, reading it into an array and using that to check the elements are present in the browser.

So the CSV file/array would look something like this,

```<code>"select","srch-op-select"
"text_field","srch-filter"
"button","srch-button"
"image","srch-showhide-icon"
"div","srch-showhide"
</code>```

I then thought I could use case statement to do the checking, something like this,

```<code>        myElements.each do |row|
        type = row[0]
        id = row[1]
        case type
          when "button"   : assert(browser.button(:id,id).exists?)
          when "checkbox" : assert(browser.checkbox(:id,id).exists?)
          when "div"      : assert(browser.div(:id,id).exists?)
          when "image"    : assert(browser.image(:id,id).exists?)
          when "label"    : assert(browser.label(:id,id).exists?)
          when "link"     : assert(browser.link(:id,id).exists?)
          when "radio"    : assert(browser.radio(:id,id).exists?)
          when "select"   : assert(browser.select_list(:id,id).exists?)
          when "span"     : assert(browser.span(:id,id).exists?)
          when "table"    : assert(browser.table(:id,id).exists?)
          else $log.debug "---Unsupported element type "+type
        end
    end
</code>```

Obviously this case statement would be come large and unwieldy if you wanted to cover all supported element types or factor in the different methods of selecting a HTML element.

Can anyone suggest a more elegant and flexible solution?

答:
Replace your case statement with this:</p>

```<code>assert(browser.send(type.to_sym, :id, id).exists?)
</code>```

Body:
I'm looking for a more elegant solution to check that a range of HTML elements are visible in the browser.

I had the idea of creating a CSV file with element type and IDs, reading it into an array and using that to check the elements are present in the browser.

So the CSV file/array would look something like this,

"select","srch-op-select"
"text_field","srch-filter"
"button","srch-button"
"image","srch-showhide-icon"
"div","srch-showhide"

I then thought I could use case statement to do the checking, something like this,

        myElements.each do |row|
        type = row[0]
        id = row[1]
        case type
          when "button"   : assert(browser.button(:id,id).exists?)
          when "checkbox" : assert(browser.checkbox(:id,id).exists?)
          when "div"      : assert(browser.div(:id,id).exists?)
          when "image"    : assert(browser.image(:id,id).exists?)
          when "label"    : assert(browser.label(:id,id).exists?)
          when "link"     : assert(browser.link(:id,id).exists?)
          when "radio"    : assert(browser.radio(:id,id).exists?)
          when "select"   : assert(browser.select_list(:id,id).exists?)
          when "span"     : assert(browser.span(:id,id).exists?)
          when "table"    : assert(browser.table(:id,id).exists?)
          else $log.debug "---Unsupported element type "+type
        end
    end

Obviously this case statement would be come large and unwieldy if you wanted to cover all supported element types or factor in the different methods of selecting a HTML element.

Can anyone suggest a more elegant and flexible solution?

Body:
Replace your case statement with this:

assert(browser.send(type.to_sym, :id, id).exists?)


问:
how to set cursor background transparent for EditText Android
I'm having this issue when I touch an EditText for changing text on Android:

A white frame appears around the red cursor, and I need it to be transparent for showing properly the line of the EditText. How do I change this?

code:

```<code><EditText
            android:id="@+id/login_user_name_text"
            android:textCursorDrawable="@null"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="16sp"
            android:inputType="textEmailAddress"
            android:imeOptions="actionNext"
            android:maxLines="1"
            android:hint="@string/email"
            android:maxLength="60"
            />
</code>```

EDIT: I could fix it by replacing:

```<code><item name="android:background">@color/white</item>
</code>```

for

```<code><item name="android:background">@color/transparent</item>
</code>```

in styles.xml

```<code> <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
        <item name="android:windowDisablePreview">true</item>
        <item name="android:background">@color/transparent</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
    </style>
</code>```

答:
Setting android:background to transparent didn't do the trick for me.

In my case I set a theme to the parent viewgroup that defined the background to be a certain color, so it was applied to the EditText as well. Making sure that the background was just set for the parent solved it.

Body:
I'm having this issue when I touch an EditText for changing text on Android:

A white frame appears around the red cursor, and I need it to be transparent for showing properly the line of the EditText. How do I change this?

code:

<EditText
            android:id="@+id/login_user_name_text"
            android:textCursorDrawable="@null"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/black"
            android:textSize="16sp"
            android:inputType="textEmailAddress"
            android:imeOptions="actionNext"
            android:maxLines="1"
            android:hint="@string/email"
            android:maxLength="60"
            />

EDIT: I could fix it by replacing:

<item name="android:background">@color/white</item>

for

<item name="android:background">@color/transparent</item>

in styles.xml


问:
How to insert chid to tag with VBScript?
I'm trying to create a XML file with the following code.

Set Client = xmlDoc.CreateElement("Client")
Set Client_ID = xmlDoc.CreateElement("Client_ID")
Client_ID.AppendChild kunden
Set name = xmlDoc.CreateElement("GivenName")
Client_ID.SelectNodes("//@Client//Client_ID")
Set surnamename = xmlDoc.CreateElement("surname")
Client_ID.AppendChild name
Client_ID.AppendChild surname
```

<p>That is what I'm getting:</p>

<pre class="lang-xml prettyprint-override"><code><ROOT>
  <Info>
    <Number>atl-ws-001</Number>
    <Date>04.12.2017</Date>
  </Info>
  <Test>
    <Client>
      <Client_ID/>
      <GiveName/>
      <SURNAME/>
    </Client>
  </Test>
</ROOT>
</code>```

and that what I'm trying to get the XML file like this one:

<ROOT>
  <Info>
    <Number>atl-ws-001</Number>
    <Date>04.12.2017</Date>
  </Info>
  <Test>
    <Client>
      <Client_ID>
        <GivenName/>
        <surname/>
      </Client_ID>
    </Client>
  </Test>
</ROOT>
```

答:
Just use the methods by the book. Demo:

```<code>Option Explicit

Dim o : Set o = CreateObject("msxml2.domdocument")
o.loadXml "<a><b></b></a>"
Dim Client : Set Client = o.createElement("Client")
Dim Client_ID : Set Client_ID = o.createElement("Client_ID")
Client_ID.appendChild o.createElement("GivenName")
Client_ID.appendChild o.createElement("SurName")
Client.appendChild Client_ID
o.SelectSingleNode("/a/b").appendChild Client
WScript.Echo o.xml
</code>```

output:

```<code>cscript 47637542.vbs
<a><b><Client><Client_ID><GivenName/><SurName/></Client_ID></Client></b></a>
</code>```

(Using XPATH "//" is nearly always a bad idea)

Body:
I'm trying to create a XML file with the following code.

Set Client = xmlDoc.CreateElement("Client")
Set Client_ID = xmlDoc.CreateElement("Client_ID")
Client_ID.AppendChild kunden
Set name = xmlDoc.CreateElement("GivenName")
Client_ID.SelectNodes("//@Client//Client_ID")
Set surnamename = xmlDoc.CreateElement("surname")
Client_ID.AppendChild name
Client_ID.AppendChild surname

That is what I'm getting:

<ROOT>
  <Info>
    <Number>atl-ws-001</Number>
    <Date>04.12.2017</Date>
  </Info>
  <Test>
    <Client>
      <Client_ID/>
      <GiveName/>
      <SURNAME/>
    </Client>
  </Test>
</ROOT>

and that what I'm trying to get the XML file like this one:

<ROOT>
  <Info>
    <Number>atl-ws-001</Number>
    <Date>04.12.2017</Date>
  </Info>
  <Test>
    <Client>
      <Client_ID>
        <GivenName/>
        <surname/>
      </Client_ID>
    </Client>
  </Test>
</ROOT>

Body:
Just use the methods by the book. Demo:

Option Explicit

Dim o : Set o = CreateObject("msxml2.domdocument")
o.loadXml "<a><b></b></a>"
Dim Client : Set Client = o.createElement("Client")
Dim Client_ID : Set Client_ID = o.createElement("Client_ID")
Client_ID.appendChild o.createElement("GivenName")
Client_ID.appendChild o.createElement("SurName")
Client.appendChild Client_ID
o.SelectSingleNode("/a/b").appendChild Client
WScript.Echo o.xml

output:

cscript 47637542.vbs
<a><b><Client><Client_ID><GivenName/><SurName/></Client_ID></Client></b></a>

(Using XPATH "//" is nearly always a bad idea)


问:
Remote validation for multiple fields with jQuery validation
I'm using the jQuery validation plugin to check if the user excists in my SQL database. I want to check the credentials in checkCredentials.php. My script does check if an email or password is filled in but it does not check if the credentials do exist in my database. Anybody who can tell me what I'm doing wrong? Thanks in advance.

This is my form:

```<code>            <form action="php/login.php" method="post" id="loginForm" class="form-horizontal">
                <div class="form-group">
                    <input type="email" class="form-control form-control-lg" id="email" name="email" placeholder="Email" />
                </div>
                <div class="form-group">
                    <input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Wachtwoord" />
                </div>
                <button class="btn btn-block" type="submit" name="login" value="Login">Login</button>
            </form>
</code>```

And this is my script:

```<code>    $( "#loginForm" ).validate( {
    rules: {
        email: {
            required: true,
            email: true
        },
        password: {
            required: true,
            remote: {
                url: "php/checkCredentials.php",
                type: "post",
                data: {
                    email: function () {
                        return $("#email").val();
                    }
                }
            }
        },
    },
    messages: {
        email: {
            required: "Vul alsjeblieft een e-mail adres in"
        },
        password: {
            required: "Vul alsjeblieft een wachtwoord in",
            remote: "E-mail of wachtwoord onjuist"
        },
    },
</code>```

And here is my PHP file checkCredentials.php

```<code><?php
require 'database-connection.php';

$email = mysqli_real_escape_string($_REQUEST['email']);
$password = mysqli_real_escape_string($_REQUEST['password']);

$query = "SELECT user_email, user_password FROM table_users WHERE user_email = '$email' AND user_password = '$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 0)
{
    echo 'true';
}
else
{
    echo 'false';
}
?>
</code>```

答:
I changed my code to this and it's working now:

Form:

```<code>    <form action="php/login.php" method="post" id="loginForm" class="form-horizontal">
                    <div class="form-group">
                        <input type="email" class="form-control form-control-lg" id="email" name="email" placeholder="Email" />
                    </div>
                    <div class="form-group">
                        <input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Wachtwoord" />
                    </div>
                    <button class="btn btn-block" type="submit" name="login" value="Login">Login</button>
                </form>
</code>```

Script:

```<code>    $( "#loginForm" ).validate( {
        rules: {
            email: {
                required: true,
                email: true
            },
            password: {
                required: true,
                remote: {
                    url: "php/checkCredentials.php",
                    type: "post",
                    data: {
                        email: function () {
                            return $("#email").val();
                        }
                    }
                }
            },
        },
        messages: {
            email: {
                required: "Vul alsjeblieft een e-mail adres in"
            },
            password: {
                required: "Vul alsjeblieft een wachtwoord in",
                remote: "E-mail of wachtwoord onjuist"
            },
        },
        errorElement: "em",
        errorPlacement: function ( error, element ) {
            error.addClass( "help-block" );

            element.parents( ".col-sm-5" ).addClass( "has-feedback" );

            if ( element.prop( "type" ) === "checkbox" ) {
                error.insertAfter( element.parent( "label" ) );
            } else {
                error.insertAfter( element );
            }

            if ( !element.next( "span" )[ 0 ] ) {
                $( "<span class='glyphicon glyphicon-remove form-control-feedback'></span>" ).insertAfter( element );
            }
        },
        success: function ( label, element ) {
            if ( !$( element ).next( "span" )[ 0 ] ) {
                $( "<span class='glyphicon glyphicon-ok form-control-feedback'></span>" ).insertAfter( $( element ) );
            }
        },
        highlight: function ( element, errorClass, validClass ) {
            $( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
            $( element ).next( "span" ).addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
        },
        unhighlight: function ( element, errorClass, validClass ) {
            $( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
            $( element ).next( "span" ).addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
        }
    } );

</script>
</code>```

checkCredentials.php:

```<code><?php
require 'database-connection.php';

$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);

$query = "SELECT user_email, user_password FROM table_users WHERE user_email = '$email' AND user_password = '$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) > 0)
{
    echo 'true';
}
else
{
    echo 'false';
}
?>
</code>```

Body:
I'm using the jQuery validation plugin to check if the user excists in my SQL database. I want to check the credentials in checkCredentials.php. My script does check if an email or password is filled in but it does not check if the credentials do exist in my database. Anybody who can tell me what I'm doing wrong? Thanks in advance.

This is my form:

            <form action="php/login.php" method="post" id="loginForm" class="form-horizontal">

                    <input type="email" class="form-control form-control-lg" id="email" name="email" placeholder="Email" />

                    <input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Wachtwoord" />

                <button class="btn btn-block" type="submit" name="login" value="Login">Login</button>
            </form>

And this is my script:

    $( "#loginForm" ).validate( {
    rules: {
        email: {
            required: true,
            email: true
        },
        password: {
            required: true,
            remote: {
                url: "php/checkCredentials.php",
                type: "post",
                data: {
                    email: function () {
                        return $("#email").val();
                    }
                }
            }
        },
    },
    messages: {
        email: {
            required: "Vul alsjeblieft een e-mail adres in"
        },
        password: {
            required: "Vul alsjeblieft een wachtwoord in",
            remote: "E-mail of wachtwoord onjuist"
        },
    },

And here is my PHP file checkCredentials.php

<?php
require 'database-connection.php';

$email = mysqli_real_escape_string($_REQUEST['email']);
$password = mysqli_real_escape_string($_REQUEST['password']);

$query = "SELECT user_email, user_password FROM table_users WHERE user_email = '$email' AND user_password = '$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) == 0)
{
    echo 'true';
}
else
{
    echo 'false';
}
?>

Body:
I changed my code to this and it's working now:

Form:

    <form action="php/login.php" method="post" id="loginForm" class="form-horizontal">
                    <div class="form-group">
                        <input type="email" class="form-control form-control-lg" id="email" name="email" placeholder="Email" />
                    </div>
                    <div class="form-group">
                        <input type="password" class="form-control form-control-lg" id="password" name="password" placeholder="Wachtwoord" />
                    </div>
                    <button class="btn btn-block" type="submit" name="login" value="Login">Login</button>
                </form>

Script:

    $( "#loginForm" ).validate( {
        rules: {
            email: {
                required: true,
                email: true
            },
            password: {
                required: true,
                remote: {
                    url: "php/checkCredentials.php",
                    type: "post",
                    data: {
                        email: function () {
                            return $("#email").val();
                        }
                    }
                }
            },
        },
        messages: {
            email: {
                required: "Vul alsjeblieft een e-mail adres in"
            },
            password: {
                required: "Vul alsjeblieft een wachtwoord in",
                remote: "E-mail of wachtwoord onjuist"
            },
        },
        errorElement: "em",
        errorPlacement: function ( error, element ) {
            error.addClass( "help-block" );

            element.parents( ".col-sm-5" ).addClass( "has-feedback" );

            if ( element.prop( "type" ) === "checkbox" ) {
                error.insertAfter( element.parent( "label" ) );
            } else {
                error.insertAfter( element );
            }

            if ( !element.next( "span" )[ 0 ] ) {
                $( "<span class='glyphicon glyphicon-remove form-control-feedback'></span>" ).insertAfter( element );
            }
        },
        success: function ( label, element ) {
            if ( !$( element ).next( "span" )[ 0 ] ) {
                $( "<span class='glyphicon glyphicon-ok form-control-feedback'></span>" ).insertAfter( $( element ) );
            }
        },
        highlight: function ( element, errorClass, validClass ) {
            $( element ).parents( ".col-sm-5" ).addClass( "has-error" ).removeClass( "has-success" );
            $( element ).next( "span" ).addClass( "glyphicon-remove" ).removeClass( "glyphicon-ok" );
        },
        unhighlight: function ( element, errorClass, validClass ) {
            $( element ).parents( ".col-sm-5" ).addClass( "has-success" ).removeClass( "has-error" );
            $( element ).next( "span" ).addClass( "glyphicon-ok" ).removeClass( "glyphicon-remove" );
        }
    } );

</script>

checkCredentials.php:

<?php
require 'database-connection.php';

$email = mysqli_real_escape_string($db, $_POST['email']);
$password = mysqli_real_escape_string($db, $_POST['password']);

$query = "SELECT user_email, user_password FROM table_users WHERE user_email = '$email' AND user_password = '$password'";
$result = mysqli_query($db, $query);
if (mysqli_num_rows($result) > 0)
{
    echo 'true';
}
else
{
    echo 'false';
}
?>


问:
Spark writing to postgresql
I want to transfer 2 million records from MongoDB to Postgres with Apache Spark (using the official drivers for both databases). After a few minutes the program stops and I find these errors in the postgres log:
2017-12-03T22:18:16+00:00 app[postgres.15348]: [AQUA] [7-1]  sql_error_code = 26000 ERROR:  prepared statement "S_4" does not exist
. Anyone who has experience with this?

答: Have a look at https://www.torodb.com, which provides a full MongoDB to PostgreSQL migration solution, fully automated. The product is Open Source.</p>

Title: Spark writing to postgresql


问:
401 Unauthrorized response while creating a Rest API instance?
I'm trying to send a POST request on http://xyz:8002/LATEST/rest-apis using Firefox's rest client. I have added two headers Content-Type: application/xml and Authorization:Basic which I selected using the dropdown UI. The body of the request is -

```<code><rest-api xmlns="http://marklogic.com/rest-api">
  <name>Status Dashboard</name>
  <database>r75-xyz-v11</database>
  <port>8020</port>
</rest-api>
</code>```

In response I'm getting a 401 Unauthoried.

```<code><html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <title>401 Unauthorized</title>
    <meta name="robots" content="noindex,nofollow"/>
  </head>
  <body>
    <h1>401 Unauthorized</h1>
  </body>
</html>
</code>```

I have Admin rights and I gave the same credential in the UI box that came after selecting authentication basic.

答:
Is port 8002 configured for BASIC or DIGEST (the default) authentication?

By the way, I don't think the name of the appserver can contain a space.

Body:
I'm trying to send a POST request on http://xyz:8002/LATEST/rest-apis using Firefox's rest client. I have added two headers Content-Type: application/xml and Authorization:Basic which I selected using the dropdown UI. The body of the request is -

<rest-api xmlns="http://marklogic.com/rest-api">
  <name>Status Dashboard</name>
  <database>r75-xyz-v11</database>
  <port>8020</port>
</rest-api>

In response I'm getting a 401 Unauthoried.

    <title>401 Unauthorized</title>
    <meta name="robots" content="noindex,nofollow"/>

401 Unauthorized

I have Admin rights and I gave the same credential in the UI box that came after selecting authentication basic.


问:
shared_ptr causing segfault
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid. </p>

```<code>#include <tr1/memory>
#include <iostream>
class Dataset ;
typedef int DataClass;
class Dataset_Impl{
    friend class Dataset ;
    DataClass *dc;
    Dataset_Impl(){dc = new DataClass[10];}
    public:
    void getSubset(Dataset_Impl* &dObj){
        dObj = new Dataset_Impl();  //Causing segfault when using shared_ptr
        /*copy subset of 'dc' to dObj->dc and return*/std::cout<<"Copied subset";
    }
};
class Dataset{
    Dataset_Impl *d;
    public:
        Dataset (){};
        inline void const getSubset(Dataset &dObj) const{d->getSubset(dObj.d);}
};
int main(){
    Dataset m1,subset1;std::shared_ptr<Dataset> subset2;
    m1.getSubset(subset1);
    m1.getSubset((*subset2)); //Causing segfault
}
</code>```

答:
you are not creating an object for the shared_ptr variable and trying to access a member variable of pointer. try </p>

```<code>std::shared_ptr<Dataset> subset2(new Dataset())
</code>```

Title: shared_ptr causing segfault

Body:
I am trying to use shared_ptr with my class but for some reason I get segfault. Maybe I am doing something stupid.

#include <tr1/memory>
#include <iostream>
class Dataset ;
typedef int DataClass;
class Dataset_Impl{
    friend class Dataset ;
    DataClass *dc;
    Dataset_Impl(){dc = new DataClass[10];}
    public:
    void getSubset(Dataset_Impl* &dObj){
        dObj = new Dataset_Impl();  //Causing segfault when using shared_ptr
        /*copy subset of 'dc' to dObj->dc and return*/std::cout<<"Copied subset";
    }
};
class Dataset{
    Dataset_Impl *d;
    public:
        Dataset (){};
        inline void const getSubset(Dataset &dObj) const{d->getSubset(dObj.d);}
};
int main(){
    Dataset m1,subset1;std::shared_ptr<Dataset> subset2;
    m1.getSubset(subset1);
    m1.getSubset((*subset2)); //Causing segfault
}

Body:
you are not creating an object for the shared_ptr variable and trying to access a member variable of pointer. try

std::shared_ptr<Dataset> subset2(new Dataset())


问:
Enumerating boolean template parameters in C++11
I'm trying to determine how to take in a boolean template parameter pack

```<code>template<bool...B> struct BoolPack{};
</code>```

and construct from it an integer parameter pack where the values indicate the enumeration of the true elements in BoolPack. The enumeration could be contained like this:

```<code>template<size_t...I> struct IntegerSequence{};
</code>```

The function should take in a BoolPack and return an IntegerSequence;

```<code>template<bool...B>
constexpr auto enumerate( const BoolPack<B...>& b ) {
  // Combination of cumulative sum and mask?
  return IntegerSequence<???>();
}
</code>```

For example, if the input would be

```<code>BoolPack<true,false,true,false,true> b;
</code>```

The function should return

```<code>IntegerSequence<1,0,2,0,3> e();
</code>```

My best guess on how to implement this would be to compute a partial sum
where the the kth template parameter is

```<code>K = K-1 + static_cast<size_t>(get<K>(make_tuple<B...>));
</code>```

I'm not sure if this is the way to do it. Is there not a more direct approach that doesn't require making tuples for example? Applying the recursion should result in

```<code>IntegerSequence<1,1,2,2,3> s();
</code>```

And then to multiply this componentwise with the elements of the original BoolPack. Is this the way to go, or can I do this without tuples?

Thanks!

答:
The way you think to implement

```<code>template<bool...B>
constexpr auto enumerate( const BoolPack<B...>& b ) {
  // Combination of cumulative sum and mask?
  return IntegerSequence<???>();
}
</code>```

can't work because C++ is a strong typed language, so the returned type can't depend from sums obtained from code that can be executed compile time.

I know that the values are known at compile time, so the values can be computed compile-time; but the best way that I see pass through a specific type traits.

By example (sorry: renamed IntegerSequence as IndexSequence to be more near to the C++14 std::index_sequence)

```<code>template <std::size_t, typename, std::size_t ...>
struct BoolIndexer
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<true, Bs...>, Is...>
   : public BoolIndexer<N+1U, BoolPack<Bs...>, Is..., N>
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<false, Bs...>, Is...>
   : public BoolIndexer<N, BoolPack<Bs...>, Is..., 0U>
 { };

template <std::size_t N, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<>, Is...>
 { using type = IndexSequence<Is...>; };
</code>```

The following is a full compiling example

```<code>#include <iostream>
#include <type_traits>

template <bool ... B>
struct BoolPack
 { };

template<size_t...I>
struct IndexSequence
 { };

template <std::size_t, typename, std::size_t ...>
struct BoolIndexer
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<true, Bs...>, Is...>
   : public BoolIndexer<N+1U, BoolPack<Bs...>, Is..., N>
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<false, Bs...>, Is...>
   : public BoolIndexer<N, BoolPack<Bs...>, Is..., 0U>
 { };

template <std::size_t N, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<>, Is...>
 { using type = IndexSequence<Is...>; };

int main ()
 {
   using type1 = BoolPack<true,false,true,false,true>;
   using type2 = typename BoolIndexer<1U, type1>::type;

   static_assert( std::is_same<type2, IndexSequence<1,0,2,0,3>>{}, "!" );
 }
</code>```

If you really need a function to get the conversion, using the BoolIndexer type traits you can write it simply as follows

```<code>template <bool ... Bs>
constexpr auto getIndexSequence (BoolPack<Bs...> const &)
   -> typename BoolIndexer<1U, BoolPack<Bs...>>::type
 { return {}; }
</code>```

and call it in this way

```<code>auto is = getIndexSequence(BoolPack<true,false,true,false,true>{});
</code>```

Body:
I'm trying to determine how to take in a boolean template parameter pack

template<bool...B> struct BoolPack{};

and construct from it an integer parameter pack where the values indicate the enumeration of the true elements in BoolPack. The enumeration could be contained like this:

template<size_t...I> struct IntegerSequence{};

The function should take in a BoolPack and return an IntegerSequence;

template<bool...B>
constexpr auto enumerate( const BoolPack& b ) {
  // Combination of cumulative sum and mask?
  return IntegerSequence<???>();
}

For example, if the input would be

BoolPack<true,false,true,false,true> b;

The function should return

IntegerSequence<1,0,2,0,3> e();

My best guess on how to implement this would be to compute a partial sum
where the the kth template parameter is

K = K-1 + static_cast<size_t>(get<K>(make_tuple));

I'm not sure if this is the way to do it. Is there not a more direct approach that doesn't require making tuples for example? Applying the recursion should result in

IntegerSequence<1,1,2,2,3> s();

And then to multiply this componentwise with the elements of the original BoolPack. Is this the way to go, or can I do this without tuples?

Thanks!

Body:
The way you think to implement

template<bool...B>
constexpr auto enumerate( const BoolPack<B...>& b ) {
  // Combination of cumulative sum and mask?
  return IntegerSequence<???>();
}

can't work because C++ is a strong typed language, so the returned type can't depend from sums obtained from code that can be executed compile time.

I know that the values are known at compile time, so the values can be computed compile-time; but the best way that I see pass through a specific type traits.

By example (sorry: renamed IntegerSequence as IndexSequence to be more near to the C++14 std::index_sequence)

template <std::size_t, typename, std::size_t ...>
struct BoolIndexer
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<true, Bs...>, Is...>
   : public BoolIndexer<N+1U, BoolPack<Bs...>, Is..., N>
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<false, Bs...>, Is...>
   : public BoolIndexer<N, BoolPack<Bs...>, Is..., 0U>
 { };

template <std::size_t N, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<>, Is...>
 { using type = IndexSequence<Is...>; };

The following is a full compiling example

#include <iostream>
#include <type_traits>

template <bool ... B>
struct BoolPack
 { };

template<size_t...I>
struct IndexSequence
 { };

template <std::size_t, typename, std::size_t ...>
struct BoolIndexer
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<true, Bs...>, Is...>
   : public BoolIndexer<N+1U, BoolPack<Bs...>, Is..., N>
 { };

template <std::size_t N, bool ... Bs, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<false, Bs...>, Is...>
   : public BoolIndexer<N, BoolPack<Bs...>, Is..., 0U>
 { };

template <std::size_t N, std::size_t ... Is>
struct BoolIndexer<N, BoolPack<>, Is...>
 { using type = IndexSequence<Is...>; };

int main ()
 {
   using type1 = BoolPack<true,false,true,false,true>;
   using type2 = typename BoolIndexer<1U, type1>::type;

   static_assert( std::is_same<type2, IndexSequence<1,0,2,0,3>>{}, "!" );
 }

If you really need a function to get the conversion, using the BoolIndexer type traits you can write it simply as follows

template <bool ... Bs>
constexpr auto getIndexSequence (BoolPack<Bs...> const &)
   -> typename BoolIndexer<1U, BoolPack<Bs...>>::type
 { return {}; }

and call it in this way

auto is = getIndexSequence(BoolPack<true,false,true,false,true>{});