问:
android - Kotlin - how to access a solid color inside a background's custom Button
I have a simple Kotlin project, with the following code :

inside an activity screen, I have a list view :

```<code>    <ListView
        android:layout_marginTop="90dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ordersListView"
        android:divider="@null"
        android:choiceMode="singleChoice"
        android:listSelector="@android:color/holo_orange_light"
        />
</code>```

this listView uses a custom row UI :

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

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/white_color">

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:gravity="center_vertical"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:paddingLeft="10dp"
        android:text="Name" />

    <Button
        android:id="@+id/send_0"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="0" />

    <Button
        android:id="@+id/send_1"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:background="@drawable/blue_button"
        android:text="1" />

    <Button
        android:id="@+id/send_2"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="2" />

    <Button
        android:id="@+id/send_3"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:background="@drawable/blue_button"
        android:text="3" />
</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@color/colorAccent"/>

</LinearLayout>

</code>```

the Button with id = send_0 uses a custom shape, using that code :

filename = v24/blue_button.xml

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

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA"
        android:id="@+id/solid_bng"/>

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>
</code>```

now, I want to change the "solid_bng" color
when I click on the Button with id = "send_0".

how can I do that ?

not sure if it is needed : I provide also my customAdapter code :
thanks for any help

:o)

Olivier

filename : CustomAdapter.kt

```<code>package fr.ormaa.o_service

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import java.util.ArrayList

class CustomAdapter(private val context: Context, private val imageModelArrayList: ArrayList<ImageModel>) : BaseAdapter() {

    override fun getViewTypeCount(): Int {
        return count
    }

    override fun getItemViewType(position: Int): Int {

        return position
    }

    override fun getCount(): Int {
        return imageModelArrayList.size
    }

    override fun getItem(position: Int): Any {
        return imageModelArrayList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var convertView = convertView
        val holder: ViewHolder

        convertView = convertView

        if (convertView == null) {

            holder = ViewHolder()

            val inflater = context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

            convertView = inflater.inflate(R.layout.meal_item, null, true)

            holder?.tvname = convertView!!.findViewById(R.id.name) as TextView
            holder?.iv = convertView.findViewById(R.id.imgView) as ImageView

            holder?.send0 = convertView.findViewById(R.id.send_0) as Button
            holder?.send1 = convertView.findViewById(R.id.send_1) as Button
            holder?.send2 = convertView.findViewById(R.id.send_2) as Button
            holder?.send3 = convertView.findViewById(R.id.send_3) as Button

            convertView.tag = holder
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = convertView.tag as ViewHolder
        }

        holder?.tvname!!.setText(imageModelArrayList[position].getNames())
        holder?.iv!!.setImageResource(imageModelArrayList[position].getImage_drawables())

        holder?.send0?.setOnTouchListener(zero_clicked)

        return convertView
    }

    private val zero_clicked = View.OnTouchListener { _, _ ->

        Toast.makeText(context,  "zero clicked", Toast.LENGTH_LONG).show()

        false
    }
    private val one_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val two_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val three_clicked = View.OnTouchListener { _, _ ->
        false
    }

    private inner class ViewHolder {

        var tvname: TextView? = null
        internal var iv: ImageView? = null

        var send0: Button? = null
        var send1: Button? = null
        var send2: Button? = null
        var send3: Button? = null

    }

}

</code>```

答:
You need to have a selector to achieve that.

blue_button.xml

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA" />

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>
</code>```

blue_button_pressed.xml

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#00608A" />

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>
</code>```

and then blue_button_selector.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/blue_button_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/blue_button" />
</selector>
</code>```

And use this selector as the background for your button.

Body:
I have a simple Kotlin project, with the following code :

inside an activity screen, I have a list view :

    <ListView
        android:layout_marginTop="90dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/ordersListView"
        android:divider="@null"
        android:choiceMode="singleChoice"
        android:listSelector="@android:color/holo_orange_light"
        />

this listView uses a custom row UI :

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

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/white_color">

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp" />

    <TextView
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="110dp"
        android:gravity="center_vertical"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:paddingLeft="10dp"
        android:text="Name" />

    <Button
        android:id="@+id/send_0"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="0" />

    <Button
        android:id="@+id/send_1"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:background="@drawable/blue_button"
        android:text="1" />

    <Button
        android:id="@+id/send_2"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:layout_marginRight="60dp"
        android:background="@drawable/blue_button"
        android:text="2" />

    <Button
        android:id="@+id/send_3"
        android:layout_width="50dp"
        android:layout_height="40dp"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:background="@drawable/blue_button"
        android:text="3" />
</RelativeLayout>

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:layout_marginTop="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:background="@color/colorAccent"/>

</LinearLayout>

the Button with id = send_0 uses a custom shape, using that code :

filename = v24/blue_button.xml

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

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA"
        android:id="@+id/solid_bng"/>

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>

now, I want to change the "solid_bng" color
when I click on the Button with id = "send_0".

how can I do that ?

not sure if it is needed : I provide also my customAdapter code :
thanks for any help

:o)

Olivier

filename : CustomAdapter.kt

package fr.ormaa.o_service

import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import java.util.ArrayList

class CustomAdapter(private val context: Context, private val imageModelArrayList: ArrayList<ImageModel>) : BaseAdapter() {

    override fun getViewTypeCount(): Int {
        return count
    }

    override fun getItemViewType(position: Int): Int {

        return position
    }

    override fun getCount(): Int {
        return imageModelArrayList.size
    }

    override fun getItem(position: Int): Any {
        return imageModelArrayList[position]
    }

    override fun getItemId(position: Int): Long {
        return 0
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {

        var convertView = convertView
        val holder: ViewHolder

        convertView = convertView

        if (convertView == null) {

            holder = ViewHolder()

            val inflater = context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

            convertView = inflater.inflate(R.layout.meal_item, null, true)

            holder?.tvname = convertView!!.findViewById(R.id.name) as TextView
            holder?.iv = convertView.findViewById(R.id.imgView) as ImageView

            holder?.send0 = convertView.findViewById(R.id.send_0) as Button
            holder?.send1 = convertView.findViewById(R.id.send_1) as Button
            holder?.send2 = convertView.findViewById(R.id.send_2) as Button
            holder?.send3 = convertView.findViewById(R.id.send_3) as Button

            convertView.tag = holder
        } else {
            // the getTag returns the viewHolder object set as a tag to the view
            holder = convertView.tag as ViewHolder
        }

        holder?.tvname!!.setText(imageModelArrayList[position].getNames())
        holder?.iv!!.setImageResource(imageModelArrayList[position].getImage_drawables())

        holder?.send0?.setOnTouchListener(zero_clicked)

        return convertView
    }

    private val zero_clicked = View.OnTouchListener { _, _ ->

        Toast.makeText(context,  "zero clicked", Toast.LENGTH_LONG).show()

        false
    }
    private val one_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val two_clicked = View.OnTouchListener { _, _ ->

        false
    }
    private val three_clicked = View.OnTouchListener { _, _ ->
        false
    }

    private inner class ViewHolder {

        var tvname: TextView? = null
        internal var iv: ImageView? = null

        var send0: Button? = null
        var send1: Button? = null
        var send2: Button? = null
        var send3: Button? = null

    }

}

Body:
You need to have a selector to achieve that.

blue_button.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#2E9BCA" />

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>

blue_button_pressed.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <solid android:color="#00608A" />

    <stroke
        android:height="1.0dip"
        android:width="1.0dip"
        android:color="#80ee82ee" />

    <corners
        android:bottomRightRadius="10dp"
        android:bottomLeftRadius="10dp"
        android:topLeftRadius="10dp"
        android:topRightRadius="10dp"/>
</shape>

and then blue_button_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/blue_button_pressed" android:state_pressed="true" />
    <item android:drawable="@drawable/blue_button" />
</selector>

And use this selector as the background for your button.


来源: stackexchange

问:
Replace only specified occurrences of string - Python Regex
I am playing around with re module in python, what i am stuck at is I want to replace only specified occurrences of the string.
for example

import re
string = "aabbaabbaabbabbaabbaa"
#I want to replace only 3rd time 'bb' appeared in the string with white space
string = re.sub("bb"," ",string,3)   #if iI do this all first 3 occurrences got replaced
print(string)
```

