问:
SQLITE custom Accent collation function and LIKE queries
I've created this NOACCENT COLLATION in Python3 to use it in an sqlite database program I'm trying to write.

My aim is to make accented vocals insensitive searches and to make data input insenstive to accents too so that (i.e.) the value 'González' will not be admitted if there is a 'Gonzalez' value already in that table field.

What I did works well for the second part (restrict values) and for complete value searches.
I cannot make it to work for SELECT ... LIKE expressions. I know about the LIKE limitation of COLLATE NOCASE in SQLite for unicode characters out of a-z, A-Z but why that limitation applies when I'm using my own defined collation NOACCENT ? 'Cause it seems that's what happening.

Example:

```<code>cur.execute(""" CREATE TABLE Demo(
            Id INTEGER PRIMARY KEY,
            Nombre TEXT COLLATE NOACCENT UNIQUE)""")

cur.execute("INSERT INTO Demo(Nombre) VALUES ('álberto')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('alberta')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('Álbertu')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('Álberte')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('Albertczo')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('albertai')")
</code>```

If I do:

```<code>cur.execute("SELECT * FROM Demo WHERE Nombre='ALBERTO' COLLATE NOACCENT")
</code>```

I get:

```<code>(1, 'álberto)
</code>```

What is fine. This works with any combination of upper and lower case and any accent in any vocal of the word ('ALBERTÓ', 'Älbèrtô'...)

If i try to insert the value 'ALBERTÓ' i get an error due to the unique constraint so this is working well.

The problem is when i try to use LIKE expressions:

```<code>cur.execute("SELECT * FROM Demo WHERE Nombre LIKE 'ALBERT%' COLLATE NOACCENT")
</code>```

That returns:

```<code>(2, 'alberta')
(5, 'Albertczo')
(6, 'albertai')
</code>```

The values without accent.

Is there any solution for this from the database itself or will I have to make partial searches (i.e. 'albert') through software.

Hope my question is clear enough.

Thanks in advance.

```<code>def noaccent(string): # eliminate accented vocals
    vocals = ['a', 'e', 'i', 'o', 'u'] * 4
    acc_vocals = ['á', 'é', 'í', 'ó', 'ú','à', 'è', 'ì', 'ò', 'ù', 'ä', 'ë', 'ï', 'ö', 'ü', 'â', 'ê', 'î', 'ô', 'û']
    no_acc = string
    for letter in acc_vocals:
        no_acc = no_acc.replace(letter, vocals[acc_vocals.index(letter)])
    return no_acc

def collate_noaccent(string1, string2):
    str1 = noaccent(string1.lower())
    str2 = noaccent(string2.lower())
    if str1 < str2:
        return -1
    elif str1 > str2:
        return 1
    else:
        return 0
</code>```

答:
I solved this problem by creating my own "like" function in the SqliteUnicode class I have designed. It slows down searchs by a factor of 8. Since the class is not yet optimized, I prefer not to post it here now, unless you ask. </p>

```<code>    link = sqlite.connect(db_file_s)
    extension = SqliteUnicode()
    link.create_collation("france", extension.collate)
    link.create_function("like", 2, extension.like)
</code>```

<p>Edit 2019 : you can find the class here :
https://pastebin.com/FvMZdBY5
Please, note I am not a professional, and there are still some cases where the personalised "like" may cause errors. The regular expressions have to be improved, but for our usage in a library database, it is working fine for years now. If you improve this work, please, share. </p>

Body:
I've created this NOACCENT COLLATION in Python3 to use it in an sqlite database program I'm trying to write.

My aim is to make accented vocals insensitive searches and to make data input insenstive to accents too so that (i.e.) the value 'González' will not be admitted if there is a 'Gonzalez' value already in that table field.

What I did works well for the second part (restrict values) and for complete value searches.
I cannot make it to work for SELECT ... LIKE expressions. I know about the LIKE limitation of COLLATE NOCASE in SQLite for unicode characters out of a-z, A-Z but why that limitation applies when I'm using my own defined collation NOACCENT ? 'Cause it seems that's what happening.

Example:

cur.execute(""" CREATE TABLE Demo(
            Id INTEGER PRIMARY KEY,
            Nombre TEXT COLLATE NOACCENT UNIQUE)""")

cur.execute("INSERT INTO Demo(Nombre) VALUES ('álberto')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('alberta')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('Álbertu')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('Álberte')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('Albertczo')")
cur.execute("INSERT INTO Demo(Nombre) VALUES ('albertai')")

If I do:

cur.execute("SELECT * FROM Demo WHERE Nombre='ALBERTO' COLLATE NOACCENT")

I get:

(1, 'álberto)

What is fine. This works with any combination of upper and lower case and any accent in any vocal of the word ('ALBERTÓ', 'Älbèrtô'...)

If i try to insert the value 'ALBERTÓ' i get an error due to the unique constraint so this is working well.

The problem is when i try to use LIKE expressions:

cur.execute("SELECT * FROM Demo WHERE Nombre LIKE 'ALBERT%' COLLATE NOACCENT")

That returns:

(2, 'alberta')
(5, 'Albertczo')
(6, 'albertai')

The values without accent.

Is there any solution for this from the database itself or will I have to make partial searches (i.e. 'albert') through software.

Hope my question is clear enough.

Thanks in advance.

def noaccent(string): # eliminate accented vocals
    vocals = ['a', 'e', 'i', 'o', 'u'] * 4
    acc_vocals = ['á', 'é', 'í', 'ó', 'ú','à', 'è', 'ì', 'ò', 'ù', 'ä', 'ë', 'ï', 'ö', 'ü', 'â', 'ê', 'î', 'ô', 'û']
    no_acc = string
    for letter in acc_vocals:
        no_acc = no_acc.replace(letter, vocals[acc_vocals.index(letter)])
    return no_acc

def collate_noaccent(string1, string2):
    str1 = noaccent(string1.lower())
    str2 = noaccent(string2.lower())
    if str1 < str2:
        return -1
    elif str1 > str2:
        return 1
    else:
        return 0

Body:
I solved this problem by creating my own "like" function in the SqliteUnicode class I have designed. It slows down searchs by a factor of 8. Since the class is not yet optimized, I prefer not to post it here now, unless you ask.

    link = sqlite.connect(db_file_s)
    extension = SqliteUnicode()
    link.create_collation("france", extension.collate)
    link.create_function("like", 2, extension.like)

Edit 2019 : you can find the class here :
https://pastebin.com/FvMZdBY5
Please, note I am not a professional, and there are still some cases where the personalised "like" may cause errors. The regular expressions have to be improved, but for our usage in a library database, it is working fine for years now. If you improve this work, please, share.


来源: stackexchange

问:
.NET App.Config issues across multiple projects
I have a solution that contains two projects.  One project is a Windows Service that contains a few classes for performing various functions.  The other project is a Windows Form Application that is meant for doing various testing and performing task that the service accomplishes on demand.  For instance, the service will do a few various task at a certain time interval, but if you wanted to perform one of those task before the time interval has elapsed, you could load the Windows Forms Application and execute one of the task immediately. The Windows Form Application (from here referred to as the tester) references the Windows Service (from here referred to as Service) project. When the Tester loads, it creates an instance of one of the classes from the Service.  Whenever buttons are pressed to perform the task, it references that instance that was created and calls the various methods of the class. The Service has uses application settings for the configuration, and thus has an app.config.  The configuration settings are accessed using [ProjectName].Properties.Settings.Default.[SettingName].  When the configuration settings for the tester are changed on its own app.config (or exe.config after release), the settings are refreshed without a problem.  If the tester is closed, configuration is modified, and then reopened, the new settings will be populated.  If the Reload method is called on the Settings, the configuration is refreshed without a problem.  The Service performs in the same way.  The configuration settings are can be updated without a problem.

The problem is that if configuration changes need to be made on the service, when the service methods are called from the tester, the configuration does not take the new settings.  Whatever settings the project was built with will be used.  I cannot get the tester to recognize that the app.config/exe.config for the service has changed, and the new configuration should be reloaded and used instead of whatever configuration was used when the project was built in visual studio.  Perhaps it I am not educated enough about this topic, but it seems to me that the app.config is rolled up into the .exe file created by the Service whenever it is built.

I have tried encapsulating the Reload method for the Service and calling it, and it doesn't seem to make a difference.

I have an example project that performs as is described above on a very basic level.  The ideal goal is to be able to modify the exe.config file or files on the fly and have both the Service and the Tester pick them up without any problems.  If you would like to see exactly what I mean from a coding perspective, an example project can be found here: example solution

Any help would be greatly appreciated.  Thanks you for your time.

Update

I have managed to find A solution to this, but I am still curious if there is a better way.  By using an app.config that is shared between both projects and using the Configuration Manager instead of App Settings, everything works as it is expected to.  I prefer to use App Settings if at all possible; however it will work to use a shared app.config and the Configuration Manager pointed at that app.config.

答: Found the solution.  An app.config must be added to the solution as is described above in my update.  Once linked like that, you can add a settings file to the project and add settings/configuration to the project and they will be added to the solutions settings file.  This will move with the build and fix the problem I was having.</p>

ContentLicense: CC BY-SA 2.5


问:
Pandas: modifying the dataframe by splitting into columns
I have a dataframe which contains the number of sold cars within 2017.
I want a time series to plot different car models sold.

Here is my current DF

```<code>      Date   Price  Location Type
2003-05-16  397500  Texas    Ford
2003-05-16  235000  Florida  Fiat
2003-05-16  235000  Florida  Mercedes
2003-05-16  235000  NJ       Mercedes
</code>```

I want to modify the data so I get the following dataframe in order to display a multiple time series graph.

```<code>Date       Ford       Fiat  Mercedes
2003-05-16  1        3       19
2003-09-10  2        2       1
</code>```

答:
It seems you need:

```<code>df.groupby(['Date','Type']).size().unstack(fill_value=0).plot.bar()
</code>```

Or:

```<code>df.reset_index().groupby(['Date','Type']).size().unstack(fill_value=0).plot.bar()
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a dataframe which contains the number of sold cars within 2017.
I want a time series to plot different car models sold.

Here is my current DF

      Date   Price  Location Type
2003-05-16  397500  Texas    Ford
2003-05-16  235000  Florida  Fiat
2003-05-16  235000  Florida  Mercedes
2003-05-16  235000  NJ       Mercedes

I want to modify the data so I get the following dataframe in order to display a multiple time series graph.

Date       Ford       Fiat  Mercedes
2003-05-16  1        3       19
2003-09-10  2        2       1

Body:
It seems you need:

df.groupby(['Date','Type']).size().unstack(fill_value=0).plot.bar()

Or:

df.reset_index().groupby(['Date','Type']).size().unstack(fill_value=0).plot.bar()


问:
How to specify nodes' positions in visNetwork package in R
I would like to fix the positions of the nodes at (1,0), (0,1), (-1,0), (0,-1) and (0,0). However, it does not not work and my Java knowledge is zero (it seems, that here ist the question concering the Java code).

Can anybody help? Here is an example:

```<code>require(visNetwork, quietly = TRUE)
nodes <- data.frame(id = 1:5)
                    # x = c(1, 0, -1, 0, 0),
                    # y = c(0, 1, 0, -1, 0))
edges <- data.frame(from = c(1,2), to = c(1,3))

visNetwork(nodes, edges, width = "100%") %>%
  visNodes(x = c(1, 0, -1, 0, 0),
           y = c(0, 1, 0, -1, 0), fixed = TRUE, physics = TRUE) %>%
  visOptions(highlightNearest = TRUE) %>%
  visInteraction(navigationButtons = TRUE, dragNodes = FALSE,
                 dragView = FALSE, zoomView = FALSE) %>%
  visEdges(arrows = 'from')
</code>```

答:
You could do

```<code>coords <- matrix(ncol=2, byrow=T, data=c(
  1,0,
  0,1,
  -1,0,
  0,-1,
  0,0))
opts <- . %>% visOptions(highlightNearest = TRUE) %>%
  visInteraction(navigationButtons = TRUE, dragNodes = FALSE,
                 dragView = FALSE, zoomView = FALSE) %>%
  visEdges(arrows = 'from')

visNetwork(nodes, edges, width = "100%") %>%
  visIgraphLayout(layout = "layout.norm", layoutMatrix = coords) %>%
  opts
</code>```

or

```<code>nodes$x <- c(1, 0, -1, 0, 0)*100
nodes$y <- c(0, 1, 0, -1, 0)*100
visNetwork(nodes, edges, width = "100%") %>%
  visNodes(fixed = TRUE) %>%
  opts
</code>```

Use coords[,2] <- coords[,2]*-1 to flip the vertical axis if necessary.

Body:
I would like to fix the positions of the nodes at (1,0), (0,1), (-1,0), (0,-1) and (0,0). However, it does not not work and my Java knowledge is zero (it seems, that here ist the question concering the Java code).

Can anybody help? Here is an example:

require(visNetwork, quietly = TRUE)
nodes <- data.frame(id = 1:5)
                    # x = c(1, 0, -1, 0, 0),
                    # y = c(0, 1, 0, -1, 0))
edges <- data.frame(from = c(1,2), to = c(1,3))

visNetwork(nodes, edges, width = "100%") %>%
  visNodes(x = c(1, 0, -1, 0, 0),
           y = c(0, 1, 0, -1, 0), fixed = TRUE, physics = TRUE) %>%
  visOptions(highlightNearest = TRUE) %>%
  visInteraction(navigationButtons = TRUE, dragNodes = FALSE,
                 dragView = FALSE, zoomView = FALSE) %>%
  visEdges(arrows = 'from')

Body:
You could do

coords <- matrix(ncol=2, byrow=T, data=c(
  1,0,
  0,1,
  -1,0,
  0,-1,
  0,0))
opts <- . %>% visOptions(highlightNearest = TRUE) %>%
  visInteraction(navigationButtons = TRUE, dragNodes = FALSE,
                 dragView = FALSE, zoomView = FALSE) %>%
  visEdges(arrows = 'from')

visNetwork(nodes, edges, width = "100%") %>%
  visIgraphLayout(layout = "layout.norm", layoutMatrix = coords) %>%
  opts

or

nodes$x <- c(1, 0, -1, 0, 0)*100
nodes$y <- c(0, 1, 0, -1, 0)*100
visNetwork(nodes, edges, width = "100%") %>%
  visNodes(fixed = TRUE) %>%
  opts

Use coords[,2] <- coords[,2]*-1 to flip the vertical axis if necessary.


问:
How to inherit properties in custom JavaFX panes
I want to make a few subclasses of JavaFX's AnchorPane component but in each case inherit AnchorPane's layout features. I am able to define a subclass:

```<code>package tuto;

import javafx.scene.Node;
import javafx.scene.layout.AnchorPane;

public class TutoPane extends javafx.scene.layout.AnchorPane {

    protected void layoutChildren() {
        super.layoutChildren();
    }

}
</code>```

... and interestingly I am also able to import this into Scene Builder. However, Scene Builder is not recognizing the inheritance relationship. If I place a normal AnchorPane next to one of my custom TutoPanes in Scene Builder I get this:

As you can see, the control placed inside of the AnchorPane (green) has positioning defined by the four Anchor Pane constraints.

However when I try with the TutoPane I get this:

The control placed inside the TutoPane (dark slate blue) is stuck in the top left corner and the "layout" properties do not give me the four AnchorPane constraints, which I'd expect to find available due to inheritance. What do I need to do to get Scene Builder to recognize my custom pane as an AnchorPane? Is there an equivalent of the JavaBeans Specification that applies to JavaFX?

答:
SceneBuilder doesn't show the Anchor constraint field in its properties palette. Add the anchor constraints in the fxml because inherited anchor pane class is not recoganized by the scene-builder tool.

please see the below code. HolderPane is a child class of AnchorPane, and here the children of HolderPane is hardcoded with the anchor values.

```<code><HolderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
   minWidth="-Infinity" prefHeight="600.0" prefWidth="500.0"
    xmlns="http://javafx.com/javafx/8.0.111"
    xmlns:fx="http://javafx.com/fxml/1">
    <children>
       <AnchorPane AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0
          AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
       </AnchorPane>
   </children>
</code>```

Body:
I want to make a few subclasses of JavaFX's AnchorPane component but in each case inherit AnchorPane's layout features. I am able to define a subclass:

package tuto;

import javafx.scene.Node;
import javafx.scene.layout.AnchorPane;

public class TutoPane extends javafx.scene.layout.AnchorPane {

    protected void layoutChildren() {
        super.layoutChildren();
    }

}

... and interestingly I am also able to import this into Scene Builder. However, Scene Builder is not recognizing the inheritance relationship. If I place a normal AnchorPane next to one of my custom TutoPanes in Scene Builder I get this:

As you can see, the control placed inside of the AnchorPane (green) has positioning defined by the four Anchor Pane constraints.

However when I try with the TutoPane I get this:

The control placed inside the TutoPane (dark slate blue) is stuck in the top left corner and the "layout" properties do not give me the four AnchorPane constraints, which I'd expect to find available due to inheritance. What do I need to do to get Scene Builder to recognize my custom pane as an AnchorPane? Is there an equivalent of the JavaBeans Specification that applies to JavaFX?

Body:
SceneBuilder doesn't show the Anchor constraint field in its properties palette. Add the anchor constraints in the fxml because inherited anchor pane class is not recoganized by the scene-builder tool.

please see the below code. HolderPane is a child class of AnchorPane, and here the children of HolderPane is hardcoded with the anchor values.

<HolderPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity"
   minWidth="-Infinity" prefHeight="600.0" prefWidth="500.0"
    xmlns="http://javafx.com/javafx/8.0.111"
    xmlns:fx="http://javafx.com/fxml/1">
    <children>
       <AnchorPane AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0
          AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
       </AnchorPane>
   </children>


问:
Why does numpy.std() use abs()?
I checked the numpy library and found the following definition for the standard deviation in numpy:

```<code>std = sqrt(mean(abs(x - x.mean())**2))
</code>```

Why is the abs() function used? - Because mathematically the square of a number will be positive per definition.

So I thought:

```<code>abs(x - x.mean())**2 == (x - x.mean())**2
</code>```

答:
The square of a real number is always positive, but this is not true for complex numbers.

A very simple example: j**2=-1

A more complex (pun intended) example: (3-2j)**2=(5-12j)

From documentation:

Note that, for complex numbers, std takes the absolute value before squaring, so that the result is always real and nonnegative.

Note:
Python uses j for the imaginary unit, while mathematicians uses i.

Title: Why does numpy.std() use abs()?

Body:
I checked the numpy library and found the following definition for the standard deviation in numpy:

std = sqrt(mean(abs(x - x.mean())**2))

Why is the abs() function used? - Because mathematically the square of a number will be positive per definition.

So I thought:

abs(x - x.mean())**2 == (x - x.mean())**2


问:
Scrollable CardView with RecyclerView inside
I would like to implement a screen where I have a Card view containing a RecyclerView.

The CardView should of the same height of the content of the recycler view, this means that if the RecyclerView has few item, I should see the bottom corners and the bottom shadow of the card but if the RecyclerView has many items, the Card view should "scroll" with the RecyclerView to have the bottom corners and shadow of the cardview at the bottom of the RecylerView.

Here what it should look like when the RecyclerView is at top :

When the user begins to scroll, the top corners disappear with the RecyclerView scrolling :

And finally, when the user reaches the bottom of the RecyclerView, the bottom corners and the shadow of the CardView appears :

From now, I managed to have a working implementation by putting the RecyclerView inside the CardView and the CardView inside a NestedScrollView but this breaks the fling gesture...

```<code><android.support.design.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:clipChildren="false"
    android:id="@+id/containerLayout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    tools:ignore="MissingPrefix">

    <android.support.v4.widget.NestedScrollView
        android:clipToPadding="false"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:paddingBottom="16dp"
        android:paddingLeft="85dp"
        android:paddingRight="85dp"
        android:paddingTop="16dp">

        <android.support.v7.widget.CardView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            app:cardBackgroundColor="?android:attr/windowBackground">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"/>
        </android.support.v7.widget.CardView>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
</code>```

Do you have any hints or idea on how I could implement such design ? I guess that CoordinatorLayout could help me but I couldn't find anything ...

Thank you

答:
Picking up Oknesif's idea of a manipulated adapter, I made an adapter with three layouts (topitem, middleitem, bottomitem) with two XML drawable shapes for topitem and bottomitem. Thus, I was able to completely get rid of the NestedScrollView and the CardView.

This is what it looks like:

And here is the code. First, MainActivity:

```<code>public class MainActivity extends AppCompatActivity {
    final static int LIST_SIZE = 100;

    final static int TOP = 0;
    final static int BOTTOM = LIST_SIZE;
    final static int MIDDLE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity);

        final ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < LIST_SIZE; i++) {
            list.add(i);
        }

        class Viewholder extends RecyclerView.ViewHolder {
            TextView textView;

            Viewholder(View itemView) {
                super(itemView);
                textView = itemView.findViewById(R.id.textView);
            }
        }

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        final RecyclerView.Adapter<Viewholder> adapter = new RecyclerView.Adapter<Viewholder>() {
            LayoutInflater inflater = LayoutInflater.from(MainActivity.this);

            @Override
            public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
                switch (viewType) {
                    case TOP:
                        return new Viewholder(inflater.inflate(R.layout.topitem, parent, false));
                    case BOTTOM:
                        return new Viewholder(inflater.inflate(R.layout.bottomitem, parent, false));
                    case MIDDLE:
                    default:
                        return new Viewholder(inflater.inflate(R.layout.middleitem, parent, false));
                }
            }

            @Override
            public void onBindViewHolder(Viewholder holder, int position) {
                holder.textView.setText(String.valueOf(list.get(position)));
                if (position != 0 && position != LIST_SIZE - 1) {
                    int color = position % 2 == 0 ? android.R.color.holo_orange_dark : android.R.color.holo_orange_light;
                    holder.itemView.setBackgroundColor(getResources().getColor(color));
                }
            }

            @Override
            public int getItemCount() {
                return LIST_SIZE;
            }

            @Override
            public int getItemViewType(int position) {
                int itemViewType;
                switch (position) {
                    case 0:
                        itemViewType = TOP;
                        break;
                    case LIST_SIZE - 1:
                        itemViewType = BOTTOM;
                        break;
                    default:
                        itemViewType = MIDDLE;
                }
                return itemViewType;
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    }
}
</code>```

res/layout/activity.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/containerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:paddingLeft="25dp"
        android:paddingRight="25dp" />
</android.support.design.widget.CoordinatorLayout>
</code>```

