问:
How do I stop using ruby Sass and start using Dart-sass. Uninstall-Install them respectively
This question needs 3 questions answered for completeness:

How do I remove ruby sass?

How do I install dart-sass?

How do I re-point the sass command at dart-sass?

I may answer these below but my notes may be wrong, unfortunately the sass website does not provide very specific instructions on how to install and how to move from ruby sass to dart-sass.
While writing this I have found some answers I will post, but feel free to add your better answer or correct me, mine may not be a good answer but hopefully it helps someone else.

Background before writing this:

I am on Ubuntu
I have been searching for days, on the best SASS solution (paid maybe the best, but I hate being disappointed by poor support after I fork out money).
All documentation I have read ends with me using dart-sass that it is the only form of sass going forwards. Ruby & Node are no longer supported. Codekit for Mac looks good, and Prepros also looks very good may try this for its other features, but I don't want to pay, just yet, and in any case I assume they are just using libsass anyway.
I am using VScode, i moved from sublime.
I am getting many errors with the different recent bootstrap versions (4.0.0-a2 - 4.3.1) So once I find the correct dart-sass, then I can focus on finding the correct bootstrap. Please feel free to answer this question if you know the specifics, again it is not commonly documented.

Currently
Using ruby sass:

Currently I can run a sass watch command sass --watch mysass:mycss and my css compiles (sometimes with errors) at least tries, so sass watch is working.
I can check the version sass --version and I get: Ruby Sass 3.7.4
I have done an apt-get remove sass, and it appears to uninstall but no I can still run sass watch.

I think I will need to do a git clone from github with the main of dart-sass.

I think I need to ad a path variable.

So now that I have some answers I will start forming my answer below, but please feel free to tell me I am wrong.
Cheers,
SASS NOOB

答:
Uninstall Ruby Sass

```<code>gem uninstall sass
</code>```

possibly have to manually (I did not have to)
remove:

```<code>/usr/local/bin/sass

/usr/local/bin/sass-convert

/usr/local/bin/scss
</code>```

Thanks to Steve Griffith Channel
https://www.youtube.com/watch?v=5jZGo_k8Rd0&t=305s

Clone was wrong, that is the issue why dart-sass wouldn't run:

instead download your preferred tar.gz version to Downloads, I am gong with the latest, then extract to your preferred location

```<code> $ cd /usr/local/bin

 $ sudo tar -zxvf ~/Downloads/dart-sass-1.26.0-test.3-linux-x64.tar.gz
</code>```

Setup Path

```<code> $ sudo nano ~/.bashrc
</code>```

add new line

```<code>export PATH="/usr/local/bin/dart-sass:$PATH"
</code>```

OK tested sass now runs dart-sass, how well is yet to be determined, I may have to go back a few versions??? And then which bootstrap, I might follow up with this.

Body:
Uninstall Ruby Sass

gem uninstall sass

possibly have to manually (I did not have to)
remove:

/usr/local/bin/sass

/usr/local/bin/sass-convert

/usr/local/bin/scss

Thanks to Steve Griffith Channel
https://www.youtube.com/watch?v=5jZGo_k8Rd0&t=305s

Clone was wrong, that is the issue why dart-sass wouldn't run:

instead download your preferred tar.gz version to Downloads, I am gong with the latest, then extract to your preferred location

 $ cd /usr/local/bin

 $ sudo tar -zxvf ~/Downloads/dart-sass-1.26.0-test.3-linux-x64.tar.gz

Setup Path

 $ sudo nano ~/.bashrc

add new line

export PATH="/usr/local/bin/dart-sass:$PATH"

OK tested sass now runs dart-sass, how well is yet to be determined, I may have to go back a few versions??? And then which bootstrap, I might follow up with this.


来源: stackexchange

问:
Why my database is not working, I am using ways in official documentation?
I have a problem: Firebase Database is not working and I cannot understand why that happened (cannot post data to server, when I press button to send data- nothing happens, data does not saving in server).

Look my code:

```<code>private var db = FirebaseDatabase.getInstance()
private lateinit var dbReference: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 setSupportActionBar(toolbar)

 dbReference = db.reference.child("member")

 add_item_to_db_button.setOnClickListener {
     dbReference.push()
         .setValue(Member(item_name.text.toString(), item_description.text.toString()))

 }
}
</code>```

My constructor class to send data to a database:

```<code> class Member {
 lateinit var itemName: String
 lateinit var itemDescription: String

constructor()
constructor(itemName: String, itemDescription: String) {
    this.itemName = itemName
    this.itemDescription = itemDescription
  }

}
</code>```

My dependencies(google() and jcenter() Is enabled in top-level Gradle):

```<code>dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

// Firebase
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.firebaseui:firebase-ui:0.6.2'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

}

apply plugin: 'com.google.gms.google-services'
</code>```

My XML file:

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:padding="40dp"
 android:orientation="vertical"
 android:gravity="center"
 android:layout_height="match_parent">

 <ImageView
    android:layout_width="200dp"
    android:src="@color/cardview_dark_background"
    android:layout_marginBottom="30dp"
    android:layout_height="200dp"/>

 <EditText
    android:layout_width="match_parent"
    android:id="@+id/item_name"
    android:text="Description"
    android:layout_height="wrap_content"/>

 <EditText
    android:text="Name of product"
    android:layout_width="match_parent"
    android:id="@+id/item_description"
    android:layout_height="wrap_content"/>

 <Button
    android:id="@+id/add_item_to_db_button"
    android:layout_width="match_parent"
    android:text="Add"
    android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

And finally, database rules:

```<code>"rules": {
   ".read": true,
   ".write": true
 }
</code>```

I'm do not understand why db is not working. Tried several ways was posted in StackOverflow - does not help.

答:
Change your class to a data class:</p>

```<code>data class Member(val itemName : String, val itemDescription : String) {
constructor() : this("", "")
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a problem: Firebase Database is not working and I cannot understand why that happened (cannot post data to server, when I press button to send data- nothing happens, data does not saving in server).

Look my code:

private var db = FirebaseDatabase.getInstance()
private lateinit var dbReference: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 setSupportActionBar(toolbar)

 dbReference = db.reference.child("member")

 add_item_to_db_button.setOnClickListener {
     dbReference.push()
         .setValue(Member(item_name.text.toString(), item_description.text.toString()))

 }
}

My constructor class to send data to a database:

 class Member {
 lateinit var itemName: String
 lateinit var itemDescription: String

constructor()
constructor(itemName: String, itemDescription: String) {
    this.itemName = itemName
    this.itemDescription = itemDescription
  }

}

My dependencies(google() and jcenter() Is enabled in top-level Gradle):

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.core:core-ktx:1.2.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

// Firebase
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.firebaseui:firebase-ui:0.6.2'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

}

apply plugin: 'com.google.gms.google-services'

My XML file:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:padding="40dp"
 android:orientation="vertical"
 android:gravity="center"
 android:layout_height="match_parent">

 <ImageView
    android:layout_width="200dp"
    android:src="@color/cardview_dark_background"
    android:layout_marginBottom="30dp"
    android:layout_height="200dp"/>

 <EditText
    android:layout_width="match_parent"
    android:id="@+id/item_name"
    android:text="Description"
    android:layout_height="wrap_content"/>

 <EditText
    android:text="Name of product"
    android:layout_width="match_parent"
    android:id="@+id/item_description"
    android:layout_height="wrap_content"/>

 <Button
    android:id="@+id/add_item_to_db_button"
    android:layout_width="match_parent"
    android:text="Add"
    android:layout_height="wrap_content"/>

</LinearLayout>

And finally, database rules:

"rules": {
   ".read": true,
   ".write": true
 }

I'm do not understand why db is not working. Tried several ways was posted in StackOverflow - does not help.

Body:
Change your class to a data class:

data class Member(val itemName : String, val itemDescription : String) {
constructor() : this("", "")
}


问:
ngClass directive to use with ngFor
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

```<code><ul>
      <li *ngFor="let text of income; let i = index" [ngClass]="'strong'">{{text.text}}</li>
    </ul>
income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];
</code>```

答:
Try with this code: </p>

```<code><ul>
    <li *ngFor="let text of income">
        {{ text.split(':')[0] }}: <span class="strong">{{ text.split(':')[1] }}</span>
    </li>