<p><strong>output</strong></p>

```aa aa aa aabbaabbaa
```

<p>any idea how to to replace only 3rd occurrence<br>
so the output would look like <strong>This</strong>  </p>

```aabbaabbaa aabbaabbaa
```

答:
This may not be the perfect way but it is a solution:

```<code>string = re.sub('bb',' ',string, 3)
string = re.sub(' ','bb',string,2)

</code>```

This is just an alternative solution I can think of.

ContentLicense: CC BY-SA 4.0

Body:
I am playing around with re module in python, what i am stuck at is I want to replace only specified occurrences of the string.
for example

import re
string = "aabbaabbaabbabbaabbaa"
#I want to replace only 3rd time 'bb' appeared in the string with white space
string = re.sub("bb"," ",string,3)   #if iI do this all first 3 occurrences got replaced
print(string)

output

aa aa aa aabbaabbaa

any idea how to to replace only 3rd occurrence

so the output would look like This

aabbaabbaa aabbaabbaa

Body:
This may not be the perfect way but it is a solution:

string = re.sub('bb',' ',string, 3)
string = re.sub(' ','bb',string,2)

This is just an alternative solution I can think of.


问:
Versions management of python packages
What is a best practice to manage a different versions of packages?
I know about virtualenv but i am not sure it is suitable in my case.

My problem:

Consider that i have 2 projects (P1, P2) which both use 1 small project (P3).
I use git submodules and add P3 to both P1 and P2.

Then i have P4 which uses all projects described above and P4 needs the latest version of P3.

How to deal with it?
I want P1, P2, P4 to use their own version of P3. But when i build P4 i have only one version of P3.

Projects structure:

All projects have such structure (some files omitted):

P4 example:

├── project_name (sources are here)
├── Makefile
├── submodules
│   └── P1
│       ├── submodules
│       │   └── P3
│   └── P2
│       ├── submodules
│       │   └── P3
│   └── P3
├── tests
└── setup.py
```

How subprojects are imported:

No surprises here, all projects import P3 in that way as it was the only one version installed.

So P1 uses:
from P3 import something

And P4 also uses:

from P3 import something

from P1 import something_else

答: Virtualenv will work, why you thought it wouldn't work?</p>

Title: Versions management of python packages

Body:
What is a best practice to manage a different versions of packages?
I know about virtualenv but i am not sure it is suitable in my case.

My problem:

Consider that i have 2 projects (P1, P2) which both use 1 small project (P3).
I use git submodules and add P3 to both P1 and P2.

Then i have P4 which uses all projects described above and P4 needs the latest version of P3.

How to deal with it?
I want P1, P2, P4 to use their own version of P3. But when i build P4 i have only one version of P3.

Projects structure:

All projects have such structure (some files omitted):

P4 example:

├── project_name (sources are here)
├── Makefile
├── submodules
│   └── P1
│       ├── submodules
│       │   └── P3
│   └── P2
│       ├── submodules
│       │   └── P3
│   └── P3
├── tests
└── setup.py

How subprojects are imported:

No surprises here, all projects import P3 in that way as it was the only one version installed.

So P1 uses:
from P3 import something

And P4 also uses:

from P3 import something

from P1 import something_else


问:
pyzmq context sometimes slow to initialize
I have recently started to use ZeroMQ and have observed that sometimes initialization of the ZeroMQ context can take as much as 40 seconds.  Usually it's much faster than that.

Eg:

import zmq

# the next line will sometimes take 40 seconds
# or so but is usually near instantaneous
with zmq.Context.instance() as context:
    # connect / bind to socket, do stuff
    pass
```

<p>This behaviour seems to be independent of whether or not I use a context manager, eg the following behaves the same as the above:</p>

<pre class="lang-py prettyprint-override"><code>import zmq

# the next line will sometimes take 40 seconds
# or so but is usually near instantaneous
context = zmq.Context.instance()

# connect / bind to socket, do stuff

context.term()
</code>```

This is running in Python 3.6.8 on Ubuntu 18.04.2

I haven't been able to establish any pattern to the slowdowns.

What are the possible causes of this behaviour?

Update

Per @user3666197 suggestion, I took some timings and managed to get the slowdown to manifest on the second run.  Things returned to "normal" after that.

The slowdown kicked in on the second run of the test script:

```<code> = zmq.Context()] took +      704 [us] to execute
 1.~                          704  us
 2.~                  131 766 816  us
 3.~                          145  us
 4.~                          137  us
</code>```

Watching memory on htop at the time did not show memory filling up at all but swap was already active.

Update 2

Using a pruned-down version of @user3666197's suggested script:

import sys

import zmq
clock = zmq.Stopwatch()

clock.start()
foo = zmq.Context()
bar = clock.stop()
print("{0:>2s}: {1:>9d}".format(sys.argv[1], bar))
foo.term()
```

<p>And calling it in a loop, eg:</p>