res/layout/topitem.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/topbackground"
    android:layout_marginTop="50dp"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:textStyle="bold" />
</code>```

res/layout/middleitem.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:textStyle="bold" />
</code>```

res/layout/bottomitem.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bottombackground"
    android:layout_marginBottom="50dp"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:textStyle="bold" />
</code>```

res/drawable/topbackground.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp" />
    <solid android:color="@android:color/holo_orange_dark" />
</shape>
</code>```

res/drawable/bottombackground.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp" />
    <solid android:color="@android:color/holo_orange_light" />
</shape>
</code>```

EDIT:

Adding this line to the bottom XML item layouts:

```<code>android:elevation="12dp"
</code>```

and changing the background to white, gives the following result:

Body:
I would like to implement a screen where I have a Card view containing a RecyclerView.

The CardView should of the same height of the content of the recycler view, this means that if the RecyclerView has few item, I should see the bottom corners and the bottom shadow of the card but if the RecyclerView has many items, the Card view should "scroll" with the RecyclerView to have the bottom corners and shadow of the cardview at the bottom of the RecylerView.

Here what it should look like when the RecyclerView is at top :

When the user begins to scroll, the top corners disappear with the RecyclerView scrolling :

And finally, when the user reaches the bottom of the RecyclerView, the bottom corners and the shadow of the CardView appears :

From now, I managed to have a working implementation by putting the RecyclerView inside the CardView and the CardView inside a NestedScrollView but this breaks the fling gesture...

<android.support.design.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:clipChildren="false"
    android:id="@+id/containerLayout"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    tools:ignore="MissingPrefix">

    <android.support.v4.widget.NestedScrollView
        android:clipToPadding="false"
        android:layout_height="match_parent"
        android:layout_width="match_parent"
        android:paddingBottom="16dp"
        android:paddingLeft="85dp"
        android:paddingRight="85dp"
        android:paddingTop="16dp">

        <android.support.v7.widget.CardView
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            app:cardBackgroundColor="?android:attr/windowBackground">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_height="wrap_content"
                android:layout_width="match_parent"/>
        </android.support.v7.widget.CardView>
    </android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>

Do you have any hints or idea on how I could implement such design ? I guess that CoordinatorLayout could help me but I couldn't find anything ...

Thank you

Body:
Picking up Oknesif's idea of a manipulated adapter, I made an adapter with three layouts (topitem, middleitem, bottomitem) with two XML drawable shapes for topitem and bottomitem. Thus, I was able to completely get rid of the NestedScrollView and the CardView.

This is what it looks like:

And here is the code. First, MainActivity:

public class MainActivity extends AppCompatActivity {
    final static int LIST_SIZE = 100;

    final static int TOP = 0;
    final static int BOTTOM = LIST_SIZE;
    final static int MIDDLE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity);

        final ArrayList<Integer> list = new ArrayList<>();
        for (int i = 0; i < LIST_SIZE; i++) {
            list.add(i);
        }

        class Viewholder extends RecyclerView.ViewHolder {
            TextView textView;

            Viewholder(View itemView) {
                super(itemView);
                textView = itemView.findViewById(R.id.textView);
            }
        }

        RecyclerView recyclerView = findViewById(R.id.recyclerView);
        final RecyclerView.Adapter<Viewholder> adapter = new RecyclerView.Adapter<Viewholder>() {
            LayoutInflater inflater = LayoutInflater.from(MainActivity.this);

            @Override
            public Viewholder onCreateViewHolder(ViewGroup parent, int viewType) {
                switch (viewType) {
                    case TOP:
                        return new Viewholder(inflater.inflate(R.layout.topitem, parent, false));
                    case BOTTOM:
                        return new Viewholder(inflater.inflate(R.layout.bottomitem, parent, false));
                    case MIDDLE:
                    default:
                        return new Viewholder(inflater.inflate(R.layout.middleitem, parent, false));
                }
            }

            @Override
            public void onBindViewHolder(Viewholder holder, int position) {
                holder.textView.setText(String.valueOf(list.get(position)));
                if (position != 0 && position != LIST_SIZE - 1) {
                    int color = position % 2 == 0 ? android.R.color.holo_orange_dark : android.R.color.holo_orange_light;
                    holder.itemView.setBackgroundColor(getResources().getColor(color));
                }
            }

            @Override
            public int getItemCount() {
                return LIST_SIZE;
            }

            @Override
            public int getItemViewType(int position) {
                int itemViewType;
                switch (position) {
                    case 0:
                        itemViewType = TOP;
                        break;
                    case LIST_SIZE - 1:
                        itemViewType = BOTTOM;
                        break;
                    default:
                        itemViewType = MIDDLE;
                }
                return itemViewType;
            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
    }
}

res/layout/activity.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/containerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:clipToPadding="false"
        android:paddingLeft="25dp"
        android:paddingRight="25dp" />
</android.support.design.widget.CoordinatorLayout>

res/layout/topitem.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/topbackground"
    android:layout_marginTop="50dp"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:textStyle="bold" />

res/layout/middleitem.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:textStyle="bold" />

res/layout/bottomitem.xml:

<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/bottombackground"
    android:layout_marginBottom="50dp"
    android:textAlignment="center"
    android:textColor="@android:color/white"
    android:textSize="24sp"
    android:textStyle="bold" />

res/drawable/topbackground.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp" />
    <solid android:color="@android:color/holo_orange_dark" />
</shape>

res/drawable/bottombackground.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners
        android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp" />
    <solid android:color="@android:color/holo_orange_light" />
</shape>

EDIT:

Adding this line to the bottom XML item layouts:

android:elevation="12dp"

and changing the background to white, gives the following result:


问:
Disable gzip content-encoding in android simulator
I was trying to read the HTTP messages between the browser in the Android simulator and other third party web-servers using tcpdump. However, since the browser can accept gzip content-encoding, I can't see the HTML content as plain-text in the tcpdump output. Is there a way to change the configs of the browser so that it doesn't send that Accept-Encoding: gzip header line?

答:
This post implies if you remove the

```<code>Accept-Encoding
</code>```

header, you'll get raw data back... you should be able to write a custom WebView that never sends that header.  Hope that works!

http://forgetmenotes.blogspot.com/2009/05/how-to-disable-gzip-compression-in.html

Body:
This post implies if you remove the

Accept-Encoding

header, you'll get raw data back... you should be able to write a custom WebView that never sends that header.  Hope that works!

http://forgetmenotes.blogspot.com/2009/05/how-to-disable-gzip-compression-in.html


问:
Spring boot Bean exception: Cannot determine embedded database driver class for database type NONE
I am trying to run a spring boot application which is made by someone else. I have tried to attach my local database to the application but when I run this, it gives the following error;

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

I am new to this and I can't find out what is the problem. Some details:

where xxx = name of the database.

Workbench:

```<code>Name: Local instance wampmysqld64
Host: localhost
Port: 3306
Server: MySQL Community Server (GPL)
Version: 5.7.18-log
Connector: C++ 1.1.4
Login User: root
Current User: root@localhost
SSL: Disabled
</code>```

And the server is up and running.

EDIT

pom.xml

```<code><project>

