问:
using WSDL.exe to convert a web service to a .cs class
I have downloaded the "ShipWebReference" from ups.com and it is working great when used in visual studio as a "web reference"
what i am trying to do is convert this set of wsdl file and wsd files to a .CS class
I have successfully done above with another UPS web reference: "XAVWSWebReference" however no luck with "ShipWebReference"

i am using the VS2015 command prompt as administrator and running the command "wsdl"

C:\WINDOWS\system32>wsdl /language:C# "C:\Users\Mark Kordahi\Desktop\ShipSample\ShipWSSample\Web References\ShipWebReference\Ship.wsdl"

I am expecting a new file generated successfully message however above code is failing with below error:

Microsoft (R) Web Services Description Language Utility [Microsoft (R)
  .NET Framework, Version 4.6.1055.0] Copyright (C) Microsoft
  Corporation. All rights reserved. Error: Unable to import binding
  'ShipBinding' from namespace
  'http://www.ups.com/WSDL/XOLTWS/Ship/v1.0'.
    - Unable to import operation 'ProcessShipment'.
    - The element 'http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0:UPSSecurity' is
  missing.

If you would like more help, please type "wsdl /?".

I have uploaded a copy of the wsdl package under this link:
https://drive.google.com/file/d/1-XPKV1xHBoifaXvqxjhXbEZzAWuPvOKO/view?usp=sharing

答:
i think you got this error because of this:

'http://www.ups.com/XMLSchema/XOLTWS/UPSS/v1.0:UPSSecurity'

The ups.com page you requested cannot be found


来源: stackexchange

问:
How to read complex objects from json file in .net core
I have a json like this to read in c# but it showing null.

Provices.json contains this json

```<code>{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}
</code>```

start up file contains

```<code> services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));
</code>```

This is c# models

```<code>   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }
</code>```

This is how I am reading this file which is giving me null values

```<code>public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}
</code>```

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

答:
What is observe, some of fields are missing to make them as nullable like DisplayOrder e.g. json is not loading because of null property.

```<code>public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }
</code>```

Note: Expect string property no need make them as null, rest type of parameter we need to make him as null and if you sure property also contain value then no need made him as a null parameter.

ContentLicense: CC BY-SA 4.0

Body:
I have a json like this to read in c# but it showing null.

Provices.json contains this json

{
   "Provinces": {
        "States": [
          {
            "CountryId": 1,
            "Name": "AA (Armed Forces Americas)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 1
          },
          {
            "CountryId": 1,
            "Name": "AE (Armed Forces Europe)",
            "Abbreviation": null,
            "Published": false,
            "DisplayOrder": 0,
            "Country": null,
            "Id": 54
          }
    ]
  }
}

start up file contains

 services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
 services.Configure<Provinces>(Configuration.GetSection("Provinces"));

This is c# models

   public class Provinces
    {
        public Provinces()
        {
            this.States = new List<State>();
        }
        public List<State> States { get; set; }
    }

    public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }

This is how I am reading this file which is giving me null values

public class UserService
{
 public UserService(IOptions<AppSettings> appSettings,
  IOptions<Provinces> states)
    {
           _appSettings = appSettings;
            _states = states;
     }

//Getting value from json

 public List<State> GetStates()
        {
            var data = this._states.Value.States; // Zero count shows here
            return new List<State>();
        }

}

I am also reading AppSettings.json which is working fine but province.json is not working.Can You please tell what's wrong i did

Body:
What is observe, some of fields are missing to make them as nullable like DisplayOrder e.g. json is not loading because of null property.

public class State
    {
        public int CountryId { get; set; }

        public string Name { get; set; }

        public string Abbreviation { get; set; }

        public bool Published { get; set; }

        public bool DisplayOrder { get; set; }

        public string Country { get; set; }

        public int Id { get; set; }

    }

Note: Expect string property no need make them as null, rest type of parameter we need to make him as null and if you sure property also contain value then no need made him as a null parameter.


问:
Remove Line If It Contains Exact String From Line Of Another File
I have a large file and would like to remove any lines from the file that contain an exact string listed in another file. However, the string must match exactly (I'm sorry I don't know how to describe this better).

Here is the file:

```<code>one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

And here is the example list to filter with:

```<code>one@email.com
three@email.com
</code>```

The desired output is:

```<code>two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state
</code>```

I have tried to do this using the following:

```<code>grep -v -f 2.txt 1.txt > 3.txt
</code>```

However this produces the output:

```<code>two@email.com,name,surname,city,state
</code>```

I assume it's doing this because "anotherone@email.com" contains "one@email.com". I've searched for a way to include beginning of the line, but not found anything suitable.

I'm open to doing in something other than grep too, I used grep because I couldn't figure it out any other way.

答:
For this particular case -- process first file by building an associative array with filter lines being the index.  In subsequent files, test if the given line is not in the array indexes -- the default action of a pattern is to print.

```<code>awk -F, -v OFS=, '
    BEGIN   { split("", m) }
    NR==FNR { m[$0] = ""; next }
    !($1 in m)
' filter.txt file.txt
</code>```

But... if we are looking to filter any occurrence of the string anywhere in the line (an unconstrained exact match) we need to do something less clever and more brute-force:

```<code>awk '
    BEGIN {
        split("", m)
        n=0
    }
    NR==FNR {
        m[n++] = $0
        next
    }
    {
        for (i=0; i<n; ++i) {
            if (index($0, m[i]))
                next
        }
        print
    }
' filter.txt file.txt
</code>```

Note that if the filter contains non-printable characters (e.g. non-unix line endings), we would need to deal with them by filtering them out (e.g. with sub(/\r/, "")).

Body:
I have a large file and would like to remove any lines from the file that contain an exact string listed in another file. However, the string must match exactly (I'm sorry I don't know how to describe this better).

Here is the file:

one@email.com,name,surname,city,state
two@email.com,name,surname,city,state
three@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

And here is the example list to filter with:

one@email.com
three@email.com

The desired output is:

two@email.com,name,surname,city,state
anotherone@email.com,name,surname,city,state

I have tried to do this using the following:

grep -v -f 2.txt 1.txt > 3.txt

However this produces the output:

two@email.com,name,surname,city,state

I assume it's doing this because "anotherone@email.com" contains "one@email.com". I've searched for a way to include beginning of the line, but not found anything suitable.

I'm open to doing in something other than grep too, I used grep because I couldn't figure it out any other way.

Body:
For this particular case -- process first file by building an associative array with filter lines being the index.  In subsequent files, test if the given line is not in the array indexes -- the default action of a pattern is to print.

awk -F, -v OFS=, '
    BEGIN   { split("", m) }
    NR==FNR { m[$0] = ""; next }
    !($1 in m)
' filter.txt file.txt

But... if we are looking to filter any occurrence of the string anywhere in the line (an unconstrained exact match) we need to do something less clever and more brute-force:

awk '
    BEGIN {
        split("", m)
        n=0
    }
    NR==FNR {
        m[n++] = $0
        next
    }
    {
        for (i=0; i<n; ++i) {
            if (index($0, m[i]))
                next
        }
        print
    }
' filter.txt file.txt

Note that if the filter contains non-printable characters (e.g. non-unix line endings), we would need to deal with them by filtering them out (e.g. with sub(/\r/, "")).


问:
Declarative jenkins pipeline do not abort on input
Simple question I got input in declarative pipeline in jenkins. When I click abort on prompt I do not want it to mark build as aborted. To prevent answers that stack already have, I am looking for solution in declarative pipeline, without escaping to scripting.</p>

```<code>
 options {
    timeout(time: 1, unit: 'HOURS')
 }

 steps {
   input 'Deploy to UAT?'
   deploy()
 }

 post {
   aborted {
     script {
       //Throws exception(not allowed to use rawBuild)
       currentBuild.rawBuild.@result = hudson.model.Result.SUCCESS
       //Do not change status because it can only be worse
       currentBuild.result = 'SUCCESS'
       //Do not change status because it can only be worse
       currentBuild.currentResult = 'SUCCESS'
     }
   }
 }