<pre class="lang-sh prettyprint-override"><code>for x in $(seq 1 20);
do python3 test.zmq.py $x;
done
</code>```

I can repeat the issue on the original server but have yet to hit it on another server, which suggests an environmental issue (or something to do with the specific distro version and/or python version as the "good" server is older).

This is sufficient for me for now but I will come back to it later and gather enough info to submit something to the maintainers.

答:
In case one has never worked with ZeroMQ,
one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds"
before diving into further details

Q : " What are the possible causes of this ( only "sometimes" present ) behaviour? "
I haven't been able to establish any pattern to the slowdowns.

a ) those 40 seconds,
 mentioned above, could make sense but with a RAM to swap-I/O operations. I cannot imagine any other reason for such block of time ( 've never noticed anything close to the 3/4 of a minute delay in ZeroMQ during my last ~10 years with ZeroMQ, never )

b ) the reality check
always measure the respective actual times of execution, before any claim get raised :

let's start to be systematic and fair on repeatable and documented test-cases, ok?
Categories like "sometimes" are not worth, data are. As a start, we may use the following templated approach, to discriminate the root cause of any actual delay :

```<code>M = "[{0:_>40s}] took +{1:_>9d} [us] to execute"
N = 0
from zmq import Stopwatch; aClk = Stopwatch()
#------------------------------
pass;                      aClk.start()
import zmq
pass;                  _ = aClk.stop(); print( M.format( "IMPORT", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context()
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
context = zmq.Context.instance()
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context.instance()", _ ) )
#------------------------------
pass;                      aClk.start()
context.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
with zmq.Context.instance() as aCtxInCtxMGR:
     N +=1
pass;                  _ = aClk.stop(); print( M.format( "with … as aCtxInCtxMGR:", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context(  0 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context(  0 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 10 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 10 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 20 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 20 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 50 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 50 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 99 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 99 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
</code>```

et cetera

ad plausible

Your actual mileage may vary
 ( and will )

```<code>[__________________________________IMPORT] took +_____1198 [us] to execute
[_________________________= zmq.Context()] took +_____1523 [us] to execute
[________________= zmq.Context.instance()] took +_____1348 [us] to execute
[_________________with … as aCtxInCtxMGR:] took +_____7909 [us] to execute
[_____________________= zmq.Context(  0 )] took +______966 [us] to execute
[_____________________= zmq.Context( 10 )] took +______944 [us] to execute
[_____________________= zmq.Context( 20 )] took +______936 [us] to execute
[_____________________= zmq.Context( 50 )] took +______962 [us] to execute
[_____________________= zmq.Context( 99 )] took +_____1015 [us] to execute
</code>```

```<code>[__________________________________IMPORT] took +______879 [us] to execute
[_________________________= zmq.Context()] took +_____1076 [us] to execute
[_________________________________.term()] took +______881 [us] to execute
[________________= zmq.Context.instance()] took +_____1105 [us] to execute
[_________________________________.term()] took +______896 [us] to execute
[_________________with … as aCtxInCtxMGR:] took +_____1474 [us] to execute
[_____________________= zmq.Context(  0 )] took +_____1163 [us] to execute
[_________________________________.term()] took +______982 [us] to execute
[_____________________= zmq.Context( 10 )] took +_____2646 [us] to execute
[_________________________________.term()] took +______873 [us] to execute
[_____________________= zmq.Context( 20 )] took +_____2689 [us] to execute
[_________________________________.term()] took +______981 [us] to execute
[_____________________= zmq.Context( 50 )] took +_____2772 [us] to execute
[_________________________________.term()] took +______910 [us] to execute
[_____________________= zmq.Context( 99 )] took +_____1086 [us] to execute
[_________________________________.term()] took +_____1010 [us] to execute
</code>```

Body:
I have recently started to use ZeroMQ and have observed that sometimes initialization of the ZeroMQ context can take as much as 40 seconds.  Usually it's much faster than that.

Eg:

import zmq

# the next line will sometimes take 40 seconds
# or so but is usually near instantaneous
with zmq.Context.instance() as context:
    # connect / bind to socket, do stuff
    pass

This behaviour seems to be independent of whether or not I use a context manager, eg the following behaves the same as the above:

import zmq

# the next line will sometimes take 40 seconds
# or so but is usually near instantaneous
context = zmq.Context.instance()

# connect / bind to socket, do stuff

context.term()

This is running in Python 3.6.8 on Ubuntu 18.04.2

I haven't been able to establish any pattern to the slowdowns.

What are the possible causes of this behaviour?

Update

Per @user3666197 suggestion, I took some timings and managed to get the slowdown to manifest on the second run.  Things returned to "normal" after that.

The slowdown kicked in on the second run of the test script:

 = zmq.Context()] took +      704 [us] to execute
 1.~                          704  us
 2.~                  131 766 816  us
 3.~                          145  us
 4.~                          137  us

Watching memory on htop at the time did not show memory filling up at all but swap was already active.

Update 2

Using a pruned-down version of @user3666197's suggested script:

import sys

import zmq
clock = zmq.Stopwatch()

clock.start()
foo = zmq.Context()
bar = clock.stop()
print("{0:>2s}: {1:>9d}".format(sys.argv[1], bar))
foo.term()

And calling it in a loop, eg:

for x in $(seq 1 20);
do python3 test.zmq.py $x;
done

I can repeat the issue on the original server but have yet to hit it on another server, which suggests an environmental issue (or something to do with the specific distro version and/or python version as the "good" server is older).

This is sufficient for me for now but I will come back to it later and gather enough info to submit something to the maintainers.

Body:
In case one has never worked with ZeroMQ,
one may here enjoy to first look at "ZeroMQ Principles in less than Five Seconds"
before diving into further details

Q : " What are the possible causes of this ( only "sometimes" present ) behaviour? "
I haven't been able to establish any pattern to the slowdowns.

a ) those 40 seconds,
 mentioned above, could make sense but with a RAM to swap-I/O operations. I cannot imagine any other reason for such block of time ( 've never noticed anything close to the 3/4 of a minute delay in ZeroMQ during my last ~10 years with ZeroMQ, never )

b ) the reality check
always measure the respective actual times of execution, before any claim get raised :

let's start to be systematic and fair on repeatable and documented test-cases, ok?
Categories like "sometimes" are not worth, data are. As a start, we may use the following templated approach, to discriminate the root cause of any actual delay :

M = "[{0:_>40s}] took +{1:_>9d} [us] to execute"
N = 0
from zmq import Stopwatch; aClk = Stopwatch()
#------------------------------
pass;                      aClk.start()
import zmq
pass;                  _ = aClk.stop(); print( M.format( "IMPORT", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context()
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
context = zmq.Context.instance()
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context.instance()", _ ) )
#------------------------------
pass;                      aClk.start()
context.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
with zmq.Context.instance() as aCtxInCtxMGR:
     N +=1
pass;                  _ = aClk.stop(); print( M.format( "with … as aCtxInCtxMGR:", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context(  0 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context(  0 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 10 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 10 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 20 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 20 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 50 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 50 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX = zmq.Context( 99 )
pass;                  _ = aClk.stop(); print( M.format( "= zmq.Context( 99 )", _ ) )
#------------------------------
pass;                      aClk.start()
aCTX.term()
pass;                  _ = aClk.stop(); print( M.format( ".term()", _ ) )
#------------------------------

et cetera

ad plausible

Your actual mileage may vary
 ( and will )

[__________________________________IMPORT] took +_____1198 [us] to execute
[_________________________= zmq.Context()] took +_____1523 [us] to execute
[________________= zmq.Context.instance()] took +_____1348 [us] to execute
[_________________with … as aCtxInCtxMGR:] took +_____7909 [us] to execute
[_____________________= zmq.Context(  0 )] took +______966 [us] to execute
[_____________________= zmq.Context( 10 )] took +______944 [us] to execute
[_____________________= zmq.Context( 20 )] took +______936 [us] to execute
[_____________________= zmq.Context( 50 )] took +______962 [us] to execute
[_____________________= zmq.Context( 99 )] took +_____1015 [us] to execute

[__________________________________IMPORT] took +______879 [us] to execute
[_________________________= zmq.Context()] took +_____1076 [us] to execute
[_________________________________.term()] took +______881 [us] to execute
[________________= zmq.Context.instance()] took +_____1105 [us] to execute
[_________________________________.term()] took +______896 [us] to execute
[_________________with … as aCtxInCtxMGR:] took +_____1474 [us] to execute
[_____________________= zmq.Context(  0 )] took +_____1163 [us] to execute
[_________________________________.term()] took +______982 [us] to execute
[_____________________= zmq.Context( 10 )] took +_____2646 [us] to execute
[_________________________________.term()] took +______873 [us] to execute
[_____________________= zmq.Context( 20 )] took +_____2689 [us] to execute
[_________________________________.term()] took +______981 [us] to execute
[_____________________= zmq.Context( 50 )] took +_____2772 [us] to execute
[_________________________________.term()] took +______910 [us] to execute
[_____________________= zmq.Context( 99 )] took +_____1086 [us] to execute
[_________________________________.term()] took +_____1010 [us] to execute


问:
Group sorted list in Jinja
It seems that you cannot group sorted lists in jinja without loosing the sort order.

Here an example template:

```<code>{% set l = [{'c': 3, 'result': 1.0},
            {'c': 3, 'result': 2.0},
            {'c': 9, 'result': 3.0},
            {'c': 1, 'result': 4.0}] %}
{% for d in l|groupby('c') %}
    {{d}}
{% endfor %}
</code>```

Unfortunately, this templates outputs:

```<code>(1, [{'c': 1, 'result': 4.0}])
(3, [{'c': 3, 'result': 1.0}, {'c': 3, 'result': 2.0}])
(9, [{'c': 9, 'result': 3.0}])
</code>```

But what I was expecting is:

```<code>(3, [{'c': 3, 'result': 1.0}, {'c': 3, 'result': 2.0}])
(9, [{'c': 9, 'result': 3.0}])
(1, [{'c': 1, 'result': 4.0}])
</code>```

I have absolutely to keep the items in the pre-sorted order.

Does anybody know how to achieve this?

答:
hopefully this answer solves your problem</p>

```<code>{% for d in l|groupby('c')|reverse %}
   {{d}}
{% endfor %}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Group sorted list in Jinja

Body:
It seems that you cannot group sorted lists in jinja without loosing the sort order.

Here an example template:

{% set l = [{'c': 3, 'result': 1.0},
            {'c': 3, 'result': 2.0},
            {'c': 9, 'result': 3.0},
            {'c': 1, 'result': 4.0}] %}
{% for d in l|groupby('c') %}
    {{d}}
{% endfor %}

Unfortunately, this templates outputs:

(1, [{'c': 1, 'result': 4.0}])
(3, [{'c': 3, 'result': 1.0}, {'c': 3, 'result': 2.0}])
(9, [{'c': 9, 'result': 3.0}])

But what I was expecting is:

(3, [{'c': 3, 'result': 1.0}, {'c': 3, 'result': 2.0}])
(9, [{'c': 9, 'result': 3.0}])
(1, [{'c': 1, 'result': 4.0}])

I have absolutely to keep the items in the pre-sorted order.

Does anybody know how to achieve this?

Body:
hopefully this answer solves your problem

{% for d in l|groupby('c')|reverse %}
   {{d}}
{% endfor %}


问:
android black color at 85% opacity
What is the color code of black with 85% opacity?

I have #65000000 - but its too light. I need it a bit darker, at 85% opacity. How do I get that?

And why can't I setAlpha(85) on a relative layout? That's what I would want to do normally. But because this is not available, I have to do it though background color.

答:
85% black should be #D8000000.

Each component (A, R, G, B) can take values from 0-255. 85% of 255 = 216. 216 in Hex = D8

Title: android black color at 85% opacity


问:
Running PyTorch multiprocessing in a Docker container with Gunicorn worker manager

I am trying to deploy a service on GCP. It's a Docker container that uses Gunicorn for worker management.

The code runs a torch.multiprocessing.process to run a POST response as a background process.

This works if I run the script using a python3 command. But hangs when using Gunicorn.

My understanding is that CUDA needs threadsafe multiprocessing and that is why torch has its own implementation. When we set up Gunicorn to manage workers, this may be causing some conflict or thread safety issues.

Has anyone come across this before. Would there be a different worker manager that I could be using?

In Dockerfile: CMD gunicorn -w 1 -t 6000 -b 0.0.0.0:8080 --timeout 6000 --preload app_script:app - this is how i am running the app in docker. So yes I am using preload. And the issue happens even if I run the docker container locally so its not just a gcp situation

p=torch.multiprocessing.Process(target=my_function args=(args, )) . p.start() - this is how a post call is getting handled.

答:
I spent a lot of time investigating a similar issue.
Pytorch calls were stuck when running on a docker container with gunicorn.

The solution that worked for me was removing the --preload flag from the Docker gunicorn command.


问:
Webpack config for svelte/sapper with typescript and scss support
i just cant wrap my head around it, no matter how hard i try to find any help on discord server or official docs theres nothing about it.

for example here is my react webpack config:

```<code>const env = process.env.NODE_ENV || 'production';
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const VersionFile = require('webpack-version-file');
const webpack = require('webpack');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

module.exports = {
    entry: {
        main: path.join(__dirname, 'src', 'index'),
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        // filename: 'assets/js/[name].[chunkhash].js',
        filename: 'assets/js/[name].js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.(jsx|tsx|js|ts)$/,
                exclude: [/node_modules/],
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            '@babel/preset-env',
                            '@babel/preset-react',
                            '@babel/preset-typescript',
                        ],
                    },
                },
                include: path.join(__dirname, 'src'),
            },
            {
                test: /\.js$/,
                use: ['source-map-loader'],
                enforce: 'pre',
            },
            {
                test: /\.(scss|sass|css)$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
            },
            {
                type: 'javascript/auto',
                test: /\.json$/,
                use: 'file-loader?name=assets/i18n/locales/[name].[ext]',
            },
            {
                test: /\.(eot?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
                use: 'file-loader?name=assets/fonts/[name]-[hash].[ext]',
            },
            {
                test: /\.(jpe?g|png|gif|svg|ico)$/i,
                use: 'file-loader?name=assets/img/[name]-[hash].[ext]',
                include: path.join(__dirname, 'src'),
            },
        ],
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css',
        }),
        new ForkTsCheckerWebpackPlugin(),
        new HtmlWebpackPlugin({
            // hash: true,
            template: './src/index.html',
            filename: 'index.html',
        }),
        new CleanWebpackPlugin(),
        new VersionFile({
            output: './dist/version.txt',
            package: './package.json',
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(env),
        }),
        // new CopyWebpackPlugin([
        //     {
        //         from: path.join(__dirname, 'src/locales'),
        //         to: path.join(__dirname, 'dist/assets/locales'),
        //     },
        // ]),
    ],
    devtool: 'source-map',
    devServer: {
        contentBase: [path.resolve(__dirname, 'dist')],
        historyApiFallback: {
            disableDotRule: true,
        },
        host: '0.0.0.0',
        useLocalIp: true,
    },
    resolve: {
        alias: {
            pages: path.resolve(__dirname, 'src/pages'),
            components: path.resolve(__dirname, 'src/components'),
            config: path.resolve(__dirname, 'src/config'),
            services: path.resolve(__dirname, 'src/services'),
            store: path.resolve(__dirname, 'src/store'),
            utils: path.resolve(__dirname, 'src/utils'),
        },
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
};
</code>```

i had absolutely no trouble configuring it myself.
Any help how to setup svelte sapper webpack config for typescript and scss support?

Or maybe someone has rollup config?

答:
You can try to use the following template:

https://github.com/Zimtir/SENT-template

Sapper.js + Node.js + Express.js + Typescript

Body:
i just cant wrap my head around it, no matter how hard i try to find any help on discord server or official docs theres nothing about it.

for example here is my react webpack config:

const env = process.env.NODE_ENV || 'production';
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const VersionFile = require('webpack-version-file');
const webpack = require('webpack');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');

module.exports = {
    entry: {
        main: path.join(__dirname, 'src', 'index'),
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        // filename: 'assets/js/[name].[chunkhash].js',
        filename: 'assets/js/[name].js',
        publicPath: '/',
    },
    module: {
        rules: [
            {
                test: /\.(jsx|tsx|js|ts)$/,
                exclude: [/node_modules/],
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: [
                            '@babel/preset-env',
                            '@babel/preset-react',
                            '@babel/preset-typescript',
                        ],
                    },
                },
                include: path.join(__dirname, 'src'),
            },
            {
                test: /\.js$/,
                use: ['source-map-loader'],
                enforce: 'pre',
            },
            {
                test: /\.(scss|sass|css)$/i,
                use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader'],
            },
            {
                type: 'javascript/auto',
                test: /\.json$/,
                use: 'file-loader?name=assets/i18n/locales/[name].[ext]',
            },
            {
                test: /\.(eot?.+|ttf?.+|otf?.+|woff?.+|woff2?.+)$/,
                use: 'file-loader?name=assets/fonts/[name]-[hash].[ext]',
            },
            {
                test: /\.(jpe?g|png|gif|svg|ico)$/i,
                use: 'file-loader?name=assets/img/[name]-[hash].[ext]',
                include: path.join(__dirname, 'src'),
            },
        ],
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name].css',
            chunkFilename: '[id].css',
        }),
        new ForkTsCheckerWebpackPlugin(),
        new HtmlWebpackPlugin({
            // hash: true,
            template: './src/index.html',
            filename: 'index.html',
        }),
        new CleanWebpackPlugin(),
        new VersionFile({
            output: './dist/version.txt',
            package: './package.json',
        }),
        new webpack.DefinePlugin({
            'process.env.NODE_ENV': JSON.stringify(env),
        }),
        // new CopyWebpackPlugin([
        //     {
        //         from: path.join(__dirname, 'src/locales'),
        //         to: path.join(__dirname, 'dist/assets/locales'),
        //     },
        // ]),
    ],
    devtool: 'source-map',
    devServer: {
        contentBase: [path.resolve(__dirname, 'dist')],
        historyApiFallback: {
            disableDotRule: true,
        },
        host: '0.0.0.0',
        useLocalIp: true,
    },
    resolve: {
        alias: {
            pages: path.resolve(__dirname, 'src/pages'),
            components: path.resolve(__dirname, 'src/components'),
            config: path.resolve(__dirname, 'src/config'),
            services: path.resolve(__dirname, 'src/services'),
            store: path.resolve(__dirname, 'src/store'),
            utils: path.resolve(__dirname, 'src/utils'),
        },
        extensions: ['.ts', '.tsx', '.js', '.jsx'],
    },
};

i had absolutely no trouble configuring it myself.
Any help how to setup svelte sapper webpack config for typescript and scss support?

Or maybe someone has rollup config?


问:
Why do I have to initialise variable?
My code is checking if a given string is in a certain format. The first char of the string has to be an uppercase letter and the rest of the string has to be any number that is from 1 to given dimension.

If the first char of the string contains a string from the alphabet array, then the code checks if the rest of the string contains a number from the numbers array. To be a valid coordinate both conditions must be true, if one of them is false it is not a valid coordinate. I want to return the boolean isValidCoordinate but however IntelliJ is telling me that I have to initialise isValid coordinate. Why do I have to initialise it, the boolean expression depends on the 'if' conditions.

Thanks.

```<code>public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return isValidCoordinate;
    }
</code>```

This is my final code:

```<code>public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return true;
    }
</code>```

答:
All the cases inside the for loop are covered, but not the case when dimension is 0.

The method will go straight to return isValidCoordinate;, where the variable isn't initialized yet.

Title: Why do I have to initialise variable?

Body:
My code is checking if a given string is in a certain format. The first char of the string has to be an uppercase letter and the rest of the string has to be any number that is from 1 to given dimension.

If the first char of the string contains a string from the alphabet array, then the code checks if the rest of the string contains a number from the numbers array. To be a valid coordinate both conditions must be true, if one of them is false it is not a valid coordinate. I want to return the boolean isValidCoordinate but however IntelliJ is telling me that I have to initialise isValid coordinate. Why do I have to initialise it, the boolean expression depends on the 'if' conditions.

Thanks.

public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return isValidCoordinate;
    }

