问:
Creating a text based game and I'm stuck
Currently in the game, it asks certain questions like, have you collected all the keys, killed all the bosses etc.
But when it gets closes to the ending and it asks "Which key would you like to use?". It does that fine, but once it get to the Door section, it doesn't actually get the value of the key, it just outputs 0

Main piece of code

```<code>public static int possibleKey()
{
    SetnGet sng = new SetnGet();
    int keys;
    do
    {
        System.out.println("Which key would you like to use?");
        keys = in.nextInt();
         }
     while(keys != 1 && keys != 2 && keys != 3);

    return keys;
}

public static int possibleLevel()
{
    SetnGet sng = new SetnGet();
    System.out.println("Which door would you like to enter? - 1, 2, 3 or 4");
    int level;

    if(sng.accessibleKey() == 3)
    {
        do
        {
            System.out.println("You have all three keys, you have complete access");
            level = in.nextInt();
        }
        while(level != 1 && level != 2 && level != 3);
    }
    else
    {
        do
        {
            System.out.println("You have no level access");
            level = in.nextInt();
        }
        while(level != 1 && level != 2 && level != 3 && level != 4);

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

The set and get from the SetnGet Class

```<code>private int possibleKey;
private int possibleLevel;

public int setPossibleKey()
{
    return possibleKey;
}

public void setPossibleKey(int possibleKey)
{
    this.possibleKey = possibleKey;
}

public int getPossibleLevel()
{
    return possibleLevel;
}

public void setPossibleLevel(int possibleLevel)
{
    this.possibleLevel = possibleLevel;
}
</code>```

答:
Method possibleLevel() creates an instance of the SetnGet class (SetnGet sng = new SetnGet();) and, right after that, reads the field of type int of the instance (sng.accessibleKey()). The result of such read is of course 0, because this is the default value of int class fields and you never set any other value to your field. As a result you always go to else and see the "You have no level access" message.

What you could do to fix the problem is to move SetnGet sng = new SetnGet(); from possibleLevel() to the class and then make sure that the result of possibleKey() call is set to it, something like this:

```<code>public class Main {

    private static Scanner in = new Scanner(System.in);

    private static SetnGet sng = new SetnGet();

    public static void main(String[] args) {
        int selectedKey = possibleKey();
        sng.accessibleKey(selectedKey);
        int level = possibleLevel();
    }

    public static int possibleKey() {
        // your initial implementation of the method
    }

    public static int possibleLevel() {
        // your initial implementation of the method, but
        // without the "SetnGet sng = new SetnGet();" line
    }
}
</code>```

Where the SetnGet class looks like this:

```<code>class SetnGet {

    private int accessibleKey;

    int accessibleKey() {
        return accessibleKey;
    }

    void accessibleKey(int accessibleKey) {
        this.accessibleKey = accessibleKey;
    }
}
</code>```

This will fix your initial problem. Then you can consider further refactoring of the code, for example, using method arguments (instead of shared class fields) to pass data between methods, get rid of the redundant SetnGet sng = new SetnGet(); line from the possibleKey() method as well, etc.

Body:
Currently in the game, it asks certain questions like, have you collected all the keys, killed all the bosses etc.
But when it gets closes to the ending and it asks "Which key would you like to use?". It does that fine, but once it get to the Door section, it doesn't actually get the value of the key, it just outputs 0

Main piece of code

public static int possibleKey()
{
    SetnGet sng = new SetnGet();
    int keys;
    do
    {
        System.out.println("Which key would you like to use?");
        keys = in.nextInt();
         }
     while(keys != 1 && keys != 2 && keys != 3);

    return keys;
}

public static int possibleLevel()
{
    SetnGet sng = new SetnGet();
    System.out.println("Which door would you like to enter? - 1, 2, 3 or 4");
    int level;

    if(sng.accessibleKey() == 3)
    {
        do
        {
            System.out.println("You have all three keys, you have complete access");
            level = in.nextInt();
        }
        while(level != 1 && level != 2 && level != 3);
    }
    else
    {
        do
        {
            System.out.println("You have no level access");
            level = in.nextInt();
        }
        while(level != 1 && level != 2 && level != 3 && level != 4);

    }
    return level;
}

The set and get from the SetnGet Class

private int possibleKey;
private int possibleLevel;

public int setPossibleKey()
{
    return possibleKey;
}

public void setPossibleKey(int possibleKey)
{
    this.possibleKey = possibleKey;
}

public int getPossibleLevel()
{
    return possibleLevel;
}

public void setPossibleLevel(int possibleLevel)
{
    this.possibleLevel = possibleLevel;
}

Body:
Method possibleLevel() creates an instance of the SetnGet class (SetnGet sng = new SetnGet();) and, right after that, reads the field of type int of the instance (sng.accessibleKey()). The result of such read is of course 0, because this is the default value of int class fields and you never set any other value to your field. As a result you always go to else and see the "You have no level access" message.

What you could do to fix the problem is to move SetnGet sng = new SetnGet(); from possibleLevel() to the class and then make sure that the result of possibleKey() call is set to it, something like this:

public class Main {

    private static Scanner in = new Scanner(System.in);

    private static SetnGet sng = new SetnGet();

    public static void main(String[] args) {
        int selectedKey = possibleKey();
        sng.accessibleKey(selectedKey);
        int level = possibleLevel();
    }

    public static int possibleKey() {
        // your initial implementation of the method
    }

    public static int possibleLevel() {
        // your initial implementation of the method, but
        // without the "SetnGet sng = new SetnGet();" line
    }
}

Where the SetnGet class looks like this:

class SetnGet {

    private int accessibleKey;

    int accessibleKey() {
        return accessibleKey;
    }

    void accessibleKey(int accessibleKey) {
        this.accessibleKey = accessibleKey;
    }
}

This will fix your initial problem. Then you can consider further refactoring of the code, for example, using method arguments (instead of shared class fields) to pass data between methods, get rid of the redundant SetnGet sng = new SetnGet(); line from the possibleKey() method as well, etc.


来源: stackexchange

问:
FuelUX tree: Default item/folder to selected on create
Does anyone know how to default a FuelUX tree item/folder to selected on create.

I know I can call tree.tree('selectItem', $('#' + node.id)) after the fact to select nodes, but it requires a lot more effort (especially with a large multi-leveled tree) compared to just setting it on creation.

Something like this, where an attribute called "Selected"  marks the item as selected

```<code>result.push({
    name: value.text,
    type: ((parentNode != null) && (!$.isEmptyObject(parentNode))) ? 'item' : 'folder',
    children: children,
    parent: parentNode,
    **selected: value.selected**
    dataAttributes: {
        id: value.id
    }});
</code>```

答:
If you have these codes bellow...

```<code><ul id="tree1"></ul>

var myTree = $('#tree1');

myTree.on('loaded.fu.tree', function (e) {
    // need to add technique here
});
</code>```

Then you could use my-selected-item class in your children >> attr like below...

```<code>'children': {
    'Cat': {text: 'Cat', type: 'item'},
    'Goat': {
        text: 'Goat', type: 'item',
        "attr": {
            "class": "my-selected-item"
        }
    },
    'Tiger': {text: 'Tiger', type: 'item'}
}
</code>```

Now write technique line in the above...

```<code>myTree.on('loaded.fu.tree', function (e) {
    myTree.tree('selectItem', $('.my-selected-item'))
})
</code>```

Hope this will make selected the Goat item.

ContentLicense: CC BY-SA 3.0

Body:
Does anyone know how to default a FuelUX tree item/folder to selected on create.

I know I can call tree.tree('selectItem', $('#' + node.id)) after the fact to select nodes, but it requires a lot more effort (especially with a large multi-leveled tree) compared to just setting it on creation.

Something like this, where an attribute called "Selected"  marks the item as selected

result.push({
    name: value.text,
    type: ((parentNode != null) && (!$.isEmptyObject(parentNode))) ? 'item' : 'folder',
    children: children,
    parent: parentNode,
    **selected: value.selected**
    dataAttributes: {
        id: value.id
    }});

Body:
If you have these codes bellow...

<ul id="tree1"></ul>

var myTree = $('#tree1');

myTree.on('loaded.fu.tree', function (e) {
    // need to add technique here
});

Then you could use my-selected-item class in your children >> attr like below...

'children': {
    'Cat': {text: 'Cat', type: 'item'},
    'Goat': {
        text: 'Goat', type: 'item',
        "attr": {
            "class": "my-selected-item"
        }
    },
    'Tiger': {text: 'Tiger', type: 'item'}
}

Now write technique line in the above...

myTree.on('loaded.fu.tree', function (e) {
    myTree.tree('selectItem', $('.my-selected-item'))
})

Hope this will make selected the Goat item.


问:
pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/
I run sudo pip install git-review, and get the following messages:

Downloading/unpacking git-review
  Cannot fetch index base URL http://pypi.python.org/simple/
  Could not find any downloads that satisfy the requirement git-review
No distributions at all found for git-review
Storing complete log in /home/sai/.pip/pip.log
```

Does anyone has any idea about this?

答:
You need to upgrade your pip installation because it is still using http instead of https.

The --index-url (short version: -i) option allows you to specify an index-url in the call to pip itself, there you can use the https-variant. Then you can instruct pip to upgrade itself.

sudo pip install --index-url https://pypi.python.org/simple/ --upgrade pip

Afterwards you should be able to use pip without the --index-url option.

I believe that the release 7.0.0 (2015-05-21) triggered this issue. The release note for that version states the following:

BACKWARD INCOMPATIBLE No longer implicitly support an insecure origin
origin, and instead require insecure origins be explicitly trusted
with the --trusted-host option.

You can check your pip version with pip --version.

This would mean that issuing sudo pip install --trusted-host --upgrade pip once would also solve this issue, albeit download pip over insecure http. This might also not work at all, because it is possible that the insecure endpoint is no longer accessible on the server (I have not tested this).

Body:
I run sudo pip install git-review, and get the following messages:

Downloading/unpacking git-review
  Cannot fetch index base URL http://pypi.python.org/simple/
  Could not find any downloads that satisfy the requirement git-review
No distributions at all found for git-review
Storing complete log in /home/sai/.pip/pip.log

Does anyone has any idea about this?

ContentLicense: CC BY-SA 4.0


问:
Creating new dataframes by subsetting and reference two dataframes in R
I have two data sets. One with employee preferences and one with a list of potential matches. For each employee, I want to find the matches and create a new dataset for each. The dataset can be one large comprehensive set that can then be split by person, or separate ones from the beginning.