<modelVersion>4.0.0</modelVersion>

<groupId>****</groupId>
<artifactId>****</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.6.RELEASE</version>
</parent>

<dependencies>
    <dependency>
      <groupId>org.modelmapper</groupId>
      <artifactId>modelmapper</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
       <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>
</code>```

EDIT2

Application.properties

```<code>spring.datasource.url=jdbc:mysql://localhost:3306/xxx
spring.datasource.username=root
spring.datasource.password=root

spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
</code>```

ng.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

Application.java

```<code>package gdprserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(exclude = RepositoryRestMvcAutoConfiguration.class)
public class Application extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}
</code>```

EDIT3

I run the Spring boot application with CMD using the command: java -jar xxx.jar

答:
```<code>package com.fyakuthibernatespringboot.demo;

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
</code>```

Body:
I am trying to run a spring boot application which is made by someone else. I have tried to attach my local database to the application but when I run this, it gives the following error;

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceAutoConfiguration$NonEmbeddedConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [javax.sql.DataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).

I am new to this and I can't find out what is the problem. Some details:

where xxx = name of the database.

Workbench:

Name: Local instance wampmysqld64
Host: localhost
Port: 3306
Server: MySQL Community Server (GPL)
Version: 5.7.18-log
Connector: C++ 1.1.4
Login User: root
Current User: root@localhost
SSL: Disabled

And the server is up and running.

EDIT

pom.xml

<project>

<modelVersion>4.0.0</modelVersion>

<groupId>****</groupId>
<artifactId>****</artifactId>
<version>0.0.1-SNAPSHOT</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.3.6.RELEASE</version>
</parent>

<dependencies>
    <dependency>
      <groupId>org.modelmapper</groupId>
      <artifactId>modelmapper</artifactId>
      <version>1.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-rest</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
       <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

</project>

EDIT2

Application.properties

spring.datasource.url=jdbc:mysql://localhost:3306/xxx
spring.datasource.username=root
spring.datasource.password=root

spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQLDialect
spring.jpa.properties.hibernate.id.new_generator_mappings = false
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

ng.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE

Application.java

package gdprserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.context.web.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;

@SpringBootApplication(exclude = RepositoryRestMvcAutoConfiguration.class)
public class Application extends SpringBootServletInitializer {
    @Override
    protected SpringApplicationBuilder configure(final SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }

    public static void main(final String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Bean
    public ModelMapper modelMapper() {
        return new ModelMapper();
    }
}

EDIT3

I run the Spring boot application with CMD using the command: java -jar xxx.jar


问:
Elixir: Ecto/Tds error when connecting to SQL Server database
I've written an elixir application that connects to two different databases, and I have it working nicely in my remote database dev environment -- connecting with the same exact setup to a different database that is across my vpn. When I run it against a different remote SQL Server database, I get a strange error:

** (DBConnection.ConnectionError) bad return value: {:error, %Tds.Protocol{env: %{trans: <<0>>}, itcp: nil, opts: [password:
  :REDACTED, idle_timeout: 5000, name: EventBridge.C3poRepo.Pool,
  otp_app: :event_bridge, repo: EventBridge.C3poRepo, timeout: 15000,
  pool_timeout: 5000, adapter: Tds.Ecto, username: :ALSO_REDACTED,
  database: :REDACTED, hostname: :REDACTED, pool:
  DBConnection.Poolboy], pak_data: "", pak_header: "", query:
  %Tds.Query{handle: 1, statement: nil}, result: %Tds.Result{columns:
  [], command: nil, num_rows: 0, rows: []}, sock: {:gen_tcp,
  #Port<0.6472>}, state: :ready, tail: "", transaction: nil, usock: nil}}

The credentials I've got in my configuration for this database are correct--I verified them manually with DBeaver. I believe I'm capable of debugging this but I've run into a bit of that error message that I don't understand. Specifically:

{:error, %Tds.Protocol{env: %{trans: <<0>>}

For the sake of completeness, here the deps section in mix.exs:

```<code>defp deps do
    [
      {:tds_ecto, "~> 2.0.3"},
      {:postgrex, ">= 0.0.0"},
      {:gen_stage, "~> 0.12"},
      {:timex, "~> 3.1"},
      {:timex_ecto, "~> 3.0"},
      {:poison, "~> 3.1"},
      {:ecto, "~> 2.1"}
    ]
  end
</code>```

What I'm asking is for some insight into what that part of the error message means, or perhaps even some more general feedback on the entire error output.

Here are the two instances of configuration for the Repo in question. First the one that works:

```<code>config :event_bridge, EventBridge.FirstRepo,
  adapter: Tds.Ecto,
  database: "first_repo_development",
  username: "testuser",
  password: "password_redacted",
  hostname: "server_one"
</code>```

And here is the configuration for the one that doesn't work:

```<code>config :event_bridge, EventBridge.FirstRepo,
  adapter: Tds.Ecto,
  database: "first_repo_staging",
  username: "staging_username",
  password: "password_redacted",
  hostname: "server_twelve"
</code>```

Both work in DBeaver.

答:
Add
    pool_size:
in the db config and try again</p>

Body:
I've written an elixir application that connects to two different databases, and I have it working nicely in my remote database dev environment -- connecting with the same exact setup to a different database that is across my vpn. When I run it against a different remote SQL Server database, I get a strange error:

** (DBConnection.ConnectionError) bad return value: {:error, %Tds.Protocol{env: %{trans: <<0>>}, itcp: nil, opts: [password:
  :REDACTED, idle_timeout: 5000, name: EventBridge.C3poRepo.Pool,
  otp_app: :event_bridge, repo: EventBridge.C3poRepo, timeout: 15000,
  pool_timeout: 5000, adapter: Tds.Ecto, username: :ALSO_REDACTED,
  database: :REDACTED, hostname: :REDACTED, pool:
  DBConnection.Poolboy], pak_data: "", pak_header: "", query:
  %Tds.Query{handle: 1, statement: nil}, result: %Tds.Result{columns:
  [], command: nil, num_rows: 0, rows: []}, sock: {:gen_tcp,
  #Port<0.6472>}, state: :ready, tail: "", transaction: nil, usock: nil}}

The credentials I've got in my configuration for this database are correct--I verified them manually with DBeaver. I believe I'm capable of debugging this but I've run into a bit of that error message that I don't understand. Specifically:

{:error, %Tds.Protocol{env: %{trans: <<0>>}

For the sake of completeness, here the deps section in mix.exs:

defp deps do
    [
      {:tds_ecto, "~> 2.0.3"},
      {:postgrex, ">= 0.0.0"},
      {:gen_stage, "~> 0.12"},
      {:timex, "~> 3.1"},
      {:timex_ecto, "~> 3.0"},
      {:poison, "~> 3.1"},
      {:ecto, "~> 2.1"}
    ]
  end

What I'm asking is for some insight into what that part of the error message means, or perhaps even some more general feedback on the entire error output.

Here are the two instances of configuration for the Repo in question. First the one that works:

config :event_bridge, EventBridge.FirstRepo,
  adapter: Tds.Ecto,
  database: "first_repo_development",
  username: "testuser",
  password: "password_redacted",
  hostname: "server_one"

And here is the configuration for the one that doesn't work:

config :event_bridge, EventBridge.FirstRepo,
  adapter: Tds.Ecto,
  database: "first_repo_staging",
  username: "staging_username",
  password: "password_redacted",
  hostname: "server_twelve"

Both work in DBeaver.


问:
How to reference environmental variables in WORKSPACE?
If a project has an external dependency to software that's installed locally and can't be managed with new_http_archive or new_git_repository because licensing or size issues prevent it from being downloaded, is there a way to have the path specified with new_local_repository use an environmental variable?

Looking at the comments on Issue #746, it looks like this was solved in some way. But I can't find any documentation on how to do it.

答:
Looking at the comments on Issue #746, it looks like this was solved in some way. But I can't find any documentation on how to do it.

Thanks for checking for existing bugs! That bug is almost 2 years old though. Bazel has changed a ton since then.

For this problem, I think you should write your own repository rule in a .bzl file.

Repository rules are allowed to perform non-hermetic operations, read the environment, look at the whole filesystem, etc. Normal build rules are not, nor do they have access to the environment or the full filesystem.

Your repository rule should check the envvar's value and write a BUILD file that Bazel will use in the external repository that your rule created.

Look at my answer here for an example: Call llvm-config --prefix and use it in a BUILD rule


问:
Read multi-line delimited sub-strings to bash array
I'd like to create array containing

```<code>Speed: 10500 Mbps
Size: 122400 MB
Load: 4544 Kg
Distance: 232680 miles
Acceleration: 11200 meters/s2
Deviation: 1100 Wierdos
</code>```

From the following code:

```<code>read -r -d '' TEST_STRING << EOM
Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos
EOM