This is my final code:

public static boolean validCoordinate(String coordinate, int dimension) {
        boolean isValidCoordinate;
        String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
        int [] numbers = new int [dimension];
        int one = 1;
        for(int i = 0; i < dimension; i++){
            numbers[i] = one + i;
        }
        for(int i = 0; i < dimension; i++){
            if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
                for(int j = 0; j < dimension; j++) {
                    if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                        isValidCoordinate = true;
                    }
                    else {
                        isValidCoordinate = false;
                    }
                }

            }
            else {
                isValidCoordinate = false;
            }

        }

        return true;
    }


问:
How to sort a mysql table in a specific way
I have the following table as a result of a query:

```<code>    SELECT f.id, f.parent_id, f.name, f.fullpath,
    FROM folders f
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fullpath ASC, name ASC;
</code>```

```<code>id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
</code>```

The table is sorted by

```<code>ORDER BY fullpath ASC, name ASC
</code>```

The desired outcome is that name column gets sorted in a manner where test3 comes after test2 while keeping the fullpath sorting. But I don't know how to achieve this?

```<code>id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
</code>```

答:
Since you want to refrain from stored functions, you need to rebuild the path using names instead of ids, using a MySQL 8.0 recursive query.

```<code>WITH RECURSIVE cte AS (
  SELECT f.id, f.parent_id, f.name, f.fullpath
       , CAST(f.name AS CHAR(50)) AS namepath
    FROM folders f
   WHERE f.id = 'fs-3'
  UNION ALL
  SELECT f.id, f.parent_id, f.name, f.fullpath
       , CONCAT(cte.namepath, '/', f.name) AS namepath
    FROM cte
    JOIN folders f ON f.parent_id = cte.id
)
SELECT id, parent_id, name, fullpath
  FROM cte
 ORDER BY namepath
</code>```