</ul>
</code>```

Title: ngClass directive to use with ngFor

Body:
I have some list elements, which I am rendering using *ngFor directive. However, some part of the list items text should be bold according to the specs. I tried to do this with the [ngClass]="'strong'" when strong is the css class I need to add some portion on the text. When I run the application the result was the whole text become bold. Below is the screenshot for your better understanding.

The requirement is to make the dollar part bold only. I am new to the angular development. Any help would be greatly appreciated.

{{text.text}}

income = [
    {text:'Your Annual Income:* $1,316,422'},
    {text:'Your Monthly Income: $109,702'}
  ];

Body:
Try with this code:

<ul>
    <li *ngFor="let text of income">
        {{ text.split(':')[0] }}: <span class="strong">{{ text.split(':')[1] }}</span>
    </li>
</ul>


问:
Create map removing duplicate from list based on condition
I want to get a list without duplication based on a condition using java 8, lambda expressions. Let's say I have the following code:

```<code>import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

    class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
           this.name = name;
           this.age = age;
        }

        public String getName() {
            return this.name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return this.age;
        }

        public void setName(int age) {
            this.age = age;
        }
    }

    public static void main(String[] args) {

        Main main = new Main();
        main.createList();
    }

    public void createList() {

        List<Person> p = new ArrayList<Person>();
        p.add(new Person("william", 34));
        p.add(new Person("billie", 62));
        p.add(new Person("Loise", 37));
        p.add(new Person("Margot", 12));
        p.add(new Person("billie", 63));
        p.add(new Person("billie", 61));

        System.out.println("show People initially");
        show(p);

        // It's going to be duplicated when it has the same name
        // It'll keep the older person. For example, for billie it should keep billie -> 63

        p = removeDuplicate(p, person -> buildPersonKey(person));

        System.out.println("show People After");
        show(p);

    }

    public void show(List<Person> pList) {
        for (Person p: pList) {
            System.out.println(p.getName() + "-Age: " + p.getAge());
        }
    }

    public <T> List<T> removeDuplicate(List<T> dataList, Function<? super T, ?> keyFunction) {
        return
                new ArrayList<>(dataList.stream()
                        .collect(Collectors.toMap(
                                p -> (keyFunction.apply(p)),
                                p -> p,
                                (oldValue, newValue) -> newValue))
                        .values());
    }

    public String buildPersonKey(Person p) {
        return p.getName();
    }
}
</code>```

This is my current output:

```<code>show People initially
william-Age: 34
billie-Age: 62
Loise-Age: 37
Margot-Age: 12
billie-Age: 63
billie-Age: 61
show People After
william-Age: 34
billie-Age: 61 // Here I want "billie-Age: 63"
Loise-Age: 37
Margot-Age: 12
</code>```

This line (oldValue, newValue) -> newValue)) is the key, but here what I'd need it's a if expression, something like mapValueOld.getAge() > mapValueNew.getAge() ? mapValueOld.getAge() : mapValueNew.getAge()

Any idea how can I get this? Thanks

答:
Since your removeDuplicate method is generic, you have to pass to it a function that chooses between two elements having the same key:

```<code>public <T> List<T> removeDuplicate(List<T> dataList, Function<? super T, ?> keyFunction, BinaryOperator<T> chooser) {
    return
            new ArrayList<>(dataList.stream()
                    .collect(Collectors.toMap(keyFunction,
                                              Function.identity(),
                                              chooser))
                    .values());
}
</code>```

and call the method with:

```<code>p = removeDuplicate(p,
                    person -> buildPersonKey(person),
                    (p1,p2) -> p1.getAge() >= p2.getAge() ? p1 : p2);
</code>```

Body:
I want to get a list without duplication based on a condition using java 8, lambda expressions. Let's say I have the following code:

import java.util.ArrayList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

public class Main {

    class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
           this.name = name;
           this.age = age;
        }

        public String getName() {
            return this.name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return this.age;
        }

        public void setName(int age) {
            this.age = age;
        }
    }

    public static void main(String[] args) {

        Main main = new Main();
        main.createList();
    }

    public void createList() {

        List<Person> p = new ArrayList<Person>();
        p.add(new Person("william", 34));
        p.add(new Person("billie", 62));
        p.add(new Person("Loise", 37));
        p.add(new Person("Margot", 12));
        p.add(new Person("billie", 63));
        p.add(new Person("billie", 61));

        System.out.println("show People initially");
        show(p);

        // It's going to be duplicated when it has the same name
        // It'll keep the older person. For example, for billie it should keep billie -> 63

        p = removeDuplicate(p, person -> buildPersonKey(person));

        System.out.println("show People After");
        show(p);

    }

    public void show(List<Person> pList) {
        for (Person p: pList) {
            System.out.println(p.getName() + "-Age: " + p.getAge());
        }
    }

    public <T> List<T> removeDuplicate(List<T> dataList, Function<? super T, ?> keyFunction) {
        return
                new ArrayList<>(dataList.stream()
                        .collect(Collectors.toMap(
                                p -> (keyFunction.apply(p)),
                                p -> p,
                                (oldValue, newValue) -> newValue))
                        .values());
    }

    public String buildPersonKey(Person p) {
        return p.getName();
    }
}

This is my current output:

show People initially
william-Age: 34
billie-Age: 62
Loise-Age: 37
Margot-Age: 12
billie-Age: 63
billie-Age: 61
show People After
william-Age: 34
billie-Age: 61 // Here I want "billie-Age: 63"
Loise-Age: 37
Margot-Age: 12

This line (oldValue, newValue) -> newValue)) is the key, but here what I'd need it's a if expression, something like mapValueOld.getAge() > mapValueNew.getAge() ? mapValueOld.getAge() : mapValueNew.getAge()

Any idea how can I get this? Thanks

Body:
Since your removeDuplicate method is generic, you have to pass to it a function that chooses between two elements having the same key:

public <T> List<T> removeDuplicate(List<T> dataList, Function<? super T, ?> keyFunction, BinaryOperator<T> chooser) {
    return
            new ArrayList<>(dataList.stream()
                    .collect(Collectors.toMap(keyFunction,
                                              Function.identity(),
                                              chooser))
                    .values());
}

and call the method with:

p = removeDuplicate(p,
                    person -> buildPersonKey(person),
                    (p1,p2) -> p1.getAge() >= p2.getAge() ? p1 : p2);


问:
How to group and aggregate in pandas
I have df like this.
this value is projected values so that many columns exist.

```<code>Customer seg value0  value1
A         a   10      60
A         b   20      50
A         c   30      40
B         a   40      30
B         b   50      20
B         c   60      10
</code>```

I would like to calculate value by referring to seg columns.

a-b-c ( a minus b minus c)

in each customers

```<code>customer value0 value1
A        -40     -30
B        -70      0
</code>```

How can I calculate each values by grouping customers.

df.groupby(customer)

Thanks

答:
Idea is multiple values for subtract by -1 and then aggregate sum:

```<code>#filter only a,b,c rows
df1 = df[df['seg'].isin(['a','b','c'])]

a = np.where(df1['seg'].eq('a'), 1, -1)
df1.iloc[:, 2:] *= a[:, None]

print (df1)
  Customer seg  value0  value1
0        A   a      10      60
1        A   b     -20     -50
2        A   c     -30     -40
3        B   a      40      30
4        B   b     -50     -20
5        B   c     -60     -10

df2 = df1.groupby('Customer', as_index=False).sum()
print (df2)
  Customer  value0  value1
0        A     -40     -30
1        B     -70       0
</code>```

Or if want multiple by numeric columns:

```<code>df1 = df[df['seg'].isin(['a','b','c'])]
c = df1.select_dtypes(np.number).columns

a = np.where(df1['seg'].eq('a'), 1, -1)
df1[c] *= a[:, None]

df2 = df1.groupby('Customer', as_index=False).sum()
print (df2)
  Customer  value0  value1
0        A     -40     -30
1        B     -70       0
</code>```

Title: How to group and aggregate in pandas

Body:
I have df like this.
this value is projected values so that many columns exist.

Customer seg value0  value1
A         a   10      60
A         b   20      50
A         c   30      40
B         a   40      30
B         b   50      20
B         c   60      10

I would like to calculate value by referring to seg columns.

a-b-c ( a minus b minus c)

in each customers

customer value0 value1
A        -40     -30
B        -70      0

How can I calculate each values by grouping customers.

df.groupby(customer)

Thanks

Body:
Idea is multiple values for subtract by -1 and then aggregate sum:

#filter only a,b,c rows
df1 = df[df['seg'].isin(['a','b','c'])]

a = np.where(df1['seg'].eq('a'), 1, -1)
df1.iloc[:, 2:] *= a[:, None]

print (df1)
  Customer seg  value0  value1
0        A   a      10      60
1        A   b     -20     -50
2        A   c     -30     -40
3        B   a      40      30
4        B   b     -50     -20
5        B   c     -60     -10

df2 = df1.groupby('Customer', as_index=False).sum()
print (df2)
  Customer  value0  value1
0        A     -40     -30
1        B     -70       0

Or if want multiple by numeric columns:

df1 = df[df['seg'].isin(['a','b','c'])]
c = df1.select_dtypes(np.number).columns

a = np.where(df1['seg'].eq('a'), 1, -1)
df1[c] *= a[:, None]

df2 = df1.groupby('Customer', as_index=False).sum()
print (df2)
  Customer  value0  value1
0        A     -40     -30
1        B     -70       0


问:
Override @QueryParam annotation to trim whitespaces
Currently I'm working with Dropwizard and want to trim whitespaces from query parameters that are passed in, that match a specific key (in my case, query). I couldn't find documentation on how to do this.

The closest solution I've found, apart from manually trimming the whitespace, is to create a new annotation, however I'm trying to avoid changing dozens of endpoints, and would rather override the base annotation to apply the change.

答:
You could write a jetty servlet filter to modify that query param, see this thread for an example:
https://stackoverflow.com/a/1422202/52954

Then register that filter:

```<code>environment.servlets().addFilter("Custom-Filter-Name", new MyCustomFilter());
</code>```

Body:
You could write a jetty servlet filter to modify that query param, see this thread for an example:
https://stackoverflow.com/a/1422202/52954

Then register that filter:

environment.servlets().addFilter("Custom-Filter-Name", new MyCustomFilter());


问:
Response is not showing while fetching data from an api
I am trying to fetch data from an api but I am getting an following error I am unable to find out where the problem is I am using separate UI thread to fetech data then too app crashes.

```<code>2020-02-20 17:20:01.088 22802-22802/com.example.flypped E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flypped, PID: 22802
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
    at okio.RealBufferedSource.select(RealBufferedSource.kt:93)
    at okhttp3.internal.Util.readBomAsCharset(Util.kt:256)
    at okhttp3.ResponseBody.string(ResponseBody.kt:187)
    at com.example.flypped.MainActivity$2$1.run(MainActivity.java:110)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7156)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Suppressed: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.Util.skipAll(Util.kt:337)
    at okhttp3.internal.Util.discard(Util.kt:358)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
    at okio.ForwardingSource.close(ForwardingSource.kt:34)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
    at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
    at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
    at okhttp3.ResponseBody.string(ResponseBody.kt:186)