STRINGS_ARRAY=()
RE_INTRALINEDELIMITER=";"

while IFS=$'\n' read -a LINE; do

    if [[ $LINE =~ $RE_INTRALINEDELIMITER ]]; then
        echo "(intraline): $LINE"
        while IFS=$';' read -a SUBSTR; do
            echo "(substr): $SUBSTR"
        done <<< "$LINE"

    fi

done <<< "$TEST_STRING"
</code>```

(echoes are added for debugging and as an empty operator). Then process lines with some functions and finally to assembly it back to the original string.

But for SUBSTR I get only first sub-string from every string (before semicolon). What I'm doing wrong?

答:
Another way to split strings, using shell expansions and avoiding read which is slow :</p>

```<code>tmp=$TEST_STRING

while [[ $tmp = *[\;$'\n']* ]]; do
    item=${tmp%%[;$'\n']*}   # to remove the largest suffix starting with ; or newline
    tmp=${tmp#*[;$'\n']}     # to remove the shortest prefix ending with ; or new line
    echo "[$item]"
done
</code>```

Body:
I'd like to create array containing

Speed: 10500 Mbps
Size: 122400 MB
Load: 4544 Kg
Distance: 232680 miles
Acceleration: 11200 meters/s2
Deviation: 1100 Wierdos

From the following code:

read -r -d '' TEST_STRING << EOM
Speed: 10500 Mbps; Size: 122400 MB
Load: 4544 Kg; Distance: 232680 miles
Acceleration: 11200 meters/s2; Deviation: 1100 Wierdos
EOM

STRINGS_ARRAY=()
RE_INTRALINEDELIMITER=";"

while IFS=$'\n' read -a LINE; do

    if [[ $LINE =~ $RE_INTRALINEDELIMITER ]]; then
        echo "(intraline): $LINE"
        while IFS=$';' read -a SUBSTR; do
            echo "(substr): $SUBSTR"
        done <<< "$LINE"

    fi

done <<< "$TEST_STRING"

(echoes are added for debugging and as an empty operator). Then process lines with some functions and finally to assembly it back to the original string.

But for SUBSTR I get only first sub-string from every string (before semicolon). What I'm doing wrong?

Body:
Another way to split strings, using shell expansions and avoiding read which is slow :

tmp=$TEST_STRING

while [[ $tmp = *[\;$'\n']* ]]; do
    item=${tmp%%[;$'\n']*}   # to remove the largest suffix starting with ; or newline
    tmp=${tmp#*[;$'\n']}     # to remove the shortest prefix ending with ; or new line
    echo "[$item]"
done


问:
Git push rejected after pull
I've performed the following steps in git:

```<code>git stash
git pull origin develop
git stash apply
git commit -a -m 'da de da'
git push origin develop
<correct local date>
GIT_COMMITTER_DATE="`date`" git commit --amend --date "`date`"
git pull origin develop
git push origin develop
</code>```

All the pushes gave this error:

```<code> ! [rejected]        develop -> develop (non-fast-forward)
error: failed to push some refs to '<details>:/var/git/mygagenet'
To prevent you from losing history, non-fast-forward updates were rejected
</code>```

How do I correct this problem?

答:
This part of the error message:

To prevent you from losing history, non-fast-forward updates were rejected

tells you why the push was rejected - it doesn't just add new commits on top of the existing ones (which Git calls a "fast-forward update"), but it changes commits you've already pushed. In this case, the git commit --amend on your most recent commit has changed that commit.

You can force the push to happen by using

```<code>git push --force origin develop
</code>```

But if this is a remote branch that other people are using, check with them before you use git push --force on the branch, as they may have already done work on this branch with the existing commits.

Title: Git push rejected after pull

Body:
I've performed the following steps in git:

git stash
git pull origin develop
git stash apply
git commit -a -m 'da de da'
git push origin develop
<correct local date>
GIT_COMMITTER_DATE="`date`" git commit --amend --date "`date`"
git pull origin develop
git push origin develop

All the pushes gave this error:

 ! [rejected]        develop -> develop (non-fast-forward)
error: failed to push some refs to ':/var/git/mygagenet'
To prevent you from losing history, non-fast-forward updates were rejected

How do I correct this problem?

Body:
This part of the error message:

To prevent you from losing history, non-fast-forward updates were rejected

tells you why the push was rejected - it doesn't just add new commits on top of the existing ones (which Git calls a "fast-forward update"), but it changes commits you've already pushed. In this case, the git commit --amend on your most recent commit has changed that commit.

You can force the push to happen by using

git push --force origin develop

But if this is a remote branch that other people are using, check with them before you use git push --force on the branch, as they may have already done work on this branch with the existing commits.


问:
Sahi scripting wait or time delay
I was wondering if someone could help me. I want to introduce a 10 minute wait or time delay within my sahi script.

Can someone confirm the correct command to use?

Thanks in advance

答:
Write _wait(parameter); where parameter is your the time in milli-seconds you want to introduce the delay for.

In your case try _wait(600000);

You can also use the setSpeed(parameter); API , in this case Sahi will wait for the time specified in milli-seconds as a parameter , after each task in the script. But I guess waiting 10 mins after each task is not your requirement.

Title: Sahi scripting wait or time delay


问:
Best way handle result from thread on UI
I want to save data to DB in new Thread and after that show toast on the UI.

Method for saving:

```<code>public void addToBasket(String text) {

        new Thread(() -> {

                //emulate save
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
              //after that I need say ti UI thread - show Toast!
        }).start();
    }
</code>```

I call this method:

```<code>BasketService.me().addToBasket(result.getContents());
</code>```

I do now want use AsyncTask for this. Please tell me the best way to implement such tasks

答:
In case of callback from a nonUi thread to Ui thread you can use runOnUiThread()(As specified above) or Handler. Below is a example of using handler.</p>

```<code> protected static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

protected void onSuccessInMainThread(final R result, final Bundle bundle) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            callback.onSuccess(result, bundle);
        }
    });
}

protected void onErrorInMainThread(final Exception error) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            callback.onError(error);
        }
    });
}
</code>```

Body:
I want to save data to DB in new Thread and after that show toast on the UI.

Method for saving:

public void addToBasket(String text) {

        new Thread(() -> {

                //emulate save
                try {
                    Thread.sleep(5000L);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
              //after that I need say ti UI thread - show Toast!
        }).start();
    }

I call this method:

BasketService.me().addToBasket(result.getContents());

I do now want use AsyncTask for this. Please tell me the best way to implement such tasks

Body:
In case of callback from a nonUi thread to Ui thread you can use runOnUiThread()(As specified above) or Handler. Below is a example of using handler.

 protected static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());

protected void onSuccessInMainThread(final R result, final Bundle bundle) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            callback.onSuccess(result, bundle);
        }
    });
}

protected void onErrorInMainThread(final Exception error) {
    mainThreadHandler.post(new Runnable() {
        @Override
        public void run() {
            callback.onError(error);
        }
    });
}


问:
How to get hours and minutes selector in jQuery DateTimePicker control
I have downloaded and tried the jQuery DatetimePicker control from http://plugins.jquery.com/datetimepicker/. This is v2.3.7.

And in the download there is an image attached here which shows the selectors on both hours and minutes. But I haven't been able to find anything in the documentation on how to achieve that. Could someone please point out how to achieve this?

```<code> $('#' + subgridid_complete).datetimepicker({
                   format: 'mm/dd/yy H:i',//'d.m.Y H:i',
                   //inline: true
                   mask:true,
               });
</code>```

This is what I get using the code above. Notice that the Hour and minute are not independently selectable.

Many thanks

答:
If you want 15 minute intervals try: </p>

```<code>step: 15,
</code>```

Body:
I have downloaded and tried the jQuery DatetimePicker control from http://plugins.jquery.com/datetimepicker/. This is v2.3.7.

And in the download there is an image attached here which shows the selectors on both hours and minutes. But I haven't been able to find anything in the documentation on how to achieve that. Could someone please point out how to achieve this?

 $('#' + subgridid_complete).datetimepicker({
                   format: 'mm/dd/yy H:i',//'d.m.Y H:i',
                   //inline: true
                   mask:true,
               });

This is what I get using the code above. Notice that the Hour and minute are not independently selectable.

Many thanks

Body:
If you want 15 minute intervals try:

step: 15,


问:
HTML Table with curved linked heading

I'm trying to achieve this type of table so that I can have extended labels for columns. But I don't even know what it's called to try and describe it in a search.

Edit
I can find how to round html borders with CSS. But that doesn't help with linking rows to columns. I can rotate the column header text, but again, that isn't what I'm after.

The closest thing I can come up with is a full table with borders or a background colour to highlight the connection, but this would be squared instead of rounded.

I'm wondering if there is a method of achieving this with css. Or alternatively a library which would do the same thing.

答:
This is a close mockup to what you were looking for

https://codepen.io/anon/pen/dZrXPd

I wrote part of it in SCSS because it's easier for me, and the snippet here is a compiled version of it...

ul {
  list-style: none;
  padding: 0;
  width: 400px;
  float: left;
}
ul li:nth-child(1) {
  background-color: blue;
}
ul li:nth-child(2) {
  background-color: green;
}
ul li:nth-child(3) {
  background-color: red;
}

.clearfix:after {
  display: block;
  content: "";
  clear: both;
}

.round-edges {
  float: left;
  width: 80px;
  background-color: grey;
  height: 70px;
  margin-top: 15px;
  border-radius: 0 50px 0 0;
  position: relative;
}
.round-edges .round1 {
  background-color: blue;
  height: 70px;
  width: 75px;
  border-radius: 0 50px 0 0;
}
.round-edges .round2 {
  background-color: green;
  height: 50px;
  width: 50px;
  position: absolute;
  bottom: 0;
  left: 0;
  border-radius: 0 25px 0 0;
}
.round-edges .round3 {
  background-color: red;
  height: 33px;
  width: 25px;
  position: absolute;
  bottom: 0;
  left: 0;
  border-radius: 0 20px 0 0;
}

tr td:nth-child(1) {
  width: 400px;
}

tr td:nth-child(2) {
  background-color: red;
  width: 20px;
  text-align: center;
}

tr td:nth-child(3) {
  background-color: green;
  width: 20px;
  text-align: center;
}

tr td:nth-child(4) {
  background-color: blue;
  width: 20px;
  text-align: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="clearfix">
  <ul>
    <li>
      Last Col
    </li>
    <li>
      Middle Col
    </li>
    <li>
      First col
    </li>
  </ul>
  <div class="round-edges">
    <div class="round1"></div>
    <div class="round2"></div>
    <div class="round3"></div>
  </div>
</div>
<table>
  <tr>
    <td>
      Something
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
  <tr>
    <td>
      Some other thing
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
  <tr>
    <td>
      Something Completely Different
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
  <tr>
    <td>
      Foo
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
</table></code>```