See DB Fiddle for demo.

Body:
I have the following table as a result of a query:

    SELECT f.id, f.parent_id, f.name, f.fullpath,
    FROM folders f
    WHERE fullpath LIKE CONCAT("%", 'fs-3', "%")
    ORDER BY fullpath ASC, name ASC;

id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4

The table is sorted by

ORDER BY fullpath ASC, name ASC

The desired outcome is that name column gets sorted in a manner where test3 comes after test2 while keeping the fullpath sorting. But I don't know how to achieve this?

id      parent_id       name        fullpath
-----------------------------------------------------------------
fs-3    null            root        fs-3
fs-d    fs-3            test        fs-3/fs-d
fs-5    fs-d            test        fs-3/fs-d/fs-5
fs-y    fs-3            test2       fs-3/fs-y
fs-4    fs-y            test        fs-3/fs-y/fs-4
fs-g    fs-3            test3       fs-3/fs-g
fs-2    fs-g            test        fs-3/fs-g/fs-2
fs-s    fs-2            test        fs-3/fs-g/fs-2/fs-s

Body:
Since you want to refrain from stored functions, you need to rebuild the path using names instead of ids, using a MySQL 8.0 recursive query.

WITH RECURSIVE cte AS (
  SELECT f.id, f.parent_id, f.name, f.fullpath
       , CAST(f.name AS CHAR(50)) AS namepath
    FROM folders f
   WHERE f.id = 'fs-3'
  UNION ALL
  SELECT f.id, f.parent_id, f.name, f.fullpath
       , CONCAT(cte.namepath, '/', f.name) AS namepath
    FROM cte
    JOIN folders f ON f.parent_id = cte.id
)
SELECT id, parent_id, name, fullpath
  FROM cte
 ORDER BY namepath