```<code> df1:

> emplid= c("empl1","empl2","empl3")
> c1 = c("HR", "Finance", "HR")
>  c2 = c("x", "y", "z")
>  c3 = c("a","b","C")
>  df1 = data.frame(emplid, c1, c2, c3)

df2:
>  job = c("job1", "job2", "job3", "job4")
>  c4 = c("HR", "HR", "Finance", "Finance")
>  c5 = c("x", "x", "y", "z")
>  c6 = c("a","b", "b","c")
>  df2 = data.frame(job, c4, c5, c6)
</code>```

The result would be

```<code>emplid      job          c4     c5        c6
empl1       job1         HR      x        a
empl3       job4         Finance y        b
</code>```

The above result could be combined, but ultimately I will split it up.

I've only successfully been able to do this when I have only one row in the first dataframe, but that will not be the case. I've tried loops but with no success.

答:
Here is a data.table solution.</p>

```<code>df1[df2, on = c(c1="c4", c2="c5",c3="c6"),nomatch=0]
</code>```

Body:
I have two data sets. One with employee preferences and one with a list of potential matches. For each employee, I want to find the matches and create a new dataset for each. The dataset can be one large comprehensive set that can then be split by person, or separate ones from the beginning.

 df1:

> emplid= c("empl1","empl2","empl3")
> c1 = c("HR", "Finance", "HR")
>  c2 = c("x", "y", "z")
>  c3 = c("a","b","C")
>  df1 = data.frame(emplid, c1, c2, c3)

df2:
>  job = c("job1", "job2", "job3", "job4")
>  c4 = c("HR", "HR", "Finance", "Finance")
>  c5 = c("x", "x", "y", "z")
>  c6 = c("a","b", "b","c")
>  df2 = data.frame(job, c4, c5, c6)

The result would be

emplid      job          c4     c5        c6
empl1       job1         HR      x        a
empl3       job4         Finance y        b

The above result could be combined, but ultimately I will split it up.

I've only successfully been able to do this when I have only one row in the first dataframe, but that will not be the case. I've tried loops but with no success.

Body:
Here is a data.table solution.

df1[df2, on = c(c1="c4", c2="c5",c3="c6"),nomatch=0]


问:
OnListenerCOnnected in NotificationListenerService not being called
My app only does not work on Huawei and on other phones it does. Why???
I have that code in my MainActivity:
        package pl.ct8.wieprzco.wieprzwatch;

```<code>public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
    startActivity(intent);
    startService(new Intent(this,NotificationGetService.class));
}
</code>```

}

And that simple code in NotificationGetService class:

```<code>public class NotificationGetService extends NotificationListenerService{
SharedPreferences sharedPreferences;
SharedPreferences.Editor spEditor;

@Override
public void onCreate(){
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    spEditor = sharedPreferences.edit();
    Log.e("jej","swiat powiadomien");
    super.onCreate();
}

@Override
public void onListenerConnected(){
    super.onListenerConnected();
    Log.e("startCommand","yeah");
}

@Override
public int onStartCommand(Intent intent,int flags, int startId){
    Log.e("startCommand","yes");
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onNotificationPosted(StatusBarNotification sbn){
    super.onNotificationPosted(sbn);
    spEditor.putInt("notificationCount",sharedPreferences.getInt("notificationCount",0)+1);
    spEditor.apply();
    Log.e("ADDED","YESSSSSS");

}

@Override
public void onNotificationRemoved(StatusBarNotification sbn){
    super.onNotificationRemoved(sbn);
    spEditor.putInt("notificationCount",sharedPreferences.getInt("notificationCount",1)-1);
    spEditor.apply();
    Log.e("REMOVED","YESSSSSS");
}
</code>```

}

That is my manifest:

```<code><?xml version="1.0" encoding="utf-8"?>
</code>```

```<code><uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <service android:name=".UpdateTimeService"/>
    <service android:name=".NotificationGetService"
        android:label="@string/service_name"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
    </service>
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>
</code>```

And it logs onCreate and onStartCommand, but no onListenerConnected or other. Please help i try to do that so much time.
Very thanks John!!

答:
Maybe it's just because you typed in the wrong tag for loggin?

In your snippet:

```<code>@Override
public void onListenerConnected(){
    super.onListenerConnected();
    Log.e("startCommand","yeah");
}

@Override
public int onStartCommand(Intent intent,int flags, int startId){
    Log.e("startCommand","yes");
    return super.onStartCommand(intent, flags, startId);
}
</code>```

These two Log.e() calls both have tag "startCommand"...

Just in case relevant: the NotificationListernerService.onBind() method shouldn't be overridden... Overridding it will prevent onListenerConnected() from being called...

Body:
My app only does not work on Huawei and on other phones it does. Why???
I have that code in my MainActivity:
        package pl.ct8.wieprzco.wieprzwatch;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent=new Intent("android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
    startActivity(intent);
    startService(new Intent(this,NotificationGetService.class));
}

}

And that simple code in NotificationGetService class:

public class NotificationGetService extends NotificationListenerService{
SharedPreferences sharedPreferences;
SharedPreferences.Editor spEditor;

@Override
public void onCreate(){
    sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    spEditor = sharedPreferences.edit();
    Log.e("jej","swiat powiadomien");
    super.onCreate();
}

@Override
public void onListenerConnected(){
    super.onListenerConnected();
    Log.e("startCommand","yeah");
}

@Override
public int onStartCommand(Intent intent,int flags, int startId){
    Log.e("startCommand","yes");
    return super.onStartCommand(intent, flags, startId);
}

@Override
public void onNotificationPosted(StatusBarNotification sbn){
    super.onNotificationPosted(sbn);
    spEditor.putInt("notificationCount",sharedPreferences.getInt("notificationCount",0)+1);
    spEditor.apply();
    Log.e("ADDED","YESSSSSS");

}

@Override
public void onNotificationRemoved(StatusBarNotification sbn){
    super.onNotificationRemoved(sbn);
    spEditor.putInt("notificationCount",sharedPreferences.getInt("notificationCount",1)-1);
    spEditor.apply();
    Log.e("REMOVED","YESSSSSS");
}

}

That is my manifest:

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

<uses-permission android:name="android.permission.READ_CALL_LOG" />
<uses-permission android:name="android.permission.READ_CONTACTS"/>
<uses-permission android:name="android.permission.INTERNET"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <service android:name=".UpdateTimeService"/>
    <service android:name=".NotificationGetService"
        android:label="@string/service_name"
        android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
    <intent-filter>
        <action android:name="android.service.notification.NotificationListenerService" />
    </intent-filter>
    </service>
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

</application>

And it logs onCreate and onStartCommand, but no onListenerConnected or other. Please help i try to do that so much time.
Very thanks John!!

Body:
Maybe it's just because you typed in the wrong tag for loggin?

In your snippet:

@Override
public void onListenerConnected(){
    super.onListenerConnected();
    Log.e("startCommand","yeah");
}

@Override
public int onStartCommand(Intent intent,int flags, int startId){
    Log.e("startCommand","yes");
    return super.onStartCommand(intent, flags, startId);
}

These two Log.e() calls both have tag "startCommand"...

Just in case relevant: the NotificationListernerService.onBind() method shouldn't be overridden... Overridding it will prevent onListenerConnected() from being called...


问:
Can i reset the selectbox in which i have removed options with Javascript/jQuery?
i am using the following command in a loop

```<code>$("#day option:last").remove();
</code>```

and if the command is executed 2 or 3 times, my selectbox is without some of the options.

So, i need to reset the selectbox as it was in the beginning of the function.

Any help?

答:
I didn't understand the question correctly in the first place.
But then a simple solution would be to use .hide() instead of removing the elements and cloning or keeping an additional copy.
And the reset function would do a .show() on the option elements.

ContentLicense: CC BY-SA 2.5

Body:
i am using the following command in a loop

$("#day option:last").remove();

and if the command is executed 2 or 3 times, my selectbox is without some of the options.

So, i need to reset the selectbox as it was in the beginning of the function.

Any help?


问:
What is (functional) reactive programming?
I've read the Wikipedia article on reactive programming. I've also read the small article on functional reactive programming. The descriptions are quite abstract.

What does functional reactive programming (FRP) mean in practice?

What does reactive programming (as opposed to non-reactive programming?) consist of?

My background is in imperative/OO languages, so an explanation that relates to this paradigm would be appreciated.

答:
FRP is a combination of Functional programming(programming paradigm built upon the idea of everything is a function) and reactive programming paradigm (built upon the idea that everything is a stream(observer and observable philosophy)). It is supposed to be the best of the worlds.

Check out Andre Staltz post on reactive programming to start with.


问:
CSS animate one direction, flip then animate back

I am trying to animate a sailboat to go horizontally from left to right, then flip the boat and animate it back from right to left, then loop.

I've got the right to left going fine. Not sure how to handle the flip and right to left part.

```<code>.sailBoatContainer {
    position: absolute;
    width: 250px;
    animation: move 20s linear infinite;
}

@keyframes move {
    from {
        left: 0;
    }
    to {
        left: 100%;
    }
}

    <div id="sail" class="sailBoatContainer">
    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98 103.18">
        <defs>
            <style>.sail1,.sail5{fill:none;}.sail1{stroke:#e1e1e1;}.sail1,.sail5,.sail6{stroke-linecap:round;}.sail1,.sail6{stroke-linejoin:round;}.sail2,.sail6{fill:#d3dfdd;}.sail3{fill:#f4f4f4;}.sail4{fill:#f1263a;}.sail5{stroke:#ae8863;stroke-miterlimit:10;stroke-width:2px;}.sail6{stroke:#c2ccca;}.sail7{fill:#7f604c;}
            </style>
        </defs>
        <title>sailboat</title>
        <g id="rigging">
            <path id="roperight" class="sail1" d="M1.48,89s37-35.67,50-70.33" transform="translate(-0.48 0)"/>
            <path id="ropeleft" class="sail1" d="M51.48,20.33c16,37.34,46,62.67,46,62.67" transform="translate(-0.48 0)"/>
        </g>
        <g id="cabin">
            <path id="cabinbox" class="sail2" d="M51.48,82v8h27V87s-9-5-12-5ZM62,83.5h4v4H62Zm-6,1h3v3H56Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="sails">
            <path id="sailright" class="sail3" d="M86.48,72s-23-43-33-49c0-1,11,24-4,46C49.48,69,75.48,68,86.48,72Z" transform="translate(-0.48 0)"/>
            <path id="sailleft" class="sail3" d="M48.48,14s-49,35-34,66c0,1,35,0,35,0S44.48,38,48.48,14Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="flag">
            <path class="sail4" d="M52,1.5s-2,2-3,2-8-2-11,0c0,0,6,1,8,4h6Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="mast">
            <line id="mastline" class="sail5" x1="51" y1="88" x2="51" y2="1"/>
        </g>
        <g id="hull">
            <path id="hullbox" class="sail6" d="M90,101.5s-78,4-89-4v-9s79,2,97-6C97,83.5,99,90.5,90,101.5Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="hullbottom">
            <path id="hullbottombox" class="sail7" d="M91.87,99.88S21.5,104,.5,97v2s8.73,6.94,89.73,2.94Z" transform="translate(-0.48 0)"/>
        </g>
    </svg>
</div>
</code>```