Title: HTML Table with curved linked heading

Body:
This is a close mockup to what you were looking for

https://codepen.io/anon/pen/dZrXPd

I wrote part of it in SCSS because it's easier for me, and the snippet here is a compiled version of it...

ul {
  list-style: none;
  padding: 0;
  width: 400px;
  float: left;
}
ul li:nth-child(1) {
  background-color: blue;
}
ul li:nth-child(2) {
  background-color: green;
}
ul li:nth-child(3) {
  background-color: red;
}

.clearfix:after {
  display: block;
  content: "";
  clear: both;
}

.round-edges {
  float: left;
  width: 80px;
  background-color: grey;
  height: 70px;
  margin-top: 15px;
  border-radius: 0 50px 0 0;
  position: relative;
}
.round-edges .round1 {
  background-color: blue;
  height: 70px;
  width: 75px;
  border-radius: 0 50px 0 0;
}
.round-edges .round2 {
  background-color: green;
  height: 50px;
  width: 50px;
  position: absolute;
  bottom: 0;
  left: 0;
  border-radius: 0 25px 0 0;
}
.round-edges .round3 {
  background-color: red;
  height: 33px;
  width: 25px;
  position: absolute;
  bottom: 0;
  left: 0;
  border-radius: 0 20px 0 0;
}

tr td:nth-child(1) {
  width: 400px;
}

tr td:nth-child(2) {
  background-color: red;
  width: 20px;
  text-align: center;
}

tr td:nth-child(3) {
  background-color: green;
  width: 20px;
  text-align: center;
}

tr td:nth-child(4) {
  background-color: blue;
  width: 20px;
  text-align: center;
}

<div class="clearfix">
  <ul>
    <li>
      Last Col
    </li>
    <li>
      Middle Col
    </li>
    <li>
      First col
    </li>
  </ul>
  <div class="round-edges">
    <div class="round1"></div>
    <div class="round2"></div>
    <div class="round3"></div>
  </div>
</div>
<table>
  <tr>
    <td>
      Something
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
  <tr>
    <td>
      Some other thing
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
  <tr>
    <td>
      Something Completely Different
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
  <tr>
    <td>
      Foo
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
    <td>
      X
    </td>
  </tr>
</table>


问:
FFmpeg: unspecified pixel format when opening video with custom context
I am trying to decode a video with a custom context. The purpose is that I want to decode the video directly from memory. In the following code, I am reading from file in the read function passed to avio_alloc_context - but this is just for testing purposes.

I think I've read any post there is on Stackoverflow or on any other website related to this topic. At least I definitely tried my best to do so. While there is much in common, the details differ: people set different flags, some say av_probe_input_format is required, some say it isn't, etc. And for some reason nothing works for me.

My problem is that the pixel format is unspecified (see output below), which is why I run into problems later when calling sws_getContext. I checked pFormatContext->streams[videoStreamIndex]->codec->pix_fmt, and it is -1.

Please note my comments // things I tried and // seems not to help in the code. I think, the answer might be hidden somehwere there. I tried many combinations of hints that I've read so far, but I am missing a detail I guess.

The problem is not the video file, because when I go the standard way and just call avformat_open_input(&pFormatContext, pFilePath, NULL, NULL) without a custom context, everything runs fine.

The code compiles and runs as is.

```<code>#include <libavformat/avformat.h>
#include <string.h>
#include <stdio.h>

FILE *f;

static int read(void *opaque, uint8_t *buf, int buf_size) {
    if (feof(f)) return -1;
    return fread(buf, 1, buf_size, f);
}

int openVideo(const char *pFilePath) {
    const int bufferSize = 32768;
    int ret;

    av_register_all();

    f = fopen(pFilePath, "rb");
    uint8_t *pBuffer = (uint8_t *) av_malloc(bufferSize + AVPROBE_PADDING_SIZE);
    AVIOContext *pAVIOContext = avio_alloc_context(pBuffer, bufferSize, 0, NULL,
                      &read, NULL, NULL);

    if (!f || !pBuffer || !pAVIOContext) {
        printf("error: open / alloc failed\n");
        // cleanup...
        return 1;
    }

    AVFormatContext *pFormatContext = avformat_alloc_context();
    pFormatContext->pb = pAVIOContext;

    const int readBytes = read(NULL, pBuffer, bufferSize);

    printf("readBytes = %i\n", readBytes);

    if (readBytes <= 0) {
        printf("error: read failed\n");
        // cleanup...
        return 2;
    }

    if (fseek(f, 0, SEEK_SET) != 0) {
        printf("error: fseek failed\n");
        // cleanup...
        return 3;
    }

    // required for av_probe_input_format
    memset(pBuffer + readBytes, 0, AVPROBE_PADDING_SIZE);

    AVProbeData probeData;
    probeData.buf = pBuffer;
    probeData.buf_size = readBytes;
    probeData.filename = "";
    probeData.mime_type = NULL;

    pFormatContext->iformat = av_probe_input_format(&probeData, 1);

    // things I tried:
    //pFormatContext->flags = AVFMT_FLAG_CUSTOM_IO;
    //pFormatContext->iformat->flags |= AVFMT_NOFILE;
    //pFormatContext->iformat->read_header = NULL;

    // seems not to help (therefore commented out here):
    AVDictionary *pDictionary = NULL;
    //av_dict_set(&pDictionary, "analyzeduration", "8000000", 0);
    //av_dict_set(&pDictionary, "probesize", "8000000", 0);

    if ((ret = avformat_open_input(&pFormatContext, "", NULL, &pDictionary)) < 0) {
        char buffer[4096];
        av_strerror(ret, buffer, sizeof(buffer));
        printf("error: avformat_open_input failed: %s\n", buffer);
        // cleanup...
        return 4;
    }

    printf("retrieving stream information...\n");

    if ((ret = avformat_find_stream_info(pFormatContext, NULL)) < 0) {
        char buffer[4096];
        av_strerror(ret, buffer, sizeof(buffer));
        printf("error: avformat_find_stream_info failed: %s\n", buffer);
        // cleanup...
        return 5;
    }

    printf("nb_streams = %i\n", pFormatContext->nb_streams);

    // further code...

    // cleanup...
    return 0;
}

int main() {
    openVideo("video.mp4");
    return 0;
}
</code>```

This is the output that I get:

readBytes = 32768

retrieving stream information...

[mov,mp4,m4a,3gp,3g2,mj2 @ 0xdf8d20] stream 0, offset 0x30: partial file
[mov,mp4,m4a,3gp,3g2,mj2 @ 0xdf8d20] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none, 640x360, 351 kb/s): unspecified pixel format

Consider increasing the value for the 'analyzeduration' and 'probesize' options

nb_streams = 2

UPDATE:

Thanks to WLGfx, here is the solution: The only thing that was missing was the seek function. Apparently, implementing it is mandatory for decoding. It is important to return the new offset - and not 0 in case of success (some solutions found in the web just return the return value of fseek, and that is wrong). Here is the minimal solution that made it work:

```<code>static int64_t seek(void *opaque, int64_t offset, int whence) {
    if (whence == SEEK_SET && fseek(f, offset, SEEK_SET) == 0) {
        return offset;
    }
    // handling AVSEEK_SIZE doesn't seem mandatory
    return -1;
}
</code>```

Of course, the call to avio_alloc_context needs to be adapted accordingly:

```<code>AVIOContext *pAVIOContext = avio_alloc_context(pBuffer, bufferSize, 0, NULL,
                      &read, NULL, &seek);
</code>```

答:
Seeing as yours is a file based stream then it is seekable so you can provide the AVIO seek when creating the AVIOContext:

```<code>avioContext = avio_alloc_context((uint8_t *)avio_buffer, AVIO_QUEUE_SIZE * PKT_SIZE7,
    0,
    this, // *** This is your data pointer to a class or other data passed to the callbacks
    avio_ReadFunc,
    NULL,
    avio_SeekFunc);
</code>```

Handle the seeking with this callback: (You can cast ptr to your class or other data structure)