</code>```

Below is my code:

XML code:

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

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

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

<include layout="@layout/content_main" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/bottomBar"
    android:layout_gravity="bottom"
    app:menu="@menu/bottom_menu"
    android:background="#fff"
    app:itemIconTint="@drawable/nav_check"
    app:itemTextColor="@drawable/nav_check"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:id="@+id/nav_view">

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

        <include
            layout="@layout/nav_header"
            android:id="@+id/header"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:id="@+id/menuRecycler"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>

</com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>
</code>```

Java code:

```<code> private void getMenuData(){

    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder().url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                      //  Log.d("array", String.valueOf(jsonArray));

                       if(jsonArray.length() > 0){

                            for(int i=0;i<jsonArray.length();i++){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");
                                String str2 = jsonObject.getString("term_id");

                                MenuModel model = new MenuModel(str1,str2);
                                list.add(model);
                            }

                            adapter = new MenuAdapter(list,getApplicationContext());
                            menuRecycler.setAdapter(adapter);
                        }

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

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

    });

}
</code>```

Log cat showing error in below line

```<code>JSONArray jsonArray = new JSONArray(response.body().string());
</code>```

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

答:
Here try this code and see if it helps . Am making use of a handler on main thread, since the main issue is you can't use UI thread directly in response, neither can you update UI in background thread.

You'll need to declare 2 more global variables like:

```<code>    Handler mainHandler = new Handler(Looper.getMainLooper());
    String mStringResponse;
</code>```

and write your method as:

```<code>private void getMenuData(){

        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20,TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder().url(URL).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

                mStringResponse = String.valueOf(response.body());

                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONArray jsonArray = new JSONArray(mStringResponse);
                            if (jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    String str1 = jsonObject.getString("name");
                                    String str2 = jsonObject.getString("term_id");
                                    MenuModel model = new MenuModel(str1, str2);
                                    list.add(model);
                                }
                                adapter = new MenuAdapter(list, getApplicationContext());
                                menuRecycler.setAdapter(adapter);
                            }
                        }catch (JSONException e) { }

                    }
                });
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                          Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                            }
             }
        });

    }

</code>```

UI changes should work like this, not sure about your adapter restrictions, but try this and check if it helps.

Body:
I am trying to fetch data from an api but I am getting an following error I am unable to find out where the problem is I am using separate UI thread to fetech data then too app crashes.

2020-02-20 17:20:01.088 22802-22802/com.example.flypped E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.flypped, PID: 22802
android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.read(Exchange.kt:279)
    at okio.RealBufferedSource.select(RealBufferedSource.kt:93)
    at okhttp3.internal.Util.readBomAsCharset(Util.kt:256)
    at okhttp3.ResponseBody.string(ResponseBody.kt:187)
    at com.example.flypped.MainActivity$2$1.run(MainActivity.java:110)
    at android.os.Handler.handleCallback(Handler.java:873)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:214)
    at android.app.ActivityThread.main(ActivityThread.java:7156)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:975)
    Suppressed: android.os.NetworkOnMainThreadException
    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1513)
    at com.android.org.conscrypt.Platform.blockGuardOnNetwork(Platform.java:415)
    at com.android.org.conscrypt.ConscryptFileDescriptorSocket$SSLInputStream.read(ConscryptFileDescriptorSocket.java:560)
    at okio.InputStreamSource.read(Okio.kt:102)
    at okio.AsyncTimeout$source$1.read(AsyncTimeout.kt:159)
    at okio.RealBufferedSource.request(RealBufferedSource.kt:62)
    at okio.RealBufferedSource.require(RealBufferedSource.kt:55)
    at okio.RealBufferedSource.readHexadecimalUnsignedLong(RealBufferedSource.kt:299)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.readChunkSize(Http1ExchangeCodec.kt:450)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.read(Http1ExchangeCodec.kt:429)
    at okhttp3.internal.Util.skipAll(Util.kt:337)
    at okhttp3.internal.Util.discard(Util.kt:358)
    at okhttp3.internal.http1.Http1ExchangeCodec$ChunkedSource.close(Http1ExchangeCodec.kt:471)
    at okio.ForwardingSource.close(ForwardingSource.kt:34)
    at okhttp3.internal.connection.Exchange$ResponseBodySource.close(Exchange.kt:306)
    at okio.RealBufferedSource.close(RealBufferedSource.kt:461)
    at kotlin.io.CloseableKt.closeFinally(Closeable.kt:56)
    at okhttp3.ResponseBody.string(ResponseBody.kt:186)

Below is my code:

XML code:

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

<androidx.drawerlayout.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer_layout"
android:fitsSystemWindows="true"
tools:context=".MainActivity"
tools:openDrawer="start">

<androidx.coordinatorlayout.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

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

<include layout="@layout/content_main" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/bottomBar"
    android:layout_gravity="bottom"
    app:menu="@menu/bottom_menu"
    android:background="#fff"
    app:itemIconTint="@drawable/nav_check"
    app:itemTextColor="@drawable/nav_check"/>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

<com.google.android.material.navigation.NavigationView
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:id="@+id/nav_view">

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

        <include
            layout="@layout/nav_header"
            android:id="@+id/header"/>

        <androidx.recyclerview.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@+id/header"
            android:id="@+id/menuRecycler"
            android:layout_marginTop="20dp"/>

    </RelativeLayout>

</com.google.android.material.navigation.NavigationView>

</androidx.drawerlayout.widget.DrawerLayout>

Java code:

 private void getMenuData(){

    OkHttpClient client = new OkHttpClient.Builder()
            .readTimeout(20, TimeUnit.SECONDS)
            .writeTimeout(20,TimeUnit.SECONDS)
            .build();

    Request request = new Request.Builder().url(URL).build();

    client.newCall(request).enqueue(new Callback() {

        @Override
        public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    try {

                        JSONArray jsonArray = new JSONArray(response.body().string());

                      //  Log.d("array", String.valueOf(jsonArray));

                       if(jsonArray.length() > 0){

                            for(int i=0;i<jsonArray.length();i++){

                                JSONObject jsonObject = jsonArray.getJSONObject(i);

                                String str1 = jsonObject.getString("name");
                                String str2 = jsonObject.getString("term_id");

                                MenuModel model = new MenuModel(str1,str2);
                                list.add(model);
                            }

                            adapter = new MenuAdapter(list,getApplicationContext());
                            menuRecycler.setAdapter(adapter);
                        }

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

        @Override
        public void onFailure(@NotNull Call call, @NotNull final IOException e) {

            runOnUiThread(new Runnable() {
                @Override
                public void run() {

                    Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                }
            });
        }

    });

}

Log cat showing error in below line

JSONArray jsonArray = new JSONArray(response.body().string());

Someone please let me know what I am doing wrong.Any help would be appreciated.

THANKS

Body:
Here try this code and see if it helps . Am making use of a handler on main thread, since the main issue is you can't use UI thread directly in response, neither can you update UI in background thread.

You'll need to declare 2 more global variables like:

    Handler mainHandler = new Handler(Looper.getMainLooper());
    String mStringResponse;

and write your method as:

private void getMenuData(){

        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(20, TimeUnit.SECONDS)
                .writeTimeout(20,TimeUnit.SECONDS)
                .build();

        Request request = new Request.Builder().url(URL).build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onResponse(@NotNull Call call, @NotNull final Response response) throws IOException {

                mStringResponse = String.valueOf(response.body());

                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONArray jsonArray = new JSONArray(mStringResponse);
                            if (jsonArray.length() > 0) {
                                for (int i = 0; i < jsonArray.length(); i++) {
                                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                                    String str1 = jsonObject.getString("name");
                                    String str2 = jsonObject.getString("term_id");
                                    MenuModel model = new MenuModel(str1, str2);
                                    list.add(model);
                                }
                                adapter = new MenuAdapter(list, getApplicationContext());
                                menuRecycler.setAdapter(adapter);
                            }
                        }catch (JSONException e) { }

                    }
                });
            }
            @Override
            public void onFailure(@NotNull Call call, @NotNull final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                          Toast.makeText(getApplicationContext(),e.getMessage(),Toast.LENGTH_SHORT).show();
                            }
             }
        });

    }

UI changes should work like this, not sure about your adapter restrictions, but try this and check if it helps.