Here is a Codpen

I'd appreciate it if someone could point me in the right direction.

答:
you can use keyframes like this in animation</p>

```<code>@keyframes move
{
  0%   {
    left: 0;
  }
    50%   {
    left: 100%;
  }
    100%   {
    left: 0%;
  }
}
</code>```

Body:
I am trying to animate a sailboat to go horizontally from left to right, then flip the boat and animate it back from right to left, then loop.

I've got the right to left going fine. Not sure how to handle the flip and right to left part.

.sailBoatContainer {
    position: absolute;
    width: 250px;
    animation: move 20s linear infinite;
}

@keyframes move {
    from {
        left: 0;
    }
    to {
        left: 100%;
    }
}

    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 98 103.18">
        <defs>

        </defs>
        <title>sailboat</title>
        <g id="rigging">
            <path id="roperight" class="sail1" d="M1.48,89s37-35.67,50-70.33" transform="translate(-0.48 0)"/>
            <path id="ropeleft" class="sail1" d="M51.48,20.33c16,37.34,46,62.67,46,62.67" transform="translate(-0.48 0)"/>
        </g>
        <g id="cabin">
            <path id="cabinbox" class="sail2" d="M51.48,82v8h27V87s-9-5-12-5ZM62,83.5h4v4H62Zm-6,1h3v3H56Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="sails">
            <path id="sailright" class="sail3" d="M86.48,72s-23-43-33-49c0-1,11,24-4,46C49.48,69,75.48,68,86.48,72Z" transform="translate(-0.48 0)"/>
            <path id="sailleft" class="sail3" d="M48.48,14s-49,35-34,66c0,1,35,0,35,0S44.48,38,48.48,14Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="flag">
            <path class="sail4" d="M52,1.5s-2,2-3,2-8-2-11,0c0,0,6,1,8,4h6Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="mast">
            <line id="mastline" class="sail5" x1="51" y1="88" x2="51" y2="1"/>
        </g>
        <g id="hull">
            <path id="hullbox" class="sail6" d="M90,101.5s-78,4-89-4v-9s79,2,97-6C97,83.5,99,90.5,90,101.5Z" transform="translate(-0.48 0)"/>
        </g>
        <g id="hullbottom">
            <path id="hullbottombox" class="sail7" d="M91.87,99.88S21.5,104,.5,97v2s8.73,6.94,89.73,2.94Z" transform="translate(-0.48 0)"/>
        </g>
    </svg>

Here is a Codpen

I'd appreciate it if someone could point me in the right direction.

Body:
you can use keyframes like this in animation

@keyframes move
{
  0%   {
    left: 0;
  }
    50%   {
    left: 100%;
  }
    100%   {
    left: 0%;
  }
}


问:
If I don't specify a datacenter in keyspace creation will data not reside on those nodes
Here is the scenario:
We have two data centers in a production cluster: one PROD and the other DR.

We create keyspaces that replicate to both data centers. No issues there. Here's the thought/question:

If we want to put/create a Prod-like environment (PL - which is a replica of production) that utilizes the existing servers - BUT - not affect production, my thought is create a new keyspace, but only specifying the DR datacenter in the CREATE KEYSPACE command. We want to be sure that data is not propagated from the DR datacenter to the PROD data center thus affecting its storage and performance. I believe this will do what I think, which means that the data will stay only on the DR datacenter thus leaving production alone. Anyone see any issues with this?

Essentially this:

```<code>CREATE KEYSPACE PL_KS WITH replication =
    {'class': 'NetworkTopologyStrategy', 'DR': '2'}  AND durable_writes = true;
</code>```

When PL transactions/queries execute against the PL keyspace, the drivers should be smart enough as well to not connect them to the production nodes, correct? So in essence, all PL activities should be against the DR datacenter nodes.

答:
Your assumptions are correct.  With only specifying replication to the DR data center with the PL_KS keyspace, only the nodes in the DR data center will be used.

The only exception to this, would be if the endpoints defined in your app code are in your PROD data center.  Then the app would use the PROD data center nodes for initial discovery only, and all forthcoming operations would be run against the DR nodes.

Body:
Here is the scenario:
We have two data centers in a production cluster: one PROD and the other DR.

We create keyspaces that replicate to both data centers. No issues there. Here's the thought/question:

If we want to put/create a Prod-like environment (PL - which is a replica of production) that utilizes the existing servers - BUT - not affect production, my thought is create a new keyspace, but only specifying the DR datacenter in the CREATE KEYSPACE command. We want to be sure that data is not propagated from the DR datacenter to the PROD data center thus affecting its storage and performance. I believe this will do what I think, which means that the data will stay only on the DR datacenter thus leaving production alone. Anyone see any issues with this?

Essentially this:

CREATE KEYSPACE PL_KS WITH replication =
    {'class': 'NetworkTopologyStrategy', 'DR': '2'}  AND durable_writes = true;

When PL transactions/queries execute against the PL keyspace, the drivers should be smart enough as well to not connect them to the production nodes, correct? So in essence, all PL activities should be against the DR datacenter nodes.


问:
Hide url parameters from php
```<code><a href="rate.php?winner=<?=$images[0]->image_id?>&loser=<?=$images[1]->image_id?>"></a>
</code>```

This is main page index.php

This was my main page. Before uploading to php file parameters can be changed using inspect element and this is a problem.

This is rate.php

```<code><?php

include('mysql.php');
include('functions.php');

// If rating - update the database
if ($_GET['winner'] && $_GET['loser']) {

// Get the winner
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['winner']." ");
$winner = $result->fetch_object();

// Get the loser
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['loser']." ");
$loser = $result->fetch_object();

// Update the winner score
$winner_expected = expected($loser->score, $winner->score);
$winner_new_score = win($winner->score, $winner_expected);
    //test print "Winner: ".$winner->score." - ".$winner_new_score." - ".$winner_expected."<br>";
$conn->query("UPDATE images SET score = ".$winner_new_score.", wins = wins+1 WHERE image_id = ".$_GET['winner']);

// Update the loser score
$loser_expected = expected($winner->score, $loser->score);
$loser_new_score = loss($loser->score, $loser_expected);
    //test print "Loser: ".$loser->score." - ".$loser_new_score." - ".$loser_expected."<br>";
$conn->query("UPDATE images SET score = ".$loser_new_score.", losses = losses+1  WHERE image_id = ".$_GET['loser']);

// Insert battle
$conn->query("INSERT INTO battles SET winner = ".$_GET['winner'].", loser = ".$_GET['loser']." ");

// Back to the frontpage
header('location: /');

}

?>
</code>```

I just want that parameters can be modified while sending data to php file

答: I suggest you to use $_POST instead of $_GET and add some validations on your images ids in your rate.php. Add a jQuery click function to your  in your html and within the anonymous function of the click, create winner_image_id and loser_image_id variables and send them to your php by using AJAX.

Title: Hide url parameters from php

Body:
<a href="rate.php?winner=<?=$images[0]->image_id?>&loser=<?=$images[1]->image_id?>">

This is main page index.php

This was my main page. Before uploading to php file parameters can be changed using inspect element and this is a problem.

This is rate.php

<?php

include('mysql.php');
include('functions.php');

// If rating - update the database
if ($_GET['winner'] && $_GET['loser']) {

// Get the winner
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['winner']." ");
$winner = $result->fetch_object();

// Get the loser
$result = $conn->query("SELECT * FROM images WHERE image_id = ".$_GET['loser']." ");
$loser = $result->fetch_object();

// Update the winner score
$winner_expected = expected($loser->score, $winner->score);
$winner_new_score = win($winner->score, $winner_expected);
    //test print "Winner: ".$winner->score." - ".$winner_new_score." - ".$winner_expected."
";
$conn->query("UPDATE images SET score = ".$winner_new_score.", wins = wins+1 WHERE image_id = ".$_GET['winner']);

// Update the loser score
$loser_expected = expected($winner->score, $loser->score);
$loser_new_score = loss($loser->score, $loser_expected);
    //test print "Loser: ".$loser->score." - ".$loser_new_score." - ".$loser_expected."
";
$conn->query("UPDATE images SET score = ".$loser_new_score.", losses = losses+1  WHERE image_id = ".$_GET['loser']);

// Insert battle
$conn->query("INSERT INTO battles SET winner = ".$_GET['winner'].", loser = ".$_GET['loser']." ");

// Back to the frontpage
header('location: /');

}

?>

I just want that parameters can be modified while sending data to php file

Body: I suggest you to use $_POST instead of $_GET and add some validations on your images ids in your rate.php. Add a jQuery click function to your <a> in your html and within the anonymous function of the click, create winner_image_id and loser_image_id variables and send them to your php by using AJAX.


问:
Fill in a ArrayList within a configuration jelly file for a Jenkins Plugin
I have a problem when trying to implement the configuration file of my plugin.
I started my program with the already existing SideBar Plugin, but I encountered a problem when I added a List<String> as a variable to the class Action : private List<String> projects;
How can I fill such a list within the jelly file?

I tried doing as such :

```<code><f:entry>
 <f:optionalBlock title="Project to be considered :">
  <f:repeatable var="project" items="${link.projects}" name="projects" add="Add a project">
   <f:entry title="Project 1 :">
   </f:entry>
  </f:repeatable>
 </f:optionalBlock>
</f:entry>
</code>```

I added these lines in the links.jelly file, but it doesn't work.

If anyone knows how to do this, it would be great.

Thank you

答:
I fixed similar problem this way:

```<code><f:entry title="Parameters" field="projects">
   <f:repeatableProperty field="projects"  minimum="1" />
</f:entry>
</code>```

Thanks to this resource

Body:
I have a problem when trying to implement the configuration file of my plugin.
I started my program with the already existing SideBar Plugin, but I encountered a problem when I added a List<String> as a variable to the class Action : private List<String> projects;
How can I fill such a list within the jelly file?