See DB Fiddle for demo.


问:
Material design icon with underscore in its name doesn't work with Vuetify
I'm using Vuetify and everything works well apart from the icons when they have an underscore in their name.
For example:

```<code><v-icon>mdi-how_to_vote</v-icon>
</code>```

doesn't work, but

```<code><v-icon>mdi-home</v-icon>
</code>```

does.

Does anybody have a clue?
Thanks in advance :)

答: OK, actually they changed the names containing an underscore... It's confusing because https://material.io/resources/icons/?style=baseline exists but you should search here: https://materialdesignicons.com/</p>

Body:
I'm using Vuetify and everything works well apart from the icons when they have an underscore in their name.
For example:

<v-icon>mdi-how_to_vote</v-icon>

doesn't work, but

<v-icon>mdi-home</v-icon>

does.

Does anybody have a clue?
Thanks in advance :)


问:
What effects can inconsistent latency have on TCP applications?
I am testing a GNU Radio program which can tunnel TCP traffic over a wireless link. We are having some strange results in testing, and in looking for a culprit I was curious about inconsistent latency.

How can inconsistent latency affect TCP applications? By inconsistent I mean widely different RTT for ACKs on a connection. For awhile ACks seem to be coming at a normal rate, then they disappear and we have retransmissions followed by the 'delayed' ACK.

For instance, say the first several ACK's received have a similar RTT. What would happen when the next ACK isn't receieved in twice the RTT of the previous ACKs? Whatever the issue is I see lots of retransmissions after a long wait for an ACK.

Now, more specifically, how can RTTs for ACKs which bounce between fast and slow affect a TCP connection?

Having said that, is there any way to tune the IP stack to handle this environment better?

答: TCP maintains a smoothed RTT (SRTT) to tell it how fast the intervening network is, i.e. how fast it can transmit. If the SRTT goes up TCP will slow down. If SRTT goes down TCP will speed up. If the actual RTT goes up and down violently, TCP may not react quickly enough, due to the smoothing, and transmit too fast, which would cause packet loss, which in turn causes retransmission, which wastes the bandwidth used by the lost packets. RTT smoothing is done via exponential decay with a gain of I think 0.2, so the old SRTT value has four times the weight of the current RTT when computing the new SRTT value.


答:
It is possible that your for loop will never be entered (for example, if dimension == 0). In that case, you will never assign a value to isValidCoordinate, but you will attempt to return the value of that variable in the last statement of your method.

What would be the value of isValidCoordinate in such case?

It wouldn't have any value.

Therefore, you are forced by the compiler to assign an initial value to isValidCoordinate, to make sure that it has a value before it is accessed.

EDIT:

Following your comments, I suggest you eliminate the boolean variable, and use return statements instead:

```<code>public static boolean validCoordinate(String coordinate, int dimension) {
    String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    int [] numbers = new int [dimension];
    int one = 1;
    for(int i = 0; i < dimension; i++){
        numbers[i] = one + i;
    }
    for(int i = 0; i < dimension; i++){
        if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
            for(int j = 0; j < dimension; j++) {
                if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                    return true;
                }
            }
        }
    }

    return false;
}
</code>```

This way you don't have to worry about breaking out of nested loops when the boolean variable is set to true.

Title: Why do I have to initialise variable?

Body:
It is possible that your for loop will never be entered (for example, if dimension == 0). In that case, you will never assign a value to isValidCoordinate, but you will attempt to return the value of that variable in the last statement of your method.

What would be the value of isValidCoordinate in such case?

It wouldn't have any value.

Therefore, you are forced by the compiler to assign an initial value to isValidCoordinate, to make sure that it has a value before it is accessed.

EDIT:

Following your comments, I suggest you eliminate the boolean variable, and use return statements instead:

public static boolean validCoordinate(String coordinate, int dimension) {
    String [] alphabet = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
    int [] numbers = new int [dimension];
    int one = 1;
    for(int i = 0; i < dimension; i++){
        numbers[i] = one + i;
    }
    for(int i = 0; i < dimension; i++){
        if((Character.toString(coordinate.charAt(0))).contains(alphabet[i])) {
            for(int j = 0; j < dimension; j++) {
                if ((coordinate.substring(1)).contains(Integer.toString(numbers[j]))) {
                    return true;
                }
            }
        }
    }

    return false;
}

This way you don't have to worry about breaking out of nested loops when the boolean variable is set to true.


问:
I can't type any character in Android Studio
When I try to edit my code I can't do it, I've got a "fat" cursor on the text and also when I try to mark and delete text it's impossible

答: I would guess the reason for this is that you've accidentally installed the IdeaVim plugin. The commands of this are the same as vim. Try pressing the i key to enter insert mode. Is this worked, then remove the IdeaVim plugin from Android Studio (pressing right shift twice and removing the plugin). You can also uncheck Enable when you press on the IdeaVim icon on the lower right of your editor.


问:
Is there a way to log in to discord using a python script?
My goal is to be able to loging to Discord using a script and then be able to send messages to channels. I need it to communicate with a music bot automatically but if I write a bot for discord other bot's will ignore it so thats not an option. Does anyone know how to do it?

Thanks!

答:
I strongly advise you not to pursue this goal further, as it is a violation of the Discord Terms of Service and is illegal.
Probably your account will be terminated by Discord as a result.

If you want to automate Discord Bots you can take it into consideration to code your own.


问:
Keeping securly API tokens in the database
I have multiple companies utilising my GET endpoint, each company needs to have their own API key which they will provide as a url parameter.

I need to keep generating these token whenever new company will join in (there is a table reflecting this).

Is it safe to just:
- create company_token pivot table
- generate token as str_random(32) (because GET request might have maximum url length)

? Or is there a safer, better method?

答:
The best solution I guess would be to use JWT.
You can generate token for each company and distribute them.

Instead of sending the token in the URL as a query parameter, use the HTTP request authorization header and send the token as bearer token.