</code>```

答:
Well, you could do

```<code>script {
    try {
        input 'Deploy to UAT?'
    } catch(err) {
       currentBuild.result = 'SUCCESS'
       return
    }
}
</code>```

I guess the above is the only correct way since the result can only worsen.

```<code>public void setResult(@Nonnull Result r) {
    if (state != State.BUILDING) {
        throw new IllegalStateException("cannot change build result while in " + state);
    }

    // result can only get worse
    if (result==null || r.isWorseThan(result)) {
        result = r;
        LOGGER.log(FINE, this + " in " + getRootDir() + ": result is set to " + r, LOGGER.isLoggable(Level.FINER) ? new Exception() : null);
    }
}
</code>```

Body:
Simple question I got input in declarative pipeline in jenkins. When I click abort on prompt I do not want it to mark build as aborted. To prevent answers that stack already have, I am looking for solution in declarative pipeline, without escaping to scripting.

 options {
    timeout(time: 1, unit: 'HOURS')
 }

 steps {
   input 'Deploy to UAT?'
   deploy()
 }

 post {
   aborted {
     script {
       //Throws exception(not allowed to use rawBuild)
       currentBuild.rawBuild.@result = hudson.model.Result.SUCCESS
       //Do not change status because it can only be worse
       currentBuild.result = 'SUCCESS'
       //Do not change status because it can only be worse
       currentBuild.currentResult = 'SUCCESS'
     }
   }
 }

Body:
Well, you could do

script {
    try {
        input 'Deploy to UAT?'
    } catch(err) {
       currentBuild.result = 'SUCCESS'
       return
    }
}

I guess the above is the only correct way since the result can only worsen.

public void setResult(@Nonnull Result r) {
    if (state != State.BUILDING) {
        throw new IllegalStateException("cannot change build result while in " + state);
    }

    // result can only get worse
    if (result==null || r.isWorseThan(result)) {
        result = r;
        LOGGER.log(FINE, this + " in " + getRootDir() + ": result is set to " + r, LOGGER.isLoggable(Level.FINER) ? new Exception() : null);
    }
}


问:
ClassCastException with CoordinatorLayout in AndroidX project
My project uses AndroidX, and has a CoordinatorLayout, AppbarLayout... I have the dependencies listed in the gradle file but the layout editor is throwing error and keeps saying classes couldn't be found. This causing a render problem but the project compiles and the app is working well.

Gradle (app):

```<code>    dependencies {
//...
//...
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.core:core:1.2.0-alpha01'
    implementation 'androidx.media:media:1.1.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0-alpha01'
    implementation group: 'androidx.coordinatorlayout', name: 'coordinatorlayout', version: '1.0.0'
}
</code>```

XML layout file:

```<code>    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBackgroundGrey"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarlayout"
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                ads:contentScrim="?attr/colorPrimary"
                ads:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    ads:layout_collapseMode="parallax">

                    <com.balysv.materialripple.MaterialRippleLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        ads:mrl_rippleAlpha="0.2"
                        ads:mrl_rippleColor="@color/colorRipple"
                        ads:mrl_rippleHover="true"
                        ads:mrl_rippleOverlay="true">

                        <ImageView
                            android:id="@+id/imv_image"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:contentDescription="@string/text_image_view_descrip"
                            android:scaleType="centerCrop"
                            ads:layout_collapseMode="none"
                            ads:srcCompat="@drawable/ic_launcher_foreground" />

                    </com.balysv.materialripple.MaterialRippleLayout>

                </RelativeLayout>

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/demo_dark_transparent"
                    ads:layout_collapseMode="pin"
                    ads:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

            </com.google.android.material.appbar.CollapsingToolbarLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:foreground="?android:attr/selectableItemBackground"
            ads:behavior_overlapTop="64dp"
            ads:cardCornerRadius="3dp"
            ads:cardElevation="3sp"
            ads:cardPreventCornerOverlap="false"
            ads:cardUseCompatPadding="true"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/nestedScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <include
                        android:id="@+id/lyt_main_content"
                        layout="@layout/include_news_content"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:visibility="visible" />

                    <ViewFlipper
                        android:id="@+id/view_flipper2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:background="#F44336">

                    </ViewFlipper>

                </RelativeLayout>

            </androidx.core.widget.NestedScrollView>

        </androidx.cardview.widget.CardView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

Tried almost everything I could without success.

EDIT:

Java class (import):

```<code>import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.widget.NestedScrollView;
</code>```

答:
'Do invalidate cache and restart you studio hope it will be helpful for you'

Click
File->Invalidate cache / Restart.

'Hope you get the answer'

Body:
My project uses AndroidX, and has a CoordinatorLayout, AppbarLayout... I have the dependencies listed in the gradle file but the layout editor is throwing error and keeps saying classes couldn't be found. This causing a render problem but the project compiles and the app is working well.

Gradle (app):

    dependencies {
//...
//...
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.core:core:1.2.0-alpha01'
    implementation 'androidx.media:media:1.1.0-beta01'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation 'androidx.coordinatorlayout:coordinatorlayout:1.1.0-alpha01'
    implementation group: 'androidx.coordinatorlayout', name: 'coordinatorlayout', version: '1.0.0'
}

XML layout file:

    <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rl_parent_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorBackgroundGrey"
        ads:layout_constraintEnd_toEndOf="parent"
        ads:layout_constraintStart_toStartOf="parent"
        ads:layout_constraintTop_toTopOf="parent">

        <com.google.android.material.appbar.AppBarLayout
            android:id="@+id/appBarlayout"
            android:layout_width="match_parent"
            android:layout_height="280dp"
            android:fitsSystemWindows="true"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar">

            <com.google.android.material.appbar.CollapsingToolbarLayout
                android:id="@+id/collapsingToolbarLayout"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fitsSystemWindows="true"
                ads:contentScrim="?attr/colorPrimary"
                ads:layout_scrollFlags="scroll|exitUntilCollapsed">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    ads:layout_collapseMode="parallax">

                    <com.balysv.materialripple.MaterialRippleLayout
                        android:layout_width="match_parent"
                        android:layout_height="match_parent"
                        ads:mrl_rippleAlpha="0.2"
                        ads:mrl_rippleColor="@color/colorRipple"
                        ads:mrl_rippleHover="true"
                        ads:mrl_rippleOverlay="true">

                        <ImageView
                            android:id="@+id/imv_image"
                            android:layout_width="match_parent"
                            android:layout_height="match_parent"
                            android:contentDescription="@string/text_image_view_descrip"
                            android:scaleType="centerCrop"
                            ads:layout_collapseMode="none"
                            ads:srcCompat="@drawable/ic_launcher_foreground" />

                    </com.balysv.materialripple.MaterialRippleLayout>

                </RelativeLayout>

                <androidx.appcompat.widget.Toolbar
                    android:id="@+id/toolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    android:background="@color/demo_dark_transparent"
                    ads:layout_collapseMode="pin"
                    ads:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" />

            </com.google.android.material.appbar.CollapsingToolbarLayout>

        </com.google.android.material.appbar.AppBarLayout>

        <androidx.cardview.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="10dp"
            android:foreground="?android:attr/selectableItemBackground"
            ads:behavior_overlapTop="64dp"
            ads:cardCornerRadius="3dp"
            ads:cardElevation="3sp"
            ads:cardPreventCornerOverlap="false"
            ads:cardUseCompatPadding="true"
            app:layout_behavior="com.google.android.material.appbar.AppBarLayout$ScrollingViewBehavior">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/nestedScrollView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:clipToPadding="false">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <include
                        android:id="@+id/lyt_main_content"
                        layout="@layout/include_news_content"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentStart="true"
                        android:layout_alignParentTop="true"
                        android:visibility="visible" />

                    <ViewFlipper
                        android:id="@+id/view_flipper2"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentBottom="true"
                        android:background="#F44336">

                    </ViewFlipper>

                </RelativeLayout>

            </androidx.core.widget.NestedScrollView>

        </androidx.cardview.widget.CardView>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

Tried almost everything I could without success.

EDIT:

Java class (import):

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AnimationUtils;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewFlipper;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ActivityOptionsCompat;
import androidx.core.content.ContextCompat;
import androidx.core.view.ViewCompat;
import androidx.core.widget.NestedScrollView;


问:
Allow no file when validation an uploaded file - CakePHP 2
I'm uploading an image for an article, and in the model, i set some validation rules for this image.

```<code>//View
$this->Form->input('Post.image');

//Model Post
public $validate = array(
    'image' => array(
        'extension' => array(
            'rule' => array('extension', array('jpeg', 'jpg', 'png', 'gif', 'bmp')),
            'message' => "L'extension de l'image envoyée n'est pas valide"
        ),
        'uploadError' => array(
            'rule' => array('uploadError', true),
            'message' => "Une erreur est survenue lors de l'upload de l'image"
        ),
        'mimeType' => array(
            'rule' => array('mimeType', array('image/png', 'image/jpeg', 'image/jpeg', 'image/jpeg', 'image/gif', 'image/bmp')),
            'message' => "Type de l'image invalide"
        ),
        'fileSize' => array(
            'rule' => array('fileSize', '<=', '2MB'),
            'message' => "La taille de l'image ne doit pas dépasser 2MB"
        )
    )
);
</code>```

The image is not required, but the input generated in html view contains the required attribute, i fix that by adding allowEmpty => true on every rule. But still, the validation doesnt pass!

How can i fix this ?

Thank you

答:
Shouldn't you include a 'required' => false instead of using 'allowEmpty' => true? Based on how I understood the CookBook regarding allowEmpty, it checks by running a !empty($value) || is_numeric($value) whereas submitting a File input would result to an array. Hence the $value would still be true and still required given the current validation rules.

Hope that was at the very least, help you in any way.

ContentLicense: CC BY-SA 3.0

Body:
I'm uploading an image for an article, and in the model, i set some validation rules for this image.

//View
$this->Form->input('Post.image');

//Model Post
public $validate = array(
    'image' => array(
        'extension' => array(
            'rule' => array('extension', array('jpeg', 'jpg', 'png', 'gif', 'bmp')),
            'message' => "L'extension de l'image envoyée n'est pas valide"
        ),
        'uploadError' => array(
            'rule' => array('uploadError', true),
            'message' => "Une erreur est survenue lors de l'upload de l'image"
        ),
        'mimeType' => array(
            'rule' => array('mimeType', array('image/png', 'image/jpeg', 'image/jpeg', 'image/jpeg', 'image/gif', 'image/bmp')),
            'message' => "Type de l'image invalide"
        ),
        'fileSize' => array(
            'rule' => array('fileSize', '<=', '2MB'),
            'message' => "La taille de l'image ne doit pas dépasser 2MB"
        )
    )
);

The image is not required, but the input generated in html view contains the required attribute, i fix that by adding allowEmpty => true on every rule. But still, the validation doesnt pass!