I tried doing as such :

<f:entry>
 <f:optionalBlock title="Project to be considered :">
  <f:repeatable var="project" items="${link.projects}" name="projects" add="Add a project">
   <f:entry title="Project 1 :">
   </f:entry>
  </f:repeatable>
 </f:optionalBlock>
</f:entry>

I added these lines in the links.jelly file, but it doesn't work.

If anyone knows how to do this, it would be great.

Thank you

Body:
I fixed similar problem this way:

<f:entry title="Parameters" field="projects">
   <f:repeatableProperty field="projects"  minimum="1" />
</f:entry>

Thanks to this resource


问:
JExcel Output Issues
I'm trying to write out to an Excel Sheet in Java using JExcel.  I successfully write out, however I keep running into the "java.lang.OutOfMemory: Java heap space" error.  From what I've read there are two solutions.

1) Change My Eclipse settings, which I have done and seems to have not made a difference.

My settings are as follows, please let me know if anything looks wrong (Upped Xmx and added the last line):

```<code>-XX:MaxPermSize=256m
-Xms128m
-Xmx2048m
-XX:+UseParallelGC
</code>```

2) Close the workbook to flush output, then reopen and append the next line or group of lines.

This I cannot figure out since I can't find any documentation on it.  When I close my WritableWorkbook (named wwb), I'm not sure how to open it.  I end up writing out one line and then getting a Null error since wwb is closed.

Thanks for all the help in advance.

答: I ended up switching to SuperCSV, works great. I had also tried OpenCSV, however it does not escape commas properly</p>

Title: JExcel Output Issues

Body:
I'm trying to write out to an Excel Sheet in Java using JExcel.  I successfully write out, however I keep running into the "java.lang.OutOfMemory: Java heap space" error.  From what I've read there are two solutions.

1) Change My Eclipse settings, which I have done and seems to have not made a difference.

My settings are as follows, please let me know if anything looks wrong (Upped Xmx and added the last line):

-XX:MaxPermSize=256m
-Xms128m
-Xmx2048m
-XX:+UseParallelGC

2) Close the workbook to flush output, then reopen and append the next line or group of lines.

This I cannot figure out since I can't find any documentation on it.  When I close my WritableWorkbook (named wwb), I'm not sure how to open it.  I end up writing out one line and then getting a Null error since wwb is closed.

Thanks for all the help in advance.


问:
Error in if (any(co)) { : missing value where TRUE/FALSE needed In addition: Warning messages: 1: In FUN(newX[, i], ...) : NAs introduced by coercion
I am working with a dataset that has approximately 150000 rows and 25 columns. The data consist of numerical and factor variables. Factor variables are both text and numbers and I need all of them. The depended variable is a factor with 20 levels.
I am trying to build a model and feed it into a SVM using the kernlab package in R.

```<code>library(kernlab)
n<- nrow(x)
trainInd<- sort(sample(1:nrow(x), n*.8))
xtrain<- x[trainInd,]
xtest<- x[-trainInd,]
ytrain<- y[trainInd]
ytest<- y[-trainInd]
modelclass<- ksvm(x=as.matrix(xtrain), y=as.matrix(ytrain),
              scaled = TRUE, type="C-svc", kernel = "rbfdot",
              kpar="automatic", C=1, cross=0)
</code>```

Following the code, I get this error:

```<code>Error in if (any(co)) { : missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In FUN(newX[, i], ...) : NAs introduced by coercion
</code>```

The xtrain data frame looks like:

```<code>Length    Gender    Age    Day    Hour     Duration    Period
  5         1       80      5      11         20          3
 0.2        2       35      2      18         10          5
 1.1        2       55      1      15         120         4
</code>```

The Gender, Day, and Period variables are categorical (factors), where the rest is numerical.

I have gone through similar questions and been through my dataset as well, but I cannot identify any NA values or other mistakes.

I assume that I am doing something wrong with variable types, and particular the factors. I am unsure of how to use them, but I can't see something wrong.
Any help of how to solve the error and possibly how to model factor together with numerical variables would be appreciated.

答:
I had the same problem with e1071 package in R. I solved it changing all variables to numeric instead of factor, except the decision variable (y), which can be either a factor (for classification tasks) or a numeric (for regression).

References:

CRAN Package 'e1071'

Body:
I am working with a dataset that has approximately 150000 rows and 25 columns. The data consist of numerical and factor variables. Factor variables are both text and numbers and I need all of them. The depended variable is a factor with 20 levels.
I am trying to build a model and feed it into a SVM using the kernlab package in R.

library(kernlab)
n<- nrow(x)
trainInd<- sort(sample(1:nrow(x), n*.8))
xtrain<- x[trainInd,]
xtest<- x[-trainInd,]
ytrain<- y[trainInd]
ytest<- y[-trainInd]
modelclass<- ksvm(x=as.matrix(xtrain), y=as.matrix(ytrain),
              scaled = TRUE, type="C-svc", kernel = "rbfdot",
              kpar="automatic", C=1, cross=0)

Following the code, I get this error:

Error in if (any(co)) { : missing value where TRUE/FALSE needed
In addition: Warning messages:
1: In FUN(newX[, i], ...) : NAs introduced by coercion

The xtrain data frame looks like:

Length    Gender    Age    Day    Hour     Duration    Period
  5         1       80      5      11         20          3
 0.2        2       35      2      18         10          5
 1.1        2       55      1      15         120         4

The Gender, Day, and Period variables are categorical (factors), where the rest is numerical.

I have gone through similar questions and been through my dataset as well, but I cannot identify any NA values or other mistakes.

I assume that I am doing something wrong with variable types, and particular the factors. I am unsure of how to use them, but I can't see something wrong.
Any help of how to solve the error and possibly how to model factor together with numerical variables would be appreciated.


问:
Effect after hover animation
I'm doing this on codepen for freecodecamp challenger and I want to see my button's animation after hover effect. Does anyone know the solution for this?  Maybe I did something wrong in the code. Here my code for the button #random.
I did the reverse animation and then I put it in #random but it doesn't work.

body{
  background-color:black;
}
.message{
  margin: auto;
    width: 50%;
  padding:20px;
  margin: auto;
  width: 50%;
  margin-top:70px;
}
h2{
  margin:auto;
  width:90%;
  margin-top: 5px;
  margin-bottom: 5px;
  color:white;
  text-transform: uppercase;
}
#random{
  background:black;
  border:1px solid;
  width: 200px;
  height: 50px;
  margin: -20px -50px;
  position:absolute;
  top:50%;
  right:10%;
  color:#595959;
  animation: reverse 0.6s;
  animation-fill-mode: forwards;
}
#random:hover{
  background:black;
  border:1px solid;
  width: 200px;
  height: 50px;
  margin: -20px -50px;
  position:absolute;
  top:50%;
  right:10%;
  animation: clickmes 0.6s;
  animation-fill-mode: forwards;
}
@keyframes clickmes {
    0% {
        color: #595959;
    }
    25% {
        color: #707070;
    }
    50% {
        color: #a3a3a3;
    }
    100% {
        color: white;
    }
}
 @keyframes reverse {
    0% {
        color: white;
    }
    25% {
        color: #a3a3a3;
    }
    50% {
        color: #707070;
    }
    100% {
        color: #595959;
    }
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <div id="social">

    </div>
  <div id="where1" class="message"><h2>I need random quotes from Api here.</h2>
    <h4></h4>
</div>

<button id="random">I'm a button</button></code>```

答:
I am not sure if a css animation is required for this, but if not I would use a transition instead. Transitions are much easier to control for things that aren't too complicated. Please see my snippet below.

body {
  background: #000000;
}
#random {
  background:black;
  border:1px solid;
  width: 200px;
  height: 50px;
  margin: -20px -50px;
  position:absolute;
  top:50%;
  right:10%;
  color:#595959;
  transition: color .5s ease;
 }

 #random:hover {
  color: #ffffff;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button type="button" id="random">Button Text</button></code>```

You can also read more about how transitions work here.

Title: Effect after hover animation

Body:
I'm doing this on codepen for freecodecamp challenger and I want to see my button's animation after hover effect. Does anyone know the solution for this?  Maybe I did something wrong in the code. Here my code for the button #random.
I did the reverse animation and then I put it in #random but it doesn't work.

body{
  background-color:black;
}
.message{
  margin: auto;
    width: 50%;
  padding:20px;
  margin: auto;
  width: 50%;
  margin-top:70px;
}
h2{
  margin:auto;
  width:90%;
  margin-top: 5px;
  margin-bottom: 5px;
  color:white;
  text-transform: uppercase;
}
#random{
  background:black;
  border:1px solid;
  width: 200px;
  height: 50px;
  margin: -20px -50px;
  position:absolute;
  top:50%;
  right:10%;
  color:#595959;
  animation: reverse 0.6s;
  animation-fill-mode: forwards;
}
#random:hover{
  background:black;
  border:1px solid;
  width: 200px;
  height: 50px;
  margin: -20px -50px;
  position:absolute;
  top:50%;
  right:10%;
  animation: clickmes 0.6s;
  animation-fill-mode: forwards;
}
@keyframes clickmes {
    0% {
        color: #595959;
    }
    25% {
        color: #707070;
    }
    50% {
        color: #a3a3a3;
    }
    100% {
        color: white;
    }
}
 @keyframes reverse {
    0% {
        color: white;
    }
    25% {
        color: #a3a3a3;
    }
    50% {
        color: #707070;
    }
    100% {
        color: #595959;
    }
 }

I need random quotes from Api here.

<button id="random">I'm a button</button>

Body:
I am not sure if a css animation is required for this, but if not I would use a transition instead. Transitions are much easier to control for things that aren't too complicated. Please see my snippet below.

body {
  background: #000000;
}
#random {
  background:black;
  border:1px solid;
  width: 200px;
  height: 50px;
  margin: -20px -50px;
  position:absolute;
  top:50%;
  right:10%;
  color:#595959;
  transition: color .5s ease;
 }

 #random:hover {
  color: #ffffff;
 }

<button type="button" id="random">Button Text</button>

You can also read more about how transitions work here.


问:
JSF and EJB together in one app using Intellij
I would like to create JSF and EJB modules but I have no clue how to connect them together or how to create EAR. At the moment I know how to create JSF application but what should I do next? Create EJB module with DAO and enities? Or create DAO and entities in JSF application?

Thanks for help

答:
You should start reading the help manual:
https://www.jetbrains.com/help/idea/developing-a-java-ee-application.html</p>