问:
OpenGL python and pygame translation after rotation not working for mouselook and movement
I'm trying to make a simple mouse look with standard arrow key movement, and I've got the mouselook working but the translations from the rotated points seem to move along an orthogonal basis, but not one that is aligned with the rotation of the mouselook.  I can't tell if my math is off or if opengl is doing something extra to transform the points and I need to adjust.  I looked at the modelview matrix and it appears to be following the same order of rotations but I'm just stuck here, I'm not sure if it has something to do with the perspective or what is happening really.  I'm not the best with linear algebra so it's got me stuck a bit.

import pygame
import pygameMenu as pgm
from pygame.locals import *

from OpenGL.GL import *
from OpenGL.GLU import *
import numpy as np
verticies = (
    (1, -1, -1),
    (1, 1, -1),
    (-1, 1, -1),
    (-1, -1, -1),
    (1, -1, 1),
    (1, 1, 1),
    (-1, -1, 1),
    (-1, 1, 1)
    )

edges = (
    (0,1),
    (0,3),
    (0,4),
    (2,1),
    (2,3),
    (2,7),
    (6,3),
    (6,4),
    (6,7),
    (5,1),
    (5,4),
    (5,7)
    )

class OGl():
    def three_func(a,b,func):
        return (func(a[0],b[0]),func(a[1],b[1]),func(a[2],b[2]))

class GLCamera():
    def __init__(self):
        self.pos = [0.0,0.0,10.0]
        self.rot = [0.0,0.0,0.0]
        self.rotating = False
        self.mouse_pos = [0,0]

    def add_to_scene(self):
        #buffer = glGetDouble( GL_MODELVIEW_MATRIX )
        #print(buffer)
        glRotatef(self.rot[2], 0, 0, 1);  # roll
        glRotatef(self.rot[1], 0, 1, 0); # heading
        glRotatef(self.rot[0], 1, 0, 0);  # pitch
        glTranslatef(-self.pos[0],-self.pos[1],-self.pos[2]);

    def change_of_basis(self):
        #skip roll for now
        c=np.cos(self.rot[1]*(np.pi/180))
        s=np.sin(self.rot[1]*(np.pi/180))
        m1=np.array([[c,0,s],[0,1,0],[-s,0,c]])
        c=np.cos(self.rot[0]*(np.pi/180))
        s=np.sin(self.rot[0]*(np.pi/180))
        m2=np.array([[1,0,0],[0,c,-s],[0,s,c]])
        m=m1.dot(m2)
        return m

    def handle_camera_events(self,event):
        if event.type == pygame.KEYDOWN:
            cb = self.change_of_basis()
            if event.key == pygame.K_f:
                m=cb.dot(np.array([0,0,-0.5]))
                self.pos=OGl.three_func(self.pos,m, lambda x,y : x+y )
            if event.key == pygame.K_g:
                m=cb.dot(np.array([0,0,0.5]))
                self.pos=OGl.three_func(self.pos,m, lambda x,y : x+y )
            if event.key == pygame.K_LEFT:
                m=cb.dot(np.array([-0.5,0,0]))
                self.pos=OGl.three_func(self.pos,m, lambda x,y : x+y )
            if event.key == pygame.K_RIGHT:
                m=cb.dot(np.array([0.5,0,0]))
                self.pos=OGl.three_func(self.pos,m, lambda x,y : x+y )
            if event.key == pygame.K_DOWN:
                m=cb.dot(np.array([0,-0.5,0]))
                self.pos=OGl.three_func(self.pos,m, lambda x,y : x+y )
            if event.key == pygame.K_UP:
                m=cb.dot(np.array([0,0.5,0]))
                self.pos=OGl.three_func(self.pos,m, lambda x,y : x+y )

        if event.type == pygame.MOUSEMOTION and self.rotating:
            tmp_pos = pygame.mouse.get_pos()
            x,y = self.mouse_pos[0] - tmp_pos[0], self.mouse_pos[1] - tmp_pos[1]
            if x != 0 or y != 0:
                self.rot[1] = (self.rot[1] + x)
                self.rot[0] = (self.rot[0] + y)
                self.mouse_pos = tmp_pos

        if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            if self.rotating == False:
                self.rotating = True
                self.mouse_pos = pygame.mouse.get_pos()

        if event.type == pygame.MOUSEBUTTONUP and event.button == 1:
            self.rotating = False

def Cube():
    glBegin(GL_LINES)
    for edge in edges:
        for vertex in edge:
            glVertex3fv(verticies[vertex])
    glEnd()

def main():
    pygame.init()
    display = (800,600)
    pygame.display.set_mode(display, DOUBLEBUF|OPENGL)
    camera = GLCamera()

    while True:
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        gluPerspective(45, (display[0]/display[1]), 0.1, 50.0)
        camera.add_to_scene()
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
            camera.handle_camera_events(event)

        glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
        Cube()
        pygame.display.flip()
        pygame.time.wait(10)

main()
```

答:
You are close, but the computation change_of_basis is not correct. The view matrix is defined by:

glRotatef(self.rot[2], 0, 0, 1);  # roll
glRotatef(self.rot[1], 0, 1, 0); # heading
glRotatef(self.rot[0], 1, 0, 0);  # pitch
glTranslatef(-self.pos[0],-self.pos[1],-self.pos[2])
```
</blockquote>

<p>If you want to move the object relative to the view space, then you have to transform the movement vectors in view space to world space. Then change the world space position of the object.<br>
Since the view matrix transforms from world space to view space, the vectors have to be transformed by the inverse view matrix.</p>

<p>Reconstruct the orientation of the view matrix and compute the inverse matrix of the view matrix.
Using NumPy, the inverse matrix can be computed by <code>numpy.linalg.inv(a)</code>. The rotation matrices matrices for the x, y and z axis can be concatenated by either <code>numpy.matmul</code> or an operator. Note, for array, <code>*</code> means element-wise multiplication, while <code>@</code> means matrix multiplication. See <code>array</code>.</p>

<p>Change <code>change_of_basis</code> to solve the issue:</p>

<pre class="lang-py prettyprint-override"><code>class GLCamera():

    # [...]

    def change_of_basis(self):
        #skip roll for now
        rx, ry, rz = [self.rot[i]*np.pi/180 for i in range(3)]
        s, c = np.sin(rx), np.cos(rx)
        mx = np.array([[1,0,0],[0,c,-s],[0,s,c]])
        s, c = np.sin(ry), np.cos(ry)
        my = np.array([[c,0,s],[0,1,0],[-s,0,c]])
        s, c = np.sin(rz), np.cos(rz)
        mz = np.array([[c,-s,0],[s,c,0],[0,0,1]])
        m = my @ mx @ mz
        inv_m = np.linalg.inv(m)
        return inv_m
