问:
Checking if tab exists in tabControl c#
I am creating tabs dynamically and I have managed to do it but when I try and make it check if the tab already exists so it cant add another one if just keeps adding them.</p>

```<code>      private void fourBtn_Click(object sender, EventArgs e)
    {
        string theName = "Level4";
        TabPage tp = new TabPage(theName);
        if (!tp.Name.Equals(theName)) {

            tp.Name = theName;
            tabControl1.TabPages.Add(tp);

            TextBox tb = new TextBox();
            tb.Dock = DockStyle.Fill;
            tb.Multiline = true;
            tp.Controls.Add(tb);
        }
    }
</code>```

答:
You can do the following to check if a TabPage exists with the same name...

```<code>tabControl1.TabPages.Contains(tabPage)
</code>```

What you currently do is, you create a new TabPage with a name, and check if that tab name does not have the same name which was and always will evaluate to true since you've literally given it that name.

```<code>private void fourBtn_Click(object sender, EventArgs e) {
 string theName = "Level4";
 TabPage tp = new TabPage(theName);
 if (!tabControl1.TabPages.Contains(tabPage2)) {

  tp.Name = theName;
  tabControl1.TabPages.Add(tp);

  TextBox tb = new TextBox();
  tb.Dock = DockStyle.Fill;
  tb.Multiline = true;
  tp.Controls.Add(tb);
 }
}
</code>```

If you wish, you can even create a loop:

```<code>foreach(TabPage tab in tabControl1.TabPages){
   if(tab.Name == tabName)
      return true;
}
</code>```

Title: Checking if tab exists in tabControl c#

Body:
I am creating tabs dynamically and I have managed to do it but when I try and make it check if the tab already exists so it cant add another one if just keeps adding them.

      private void fourBtn_Click(object sender, EventArgs e)
    {
        string theName = "Level4";
        TabPage tp = new TabPage(theName);
        if (!tp.Name.Equals(theName)) {

            tp.Name = theName;
            tabControl1.TabPages.Add(tp);

            TextBox tb = new TextBox();
            tb.Dock = DockStyle.Fill;
            tb.Multiline = true;
            tp.Controls.Add(tb);
        }
    }

Body:
You can do the following to check if a TabPage exists with the same name...

tabControl1.TabPages.Contains(tabPage)

What you currently do is, you create a new TabPage with a name, and check if that tab name does not have the same name which was and always will evaluate to true since you've literally given it that name.

private void fourBtn_Click(object sender, EventArgs e) {
 string theName = "Level4";
 TabPage tp = new TabPage(theName);
 if (!tabControl1.TabPages.Contains(tabPage2)) {

  tp.Name = theName;
  tabControl1.TabPages.Add(tp);

  TextBox tb = new TextBox();
  tb.Dock = DockStyle.Fill;
  tb.Multiline = true;
  tp.Controls.Add(tb);
 }
}

If you wish, you can even create a loop:

foreach(TabPage tab in tabControl1.TabPages){
   if(tab.Name == tabName)
      return true;
}


来源: stackexchange

问:
How to reduce File IO on legacy app that writes to disk, and app that reads it in real time (.NET)
My situation is I have a legacy app which I don't have the code for which writes out data to disk every second or so. I have a C# program I wrote which every second reads what was written to disk and uses the data. The data is written to a few text files which I know the file name before its created.

The issue is I have lots of virtual machines running this legacy app and my program. They are not limited by ram or cpu but I can't add more than 10 VMs per machine due to file io bottleneck.

Is there an easy way I can make a file on disk that exists in ram or something else? I heard something about named pipes being an option?

Thanks!

答:
Are you sure of the actual IO involved?

Long ago I implemented a very ugly connection sending data from a dos program to a Windows program by means of a file.  This was a lot faster than once a second, though--the dos program would send a 4k block anytime anything on it changed, 50 times a second (if it was caught up) the Windows program would read the frame number and then read the 4K block if the frame number differed.

This did NOT cause disk IO!  You could sit there causing the dos program to update the frame many times a second for as long as you wanted and the hard drive light would stay off.  Windows saw the file was open and being frequently written, the buffers were NOT flushed to disk until the updates stopped.

While I spent a lot of time optimizing the Windows side of the link it was all in what was done with the data, not in the connection--that simply wasn't a bottleneck despite it's apparent ugliness.

It's possible Windows would handle it differently if the file was closed each time.  Sticking it on a ramdisk would keep it from doing the disk IO even then.

ContentLicense: CC BY-SA 2.5


问:
How to select all columns not containing a certain substring in Postgresql?
If I have a table with column names like that:

```<code>name,
name_raw,
item,
item_raw,
message,
message_raw
...
... etc.
</code>```

How can I select every column that does not end with _raw dynamically?

Is something like this:

```<code>SELECT
   [SOME REGEX LOGIC HERE]
FROM
   mytable
</code>```

or similar possible?

答:
Use the information schema e.g.

```<code>SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'my_schema'
AND table_name   = 'mytable'
AND NOT column_name LIKE '%\_raw'
</code>```

note because the underscore itself is a query wildcard it needs to be "escaped"

ContentLicense: CC BY-SA 3.0

Body:
If I have a table with column names like that:

name,
name_raw,
item,
item_raw,
message,
message_raw
...
... etc.

How can I select every column that does not end with _raw dynamically?

Is something like this:

SELECT
   [SOME REGEX LOGIC HERE]
FROM
   mytable

or similar possible?

Body:
Use the information schema e.g.

SELECT column_name
FROM information_schema.columns
WHERE table_schema = 'my_schema'
AND table_name   = 'mytable'
AND NOT column_name LIKE '%\_raw'

note because the underscore itself is a query wildcard it needs to be "escaped"


问:
Bridging Events in Xamarin with Rx
At the moment, I'm just using the plain old delegates/events observer pattern for click events on my buttons. So, I thought I would go Rx.

My first attempt was balls. I thought I'd go for the simplest overload that you see in WinForms examples:

```<code>Observable.FromEventPattern<EventArgs>(__navToTestButton, 'click');
</code>```

But I got an exception that Android buttons don't have a click event. That is a reflection fail of epic proportions. I'm guessing perhaps I'm missing a dll (great, another dll to make my apk even bigger).

Anyhow, I thought I'd forge on with a different overload. Now it looks like this:

```<code>navToTest = Observable.FromEventPattern<EventArgs>(
    x => _navToTestButton.Click += _navToTestButton_Click,
    x => _navToTestButton.Click -= _navToTestButton_Click
).ObserveOn(SynchronizationContext.Current);
</code>```

Still a fail. No exception. But when I click the button, just crickets and tumbleweeds. Am I meant to subscribe to that? What would that look like, as the subscription seems to have already happened in that overload?