问:
how to debug system typeloadexception old VS
First of all, I already had a look at What could be causing a System.TypeLoadException?, and it did not solve my issue.

I am currently working with old, old, old, old code, writen in vb.net and csharp. This very old code was built with VS 2008, it is for a device that runs Windows Mobile, and the solution contains a few sdf files (databases).

I have already look at the top link and it is suggested to use fuslogvw.exe, but according to the documentation it is for VS 2019, so not for me.

The error is when I tried to get the computer name, any ideas of how to debug it? Everything that I have looked is for more modern VS

答: Found it, in windows, modules we can see the libraries, dlls and pdbs that were pull through. The problem was that one pdb was being blocked from being updated.</p>


问:
Issue in Adding large numbers in C# with int datatype
I am trying to add five large numbers in C# with int dataType. But the result was not correct. why .net is forcing me cast to long and perform the add to get the correct result.

```<code>using System;
public class Program
{
    public static void Main()
    {
        int i1= 256741038,i2=  623958417,i3=  467905213 ,i4= 714532089,i5=938071625;
        long l1= 256741038,l2=  623958417,l3=  467905213 ,l4= 714532089,l5=938071625;
        long result1=i2+i3+i4+i5;
        long result2=l2+l3+l4+l5;
        long result3=(long)l2+(long)l3+(long)l4+(long)l5;
        Console.WriteLine(result1);
        Console.WriteLine(result2);
        Console.WriteLine(result3);
        }
}
</code>```

答:
You can use checked keyword to see that long result1=i2+i3+i4+i5; is generating System.OverflowException: 'Arithmetic operation resulted in an overflow.', as other answers say. Valid result of your operation is 2,744,467,344, but max of the int (which is just Int32) is 2,147,483,647. Long type (aliasa for Int64) can contain up to 9,223,372,036,854,775,807 which is enough to add your numbers without overflow.

public static void Main()
{
    checked
    {
        int i1 = 256741038, i2 = 623958417, i3 = 467905213, i4 = 714532089, i5 = 938071625;
        long l1 = 256741038, l2 = 623958417, l3 = 467905213, l4 = 714532089, l5 = 938071625;
        long result1 = i2 + i3 + i4 + i5;
        long result2 = l2 + l3 + l4 + l5;
        long result3 = (long)l2 + (long)l3 + (long)l4 + (long)l5;
        Console.WriteLine(result1);
        Console.WriteLine(result2);
        Console.WriteLine(result3);
        Console.Read();
    }
}
```

Body:
I am trying to add five large numbers in C# with int dataType. But the result was not correct. why .net is forcing me cast to long and perform the add to get the correct result.

using System;
public class Program
{
    public static void Main()
    {
        int i1= 256741038,i2=  623958417,i3=  467905213 ,i4= 714532089,i5=938071625;
        long l1= 256741038,l2=  623958417,l3=  467905213 ,l4= 714532089,l5=938071625;
        long result1=i2+i3+i4+i5;
        long result2=l2+l3+l4+l5;
        long result3=(long)l2+(long)l3+(long)l4+(long)l5;
        Console.WriteLine(result1);
        Console.WriteLine(result2);
        Console.WriteLine(result3);
        }
}


问:
Why people[1].a don't have access to properties from class User?
Why people[1].a don't have access to properties from class User, but have need nested from through proto ?!

```<code>class User {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }

        static a = 12;
    }

    class User2 extends User {}

    let people = [
        new User2('Vasia', 20),
        new User2('Peter', 19),
        new User2('Misha', 21),
    ]

    console.dir(User2.a) // 12
    console.dir(people[1].a) // ?????
</code>```

答:
static properties appear on the Class objects. They do not appear on instances of the class.

They are intended to hold static methods.

From MDN:

The static keyword defines a static method for a class. Static methods aren't called on instances of the class. Instead, they're called on the class itself. These are often utility functions, such as functions to create or clone objects.

Body:
Why people[1].a don't have access to properties from class User, but have need nested from through proto ?!

class User {
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }

        static a = 12;
    }

    class User2 extends User {}

    let people = [
        new User2('Vasia', 20),
        new User2('Peter', 19),
        new User2('Misha', 21),
    ]

    console.dir(User2.a) // 12
    console.dir(people[1].a) // ?????


问:
Play / Stop buttons
I need to write a feature that will render multiple audio files and for each there will be a play button.
When individual button clicked, the audio is played and the button will turn to stop icon. How can I control each button individually in same component?

Here is an example I am working with

答:
You need to have a list it's better.

Try this :

TS :

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  playlist = [
    {name: 'music1', play : false},
    {name: 'music2', play : false},
    {name: 'music3', play : false}
  ]

  togglePlay(music :any) {
    music.play = !music.play;
  }
}
</code>```

HTML :

```<code><button *ngFor="let music of playlist" (click)="togglePlay(music)" mat-icon-button>
  <mat-icon class="blue"> {{ music.play ? 'stop_circle_outline' : 'play_circle_outline'}}</mat-icon>
</button>
</code>```

Title: Play / Stop buttons

Body:
You need to have a list it's better.

Try this :

TS :

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  playlist = [
    {name: 'music1', play : false},
    {name: 'music2', play : false},
    {name: 'music3', play : false}
  ]

  togglePlay(music :any) {
    music.play = !music.play;
  }
}

HTML :

<button *ngFor="let music of playlist" (click)="togglePlay(music)" mat-icon-button>
  <mat-icon class="blue"> {{ music.play ? 'stop_circle_outline' : 'play_circle_outline'}}</mat-icon>
</button>


问:
How to implement VerticalMultiDragGestureRecognizer bottom to up gesture in flutter?
I'm trying to implement a simple two fingers swipe (bottom to up and up to bottom) in flutter, with VerticalMultiDragGestureRecognizer, but couldn't find an fully example how to work with theses recognizer, tried with Listener widget and RawGestureDetector with GestureRecognizerFactoryWithHandlers, but didn't understand how should work with custom recognizers.

What I pretend:

Two fingers bottom to up triggers an event to show page A

Two fingers up to bottom triggers an event to show page B

Extra:

Just detect two fingers event is enought for me, but if is possible, can be controll the animation of page A or B transition? Like an "Slider"? (poping the new page as the hand's moviment of user progress)

Could any one help-me with this question?

答: I have created a sample gist on GitHub here that should guide you about how to detect two finger swipe.


问:
The While running Docker container getting error "current working directory, nor any of its parents, seems to be a Nanoc site"
My docker file

```<code>FROM ruby:latest

# Create app directory
WORKDIR /usr/src/app

COPY Gemfile .

# Copy the files
COPY . ./docs

RUN bundler install
RUN bundle exec nanoc

EXPOSE 5300
CMD [ "nanoc", "view" ]
</code>```

While Running the build container:

Step : 1

Successfully built 2fa7cc6d083b

Step : 2

```<code> root@ubuntu:/var/docs# docker run -p 0.0.0.0:4300:4300 --name nanoc-latest -t -d nanoc:latest

414b227902d15bbe831d8c77f7c68a3c2ca48ae20c9f20e68f92d52f55350b31
</code>```

Step : 3

```<code>root@ubuntu:/var/docs# docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED   STATUS              PORTS               NAMES
</code>```

Step : 4

```<code>root@ubuntu-s-2vcpu-2gb-sgp1-01:/var/docs# docker ps -a
</code>```

CONTAINER ID        IMAGE               COMMAND                  CREATED

                                                                                STATUS                     PORTS               NAMES

```<code>414b227902d1        nanoc:latest        "/bin/sh -c /usr/loc…"   9 seconds ago    Exited (1) 6 seconds ago  nanoc-latest
</code>```

Step : 5

```<code>root@ubuntu:/var/docs# sudo docker logs 414b227902d1
</code>```

A Gemfile was detected, but Bundler is not loaded. This is probably not what you                                                                                want. To run Nanoc with Bundler, use bundle exec nanoc.

Error:The current working directory, nor any of its parents, seems to be a Nano                                                                                c site.

I tried to open the nanoc image container

```<code>root@ubuntu:/var/docs#   docker run -ti --entrypoint=sh nanoc
# ls
Gemfile  Gemfile.lock  docs
# cd docs
# ls
Dockerfile  Gemfile  m1  m2  m3  m6
</code>```

So no nanoc file.

答:
Docker file:

```<code>FROM ruby:2.3
RUN mkdir -p /user/src/app
COPY . /usr/src/app
WORKDIR /usr/src/app/docs

RUN bundle install
RUN bundle exec nanoc
EXPOSE 3000
CMD bundle exec nanoc view
</code>```

Docker build command:

```<code>docker build -f Dockerfile -t nanoc:latest .
docker run -p 0.0.0.0:3000:3000 --name nanoc-latest -t -d nanoc:latest
</code>```

Successfully you get the deployed index.html file

Body:
My docker file

FROM ruby:latest

# Create app directory
WORKDIR /usr/src/app

COPY Gemfile .

# Copy the files
COPY . ./docs

RUN bundler install
RUN bundle exec nanoc

EXPOSE 5300
CMD [ "nanoc", "view" ]

While Running the build container:

Step : 1

Successfully built 2fa7cc6d083b

Step : 2

 root@ubuntu:/var/docs# docker run -p 0.0.0.0:4300:4300 --name nanoc-latest -t -d nanoc:latest

414b227902d15bbe831d8c77f7c68a3c2ca48ae20c9f20e68f92d52f55350b31

Step : 3

root@ubuntu:/var/docs# docker ps

CONTAINER ID        IMAGE               COMMAND             CREATED   STATUS              PORTS               NAMES

Step : 4

root@ubuntu-s-2vcpu-2gb-sgp1-01:/var/docs# docker ps -a

CONTAINER ID        IMAGE               COMMAND                  CREATED

                                                                                STATUS                     PORTS               NAMES

414b227902d1        nanoc:latest        "/bin/sh -c /usr/loc…"   9 seconds ago    Exited (1) 6 seconds ago  nanoc-latest

Step : 5

root@ubuntu:/var/docs# sudo docker logs 414b227902d1

A Gemfile was detected, but Bundler is not loaded. This is probably not what you                                                                                want. To run Nanoc with Bundler, use bundle exec nanoc.

Error:The current working directory, nor any of its parents, seems to be a Nano                                                                                c site.

I tried to open the nanoc image container

root@ubuntu:/var/docs#   docker run -ti --entrypoint=sh nanoc
# ls
Gemfile  Gemfile.lock  docs
# cd docs
# ls
Dockerfile  Gemfile  m1  m2  m3  m6

So no nanoc file.

Body:
Docker file:

FROM ruby:2.3
RUN mkdir -p /user/src/app
COPY . /usr/src/app
WORKDIR /usr/src/app/docs

RUN bundle install
RUN bundle exec nanoc
EXPOSE 3000
CMD bundle exec nanoc view

Docker build command:

docker build -f Dockerfile -t nanoc:latest .
docker run -p 0.0.0.0:3000:3000 --name nanoc-latest -t -d nanoc:latest

Successfully you get the deployed index.html file


问:
How can I print_r an array from controller while an ajax process?
I am trying to debug my AJAX call to database.

But there is no way to see the data i am using. I have tried to do it inserting some Javascript:

I also tried to use print_r, but nothing happens.

Is there any way to see my variables? A developer tool for example, or any command i could use.

Thanks for your help.

```<code>function console_log( $data ){
    echo '<script>';
    echo 'console.log('. json_encode( $data ) .')';
    echo '</script>';
}
</code>```

This is my controller code:

```<code>public function searchEvents(){
        $request = Request::createFromGlobals();
        if($request->getMethod()=='POST') {
            $value = $request->request->get('searchBox');
            $em=$this->getDoctrine()->getManager();
            $searchFor = $request->request->get('value');
            $qb = $em->createQueryBuilder();
            //$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
            $query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
            $query->setParameter('value', '%'.$searchFor.'%');
            $eventos = $query->getResult();
            /*$qb->select('u')
                ->from('App:Evento','u')
                ->where(('u.title = '.$searchFor));
            $query = $qb->getQuery();
            $eventos = $query->getResult();*/
            $response = [];
            foreach($eventos as $evento){
                array_unshift($response,[
                    $evento->getTitle(),
                    $evento->getFecha()
                ]);
                print_r($response);
            }
            $respuesta = new JsonResponse();
            $respuesta->setData(
                array('response'=>'success',
                    'eventos'=>$response)
            );
        }
        return $respuesta;
}
</code>```

And my js code:

```<code>function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: value=2,
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}
</code>```

答: Not sure if I understand you question correctly, but AJAX requests have to be debugged separately using symfony developer toolbar or by peeking request in browsers dev tools → Network tab. You can also check var/log/dev.log</p>

Body:
I am trying to debug my AJAX call to database.

But there is no way to see the data i am using. I have tried to do it inserting some Javascript:

I also tried to use print_r, but nothing happens.

Is there any way to see my variables? A developer tool for example, or any command i could use.

Thanks for your help.

function console_log( $data ){
    echo '';
}

This is my controller code:

public function searchEvents(){
        $request = Request::createFromGlobals();
        if($request->getMethod()=='POST') {
            $value = $request->request->get('searchBox');
            $em=$this->getDoctrine()->getManager();
            $searchFor = $request->request->get('value');
            $qb = $em->createQueryBuilder();
            //$eventos = $em->getRepository('App:Evento')->findBy(array('title'=>'Invi Chuwi'));
            $query = $em->createQuery('SELECT e FROM App:Evento e WHERE e.title LIKE :value');
            $query->setParameter('value', '%'.$searchFor.'%');
            $eventos = $query->getResult();
            /*$qb->select('u')
                ->from('App:Evento','u')
                ->where(('u.title = '.$searchFor));
            $query = $qb->getQuery();
            $eventos = $query->getResult();*/
            $response = [];
            foreach($eventos as $evento){
                array_unshift($response,[
                    $evento->getTitle(),
                    $evento->getFecha()
                ]);
                print_r($response);
            }
            $respuesta = new JsonResponse();
            $respuesta->setData(
                array('response'=>'success',
                    'eventos'=>$response)
            );
        }
        return $respuesta;
}

And my js code:

function searchForEvents(value){
    $.ajax({
        method:"POST",
        data: value=2,
        url:"{{ path('searchEvents') }}",
        dataType:'json',
        success: function(data){
            //var results = JSON.parse(data.events);
            alert(JSON.stringify(data, null, 4));
            //putEvents(results);
        }
    })
}


问:
How to separate full name string into firstname and lastname string?
I need some help with this, I have a fullname string and what I need to do is separate and use this fullname string as firstname and lastname separately. </p>

答:
There is more than one method for this. My specific situation is solved with a code example like below.

for Example

if there is only one space in the user's name.

```<code> int idx = fullName.IndexOf(' '); //This customer name : Osman Veli
</code>```

if there is more than one space in the user's name.

```<code> if (fullName.Count(Char.IsWhiteSpace) > 1)
 {
    idx = fullName.LastIndexOf(' '); //This customer name : Osman Veli Sağlam
 }

  if (idx != -1)
  {
    // Osman Veli Sağlam
    firstName = fullName.Substring(0, idx); // FirstName: Osman Veli
    lastName = fullName.Substring(idx + 1); // LastName : Sağlam
   }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
There is more than one method for this. My specific situation is solved with a code example like below.

for Example

if there is only one space in the user's name.

 int idx = fullName.IndexOf(' '); //This customer name : Osman Veli

if there is more than one space in the user's name.

 if (fullName.Count(Char.IsWhiteSpace) > 1)
 {
    idx = fullName.LastIndexOf(' '); //This customer name : Osman Veli Sağlam
 }

  if (idx != -1)
  {
    // Osman Veli Sağlam
    firstName = fullName.Substring(0, idx); // FirstName: Osman Veli
    lastName = fullName.Substring(idx + 1); // LastName : Sağlam
   }


问:
R function/loop to get column wise values
```<code>GT  VB  WM
23  34  28
34  27  33
    44  46
    54
</code>```

I have a data like above in a csv file.I need a R script to retrieve by column wise values either by loop or function when passing arguments as a variable name.Ex. When I type GT I should get relevant values without NA like

```<code>GT
23 34
</code>```

答:
This

```<code>lapply(df, na.omit)
</code>```

creates a list of vector where all NAs are removed.

Body:
GT  VB  WM
23  34  28
34  27  33
    44  46
    54

I have a data like above in a csv file.I need a R script to retrieve by column wise values either by loop or function when passing arguments as a variable name.Ex. When I type GT I should get relevant values without NA like

GT
23 34

Body:
This

lapply(df, na.omit)

creates a list of vector where all NAs are removed.


问:
Apple notarization lists dylib files as not signed
We distribute a Java application with a bundled JRE, 1.8.0_172. I sign the app using the flags -f --deep and --options runtime. Looking at the CodeResources file in the _CodeSignature directory of the bundled JRE, every file in the JRE is signed and accounted for.

However, after submitting a DMG containing the app to Apple for notarizing, our software is rejected. ALL 60 DYLIB FILES IN THE JRE ARE LISTED AS NOT SIGNED. Here is an example:

From the CodeResources file:

```<code><key>Home/jre/lib/libAppleScriptEngine.dylib</key>
    <dict>
        <key>hash</key>
        <data>
        oJjQQGky4LuYNhwuBu8zMLG4zbc=
        </data>
        <key>hash2</key>
        <data>
        grMACw0q7A9GJyPxlSBDGYEkZKrDusKLRRnXsW/bHGI=
        </data>
    </dict>
</code>```

From the response from Apple:

```<code>"severity": "error",
"code": null,
"path": "TheApplication.dmg/TheApplication.app/Contents/PlugIns/jdk1.8.0_172.jdk/Contents/Home/jre/lib/libAppleScriptEngine.dylib",
"message": "The binary is not signed.",
"docUrl": null,
"architecture": "x86_64"
</code>```

In addition to the dylib files, the file jspawnhelper is also rejected as not signed.

Lastly, the file libjli.dylib is rejected for the following reason:
"The binary uses an SDK older than the 10.9 SDK."

Has anyone encountered a similar problem and then been able to pass the notarization process?

January 14, 2020:
The steps I used from this website http://www.zarkonnen.com/signing_notarizing_catalina
do not work as of today. Apple changed their restrictions. I now have the same issues as I first asked about in this post.

February 21, 2020:
It turned out the files listed as not signed were in fact not signed. I now use a shell script to recursively sign every file in our application. I follow that with overall signing of the bundled JRE, other internal apps, and lastly the entire app at the top level.

The remaining problem is Java 8 is not built with files that use the hardened runtime. Hopefully OpenJDK and/or AdoptOpenJDK will soon have new versions of Java 8 that satisfy Apple's hardened runtime requirements.

答:
This is a bug in Java 8: https://bugs.openjdk.java.net/browse/JDK-8223671

The fastest solution to this problem might come from AdoptOpenJDK hopefully by the end of current month: https://github.com/AdoptOpenJDK/openjdk-build/issues/1130

Body:
We distribute a Java application with a bundled JRE, 1.8.0_172. I sign the app using the flags -f --deep and --options runtime. Looking at the CodeResources file in the _CodeSignature directory of the bundled JRE, every file in the JRE is signed and accounted for.

However, after submitting a DMG containing the app to Apple for notarizing, our software is rejected. ALL 60 DYLIB FILES IN THE JRE ARE LISTED AS NOT SIGNED. Here is an example:

From the CodeResources file:

<key>Home/jre/lib/libAppleScriptEngine.dylib</key>
    <dict>
        <key>hash</key>
        <data>
        oJjQQGky4LuYNhwuBu8zMLG4zbc=
        </data>
        <key>hash2</key>
        <data>
        grMACw0q7A9GJyPxlSBDGYEkZKrDusKLRRnXsW/bHGI=
        </data>
    </dict>

From the response from Apple:

"severity": "error",
"code": null,
"path": "TheApplication.dmg/TheApplication.app/Contents/PlugIns/jdk1.8.0_172.jdk/Contents/Home/jre/lib/libAppleScriptEngine.dylib",
"message": "The binary is not signed.",
"docUrl": null,
"architecture": "x86_64"

In addition to the dylib files, the file jspawnhelper is also rejected as not signed.

Lastly, the file libjli.dylib is rejected for the following reason:
"The binary uses an SDK older than the 10.9 SDK."

Has anyone encountered a similar problem and then been able to pass the notarization process?

January 14, 2020:
The steps I used from this website http://www.zarkonnen.com/signing_notarizing_catalina
do not work as of today. Apple changed their restrictions. I now have the same issues as I first asked about in this post.

February 21, 2020:
It turned out the files listed as not signed were in fact not signed. I now use a shell script to recursively sign every file in our application. I follow that with overall signing of the bundled JRE, other internal apps, and lastly the entire app at the top level.

The remaining problem is Java 8 is not built with files that use the hardened runtime. Hopefully OpenJDK and/or AdoptOpenJDK will soon have new versions of Java 8 that satisfy Apple's hardened runtime requirements.


问:
How does google-visualization-tooltip calculate the left and top values?
How does google-visualization-tooltip calculate the left and top values for style ?
example - on debugging i can see that :-

```<code><div class="google-visualization-tooltip" style="width: 1px; height: 0px; left: 453.25px; top: 44.91px;"</div>
</code>```

How can i calculate this relatively, so that the tooltip shows on top and is center aligned to the point that is hovered upon, irrespective of the width of the element?

答:
most charts in the 'corechart' package,

have methods for getting the position of various chart elements.

first, get the chart's layout interface...

```<code>var chartLayout = chart.getChartLayoutInterface();
</code>```

the layout interface has method --> getBoundingBox(id)

where id is a string id of the chart element.

to find the position of a point, use this format for id --> point#series#row -- point#0#0

we can use chart event onmouseover to know when a point has been hovered,

and the tooltip is being shown.

the onmouseover event sends an argument with the row and column from the data table,

of the point that is being hovered.

as such, we can get the layout, find the point, and position the tooltip.

```<code>google.visualization.events.addListener(chart, 'onmouseover', function (sender) {
  // ensure point is hovered
  if (sender.row !== null) {
    var padding = 16;
    var chartLayout = chart.getChartLayoutInterface();
    var pointBounds = chartLayout.getBoundingBox('point#' + (sender.column - 1) + '#' + sender.row);
    var tooltip = chart.getContainer().getElementsByClassName('google-visualization-tooltip');
    if (tooltip.length > 0) {
      var tooltipBounds = tooltip[0].getBoundingClientRect();
      tooltip[0].style.top = (pointBounds.top - tooltipBounds.height - padding) + 'px';
      tooltip[0].style.left = ((pointBounds.left + (pointBounds.width / 2)) - (tooltipBounds.width  / 2)) + 'px';
    }
  }
});
</code>```

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable({
    "cols": [
      {"label": "x", "type": "number"},
      {"label": "y", "type": "number"}
    ],
    "rows": [
      {"c":[{"v": 2015}, {"v": 1}]},
      {"c":[{"v": 2016}, {"v": 2}]},
      {"c":[{"v": 2017}, {"v": 3}]},
      {"c":[{"v": 2018}, {"v": 4}]},
      {"c":[{"v": 2019}, {"v": 5}]},
      {"c":[{"v": 2020}, {"v": 6}]}
    ]
  });

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

  google.visualization.events.addListener(chart, 'onmouseover', function (sender) {
    // ensure point is hovered
    if (sender.row !== null) {
      var padding = 16;
      var chartLayout = chart.getChartLayoutInterface();
      var pointBounds = chartLayout.getBoundingBox('point#' + (sender.column - 1) + '#' + sender.row);
      var tooltip = chart.getContainer().getElementsByClassName('google-visualization-tooltip');
      if (tooltip.length > 0) {
        var tooltipBounds = tooltip[0].getBoundingClientRect();
        tooltip[0].style.top = (pointBounds.top - tooltipBounds.height - padding) + 'px';
        tooltip[0].style.left = ((pointBounds.left + (pointBounds.width / 2)) - (tooltipBounds.width  / 2)) + 'px';
      }
    }
  });

  var options = {
    chartArea: {
      bottom: 32,
      left: 32,
      right: 32,
      top: 48,
      width: '100%',
      height: '100%'
    },
    hAxis: {
      format: '0',
      ticks: data.getDistinctValues(0)
    },
    legend: {
      position: 'top'
    },
    pointSize: 4,
    tooltip: {
      isHtml: true,
      trigger: 'both'
    }
  };

  chart.draw(data, options);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div></code>```

Body:
How does google-visualization-tooltip calculate the left and top values for style ?
example - on debugging i can see that :-

<div class="google-visualization-tooltip" style="width: 1px; height: 0px; left: 453.25px; top: 44.91px;"

How can i calculate this relatively, so that the tooltip shows on top and is center aligned to the point that is hovered upon, irrespective of the width of the element?

Body:
most charts in the 'corechart' package,

have methods for getting the position of various chart elements.

first, get the chart's layout interface...

var chartLayout = chart.getChartLayoutInterface();

the layout interface has method --> getBoundingBox(id)

where id is a string id of the chart element.

to find the position of a point, use this format for id --> point#series#row -- point#0#0

we can use chart event onmouseover to know when a point has been hovered,

and the tooltip is being shown.

the onmouseover event sends an argument with the row and column from the data table,

of the point that is being hovered.

as such, we can get the layout, find the point, and position the tooltip.

google.visualization.events.addListener(chart, 'onmouseover', function (sender) {
  // ensure point is hovered
  if (sender.row !== null) {
    var padding = 16;
    var chartLayout = chart.getChartLayoutInterface();
    var pointBounds = chartLayout.getBoundingBox('point#' + (sender.column - 1) + '#' + sender.row);
    var tooltip = chart.getContainer().getElementsByClassName('google-visualization-tooltip');
    if (tooltip.length > 0) {
      var tooltipBounds = tooltip[0].getBoundingClientRect();
      tooltip[0].style.top = (pointBounds.top - tooltipBounds.height - padding) + 'px';
      tooltip[0].style.left = ((pointBounds.left + (pointBounds.width / 2)) - (tooltipBounds.width  / 2)) + 'px';
    }
  }
});

see following working snippet...

google.charts.load('current', {
  packages: ['corechart']
}).then(function () {
  var data = new google.visualization.DataTable({
    "cols": [
      {"label": "x", "type": "number"},
      {"label": "y", "type": "number"}
    ],
    "rows": [
      {"c":[{"v": 2015}, {"v": 1}]},
      {"c":[{"v": 2016}, {"v": 2}]},
      {"c":[{"v": 2017}, {"v": 3}]},
      {"c":[{"v": 2018}, {"v": 4}]},
      {"c":[{"v": 2019}, {"v": 5}]},
      {"c":[{"v": 2020}, {"v": 6}]}
    ]
  });

  var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

  google.visualization.events.addListener(chart, 'onmouseover', function (sender) {
    // ensure point is hovered
    if (sender.row !== null) {
      var padding = 16;
      var chartLayout = chart.getChartLayoutInterface();
      var pointBounds = chartLayout.getBoundingBox('point#' + (sender.column - 1) + '#' + sender.row);
      var tooltip = chart.getContainer().getElementsByClassName('google-visualization-tooltip');
      if (tooltip.length > 0) {
        var tooltipBounds = tooltip[0].getBoundingClientRect();
        tooltip[0].style.top = (pointBounds.top - tooltipBounds.height - padding) + 'px';
        tooltip[0].style.left = ((pointBounds.left + (pointBounds.width / 2)) - (tooltipBounds.width  / 2)) + 'px';
      }
    }
  });

  var options = {
    chartArea: {
      bottom: 32,
      left: 32,
      right: 32,
      top: 48,
      width: '100%',
      height: '100%'
    },
    hAxis: {
      format: '0',
      ticks: data.getDistinctValues(0)
    },
    legend: {
      position: 'top'
    },
    pointSize: 4,
    tooltip: {
      isHtml: true,
      trigger: 'both'
    }
  };

  chart.draw(data, options);
});

<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>


答:
With a few exceptions, type resolution in C# doesn't care about the type you're assigning to. All the compiler is considering in your case is

```<code>i2 + i3 + i4 + i5
</code>```

Since each of the operands is of type int, the result is also of type int (or, more accurately, it uses the addition operator that takes two ints as arguments and returns int), even though you later assign it to a long local.

By casting one of the operands to long, the int, int -> int operator no longer fits, and the long, long -> long is chosen. The same is true of float, for example - as soon as one of the operands is float, the result is float - otherwise,  a / b gives you integer division (operator int, int -> int).

In general, you need to make sure the data type you're working with is big enough to hold the result and any intermediate values. If you expect a result that doesn't fit into an int, don't use int. By default, C# doesn't check for overflows - you can override it like this:

```<code>var result = checked(i2 + i3 + i4 + i5);
</code>```

This way, instead of silently wrapping around to the wrong int value, you get an exception.

Title: Issue in Adding large numbers in C# with int datatype

Body:
With a few exceptions, type resolution in C# doesn't care about the type you're assigning to. All the compiler is considering in your case is

i2 + i3 + i4 + i5

Since each of the operands is of type int, the result is also of type int (or, more accurately, it uses the addition operator that takes two ints as arguments and returns int), even though you later assign it to a long local.

By casting one of the operands to long, the int, int -> int operator no longer fits, and the long, long -> long is chosen. The same is true of float, for example - as soon as one of the operands is float, the result is float - otherwise,  a / b gives you integer division (operator int, int -> int).

In general, you need to make sure the data type you're working with is big enough to hold the result and any intermediate values. If you expect a result that doesn't fit into an int, don't use int. By default, C# doesn't check for overflows - you can override it like this:

var result = checked(i2 + i3 + i4 + i5);

This way, instead of silently wrapping around to the wrong int value, you get an exception.


问:
GitKraken won't let me open my Private Repository on GitLab
So, in addition to GitKraken won't let me clone from a private repo on GitHub
I get this screen when opening my GitLab Repo:

Anyone got a solution of how to make my Repo 'non-private' or how to make GitKraken let me open this without the Pro Plan?

Already tried:

Generating new SSH Key in GitKraken

Removing Repo, Generate new GitLab connection, Clone Repo

Checked GitLab: GitKraken is an Authorized applications

Git Pull via command line gives no trouble, so no permission issue

...

答: My solution is to uninstall GitKraken and install Fork, a very similar program with all the options that I have used previously in GitKraken. It's free and has a dark mode too :-)</p>


问:
Android service gets killed on swiping out the application
I have an Android Service class the code for which is as follows:

```<code>public class LoginService extends Service {
BroadcastReceiver wifiStateChangeReciever;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("AndroidLearning", "Service onStartCommand Started.");
    return Service.START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i("AndroidLearning", "Service Started.");

    final IntentFilter intentFilter = new IntentFilter();
    // intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
    intentFilter.addAction("android.net.wifi.STATE_CHANGE");
    wifiStateChangeReciever = new WifiStateChangeReciever();
    this.registerReceiver(wifiStateChangeReciever, intentFilter, null, null);

    Log.i("AndroidLearning", "Reciever Registered.");
}

@Override
public void onDestroy() {
    Log.i("AndroidLearning", "Service Destroyed.");
    this.unregisterReceiver(wifiStateChangeReciever);
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    Log.w("AndroidLearning", "On Task Remove: FLAG_STOP_WITH_TASK - "
            + ServiceInfo.FLAG_STOP_WITH_TASK);
    this.unregisterReceiver(wifiStateChangeReciever);
    Intent restartServiceIntent = new Intent(getApplicationContext(),
    this.getClass()); restartServiceIntent.setPackage(getPackageName());
    PendingIntent restartServicePendingIntent = PendingIntent.getService(
            getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
    alarmService.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent);
    Log.w("AndroidLearning", "End on task removed");
    super.onTaskRemoved(rootIntent);

}
}
</code>```

It registers a BroadcastReciever. The Activity which starts this service has the following code:

```<code>Intent intent = new Intent(this, LoginService.class);
startService(intent);
</code>```

However whenever the Activity is swiped out from the task list (recent) the service is also stopped. I over rode the onTaskRemoved to remedy it but it still does not seem to work and the AlarmManager never starts the pendingIntent. I have tries using both method: set and setExact for the AlarmManager.

I also tried adding the following options to <service> tags

```<code>android:stopWithTask="false"
android:process=":remote"
</code>```

but to no avail.

What am I doing wrong here? Thanks for the help.

答:
If you try this on some devices, sadly, it won't work.

Some OEMs decided to change the normal behavior of what happens when you remove an app from the recent tasks, so they become semi-disabled:

https://issuetracker.google.com/issues/122098785

https://dontkillmyapp.com/

Body:
I have an Android Service class the code for which is as follows:

public class LoginService extends Service {
BroadcastReceiver wifiStateChangeReciever;

@Override
public IBinder onBind(Intent arg0) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("AndroidLearning", "Service onStartCommand Started.");
    return Service.START_STICKY;
}

@Override
public void onCreate() {
    super.onCreate();
    Log.i("AndroidLearning", "Service Started.");

    final IntentFilter intentFilter = new IntentFilter();
    // intentFilter.addAction("android.net.wifi.WIFI_STATE_CHANGED");
    intentFilter.addAction("android.net.wifi.STATE_CHANGE");
    wifiStateChangeReciever = new WifiStateChangeReciever();
    this.registerReceiver(wifiStateChangeReciever, intentFilter, null, null);

    Log.i("AndroidLearning", "Reciever Registered.");
}

@Override
public void onDestroy() {
    Log.i("AndroidLearning", "Service Destroyed.");
    this.unregisterReceiver(wifiStateChangeReciever);
}

@Override
public void onTaskRemoved(Intent rootIntent) {
    Log.w("AndroidLearning", "On Task Remove: FLAG_STOP_WITH_TASK - "
            + ServiceInfo.FLAG_STOP_WITH_TASK);
    this.unregisterReceiver(wifiStateChangeReciever);
    Intent restartServiceIntent = new Intent(getApplicationContext(),
    this.getClass()); restartServiceIntent.setPackage(getPackageName());
    PendingIntent restartServicePendingIntent = PendingIntent.getService(
            getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
    alarmService.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent);
    Log.w("AndroidLearning", "End on task removed");
    super.onTaskRemoved(rootIntent);

}
}