</code>```

Body:
You are close, but the computation change_of_basis is not correct. The view matrix is defined by:

glRotatef(self.rot[2], 0, 0, 1);  # roll
glRotatef(self.rot[1], 0, 1, 0); # heading
glRotatef(self.rot[0], 1, 0, 0);  # pitch
glTranslatef(-self.pos[0],-self.pos[1],-self.pos[2])

If you want to move the object relative to the view space, then you have to transform the movement vectors in view space to world space. Then change the world space position of the object.

Since the view matrix transforms from world space to view space, the vectors have to be transformed by the inverse view matrix.

Reconstruct the orientation of the view matrix and compute the inverse matrix of the view matrix.
Using NumPy, the inverse matrix can be computed by numpy.linalg.inv(a). The rotation matrices matrices for the x, y and z axis can be concatenated by either numpy.matmul or an operator. Note, for array, * means element-wise multiplication, while @ means matrix multiplication. See array.

Change change_of_basis to solve the issue:

class GLCamera():

    # [...]

    def change_of_basis(self):
        #skip roll for now
        rx, ry, rz = [self.rot[i]*np.pi/180 for i in range(3)]
        s, c = np.sin(rx), np.cos(rx)
        mx = np.array([[1,0,0],[0,c,-s],[0,s,c]])
        s, c = np.sin(ry), np.cos(ry)
        my = np.array([[c,0,s],[0,1,0],[-s,0,c]])
        s, c = np.sin(rz), np.cos(rz)
        mz = np.array([[c,-s,0],[s,c,0],[0,0,1]])
        m = my @ mx @ mz
        inv_m = np.linalg.inv(m)
        return inv_m


问:
preg_replace with replacement function
How do you use preg_replace with a function as the replacement parameter? I'm getting an error with this code.

```<code>function getInfo($id,$slot){
  if(!$id){ return '<b>Error</b> Id Not Returned. Please contact support@site.com for more information.'; }
  $mm = mysql_query("SELECT * FROM `users` WHERE `id`='".$id."'");
  $mma = mysql_fetch_assoc($mm);
  $p = $mma[$slot];
  return $p;
  //return $id; <- Debug (Returns ID given)
}
$post = preg_replace(
  "/\[CallName]([^]]+)\[\/CallName\]/",
  getInfo('\\1',"fullname"),
  $post
);
</code>```

答:
I think you forgot e modifier (PREG_REPLACE_EVAL) in preg_replace function, this modifier is needed to evaluate replacement string as PHP code. It should be like this:

```<code>$post = preg_replace('~\[CallName\]([^]]+)\[/CallName\]~e', 'getInfo("$1", "fullname")', $post);
</code>```

See this manual for for details.

Title: preg_replace with replacement function

Body:
How do you use preg_replace with a function as the replacement parameter? I'm getting an error with this code.

function getInfo($id,$slot){
  if(!$id){ return 'Error Id Not Returned. Please contact support@site.com for more information.'; }
  $mm = mysql_query("SELECT * FROM `users` WHERE `id`='".$id."'");
  $mma = mysql_fetch_assoc($mm);
  $p = $mma[$slot];
  return $p;
  //return $id; <- Debug (Returns ID given)
}
$post = preg_replace(
  "/\[CallName]([^]]+)\[\/CallName\]/",
  getInfo('\\1',"fullname"),
  $post
);

Body:
I think you forgot e modifier (PREG_REPLACE_EVAL) in preg_replace function, this modifier is needed to evaluate replacement string as PHP code. It should be like this:

$post = preg_replace('~\[CallName\]([^]]+)\[/CallName\]~e', 'getInfo("$1", "fullname")', $post);

See this manual for for details.


问:
Jenkins dotnet lambda deploy-serverless Could not execute because the specified command or file was not found
I am new to CI/CD and trying to deploy a simple serverless function through Jenkins and getting error.

Here are my steps

Create a new project using dotnet new serverless.AspNetCoreWebAPI

Configured Git source {GitHub} where this project is located.

Added following lines in Build Step

`export PATH=$PATH:/usr/local/share/dotnet:/usr/local/bin

dotnet lambda deploy-serverless`

After running the above command I get the error

/usr/local/share/dotnet/dotnet lambda deploy-serverless Could not execute because the specified command or file was not found. Possible reasons for this include:

  You misspelled a built-in dotnet command.

  You intended to execute a .NET Core program, but dotnet-lambda does not exist.

  You intended to run a global tool, but a dotnet-prefixed executable with this name could not be found on the PATH.

  Build step 'Execute shell' marked build as failure Finished: FAILURE

Needless to say I can successfully run dotnet lambda deploy-serverless if using terminal window.

Any idea what's wrong here?

答:
Solved the issue finally.

Compared the .csproj files one for successful lambda deployment and one where it was failing. Noticed that following lines were the difference. It worked as soon as I added the below in my project file.

```<code><ItemGroup><DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="2.2.0" /></ItemGroup>
</code>```

It will be still interesting to know that why dotnet lambda deploy-serverless works from terminal window for the same project without the above line but not from inside jenkins job.

Body:
Solved the issue finally.

Compared the .csproj files one for successful lambda deployment and one where it was failing. Noticed that following lines were the difference. It worked as soon as I added the below in my project file.

<ItemGroup><DotNetCliToolReference Include="Amazon.Lambda.Tools" Version="2.2.0" /></ItemGroup>

It will be still interesting to know that why dotnet lambda deploy-serverless works from terminal window for the same project without the above line but not from inside jenkins job.


问:
Is there replacement for cat on Windows
I need to join two binary files with a *.bat script on Windows.

How can I achieve that?

答:
Just use the dos copy command with multiple source files and one destination file.

copy file1+file2 appendedfile
```

You might need the /B option for binary files

OwnerDisplayName: Artem Tikhomirov

Title: Is there replacement for cat on Windows

LastEditorDisplayName: Greg Hewgill

Body:
Just use the dos copy command with multiple source files and one destination file.

copy file1+file2 appendedfile

You might need the /B option for binary files

OwnerDisplayName: simon


问:
HTML <select> element is abbreviated in iPhone or Android browsers
I'm in a bit of a situation with my HTML <select> dropdowns, when they are displayed in an iPhone or Android browser. I often need to render <option> labels that are quite long, such as for instance

[AccountType] [EUR] - [Customer] - CH12 3456 7890 1234 5678 9

On Android, this will render something like that:

On the iPhone it's even worse. While I like the native look and feel, the cropping of the labels is a no-go. Circled in red, you'll find how the dropdown itself is rendered. I could live with that. But check out the blue popup that appears, when I click on it. The user will never find his data...

PLEASE, before you answer...

... consider these points:

I can abbreviate some information, but I will still have cases with long option labels in the select. So no need to tell me that the IBAN could be abbreviated, etc.

I cannot rely on CSS styling of <select> or <option> elements.

User hunter has already proposed the <optgroup> tag here. That's quite a nice idea and will be a small workaround, but is not enough, as the IBAN is still cropped by both iPhone and Android browsers :-(

I already know the very nice looking jQuery UI Selectmenu prototype. Unfortunately, it's not yet compatible with jquery-ui 1.8.5 and there is no guarantee when it will be stable.

I am using jquery and jquery-ui 1.8.5, so any ideas / references to plugins are very welcome.

Any other ideas to circumvent that problem GENERALLY are welcome.

答: I ran into the same problem. I wanted an imitation drop-down box similar to the jQuery UI combobox but I didn't want to use jQuery UI so I used this other jQuery selectbox plugin. It is somewhat buggy but better for my purposes than the default iPhone select element.</p>

ContentLicense: CC BY-SA 2.5