Xamarin is tricky enough, but Rx just makes it bloody hard. Especially with the lack of abundance of people blogging about it (at least my Google searches turned up nothing too useful. I based my code on the few bits and pieces I did find.

Thanks

答:
I do not see any subscriptions on your observable(s):

Reflection:

```<code>Observable.FromEventPattern(aButton, "Click")
  .Subscribe((obj) => Log.Debug(TAG, $"StackOverflow: {obj}"));
</code>```

Handler:

```<code>Observable.FromEventPattern(
    handler => aButton.Click += handler,
    handler => aButton.Click -= handler
)
.Subscribe(
  (obj) => Log.Debug(TAG, $"StackOverflow: {obj}")
);
</code>```

Make a double tap observable:

```<code>var fromInterval = TimeSpan.FromMilliseconds(250);
var toInterval = TimeSpan.FromMilliseconds(500);

var buttonTapped = Observable.FromEventPattern(
    handler => aButton.Click += handler,
    handler => aButton.Click -= handler
);
var doubleTaps = buttonTapped
        .TimeInterval()
        .SkipWhile(t => t.Interval < toInterval)
        .FirstAsync(t => t.Interval < fromInterval)
        .Repeat();
doubleTaps
        .Subscribe(
          (obj) => Log.Debug(TAG, $"Double Tap: {obj}")
     );
</code>```

Title: Bridging Events in Xamarin with Rx

Body:
At the moment, I'm just using the plain old delegates/events observer pattern for click events on my buttons. So, I thought I would go Rx.

My first attempt was balls. I thought I'd go for the simplest overload that you see in WinForms examples:

Observable.FromEventPattern<EventArgs>(__navToTestButton, 'click');

But I got an exception that Android buttons don't have a click event. That is a reflection fail of epic proportions. I'm guessing perhaps I'm missing a dll (great, another dll to make my apk even bigger).

Anyhow, I thought I'd forge on with a different overload. Now it looks like this:

navToTest = Observable.FromEventPattern<EventArgs>(
    x => _navToTestButton.Click += _navToTestButton_Click,
    x => _navToTestButton.Click -= _navToTestButton_Click
).ObserveOn(SynchronizationContext.Current);

Still a fail. No exception. But when I click the button, just crickets and tumbleweeds. Am I meant to subscribe to that? What would that look like, as the subscription seems to have already happened in that overload?

Xamarin is tricky enough, but Rx just makes it bloody hard. Especially with the lack of abundance of people blogging about it (at least my Google searches turned up nothing too useful. I based my code on the few bits and pieces I did find.

Thanks

Body:
I do not see any subscriptions on your observable(s):

Reflection:

Observable.FromEventPattern(aButton, "Click")
  .Subscribe((obj) => Log.Debug(TAG, $"StackOverflow: {obj}"));

Handler:

Observable.FromEventPattern(
    handler => aButton.Click += handler,
    handler => aButton.Click -= handler
)
.Subscribe(
  (obj) => Log.Debug(TAG, $"StackOverflow: {obj}")
);

Make a double tap observable:

var fromInterval = TimeSpan.FromMilliseconds(250);
var toInterval = TimeSpan.FromMilliseconds(500);

var buttonTapped = Observable.FromEventPattern(
    handler => aButton.Click += handler,
    handler => aButton.Click -= handler
);
var doubleTaps = buttonTapped
        .TimeInterval()
        .SkipWhile(t => t.Interval < toInterval)
        .FirstAsync(t => t.Interval < fromInterval)
        .Repeat();
doubleTaps
        .Subscribe(
          (obj) => Log.Debug(TAG, $"Double Tap: {obj}")
     );


问:
Pylint ignore-patterns Not Working
I'm using an rc file that has:

ignore-patterns=".*local.*"

I expect this to ignore all files with the word local in the name.  So, tmplocal.py, tmp.local.py, tmp_local.py, local_tmp.py, etc.

When running Pylint (1.7.2), these files are not ignored.  Any suggestions?

答:
What ended up working for me was not including quotes. My current config looks something like this: ignore-patterns=one.py,.*local.*

```<code>$ pylint --version
pylint 1.7.2,
astroid 1.5.3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609]
</code>```

Title: Pylint ignore-patterns Not Working

Body:
What ended up working for me was not including quotes. My current config looks something like this: ignore-patterns=one.py,.*local.*

$ pylint --version
pylint 1.7.2,
astroid 1.5.3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609]


问:
How to make Scons build object files in a separate folder
I'm working on a project which we used to compile using make. Now we wanna use scons instead so I've created a Sconstruct file that seems to handle this just fine.

Nevertheless, I'm greatly dissatisfied with the location where scons puts .o files (right next to my source files (.c), which is annoying) and i can't seem to understand how to make it create them in a specific folder during the build.

I've tried several (quite a lot) "VariantDir()", "env.VariantDir()", "variant_dir=...", etc... calls but none have worked for me yet. All I'm asking for is an option that would enable me to choose the folder where .o files will go so that they don't end up mixed with my source files.

Here's a taste of what I've done so far :

```<code>### Imports ###
import os

### Environment de compilation ###

# Dossier et nom du binaire
binFolder = 'bin/'
binName = 'sc.bin'

# Outils de l'environnement
env = DefaultEnvironment(
    tools = [ 'gcc', 'link' ],
)

# Chaine de compilation
env.PrependENVPath('PATH', os.path.abspath('path/to/cross/compiler'))
prefix = 'cross-compiler-prefix'
env['CC'] = prefix + env['CC']

### Fichiers a compiler ###
srcFiles = [
    'some',
    'source',
    'files'
]

### Dossiers a inclure (headers) ###
includeFolders = [
    'some',
    'include',
    'folders'
]

### Flags de compilation ###
compilationFlags = '-some -compilation -flags'

### Librairies externes ##
libs = [
    'some',
    'libraries'
]

### Regle de generation sc.bin  ###
sc_multi = env.Program(
    binFolder+binName,
    srcFiles,
    CDEFINES = {'SOME_MACRO':'SOME_VALUE'},
    CPPPATH = includeFolders,
    CFLAGS = compilationFlags,
    LIBS = libs,
)

# Par default, on genere la cible sc_multi
Default(sc_multi)
Alias('sc_multi', sc_multi)
</code>```

If anyone has insight, please share as I nearly don't have any hair left.
Thx !

答:
Ok. I'm going to assume based on your comments above that you are really talking about source files in a subdirectory (or at least another directory) from where your SConstruct is located

Let's assume your tree looks like this:

```<code> - SConstruct
 - Git_Submodule_Directory
     |--- a.c
     |--- b.c
 - bin
     |--- a.o
     |--- b.o
</code>```

Here's the SConstruct:

```<code>env=Environment()

binName='my_favorite'
### Fichiers a compiler ###
srcFiles = [
    'a.c',
    'b.c',
]

### Dossiers a inclure (headers) ###
includeFolders = [
    'git-submodule',
]

### Flags de compilation ###
compilationFlags = '-some -compilation -flags'

### Librairies externes ##
libs = [
    'm',
]

VariantDir('bin','git-submodule')

var_src = ["#bin/"+f for f in srcFiles]

### Regle de generation sc.bin  ###
sc_multi = env.Program(
    "#bin/"+binName,
    var_src,
    CDEFINES = {'SOME_MACRO':'SOME_VALUE'},
    CPPPATH = includeFolders,
    CFLAGS = compilationFlags,
    LIBS = libs,
)

# Par default, on genere la cible sc_multi
Default(sc_multi)
Alias('sc_multi', sc_multi)
</code>```

git-submodule/a.c

```<code>#include <stdio.h>

void another()
{
    printf("Another\n");
}
</code>```

git-submodule/b.c

```<code>/* Hello World program */

#include<stdio.h>

extern void another();

int main()
{
    printf("Hello World");
    another();
    return(0);
}
</code>```

Does this do what you're looking for?
Build output:

```<code>scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
gcc -o bin/a.o -c -Igit-submodule bin/a.c
gcc -o bin/b.o -c -Igit-submodule bin/b.c
gcc -o bin/my_favorite bin/a.o bin/b.o -lm
scons: done building targets.
</code>```

Note: you could add duplicate=0 to the VariantDir() then the output would be:

```<code>scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
gcc -o bin/a.o -c -Igit-submodule git-submodule/a.c
gcc -o bin/b.o -c -Igit-submodule git-submodule/b.c
gcc -o bin/my_favorite bin/a.o bin/b.o -lm
scons: done building targets.
</code>```

Body:
I'm working on a project which we used to compile using make. Now we wanna use scons instead so I've created a Sconstruct file that seems to handle this just fine.

Nevertheless, I'm greatly dissatisfied with the location where scons puts .o files (right next to my source files (.c), which is annoying) and i can't seem to understand how to make it create them in a specific folder during the build.

I've tried several (quite a lot) "VariantDir()", "env.VariantDir()", "variant_dir=...", etc... calls but none have worked for me yet. All I'm asking for is an option that would enable me to choose the folder where .o files will go so that they don't end up mixed with my source files.

Here's a taste of what I've done so far :

### Imports ###
import os

### Environment de compilation ###

# Dossier et nom du binaire
binFolder = 'bin/'
binName = 'sc.bin'

# Outils de l'environnement
env = DefaultEnvironment(
    tools = [ 'gcc', 'link' ],
)

# Chaine de compilation
env.PrependENVPath('PATH', os.path.abspath('path/to/cross/compiler'))
prefix = 'cross-compiler-prefix'
env['CC'] = prefix + env['CC']

### Fichiers a compiler ###
srcFiles = [
    'some',
    'source',
    'files'
]

### Dossiers a inclure (headers) ###
includeFolders = [
    'some',
    'include',
    'folders'
]

### Flags de compilation ###
compilationFlags = '-some -compilation -flags'

### Librairies externes ##
libs = [
    'some',
    'libraries'
]

### Regle de generation sc.bin  ###
sc_multi = env.Program(
    binFolder+binName,
    srcFiles,
    CDEFINES = {'SOME_MACRO':'SOME_VALUE'},
    CPPPATH = includeFolders,
    CFLAGS = compilationFlags,
    LIBS = libs,
)

# Par default, on genere la cible sc_multi
Default(sc_multi)
Alias('sc_multi', sc_multi)

If anyone has insight, please share as I nearly don't have any hair left.
Thx !

Body:
Ok. I'm going to assume based on your comments above that you are really talking about source files in a subdirectory (or at least another directory) from where your SConstruct is located

Let's assume your tree looks like this:

 - SConstruct
 - Git_Submodule_Directory
     |--- a.c
     |--- b.c
 - bin
     |--- a.o
     |--- b.o

Here's the SConstruct:

env=Environment()

binName='my_favorite'
### Fichiers a compiler ###
srcFiles = [
    'a.c',
    'b.c',
]

### Dossiers a inclure (headers) ###
includeFolders = [
    'git-submodule',
]

### Flags de compilation ###
compilationFlags = '-some -compilation -flags'

### Librairies externes ##
libs = [
    'm',
]

VariantDir('bin','git-submodule')

var_src = ["#bin/"+f for f in srcFiles]

### Regle de generation sc.bin  ###
sc_multi = env.Program(
    "#bin/"+binName,
    var_src,
    CDEFINES = {'SOME_MACRO':'SOME_VALUE'},
    CPPPATH = includeFolders,
    CFLAGS = compilationFlags,
    LIBS = libs,
)

# Par default, on genere la cible sc_multi
Default(sc_multi)
Alias('sc_multi', sc_multi)

git-submodule/a.c

#include <stdio.h>

void another()
{
    printf("Another\n");
}

git-submodule/b.c

/* Hello World program */

#include<stdio.h>

extern void another();

int main()
{
    printf("Hello World");
    another();
    return(0);
}

Does this do what you're looking for?
Build output:

scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
gcc -o bin/a.o -c -Igit-submodule bin/a.c
gcc -o bin/b.o -c -Igit-submodule bin/b.c
gcc -o bin/my_favorite bin/a.o bin/b.o -lm
scons: done building targets.

Note: you could add duplicate=0 to the VariantDir() then the output would be:

scons: Reading SConscript files ...
scons: done reading SConscript files.
scons: Building targets ...
gcc -o bin/a.o -c -Igit-submodule git-submodule/a.c
gcc -o bin/b.o -c -Igit-submodule git-submodule/b.c
gcc -o bin/my_favorite bin/a.o bin/b.o -lm
scons: done building targets.


问:
Typescript library for SVG
I've been using Raphael with an Angular 4 app and also tried to switch to Snap.  Neither of these support typescript very well (at all?).

Does anyone know of a library that includes full typescript types and doesn't require a PhD to get it working with Angular2/4/5?

If not, I'm thinking I will create a pure typescript library but that's a lot of work.

答:
Just install the @types package for Raphael.

It is maintained by the TypeScript community. These are people who like yourself, write apps in TypeScript and use Raphael.

If you find that the declarations are imperfect, you can open an issue (or a pull request) on https://github.com/DefinitelyTyped/DefinitelyTyped

Installation:

With NPM:

```<code>$ npm install --save @types/raphael
</code>```

With JSPM:

```<code>$ jspm install npm:@types/raphael
</code>```

With Yarn:

```<code>$ yarn add @types/raphael
</code>```

Usage:

```<code>import Raphael from 'raphael';
</code>```

The same applies to snapsvg

Title: Typescript library for SVG

Body:
Just install the @types package for Raphael.

It is maintained by the TypeScript community. These are people who like yourself, write apps in TypeScript and use Raphael.

If you find that the declarations are imperfect, you can open an issue (or a pull request) on https://github.com/DefinitelyTyped/DefinitelyTyped

Installation:

With NPM:

$ npm install --save @types/raphael

With JSPM:

$ jspm install npm:@types/raphael

With Yarn:

$ yarn add @types/raphael

Usage:

import Raphael from 'raphael';

The same applies to snapsvg


问:
What is the fastest way to insert text into a
 element with javascript?
I am writing a long series of numbers to my document, one at a time. document.write() handles this fine, but using innerHTML with a
 element is sluggish, and rather quickly crashes my tab.  Is there some way to insert text into a
 element that is as fast as document.write?

答: You could try node.textContent = "foo" but im not sure how much faster it will be, assuming it's not slower.

Title: What is the fastest way to insert text into a <div> element with javascript?


问:
Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path
I have this error, it's about an object.

This is my port:

```<code>http://localhost:3000/cupones
</code>```

I can see this:

```<code>[
{
    "id": "YLabhnB",
    "empresa": "KFC",
    "titulo": "Mega Online",
    "descripcion": "9 Piezas de pollo, 1 Papa Familiar, 6 Nuggets, 1 Ensalada Familiar, 1 Gaseosa de 1.5Lts",
    "precio": 55.9,
    "imgUrl": "https://www.kfc.com.pe/Imagenes/800x275/BOTONERA%20MEGA%20ONLINE%202.jpg"
},
{
    "id": "LLzwhnA",
    "empresa": "Bembos",
    "titulo": "Promo Clásica",
    "descripcion": "Clásica Mediana + 1 Papa Mediana + 1 Gaseosa 500ml",
    "precio": 13.9,
    "imgUrl": "http://www.bembos.com.pe/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/o/k/okpromoclasica__2_.png"
}
]
</code>```

Then I created a class with jsonschema2pojo, after that I created my JSONResponse, here:

```<code>public class JSONResponse {
    private Cupon[] cupon;

    public Cupon[] getCupon() {
        return cupon;
    }
}
</code>```

I think that I can change something here in my interface that is called

```<code>public interface RequestInterface {
    @GET("cupones")
    Call<JSONResponse> getJSON();
}
</code>```

Finally in my fragment:

```<code>private void initViews(View rootView){
    recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(new CuponAdapter(new ArrayList<Cupon>()));
    loadJSON();
}

private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.42:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
            adapter = new CuponAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}
</code>```

How could I fix that?

答:
According to your problem

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path

We can know that your parse json error ,and your root tag of your response is [](JSONArray).So you should use List in your Retrofit .

So you should change JSONResponse to List<JSONResponse> in your code .

First

change the JSONResponse class

```<code>public class JSONResponse {

    /**
     * id : YLabhnB
     * empresa : KFC
     * titulo : Mega Online
     * descripcion : 9 Piezas de pollo, 1 Papa Familiar, 6 Nuggets, 1 Ensalada Familiar, 1 Gaseosa de 1.5Lts
     * precio : 55.9
     * imgUrl : https://www.kfc.com.pe/Imagenes/800x275/BOTONERA%20MEGA%20ONLINE%202.jpg
     */

    private String id;
    private String empresa;
    private String titulo;
    private String descripcion;
    private double precio;
    private String imgUrl;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmpresa() {
        return empresa;
    }

    public void setEmpresa(String empresa) {
        this.empresa = empresa;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public double getPrecio() {
        return precio;
    }

    public void setPrecio(double precio) {
        this.precio = precio;
    }

    public String getImgUrl() {
        return imgUrl;
    }

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

Second

change the call code Call<JSONResponse> getJSON(); to

```<code>@GET("cupones")
Call<List<JSONResponse>> getJSON();
</code>```

Body:
I have this error, it's about an object.

This is my port:

http://localhost:3000/cupones

I can see this:

[
{
    "id": "YLabhnB",
    "empresa": "KFC",
    "titulo": "Mega Online",
    "descripcion": "9 Piezas de pollo, 1 Papa Familiar, 6 Nuggets, 1 Ensalada Familiar, 1 Gaseosa de 1.5Lts",
    "precio": 55.9,
    "imgUrl": "https://www.kfc.com.pe/Imagenes/800x275/BOTONERA%20MEGA%20ONLINE%202.jpg"
},
{
    "id": "LLzwhnA",
    "empresa": "Bembos",
    "titulo": "Promo Clásica",
    "descripcion": "Clásica Mediana + 1 Papa Mediana + 1 Gaseosa 500ml",
    "precio": 13.9,
    "imgUrl": "http://www.bembos.com.pe/media/catalog/product/cache/1/image/9df78eab33525d08d6e5fb8d27136e95/o/k/okpromoclasica__2_.png"
}
]

Then I created a class with jsonschema2pojo, after that I created my JSONResponse, here:

public class JSONResponse {
    private Cupon[] cupon;

    public Cupon[] getCupon() {
        return cupon;
    }
}

I think that I can change something here in my interface that is called

public interface RequestInterface {
    @GET("cupones")
    Call<JSONResponse> getJSON();
}

Finally in my fragment:

private void initViews(View rootView){
    recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recycler_view);
    recyclerView.setHasFixedSize(true);
    RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(layoutManager);
    recyclerView.setAdapter(new CuponAdapter(new ArrayList<Cupon>()));
    loadJSON();
}

private void loadJSON(){
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("http://192.168.1.42:3000/")
            .addConverterFactory(GsonConverterFactory.create())
            .build();
    RequestInterface request = retrofit.create(RequestInterface.class);
    Call<JSONResponse> call = request.getJSON();
    call.enqueue(new Callback<JSONResponse>() {
        @Override
        public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
            JSONResponse jsonResponse = response.body();
            data = new ArrayList<>(Arrays.asList(jsonResponse.getCupon()));
            adapter = new CuponAdapter(data);
            recyclerView.setAdapter(adapter);
        }

        @Override
        public void onFailure(Call<JSONResponse> call, Throwable t) {
            Log.d("Error", t.getMessage());
        }
    });
}

How could I fix that?

Body:
According to your problem

Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path

We can know that your parse json error ,and your root tag of your response is [](JSONArray).So you should use List in your Retrofit .

So you should change JSONResponse to List<JSONResponse> in your code .

First

change the JSONResponse class

public class JSONResponse {

    /**
     * id : YLabhnB
     * empresa : KFC
     * titulo : Mega Online
     * descripcion : 9 Piezas de pollo, 1 Papa Familiar, 6 Nuggets, 1 Ensalada Familiar, 1 Gaseosa de 1.5Lts
     * precio : 55.9
     * imgUrl : https://www.kfc.com.pe/Imagenes/800x275/BOTONERA%20MEGA%20ONLINE%202.jpg
     */

    private String id;
    private String empresa;
    private String titulo;
    private String descripcion;
    private double precio;
    private String imgUrl;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getEmpresa() {
        return empresa;
    }

    public void setEmpresa(String empresa) {
        this.empresa = empresa;
    }

    public String getTitulo() {
        return titulo;
    }

    public void setTitulo(String titulo) {
        this.titulo = titulo;
    }

    public String getDescripcion() {
        return descripcion;
    }

    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }

    public double getPrecio() {
        return precio;
    }

    public void setPrecio(double precio) {
        this.precio = precio;
    }

    public String getImgUrl() {
        return imgUrl;
    }

    public void setImgUrl(String imgUrl) {
        this.imgUrl = imgUrl;
    }
}

Second

change the call code Call<JSONResponse> getJSON(); to

@GET("cupones")
Call<List<JSONResponse>> getJSON();


问:
Why can't I append an object in an array in Rethinkdb?
I am trying to append an object into an array in rethink.  Here is how I am trying to append it:

```<code>rethink('shifts')
        .get(shiftId)
        .update(row => row("milestones").default([]).append({
            dateAchieved: date,
            phaseType: phasetype.toUpperCase()
        })).run(rethinkConnection)
</code>```

The error I get is this:

```<code>UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReqlQueryLogicError: Expected type TABLE but found DATUM:
"shifts" in:
r("shifts").get("5d1b607f-e670-4eb5-b873-6e800f8ae8f8").update(function(var_15) { return var_15("milestones").default([]).append({"dateAchieved": r.ISO8601("2012-04-12T06:00:00.000Z"), "phaseType": "PILOT"}); })
  ^^^^^^^^
</code>```

What does it mean that it is expecting a 'TABLE', but found a 'DATUM'?  How do I get this to insert an object into the array?

答:
You need to do

```<code>rethink.table(“shifts”)
</code>```

Calling the rethink namespace  with a string just returns an expression

Body:
I am trying to append an object into an array in rethink.  Here is how I am trying to append it:

rethink('shifts')
        .get(shiftId)
        .update(row => row("milestones").default([]).append({
            dateAchieved: date,
            phaseType: phasetype.toUpperCase()
        })).run(rethinkConnection)

The error I get is this:

UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ReqlQueryLogicError: Expected type TABLE but found DATUM:
"shifts" in:
r("shifts").get("5d1b607f-e670-4eb5-b873-6e800f8ae8f8").update(function(var_15) { return var_15("milestones").default([]).append({"dateAchieved": r.ISO8601("2012-04-12T06:00:00.000Z"), "phaseType": "PILOT"}); })
  ^^^^^^^^

What does it mean that it is expecting a 'TABLE', but found a 'DATUM'?  How do I get this to insert an object into the array?

Body:
You need to do

rethink.table(“shifts”)

Calling the rethink namespace  with a string just returns an expression


问:
Rake gems:install says "could not find table", rake db:migrate says "required gems missing"
I just cloned a github repo on a fresh Ubuntu machine, running sqlite3 for all environments. rake db:create says development.sqlite3 already exists. rake db:migrate says I'm missing a bunch of required gems and should run rake gems:install. rake gems:install, of course, says it Could not find table 'studies', which sounds to me like something rake db:migrate should fix.

I looked around the net and while lots of people have gotten 'could not find table' errors, they all got them from rake db:migrate, not rake gems:install. I'm suspecting it's an application-specific error, but still, any ideas would be appreciated.

PS: Ruby 1.8.7, Rails 2.3.8.

答:
Is this a Rails 3 app? If so, you should run:

```<code>bundle install
</code>```

Rails 3 uses Bundler instead of the rake tasks to manage gems. http://gembundler.com/

Body:
Is this a Rails 3 app? If so, you should run:

bundle install

Rails 3 uses Bundler instead of the rake tasks to manage gems. http://gembundler.com/


问:
combining drawCircle on map click and displaying multiple markers at the same time and also showing markers which fall under the circle
I am making a web application to track assets and I need to show the location of assets using the database. I have written a code for that and it works fine. Now  I need to show the assets which are within a variable radius of 200 to 2000 m. I have written the code for variable circle when clicked on any location on map and it can be dragged any where (code separately written on two different pages) . I need help to combine both. I tried doing so but failed and got confused. Please help. The backend is C# and ASP.NET. Any thing else please ask!!
This is code for plotting markers from database

```<code> <script type="text/javascript">
var markers = [
    <asp:Repeater ID="rptMarkers" runat="server">
        <ItemTemplate>
            {
                "Name": '<%# Eval("AID") %>',
                "lat": '<%# Eval("Current_Location_Y") %>',
        "lng": '<%# Eval("Current_Location_X") %>',
            "description": '<%# Eval("Description") %>',
            "CCId": '<%# Eval("CCID") %>'

       }

</ItemTemplate>
<SeparatorTemplate>
    ,

</SeparatorTemplate>
    </asp:Repeater >

  ];

</script>

 <script type="text/javascript">
  window.onload = function initMap() {

    var mapOptions = {
        center: new google.maps.LatLng(markers[0].lat, markers[0].lng),
        zoom: 16,
        mapTypeId: google.maps.MapTypeId.ROADMAP ,
  navigationControl: true
    };
    var infoWindow = new google.maps.InfoWindow/*()*/;
    var map = new google.maps.Map(document.getElementById("map"), mapOptions);
    for (i = 0; i < markers.length; i++) {
        var data = markers[i]
        var myLatlng = new google.maps.LatLng(data.lat, data.lng);
 switch (data.CCId) {
            case "1":
                icon = "images/red-dot.png";
                break;
            case "3":
                icon = "images/yellow-dot.png";
                break;
            case "2":
                icon = "images/green-dot.png";
                break;
            default:
                icon = "images/Google Maps Markers/red_markerC.png";
        }
        var marker = new google.maps.Marker({
            position: myLatlng,
            map: map,
            draggable: true,
            title: data.title
        });
      (function (marker, data) {
            google.maps.event.addListener(marker, "click", function (e) {
                infoWindow.setContent(data.Name);
                infoWindow.open(map, marker);
                               });
        })(marker, data);
    }
}

 </script>
</code>```

This is the draw circle function which shows a draggable circle and a marker when clicked anywhere on the map.

```<code> <script>
    var map;
    var circle;
    var marker;
    var currentlatlng;
    function setLatLongValue() {
        jQuery('#txtPointA1').val(currentlatlng.lat()); //#txtPointA1
        jQuery('#txtPointA2').val(currentlatlng.lng());
    }
    function loadMap() {

        currentlatlng = new google.maps.LatLng(23.06368, 72.53135);
        map = new google.maps.Map(document.getElementById('map'), {
            zoom: 16,
            center: currentlatlng,
            mapTypeId: 'terrain',
            mapTypeControl: true,
            navigationControl: true
        });
        google.maps.event.addDomListener(map, 'click', function (e) {

            currentlatlng = e.latLng;

            if (currentlatlng) {

                map.panTo(currentlatlng);
                setLatLongValue();
                setMarker();
            }
        });
    }
        function drawCircle() {

            if (circle != undefined)
                circle.setMap(null);

            var radius = 200;

            if (jQuery('#txtPointB1').val() != '' && !isNaN(jQuery('#txtPointB1').val()) && parseInt(jQuery('#txtPointB1').val()) > 0) {
                radius = parseInt(jQuery('#txtPointB1').val());
            }
            jQuery('#txtPointB1').val(radius.toString());

            var options = {
                strokeColor: '#800000',
                strokeOpacity: 1.0,
                strokeWeight: 1,
                fillColor: '#C64D45',
                fillOpacity: 0.5,
                map: map,
                center: currentlatlng,
                radius: radius
            };

            circle = new google.maps.Circle(options);
        }
        function setMarker() {

            if (marker != undefined)
                marker.setMap(null);

            marker = new google.maps.Marker({
                position: currentlatlng,
                draggable: true,
                map: map
            });

            if (marker) {
                google.maps.event.addDomListener(marker, "dragend", function () {
                    currentlatlng = marker.getPosition();
                    setLatLongValue();
                    drawCircle();
                });
                drawCircle();
            }
        }

</script>
   <script type="text/javascript" >

        $(window).load(function () {
            loadMap();
        });

</script>
</code>```

答:
Here is an example of how I do it.

To see the demo you need to preload your browser with the coordinates: -
                latitude: -31.98118
                longitude: 115.81991

OR tap/click the Radar icon (bottom right), make the circle very big, zoom out a lot, then drag the circle to UWA in Perth Western Australia. Then zoom back in.

You need to do the above 'cos there is only data for the UWA campus.

You will see that as you drag the circle around campus green gems appear in the circle and disappear when the circle leaves.

Tap to remove the circle. Double-Tap to toggle from a movable circle to a static quadrangle. Tap-and-hold to get the search filter options.

The searching is done in a Web Worker to allow the main-thread to service the UI promptly.

Body:
I am making a web application to track assets and I need to show the location of assets using the database. I have written a code for that and it works fine. Now  I need to show the assets which are within a variable radius of 200 to 2000 m. I have written the code for variable circle when clicked on any location on map and it can be dragged any where (code separately written on two different pages) . I need help to combine both. I tried doing so but failed and got confused. Please help. The backend is C# and ASP.NET. Any thing else please ask!!
This is code for plotting markers from database

This is the draw circle function which shows a draggable circle and a marker when clicked anywhere on the map.


问:
Can't find file I created
I am new to java and I have a problem with finding a file I created that is usually visible within Eclipse.After running and refreshing multiple times I still don't see it.Here is my code, any help would be welcome.</p>

```<code>    Scanner input = new Scanner(System.in);
    Scanner x= new Scanner(System.in);
    System.out.println("You got a high score!");
    System.out.println();
    System.out.println("Please enter your score: ");

    int score = input.nextInt();
    System.out.println("Please enter your name: ");

    String name = x.nextLine();

    input.close();

    File file = new File("highscore.txt");

    try(BufferedWriter bw = new BufferedWriter(new FileWriter(file))){

        bw.write(score);
        bw.write(name);

    } catch (FileNotFoundException e) {
        System.out.println("File is not found");;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}
</code>```

答:
Try printing the absolute path.</p>

```<code>File file = new File("highscore.txt");
System.out.println("file: " + file.getAbsolutePath());
</code>```

Title: Can't find file I created

Body:
I am new to java and I have a problem with finding a file I created that is usually visible within Eclipse.After running and refreshing multiple times I still don't see it.Here is my code, any help would be welcome.

    Scanner input = new Scanner(System.in);
    Scanner x= new Scanner(System.in);
    System.out.println("You got a high score!");
    System.out.println();
    System.out.println("Please enter your score: ");

    int score = input.nextInt();
    System.out.println("Please enter your name: ");

    String name = x.nextLine();

    input.close();

    File file = new File("highscore.txt");

    try(BufferedWriter bw = new BufferedWriter(new FileWriter(file))){

        bw.write(score);
        bw.write(name);

    } catch (FileNotFoundException e) {
        System.out.println("File is not found");;
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
}

Body:
Try printing the absolute path.

File file = new File("highscore.txt");
System.out.println("file: " + file.getAbsolutePath());


问:
Angular 4 Setting Headers with HttpClient Module
im new with Angular and i'm working on a project that for some reasons i have to set headers for server side authorization, Im using Angular 4 and the HttpClient Module imported from '@angular/common/http'

This is my AuthService Class

```<code>import { Injectable } from '@angular/core';
import { User } from '../../models/user';
import { HttpClient, HttpHeaders, HttpRequest } from
'@angular/common/http';
import { Observable } from 'rxjs';
import { Globals } from '../../utils/global';
import { Converters } from '../../utils/converters';

@Injectable()
export class AuthService {
getUserByToken(token: string): any {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('authorization', 'Bearer ' + token);

    console.log(headers);

    return new Promise((resolve, reject) => {
      this.http.get(this.global.urls['info'], { headers: headers }).subscribe((data) => {
        if (data != null) {
          this.converter.userJsonToObject(data).then((data: User) => {
            this.setCurrentUser(data);
            this.persistToken(data.token);
            resolve(data);
          });
        } else {
          reject('This user is not defined');
        }
      }, (err) => {
        reject(err);
      });
    });

  }
</code>```

When i run my project and i call getUserByToken(token) function, the server console told me that no token was send.
The endpoint is working perfect with ARC so the issue is on the client side.
does anyone can help me to resolve this issue problem.
:D

答:
It is of type  immutable Map so if you assign a new value it will reinitialize the object so you should be doing as

```<code>let headers = new HttpHeaders().set('Content-Type', 'application/json')
                               .set('authorization', 'Bearer ' + token);
</code>```

or

```<code>let headers = new HttpHeaders().set('Content-Type', 'application/json');
headers = headers.set('authorization', 'Bearer ' + token);
</code>```

Body:
im new with Angular and i'm working on a project that for some reasons i have to set headers for server side authorization, Im using Angular 4 and the HttpClient Module imported from '@angular/common/http'

This is my AuthService Class

import { Injectable } from '@angular/core';
import { User } from '../../models/user';
import { HttpClient, HttpHeaders, HttpRequest } from
'@angular/common/http';
import { Observable } from 'rxjs';
import { Globals } from '../../utils/global';
import { Converters } from '../../utils/converters';

@Injectable()
export class AuthService {
getUserByToken(token: string): any {
    let headers = new HttpHeaders();
    headers.append('Content-Type', 'application/json');
    headers.append('authorization', 'Bearer ' + token);

    console.log(headers);

    return new Promise((resolve, reject) => {
      this.http.get(this.global.urls['info'], { headers: headers }).subscribe((data) => {
        if (data != null) {
          this.converter.userJsonToObject(data).then((data: User) => {
            this.setCurrentUser(data);
            this.persistToken(data.token);
            resolve(data);
          });
        } else {
          reject('This user is not defined');
        }
      }, (err) => {
        reject(err);
      });
    });

  }

When i run my project and i call getUserByToken(token) function, the server console told me that no token was send.
The endpoint is working perfect with ARC so the issue is on the client side.
does anyone can help me to resolve this issue problem.
:D

Body:
It is of type  immutable Map so if you assign a new value it will reinitialize the object so you should be doing as

let headers = new HttpHeaders().set('Content-Type', 'application/json')
                               .set('authorization', 'Bearer ' + token);

or

let headers = new HttpHeaders().set('Content-Type', 'application/json');
headers = headers.set('authorization', 'Bearer ' + token);


问:
Changing Woocommerce featured to vertical
I am wanting to change my featured products to be a vertical listing instead of horizontal. What I am looking for is

All I can find is how to edit the look but it still be horizontal.

答: Disregard, I found the solution with a plugin</p>


问:
How to configure/override Maven property used as parent version in dependencies?
Suppose there are two 3rd-party Maven artifacts with the following POM.XMLs:

artifact1 POM.XML:

```<code><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>group1</groupId>
<artifactId>artifact1</artifactId>
<version>${artifact1.version}</version>
<packaging>pom</packaging>
<properties>
    <artifact1.version>0.0.1-SNAPSHOT</artifact1.version>
</properties>
<modules>
    <module>../artifact2</module>
</modules>
</code>```

artifact2 POM.XML:

```<code><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>
<artifactId>artifact2</artifactId>
<parent>
    <groupId>group1</groupId>
    <artifactId>artifact1</artifactId>
    <version>${artifact1.version}</version>
    <relativePath>../artifact1</relativePath>
</parent>
</code>```

They are built normally using

```<code>mvn clean install
</code>```

Now, if I try to reuse artifact2 in a 3rd POM.XML:

```<code><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>group2</groupId>
<artifactId>artifact3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>group1</groupId>
        <artifactId>artifact2</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>
</code>```

After executing...

```<code>mvn clean install
</code>```

...the build fails trying to locate group1:artifact1:pom:${artifact1.version}

```<code>[ERROR] Failed to execute goal on project artifact3: Could not resolve dependencies for project group2:artifact3:jar:0.0.1-SNAPSHOT: Failed to collect dependencies at group1:artifact2:jar:0.0.1-SNAPSHOT: Failed to read artifact descriptor for group1:artifact2:jar:0.0.1-SNAPSHOT: Could not find artifact group1:artifact1:pom:${artifact1.version} in central (https://repo.maven.apache.org/maven2) -> [Help 1]
</code>```

And setting the property in the command-line doesn't work either:

```<code>mvn clean install -Dartifact1.version=0.0.1-SNAPSHOT
</code>```

How can I use artifact2 as a dependency?

答:
<parent> doesn't allow variables. Because in order to get a list of variables Maven first has to build Effective POM and for this it needs to resolve parents.

Even if there is some version of Maven that allowed such module to be installed it's not a working solution in general. Maven's ideology is that all the dependencies (including parent) could be downloaded from a repo and are not necessarily present on local FS/in the reactor. With properties in the parent dependency definition you violate this rule.

Body:
Suppose there are two 3rd-party Maven artifacts with the following POM.XMLs:

artifact1 POM.XML:

<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>group1</groupId>
<artifactId>artifact1</artifactId>
<version>${artifact1.version}</version>
<packaging>pom</packaging>
<properties>
    <artifact1.version>0.0.1-SNAPSHOT</artifact1.version>
</properties>
<modules>
    <module>../artifact2</module>
</modules>

artifact2 POM.XML:

<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>
<artifactId>artifact2</artifactId>
<parent>
    <groupId>group1</groupId>
    <artifactId>artifact1</artifactId>
    <version>${artifact1.version}</version>
    <relativePath>../artifact1</relativePath>
</parent>

They are built normally using

mvn clean install

Now, if I try to reuse artifact2 in a 3rd POM.XML:

<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>group2</groupId>
<artifactId>artifact3</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
    <dependency>
        <groupId>group1</groupId>
        <artifactId>artifact2</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

After executing...

mvn clean install

...the build fails trying to locate group1:artifact1:pom:${artifact1.version}

[ERROR] Failed to execute goal on project artifact3: Could not resolve dependencies for project group2:artifact3:jar:0.0.1-SNAPSHOT: Failed to collect dependencies at group1:artifact2:jar:0.0.1-SNAPSHOT: Failed to read artifact descriptor for group1:artifact2:jar:0.0.1-SNAPSHOT: Could not find artifact group1:artifact1:pom:${artifact1.version} in central (https://repo.maven.apache.org/maven2) -> [Help 1]

And setting the property in the command-line doesn't work either:

mvn clean install -Dartifact1.version=0.0.1-SNAPSHOT

How can I use artifact2 as a dependency?


问:
Take the last N elements of an array instead of first elements in PowerShell
Quick question.  I have the following:

```<code>$domain = "my.new.domain.com"
$domain.Split('.')[0,1]
</code>```

...which returns the value:

```<code>my
new
</code>```

That's great except I need the LAST TWO (domain.com) and am unsure how to do that.  Unfortunately the number of splits is variable (e.g. test.my.new.domain.com).  How does one say "go to the end and count X splits backwards"?

答:
To take last N elements of an array, you can use either of the following options:

$array | select -Last n

$array[-n..-1] (← '..' is the Range Operator)

Example

```<code>$domain = "my.new.domain.com"
$domain.Split('.') | select -Last 2
</code>```

Will result in:

```<code>domain
com
</code>```

Note

Using the select cmdlet, you can do some jobs that you usually do using LINQ in .NET, for example:

Take first N elements: $array | select -First N

Take last N elements: $array | select -Last N

Skip first N elements: $array | select -Skip N

Skip last N elements: $array | select -SkipLast N

Skip and take from first: $array | select -Skip N -First M

Skip and take from last: $array | select -Skip N -Last M

Select distinct elements: $array | select -Distinct

select elements at index: $array | select -Index (0,2,4)

Body:
Quick question.  I have the following:

$domain = "my.new.domain.com"
$domain.Split('.')[0,1]

...which returns the value:

my
new

That's great except I need the LAST TWO (domain.com) and am unsure how to do that.  Unfortunately the number of splits is variable (e.g. test.my.new.domain.com).  How does one say "go to the end and count X splits backwards"?

Body:
To take last N elements of an array, you can use either of the following options:

$array | select -Last n

$array[-n..-1] (← '..' is the Range Operator)

Example

$domain = "my.new.domain.com"
$domain.Split('.') | select -Last 2

Will result in:

domain
com

Note

Using the select cmdlet, you can do some jobs that you usually do using LINQ in .NET, for example:

Take first N elements: $array | select -First N

Take last N elements: $array | select -Last N

Skip first N elements: $array | select -Skip N

Skip last N elements: $array | select -SkipLast N

Skip and take from first: $array | select -Skip N -First M

Skip and take from last: $array | select -Skip N -Last M

Select distinct elements: $array | select -Distinct

select elements at index: $array | select -Index (0,2,4)

ContentLicense: CC BY-SA 4.0


问:
How to share state between tabs in react-native-router-flux?
So I have a TabNavigation scene using react-native-router-flux.  I want to share state from the initial tab screen component to the second tab screen component when the second tab is pressed.  What is the best way to do this?

Here is my TabNavigation scene with the two child tabs:

```<code>                  <Scene key="showPlaceTabBar" tabs={true} labelStyle={{fontSize: 20, marginBottom: 15}} hideNavBar>
                   <Scene key="postsTab" title="Posts"
                     onPress={()=> {Actions.posts()}}>
                     <Scene hideNavBar={false} key="showPlace" component={PlacesShow} title="Show Place" />

                   </Scene>

                   <Scene hideNavBar={false} key="createPostTab" title="Create Post"
                     onPress={()=> {Actions.createPost({placeName: this.props.placeName})}}>
                     <Scene key="createPost" component={CreatePost} title="Create Post" />

                   </Scene>
                 </Scene>
</code>```

I want to send some state/props data from the PlacesShow component to the CreatePlace component.  The Actions method does not have access to the PlacesShow component props/state because it lives where the screen is defined.  How should I accomplish this?

I have looked into Redux but I am having a hard time understanding what exactly it does.  Is this a job for Redux?  I was using react-navigation earlier, but was having a hard time customizing navbars, and when I switched to react-native-router-flux everything became 10 times easier.  This is basically the last piece of navigation functionality I need for my app, and would rather not introduce new libraries/switch back to react-navigation unless I absolutely have to (custom Navigation components were hard to understand, and I am pretty sure that is what I need for my app).

Thanks for the help.

答:
AsyncStorage

__

Since you are using React-Native , you can leverage the shared storage of the underlined device using AsyncStorage interface.

persist :

```<code>await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.');
</code>```

retrieve :

```<code> const value = await AsyncStorage.getItem('@MySuperStore:key');
</code>```

More details in the official documentation .

Body:
So I have a TabNavigation scene using react-native-router-flux.  I want to share state from the initial tab screen component to the second tab screen component when the second tab is pressed.  What is the best way to do this?

Here is my TabNavigation scene with the two child tabs:

                  <Scene key="showPlaceTabBar" tabs={true} labelStyle={{fontSize: 20, marginBottom: 15}} hideNavBar>
                   <Scene key="postsTab" title="Posts"
                     onPress={()=> {Actions.posts()}}>
                     <Scene hideNavBar={false} key="showPlace" component={PlacesShow} title="Show Place" />

                   </Scene>

                   <Scene hideNavBar={false} key="createPostTab" title="Create Post"
                     onPress={()=> {Actions.createPost({placeName: this.props.placeName})}}>
                     <Scene key="createPost" component={CreatePost} title="Create Post" />

                   </Scene>
                 </Scene>

I want to send some state/props data from the PlacesShow component to the CreatePlace component.  The Actions method does not have access to the PlacesShow component props/state because it lives where the screen is defined.  How should I accomplish this?

I have looked into Redux but I am having a hard time understanding what exactly it does.  Is this a job for Redux?  I was using react-navigation earlier, but was having a hard time customizing navbars, and when I switched to react-native-router-flux everything became 10 times easier.  This is basically the last piece of navigation functionality I need for my app, and would rather not introduce new libraries/switch back to react-navigation unless I absolutely have to (custom Navigation components were hard to understand, and I am pretty sure that is what I need for my app).

Thanks for the help.

Body:
AsyncStorage

__

Since you are using React-Native , you can leverage the shared storage of the underlined device using AsyncStorage interface.

persist :

await AsyncStorage.setItem('@MySuperStore:key', 'I like to save it.');

retrieve :

 const value = await AsyncStorage.getItem('@MySuperStore:key');

More details in the official documentation .


问:
How can I select only rows with multiple hits for a specific column?
I am not sure how to phrase this question so I'll give an example:

Suppose there is a table called tagged that has two columns: tagger and taggee. What would the SQL query look like to return the taggee(s) that are in multiple rows? That is to say, they have been tagged 2 or more times by any tagger.

I would like a 'generic' SQL query and not something that only works on a specific DBMS.

EDIT: Added "tagged 2 or more times by any tagger."

答:
```<code>select distinct t1.taggee from tagged t1 inner join tagged t2
        on t1.taggee = t2.taggee and t1.tagger != t2.tagger;
</code>```

Will give you all the taggees who have been tagged by more than one tagger

Body:
select distinct t1.taggee from tagged t1 inner join tagged t2
        on t1.taggee = t2.taggee and t1.tagger != t2.tagger;

Will give you all the taggees who have been tagged by more than one tagger


问:
Can't override styles using classes in material-ui
I am having a hell of a time trying to understand how to change the styles for a one time use of TextField

The docs really don't make any sense to me

```<code><FormControl>
  <InputLabel
    htmlFor="mobile-number-input"
  >
    Mobile Number
  </InputLabel>
  <Input
    value={this.state.mobileNumber}
    onChange={this.onMobileNumberChange}
    fullWidth
    classes={{
      inkbar: {
        '&:after': {
          backgroundColor: 'white',
        }
      }
    }}
    id="mobile-number-input"
  />
</FormControl><br />
</code>```

But I get this error

```<code>Warning: Material-UI: the key `inkbar` provided to the classes property is not valid for Input.
You need to provide a non empty string instead of: [object Object].
</code>```

答:
You need to override inkbar with the name of another class, not a JSS object.

One way of doing this is to declare your JSS object outside of the component and use the withStyles higher-order component to provide your component with a classes prop that maps the class names defined in JSS to their actual names:

import { withStyles } from 'material-ui/styles';

const styles = {
  inkbarOverride: {
    '&:after': {
      backgroundColor: 'white',
    }
  }
};

const Test = ({ classes }) =>
  <FormControl>
    <InputLabel
      htmlFor="mobile-number-input"
    >
      Mobile Number
    </InputLabel>
    <Input
      value={this.state.mobileNumber}
      onChange={this.onMobileNumberChange}
      fullWidth
      classes={{
        inkbar: classes.inkbarOverride,
      }}
      id="mobile-number-input"
    />
  </FormControl>

export default withStyles(styles)(Test);
```

Refer to Overriding with classes for more information.

Body:
I am having a hell of a time trying to understand how to change the styles for a one time use of TextField

The docs really don't make any sense to me

<FormControl>
  <InputLabel
    htmlFor="mobile-number-input"
  >
    Mobile Number
  </InputLabel>
  <Input
    value={this.state.mobileNumber}
    onChange={this.onMobileNumberChange}
    fullWidth
    classes={{
      inkbar: {
        '&:after': {
          backgroundColor: 'white',
        }
      }
    }}
    id="mobile-number-input"
  />
</FormControl>

But I get this error

Warning: Material-UI: the key `inkbar` provided to the classes property is not valid for Input.
You need to provide a non empty string instead of: [object Object].

Body:
You need to override inkbar with the name of another class, not a JSS object.

One way of doing this is to declare your JSS object outside of the component and use the withStyles higher-order component to provide your component with a classes prop that maps the class names defined in JSS to their actual names:

import { withStyles } from 'material-ui/styles';

const styles = {
  inkbarOverride: {
    '&:after': {
      backgroundColor: 'white',
    }
  }
};

const Test = ({ classes }) =>
  <FormControl>
    <InputLabel
      htmlFor="mobile-number-input"
    >
      Mobile Number
    </InputLabel>
    <Input
      value={this.state.mobileNumber}
      onChange={this.onMobileNumberChange}
      fullWidth
      classes={{
        inkbar: classes.inkbarOverride,
      }}
      id="mobile-number-input"
    />
  </FormControl>

export default withStyles(styles)(Test);

Refer to Overriding with classes for more information.


问:
Unable to delete PostgreSQL role
Yesterday I created a user to make backups from PostgreSQL. I granted select to this user and then I noticed that the name was not well written. The problem is that I tried to erase the user using the command line and the response was, due to the grants that I made a few moments back:

```<code>ERROR:  role "dump_user" cannot be dropped because some objects depend on it
</code>```

Long story short, I erased this user using pgadmin and now I have problems because when I want to create a new table, it tells:

```<code>ERROR:  role 313898229 was concurrently dropped
</code>```

I cheked and 313898229 was the oid of this dump_user in the pg_authid table, I tried to create a new user and assign this oid, but postgres says that I can't modify system id "oid".

Is there a way that I can permanently erase this user?

答:
If all you wanted was a different name:

```<code>ALTER ROLE dump_user RENAME TO better_name;
</code>```

Too late for that now. Before deleting the role you should have run:

```<code>REASSIGN OWNED BY pg_dump TO postgres; -- postgres being default superuser role
</code>```

Read details here:

Find objects linked to a PostgreSQL role

Your error message:

ERROR: role 313898229 was concurrently dropped

is defined in the source code here. Looks like a race condition between two transactions. But you omitted relevant details.

Title: Unable to delete PostgreSQL role

Body:
Yesterday I created a user to make backups from PostgreSQL. I granted select to this user and then I noticed that the name was not well written. The problem is that I tried to erase the user using the command line and the response was, due to the grants that I made a few moments back:

ERROR:  role "dump_user" cannot be dropped because some objects depend on it

Long story short, I erased this user using pgadmin and now I have problems because when I want to create a new table, it tells:

ERROR:  role 313898229 was concurrently dropped

I cheked and 313898229 was the oid of this dump_user in the pg_authid table, I tried to create a new user and assign this oid, but postgres says that I can't modify system id "oid".

Is there a way that I can permanently erase this user?

Body:
If all you wanted was a different name:

ALTER ROLE dump_user RENAME TO better_name;

Too late for that now. Before deleting the role you should have run:

REASSIGN OWNED BY pg_dump TO postgres; -- postgres being default superuser role

Read details here:

Find objects linked to a PostgreSQL role

Your error message:

ERROR: role 313898229 was concurrently dropped

is defined in the source code here. Looks like a race condition between two transactions. But you omitted relevant details.


问:
DDD, Status object / Value Objects
I've a class, Proposal, which has a $status of type ProposalStatus.  Now, for the most part the ProposalStatus's identity does not change...  but it does (sort of).  It's $id is fixed, but the $display_name and $definition (just strings) can change over a long period of time as the master data is updated, but it will NOT change within the lifetime of an HTTP Request-Response.

Question #1 - Entity or Value Object?

Is a value object something is never supposed to change or only never supposed to change over the lifetime of a specific execution of the application?  If the display name or definition are changed then really I expect / want it to be changed for everyone.  However, since they can be defined outside of the proposal I'm think that just straight up makes them entities instead of value objects.

At no time does the Proposal change the ProposalStatus's attributes, it only changes which ProposalStatus is has.

Question #2 - How to set the status correctly for a domain-driven design?

My proposal object has the ability to manage it's statuses, but in order to do that I need to have a specific ProposalStatus object.  Only, where is the list of statuses that allows it to returns the right expected to be?

I could get it from a the ProposalRepository...  but everything is accessed via the aggregate root which the Proposal so that doesn't make sense.

I could have constants that match the $id of the ProposalStatus, but that seems wrong.

I could make a ProposalStatusRepository...  but should I be accessing another repository from within the Proposal?

I could make a array of all possible statuses with the $id as the key and add to the proposal, but that isn't much different from a repository...

Example:

```<code>class ProposalStatus {
    protected $id; // E.g., pending_customer_approval
    protected $display_name; // E.g., Pending Customer Approval
    protected $definition; // E.g., The proposal needs to be approved by the customer
}

class Proposal {
    /**
     * The current status of the proposal
     * @var ProposalStatus
     */
    protected $proposal_status;

    public function withdraw() {
        // verify status is not closed or canceled
        // change status to draft
    }

    public function submit() {
        // verify status is draft
        // change status to pending customer approval
    }

    public function approve() {
        // verify status is pending customer approval
        // change status to approved
    }

    public function reject() {
        // verify status is pending customer approval
        // change status to rejected
    }

    public function close() {
        // verify status is not canceled
        // change status to closed
    }

    public function cancel() {
        // verify status is not closed
        // change status to canceled
    }
}
</code>```

答:
Is list of all possible proposal statuses static? I think it is. So ProposalStatus looks like a simple enumeration. Attributes like DisplayName and Definition are not related to business code.

Just define ProposalStatus as enumeration (static class with read-only fields or any other structure supported by your language). It shuld be defined in business layer. Bussiness code should be able to distinguish enumeration values (e.g. if (proposal.Status == ProposalStatus.Pending) { poposal.Status = ProposalStatus.Approved; }).

In application or even presentation layer define a dictionary that contains DisplayName and Definition mapped to ProposalStatus. It will be used only when displaying data to users.

Title: DDD, Status object / Value Objects

Body:
I've a class, Proposal, which has a $status of type ProposalStatus.  Now, for the most part the ProposalStatus's identity does not change...  but it does (sort of).  It's $id is fixed, but the $display_name and $definition (just strings) can change over a long period of time as the master data is updated, but it will NOT change within the lifetime of an HTTP Request-Response.

Question #1 - Entity or Value Object?

Is a value object something is never supposed to change or only never supposed to change over the lifetime of a specific execution of the application?  If the display name or definition are changed then really I expect / want it to be changed for everyone.  However, since they can be defined outside of the proposal I'm think that just straight up makes them entities instead of value objects.

At no time does the Proposal change the ProposalStatus's attributes, it only changes which ProposalStatus is has.

Question #2 - How to set the status correctly for a domain-driven design?

My proposal object has the ability to manage it's statuses, but in order to do that I need to have a specific ProposalStatus object.  Only, where is the list of statuses that allows it to returns the right expected to be?

I could get it from a the ProposalRepository...  but everything is accessed via the aggregate root which the Proposal so that doesn't make sense.

I could have constants that match the $id of the ProposalStatus, but that seems wrong.

I could make a ProposalStatusRepository...  but should I be accessing another repository from within the Proposal?

I could make a array of all possible statuses with the $id as the key and add to the proposal, but that isn't much different from a repository...

Example:

class ProposalStatus {
    protected $id; // E.g., pending_customer_approval
    protected $display_name; // E.g., Pending Customer Approval
    protected $definition; // E.g., The proposal needs to be approved by the customer
}

class Proposal {
    /**
     * The current status of the proposal
     * @var ProposalStatus
     */
    protected $proposal_status;

    public function withdraw() {
        // verify status is not closed or canceled
        // change status to draft
    }

    public function submit() {
        // verify status is draft
        // change status to pending customer approval
    }

    public function approve() {
        // verify status is pending customer approval
        // change status to approved
    }

    public function reject() {
        // verify status is pending customer approval
        // change status to rejected
    }

    public function close() {
        // verify status is not canceled
        // change status to closed
    }

    public function cancel() {
        // verify status is not closed
        // change status to canceled
    }
}


问:
Apply math to a member of a list in python
I am trying to keep track of some numbers in a list, but I am unable to edit members of said list. When I try subtracting from it I am given the error "unsupported operand type(s) for -=: 'list' and 'int'"

```<code>with open("prices.txt") as f:
        seatCapacity = []
        for line in f:
            line = [int(i) for i in line[10:].split()]
            seatCapacity.append(line)

seatCapacity[seat] -= 1
</code>```

seatCapacity[seat] displays a number correctly so I'm not certain what I'm doing wrong.

Edit:
Some examples of output are

```<code>print(seatCapacity)
</code>```

output:

```<code>[[150], [120], [200], [80], [120], [80]]
</code>```

and

```<code>print(seatCapacity[seat])
</code>```

output:

```<code>[150]
</code>```

答:
seatCapacity is a list of lists, because line is a list - see the first line after the for loop begins:

```<code> line = [int(i) for i in line[10:].split()]
</code>```

Depending on the contents of prices.txt, you might be able to fix this problem by removing the brackets on that line.

Body:
I am trying to keep track of some numbers in a list, but I am unable to edit members of said list. When I try subtracting from it I am given the error "unsupported operand type(s) for -=: 'list' and 'int'"

with open("prices.txt") as f:
        seatCapacity = []
        for line in f:
            line = [int(i) for i in line[10:].split()]
            seatCapacity.append(line)

seatCapacity[seat] -= 1

seatCapacity[seat] displays a number correctly so I'm not certain what I'm doing wrong.

Edit:
Some examples of output are

print(seatCapacity)

output:

[[150], [120], [200], [80], [120], [80]]

and

print(seatCapacity[seat])

output:

[150]

Body:
seatCapacity is a list of lists, because line is a list - see the first line after the for loop begins:

 line = [int(i) for i in line[10:].split()]

Depending on the contents of prices.txt, you might be able to fix this problem by removing the brackets on that line.


问:
Words not replacing correctly
I am writing a class that takes a dictionary and a txt file and if a word in the txt file isn't in the dictionary then it gives the user a chance to change the incorrect words. After the corrections are made, it will output the corrected txt file.

Here's an example txt file:

```<code>twinkx twinkx lottle star how I
lottle lamb its a warld of laughter a
warld of tears
</code>```

For example, it would ask me if i wanted to correct twinkx, and when i switch it to twinkle, it would still output the same thing as above, with it still saying twinkx. That leads me to believe there is something wrong with my replacement method. The algorithm for it is described in the comments so I possibly could have missed something.

```<code>    private void replace(String misspelled, String replacement){
    //TODO: Algorithm:
    //If wrongWords contains the misspelled word:
    //   get ALL the lineNumbers on where the misspelled word appears
    //   for each line number where it appears:
    //        in fileLines[line] replace misspelled with replacement
    //        (Hint: use one of the available methods in the String class to do the replacement)
    if(wrongWords.containsKey(misspelled))
       wrongWords.get(misspelled);
       for(String line : fileLine){
          line.replace(misspelled, replacement);
       }
    }
</code>```

Here is the method that calls replace in the first place:

```<code>private Scanner scan; // a Scanner to read user's input
private HashSet<String> dictionary;
private HashMap<String, ArrayList<Integer>> wrongWords;
private ArrayList<String> fileLine;

private void correctionMode(){
  //for each line in fileLines:
  //   for each word in the line:
  //      if the word is in wrongWords:
  //            display the word and ALL the line numbers it appears on
  //            ask user if they like to replace?(y/n)
  //            if user chooses y:
  //              ask for a new word and call the replace method replaceAll occurrences
  //            for either y or n delete word from wrongWords
  //Hint: for parsing lines look back at the processFile()
  for(String line: fileLine)
    for(String w: line.split("\\s"))
       if(wrongWords.containsKey(w)){
           System.out.println(w + " " + wrongWords.get(w));
           System.out.println("replace all? (y or n): ");
           String r = scan.nextLine();
           if(r.equals("y")){
              System.out.println("Enter replacement: ");
              String r2 = scan.nextLine();
              replace(w, r2);
              wrongWords.remove(w);
           }
           else if(r.equals("n")){
              wrongWords.remove(w);
           }
       }
}
</code>```

答:
line is only a loop variable. You need something like:</p>

```<code>    for (int i = 0; i < fileLine.size(); i++) {
        fileLine.set(i, fileLine.get(i).replace(misspelled, replacement));
    }
</code>```

Title: Words not replacing correctly

Body:
I am writing a class that takes a dictionary and a txt file and if a word in the txt file isn't in the dictionary then it gives the user a chance to change the incorrect words. After the corrections are made, it will output the corrected txt file.

Here's an example txt file:

twinkx twinkx lottle star how I
lottle lamb its a warld of laughter a
warld of tears

For example, it would ask me if i wanted to correct twinkx, and when i switch it to twinkle, it would still output the same thing as above, with it still saying twinkx. That leads me to believe there is something wrong with my replacement method. The algorithm for it is described in the comments so I possibly could have missed something.

    private void replace(String misspelled, String replacement){
    //TODO: Algorithm:
    //If wrongWords contains the misspelled word:
    //   get ALL the lineNumbers on where the misspelled word appears
    //   for each line number where it appears:
    //        in fileLines[line] replace misspelled with replacement
    //        (Hint: use one of the available methods in the String class to do the replacement)
    if(wrongWords.containsKey(misspelled))
       wrongWords.get(misspelled);
       for(String line : fileLine){
          line.replace(misspelled, replacement);
       }
    }

Here is the method that calls replace in the first place:

private Scanner scan; // a Scanner to read user's input
private HashSet<String> dictionary;
private HashMap<String, ArrayList<Integer>> wrongWords;
private ArrayList<String> fileLine;

private void correctionMode(){
  //for each line in fileLines:
  //   for each word in the line:
  //      if the word is in wrongWords:
  //            display the word and ALL the line numbers it appears on
  //            ask user if they like to replace?(y/n)
  //            if user chooses y:
  //              ask for a new word and call the replace method replaceAll occurrences
  //            for either y or n delete word from wrongWords
  //Hint: for parsing lines look back at the processFile()
  for(String line: fileLine)
    for(String w: line.split("\\s"))
       if(wrongWords.containsKey(w)){
           System.out.println(w + " " + wrongWords.get(w));
           System.out.println("replace all? (y or n): ");
           String r = scan.nextLine();
           if(r.equals("y")){
              System.out.println("Enter replacement: ");
              String r2 = scan.nextLine();
              replace(w, r2);
              wrongWords.remove(w);
           }
           else if(r.equals("n")){
              wrongWords.remove(w);
           }
       }
}

Body:
line is only a loop variable. You need something like:

    for (int i = 0; i < fileLine.size(); i++) {
        fileLine.set(i, fileLine.get(i).replace(misspelled, replacement));
    }