问:
How to check if a value doesn't exist in one or more arrays inside array of arrays?
I need to write a function that returns true if a value exists in a multidimensional array and false if the value doesn't exist in atleast one array in the multidimensional array.</p>

```<code>    function isItemOmnipresent (arrayOfArrays, item) {

     var arrays = arrayOfArrays;
     var itemCheck = item;

     for(var i = 0; i < arrays.length; i++){
      for(var j = 0; j < arrays[i].length; j++){
       if(arrays[i][j] == itemCheck) {
         return true;
      } else {
         return false;
      }
    }
  }
</code>```

答:
Much like "There's an App for that!" - typically "There's a Method for that!" if you look hard enough and this is the case for your issue. You can use the .some method of an Array to determine if anything within meets the required value.

We set a flag called inArrays to keep track if the returned value of the some function is ever true and return it at the end of our function call.

```<code>function isItemPresent(OuterArr, item) {
  let inArrays = false;

  for (let InnerArr of OuterArr) {
    if(InnerArr.some(array_item => array_item === item)) {
    inArrays = true;
    }
  }
  return inArrays;
}
</code>```

let _2dArr = [
  [1, 2, 3, 4],
  [6, 7, 8, 9]
];

function isItemPresent(OuterArr, item) {
  let inArrays = false;

  for (let InnerArr of OuterArr) {
    if(InnerArr.some(array_item => array_item === item)) {
    inArrays = true;
    }
  }
  return inArrays;
}

console.log(isItemPresent(_2dArr, 3));
console.log(isItemPresent(_2dArr, 5));```
</div>
</div>
</p>

<p><strong>ES5/IE</strong></p>

<p>Here's an IE/ES5 Friendly Version if you're worried about that sort of thing</p>

```function isItemPresent(OuterArr, item) {
  var inArrays = false;

  for (InnerArr = 0; InnerArr < OuterArr.length; InnerArr++) {
    if(OuterArr[InnerArr].some(function(array_item) { return array_item === item; })) {
    inArrays = true;
    }
  }
  return inArrays;
}
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var _2dArr = [
  [1, 2, 3, 4],
  [6, 7, 8, 9]
];

function isItemPresent(OuterArr, item) {
  var inArrays = false;

  for (InnerArr = 0; InnerArr < OuterArr.length; InnerArr++) {
    if(OuterArr[InnerArr].some(function(array_item) { return array_item === item; })) {
    inArrays = true;
    }
  }
  return inArrays;
}

console.log(isItemPresent(_2dArr, 3));
console.log(isItemPresent(_2dArr, 5));</code>```

Body:
I need to write a function that returns true if a value exists in a multidimensional array and false if the value doesn't exist in atleast one array in the multidimensional array.

    function isItemOmnipresent (arrayOfArrays, item) {

     var arrays = arrayOfArrays;
     var itemCheck = item;

     for(var i = 0; i < arrays.length; i++){
      for(var j = 0; j < arrays[i].length; j++){
       if(arrays[i][j] == itemCheck) {
         return true;
      } else {
         return false;
      }
    }
  }

Body:
Much like "There's an App for that!" - typically "There's a Method for that!" if you look hard enough and this is the case for your issue. You can use the .some method of an Array to determine if anything within meets the required value.

We set a flag called inArrays to keep track if the returned value of the some function is ever true and return it at the end of our function call.

function isItemPresent(OuterArr, item) {
  let inArrays = false;

  for (let InnerArr of OuterArr) {
    if(InnerArr.some(array_item => array_item === item)) {
    inArrays = true;
    }
  }
  return inArrays;
}

let _2dArr = [
  [1, 2, 3, 4],
  [6, 7, 8, 9]
];

function isItemPresent(OuterArr, item) {
  let inArrays = false;

  for (let InnerArr of OuterArr) {
    if(InnerArr.some(array_item => array_item === item)) {
    inArrays = true;
    }
  }
  return inArrays;
}

console.log(isItemPresent(_2dArr, 3));
console.log(isItemPresent(_2dArr, 5));

ES5/IE

Here's an IE/ES5 Friendly Version if you're worried about that sort of thing

function isItemPresent(OuterArr, item) {
  var inArrays = false;

  for (InnerArr = 0; InnerArr < OuterArr.length; InnerArr++) {
    if(OuterArr[InnerArr].some(function(array_item) { return array_item === item; })) {
    inArrays = true;
    }
  }
  return inArrays;
}

var _2dArr = [
  [1, 2, 3, 4],
  [6, 7, 8, 9]
];

function isItemPresent(OuterArr, item) {
  var inArrays = false;

  for (InnerArr = 0; InnerArr < OuterArr.length; InnerArr++) {
    if(OuterArr[InnerArr].some(function(array_item) { return array_item === item; })) {
    inArrays = true;
    }
  }
  return inArrays;
}

console.log(isItemPresent(_2dArr, 3));
console.log(isItemPresent(_2dArr, 5));


答:
I would suggest using the .clone() http://api.jquery.com/clone/method of jQuery, to hold a copy of your drop down list, and you can either replace the list when you want to reset the values, or you could iterate through the values in the copy and add them to the existing dropdownlist.

Here is a sample using clone in jQuery that does what I explained above.

```<code><html>
<head>
<script src="jquery.js" type="text/javascript">
</script>
<script>

$(document).ready(function(){
//clone the select list
var optionlist = $("#options").clone();

//add the remove function event handler to a link
$("#remove").click(function(){

$("#options option:last").remove();

return false; //don't refresh the page

});

// add the reset click event handler to the reset link
$("#reset").click(function(){

//replace the select list with the original clone
$("#options").replaceWith(optionlist);

//clone the new list into the original optionlist variable
optionlist = $("#options").clone;

return false; //don't refresh

});

});

</script>
</head>
<body>
<select id="options" multiple="true" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<a id="remove" href="#" >remove</a>
<a id="reset" href="#">reset</a>
</body>
</html>
</code>```

Title: Can i reset the selectbox in which i have removed options with Javascript/jQuery?

Body:
I would suggest using the .clone() http://api.jquery.com/clone/method of jQuery, to hold a copy of your drop down list, and you can either replace the list when you want to reset the values, or you could iterate through the values in the copy and add them to the existing dropdownlist.

Here is a sample using clone in jQuery that does what I explained above.

<html>
<head>
<script src="jquery.js" type="text/javascript">
</script>
<script>

$(document).ready(function(){
//clone the select list
var optionlist = $("#options").clone();

//add the remove function event handler to a link
$("#remove").click(function(){

$("#options option:last").remove();

return false; //don't refresh the page

});

// add the reset click event handler to the reset link
$("#reset").click(function(){

//replace the select list with the original clone
$("#options").replaceWith(optionlist);

//clone the new list into the original optionlist variable
optionlist = $("#options").clone;

return false; //don't refresh

});

});

</script>
</head>
<body>
<select id="options" multiple="true" >
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<a id="remove" href="#" >remove</a>
<a id="reset" href="#">reset</a>
</body>
</html>


问:
The difference between Reactive and Functional-Reactive programming
I have been doing some research into reactive programming recently and I'm finding it hard to find a good description of the difference between Reactive and Functional-Reactive.

Is it simply that the reactive programming is implemented using functional methods/paradigms as opposed to using declarative or OO paradigms?

答:
FRP is a combination of Functional programming(programming paradigm built upon the idea of everything is a pure function) and reactive programming paradigm (built upon the idea that everything is a stream(observer and observable philosophy)). It is suppose to be the best of both the worlds.

The definition of both give a more clear distinction between the two.


问:
Difference between now and future date as x day , y hours , z minutes via php Carbon
I'm using laravel 5.5 and Carbon DateTime Library and have a future date and want to display difference between that time and Now.

But note that I want to display differences as this format :

```<code>x day , y hours , z minutes
</code>```

that shows how many days, hours and minutes is left to that future date

答:
You can read the documentation here regarding everything with difference between dates:

PHP Date difference

Body:
I'm using laravel 5.5 and Carbon DateTime Library and have a future date and want to display difference between that time and Now.

But note that I want to display differences as this format :

x day , y hours , z minutes

that shows how many days, hours and minutes is left to that future date


问:
Export large time series in Google Earth Engine
How can I export large time series of a specific region? The idea is to get a table with the Date and the average band value for this region. In this case it would be the mean NDVI of a region.

```<code>var collectionModNDVI = ee.ImageCollection('MODIS/006/MOD13Q1')
        .filterDate('2002-01-01', '2017-11-17');
</code>```

In the case of a single point time serie it would be

```<code>var geom = ee.Geometry.Point(-1,40).buffer(250);

print(ui.Chart.image.series(collectionModNDVI, geom, ee.Reducer.mean(), 30));
</code>```

This is working well and you get a chart where you can download the time serie in csv. But when it is a large region, I get issues with the memory and computation time.

```<code>var table2 = ee.Geometry.Rectangle(-1,40,0,41);

chart = ui.Chart.image.seriesByRegion(collectionModNDVI,table2,
       ee.Reducer.mean(), 'NDVI',30, 'system:time_start', 'label');

print(chart);
</code>```

Using this code I got the following error "User memory limit exceeded".

I also tried this:

```<code>Export.table.toDrive({
  collection: chart,
  description:'vectorsToDriveExample',
  fileFormat: 'csv'
});
</code>```

But I got the same error and "d.yc is not a function".

答:
You need to provide more information about how you want the table formatted.  Here is an example of two ways of exporting a single band to get you started:

```<code>var roi = /* color: #d63000 */ee.Geometry.Polygon(
        [[[-122.27577209472656, 37.891247253777074],
          [-122.27577209472656, 37.86875557241152],
          [-122.24040985107422, 37.86875557241152],
          [-122.24040985107422, 37.891247253777074]]], null, false);

// Load imagery.
var l8 = ee.ImageCollection('LANDSAT/LC8_SR')
    .filterBounds(roi)
    .filterDate('2016-01-01', '2016-12-31')
    .map(function(image) {
      var qa = image.select('cfmask');
      var mask = qa.neq(2).and(qa.neq(4));
      return image.updateMask(mask).divide(10000);
    });
print('Size of Landsat collection', l8.size()); // 21

// Load an Earth Engine table.
var blocks = ee.FeatureCollection('TIGER/2010/Blocks');
var subset = blocks.filterBounds(roi);
print('Size of Census blocks subset', subset.size()); // 409

Map.centerObject(roi, 13);
Map.addLayer(blocks, {color: 'gray'}, 'blocks');
Map.addLayer(subset, {}, 'subset');