How can i fix this ?

Thank you


问:
How to replace a string of specific characters with sed command
I want to use the sed command to delete some specific strings.

This is the file(tRNA.fa):

```<code>>tRNA-Ala-AGC-1-1 (chrII.trna5-AlaAGC) chrII:4565386-4565457 (+) Ala (AGC) 72 bp Sc: 72.4
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-10 (chrX.trna261-AlaAGC) chrX:7378738-7378809 (-) Ala (AGC) 72 bp Sc: 72.4
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-11 (chrX.trna260-AlaAGC) chrX:7507245-7507316 (-) Ala (AGC) 72 bp Sc: 72.4
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
</code>```

I just want to keep “>tRNA-XXX-XXX-X-X”and the next line.

So,I tried to replace unnecessary information with sed command:

```<code>sed -i 's/\(.*\).*[0-9]$//g' tRNA.fa
</code>```

However,I deleted all the line starting with '>'.

The result I hope to get is:

```<code>>tRNA-Ala-AGC-1-1
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-10
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-11
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
</code>```

If you know how to replace it, please tell me,thank you.

答:
If you want to match a ( don't escape it.

```<code>sed -i 's/(.*).*[0-9]$//g' tRNA.fa
</code>```

But really the following is just enough to remove everything after (:

```<code>sed -i 's/(.*//' tRNA.fa
</code>```

Note that you may also want s/ (.*// to remove that space before ( too.

The \(...\) is used to group expression into a subgroup. It is most often used for back references, but may also be used for example as \(abc\)* - will search zero or more occurrences of the string "abc".

Here is a great sed introduction.

Body:
I want to use the sed command to delete some specific strings.

This is the file(tRNA.fa):

>tRNA-Ala-AGC-1-1 (chrII.trna5-AlaAGC) chrII:4565386-4565457 (+) Ala (AGC) 72 bp Sc: 72.4
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-10 (chrX.trna261-AlaAGC) chrX:7378738-7378809 (-) Ala (AGC) 72 bp Sc: 72.4
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-11 (chrX.trna260-AlaAGC) chrX:7507245-7507316 (-) Ala (AGC) 72 bp Sc: 72.4
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA

I just want to keep “>tRNA-XXX-XXX-X-X”and the next line.

So,I tried to replace unnecessary information with sed command:

sed -i 's/\(.*\).*[0-9]$//g' tRNA.fa

However,I deleted all the line starting with '>'.

The result I hope to get is:

>tRNA-Ala-AGC-1-1
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-10
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA
>tRNA-Ala-AGC-1-11
GGGGGTATAGCTCAGTGGTAGAGCGCTCCCTTAGCATGGGAGAGGgCTGGGGTTCAATTC
CCCATACCTCCA

If you know how to replace it, please tell me,thank you.

Body:
If you want to match a ( don't escape it.

sed -i 's/(.*).*[0-9]$//g' tRNA.fa

But really the following is just enough to remove everything after (:

sed -i 's/(.*//' tRNA.fa

Note that you may also want s/ (.*// to remove that space before ( too.

The \(...\) is used to group expression into a subgroup. It is most often used for back references, but may also be used for example as \(abc\)* - will search zero or more occurrences of the string "abc".

Here is a great sed introduction.


问:
Replace all occurrences of stirng in a string excluding other words starting with same characters
I want to replace all occurrences of string in a sentence but it should not replace other words starting with same string. Example If string is "abc bb bb bbcv cc ccv" and I want to replace bb and cc with "" so my expected output should be "abc bbcv cc".

I am using .replace method with but it is replacing bb and cc in word "bbcv" & "ccv" as well.

答:
Try checking the pattern bb or cc using alternation preceded and followed by word boundaries \b and one or more optional whitespaces.

Regex - /\b([\s+]?bb|cc[\s+]?)\b/ig

const str = "abc bb bb bbcv cc ccv";
const pattern = /\b([\s+]?bb|cc[\s+]?)\b/ig;
const replacedString = str.replace(pattern, function (match, p1) {
  return '';
});

console.log(replacedString);```


问:
Why isn't textarea an input[type="textarea"]?
Why is there an element <textarea> instead of <input type="textarea">?

答:
A textarea can contain multiple lines of text, so one wouldn't be able to pre-populate it using a value attribute.

Similarly, the select element needs to be its own element to accommodate option sub-elements.


问:
collect socket returned result in socket.io
In node.js (express.js) I can't do multiple return in an endpoint.

```<code>let result = {}
socket.on('receive_stream', ({data}) => {

  result = {
     ...result,
     ...data,
  }
  // must I send it here? res.send(result)
})
res.send(result) //this is empty object
</code>```

How can I wait and collect the stream to be finished, then only send the result to the client?

答:
```<code>let result = {}
socket.on('receive_stream', ({data}) => {

  result = {
     ...result,
     ...data,
  }
  // have to uncommented in case always opened socket
 // res.send(result);
})

socket.on('end', () => {
  res.send(result);
 } );
</code>```

But  you might convert your object to string with JSON.stringify(result) and it works only in case closing socket. If it is always opened end event is never triggered

Body:
In node.js (express.js) I can't do multiple return in an endpoint.

let result = {}
socket.on('receive_stream', ({data}) => {

  result = {
     ...result,
     ...data,
  }
  // must I send it here? res.send(result)
})
res.send(result) //this is empty object

How can I wait and collect the stream to be finished, then only send the result to the client?

Body:
let result = {}
socket.on('receive_stream', ({data}) => {

  result = {
     ...result,
     ...data,
  }
  // have to uncommented in case always opened socket
 // res.send(result);
})

socket.on('end', () => {
  res.send(result);
 } );

But  you might convert your object to string with JSON.stringify(result) and it works only in case closing socket. If it is always opened end event is never triggered


问:
How can I get specific object key in map iteration
I have one json file and I iterate it with map but I have a deep object key with name 'content' and  I want to get specific key from it when I return my json array with map

JSON:

```<code>{
  "item": [

    {
       "title": "...",
       "link": "...",
       "content": {
        "_url": "How can I get this :D",
        ...
       }
    }

   ]
}
</code>```

My javascript code:

```<code>getAllNews = async () => {
    const result = await this.getResource('item/')

    return result.map(this._transformPosts)
    // Here I iterate my json

}

_transformPosts = (item) => {

    return {
       title: item.title,
       link: item.link,
       image: item.content._url,
       // and here I try get _url
       id: item.guide,

    }

}
</code>```

答:
first of all you have to get item key and It an array. Lets iterate over it and get the key you want to fetch

let jsonData = {
    "item": [

      {
         "title": "title",
         "link": "link",
         "content": {
          "_url": "How can I get this :D"
         }
      }

     ]
  }
   function getKeyFromObject(obj,key){

          return obj.item.map(each=>each.content[key])
      }

  const url = getKeyFromObject(jsonData,"_url");
  console.log(url);```

Body:
I have one json file and I iterate it with map but I have a deep object key with name 'content' and  I want to get specific key from it when I return my json array with map

JSON:

{
  "item": [

    {
       "title": "...",
       "link": "...",
       "content": {
        "_url": "How can I get this :D",
        ...
       }
    }

   ]
}

My javascript code:

getAllNews = async () => {
    const result = await this.getResource('item/')

    return result.map(this._transformPosts)
    // Here I iterate my json

}

_transformPosts = (item) => {

    return {
       title: item.title,
       link: item.link,
       image: item.content._url,
       // and here I try get _url
       id: item.guide,

    }

}


问:
Why do String behaves like an Array ? - JS
We all know Strings somewhat behaves like an Array.You can even apply some of the array methods to it and take benefits, like the below example.

```<code>[].filter.call('abcdef',function(val){
    return val<'e';
});
</code>```

Also,

```<code>var a='xyz';
</code>```

I can access first element using a[0] or I can call a.length like an Array

My question is why String behaves like an Array. and if it does, why do I get false below when I check if it is an instance of Array. Is String Array-like?

```<code>'a' instanceof Array
</code>```

答:
To use instanceof you need to create an instance of an Object and a is not an instance of one. It is a primitive or also known as string literal:

String literals (denoted by double or single quotes) and strings
  returned from String calls in a non-constructor context (i.e., without
  using the new keyword) are primitive strings. JavaScript automatically
  converts primitives to String objects, so that it's possible to use
  String object methods for primitive strings. In contexts where a
  method is to be invoked on a primitive string or a property lookup
  occurs, JavaScript will automatically wrap the string primitive and
  call the method or perform the property lookup.

For example:

let foo = 'abc'         // primitive
let boo = new String()  // object

console.log(foo instanceof String)  // false
console.log(boo instanceof String)  // true

console.log(typeof foo)  // 'string' <-- notice not String
console.log(typeof boo)  // object```
</div>
</div>
</p>

<p>This is simply due to:</p>

<blockquote>
  <p>The instanceof operator tests the presence of <strong>constructor.prototype</strong> in
  object's prototype chain</p>
</blockquote>

<p>But as we explained above we are dealing with string literals which are created without a constructor call (<strong>new keyword</strong>) and only boxed for our convenience when operating on them. They are not actual instances of String and thus <code>instanceof</code> returns <code>false</code>.</p>

<p>The reason you can use <code>Array.filter</code> on the string primitive is simply due to the fact that it was boxed for you to a <code>String</code> from where it got the <code>length</code> property at the time of execution.</p>

<p>For example in the case of <code>V8 engine</code> string primitive is parsed/boxed to String and a <code>String</code> to a StringObject. Notice they are actually different instances.</p>

<p><code>Array.filter</code> only cares about that length property and <code>numeric indicies</code> as pointed nicely by CertainPerformance which are provided by the boxing to <code>String</code>. Example:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>console.log(Object.getOwnPropertyNames('a'))  // ["0", "length"]</code>```

However String is not StringObject and thus instanceof would return false.

Body:
We all know Strings somewhat behaves like an Array.You can even apply some of the array methods to it and take benefits, like the below example.

[].filter.call('abcdef',function(val){
    return val<'e';
});

Also,

var a='xyz';

I can access first element using a[0] or I can call a.length like an Array

My question is why String behaves like an Array. and if it does, why do I get false below when I check if it is an instance of Array. Is String Array-like?

'a' instanceof Array

Body:
To use instanceof you need to create an instance of an Object and a is not an instance of one. It is a primitive or also known as string literal:

String literals (denoted by double or single quotes) and strings
  returned from String calls in a non-constructor context (i.e., without
  using the new keyword) are primitive strings. JavaScript automatically
  converts primitives to String objects, so that it's possible to use
  String object methods for primitive strings. In contexts where a
  method is to be invoked on a primitive string or a property lookup
  occurs, JavaScript will automatically wrap the string primitive and
  call the method or perform the property lookup.

For example:

let foo = 'abc'         // primitive
let boo = new String()  // object

console.log(foo instanceof String)  // false
console.log(boo instanceof String)  // true

console.log(typeof foo)  // 'string' <-- notice not String
console.log(typeof boo)  // object

This is simply due to:

The instanceof operator tests the presence of constructor.prototype in
  object's prototype chain

But as we explained above we are dealing with string literals which are created without a constructor call (new keyword) and only boxed for our convenience when operating on them. They are not actual instances of String and thus instanceof returns false.

The reason you can use Array.filter on the string primitive is simply due to the fact that it was boxed for you to a String from where it got the length property at the time of execution.

For example in the case of V8 engine string primitive is parsed/boxed to String and a String to a StringObject. Notice they are actually different instances.

Array.filter only cares about that length property and numeric indicies as pointed nicely by CertainPerformance which are provided by the boxing to String. Example:

console.log(Object.getOwnPropertyNames('a'))  // ["0", "length"]

However String is not StringObject and thus instanceof would return false.


问:
Is it possible in Go to call a function with named arguments?
I want to call a function in Go, and attach to the argument values the argument names

func sum(a int, b int) int {
  return a + b
}

func main() {
  result := sum(a=4, b=5) // result == 9
}
```

Is it possible?

答: There is no such thing like named arguments in go

Body:
I want to call a function in Go, and attach to the argument values the argument names

func sum(a int, b int) int {
  return a + b
}

func main() {
  result := sum(a=4, b=5) // result == 9
}

Is it possible?


问:
Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections
Here my DockerFile :-

```<code>FROM openjdk:10
ENV AQUILA_HOME /data/config
#USER root
#VOLUME /tmp
ADD a2i-web-1.0.0-SNAPSHOT.jar app.jar
#RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-jar","app.jar"]
</code>```

My jar is spring boot application which requires postgres.
I installed portgres locally and it is successfully runnning on my localhost.
I am building DockerFile successfully by command

```<code>sudo docker build -t djtijare/a2i-web:v1 .
</code>```

But while running it by command

```<code>sudo docker run -p 8080:8080 -t djtijare/a2i-web:v1
</code>```

giving exception as :

```<code>Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
</code>```

I am running this docker command from directory containing DockerFile and my jar
Do I need to set any configuration to run postgres?

答:
You can't access service which on the host using localhost from container, you had to use the ip address of your host to access.

This because: default docker will use bridge which will setup a internal network for your container, so when container use localhost, it doesn't mean the host, it mean the container self's network.

If insist on, a ugly solution is use --net=host.

Something like next:

```<code>sudo docker run --net=host -p 8080:8080 -t djtijare/a2i-web:v1
</code>```

Then you can use localhost to visit host's service from container.

Body:
Here my DockerFile :-

FROM openjdk:10
ENV AQUILA_HOME /data/config
#USER root
#VOLUME /tmp
ADD a2i-web-1.0.0-SNAPSHOT.jar app.jar
#RUN bash -c 'touch /app.jar'
ENTRYPOINT ["java","-jar","app.jar"]

My jar is spring boot application which requires postgres.
I installed portgres locally and it is successfully runnning on my localhost.
I am building DockerFile successfully by command

sudo docker build -t djtijare/a2i-web:v1 .

But while running it by command

sudo docker run -p 8080:8080 -t djtijare/a2i-web:v1

giving exception as :

Connection to localhost:5432 refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.

I am running this docker command from directory containing DockerFile and my jar
Do I need to set any configuration to run postgres?

Body:
You can't access service which on the host using localhost from container, you had to use the ip address of your host to access.

This because: default docker will use bridge which will setup a internal network for your container, so when container use localhost, it doesn't mean the host, it mean the container self's network.

If insist on, a ugly solution is use --net=host.

Something like next:

sudo docker run --net=host -p 8080:8080 -t djtijare/a2i-web:v1

Then you can use localhost to visit host's service from container.


答:
Seems you have 2 streams. So you can theoretically just pipe.

```<code>socket.pipe(res);
</code>```

Or

```<code>socket.on('receive_stream', data => res.emit('data', data));
socket.on('end', data => res.emit('end'));
</code>```

Title: collect socket returned result in socket.io

Body:
Seems you have 2 streams. So you can theoretically just pipe.

socket.pipe(res);

Or

socket.on('receive_stream', data => res.emit('data', data));
socket.on('end', data => res.emit('end'));


问:
Structuring a TypeScript project with workers
How should I structure a project that includes main thread (DOM) script, and workers? Eg:

main.ts

```<code>// This file must have DOM types, but not worker types.

const worker = new Worker('worker.js');

worker.onmessage = (event) => {
  // Ideally, I should be able to reference types from the worker:
  const data = event.data as import('./worker').HelloMessage;
  console.log(data.hello);
};
</code>```

worker.ts

```<code>// This file must have worker types, but not DOM types.
// The global object must be one of the worker globals (how do I pick which?)

const helloMessage = {
  hello: 'world',
};

export type HelloMessage = typeof helloMessage;

postMessage(helloMessage);
</code>```

Whenever I've tried this in the past I feel like I've been fighting TypeScript by either:

Using one tsconfig.json that has both worker & DOM types. But of course this isn't accurate type-wise.

Using multiple tsconfig.json. But then the project boundary makes it hard to reference types between them.

Additionally, how do I declare the global in a worker? Previously I've used declare var self: DedicatedWorkerGlobalScope, but is there a way to actually set the global (rather than just setting self)?

答:
Many thanks to Mattias Buelens who pointed me in the right direction.

Here's a working example.

The project structure is:

dist

src

generic-tsconfig.json

main

(typescript files)

tsconfig.json

dedicated-worker

(typescript files)

tsconfig.json

service-worker

(typescript files)

tsconfig.json

src/generic-tsconfig.json

This contains the config common to each project:

```<code>{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "moduleResolution": "node",
    "rootDir": ".",
    "outDir": "../dist",
    "composite": true,
    "declarationMap": true,
    "sourceMap": true
  }
}
</code>```

I've deliberately avoided calling this tsconfig.json, as it isn't a project itself. Adapt the above to your needs. Here are the important parts:

outDir - This is where the transpiled script, declarations and source maps will go.

rootDir - By setting this to the src directory, each of the subprojects (main, dedicated-worker, service-worker) will appear as subdirectories in the outDir, otherwise they'll try and share the same directory and overwrite each other.

composite - This is required for TypeScript to keep references between projects.

Do not include references in this file. They'll be ignored for some undocumented reason (this is where I got stuck).

src/main/tsconfig.json

This is the config for the 'main thread' project, As in, the JavaScript that will have access to the document.

```<code>{
  "extends": "../generic-tsconfig.json",
  "compilerOptions": {
    "lib": ["esnext", "dom"],
  },
  "references": [
    {"path": "../dedicated-worker"},
    {"path": "../service-worker"}
  ]
}
</code>```

extends - This points to our generic config above.

compilerOptions.lib - The libs used by this project. In this case, JS and the DOM.

references - Since this is the main project (the one we build), it must reference all other subprojects to ensure they're also built.

src/dedicated-worker/tsconfig.json

This is the config for the dedicated worker (the kind you create with new Worker()).

```<code>{
  "extends": "../generic-tsconfig.json",
  "compilerOptions": {
    "lib": ["esnext", "webworker"],
  }
}
</code>```

You don't need to reference the other sub projects here unless you import things from them (eg types).

Using dedicated worker types

TypeScript doesn't differentiate between different worker contexts, despite them having different globals. As such, things get a little messy:

```<code>postMessage('foo');
</code>```

This works, as TypeScript's "webworker" types create globals for all dedicated worker globals. However:

```<code>self.postMessage('foo');
</code>```

…this fails, as TypeScript gives self a non-existent type that's sort-of an abstract worker global.

To fix this, include this in your source:

```<code>declare var self: DedicatedWorkerGlobalScope;
export {};
</code>```

This sets self to the correct type.

The declare var bit doesn't work unless the file is a module, and the dummy export makes TypeScript treat it as a module. This means you're declaring self in the module scope, which doesn't currently exist. Otherwise, you're trying to declare it on the global, where it does already exist.

src/service-worker/tsconfig.json

Same as above.

```<code>{
  "extends": "../generic-tsconfig.json",
  "compilerOptions": {
    "lib": ["esnext", "webworker"],
  }
}
</code>```

Using service worker types

As above, TypeScript's "webworker" types create globals for all dedicated worker globals. But this isn't a dedicated worker, so some of the types are incorrect:

```<code>postMessage('yo');
</code>```

TypeScript doesn't complain about the above, but it'll fail at runtime as postMessage isn't on the service worker global.

Unfortunately there's nothing you can do to fix the real global, but you can still fix self:

```<code>declare var self: ServiceWorkerGlobalScope;
export {};
</code>```

Now you need to ensure every global that's special to service workers is accessed via self.

```<code>addEventListener('fetch', (event) => {
  // This is a type error, as the global addEventListener
  // doesn't know anything about the 'fetch' event.
  // Therefore it doesn't know about event.request.
  console.log(event.request);
});

self.addEventListener('fetch', (event) => {
  // This works fine.
  console.log(event.request);
});
</code>```

The same issues and workarounds exist for other worker types, such as worklets and shared workers.

Building

tsc --build src/main
```

And that's it!

Body:
How should I structure a project that includes main thread (DOM) script, and workers? Eg:

main.ts

// This file must have DOM types, but not worker types.

const worker = new Worker('worker.js');

worker.onmessage = (event) => {
  // Ideally, I should be able to reference types from the worker:
  const data = event.data as import('./worker').HelloMessage;
  console.log(data.hello);
};

worker.ts

// This file must have worker types, but not DOM types.
// The global object must be one of the worker globals (how do I pick which?)

const helloMessage = {
  hello: 'world',
};

export type HelloMessage = typeof helloMessage;

postMessage(helloMessage);

Whenever I've tried this in the past I feel like I've been fighting TypeScript by either:

Using one tsconfig.json that has both worker & DOM types. But of course this isn't accurate type-wise.

Using multiple tsconfig.json. But then the project boundary makes it hard to reference types between them.

Additionally, how do I declare the global in a worker? Previously I've used declare var self: DedicatedWorkerGlobalScope, but is there a way to actually set the global (rather than just setting self)?

Body:
Many thanks to Mattias Buelens who pointed me in the right direction.

Here's a working example.

The project structure is:

dist

src

generic-tsconfig.json

main

(typescript files)

tsconfig.json

dedicated-worker

(typescript files)

tsconfig.json

service-worker

(typescript files)

tsconfig.json

src/generic-tsconfig.json

This contains the config common to each project:

{
  "compilerOptions": {
    "target": "esnext",
    "module": "esnext",
    "strict": true,
    "moduleResolution": "node",
    "rootDir": ".",
    "outDir": "../dist",
    "composite": true,
    "declarationMap": true,
    "sourceMap": true
  }
}

I've deliberately avoided calling this tsconfig.json, as it isn't a project itself. Adapt the above to your needs. Here are the important parts:

outDir - This is where the transpiled script, declarations and source maps will go.

rootDir - By setting this to the src directory, each of the subprojects (main, dedicated-worker, service-worker) will appear as subdirectories in the outDir, otherwise they'll try and share the same directory and overwrite each other.

composite - This is required for TypeScript to keep references between projects.

Do not include references in this file. They'll be ignored for some undocumented reason (this is where I got stuck).

src/main/tsconfig.json

This is the config for the 'main thread' project, As in, the JavaScript that will have access to the document.

{
  "extends": "../generic-tsconfig.json",
  "compilerOptions": {
    "lib": ["esnext", "dom"],
  },
  "references": [
    {"path": "../dedicated-worker"},
    {"path": "../service-worker"}
  ]
}

extends - This points to our generic config above.

compilerOptions.lib - The libs used by this project. In this case, JS and the DOM.

references - Since this is the main project (the one we build), it must reference all other subprojects to ensure they're also built.

src/dedicated-worker/tsconfig.json

This is the config for the dedicated worker (the kind you create with new Worker()).

{
  "extends": "../generic-tsconfig.json",
  "compilerOptions": {
    "lib": ["esnext", "webworker"],
  }
}

You don't need to reference the other sub projects here unless you import things from them (eg types).

Using dedicated worker types

TypeScript doesn't differentiate between different worker contexts, despite them having different globals. As such, things get a little messy:

postMessage('foo');

This works, as TypeScript's "webworker" types create globals for all dedicated worker globals. However:

self.postMessage('foo');

…this fails, as TypeScript gives self a non-existent type that's sort-of an abstract worker global.

To fix this, include this in your source:

declare var self: DedicatedWorkerGlobalScope;
export {};

This sets self to the correct type.

The declare var bit doesn't work unless the file is a module, and the dummy export makes TypeScript treat it as a module. This means you're declaring self in the module scope, which doesn't currently exist. Otherwise, you're trying to declare it on the global, where it does already exist.

src/service-worker/tsconfig.json

Same as above.

{
  "extends": "../generic-tsconfig.json",
  "compilerOptions": {
    "lib": ["esnext", "webworker"],
  }
}

Using service worker types

As above, TypeScript's "webworker" types create globals for all dedicated worker globals. But this isn't a dedicated worker, so some of the types are incorrect:

postMessage('yo');

TypeScript doesn't complain about the above, but it'll fail at runtime as postMessage isn't on the service worker global.

Unfortunately there's nothing you can do to fix the real global, but you can still fix self:

declare var self: ServiceWorkerGlobalScope;
export {};

Now you need to ensure every global that's special to service workers is accessed via self.

addEventListener('fetch', (event) => {
  // This is a type error, as the global addEventListener
  // doesn't know anything about the 'fetch' event.
  // Therefore it doesn't know about event.request.
  console.log(event.request);
});

self.addEventListener('fetch', (event) => {
  // This works fine.
  console.log(event.request);
});

The same issues and workarounds exist for other worker types, such as worklets and shared workers.

Building

tsc --build src/main

And that's it!


问:
WPF Noob Seeking Guidance
So, most of the time I live in ASP.NET MVC Land - however, right now I'm trying to make some analysis tools for our solution using WPF (aka, it would count lines of code, which files have tests, extracting meta data from attributes, etc). Everything is mostly going well (the reflection code I have works fine). What I'm having trouble with is the WPF ItemsControl. Compared to a tradition <asp:Repeater />, ItemsControl is completely boggling me.

My XAML:

```<code><ItemsControl x:Name="repeaterRecentProjects">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Background="#094563" Margin="5" Padding="3">
                <DockPanel>
                    <Image Source="/Content/Black-Internal-icon.png" Height="16" Width="16"></Image>
                    <TextBlock Margin="5,0" Text="{Binding}"></TextBlock>
                </DockPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical"></StackPanel>
    </ItemsPanelTemplate>
</ItemsControl>
</code>```

The idea is that the DataTemplate contains my template, as I understand it. Then, in code I can do something like this (EDIT: Full code behind of the page):

```<code>public partial class HomeScreen : Page
{
    protected bool _isProjectChosen = false;

    public HomeScreen()
    {
        InitializeComponent();
    }

    protected ObservableCollection<string> someFiles = new ObservableCollection<string>();

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        someFiles.Add("SomeFile.aspx");
        someFiles.Add("SomeFile2.aspx");
        someFiles.Add("SomeFile3.aspx");

        repeaterRecentProjects.ItemsSource = someFiles;
    }

    private void buttonSelectProject_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialogSelectProject = new OpenFileDialog();

        dialogSelectProject.DefaultExt = ".sln";
        dialogSelectProject.Filter = "Visual Studio Solution (.sln)|*.sln";

        if (dialogSelectProject.ShowDialog() == true)
        {
            textBlockProjectName.Text = dialogSelectProject.FileName;
            _isProjectChosen = true;
            buttonAnalyzeProject.IsEnabled = true;
        }

        someFiles.Add("AnotherString.aspx");
    }

    private void buttonAnalyzeProject_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Click");
    }
}
</code>```

However, whenever I run my application, I don't see three items in my items control, only one item. Why is this? Also, would my binding expression be correct? Since I'm not binding to a property of string, simply {Binding} should be acceptable right?

答:
```<code><ItemsPanelTemplate>
    <StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>
</code>```

Is being added to the the ItemsControl as an item instead of setting it as the ItemsPanel, this would be the right way:

```<code>    <ItemsControl>
        ...
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>
</code>```

(This is redundant anyway, because the default panel is already a vertical StackPanel)

Title: WPF Noob Seeking Guidance

Body:
So, most of the time I live in ASP.NET MVC Land - however, right now I'm trying to make some analysis tools for our solution using WPF (aka, it would count lines of code, which files have tests, extracting meta data from attributes, etc). Everything is mostly going well (the reflection code I have works fine). What I'm having trouble with is the WPF ItemsControl. Compared to a tradition <asp:Repeater />, ItemsControl is completely boggling me.

My XAML:

<ItemsControl x:Name="repeaterRecentProjects">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border Background="#094563" Margin="5" Padding="3">
                <DockPanel>
                    <Image Source="/Content/Black-Internal-icon.png" Height="16" Width="16"></Image>
                    <TextBlock Margin="5,0" Text="{Binding}"></TextBlock>
                </DockPanel>
            </Border>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsPanelTemplate>
        <StackPanel Orientation="Vertical"></StackPanel>
    </ItemsPanelTemplate>
</ItemsControl>

The idea is that the DataTemplate contains my template, as I understand it. Then, in code I can do something like this (EDIT: Full code behind of the page):

public partial class HomeScreen : Page
{
    protected bool _isProjectChosen = false;

    public HomeScreen()
    {
        InitializeComponent();
    }

    protected ObservableCollection<string> someFiles = new ObservableCollection<string>();

    protected override void OnInitialized(EventArgs e)
    {
        base.OnInitialized(e);

        someFiles.Add("SomeFile.aspx");
        someFiles.Add("SomeFile2.aspx");
        someFiles.Add("SomeFile3.aspx");

        repeaterRecentProjects.ItemsSource = someFiles;
    }

    private void buttonSelectProject_Click(object sender, RoutedEventArgs e)
    {
        OpenFileDialog dialogSelectProject = new OpenFileDialog();

        dialogSelectProject.DefaultExt = ".sln";
        dialogSelectProject.Filter = "Visual Studio Solution (.sln)|*.sln";

        if (dialogSelectProject.ShowDialog() == true)
        {
            textBlockProjectName.Text = dialogSelectProject.FileName;
            _isProjectChosen = true;
            buttonAnalyzeProject.IsEnabled = true;
        }

        someFiles.Add("AnotherString.aspx");
    }

    private void buttonAnalyzeProject_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show("Click");
    }
}

However, whenever I run my application, I don't see three items in my items control, only one item. Why is this? Also, would my binding expression be correct? Since I'm not binding to a property of string, simply {Binding} should be acceptable right?

Body:
<ItemsPanelTemplate>
    <StackPanel Orientation="Vertical"></StackPanel>
</ItemsPanelTemplate>

Is being added to the the ItemsControl as an item instead of setting it as the ItemsPanel, this would be the right way:

    <ItemsControl>
        ...
        <ItemsControl.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Vertical"/>
            </ItemsPanelTemplate>
        </ItemsControl.ItemsPanel>
    </ItemsControl>

(This is redundant anyway, because the default panel is already a vertical StackPanel)


问:
Rule of thumb for choosing an implementation of a Java Collection?
Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set?

For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap?

答:
Well, it depends on what you need. The general guidelines are:

List is a collection where data is kept in order of insertion and each element got index.

Set is a bag of elements without duplication (if you reinsert the same element, it won't be added). Data doesn't have the notion of order.

Map You access and write your data elements by their key, which could be any possible object.

Attribution: https://stackoverflow.com/a/21974362/2811258

For more information about Java Collections, check out this article.

OwnerDisplayName: hydeph

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: hydeph


问:
Deploying Strapi to Azure
I want to deploy Strapi to my Azure. Anyone here who has an experience doing such and making it up and running completely? Somehow I couldn't find any detailed instructions how to do that in Azure.. I'm looking for something that is as easy as deploying it to Heroku - but it's fine though if it'll require more steps as long as I can make it to work completely.</p>

答:
It should not be any different than installing Strapi on any VM (Azure, AWS, GCP or even local VM).

Quick start guide should help you setup things and run Strapi server --> https://strapi.io/documentation/3.x.x/getting-started/quick-start.html

Primarily: Install nodejs, npm and strapi (via npm). Execute strapi new cms --quickstart and you should be good to go (with default configuration).

Title: Deploying Strapi to Azure


问:
AWS Glue python shell job can call AWS glue spark job
I am new to AWS GLUE and just want to solve a particular problem. Currently i have only Glue service available only and no EC2 node no lambda.
I am trying to run a AWS spark glue job from Aws python shell glue job . is that possible to run a AWS glue python shell job as a wrapper and call multiple time the same AWS glue spark job with different parameters.
I tried to run the below code snipet but getting boto Ecxeption error in logs.

```<code>import boto3
glue = boto3.client(service_name='glue', region_name='us-east-1',
              endpoint_url='https://glue.us-east-1.amazonaws.com')
myNewJobRun = glue.start_job_run(JobName='WHICH I CREATED IN CONSOLE')
</code>```

In the above code i have already created a job in console and wants to hit the job from AWS python shell glue job.

Below i want to get the status of job if it is running then it will wait for some time and then again check the status.

```<code>status = glue.get_job_run(JobName=myJob['Name'], RunId=JobRun['JobRunId'])
</code>```

Can someone advice for share any code sample for reference

Thanks
Pradeep

答:
Following is a sample code which keeps checking the job status till the job is SUCCEEDED and raises an exception if any of the error state is observed:

```<code>import boto3
client = boto3.client(service_name='glue', region_name='us-east-1',
          endpoint_url='https://glue.us-east-1.amazonaws.com')
response = client.start_job_run(JobName='WHICH U CREATED IN CONSOLE')
status = client.get_job_run(JobName=job_name, RunId=response['JobRunId'])

if status:
    state = status['JobRun']['JobRunState']
    while state not in ['SUCCEEDED']:
        time.sleep(30)
        status = client.get_job_run(JobName=job_name, RunId=response['JobRunId'])
        state = status['JobRun']['JobRunState']
        if state in ['STOPPED', 'FAILED', 'TIMEOUT']:
            raise Exception('Failed to execute glue job: ' + status['JobRun']['ErrorMessage'] + '. State is : ' + state)
</code>```

You can modify the conditions and sleep time as per your requirement.

Body:
I am new to AWS GLUE and just want to solve a particular problem. Currently i have only Glue service available only and no EC2 node no lambda.
I am trying to run a AWS spark glue job from Aws python shell glue job . is that possible to run a AWS glue python shell job as a wrapper and call multiple time the same AWS glue spark job with different parameters.
I tried to run the below code snipet but getting boto Ecxeption error in logs.

import boto3
glue = boto3.client(service_name='glue', region_name='us-east-1',
              endpoint_url='https://glue.us-east-1.amazonaws.com')
myNewJobRun = glue.start_job_run(JobName='WHICH I CREATED IN CONSOLE')

In the above code i have already created a job in console and wants to hit the job from AWS python shell glue job.

Below i want to get the status of job if it is running then it will wait for some time and then again check the status.

status = glue.get_job_run(JobName=myJob['Name'], RunId=JobRun['JobRunId'])

Can someone advice for share any code sample for reference

Thanks
Pradeep

Body:
Following is a sample code which keeps checking the job status till the job is SUCCEEDED and raises an exception if any of the error state is observed:

import boto3
client = boto3.client(service_name='glue', region_name='us-east-1',
          endpoint_url='https://glue.us-east-1.amazonaws.com')
response = client.start_job_run(JobName='WHICH U CREATED IN CONSOLE')
status = client.get_job_run(JobName=job_name, RunId=response['JobRunId'])

if status:
    state = status['JobRun']['JobRunState']
    while state not in ['SUCCEEDED']:
        time.sleep(30)
        status = client.get_job_run(JobName=job_name, RunId=response['JobRunId'])
        state = status['JobRun']['JobRunState']
        if state in ['STOPPED', 'FAILED', 'TIMEOUT']:
            raise Exception('Failed to execute glue job: ' + status['JobRun']['ErrorMessage'] + '. State is : ' + state)

You can modify the conditions and sleep time as per your requirement.


问:
match two lists by common value (id)
I want create a new list such that the keys are used to match the roles.

For example two lists:

[['9', u'bob'], ['18', u'alice']]

[['1', 'officer'], ['2', 'nurse'], ['9', 'teacher'],['18', 'unknown']]

I'd like a new list that is:

[['9', u'bob', 'teacher'], ['18', u'alice' 'unknown']] or

[[u'bob', 'teacher'], [u'alice' 'unknown']]

Title: match two lists by common value (id)

Body:
L1 = [[9, u'bob'], [18, u'alice']]

L2 = [[1, 'officer'], [2, 'nurse'], ['9', 'teacher'],['18', 'unknown']]

final_List = []

for l1 in L1:
    for l2 in L2:

        if str(l1[0]) == l2[0]:

            num_L = [l1[1],l2[1]]
            final_List.append(num_L)

print(final_List)

---------
Output:
---------
[['bob', 'teacher'], ['alice', 'unknown']]


问:
SSIS Not building file path when executed via Agent Job but works in SSDT
I'm just after some advice\thoughts.

I have a SSIS Package (SQL Server 2016) that performs the following:

It loops through a folder on a network share (I have even granted the 'Everyone' group full control to this folder and assigns the file paths on files in the folder to a variable (@FilePaths)

This variable is then used as an attachment in a Send Email task

When I execute interactively in Visual Studio\SSDT it works fine - I receive an email with the attachment(s)

If I call via a SQL Agent Job I receive the email, but no attachment

As a test, I have also inserted the @FilePaths as the body of the email - again when executed via SSDT I receive the path of the files in the email and when via the Agent Job the body is blank

I'm using a script task within a loop to retrieve the file names

In summary, when executed via the SQL Agent job, it cannot 'see' the files to retrieve the paths, even though I have set the Everyone group to the folder and also the account the Agent is being run as.

Does anyone have any ideas what I could be missing here?  It has to be permissions of some sort.

Thanks.

答: Just to finish this - the overnight job was successful - so the fix was to change the 'TargetServerVersion' from 2017 to 2016 and re-deploy to the SSIS catalog.</p>


问:
Adjusting center of nine-patch png
I have a nine-patch png that I'm using as a popup bubble.  It looks like this:

I'm putting it in an TextView of width fill_parent so the bubble expands the width of the screen.  As one might expect, the pointer at the top is then centered horizontally in the middle of the screen.

What is the easiest way to adjust the location of the pointer so that it's, say, 5/8ths of the way over from the left instead of centered?

I can re-cut the png if necessary.

UPDATE: Cubic has a very simple solution to the problem that I can't believe I missed.  It works very effectively for my current problem. However, one downside with this solution is that it can't be adjusted on the fly.  If I need to put the pointer in one place for one view, but a different place for another view, I need to cut two different PNGs.  Is there a solution that can be adjusted at runtime?

答: You have a balanced stretch at the moment with one dot on each side. Can you try adding more to the left or right?</p>

Title: Adjusting center of nine-patch png


问:
Compute sum of values in array using PHP
I'm trying to combine the scores of employee for my program. My sample is one employee is evaluated more than one. So basically, if employee 1 have scored of 87 and 90 the total should be 177. After computation, I need to return the result with the highest score.
Here so far my sample code (I simplified my code for this question because it is too long to post the original code):

```<code>$scores = array(
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
);

print_r($scores);

get_topemployee($scores);

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    foreach($scores as $key) {
        for($i=0; count($scores) <= $i; $i++) {
            if($key[0] == $key[0][$i]) {
                $total_score += $key[1];
            }
            $combined_score[] = array($key[0], $key[1], $total_score);
        }
    }

    $employee = ""; // employee with highest score
    $compare_score = 0;
    foreach($combined_score as $value) {
        $compare_score = $value[1];
        if($value[1] >= $compare_score) {
            $employee = $value[0];
        }
    }

    return $employee;
}
</code>```

The result does not return the employee with highest score and not sure which in my code is incorrect. thanks for help

do this:- https://3v4l.org/WhVaN

答:
Here is a snippet for you, please see inline doc for explanation

```<code>$result = [];
array_walk($scores, function($item) use(&$result){
   // pushing on the behalf of name and checking if not isset with '??'
   $result[$item[1]] = ($result[$item[1]] ?? 0) + $item[2];
});
// searching for index with max value in result and show max value too
echo array_search(max($result), $result).' -> '. max($result);
</code>```

array_search — Searches the array for a given value and returns the first corresponding key if successful

array_walk — Apply a user supplied function to every member of an array

Output

```<code>allan -> 267
</code>```

Demo Link.

Body:
I'm trying to combine the scores of employee for my program. My sample is one employee is evaluated more than one. So basically, if employee 1 have scored of 87 and 90 the total should be 177. After computation, I need to return the result with the highest score.
Here so far my sample code (I simplified my code for this question because it is too long to post the original code):

$scores = array(
    array(1, "allan", 90),
    array(2, "allan", 85),
    array(3, "mark", 100),
    array(4, "jason", 88),
    array(5, "allan", 92),
    array(6, "mark", 77),
    array(7, "mark", 88),
    array(8, "jason", 90)
);

print_r($scores);

get_topemployee($scores);

function get_topemployee($scores) {
    $total_score = 0;
    $combined_score = array();

    foreach($scores as $key) {
        for($i=0; count($scores) <= $i; $i++) {
            if($key[0] == $key[0][$i]) {
                $total_score += $key[1];
            }
            $combined_score[] = array($key[0], $key[1], $total_score);
        }
    }

    $employee = ""; // employee with highest score
    $compare_score = 0;
    foreach($combined_score as $value) {
        $compare_score = $value[1];
        if($value[1] >= $compare_score) {
            $employee = $value[0];
        }
    }

    return $employee;
}

The result does not return the employee with highest score and not sure which in my code is incorrect. thanks for help

do this:- https://3v4l.org/WhVaN

Body:
Here is a snippet for you, please see inline doc for explanation

$result = [];
array_walk($scores, function($item) use(&$result){
   // pushing on the behalf of name and checking if not isset with '??'
   $result[$item[1]] = ($result[$item[1]] ?? 0) + $item[2];
});
// searching for index with max value in result and show max value too
echo array_search(max($result), $result).' -> '. max($result);

array_search — Searches the array for a given value and returns the first corresponding key if successful

array_walk — Apply a user supplied function to every member of an array

Output

allan -> 267

Demo Link.


问:
Nginx error recv() failed (104: Connection reset by peer)
Since a couple of days ago, I'm getting some errors on my server. I use CentOS 6.5 with Parallels 12.0.18, Apache server to serve dynamic content and Nginx as proxy to serve static content.

At first, I was getting the following error:

```<code>[error] 29951#0: *5138862 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 89.7.24.108, server: , request: "GET /page/2/ HTTP/1.1", upstream: "http://ip:7080/page/2/", host: "domain.es", referrer: "http://domain.es/"
</code>```

Then, I changed some configuration, like increasing MaxClients on my "httpd.conf" file and this lines to my /etc/nginx/conf.d/timeout.conf file:

```<code>proxy_connect_timeout       600;
proxy_send_timeout          600;
proxy_read_timeout          600;
send_timeout                600;
</code>```

It all seemed to be working fine until I got the same errors again, along with a new one:

```<code>[error] 15228#0: *130292 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 89.130.25.154, server: domain.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:7080/", host: "domain.com"
</code>```

I have two different websites on the same server. That's why you see two different hosts in there.

Here's the problem: when I got these errors, I got a "502 Bad Gateway" and the server becomes so slow that I can't even log in using the SSH terminal. I can only fix it temporally by resetting the httpd service.

I know there are other topics similar to this one, but all I found were problems with PHP-FPM, which I don't use.

Here's my Nginx configuration file:
    user  nginx;
    worker_processes  16;

```<code>error_log  /var/log/nginx/error.log;

events {
    worker_connections  1024;
}

http {
server_names_hash_max_size 2048;
server_names_hash_bucket_size 512;

server_tokens off;

include    mime.types;
default_type  application/octet-stream;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout  10;

# Gzip on
gzip on;
gzip_vary on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_buffers 4 32k;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;
gzip_disable "MSIE [1-6]\.";

# Other configurations
ignore_invalid_headers on;
client_max_body_size    8m;
client_header_timeout  3m;
client_body_timeout 3m;
#send_timeout     3m;
connection_pool_size  256;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
request_pool_size  4k;
output_buffers   4 32k;
postpone_output  1460;

# Cache most accessed static files
open_file_cache          max=10000 inactive=10m;
open_file_cache_valid    2m;
open_file_cache_min_uses 1;
open_file_cache_errors   on;

# virtual hosts includes
include "/etc/nginx/conf.d/*.conf";
}
</code>```

Here's my Nginx vhost file:
    server {
    listen ip:80 default_server;

```<code>server_name domain.es;
server_name www.domain.es;
server_name ipv4.domain.es;

client_max_body_size 128m;

root "/var/www/vhosts/domain.es/httpdocs";
access_log "/var/www/vhosts/system/domain.es/logs/proxy_access_log";
error_log "/var/www/vhosts/system/domain.es/logs/proxy_error_log";

if ($host ~* ^www.domain.es$) {
    rewrite ^(.*)$ http://domain.es$1 permanent;
}

location / {
    proxy_pass http://82.194.74.41:7080;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
    access_log off;
}

location @fallback {
    proxy_pass http://ip:7080;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
    access_log off;
}

location ~ ^/plesk-stat/ {
    proxy_pass http://ip:7080;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
    access_log off;
}

location ~ ^/(.*\.(ac3|avi|bmp|bz2|css|cue|dat|doc|docx|dts|exe|flv|gif|gz|htm|html|ico|img|iso|jpeg|jpg|js|mkv|mp3|mp4|mpeg|mpg|ogg|pdf|png|ppt|pptx|qt|rar|rm|swf|tar|tgz|txt|wav|xls|xlsx|zip))$ {
    access_log off;
    expires 7d;
    add_header Cache-Control public;

 try_files $uri @fallback;
}

include "/var/www/vhosts/system/domain.es/conf/vhost_nginx.conf";
}
</code>```

And some of the configuration vars I use with Apache (httpd.conf):

```<code><IfModule prefork.c>
StartServers      14
MinSpareServers    8
MaxSpareServers   14
ServerLimit      1000
MaxClients       1000
MaxRequestsPerChild  2000
</IfModule>
</code>```

Thank you very much in advance!

答:
In a case I saw recently this error was being logged for 95% of requests but both the web server and the apps server were almost idle with only a few connections open. The other 5% were successful.

It turned out that our friendly networking colleagues had configured an IPS device between the web and apps server and it started clawing back and dropping connections when traffic increased because it thought there was a brute force attack happening. A false-positive. So nothing to do with Nginx or Apache, but reconfiguring the IPS fixed the issue.

Body:
Since a couple of days ago, I'm getting some errors on my server. I use CentOS 6.5 with Parallels 12.0.18, Apache server to serve dynamic content and Nginx as proxy to serve static content.

At first, I was getting the following error:

[error] 29951#0: *5138862 upstream timed out (110: Connection timed out) while reading response header from upstream, client: 89.7.24.108, server: , request: "GET /page/2/ HTTP/1.1", upstream: "http://ip:7080/page/2/", host: "domain.es", referrer: "http://domain.es/"

Then, I changed some configuration, like increasing MaxClients on my "httpd.conf" file and this lines to my /etc/nginx/conf.d/timeout.conf file:

proxy_connect_timeout       600;
proxy_send_timeout          600;
proxy_read_timeout          600;
send_timeout                600;

It all seemed to be working fine until I got the same errors again, along with a new one:

[error] 15228#0: *130292 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 89.130.25.154, server: domain.com, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:7080/", host: "domain.com"

I have two different websites on the same server. That's why you see two different hosts in there.

Here's the problem: when I got these errors, I got a "502 Bad Gateway" and the server becomes so slow that I can't even log in using the SSH terminal. I can only fix it temporally by resetting the httpd service.

I know there are other topics similar to this one, but all I found were problems with PHP-FPM, which I don't use.

Here's my Nginx configuration file:
    user  nginx;
    worker_processes  16;

error_log  /var/log/nginx/error.log;

events {
    worker_connections  1024;
}

http {
server_names_hash_max_size 2048;
server_names_hash_bucket_size 512;

server_tokens off;

include    mime.types;
default_type  application/octet-stream;

sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout  10;

# Gzip on
gzip on;
gzip_vary on;
gzip_min_length 10240;
gzip_proxied expired no-cache no-store private auth;
gzip_buffers 4 32k;
gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript text/x-js;
gzip_disable "MSIE [1-6]\.";

# Other configurations
ignore_invalid_headers on;
client_max_body_size    8m;
client_header_timeout  3m;
client_body_timeout 3m;
#send_timeout     3m;
connection_pool_size  256;
client_header_buffer_size 4k;
large_client_header_buffers 4 32k;
request_pool_size  4k;
output_buffers   4 32k;
postpone_output  1460;

# Cache most accessed static files
open_file_cache          max=10000 inactive=10m;
open_file_cache_valid    2m;
open_file_cache_min_uses 1;
open_file_cache_errors   on;

# virtual hosts includes
include "/etc/nginx/conf.d/*.conf";
}

Here's my Nginx vhost file:
    server {
    listen ip:80 default_server;

server_name domain.es;
server_name www.domain.es;
server_name ipv4.domain.es;

client_max_body_size 128m;

root "/var/www/vhosts/domain.es/httpdocs";
access_log "/var/www/vhosts/system/domain.es/logs/proxy_access_log";
error_log "/var/www/vhosts/system/domain.es/logs/proxy_error_log";

if ($host ~* ^www.domain.es$) {
    rewrite ^(.*)$ http://domain.es$1 permanent;
}

location / {
    proxy_pass http://82.194.74.41:7080;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
    access_log off;
}

location @fallback {
    proxy_pass http://ip:7080;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
    access_log off;
}

location ~ ^/plesk-stat/ {
    proxy_pass http://ip:7080;
    proxy_set_header Host             $host;
    proxy_set_header X-Real-IP        $remote_addr;
    proxy_set_header X-Forwarded-For  $proxy_add_x_forwarded_for;
    access_log off;
}

location ~ ^/(.*\.(ac3|avi|bmp|bz2|css|cue|dat|doc|docx|dts|exe|flv|gif|gz|htm|html|ico|img|iso|jpeg|jpg|js|mkv|mp3|mp4|mpeg|mpg|ogg|pdf|png|ppt|pptx|qt|rar|rm|swf|tar|tgz|txt|wav|xls|xlsx|zip))$ {
    access_log off;
    expires 7d;
    add_header Cache-Control public;

 try_files $uri @fallback;
}

include "/var/www/vhosts/system/domain.es/conf/vhost_nginx.conf";
}

And some of the configuration vars I use with Apache (httpd.conf):

<IfModule prefork.c>
StartServers      14
MinSpareServers    8
MaxSpareServers   14
ServerLimit      1000
MaxClients       1000
MaxRequestsPerChild  2000
</IfModule>

Thank you very much in advance!


问:
Add custom Checkout field based on Cart weight in Woocommerce
On the checkout page, I would like to add a custom field if the contents of the cart weighs over 1000kg.

Is there a way of adding an if statement (to form-checkout.php?) which gets the cart weight and then I can add in a select field?

答:
First read the official related documentation to customize checkout fields or this documentation too.

Here is an example that will add a custom billing select field when cart weight is over 1000 Kg (1 Ton) in checkout page:

```<code>add_filter( 'woocommerce_checkout_fields' , 'customizing_checkout_fields', 10, 1 );
function customizing_checkout_fields( $fields ) {

    if( WC()->cart->get_cart_contents_weight() > 1000 ) {

        // Custom Select field
        $fields['billing']['billing_custom'] = array(
            'type'     => 'select',
            'label'    => __("Cart weight over 1 Ton", "woocommerce"),
            'class'    => array('form-row-wide'),
            'options'  => array(
                ''         => __("Choose an option please…", "woocommerce"),
                'option-1' => __("Option 1", "woocommerce"),
                'option-2' => __("Option 1", "woocommerce"),
                'option-3' => __("Option 1", "woocommerce"),
            ),
            'priority' => '120',
            'required' => true,
        );
    }

    return $fields;
}
</code>```

Code goes in functions.php file of your active child theme (or active theme). Tested and work.

Body:
First read the official related documentation to customize checkout fields or this documentation too.

Here is an example that will add a custom billing select field when cart weight is over 1000 Kg (1 Ton) in checkout page:

add_filter( 'woocommerce_checkout_fields' , 'customizing_checkout_fields', 10, 1 );
function customizing_checkout_fields( $fields ) {

    if( WC()->cart->get_cart_contents_weight() > 1000 ) {

        // Custom Select field
        $fields['billing']['billing_custom'] = array(
            'type'     => 'select',
            'label'    => __("Cart weight over 1 Ton", "woocommerce"),
            'class'    => array('form-row-wide'),
            'options'  => array(
                ''         => __("Choose an option please…", "woocommerce"),
                'option-1' => __("Option 1", "woocommerce"),
                'option-2' => __("Option 1", "woocommerce"),
                'option-3' => __("Option 1", "woocommerce"),
            ),
            'priority' => '120',
            'required' => true,
        );
    }

    return $fields;
}

Code goes in functions.php file of your active child theme (or active theme). Tested and work.


问:
Remove the first element from a multidimensional array with PHP
Form this array, how can I remove the first element of Provinces ?

```<code>Array
(
    [Country] => Canada
    [Provinces] => Array
        (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)
</code>```

Thanks.

答:
You can do both way but difference is that when you use unset will remove an element by its key, say unset( $myArray['country']) will remove the country key value pair.

if you want to remove first element in multidimensional array then you can easily d t with array_shift(); it will remove all the child array of this particular element.

suppose it is a location array

```<code>   $location = Array
       (
        [Country] => Canada
        [Provinces] => Array
         (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

// Removing first array item
$location_new = array_shift($planets);
print_r($location_new);//it will give **Canada**
//and now
print_r($location);//it will give the

 Array
       (
        [Provinces] => Array
         (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)
</code>```

Body:
Form this array, how can I remove the first element of Provinces ?

Array
(
    [Country] => Canada
    [Provinces] => Array
        (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

Thanks.

Body:
You can do both way but difference is that when you use unset will remove an element by its key, say unset( $myArray['country']) will remove the country key value pair.

if you want to remove first element in multidimensional array then you can easily d t with array_shift(); it will remove all the child array of this particular element.

suppose it is a location array

   $location = Array
       (
        [Country] => Canada
        [Provinces] => Array
         (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)

// Removing first array item
$location_new = array_shift($planets);
print_r($location_new);//it will give **Canada**
//and now
print_r($location);//it will give the

 Array
       (
        [Provinces] => Array
         (
            [0] => Quebec
            [1] => Ontario
            [2] => British Columbia
        )
)


问:
Hiding the selection in a WPF ListBox, keeping it in contained controls
I'm using a ListBox to display a list of editable objects whose template contains, among other things, a ComboBox.

I used this common technique to hide the ListBox selection, which is not used for anything:

```<code><ListBox.Resources>
  <Style TargetType="ListBoxItem">
    <Style.Resources>
      <Brush x:Key="{x:Static SystemColors.HighlightBrushKey}">Transparent</Brush>
      <Brush x:Key="{x:Static SystemColors.ControlBrushKey}">Transparent</Brush>
</code>```

The problem is this messes with the ComboBox dropdown list selection.

I'd like to override these resources again in my template, specifying the original values (SystemColors.HighlightBrush, etc) instead of hardcoding them. How can I do that?

```<code><ListBox.ItemTemplate>
  <DataTemplate DataType="{x:Type SearchService:Criterion}">
    <DataTemplate.Resources>
      <!--I know how to specify a hardcoded brush here,
          but not how to reference one from SystemColors-->
</code>```

答:
You could do:

```<code><SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
    Color="{x:Static SystemColors.HighlightColor}" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
    Color="{x:Static SystemColors.ControlColor}" />
</code>```

or

```<code><SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
    Color="{DynamicResource {x:Static SystemColors.HighlightColorKey}}" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
    Color="{DynamicResource {x:Static SystemColors.ControlColorKey}}" />
</code>```

To restore the brushes to their default colors.

Body:
I'm using a ListBox to display a list of editable objects whose template contains, among other things, a ComboBox.

I used this common technique to hide the ListBox selection, which is not used for anything:

<ListBox.Resources>

Body:
You could do:

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
    Color="{x:Static SystemColors.HighlightColor}" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
    Color="{x:Static SystemColors.ControlColor}" />

or

<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
    Color="{DynamicResource {x:Static SystemColors.HighlightColorKey}}" />
<SolidColorBrush x:Key="{x:Static SystemColors.ControlBrushKey}"
    Color="{DynamicResource {x:Static SystemColors.ControlColorKey}}" />

To restore the brushes to their default colors.