```<code>int64_t FFIOBufferManager::avio_SeekFunc(void *ptr, int64_t pos64, int whence) {
    // SEEK_SET(0), SEEK_CUR(1), SEEK_END(2), AVSEEK_SIZE
    // ptr is cast to your data or class

    switch (whence) {
    case 0 : // SEEK_SET
    ... etc
    case (AVSEEK_SIZE) : // get size
        return -1; // if you're unable to get the size
        break;
    }

    // set new position in the file

    return (int64_t)new_pos; // new position
}
</code>```

You can also define the codec and the probesize when attaching the AVIOContext to the AVFormatContext. This allows ffmpeg to seek in the stream to better determine the format.

```<code>context->pb = ffio->avioContext;
context->flags = AVFMT_FLAG_CUSTOM_IO;
context->iformat = av_find_input_format("mpegts"); // not necessary
context->probesize = 1200000;
</code>```

So far I haven't had the need for av_probe_input_format, but then again my streams are mpegts.

Hope this helps.

EDIT: Added a comment to the avio_alloc_context function to mention how the ptr is used in the callbacks.

Body:
I am trying to decode a video with a custom context. The purpose is that I want to decode the video directly from memory. In the following code, I am reading from file in the read function passed to avio_alloc_context - but this is just for testing purposes.

I think I've read any post there is on Stackoverflow or on any other website related to this topic. At least I definitely tried my best to do so. While there is much in common, the details differ: people set different flags, some say av_probe_input_format is required, some say it isn't, etc. And for some reason nothing works for me.

My problem is that the pixel format is unspecified (see output below), which is why I run into problems later when calling sws_getContext. I checked pFormatContext->streams[videoStreamIndex]->codec->pix_fmt, and it is -1.

Please note my comments // things I tried and // seems not to help in the code. I think, the answer might be hidden somehwere there. I tried many combinations of hints that I've read so far, but I am missing a detail I guess.

The problem is not the video file, because when I go the standard way and just call avformat_open_input(&pFormatContext, pFilePath, NULL, NULL) without a custom context, everything runs fine.

The code compiles and runs as is.

#include <libavformat/avformat.h>
#include <string.h>
#include <stdio.h>

FILE *f;

static int read(void *opaque, uint8_t *buf, int buf_size) {
    if (feof(f)) return -1;
    return fread(buf, 1, buf_size, f);
}

int openVideo(const char *pFilePath) {
    const int bufferSize = 32768;
    int ret;

    av_register_all();

    f = fopen(pFilePath, "rb");
    uint8_t *pBuffer = (uint8_t *) av_malloc(bufferSize + AVPROBE_PADDING_SIZE);
    AVIOContext *pAVIOContext = avio_alloc_context(pBuffer, bufferSize, 0, NULL,
                      &read, NULL, NULL);

    if (!f || !pBuffer || !pAVIOContext) {
        printf("error: open / alloc failed\n");
        // cleanup...
        return 1;
    }

    AVFormatContext *pFormatContext = avformat_alloc_context();
    pFormatContext->pb = pAVIOContext;

    const int readBytes = read(NULL, pBuffer, bufferSize);

    printf("readBytes = %i\n", readBytes);

    if (readBytes <= 0) {
        printf("error: read failed\n");
        // cleanup...
        return 2;
    }

    if (fseek(f, 0, SEEK_SET) != 0) {
        printf("error: fseek failed\n");
        // cleanup...
        return 3;
    }

    // required for av_probe_input_format
    memset(pBuffer + readBytes, 0, AVPROBE_PADDING_SIZE);

    AVProbeData probeData;
    probeData.buf = pBuffer;
    probeData.buf_size = readBytes;
    probeData.filename = "";
    probeData.mime_type = NULL;

    pFormatContext->iformat = av_probe_input_format(&probeData, 1);

    // things I tried:
    //pFormatContext->flags = AVFMT_FLAG_CUSTOM_IO;
    //pFormatContext->iformat->flags |= AVFMT_NOFILE;
    //pFormatContext->iformat->read_header = NULL;

    // seems not to help (therefore commented out here):
    AVDictionary *pDictionary = NULL;
    //av_dict_set(&pDictionary, "analyzeduration", "8000000", 0);
    //av_dict_set(&pDictionary, "probesize", "8000000", 0);

    if ((ret = avformat_open_input(&pFormatContext, "", NULL, &pDictionary)) < 0) {
        char buffer[4096];
        av_strerror(ret, buffer, sizeof(buffer));
        printf("error: avformat_open_input failed: %s\n", buffer);
        // cleanup...
        return 4;
    }

    printf("retrieving stream information...\n");

    if ((ret = avformat_find_stream_info(pFormatContext, NULL)) < 0) {
        char buffer[4096];
        av_strerror(ret, buffer, sizeof(buffer));
        printf("error: avformat_find_stream_info failed: %s\n", buffer);
        // cleanup...
        return 5;
    }

    printf("nb_streams = %i\n", pFormatContext->nb_streams);

    // further code...

    // cleanup...
    return 0;
}

int main() {
    openVideo("video.mp4");
    return 0;
}

This is the output that I get:

readBytes = 32768

retrieving stream information...

[mov,mp4,m4a,3gp,3g2,mj2 @ 0xdf8d20] stream 0, offset 0x30: partial file
[mov,mp4,m4a,3gp,3g2,mj2 @ 0xdf8d20] Could not find codec parameters for stream 0 (Video: h264 (avc1 / 0x31637661), none, 640x360, 351 kb/s): unspecified pixel format

Consider increasing the value for the 'analyzeduration' and 'probesize' options

nb_streams = 2

UPDATE:

Thanks to WLGfx, here is the solution: The only thing that was missing was the seek function. Apparently, implementing it is mandatory for decoding. It is important to return the new offset - and not 0 in case of success (some solutions found in the web just return the return value of fseek, and that is wrong). Here is the minimal solution that made it work:

static int64_t seek(void *opaque, int64_t offset, int whence) {
    if (whence == SEEK_SET && fseek(f, offset, SEEK_SET) == 0) {
        return offset;
    }
    // handling AVSEEK_SIZE doesn't seem mandatory
    return -1;
}

Of course, the call to avio_alloc_context needs to be adapted accordingly:

AVIOContext *pAVIOContext = avio_alloc_context(pBuffer, bufferSize, 0, NULL,
                      &read, NULL, &seek);

Body:
Seeing as yours is a file based stream then it is seekable so you can provide the AVIO seek when creating the AVIOContext:

avioContext = avio_alloc_context((uint8_t *)avio_buffer, AVIO_QUEUE_SIZE * PKT_SIZE7,
    0,
    this, // *** This is your data pointer to a class or other data passed to the callbacks
    avio_ReadFunc,
    NULL,
    avio_SeekFunc);

Handle the seeking with this callback: (You can cast ptr to your class or other data structure)

int64_t FFIOBufferManager::avio_SeekFunc(void *ptr, int64_t pos64, int whence) {
    // SEEK_SET(0), SEEK_CUR(1), SEEK_END(2), AVSEEK_SIZE
    // ptr is cast to your data or class

    switch (whence) {
    case 0 : // SEEK_SET
    ... etc
    case (AVSEEK_SIZE) : // get size
        return -1; // if you're unable to get the size
        break;
    }

    // set new position in the file

    return (int64_t)new_pos; // new position
}

You can also define the codec and the probesize when attaching the AVIOContext to the AVFormatContext. This allows ffmpeg to seek in the stream to better determine the format.

context->pb = ffio->avioContext;
context->flags = AVFMT_FLAG_CUSTOM_IO;
context->iformat = av_find_input_format("mpegts"); // not necessary
context->probesize = 1200000;

So far I haven't had the need for av_probe_input_format, but then again my streams are mpegts.

Hope this helps.

EDIT: Added a comment to the avio_alloc_context function to mention how the ptr is used in the callbacks.


问:
Using hidden frame to store or pass data between pages
We need to implement a mechanism to persist information between web pages in the same session. There is a lot of information on the client-side and passing it back and forth to the server across requests is something we want to avoid. HTML5 local storage is one option.

The other option mentioned was "using a hidden frame where the data is kept".  I am not sure what this option really means.

Does it mean keeping a hidden frame that holds on to the data across page requests?

How would this be accomplished? Are there any jquery plugins or sample code I can look at?

What are the advantages and disadvantages?

答:
You can't keep a frame from one page to another, so the only way to use that is to make the frame cover the window and load the actual pages in the frame. That way you can keep the data in the surrounding page that won't be replaced.

This of course means that you actually never leave the page. The URL in the location bar remains the same when the content changes, so you can't bookmark a specific page or share it with others. Search engines will link to the content pages instead of the frame, so anyone finding your page that way will end up on a non-functioning frame page.


问:
add two different queries result into one table
I have two different query (having same no. of columns in result).
I want to put both in one table.

for example i have following table:

```<code>id     country     salary
1        us        10000

2        uk        25000

3        us        35000

4        uk        31000

5        uk        26000
</code>```

now I have following queries:

Query 1 :

```<code>select * from table where country='us';
</code>```

and

Query 2 :

```<code>select * from table where country='uk';
</code>```

i have one final table having six columns like:

```<code> id1   |country1  |  salary 1 |  id2  |  country2 |  salary2
</code>```

Now, i want to put both queries result in this table so following output should be shown:

Desired Output:

```<code>id1   |country1  |  salary 1  |  id2   |  country2 |  salary2
 1    |     us   |   10000    |    2   |      uk   |   25000

 3    |     us   |   35000    |    4   |      uk   |   31000

null  |   null   |   null     |    5   |      uk   |   26000
</code>```