// Collect block, image, value triplets.
var triplets = l8.map(function(image) {
  return image.select('B1').reduceRegions({
    collection: subset.select(['blockid10']),
    reducer: ee.Reducer.mean(),
    scale: 30
  }).filter(ee.Filter.neq('mean', null))
    .map(function(f) {
      return f.set('imageId', image.id());
    });
}).flatten();
print(triplets.first());

// Format a table of triplets into a 2D table of rowId x colId.
var format = function(table, rowId, colId) {
  // Get a FeatureCollection with unique row IDs.
  var rows = table.distinct(rowId);
  // Join the table to the unique IDs to get a collection in which
  // each feature stores a list of all features having a common row ID.
  var joined = ee.Join.saveAll('matches').apply({
    primary: rows,
    secondary: table,
    condition: ee.Filter.equals({
      leftField: rowId,
      rightField: rowId
    })
  });

  return joined.map(function(row) {
      // Get the list of all features with a unique row ID.
      var values = ee.List(row.get('matches'))
        // Map a function over the list of rows to return a list of
        // column ID and value.
        .map(function(feature) {
          feature = ee.Feature(feature);
          return [feature.get(colId), feature.get('mean')];
        });
      // Return the row with its ID property and properties for
      // all matching columns IDs storing the output of the reducer.
      // The Dictionary constructor is using a list of key, value pairs.
      return row.select([rowId]).set(ee.Dictionary(values.flatten()));
    });
};

var link = '78503bfa1fb76b3a9fa06b515d1e2488';

var table1 = format(triplets, 'imageId', 'blockid10');

var desc1 = 'table1_demo_' + link;
Export.table.toDrive({
  collection: table1,
  description: desc1,
  fileNamePrefix: desc1,
  fileFormat: 'CSV'
});

var table2 = format(triplets, 'blockid10', 'imageId');

var desc2 = 'table2_demo_' + link;
Export.table.toDrive({
  collection: table2,
  description: desc2,
  fileNamePrefix: desc2,
  fileFormat: 'CSV'
});
</code>```

That example is from this presentation, linked from this page.

Body:
How can I export large time series of a specific region? The idea is to get a table with the Date and the average band value for this region. In this case it would be the mean NDVI of a region.

var collectionModNDVI = ee.ImageCollection('MODIS/006/MOD13Q1')
        .filterDate('2002-01-01', '2017-11-17');

In the case of a single point time serie it would be

var geom = ee.Geometry.Point(-1,40).buffer(250);

print(ui.Chart.image.series(collectionModNDVI, geom, ee.Reducer.mean(), 30));

This is working well and you get a chart where you can download the time serie in csv. But when it is a large region, I get issues with the memory and computation time.

var table2 = ee.Geometry.Rectangle(-1,40,0,41);

chart = ui.Chart.image.seriesByRegion(collectionModNDVI,table2,
       ee.Reducer.mean(), 'NDVI',30, 'system:time_start', 'label');

print(chart);

Using this code I got the following error "User memory limit exceeded".

I also tried this:

Export.table.toDrive({
  collection: chart,
  description:'vectorsToDriveExample',
  fileFormat: 'csv'
});

But I got the same error and "d.yc is not a function".

Body:
You need to provide more information about how you want the table formatted.  Here is an example of two ways of exporting a single band to get you started:

var roi = /* color: #d63000 */ee.Geometry.Polygon(
        [[[-122.27577209472656, 37.891247253777074],
          [-122.27577209472656, 37.86875557241152],
          [-122.24040985107422, 37.86875557241152],
          [-122.24040985107422, 37.891247253777074]]], null, false);

// Load imagery.
var l8 = ee.ImageCollection('LANDSAT/LC8_SR')
    .filterBounds(roi)
    .filterDate('2016-01-01', '2016-12-31')
    .map(function(image) {
      var qa = image.select('cfmask');
      var mask = qa.neq(2).and(qa.neq(4));
      return image.updateMask(mask).divide(10000);
    });
print('Size of Landsat collection', l8.size()); // 21

// Load an Earth Engine table.
var blocks = ee.FeatureCollection('TIGER/2010/Blocks');
var subset = blocks.filterBounds(roi);
print('Size of Census blocks subset', subset.size()); // 409

Map.centerObject(roi, 13);
Map.addLayer(blocks, {color: 'gray'}, 'blocks');
Map.addLayer(subset, {}, 'subset');

// Collect block, image, value triplets.
var triplets = l8.map(function(image) {
  return image.select('B1').reduceRegions({
    collection: subset.select(['blockid10']),
    reducer: ee.Reducer.mean(),
    scale: 30
  }).filter(ee.Filter.neq('mean', null))
    .map(function(f) {
      return f.set('imageId', image.id());
    });
}).flatten();
print(triplets.first());

// Format a table of triplets into a 2D table of rowId x colId.
var format = function(table, rowId, colId) {
  // Get a FeatureCollection with unique row IDs.
  var rows = table.distinct(rowId);
  // Join the table to the unique IDs to get a collection in which
  // each feature stores a list of all features having a common row ID.
  var joined = ee.Join.saveAll('matches').apply({
    primary: rows,
    secondary: table,
    condition: ee.Filter.equals({
      leftField: rowId,
      rightField: rowId
    })
  });

  return joined.map(function(row) {
      // Get the list of all features with a unique row ID.
      var values = ee.List(row.get('matches'))
        // Map a function over the list of rows to return a list of
        // column ID and value.
        .map(function(feature) {
          feature = ee.Feature(feature);
          return [feature.get(colId), feature.get('mean')];
        });
      // Return the row with its ID property and properties for
      // all matching columns IDs storing the output of the reducer.
      // The Dictionary constructor is using a list of key, value pairs.
      return row.select([rowId]).set(ee.Dictionary(values.flatten()));
    });
};

var link = '78503bfa1fb76b3a9fa06b515d1e2488';

var table1 = format(triplets, 'imageId', 'blockid10');

var desc1 = 'table1_demo_' + link;
Export.table.toDrive({
  collection: table1,
  description: desc1,
  fileNamePrefix: desc1,
  fileFormat: 'CSV'
});

var table2 = format(triplets, 'blockid10', 'imageId');

var desc2 = 'table2_demo_' + link;
Export.table.toDrive({
  collection: table2,
  description: desc2,
  fileNamePrefix: desc2,
  fileFormat: 'CSV'
});

That example is from this presentation, linked from this page.


答:
You can clone the select element before you make any changes:

```<code>var copy = $('#day').clone();
</code>```

Later, when you want to restore it, just replace the current select with the old one:

```<code>$('#day').replaceWith(copy);
</code>```

Body:
i am using the following command in a loop

$("#day option:last").remove();

and if the command is executed 2 or 3 times, my selectbox is without some of the options.

So, i need to reset the selectbox as it was in the beginning of the function.

Any help?

Body:
You can clone the select element before you make any changes:

var copy = $('#day').clone();

Later, when you want to restore it, just replace the current select with the old one:

$('#day').replaceWith(copy);


问:
Having trouble in creating new row/ cell with custom labels
Using Swift, My custom cell has 4 labels which I would like to edit when adding the new row/cell to the tableview.

On top of my app in the bar I have an add button which is supposed to add the new cell/row to the table view but only the first one works and when I add a second cell/row it changes and becomes smaller.

I know the code is wrong obviously but I can't seem to fix it as its using an array called objects but I can't seem to be able to add multiple strings to the object to be used in the table view.

I'm using the standard Master Detail template for the project but in changing the code to be custom to my liking I ran into these problems.

```<code>override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objects.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

    //let object = objects[indexPath.row] as! String // NSDate
    //cell.textLabel!.text = object.description

    cell.firstLabel.text = "name"
    cell.secondLabel.text = "bought"
    cell.thirdLabel.text = "18"
    cell.fourthLabel.text = "30"

    return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        objects.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

@objc
func insertNewObject(_ sender: Any) {

    // Adding cell with new added info

    // can not be an array of strings, has to be an array of an array of strings, doesn't it?
    // "tester" is was there from the project template
    let test: String = "tester"
    objects.insert(test, at: 0) // NSDate()

    let indexPath = IndexPath(row: 0, section: 0)
    tableView.insertRows(at: [indexPath], with: .automatic)
}

// MARK: - Segues

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetail" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let object = objects[indexPath.row] as! NSDate
            let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
            controller.detailItem = object
            controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            controller.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

@IBOutlet var myTableView: UITableView!
var detailViewController: DetailViewController? = nil
var objects = [Any]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Custom Cell
    self.myTableView.dataSource = self
    self.myTableView.delegate = self

    // Do any additional setup after loading the view, typically from a nib.
    navigationItem.leftBarButtonItem = editButtonItem

    let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
    navigationItem.rightBarButtonItem = addButton
    if let split = splitViewController {
        let controllers = split.viewControllers
        detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
    }
}
</code>```

答:
according to our previous conversation try something like this:</p>

```<code>@IBOutlet private weak var tableView: UITableView!

private var objects = [["A1", "A2", "A3", "A4"],["B1", "B2", "B3", "B4"],["C1", "C2", "C3", "C4"],["D1", "D2", "D3", "D4"]]