It registers a BroadcastReciever. The Activity which starts this service has the following code:

Intent intent = new Intent(this, LoginService.class);
startService(intent);

However whenever the Activity is swiped out from the task list (recent) the service is also stopped. I over rode the onTaskRemoved to remedy it but it still does not seem to work and the AlarmManager never starts the pendingIntent. I have tries using both method: set and setExact for the AlarmManager.

I also tried adding the following options to <service> tags

android:stopWithTask="false"
android:process=":remote"

but to no avail.

What am I doing wrong here? Thanks for the help.


问:
Jquery when appending text to html charset utf8 not working
When I'm passing information to a div inside html the charset utf 8 is not recognized and it comes with interrogation points inside the text.
Is there a way to force the charset utf 8 inside jquery so all the text passed by the script comes in the correct charset?

Edit:
I think I set all the charsets I could inside all my files:
HTML

```<code><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Type:application/json; charset=UTF-8" />
<script type="text/javascript" src="scripts/jquery-1.9.0.min.js" charset="utf-8"></script>
<script type="text/javascript" src="message_validator.js" charset="utf-8"></script>
</head>
<body>
<div class="error_display" charset="utf-8"></div>
<form charset="utf-8">
<input type="text" id="name" class="textbox" name="name" minlength="2" maxlength="12" />
</form>
</body>
</code>```