I have tried this but it doesn't combine the result:

```<code>insert into table (id1,country1,salary1)
select id,country,salary
from table1
where country='us';
</code>```

and

```<code>insert into table (id2,country2,salary2)
select id,country,salary
from table1
where country='uk';
</code>```

but it gives following result:

```<code>id1   |country1    |  salary 1  |  id2      |  country2   |  salary2
 1    |     us     |     10000  |     null  |     null    |     null

3     |    us      |    35000   |    null   |    null     |    null

null  |   null     |   null     |   2       |    uk       |    25000

null  |   null     |   null     |   4       |    uk       |    31000

null  |   null     |   null     |   5       |    uk       |    26000
</code>```

Please help me out:

答:
If your DBMS support window functions, you may use them to join your intermediate result appropriately.

```<code>select t1.id, t1.country, t1.salary, t2.id, t2.country, t2.salary
from
(
  select *, row_number() over (order by id) rn
  from data
  where country = 'us'
) t1
full join
(
  select *, row_number() over (order by id) rn
  from data
  where country = 'uk'
) t2 on t1.rn = t2.rn
</code>```

demo

RESULT

```<code>id      country salary  id  country salary
-------------------------------------------
1       us      10000   2   uk      25000
3       us      35000   4   uk      31000
null    null    null    5   uk      26000
</code>```

Body:
I have two different query (having same no. of columns in result).
I want to put both in one table.

for example i have following table:

id     country     salary
1        us        10000

2        uk        25000

3        us        35000

4        uk        31000

5        uk        26000

now I have following queries:

Query 1 :

select * from table where country='us';

and

Query 2 :

select * from table where country='uk';

i have one final table having six columns like:

 id1   |country1  |  salary 1 |  id2  |  country2 |  salary2

Now, i want to put both queries result in this table so following output should be shown:

Desired Output:

id1   |country1  |  salary 1  |  id2   |  country2 |  salary2
 1    |     us   |   10000    |    2   |      uk   |   25000

 3    |     us   |   35000    |    4   |      uk   |   31000

null  |   null   |   null     |    5   |      uk   |   26000

I have tried this but it doesn't combine the result:

insert into table (id1,country1,salary1)
select id,country,salary
from table1
where country='us';

and

insert into table (id2,country2,salary2)
select id,country,salary
from table1
where country='uk';

but it gives following result:

id1   |country1    |  salary 1  |  id2      |  country2   |  salary2
 1    |     us     |     10000  |     null  |     null    |     null

3     |    us      |    35000   |    null   |    null     |    null

null  |   null     |   null     |   2       |    uk       |    25000

null  |   null     |   null     |   4       |    uk       |    31000

null  |   null     |   null     |   5       |    uk       |    26000

Please help me out:

Body:
If your DBMS support window functions, you may use them to join your intermediate result appropriately.

select t1.id, t1.country, t1.salary, t2.id, t2.country, t2.salary
from
(
  select *, row_number() over (order by id) rn
  from data
  where country = 'us'
) t1
full join
(
  select *, row_number() over (order by id) rn
  from data
  where country = 'uk'
) t2 on t1.rn = t2.rn

demo

RESULT

id      country salary  id  country salary
-------------------------------------------
1       us      10000   2   uk      25000
3       us      35000   4   uk      31000
null    null    null    5   uk      26000


问:
toggle pseudo class :active with css/jquery
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

```<code>(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);
</code>```

And the HTML around the Elements we are looking for

```<code><div class="helpmark">
    <img class="emoticon" src="http://*********/plugins/cute/static/resource/SD-CGM-TT/help_16.gif"> </div>
<div class="description">
    <p>Hier können Sie einen kurzen Betreff einfügen</p>
</div>
</code>```

by clicking on .helpmark .description is displayed

And the CSS i have

```<code>.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}
</code>```

I hope anybody can help me.

Best regards,
Stephan

答:
You can use .toggleClass() to add/remove an active class on your .helpmark element, and then add some CSS to show/hide the sibling based on that class, like so:

CSS:

```<code>.helpmark.active + .description {
  display: inline-block;
}
.description {
  display: none;
}
</code>```

jQuery:

```<code>// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');

  // Add this part to your script:
  banner.on('click',function() {
    $(this).toggleClass('active');
  });

}
}, 1)
})(jQuery);
</code>```

Here's a Codepen example

Body:
i have a little css problem.
There is a div which is only display an image of an help mark. What i try is on clicking on this image the next div on the same level is display:inline-block. On a second click it is display:none again.

The display:inline-block on :active is working but it is not toggle.

There is JQuery:

(function($) {

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('
'
+ ''
+ ' @message'
+   '
');
banner.insertBefore('div.description');
}
}, 1)
})(jQuery);

And the HTML around the Elements we are looking for

Hier können Sie einen kurzen Betreff einfügen

by clicking on .helpmark .description is displayed

And the CSS i have

.helpmark {
    cursor: pointer;
    display: inline-block;
    margin-top: 5px;
}

.helpmark:active + .description {
    display: inline-block;
}

.description {
    display: none;
}

I hope anybody can help me.

Best regards,
Stephan

Body:
You can use .toggleClass() to add/remove an active class on your .helpmark element, and then add some CSS to show/hide the sibling based on that class, like so:

CSS:

.helpmark.active + .description {
  display: inline-block;
}
.description {
  display: none;
}

jQuery:

// Execute after the page was fully
setTimeout( function(){
if ($('#jsonPayload').length) {
// scope to JSD
var banner = jQuery('<div class="helpmark">'
+ '<img class="emoticon" align="adsmiddle" src="@contextPath/plugins/cute/static/resource/SD-CGM-TT/help_16.gif" />'
+ ' @message'
+   '</div>');
banner.insertBefore('div.description');

  // Add this part to your script:
  banner.on('click',function() {
    $(this).toggleClass('active');
  });

}
}, 1)
})(jQuery);

Here's a Codepen example


问:
What is the difference between Python's list methods append and extend?
What's the difference between the list methods append() and extend()?

答:
To distinguish them intuitively

```<code>l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l1.append(l2)
l1
['a', 'b', 'c', ['d', 'e', 'f']]
</code>```

It's like l1 reproduce a body inside her body(nested).

```<code># Reset l1 = ['a', 'b', 'c']
l1.extend(l2)
l1
['a', 'b', 'c', 'd', 'e', 'f']
</code>```

It's like that two separated individuals get married and construct an united family.

Besides I make an exhaustive cheatsheet of all list's methods for your reference.

```<code>list_methods = {'Add': {'extend', 'append', 'insert'},
                'Remove': {'pop', 'remove', 'clear'}
                'Sort': {'reverse', 'sort'},
                'Search': {'count', 'index'},
                'Copy': {'copy'},
                }
</code>```

OwnerDisplayName: Claudiu

ContentLicense: CC BY-SA 4.0

Body:
To distinguish them intuitively

l1 = ['a', 'b', 'c']
l2 = ['d', 'e', 'f']
l1.append(l2)
l1
['a', 'b', 'c', ['d', 'e', 'f']]

It's like l1 reproduce a body inside her body(nested).

# Reset l1 = ['a', 'b', 'c']
l1.extend(l2)
l1
['a', 'b', 'c', 'd', 'e', 'f']

It's like that two separated individuals get married and construct an united family.

Besides I make an exhaustive cheatsheet of all list's methods for your reference.

list_methods = {'Add': {'extend', 'append', 'insert'},
                'Remove': {'pop', 'remove', 'clear'}
                'Sort': {'reverse', 'sort'},
                'Search': {'count', 'index'},
                'Copy': {'copy'},
                }


问:
how to intentionally not have same/equal heights with flex-wrap?
Title says it all,
My list is supposed to be 2 columns because of the display flex and 50% width, but if one side is longer the other side will have a gap and that's what I'm trying to remove.

ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  margin: 0;
}
li {
  display: block;
  width: 50%;
  margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Some Text Here</li>
  <li>Some Text Here Some Text Here Some Text Here</li>
  <li>Some Text Here</li>
  <li>Some Text Here</li>
  <li>Some Text Here</li>
</ul></code>```

答:
You will not be able to do it using flex like this, as they will all have same height by default (you may add border and you will see).

Instead you may consider using column like this :

* {
  box-sizing: border-box;
}

ul {
  column-count: 2;
  list-style: none;
  margin: 0;
}

li {
  display: block;
  margin-bottom: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><ul>
  <li>Some Text Here</li>
  <li>Some Text Here</li>
  <li>Some Text Here</li>
  <li>Some Text Here Some Text Here Some Text Here</li>
  <li>Some Text Here</li>
</ul></code>```

Body:
Title says it all,
My list is supposed to be 2 columns because of the display flex and 50% width, but if one side is longer the other side will have a gap and that's what I'm trying to remove.

ul {
  display: flex;
  flex-wrap: wrap;
  list-style: none;
  margin: 0;
}
li {
  display: block;
  width: 50%;
  margin-bottom: 5px;
}

Some Text Here

Some Text Here Some Text Here Some Text Here

Some Text Here

Some Text Here

Some Text Here

Body:
You will not be able to do it using flex like this, as they will all have same height by default (you may add border and you will see).

Instead you may consider using column like this :

* {
  box-sizing: border-box;
}

ul {
  column-count: 2;
  list-style: none;
  margin: 0;
}

li {
  display: block;
  margin-bottom: 5px;
}

<ul>
  <li>Some Text Here</li>
  <li>Some Text Here</li>
  <li>Some Text Here</li>
  <li>Some Text Here Some Text Here Some Text Here</li>
  <li>Some Text Here</li>
</ul>