private func insertNewObject() {

    self.objects.append(["NewString1", "NewString2", "NewString3", "NewString4"])
    self.tableView.reloadData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.objects.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 200 // add the height you like
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

    cell.firstLabel.text = objects[indexPath.row][0]
    cell.secondLabel.text = objects[indexPath.row][1]
    cell.thirdLabel.text = objects[indexPath.row][2]
    cell.fourthLabel.text = objects[indexPath.row][3]

    return cell
}
</code>```

Body:
Using Swift, My custom cell has 4 labels which I would like to edit when adding the new row/cell to the tableview.

On top of my app in the bar I have an add button which is supposed to add the new cell/row to the table view but only the first one works and when I add a second cell/row it changes and becomes smaller.

I know the code is wrong obviously but I can't seem to fix it as its using an array called objects but I can't seem to be able to add multiple strings to the object to be used in the table view.

I'm using the standard Master Detail template for the project but in changing the code to be custom to my liking I ran into these problems.

override func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return objects.count
}

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

    //let object = objects[indexPath.row] as! String // NSDate
    //cell.textLabel!.text = object.description

    cell.firstLabel.text = "name"
    cell.secondLabel.text = "bought"
    cell.thirdLabel.text = "18"
    cell.fourthLabel.text = "30"

    return cell
}

override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    // Return false if you do not want the specified item to be editable.
    return true
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        objects.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .fade)
    } else if editingStyle == .insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
    }
}

@objc
func insertNewObject(_ sender: Any) {

    // Adding cell with new added info

    // can not be an array of strings, has to be an array of an array of strings, doesn't it?
    // "tester" is was there from the project template
    let test: String = "tester"
    objects.insert(test, at: 0) // NSDate()

    let indexPath = IndexPath(row: 0, section: 0)
    tableView.insertRows(at: [indexPath], with: .automatic)
}

// MARK: - Segues

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "showDetail" {
        if let indexPath = tableView.indexPathForSelectedRow {
            let object = objects[indexPath.row] as! NSDate
            let controller = (segue.destination as! UINavigationController).topViewController as! DetailViewController
            controller.detailItem = object
            controller.navigationItem.leftBarButtonItem = splitViewController?.displayModeButtonItem
            controller.navigationItem.leftItemsSupplementBackButton = true
        }
    }
}

@IBOutlet var myTableView: UITableView!
var detailViewController: DetailViewController? = nil
var objects = [Any]()

override func viewDidLoad() {
    super.viewDidLoad()

    // Custom Cell
    self.myTableView.dataSource = self
    self.myTableView.delegate = self

    // Do any additional setup after loading the view, typically from a nib.
    navigationItem.leftBarButtonItem = editButtonItem

    let addButton = UIBarButtonItem(barButtonSystemItem: .add, target: self, action: #selector(insertNewObject(_:)))
    navigationItem.rightBarButtonItem = addButton
    if let split = splitViewController {
        let controllers = split.viewControllers
        detailViewController = (controllers[controllers.count-1] as! UINavigationController).topViewController as? DetailViewController
    }
}

Body:
according to our previous conversation try something like this:

@IBOutlet private weak var tableView: UITableView!

private var objects = [["A1", "A2", "A3", "A4"],["B1", "B2", "B3", "B4"],["C1", "C2", "C3", "C4"],["D1", "D2", "D3", "D4"]]

private func insertNewObject() {

    self.objects.append(["NewString1", "NewString2", "NewString3", "NewString4"])
    self.tableView.reloadData()
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.objects.count
}

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return 200 // add the height you like
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! CustomCell

    cell.firstLabel.text = objects[indexPath.row][0]
    cell.secondLabel.text = objects[indexPath.row][1]
    cell.thirdLabel.text = objects[indexPath.row][2]
    cell.fourthLabel.text = objects[indexPath.row][3]

    return cell
}


问:
Why CloudKit notification doesn't arrive when app is installed from testflight while it works when compiled from Xcode?
CloudKit notifications doesn't arrive on production (AppStore, TestFlight), but works in development mode (installed from Xcode).

Why?

This is how I register for remote notifications:

```<code>    let center = UNUserNotificationCenter.current()

    center.delegate = self
    center.requestAuthorization(options: [.alert, .badge, .sound]) { authorised, error in

        DispatchQueue.main.sync {
            application.registerForRemoteNotifications()
        }
    }
</code>```

and this is how I save subscriptions:

```<code>func subscribeForChanges() {

    let options: CKQuerySubscriptionOptions = [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]

    let serviceSubscription = CKQuerySubscription(recordType: "Service", predicate: NSPredicate(value: true), options: options)
    let goalSubscription = CKQuerySubscription(recordType: "Goal", predicate: NSPredicate(value: true), options: options)
    let territorySubscription = CKQuerySubscription(recordType: "Territory", predicate: NSPredicate(value: true), options: options)
    let addressSubscription = CKQuerySubscription(recordType: "Address", predicate: NSPredicate(value: true), options: options)
    let noteSubscription = CKQuerySubscription(recordType: "Note", predicate: NSPredicate(value: true), options: options)
    let daySubscription = CKQuerySubscription(recordType: "Day", predicate: NSPredicate(value: true), options: options)
    let shareSubscription = CKQuerySubscription(recordType: "cloudkit.share", predicate: NSPredicate(value: true), options: options)

    let notificationInfo = CKNotificationInfo()
    notificationInfo.shouldBadge = false
    notificationInfo.shouldSendContentAvailable = true

    serviceSubscription.notificationInfo = notificationInfo
    goalSubscription.notificationInfo = notificationInfo
    territorySubscription.notificationInfo = notificationInfo
    addressSubscription.notificationInfo = notificationInfo
    noteSubscription.notificationInfo = notificationInfo
    daySubscription.notificationInfo = notificationInfo
    shareSubscription.notificationInfo = notificationInfo

    let privateSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [serviceSubscription, goalSubscription, territorySubscription, addressSubscription, noteSubscription, daySubscription, shareSubscription], subscriptionIDsToDelete: nil)
    privateSubscriptionsOperation.database = CloudAssistant.shared.privateDatabase

    let notificationInfoDatabaseSubscription = CKNotificationInfo()
    notificationInfoDatabaseSubscription.shouldSendContentAvailable = true

    let subscription = CKDatabaseSubscription(subscriptionID: "pl.blue-world.fieldservice.sharedDatabase")
    subscription.notificationInfo = notificationInfoDatabaseSubscription
    let sharedSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
    sharedSubscriptionsOperation.database = CloudAssistant.shared.sharedDatabase

    let queue = OperationQueue()
    queue.maxConcurrentOperationCount = 1
    queue.addOperation(privateSubscriptionsOperation)
    queue.addOperation(sharedSubscriptionsOperation)
    privateDatabase.save(CKRecordZone(zoneName: "fieldservice")) { _, _ in }
}
</code>```

答:
Silent push notifications are problematic in iOS 11.0.X In iOS 11.1 there was a fix.

In development mode you might get the notification because generally the device is connected by the power cable to you computer. Silent notifications are processed when connected to power!

If your development device is iOS 11.0.X this might be the issue.

Body:
CloudKit notifications doesn't arrive on production (AppStore, TestFlight), but works in development mode (installed from Xcode).

Why?

This is how I register for remote notifications:

    let center = UNUserNotificationCenter.current()

    center.delegate = self
    center.requestAuthorization(options: [.alert, .badge, .sound]) { authorised, error in

        DispatchQueue.main.sync {
            application.registerForRemoteNotifications()
        }
    }

and this is how I save subscriptions:

func subscribeForChanges() {

    let options: CKQuerySubscriptionOptions = [.firesOnRecordCreation, .firesOnRecordUpdate, .firesOnRecordDeletion]

    let serviceSubscription = CKQuerySubscription(recordType: "Service", predicate: NSPredicate(value: true), options: options)
    let goalSubscription = CKQuerySubscription(recordType: "Goal", predicate: NSPredicate(value: true), options: options)
    let territorySubscription = CKQuerySubscription(recordType: "Territory", predicate: NSPredicate(value: true), options: options)
    let addressSubscription = CKQuerySubscription(recordType: "Address", predicate: NSPredicate(value: true), options: options)
    let noteSubscription = CKQuerySubscription(recordType: "Note", predicate: NSPredicate(value: true), options: options)
    let daySubscription = CKQuerySubscription(recordType: "Day", predicate: NSPredicate(value: true), options: options)
    let shareSubscription = CKQuerySubscription(recordType: "cloudkit.share", predicate: NSPredicate(value: true), options: options)

    let notificationInfo = CKNotificationInfo()
    notificationInfo.shouldBadge = false
    notificationInfo.shouldSendContentAvailable = true

    serviceSubscription.notificationInfo = notificationInfo
    goalSubscription.notificationInfo = notificationInfo
    territorySubscription.notificationInfo = notificationInfo
    addressSubscription.notificationInfo = notificationInfo
    noteSubscription.notificationInfo = notificationInfo
    daySubscription.notificationInfo = notificationInfo
    shareSubscription.notificationInfo = notificationInfo

    let privateSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [serviceSubscription, goalSubscription, territorySubscription, addressSubscription, noteSubscription, daySubscription, shareSubscription], subscriptionIDsToDelete: nil)
    privateSubscriptionsOperation.database = CloudAssistant.shared.privateDatabase

    let notificationInfoDatabaseSubscription = CKNotificationInfo()
    notificationInfoDatabaseSubscription.shouldSendContentAvailable = true

    let subscription = CKDatabaseSubscription(subscriptionID: "pl.blue-world.fieldservice.sharedDatabase")
    subscription.notificationInfo = notificationInfoDatabaseSubscription
    let sharedSubscriptionsOperation = CKModifySubscriptionsOperation(subscriptionsToSave: [subscription], subscriptionIDsToDelete: nil)
    sharedSubscriptionsOperation.database = CloudAssistant.shared.sharedDatabase

    let queue = OperationQueue()
    queue.maxConcurrentOperationCount = 1
    queue.addOperation(privateSubscriptionsOperation)
    queue.addOperation(sharedSubscriptionsOperation)
    privateDatabase.save(CKRecordZone(zoneName: "fieldservice")) { _, _ in }
}


问:
Postgres “missing FROM-clause entry” error on query
I am trying to use this query in Postgres:

```<code>SELECT ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;
</code>```

I get this error:

ERROR:  column reference "ean" is ambiguous
LINE 1: SELECT ean, count(nif)

If I change the query to:

```<code>SELECT P.ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;
</code>```

Appears another error:

ERROR:  missing FROM-clause entry for table "p"
LINE 4: GROUP BY P.ean

Those two tables are created this way:

```<code>create table produto (
ean char(13) not null unique,
design varchar(255) not null,
categoria varchar(80) not null,
forn_primario char(9) not null,
data date not null,
constraint ean_size CHECK (Length(ean)=13),
constraint pk_produto primary key(ean),
constraint fk_produto_categoria foreign key(categoria) references categoria(nome) ON DELETE CASCADE,
constraint fk_produto_fornecedor foreign key(forn_primario) references fornecedor(nif));