JQUERY

```<code> $(document).ready(function() {
    $(document).load("Content-Type:application/json; charset=UTF-8");
    $('.submit').click(function(){
        var errorlist = [];
        errorlist.length = 0;

        errorlist.push("- Tem de preencher os campos obrigatórios.");

         if(errorlist.length >= 1){
            $('.error_display').animate({'height':errorlist.length*20}, {queue:false, duration:500});
            for(var i = 0; i < errorlist.length; i++) {
                $('.error_display').append(errorlist[i]+"<br/>");
            }

         }
    });
});
</code>```

答:
One thing that one should be aware of, is taht the encoding of the script file itself can result in this error. Make sure that your script file is encoded correctly. In Visual Studio, this is done by:

Opening the file and do a "Save as"

click the chrevon down next to the Save button and choose "Save with encoding"

Choose your required encoding

It varies a bit from IDE to IDE, but the gist is the same

Body:
When I'm passing information to a div inside html the charset utf 8 is not recognized and it comes with interrogation points inside the text.
Is there a way to force the charset utf 8 inside jquery so all the text passed by the script comes in the correct charset?

Edit:
I think I set all the charsets I could inside all my files:
HTML

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Type:application/json; charset=UTF-8" />

<form charset="utf-8">
<input type="text" id="name" class="textbox" name="name" minlength="2" maxlength="12" />
</form>