create table fornece_sec (
nif char(9) not null,
ean char(13) not null,
constraint pk_fornece_sec primary key(nif, ean),
constraint fk_fornece_sec_fornecedor foreign key(nif) references fornecedor(nif),
constraint fk_fornece_sec_produto foreign key(ean) references produto(ean) ON DELETE CASCADE);
</code>```

Note: the attribute nif in fornece_sec table is the same type of the attribute forn_primario in the product table.

答:
Tommy was right:

"Your GROUP BY seems to contain unicode, not ASCII. Maybe the P is non-ASCII character that looks like P."

Body:
I am trying to use this query in Postgres:

SELECT ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;

I get this error:

ERROR:  column reference "ean" is ambiguous
LINE 1: SELECT ean, count(nif)

If I change the query to:

SELECT P.ean, count(nif)
FROM produto P, fornece_sec F
WHERE P.ean = F.ean
GROUP BY P.ean
HAVING count(nif) > 1;

Appears another error:

ERROR:  missing FROM-clause entry for table "p"
LINE 4: GROUP BY P.ean

Those two tables are created this way:

create table produto (
ean char(13) not null unique,
design varchar(255) not null,
categoria varchar(80) not null,
forn_primario char(9) not null,
data date not null,
constraint ean_size CHECK (Length(ean)=13),
constraint pk_produto primary key(ean),
constraint fk_produto_categoria foreign key(categoria) references categoria(nome) ON DELETE CASCADE,
constraint fk_produto_fornecedor foreign key(forn_primario) references fornecedor(nif));

create table fornece_sec (
nif char(9) not null,
ean char(13) not null,
constraint pk_fornece_sec primary key(nif, ean),
constraint fk_fornece_sec_fornecedor foreign key(nif) references fornecedor(nif),
constraint fk_fornece_sec_produto foreign key(ean) references produto(ean) ON DELETE CASCADE);

Note: the attribute nif in fornece_sec table is the same type of the attribute forn_primario in the product table.


问:
Why does this WebStorm configuration not allow me to hit breakpoints in my node application?
I'm trying to debug an application that has a go backend and a node.js front-end. I run the backend with just a simple bra run, which emits:

NFO[12-08|11:57:59] Initializing HTTP Server    logger=http.server address=0.0.0.0:3000 protocol=http subUrl= socket=

I then try to run a debugging session in WebStorm, with the following npm configuration:

This outputs the following when I start the debugging session:

```<code>/usr/local/bin/node --inspect-brk /usr/local/lib/node_modules/npm/bin/npm-cli.js run watch --scripts-prepend-node-path=auto

To debug the "watch" script, make sure the $NODE_DEBUG_OPTION string is specified as the first argument for the node command you'd like to debug.
For example:
  "scripts": {
    "start": "node $NODE_DEBUG_OPTION server.js"
  }
Debugger listening on ws://127.0.0.1:9229/7c6f9f1b-377e-4a07-b7f8-0155b0d59adb
For help see https://nodejs.org/en/docs/inspector
Debugger attached.
</code>```

So I'm pretty new to debugging web apps in general, but I expected that I could now just open my browser to localhost:3000/my/script.js and have breakpoints in WebStorm get hit. This isn't the case though; I can navigate my application just fine (even with just the bra run command and the debugging session not active in WebStorm), but it doesn't trigger any breakpoints in WebStorm. I'm also not entirely sure what the ws://128.0.0.1:9229 endpoint is for, but I assume it has something to do with why I can't get anything to work.

I've been struggling with this for hours and am pretty stuck on how to get the application to run so that I can use WebStorm to debug it.

答:
With this configuration, you are debugging the watch npm script, not the application served by grafana. To debug the application, you should have created a JavaScript debug run configuration, specifying localhost:3000 as URL.
See https://www.jetbrains.com/help/webstorm/2017.3/debugging-javascript-in-chrome.html, Debugging an application running on an external web server

Body:
I'm trying to debug an application that has a go backend and a node.js front-end. I run the backend with just a simple bra run, which emits:

NFO[12-08|11:57:59] Initializing HTTP Server    logger=http.server address=0.0.0.0:3000 protocol=http subUrl= socket=

I then try to run a debugging session in WebStorm, with the following npm configuration:

This outputs the following when I start the debugging session:

/usr/local/bin/node --inspect-brk /usr/local/lib/node_modules/npm/bin/npm-cli.js run watch --scripts-prepend-node-path=auto

To debug the "watch" script, make sure the $NODE_DEBUG_OPTION string is specified as the first argument for the node command you'd like to debug.
For example:
  "scripts": {
    "start": "node $NODE_DEBUG_OPTION server.js"
  }
Debugger listening on ws://127.0.0.1:9229/7c6f9f1b-377e-4a07-b7f8-0155b0d59adb
For help see https://nodejs.org/en/docs/inspector
Debugger attached.

So I'm pretty new to debugging web apps in general, but I expected that I could now just open my browser to localhost:3000/my/script.js and have breakpoints in WebStorm get hit. This isn't the case though; I can navigate my application just fine (even with just the bra run command and the debugging session not active in WebStorm), but it doesn't trigger any breakpoints in WebStorm. I'm also not entirely sure what the ws://128.0.0.1:9229 endpoint is for, but I assume it has something to do with why I can't get anything to work.

I've been struggling with this for hours and am pretty stuck on how to get the application to run so that I can use WebStorm to debug it.


问:
Will my session be automatically closed?
Edit

Orignal Title: My transaction is closed by the time it gets to my Repo. What am I doing wrong?

I got a answer to my origanl questions(I forgot to open the transaction lol). Now I am wondering if my code is automatically closing the session or if I have to somehow tell it to do this.

Hi

I am using mvc 3.0, nhibernate, fluent nhibernate and ninject 2.0

Global.asax

```<code>// Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            // Hook our DI stuff when application starts
            SetupDependencyInjection();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        public void SetupDependencyInjection()
        {
            // Tell ASP.NET MVC 3 to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjectDependencyResolver(CreateKernel()));
        }

        protected IKernel CreateKernel()
        {
            var modules = new INinjectModule[]
                              {
                                 new NhibernateModule(),
                                 new ServiceModule(),
                                 new RepoModule()
                              };

            return new StandardKernel(modules);
        }

    }
</code>```

Session Factory

```<code>public class NhibernateSessionFactory
    {
        public ISessionFactory GetSessionFactory()
        {
            ISessionFactory fluentConfiguration = Fluently.Configure()
                                                  .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test")))
                                                  .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MyMaps>())
                                                  .BuildSessionFactory();

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

Session Factory Provider

```<code> public class NhibernateSessionFactoryProvider : Provider<ISessionFactory>
    {
        protected override ISessionFactory CreateInstance(IContext context)
        {
            var sessionFactory = new NhibernateSessionFactory();
            return sessionFactory.GetSessionFactory();
        }
    }
</code>```

Nhibernate Module

```<code> public class NhibernateModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ISessionFactory>().ToProvider<NhibernateSessionFactoryProvider>().InSingletonScope();
            Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();
        }
    }
</code>```

Service Module

```<code>  public class ServiceModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ITest>().To<Test>();
        }
    }
</code>```

Repo Module

```<code> public class RepoModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IStudentRepo>().To<StudentRepo>();
        }
    }
</code>```

HomeController

```<code> private readonly ITest test;
        public HomeController(ITest test)
        {
            this.test = test;
        }

        //
        // GET: /Home/
        public ActionResult Index()
        {
           return View();
        }
</code>```

Test(my service layer file)

```<code>  public class Test : ITest
    {
        private readonly IStudentRepo studentRepo;

        public Test(IStudentRepo studentRepo)
        {
            this.studentRepo = studentRepo;
        }

    }
</code>```

Repo

```<code>  public class StudentRepo : IStudentRepo
    {
        private readonly ISession session;

        public StudentRepo(ISession session)
        {
            this.session = session;
        }
    }
</code>```

When I look through my debugger at the session that is coming into my repo. It says the session is open and connected but the (session.Transaction).IsActive = false

答: You're currently set up to use implicit transactions, which I don't believe are exposed through session.Transaction. Of course, Use of implicit transactions is discouraged.

Body:
Edit

Orignal Title: My transaction is closed by the time it gets to my Repo. What am I doing wrong?

I got a answer to my origanl questions(I forgot to open the transaction lol). Now I am wondering if my code is automatically closing the session or if I have to somehow tell it to do this.

Hi

I am using mvc 3.0, nhibernate, fluent nhibernate and ninject 2.0

Global.asax

// Note: For instructions on enabling IIS6 or IIS7 classic mode,
    // visit http://go.microsoft.com/?LinkId=9394801

    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

        }

        protected void Application_Start()
        {
            // Hook our DI stuff when application starts
            SetupDependencyInjection();

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }

        public void SetupDependencyInjection()
        {
            // Tell ASP.NET MVC 3 to use our Ninject DI Container
            DependencyResolver.SetResolver(new NinjectDependencyResolver(CreateKernel()));
        }

        protected IKernel CreateKernel()
        {
            var modules = new INinjectModule[]
                              {
                                 new NhibernateModule(),
                                 new ServiceModule(),
                                 new RepoModule()
                              };

            return new StandardKernel(modules);
        }

    }

Session Factory

public class NhibernateSessionFactory
    {
        public ISessionFactory GetSessionFactory()
        {
            ISessionFactory fluentConfiguration = Fluently.Configure()
                                                  .Database(MsSqlConfiguration.MsSql2008.ConnectionString(c => c.FromConnectionStringWithKey("test")))
                                                  .Mappings(m => m.FluentMappings.AddFromAssemblyOf<MyMaps>())
                                                  .BuildSessionFactory();

            return fluentConfiguration;
        }
    }

Session Factory Provider

 public class NhibernateSessionFactoryProvider : Provider<ISessionFactory>
    {
        protected override ISessionFactory CreateInstance(IContext context)
        {
            var sessionFactory = new NhibernateSessionFactory();
            return sessionFactory.GetSessionFactory();
        }
    }

Nhibernate Module

 public class NhibernateModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ISessionFactory>().ToProvider<NhibernateSessionFactoryProvider>().InSingletonScope();
            Bind<ISession>().ToMethod(context => context.Kernel.Get<ISessionFactory>().OpenSession()).InRequestScope();
        }
    }

Service Module

  public class ServiceModule : NinjectModule
    {
        public override void Load()
        {
            Bind<ITest>().To<Test>();
        }
    }

Repo Module

 public class RepoModule : NinjectModule
    {
        public override void Load()
        {
            Bind<IStudentRepo>().To<StudentRepo>();
        }
    }

HomeController

 private readonly ITest test;
        public HomeController(ITest test)
        {
            this.test = test;
        }

        //
        // GET: /Home/
        public ActionResult Index()
        {
           return View();
        }

Test(my service layer file)

  public class Test : ITest
    {
        private readonly IStudentRepo studentRepo;

        public Test(IStudentRepo studentRepo)
        {
            this.studentRepo = studentRepo;
        }

    }

Repo

  public class StudentRepo : IStudentRepo
    {
        private readonly ISession session;

        public StudentRepo(ISession session)
        {
            this.session = session;
        }
    }

When I look through my debugger at the session that is coming into my repo. It says the session is open and connected but the (session.Transaction).IsActive = false