JQUERY

 $(document).ready(function() {
    $(document).load("Content-Type:application/json; charset=UTF-8");
    $('.submit').click(function(){
        var errorlist = [];
        errorlist.length = 0;

        errorlist.push("- Tem de preencher os campos obrigatórios.");

         if(errorlist.length >= 1){
            $('.error_display').animate({'height':errorlist.length*20}, {queue:false, duration:500});
            for(var i = 0; i < errorlist.length; i++) {
                $('.error_display').append(errorlist[i]+"
");
            }

         }
    });
});


问:
Export bitfield to an array
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

```<code>union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];
</code>```

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

答:
Instead of using bit fields, use just an array of uint8_t and access each bit using shifts and masks. There is actually no other way to access bits by index in standard C (not counting any library implementations).

```<code>uint8_t data[SIZE];
...
data[bitIndex >> 3] |= 1 << (bitIndex & 7);  // set bit at bitIndex
data[bitIndex >> 3] &= ~(1 << (bitIndex & 7); // clear bit at bitIndex
bitValue = !!(data[bitIndex >> 3] & (1 << bitIndex & 7)); // read bit at bitIndex
</code>```

Using larger types (16, 32, 64) can be more efficient but requires suitably changed shifts and masks (eg, 4 and 15 for uint16_t).

Title: Export bitfield to an array

Body:
I've declared this bit field. What I am trying to do is to get the whole value of the bitfield in binary and convert it into an array so I can use the index and address every '1' value.

union{
    struct shape{
        uint8_t p0 : 1;
        uint8_t p1 : 1;
        uint8_t p2 : 1;
        uint8_t p3 : 1;
        uint8_t p4 : 1;
        uint8_t p5 : 1;
        uint8_t p6 : 1;
        uint8_t p7 : 1;
    };
    uint8_t row;
}rows[8*2+4];

what I am trying to do is to export the bitfield to have it an array like uint8_t tab[8] = {0,1,1,0,0,1,0,1};

Is that even possible? Any tips?
Thanks in advance

Body:
Instead of using bit fields, use just an array of uint8_t and access each bit using shifts and masks. There is actually no other way to access bits by index in standard C (not counting any library implementations).

uint8_t data[SIZE];
...
data[bitIndex >> 3] |= 1 << (bitIndex & 7);  // set bit at bitIndex
data[bitIndex >> 3] &= ~(1 << (bitIndex & 7); // clear bit at bitIndex
bitValue = !!(data[bitIndex >> 3] & (1 << bitIndex & 7)); // read bit at bitIndex

Using larger types (16, 32, 64) can be more efficient but requires suitably changed shifts and masks (eg, 4 and 15 for uint16_t).


问:
sending email programmatically using default user account
I want to be able to send an email out of my app, based on the user pressing a button on my app's Activity. The email needs to be sent automatically by the application upon button press, i.e. I don't want to show another email form to the user. And the email should be sent using the user's default email account on the phone not an email account that I hardcode into my app. And I don't want to have the user key in their email credentials into my app's configuration, I just want to be able to call some android api and say "send this email with this subject and body to this email address, using the default account that the user has set up on the phone".

Is this possible? If so, how?

答:
To send in the background, see the first link at your right on the list of related questions:

You need to use an email API such as JavaMail:

Sending Email in Android using JavaMail API without using the default/built-in app

Update based on the comments:

There is no way to send an email silently, without either:

letting the user know and accept it first (by using intents and an email provider)

or asking for the username and password before and using an email API as above (the user will implicitly give you the approval to send/receive emails by entering those values)

And that is a very good thing! There are too many security concerns otherwise. If you ever find a way, please post it as a bug report in android.


问:
How to implement free plans in Stripe
To implement a free plan for a subscription, I have created a plan with a monthly charge of $0.

Is this the correct way to subscribe users to a free plan so that they don't have to pay?

Will users still get invoices when they are subscribed to a free plan? If so, how can I avoid sending invoices to those subscribed to the free plan?

答:
If you want to track a subscription with a zero plan on Stripe it will of course work. I use zero plans all the time.

All the invoices will be generated each month but will have a zero value which means they will automatically be marked as paid.

Invoice was finalized and automatically marked as paid because the amount due was 0.00kr

I am using custom accounts with custom integration so there is no automatic email going out from stripe for me, but I do receive the entire stack of events like I would any normal invoice which i have to deal with.

The event progression is: Invoice created -> finalized -> paid -> changed. Although instant the webhook events all come in.

There is no issue with zero plans, everything shows up in the Stripe admin and works just like any subscription. You can start out with a free plan and upgrade them later - the payment information is gathered and can be charged later so it is all good.

Title: How to implement free plans in Stripe


问:
Set-Cookie is stopping me from logging into WordPress
I am running WordPress 5.3.2 on Apache/2.4.29 (Ubuntu) 18.04 on a Digital Ocean droplet.

My client requested the following:

All cookies transferred over an encrypted session, in particular session cookies, should be marked as 'Secure' and all session information should be transmitted over HTTPS.

The HttpOnly flag should also be set within the cookie

So, I defined the following in the virtual host:

```<code>Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure;SameSite=Strict
</code>```

I then tested the header response and could see my Set-Cookie defined.

The problem is, I now can't login to WordPress. WordPress says:

ERROR: cookies are blocked or not supported by your browser. You must
  enable cookies to use WordPress.

What am I doing wrong?

答:
Strict is probably more restrictive than you want, as this will prevent cookies from being sent on initial cross-site navigations, e.g. if I emailed you a link to a page on your blog, when you first followed that link, the SameSite=Strict cookies would not be sent and it might appear as if you were not logged in.

SameSite=Lax is a better default here. Then I would explicitly look at setting SameSite=Strict or SameSite=None on individual cookies where you know the level of access required.

The HttpOnly attribute is also blanket preventing all of your server-side set cookies from being read by JavaScript. You may well have functionality on your page that requires this.

Finally, a blanket approach here is probably overkill - as it looks as if you will be appending this snippet to every outgoing cookie header, even the ones that already include those attributes. This is likely to cause some unpredictable behaviour. I would either do this on a specific allow-list basis by checking for explicit cookie names or I would alter the regex to only set this if those attributes are missing.

Body:
I am running WordPress 5.3.2 on Apache/2.4.29 (Ubuntu) 18.04 on a Digital Ocean droplet.

My client requested the following:

All cookies transferred over an encrypted session, in particular session cookies, should be marked as 'Secure' and all session information should be transmitted over HTTPS.

The HttpOnly flag should also be set within the cookie

So, I defined the following in the virtual host:

Header edit Set-Cookie ^(.*)$ $1;HttpOnly;Secure;SameSite=Strict

I then tested the header response and could see my Set-Cookie defined.

The problem is, I now can't login to WordPress. WordPress says:

ERROR: cookies are blocked or not supported by your browser. You must
  enable cookies to use WordPress.

What am I doing wrong?


问:
Javascript : Increase a Date object by a year
I'm assign a new date object to my object attribute like that :

giftObject.purshasedDate = new Date()

which give a date format :

Date Thu Feb 20 2020 13:36:37 GMT+0100 (heure normale d’Europe
  centrale)

I want to increase this date by one year, I tried :

new Date().setFullYear(giftObject.purshasedDate.getFullYear() + 1) but it give a number serial like this : 1613824899244

I do not understand what that number serial mean! it's a date or should a try some thing else ?

答:
By default all dates object are timestamps.

JavaScript Date objects represent a single moment in time in a
platform-independent format. Date objects contain a Number that
represents milliseconds since 1 January 1970 UTC.
Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

I think the default new Date() object can display itself to string by in fact it's also a timestamp.
If you want to display a date as string, you have to use the toLocaleString() method on Date.

I tried by updating the original date and it return the string of the date, don't know why but it's work by updating the original date.

Example :

```<code>let giftObject = {};
giftObject.purshasedDate = new Date();
giftObject.purshasedDate.setFullYear(giftObject.purshasedDate.getFullYear() + 1);
console.log(giftObject.purshasedDate)
</code>```

Result : "20/02/2021 à 13:55:49" for my French browser

Body:
By default all dates object are timestamps.

JavaScript Date objects represent a single moment in time in a
platform-independent format. Date objects contain a Number that
represents milliseconds since 1 January 1970 UTC.
Source : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

I think the default new Date() object can display itself to string by in fact it's also a timestamp.
If you want to display a date as string, you have to use the toLocaleString() method on Date.

I tried by updating the original date and it return the string of the date, don't know why but it's work by updating the original date.

Example :

let giftObject = {};
giftObject.purshasedDate = new Date();
giftObject.purshasedDate.setFullYear(giftObject.purshasedDate.getFullYear() + 1);
console.log(giftObject.purshasedDate)

Result : "20/02/2021 à 13:55:49" for my French browser