问:
How to add more than one information to the same ID?
I am creating a code that works with database, and would like to know how to add more than one information to the same ID.

It is for a student's note control code.

```<code>def add_series(self):
        conn = sqlite3.connect('obje_bd.db')
        cursor = conn.cursor()
        id_ = self.ids.txt_id.text.encode('utf-8')
        series = self.ids.txt_series_professor.text.encode('utf-8')
        # alterando os dados da tabela
        cursor.execute("""
              # would like to put all series in the same ID.
              INSERT INTO lista_professores WHERE id = ?, series = ?""")

        conn.commit()
        conn.close()
</code>```

答:
Typically you wouldn't directly, that is if the "more information" is a variable amount of information per id.

For example assume that a Student (the assumption is that a student's row has an id) has x number of notes.

You would not have x columns (as you would forever be adding new columns).

It would prove clumsy to place all the notes into single column with a separator e.g something like 'Hello this is my first note','Thankyou this is my second note' and so on.

e.g. if a comma separates data how do you cope with commas in the notes.

how do you split the data, say to find note 3?

What you would typically do is normalise the data and have a table for the notes, each note being an individual row. There would be a column in the notes table that relates the note to the respective student.
- SQLite is a relational database and handles relationships pretty well.

Example

Consider the following, where instead of a Student having x number of data (notes) in the Student table another table for the notes exists and each note contains a column for relating the note to the student :-

```<code>DROP TABLE IF EXISTS Student;
DROP TABLE IF EXISTS Note;
CREATE TABLE IF NOT EXISTS Student (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE IF NOT EXISTS Note(id INTEGER PRIMARY KEY, studentReference INTEGER, note TEXT);

INSERT INTO Student (name) VALUES ('Fred'),('Mary'),('Anne'); -- ids will be 1 2 and 3

INSERT INTO Note (studentReference,note) VALUES
    (1,'My Note 1'),
    (3,'My Note 1'),
    (3,'My Note 2'),
    (2,'My Note 1'),
    (3,'My Note 3'),
    (2,'My Note 2'),
    (2,'My Note 3'),
    (1,'My Note 2'),
    (1,'My Note 3'),
    (1,'My Note 4'),
    (1,'My Note 5'),
    (3,'My Note 4');

    SELECT * FROM Student; -- The Student table
    SELECT * FROM Note; -- The Note table
    -- Get the Notes with the Student (both have the same result)
    SELECT name, note FROM Note JOIN Student ON Student.id = Note.studentReference ORDER BY Student.name;
    SELECT name, note FROM Student JOIN  Note ON Student.id = Note.studentReference ORDER BY Student.name;
    -- Get the number of notes and all the notes concatenated as a CSV per student
    SELECT student.name,count(), group_concat(note) FROM student JOIN Note ON Student.id = Note.studentReference GROUP BY student.id;
</code>```

Results

1 The Student Table

2 The Notes Table

3 and 4 Student and Notes

5 Number of notes and the notes as a CSV per student

Body:
I am creating a code that works with database, and would like to know how to add more than one information to the same ID.

It is for a student's note control code.

def add_series(self):
        conn = sqlite3.connect('obje_bd.db')
        cursor = conn.cursor()
        id_ = self.ids.txt_id.text.encode('utf-8')
        series = self.ids.txt_series_professor.text.encode('utf-8')
        # alterando os dados da tabela
        cursor.execute("""
              # would like to put all series in the same ID.
              INSERT INTO lista_professores WHERE id = ?, series = ?""")

        conn.commit()
        conn.close()

Body:
Typically you wouldn't directly, that is if the "more information" is a variable amount of information per id.

For example assume that a Student (the assumption is that a student's row has an id) has x number of notes.

You would not have x columns (as you would forever be adding new columns).

It would prove clumsy to place all the notes into single column with a separator e.g something like 'Hello this is my first note','Thankyou this is my second note' and so on.

e.g. if a comma separates data how do you cope with commas in the notes.

how do you split the data, say to find note 3?

What you would typically do is normalise the data and have a table for the notes, each note being an individual row. There would be a column in the notes table that relates the note to the respective student.
- SQLite is a relational database and handles relationships pretty well.

Example

Consider the following, where instead of a Student having x number of data (notes) in the Student table another table for the notes exists and each note contains a column for relating the note to the student :-

DROP TABLE IF EXISTS Student;
DROP TABLE IF EXISTS Note;
CREATE TABLE IF NOT EXISTS Student (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE IF NOT EXISTS Note(id INTEGER PRIMARY KEY, studentReference INTEGER, note TEXT);

INSERT INTO Student (name) VALUES ('Fred'),('Mary'),('Anne'); -- ids will be 1 2 and 3

INSERT INTO Note (studentReference,note) VALUES
    (1,'My Note 1'),
    (3,'My Note 1'),
    (3,'My Note 2'),
    (2,'My Note 1'),
    (3,'My Note 3'),
    (2,'My Note 2'),
    (2,'My Note 3'),
    (1,'My Note 2'),
    (1,'My Note 3'),
    (1,'My Note 4'),
    (1,'My Note 5'),
    (3,'My Note 4');

    SELECT * FROM Student; -- The Student table
    SELECT * FROM Note; -- The Note table
    -- Get the Notes with the Student (both have the same result)
    SELECT name, note FROM Note JOIN Student ON Student.id = Note.studentReference ORDER BY Student.name;
    SELECT name, note FROM Student JOIN  Note ON Student.id = Note.studentReference ORDER BY Student.name;
    -- Get the number of notes and all the notes concatenated as a CSV per student
    SELECT student.name,count(), group_concat(note) FROM student JOIN Note ON Student.id = Note.studentReference GROUP BY student.id;

Results

1 The Student Table

2 The Notes Table

3 and 4 Student and Notes

5 Number of notes and the notes as a CSV per student


来源: stackexchange

问:
Need to swap 2 lines
For each instance of the below code (have many) I need to swap the "userId" line with the "screen_name" line so "screen_name" line is above "userId" line.</p>

```<code>{
  active: true,
  userId: '14053424',
  screen_name: '0xstark',
  maxTopTweets: 2,
  minLikesCount: 2,
  keywordsToReject: [],
  keywords: [],
  useDefaultKeywords: true,
  useDefaultRejectKeywords: true,
  useStrictKeywords: false,
  defaultPhoto: null,
},
</code>```

答:
To flip the lines of user_id and screen name:

```<code>awk '/userId:/{uid=$0;next}/screen_name/{$0 = $0 RS uid}1' input
</code>```

This is storing the line containing  the string userId: into a variable uid and moving to next line , whenever it sees a string screen_name it will reconstruct that line like $0 = $0 RS uid where RS is used to get new line.

ContentLicense: CC BY-SA 4.0

Title: Need to swap 2 lines

Body:
For each instance of the below code (have many) I need to swap the "userId" line with the "screen_name" line so "screen_name" line is above "userId" line.

{
  active: true,
  userId: '14053424',
  screen_name: '0xstark',
  maxTopTweets: 2,
  minLikesCount: 2,
  keywordsToReject: [],
  keywords: [],
  useDefaultKeywords: true,
  useDefaultRejectKeywords: true,
  useStrictKeywords: false,
  defaultPhoto: null,
},

Body:
To flip the lines of user_id and screen name:

awk '/userId:/{uid=$0;next}/screen_name/{$0 = $0 RS uid}1' input

This is storing the line containing  the string userId: into a variable uid and moving to next line , whenever it sees a string screen_name it will reconstruct that line like $0 = $0 RS uid where RS is used to get new line.


问:
Problems with table border styling in Chrome (works in FF)
In a table with collapsed borders I need to give a special border style to some cells. In Chrome this does not work properly. (Without collapsed borders the result is as expected.)

```<code>table { border-collapse: collapse; }
td { border: 1px solid gray; }
</code>```

Strong border: https://jsfiddle.net/r8h7abnf/ Whole bottom border of cell above affeced.

```<code>td.red { border: 3px solid red; }
</code>```

No border: https://jsfiddle.net/yrm8sfLp/ Does not always work.

```<code>td.gap { border: 0; }
</code>```

Can I somehow adapt the styles to make it work in both browsers?

答:
Edit: fixed in Chrome 92 released in July 2021. Still broken in Safari in Dec 2022.

This is a very longstanding bug in Chrome: https://crbug.com/2902 :(

You can workaround it if you figure out a way to only use colspan == 1.

Note that FWIW, adding display:block to the td.redputs a border around a box that's inside an implicitly-added cell. You can see that the red border doesn't cover the grey border, but instead is inside it.

Body:
In a table with collapsed borders I need to give a special border style to some cells. In Chrome this does not work properly. (Without collapsed borders the result is as expected.)

table { border-collapse: collapse; }
td { border: 1px solid gray; }

Strong border: https://jsfiddle.net/r8h7abnf/ Whole bottom border of cell above affeced.

td.red { border: 3px solid red; }

No border: https://jsfiddle.net/yrm8sfLp/ Does not always work.

td.gap { border: 0; }

Can I somehow adapt the styles to make it work in both browsers?


问:
android app can't find string resource at runtime
I have packed my AndroidStudio project in ubuntu14.04 which can be deployed on my cell phone properly.But when I unpacked it and tried to build and debug it in the windows10 AndroidStudio enveriment,I got this runtime error found in log:

```<code>    2018-11-28 17:15:16.071 21275-21303/? W/ResourceType: Failure getting entry for 0x7f0d001f (t=12 e=31) (error -2147483647)
    2018-11-28 17:15:16.071 1697-1721/? I/zygote64: Successfully killed process cgroup uid 10177 pid 16739 in 8ms
    2018-11-28 17:15:16.071 21275-21303/? W/PackageManager: Failure retrieving text 0x7f0d001f in package graduationproject.usst.edu.facedetect
android.content.res.Resources$NotFoundException: String resource ID #0x7f0d001f
    at android.content.res.Resources.getText(Resources.java:380)
    at android.app.ApplicationPackageManager.getText(ApplicationPackageManager.java:1890)
    at android.content.pm.PackageItemInfo.loadLabel(PackageItemInfo.java:138)
    at com.nearme.statistics.rom.a.h.l.a(Utils.java:88)
    at com.nearme.statistics.rom.usermodel.a.c(BackgroundAppData.java:95)
    at com.nearme.statistics.rom.usermodel.a.a(BackgroundAppData.java:69)
    at com.nearme.statistics.rom.usermodel.a.a(BackgroundAppData.java:20)
    at com.nearme.statistics.rom.usermodel.BackgroundAppData$1$1.run(BackgroundAppData.java:48)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)
</code>```

And I didn't have any error message in the debug toolbar:

```<code>    Connected to the target VM, address: 'localhost:8600', transport: 'socket'
    Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'
</code>```

I have checked my R.java class and I found：

```<code>    public static final int app_name=0x7f0d001f;
</code>```

All where I used app_name is only in the AndroidManifest.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="graduationproject.usst.edu.facedetect">

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

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    <activity
            android:name=".menu"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

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

</manifest>
</code>```

I think I am quiet sure this is where the problem occurs because when i changed

```<code>android:label="@string/app_name"
</code>```

to

```<code>android:label="@string/another_name"
</code>```

Then the error message in the log became:

```<code>2018-11-28 17:15:16.071 21275-21303/? W/PackageManager: Failure retrieving text 0x7f0d001e in package graduationproject.usst.edu.facedetect
android.content.res.Resources$NotFoundException: String resource ID #0x7f0d001e
</code>```

with the following in the R.java class:

```<code>public static final int another_name=0x7f0d001e;
</code>```

The file "project\app\src\main\res\values\strings.xml" exists and the body in it is:

```<code><resources>
    <string name="app_name">facedetect</string>

    <string name="another_name">facedetectt</string>

    <string name="action_settings">Settings</string>
</resources>
</code>```

The AndroidStudio version is 3.2.1 and I'm using

```<code>JDK 1.8
Android SDK 27
NDK 18
Gradle 4.6
Gradle plugin:3.2.1
</code>```

I have tried rebuild,clean and I had even delete the Build folder to clean and rebuild thoroughly.

I don't know where the problems is. Can Anyone please kindly help me to solve this problem? Thanks!

答:
I had a similar issue; try disabling the "Instant Run" feature within Android Studio: Settings > Build, Execution, Deployment > Instant Run > uncheck Enable Instant Run.

Source: https://stackoverflow.com/a/54043188/1992342

Body:
I have packed my AndroidStudio project in ubuntu14.04 which can be deployed on my cell phone properly.But when I unpacked it and tried to build and debug it in the windows10 AndroidStudio enveriment,I got this runtime error found in log:

    2018-11-28 17:15:16.071 21275-21303/? W/ResourceType: Failure getting entry for 0x7f0d001f (t=12 e=31) (error -2147483647)
    2018-11-28 17:15:16.071 1697-1721/? I/zygote64: Successfully killed process cgroup uid 10177 pid 16739 in 8ms
    2018-11-28 17:15:16.071 21275-21303/? W/PackageManager: Failure retrieving text 0x7f0d001f in package graduationproject.usst.edu.facedetect
android.content.res.Resources$NotFoundException: String resource ID #0x7f0d001f
    at android.content.res.Resources.getText(Resources.java:380)
    at android.app.ApplicationPackageManager.getText(ApplicationPackageManager.java:1890)
    at android.content.pm.PackageItemInfo.loadLabel(PackageItemInfo.java:138)
    at com.nearme.statistics.rom.a.h.l.a(Utils.java:88)
    at com.nearme.statistics.rom.usermodel.a.c(BackgroundAppData.java:95)
    at com.nearme.statistics.rom.usermodel.a.a(BackgroundAppData.java:69)
    at com.nearme.statistics.rom.usermodel.a.a(BackgroundAppData.java:20)
    at com.nearme.statistics.rom.usermodel.BackgroundAppData$1$1.run(BackgroundAppData.java:48)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
    at java.lang.Thread.run(Thread.java:764)

And I didn't have any error message in the debug toolbar:

    Connected to the target VM, address: 'localhost:8600', transport: 'socket'
    Disconnected from the target VM, address: 'localhost:8600', transport: 'socket'

I have checked my R.java class and I found：

    public static final int app_name=0x7f0d001f;

All where I used app_name is only in the AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="graduationproject.usst.edu.facedetect">

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

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    <activity
            android:name=".menu"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

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

</manifest>

I think I am quiet sure this is where the problem occurs because when i changed

android:label="@string/app_name"

to

android:label="@string/another_name"

Then the error message in the log became:

2018-11-28 17:15:16.071 21275-21303/? W/PackageManager: Failure retrieving text 0x7f0d001e in package graduationproject.usst.edu.facedetect
android.content.res.Resources$NotFoundException: String resource ID #0x7f0d001e

with the following in the R.java class:

public static final int another_name=0x7f0d001e;

The file "project\app\src\main\res\values\strings.xml" exists and the body in it is:

<resources>
    <string name="app_name">facedetect</string>

    <string name="another_name">facedetectt</string>

    <string name="action_settings">Settings</string>
</resources>

The AndroidStudio version is 3.2.1 and I'm using

JDK 1.8
Android SDK 27
NDK 18
Gradle 4.6
Gradle plugin:3.2.1

I have tried rebuild,clean and I had even delete the Build folder to clean and rebuild thoroughly.

I don't know where the problems is. Can Anyone please kindly help me to solve this problem? Thanks!


问:
optimize sql query on 5B records table in postgresql database
My postgresql database has the table electrical_measurement which contains approximately 5 billion records. I have indexes on every column. I am trying to perform the following query but it never ends. Wondering how I can modify it to run faster.

```<code>SELECT
    em.id AS em_id,
    em.test_board_id_in,
    em.die,
    tvt_net.name,
    mb_pad_map.x,
    mb_pad_map.y,
    em.temperature,
    em.timestamp,
    em.avg_meas_voltage
FROM electrical_measurement AS em
INNER JOIN main_board_pad_map AS mb_pad_map
    ON em.net_id_in = mb_pad_map.net_id
INNER JOIN tvt_net
    ON em.net_id_in = tvt_net.id
WHERE em.assembly_id = 1
AND em.net_id_in IN
 (SELECT em.net_id_in
  FROM electrical_measurement AS em
  WHERE em.assembly_id = 1
  AND em.avg_meas_voltage > 0
  GROUP BY em.net_id_in)
ORDER BY em.timestamp
</code>```

This is the result from EXPLAIN:

```<code>-------------------------------------------------------------------------------------------------------------------------------------------------------
 Gather Merge  (cost=373158311.30..573643901.29 rows=1718327938 width=63)
   Workers Planned: 2
   ->  Sort  (cost=373157311.28..375305221.20 rows=859163969 width=63)
         Sort Key: em."timestamp"
         ->  Hash Join  (cost=84935808.04..171830022.94 rows=859163969 width=63)
               Hash Cond: (em.net_id_in = mb_pad_map.net_id)
               ->  Hash Join  (cost=84935424.26..161155613.60 rows=118993479 width=41)
                     Hash Cond: (em.net_id_in = em_1.net_id_in)
                     ->  Parallel Bitmap Heap Scan on electrical_measurement em  (cost=2996320.29..78903135.78 rows=118993479 width=37)
                           Recheck Cond: (assembly_id = 1)
                           ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                 Index Cond: (assembly_id = 1)
                     ->  Hash  (cost=81939087.68..81939087.68 rows=1303 width=4)
                           ->  HashAggregate  (cost=81939061.62..81939074.65 rows=1303 width=4)
                                 Group Key: em_1.net_id_in
                                 ->  Bitmap Heap Scan on electrical_measurement em_1  (cost=2953194.68..81656356.93 rows=113081878 width=4)
                                       Recheck Cond: (assembly_id = 1)
                                       Filter: (avg_meas_voltage > '0'::numeric)
                                       ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                             Index Cond: (assembly_id = 1)
               ->  Hash  (cost=266.17..266.17 rows=9408 width=38)
                     ->  Hash Join  (cost=42.32..266.17 rows=9408 width=38)
                           Hash Cond: (mb_pad_map.net_id = tvt_net.id)
                           ->  Seq Scan on main_board_pad_map mb_pad_map  (cost=0.00..199.08 rows=9408 width=16)
                           ->  Hash  (cost=26.03..26.03 rows=1303 width=22)
                                 ->  Seq Scan on tvt_net  (cost=0.00..26.03 rows=1303 width=22)
(26 rows)
</code>```

Do you have any suggestions?
Thanks

答:
You can try window functions:</p>

```<code>SELECT . . .
FROM (SELECT em.*,
             COUNT(*) FILTER (WHERE em.assembly_id = 1 AND em.avg_meas_voltage) OVER (PARTITION BY em.net_id_in) as cnt
      FROM electrical_measurement em
     ) em JOIN
     main_board_pad_map mbpm
     ON em.net_id_in = mbpm.net_id JOIN
     tvt_net
     ON em.net_id_in = tv.id
WHERE em.assembly_id = 1 AND
      cnt > 0
ORDER BY em.timestamp
</code>```

Body:
My postgresql database has the table electrical_measurement which contains approximately 5 billion records. I have indexes on every column. I am trying to perform the following query but it never ends. Wondering how I can modify it to run faster.

SELECT
    em.id AS em_id,
    em.test_board_id_in,
    em.die,
    tvt_net.name,
    mb_pad_map.x,
    mb_pad_map.y,
    em.temperature,
    em.timestamp,
    em.avg_meas_voltage
FROM electrical_measurement AS em
INNER JOIN main_board_pad_map AS mb_pad_map
    ON em.net_id_in = mb_pad_map.net_id
INNER JOIN tvt_net
    ON em.net_id_in = tvt_net.id
WHERE em.assembly_id = 1
AND em.net_id_in IN
 (SELECT em.net_id_in
  FROM electrical_measurement AS em
  WHERE em.assembly_id = 1
  AND em.avg_meas_voltage > 0
  GROUP BY em.net_id_in)
ORDER BY em.timestamp

This is the result from EXPLAIN:

-------------------------------------------------------------------------------------------------------------------------------------------------------
 Gather Merge  (cost=373158311.30..573643901.29 rows=1718327938 width=63)
   Workers Planned: 2
   ->  Sort  (cost=373157311.28..375305221.20 rows=859163969 width=63)
         Sort Key: em."timestamp"
         ->  Hash Join  (cost=84935808.04..171830022.94 rows=859163969 width=63)
               Hash Cond: (em.net_id_in = mb_pad_map.net_id)
               ->  Hash Join  (cost=84935424.26..161155613.60 rows=118993479 width=41)
                     Hash Cond: (em.net_id_in = em_1.net_id_in)
                     ->  Parallel Bitmap Heap Scan on electrical_measurement em  (cost=2996320.29..78903135.78 rows=118993479 width=37)
                           Recheck Cond: (assembly_id = 1)
                           ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                 Index Cond: (assembly_id = 1)
                     ->  Hash  (cost=81939087.68..81939087.68 rows=1303 width=4)
                           ->  HashAggregate  (cost=81939061.62..81939074.65 rows=1303 width=4)
                                 Group Key: em_1.net_id_in
                                 ->  Bitmap Heap Scan on electrical_measurement em_1  (cost=2953194.68..81656356.93 rows=113081878 width=4)
                                       Recheck Cond: (assembly_id = 1)
                                       Filter: (avg_meas_voltage > '0'::numeric)
                                       ->  Bitmap Index Scan on electrical_measurement_assembly_id_idx  (cost=0.00..2924924.21 rows=285584350 width=0)
                                             Index Cond: (assembly_id = 1)
               ->  Hash  (cost=266.17..266.17 rows=9408 width=38)
                     ->  Hash Join  (cost=42.32..266.17 rows=9408 width=38)
                           Hash Cond: (mb_pad_map.net_id = tvt_net.id)
                           ->  Seq Scan on main_board_pad_map mb_pad_map  (cost=0.00..199.08 rows=9408 width=16)
                           ->  Hash  (cost=26.03..26.03 rows=1303 width=22)
                                 ->  Seq Scan on tvt_net  (cost=0.00..26.03 rows=1303 width=22)
(26 rows)

Do you have any suggestions?
Thanks

Body:
You can try window functions:

SELECT . . .
FROM (SELECT em.*,
             COUNT(*) FILTER (WHERE em.assembly_id = 1 AND em.avg_meas_voltage) OVER (PARTITION BY em.net_id_in) as cnt
      FROM electrical_measurement em
     ) em JOIN
     main_board_pad_map mbpm
     ON em.net_id_in = mbpm.net_id JOIN
     tvt_net
     ON em.net_id_in = tv.id
WHERE em.assembly_id = 1 AND
      cnt > 0
ORDER BY em.timestamp


问:
Remove Element from JDOM document using removeContent()
Given the following scenario, where the xml, Geography.xml looks like -

```<code><Geography xmlns:ns="some valid namespace">
    <Country>
        <Region>
            <State>
                <City>
                    <Name></Name>
                    <Population></Population>
                </City>
            </State>
            </Region>
        </Country>
    </Geography>
</code>```

and the following sample java code -

```<code>InputStream is = new FileInputStream("C:\\Geography.xml");
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = saxBuilder.build(is);

XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
Element el = (Element) xpath.selectSingleNode(doc);
boolean b = doc.removeContent(el);
</code>```

The removeContent() method doesn't remove the Element City from the content list of the doc. The value of b is false

I don't understand why is it not removing the Element, I even tried to delete the Name & Population elements from the xml just to see if that was the issue but apparently its not.

Another way I tried, I don't know why I know its not essentially different, still just for the sake, was to use Parent -

```<code>Parent p = el.getParent();
boolean s = p.removeContent(new Element("City"));
</code>```

What might the problem? and a possible solution? and if anyone can share the real behaviour of the method removeContent(), I suspect it has to do with the parent-child relationship.

答: Sure, removeContent(Content child) removes child if child belongs to the parents immediate children, which it does not in your case. Use el.detach()instead.

ContentLicense: CC BY-SA 3.0

Body:
Given the following scenario, where the xml, Geography.xml looks like -

<Geography xmlns:ns="some valid namespace">
    <Country>
        <Region>
            <State>
                <City>
                    <Name></Name>
                    <Population></Population>
                </City>
            </State>
            </Region>
        </Country>
    </Geography>

and the following sample java code -

InputStream is = new FileInputStream("C:\\Geography.xml");
SAXBuilder saxBuilder = new SAXBuilder();
Document doc = saxBuilder.build(is);

XPath xpath = XPath.newInstance("/*/Country/Region/State/City");
Element el = (Element) xpath.selectSingleNode(doc);
boolean b = doc.removeContent(el);

The removeContent() method doesn't remove the Element City from the content list of the doc. The value of b is false

I don't understand why is it not removing the Element, I even tried to delete the Name & Population elements from the xml just to see if that was the issue but apparently its not.

Another way I tried, I don't know why I know its not essentially different, still just for the sake, was to use Parent -

Parent p = el.getParent();
boolean s = p.removeContent(new Element("City"));

What might the problem? and a possible solution? and if anyone can share the real behaviour of the method removeContent(), I suspect it has to do with the parent-child relationship.


问:
How to make ASP.NET website and ASP.NET Core website work on a same server
There is a domain name www.xxx.com. This is a ASP.NET web site, and it is working well. There is a second level domain name which is yyy.xxx.com. This is an ASP.NET Core 2.0 website. This yyy.xxx.com is what I am developing.

I try to publish and upload ASP.NET Core web application to yyy.xxx.com. Then both websites are on same server. I know I have to install some software to make ASP.NET Core web application work on the server.

So my question is can both ASP.NET website and ASP.NET Core website be visited at same time? I am afraid once I install some software which make ASP.NET Core website can work, the ASP.NET website will work well.

I try use ASP.NET Core 2.0 to develop my website again. Before the new website can work perfect I want the current website to work. That is why there are 2 websites on a same server, one is ASP.NET, the other is ASP.NET Core.

答:
too many characters in my words so i post this answer instead of post a comment.

what i did is:
1.create a second level domain name, such as xxx.mydomain.com
2.open iis to create a website
3.publish my sample asp.net core web application and uplaod to the website.

which cause my top level domain website www.mydomain.com can not work, there is a 500 error.
the error message probably is can not handle web core ... or something. Until i open iis and
remove the second level domain, www.mydomain.com can work again.

so i do not dare to do anymore on host directly. dependence on my research, if i should follow
these steps below to make asp.net and asp.ent core website can work on a same host at same time?
1. install dotnet-hosting-2.1.11-win.exe
2. install aspnetcore-runtime-2.1.11-win-x86.exe
3. open iis to config the second level domain website
4. publish and upload files to the folder of the second level domain website

I wish it is all i should do to reach my goal. but there is something make me do not feel good.
it says asp.net core host in iis can catch all requests before iis then deliver to asp.net core web application
so asp.net web appllication does not have any chance to get request. dependence on my first bad experience, it
looks it is true and that cause my www.domain.com website can not work.

so what i should do ? thanks a lot.


问:
How do I allow just 1 user to push to a branch in GitHub?

I would like for only 1 user to be able to push (force push and regular push) to a certain branch, and everyone else to not have permissions to push.

These are the permissions I set (with my user listed under "Restrict who can push to matching branches". However, when I try to force push I get a branch protected error.

答:
First, you will want to make the branch pull request only. The screenshot you showed will get you that.

After that is done, I guess you can make one of the CI checks to be "checking if the author of the pull request is in the whitelist".

Then, in the "require status check to pass before merging", add the check mentioned in the last step.

Now, no one can ever make changes to this branch unless your CI says "yes, this author is allowed to make changes in this branch"

As for if you want to automatically merge branches that pass the whitelist check, I will not suggest doing it, but if you want to, there are many GitHub apps that can do that, and you can also make a very minimal GitHub app yourself using the GitHub APIs.


问:
Force Trigger event listner with button onclick
Using below code to make basic audio background music player to play files in a folder. On open and after Play (either button or on scale), it plays a random file in the Music folder. When that file ends, it loads another random file and plays it, then continues to repeat the process.  The Question - Is it possible add a button onclick = (i.e. Next Song) to trigger the "ended" event and trigger the next song when clicked.  I think I need to add a music.stop() also. I'm just trying to force the playing song to end and have the loop load the next song.  It appears that the "ended" event is a read only event and can't be manually changed to a true.

```<code>    <html>
<head>
<body>
<!-- <audio id="player" controls><source src="music/0.mp3" type="audio/mp3"></audio> -->
<div align="center" id="soundtrack">
<script>
var WhichSong="Music2/song"+(Math.floor(Math.random()*23))+".mp3"

document.getElementById('soundtrack').innerHTML="<audio controls id='player'><source src=\"" + WhichSong + "\"></source>Your browser does not support the audio element.</audio>";

    var x = 0;
    var music = document.getElementById("player");
    music.addEventListener("ended", function() {
    x=x+1;
    music.src = "Music2/song"+(Math.floor(Math.random()*23))+".mp3";
    music.load();
    music.play();
    });
    </script>
    <br/>
  <button onclick="document.getElementById('player').play()">Play Music</button>
  <button onclick="document.getElementById('player').pause()">Pause Music</button>
  <button onclick="document.getElementById('player').muted=true">Mute</button>
  <button onclick="document.getElementById('player').muted=false">Un-mute</button>
  <button onclick="document.getElementById('player').volume += 0.1">Vol +</button>
  <button onclick="document.getElementById('player').volume -= 0.1">Vol -</button>

</div>
</body>
</code>```

答:
The easiest way is by assigning the event listener to a variable and then calling that function from your onclick.

var endedListener = function() {
    x=x+1;
    music.src = "Music2/song"+(Math.floor(Math.random()*23))+".mp3";
    music.load();
    music.play();
    };
music.addEventListener("ended", endedListener);
```

<pre class="lang-html prettyprint-override"><code>
<button onclick="endedListener()">Next</button>
</code>```

Keep in mind that calling endedListener does not actually stop the audio from playing. It just triggers your own function logic.

Body:
Using below code to make basic audio background music player to play files in a folder. On open and after Play (either button or on scale), it plays a random file in the Music folder. When that file ends, it loads another random file and plays it, then continues to repeat the process.  The Question - Is it possible add a button onclick = (i.e. Next Song) to trigger the "ended" event and trigger the next song when clicked.  I think I need to add a music.stop() also. I'm just trying to force the playing song to end and have the loop load the next song.  It appears that the "ended" event is a read only event and can't be manually changed to a true.

  <button onclick="document.getElementById('player').play()">Play Music</button>
  <button onclick="document.getElementById('player').pause()">Pause Music</button>
  <button onclick="document.getElementById('player').muted=true">Mute</button>
  <button onclick="document.getElementById('player').muted=false">Un-mute</button>
  <button onclick="document.getElementById('player').volume += 0.1">Vol +</button>
  <button onclick="document.getElementById('player').volume -= 0.1">Vol -</button>

Body:
The easiest way is by assigning the event listener to a variable and then calling that function from your onclick.

var endedListener = function() {
    x=x+1;
    music.src = "Music2/song"+(Math.floor(Math.random()*23))+".mp3";
    music.load();
    music.play();
    };
music.addEventListener("ended", endedListener);

<button onclick="endedListener()">Next</button>

Keep in mind that calling endedListener does not actually stop the audio from playing. It just triggers your own function logic.


问:
How do I stop an active AutoHotkey script?
Yesterday while debugging my AutoHotkey script, I accidentally triggered an endless loop of MouseMove and MouseClick events. Every 0.5 seconds my mouse would click random parts of the screen.

After unsuccessfully trying to terminate AHK with the task manager, I ended up turning off my computer to end the script.

How can I stop an active AutoHotkey script?

答:
If you want to get fancy and stop it from the Windows command prompt,

Stop all autohotkey scripts with:

```<code>taskkill /im "autohotkey.exe"
</code>```

Stop specific script with:

```<code>wmic process where "commandline like '%%MyScript.ahk'" delete
</code>```

As of Windows 10 21H1, WMIC is deprecated, so the following PowerShell script will do the equivalent:

```<code>Get-WmiObject win32_process -Filter "commandline like '%%MyScript.ahk""'" |
    ForEach-Object { $_.Terminate() }
</code>```

Body:
If you want to get fancy and stop it from the Windows command prompt,

Stop all autohotkey scripts with:

taskkill /im "autohotkey.exe"

Stop specific script with:

wmic process where "commandline like '%%MyScript.ahk'" delete

As of Windows 10 21H1, WMIC is deprecated, so the following PowerShell script will do the equivalent:

Get-WmiObject win32_process -Filter "commandline like '%%MyScript.ahk""'" |
    ForEach-Object { $_.Terminate() }


问:
Search for issues with custom field of type "Multi-Checkboxes" not ticked
In our Jira we have a custom field of type "Multi-Checkboxes".  How can I search for issues which do not have a checkbox checked?  Issues with nothing checked would do, since this is the only checkbox.

I can search for issues with the checkbox checked with a simple query:

```<code>Colour = "Red"
</code>```

But nothing I can think of will find issues where it is not checked.  I have tried the following:

```<code>Colour != "Red"
Colour = ""
Colour is not "Red"
Colour not in ("Red")
</code>```

答:
Colour IS EMPTY has an implicit check that the "Colour" field exists, so it won't return issues that don't have anything defined.

I had the following situation:

Tickets already existed.

I created a new "Checkbox" custom field.

Searching Colour IS EMPTY returned no results, which was unexpected.

I reindexed the project

Searching Colour IS EMPTY returned results as expected

ContentLicense: CC BY-SA 2.5

Body:
In our Jira we have a custom field of type "Multi-Checkboxes".  How can I search for issues which do not have a checkbox checked?  Issues with nothing checked would do, since this is the only checkbox.

I can search for issues with the checkbox checked with a simple query:

Colour = "Red"

But nothing I can think of will find issues where it is not checked.  I have tried the following:

Colour != "Red"
Colour = ""
Colour is not "Red"
Colour not in ("Red")


问:
Android Multiline Snackbar
I'm trying to leverage new Snackbar from Android Design Support Library to display multiline snackbar, as shown in http://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-specs:

```<code>import android.support.design.widget.Snackbar;

final String snack = "First line\nSecond line\nThird line";
Snackbar.make(mView, snack, Snackbar.LENGTH_LONG).show();
</code>```

It displays only First line... on my Nexus 7. How to make it display all lines?

PS: I tried Toast and it displayed all lines.

答:
For Material Design, the reference is com.google.android.material.R.id.snackbar_text

```<code>val snack = Snackbar.make(myView, R.string.myLongText, Snackbar.LENGTH_INDEFINITE).apply {
                view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text).maxLines = 10
            }
            snack.show()
</code>```

Title: Android Multiline Snackbar

Body:
I'm trying to leverage new Snackbar from Android Design Support Library to display multiline snackbar, as shown in http://www.google.com/design/spec/components/snackbars-toasts.html#snackbars-toasts-specs:

import android.support.design.widget.Snackbar;

final String snack = "First line\nSecond line\nThird line";
Snackbar.make(mView, snack, Snackbar.LENGTH_LONG).show();

It displays only First line... on my Nexus 7. How to make it display all lines?

PS: I tried Toast and it displayed all lines.

Body:
For Material Design, the reference is com.google.android.material.R.id.snackbar_text

val snack = Snackbar.make(myView, R.string.myLongText, Snackbar.LENGTH_INDEFINITE).apply {
                view.findViewById<TextView>(com.google.android.material.R.id.snackbar_text).maxLines = 10
            }
            snack.show()


问:
Multiple Azure Functions in one Timer trigger class
We have to write multiple triggers. I was hoping to create separate functions, based on the trigger types. So if I need 5 timer triggers, that will run at different times, I would create one Timer trigger function class and name the functions like [TimerTrigger1], [TimerTrigger2], [TimerTrigger3] ... and so forth. After I added the code I am not sure if I can do that anymore.

Can someone suggest how I can go about adding multiple triggers? I can't have two Run functions under one class.

public static class TimerTrigger
{
    [FunctionName("InsertTimerTrigger1")]
    public static void Run([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
         // Do task 1
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }

    [FunctionName("InsertTimerTrigger2")]
    public static void Run([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer, ILogger log)
    {
        //Do Task 2
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}
```

答:
You can choose any name for the methods. (Naming it as "Run" is not a requirement.)

public static class TimerTrigger
{
    [FunctionName("InsertTimerTrigger1")]
    public static void InsertTimerTrigger1([TimerTrigger("0 */5 * * * *")]TimerInfo myTimer, ILogger log)
    {
         // Do task 1
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }

    [FunctionName("InsertTimerTrigger2")]
    public static void InsertTimerTrigger2([TimerTrigger("0 */15 * * * *")]TimerInfo myTimer, ILogger log)
    {
        //Do Task 2
        log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}");
    }
}
```


问:
Check rendered SQL sent to the server from SSDT/SSRS
I'm building a report in Visual Studio Data Tools and I'm having trouble in passing a multivalued parameter to a DB2 LUW server.

How to check the rendered SQL string sent to the server?

答:
You can use the SQL Server Profiler to see the actual query. Or you can catch it in the query monitor in SSMS.

If you post more details someone might be able to see what's wrong. It usually has to do with how the WHERE clause is written.


问:
Cypress.io: Waiting for results of exec command
I am trying to set some variables based on the results of a cy.exec() command for use later in the script. For example:

```<code>cy.exec('some command').then((result) => {
  let json = JSON.parse(result.stdout)
  this.foo = json.foo
})
</code>```

How can I wait for this.foo to be defined before proceeding with the rest of the script? I tried:

```<code>cy.exec('some command').as('results')
cy.wait('@results')
</code>```

However this.results is undefined after the cy.wait() command.

答:
You don't need aliases. Your code is correct, but you can't use this inside of a () => {}. You should use a function declaration to make use of this.

Try this instead:

cy.exec('some command').then(function(result) {
  let json = JSON.parse(result.stdout)
  this.foo = json.foo
})
```

<p>Note that Cypress is asynchronous. What this means is that if you do something like this:</p>

<pre class="lang-js prettyprint-override"><code>cy.exec('some command').then(function(result) {
  let json = JSON.parse(result.stdout)
  this.foo = json.foo
})

expect(this.foo).to.eq(expectedStdout)
</code>```

...your test will always fail. this.foo = json.foo will be executed after the expect(this.foo)... is evaluated.

If you want to use this.foo in this way, just use the Promise returned by cy.exec():

cy.exec('some command').then(result => {
  return JSON.parse(result.stdout)
})
.then(json => {
  // write the rest of your test here
  cy.get('blah').contains(json.something)
})
```

Body:
I am trying to set some variables based on the results of a cy.exec() command for use later in the script. For example:

cy.exec('some command').then((result) => {
  let json = JSON.parse(result.stdout)
  this.foo = json.foo
})

How can I wait for this.foo to be defined before proceeding with the rest of the script? I tried:

cy.exec('some command').as('results')
cy.wait('@results')

However this.results is undefined after the cy.wait() command.

Body:
You don't need aliases. Your code is correct, but you can't use this inside of a () => {}. You should use a function declaration to make use of this.

Try this instead:

cy.exec('some command').then(function(result) {
  let json = JSON.parse(result.stdout)
  this.foo = json.foo
})

Note that Cypress is asynchronous. What this means is that if you do something like this:

cy.exec('some command').then(function(result) {
  let json = JSON.parse(result.stdout)
  this.foo = json.foo
})

expect(this.foo).to.eq(expectedStdout)

...your test will always fail. this.foo = json.foo will be executed after the expect(this.foo)... is evaluated.

If you want to use this.foo in this way, just use the Promise returned by cy.exec():

cy.exec('some command').then(result => {
  return JSON.parse(result.stdout)
})
.then(json => {
  // write the rest of your test here
  cy.get('blah').contains(json.something)
})


问:
Need 3 digits in column in a CSV-file
I have a script that extracts data from an XML file and put this into an CSV file with 2 columns.
The file looks like this:

```<code>Name, Count
1,34
3,55
15,66
103,99
etc.
</code>```

So far so good...

My problem is that the program that reads the CSV-file always expect 3 digits in the column "Name".

So the CSV-file need to look like this:

```<code>Name, Count
001,34
003,55
015,66
103,99
etc.
</code>```

How can I do this formatting using "Export-CSV"?

Please help I'm stuck here..

答:
There are several ways to apply the changes to the csv file.

Read/Import to a variable, change name, Export-Csv variable

```<code>$Csv = Import-Csv .\Sample.csv
$Csv | ForEach-Object{ $_.Name = $_.Name.PadLeft(3,'0') }
$Csv | Export-Csv .\NewSample.csv -NoTypeInformation
</code>```

Do the same on the fly with a calculated property reusing the same header/property name.

```<code>Import-Csv .\Sample.csv |
  Select-Object @{n='Name';e={$_.Name.PadLeft(3,'0')}},Count|
    Export-Csv .\NewSample2.csv -NoTypeInformation
</code>```

Title: Need 3 digits in column in a CSV-file

Body:
I have a script that extracts data from an XML file and put this into an CSV file with 2 columns.
The file looks like this:

Name, Count
1,34
3,55
15,66
103,99
etc.

So far so good...

My problem is that the program that reads the CSV-file always expect 3 digits in the column "Name".

So the CSV-file need to look like this:

Name, Count
001,34
003,55
015,66
103,99
etc.

How can I do this formatting using "Export-CSV"?

Please help I'm stuck here..

Body:
There are several ways to apply the changes to the csv file.

Read/Import to a variable, change name, Export-Csv variable

$Csv = Import-Csv .\Sample.csv
$Csv | ForEach-Object{ $_.Name = $_.Name.PadLeft(3,'0') }
$Csv | Export-Csv .\NewSample.csv -NoTypeInformation

Do the same on the fly with a calculated property reusing the same header/property name.

Import-Csv .\Sample.csv |
  Select-Object @{n='Name';e={$_.Name.PadLeft(3,'0')}},Count|
    Export-Csv .\NewSample2.csv -NoTypeInformation


问:
Big O Question - Algorithmic Analysis III
I have the following question:

Solve the recurrence relation simplifying the answer using Big 'O' notation:

```<code>f(0) = 2
f(n) = 6f(n-1)-5, n>0
</code>```

I know this is a first order inhomogenous recurrence relation and have had a go at the question but I cannot seem to get the right output for the base case (f(0) = 2).

The question MUST use the sum of geometric series forumla within the proof.

Here is my answer - Note sum(x = y, z) is a replacement for capital sigma notation, where x is the lower bound of the summation initialised to y and z is the upper bound of the summation:

```<code>1.  *change forumla:*
2.     f(n) = 6^n.g(n)
3.  => 6^n.g(n) = 6.6^(n-1) .g(n-1) -5
4.  => g(n) = g(n-1)-5/6^n
5.  => g(n) = sum(i=1, n)-5/6^i
6.  => f(n) = 6^n.sum(i=1, n)-5/6^i
7.  => *Evaluate the sum using geometric series forumla*
8.  => sum(i = 1, n)-5/6^i = [sum(i = 1, n)a^i] -------> (a = -5/6)
9.  => *sub a = -5/6 into geometric forumla [a(1-a^n)/(1-a)]*
10. => [(-5/6(1 - (-5/6)^n))/(1-(-5/6))]
11. => g(n) = [(-5/6(1 + (5/6)^n))/(1+5/6)]
12. => f(n) = 6^n . g(n) = 6^n[(-5/6(1 + (5/6)^n))/(1+5/6)]
13. => *sub in n = 0 to see if f(0) = 2*
</code>```

Firstly, I am sure the equation on line 11 can be simplified further and secondly subbing in n = 0 should yield 2 as the result. I cannot obtain this answer when reaching line 13...

EDIT: What I need to know is why I am not getting f(0) = 2 when subbing n = 0 into the equation in line 12. Also what I would like to know is how can I simplify the equation for f(n) in line 12?

Anyone...?

答:
Without thinking too hard about this, I'm going to say that f(n + 1) is 6 times larger than f(n), minus a constant.  f(n) is therefore certainly O(6^n).  Although you may find a tighter bound, that's about as far as I'd go in practice!

For the fun of it, I'll try this:

```<code>f(1) = 6f(0) - 5
     = 6^1.f(0)
f(2) = 6f(1) - 5
     = 6(6f(0) - 5) - 5
     = 6^2.f(0) - 6^1.5 - 5
f(3) = 6f(2) - 5
     = 6^3.f(0) - 6^2.5 - 6^1.5 - 5
</code>```

I'll hazard a guess that

```<code>f(n) = 6^n.f(0) - 5.(6^0 + 6^1 + ... + 6^(n-1))
</code>```

and I'm pretty sure that I could prove this by induction in a few lines (exercise left as an exercise for the student).

Now,

```<code>sum (k in 0..n-1) 6^k  =  (1 - 6^n) / (1 - 6)
</code>```

therefore

```<code>f(n) = 6^n.f(0) - 5.(1 - 6^n) / (1 - 6)
     = 6^n.f(0) + (1 - 6^n)
     = 6^n.(2 - 1) + 1
     = 6^n + 1
</code>```

confirming my earlier intuition.

Let's just do a few quick check calculations:

```<code>f(0) = 2 = 6^0 + 1
f(1) = 6.2 - 5 = 7 = 6^1 + 1
f(2) = 6.7 - 5 = 37 = 6^2 + 1
f(3) = 6.37 - 5 = 237 = 6^3 + 1
</code>```

That's enough for me for homework :-)

Body:
I have the following question:

Solve the recurrence relation simplifying the answer using Big 'O' notation:

f(0) = 2
f(n) = 6f(n-1)-5, n>0

I know this is a first order inhomogenous recurrence relation and have had a go at the question but I cannot seem to get the right output for the base case (f(0) = 2).

The question MUST use the sum of geometric series forumla within the proof.

Here is my answer - Note sum(x = y, z) is a replacement for capital sigma notation, where x is the lower bound of the summation initialised to y and z is the upper bound of the summation:

1.  *change forumla:*
2.     f(n) = 6^n.g(n)
3.  => 6^n.g(n) = 6.6^(n-1) .g(n-1) -5
4.  => g(n) = g(n-1)-5/6^n
5.  => g(n) = sum(i=1, n)-5/6^i
6.  => f(n) = 6^n.sum(i=1, n)-5/6^i
7.  => *Evaluate the sum using geometric series forumla*
8.  => sum(i = 1, n)-5/6^i = [sum(i = 1, n)a^i] -------> (a = -5/6)
9.  => *sub a = -5/6 into geometric forumla [a(1-a^n)/(1-a)]*
10. => [(-5/6(1 - (-5/6)^n))/(1-(-5/6))]
11. => g(n) = [(-5/6(1 + (5/6)^n))/(1+5/6)]
12. => f(n) = 6^n . g(n) = 6^n[(-5/6(1 + (5/6)^n))/(1+5/6)]
13. => *sub in n = 0 to see if f(0) = 2*

Firstly, I am sure the equation on line 11 can be simplified further and secondly subbing in n = 0 should yield 2 as the result. I cannot obtain this answer when reaching line 13...

EDIT: What I need to know is why I am not getting f(0) = 2 when subbing n = 0 into the equation in line 12. Also what I would like to know is how can I simplify the equation for f(n) in line 12?

Anyone...?

Body:
Without thinking too hard about this, I'm going to say that f(n + 1) is 6 times larger than f(n), minus a constant.  f(n) is therefore certainly O(6^n).  Although you may find a tighter bound, that's about as far as I'd go in practice!

For the fun of it, I'll try this:

f(1) = 6f(0) - 5
     = 6^1.f(0)
f(2) = 6f(1) - 5
     = 6(6f(0) - 5) - 5
     = 6^2.f(0) - 6^1.5 - 5
f(3) = 6f(2) - 5
     = 6^3.f(0) - 6^2.5 - 6^1.5 - 5

I'll hazard a guess that

f(n) = 6^n.f(0) - 5.(6^0 + 6^1 + ... + 6^(n-1))

and I'm pretty sure that I could prove this by induction in a few lines (exercise left as an exercise for the student).

Now,

sum (k in 0..n-1) 6^k  =  (1 - 6^n) / (1 - 6)

therefore

f(n) = 6^n.f(0) - 5.(1 - 6^n) / (1 - 6)
     = 6^n.f(0) + (1 - 6^n)
     = 6^n.(2 - 1) + 1
     = 6^n + 1

confirming my earlier intuition.

Let's just do a few quick check calculations:

f(0) = 2 = 6^0 + 1
f(1) = 6.2 - 5 = 7 = 6^1 + 1
f(2) = 6.7 - 5 = 37 = 6^2 + 1
f(3) = 6.37 - 5 = 237 = 6^3 + 1

That's enough for me for homework :-)


问:
Glide not Loading image from StorageReference
I have problem when loading image from StorageReference to ImageView using Glide 4.9.0 (latest).

It's stuck on PlaceHolder..
When I try to put the downloadable url of my ref, it's working..

```<code>StorageReference ref = FirebaseStorage.getInstance().getReference().child("myImage")

//It's not working
Glide.with(mContext)
   .load(ref)
   .placeholder(R.drawable.ic_loading_circle)
   .error(R.drawable.ic_loading_circle)
   .into(mImageView);

//It's working
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
    @Override
    public void onSuccess(Uri downloadUrl)
    {
        Glide.with(mContext)
            .load(downloadUrl.toString())
            .placeholder(R.drawable.ic_loading_circle)
            .error(R.drawable.ic_loading_circle)
            .into(mImageView);
    }
});
</code>```

I didn't see any error using try-catch, I already put Internet permission in Manifest. Other image from drawable are working also

Note: My firebase is used by 2 apps, the first app is working without any problem with Glide, but this 2nd app got unknown problem.

any solution or alternative? because using getDownloadUrl().addOnSuccessListener to get URI are so slow

答:
I don't think Glide support StorageReference it is different protocol, but you can use FirebaseUI that support this, and uses behind the scene Glidelibrary.

FirebaseUI

Body:
I have problem when loading image from StorageReference to ImageView using Glide 4.9.0 (latest).

It's stuck on PlaceHolder..
When I try to put the downloadable url of my ref, it's working..

StorageReference ref = FirebaseStorage.getInstance().getReference().child("myImage")

//It's not working
Glide.with(mContext)
   .load(ref)
   .placeholder(R.drawable.ic_loading_circle)
   .error(R.drawable.ic_loading_circle)
   .into(mImageView);

//It's working
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>()
{
    @Override
    public void onSuccess(Uri downloadUrl)
    {
        Glide.with(mContext)
            .load(downloadUrl.toString())
            .placeholder(R.drawable.ic_loading_circle)
            .error(R.drawable.ic_loading_circle)
            .into(mImageView);
    }
});

I didn't see any error using try-catch, I already put Internet permission in Manifest. Other image from drawable are working also

Note: My firebase is used by 2 apps, the first app is working without any problem with Glide, but this 2nd app got unknown problem.

any solution or alternative? because using getDownloadUrl().addOnSuccessListener to get URI are so slow


问:
Optical Flow: What exactly is the temporal derivative?
I'm trying to understand what the meaning of a temporal derivative is in an image. While I understand the brightness constancy equation, I don't understand why taking the difference between two images gives me the temporal derivative.

Taking the difference between two frames gives me the difference in pixel intensity per pixel between the two, but how is that the same as asking how much the image changed over a certain span of time?

答:
The difference between subsequent frames is the finite difference approximation to the temporal derivative.

Proper units would be obtained if the value were divided by the time between frames (i.e. multiplied by the frames per second value).


问:
React router changes url but not view
I am having trouble changing the view in react with routing. I only want to show a list of users, and clicking on each user should navigate to a details page. Here is the router:

```<code>import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from 'react-router-dom';
import Users from "./components/Users";
import { Router, Route } from "react-router";
import Details from "./components/Details";

ReactDOM.render((
  <BrowserRouter>
    <div>
        <Route path="/" component={Users} />
        <Route path="/details" component={Details} />
    </div>
  </BrowserRouter>
), document.getElementById('app'))
</code>```

When I use the url /details my browser navigates to that url, but does not change the view. Any other route throws 404 so it seems to recognize the route but not update.

答:
I had a similar issue with a conditional Layout:

```<code>class LayoutSwitcher extends Component {
  render () {
    const isLoggedIn = this.props.isLoggedIn
    return (
      <React.Fragment>
        { isLoggedIn
          ? <MainLayout {...this.props} />
          : <Login />
        }
      </React.Fragment>
    )
  }
}
</code>```

and rewrote the conditions like so:

```<code>  render () {
    const isLoggedIn = this.props.isLoggedIn
    if (isLoggedIn) {
      return <MainLayout {...this.props} />
    }
    return <Login />
  }
</code>```

This solved it. In my case, it seems that the context was lost.

Title: React router changes url but not view

Body:
I am having trouble changing the view in react with routing. I only want to show a list of users, and clicking on each user should navigate to a details page. Here is the router:

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter } from 'react-router-dom';
import Users from "./components/Users";
import { Router, Route } from "react-router";
import Details from "./components/Details";

ReactDOM.render((
  <BrowserRouter>

        <Route path="/" component={Users} />
        <Route path="/details" component={Details} />

  </BrowserRouter>
), document.getElementById('app'))

When I use the url /details my browser navigates to that url, but does not change the view. Any other route throws 404 so it seems to recognize the route but not update.

Body:
I had a similar issue with a conditional Layout:

class LayoutSwitcher extends Component {
  render () {
    const isLoggedIn = this.props.isLoggedIn
    return (
      <React.Fragment>
        { isLoggedIn
          ? <MainLayout {...this.props} />
          : <Login />
        }
      </React.Fragment>
    )
  }
}

and rewrote the conditions like so:

  render () {
    const isLoggedIn = this.props.isLoggedIn
    if (isLoggedIn) {
      return <MainLayout {...this.props} />
    }
    return <Login />
  }

This solved it. In my case, it seems that the context was lost.


问:
how to add columns to existing hive partitioned table?
```<code>alter table abc add columns (stats1 map<string,string>, stats2 map<string,string>)
</code>```

i have altered my table with above query. But after while checking the data i got NULL's for the both extra columns. I'm not getting data.

screenshot

答:
As others have noted CASCADE will change the metadata for all partitions. Without CASCADE, if you want to change old partitions to include the new columns, you'll need to DROP the old partitions first and then fill them, INSERT OVERWRITE without the DROP won't work, because the metadata won't update to the new default metadata.

Let's say you have already run alter table abc add columns (stats1 map<string,string>, stats2 map<string,string>) without CASCADE by accident and then you INSERT OVERWRITE an old partition without DROPPING first. The data will be stored in the underlying files, but if you query that table from hive for that partition, it won't show because the metadata wasn't updated. This can be fixed without having to rerun the insert overwrite using the following:

Run SHOW CREATE TABLE dbname.tblname and copy all the column definitions that existed before adding new columns

Run ALTER TABLE dbname.tblname REPLACE COLUMNS ({paste in col defs besides columns to add here}) CASCADE

Run ALTER TABLE dbname.tblname ADD COLUMNS (newcol1 int COMMENT "new col") CASCADE

be happy that the metadata has been changed for all partitions =)

As an example of steps 2-3:

```<code>DROP TABLE IF EXISTS  junk.testcascade ;
CREATE TABLE junk.testcascade (
startcol INT
)
partitioned by (d int)
stored as parquet
;
INSERT INTO TABLE junk.testcascade PARTITION(d=1)
VALUES
    (1),
    (2)
;

INSERT INTO TABLE junk.testcascade PARTITION(d=2)
VALUES
    (1),
    (2)
;

SELECT * FROM junk.testcascade ;
+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.d  |
+-----------------------+----------------+--+
| 1                     | 1              |
| 2                     | 1              |
| 1                     | 2              |
| 2                     | 2              |
+-----------------------+----------------+--+

 --no cascade! opps
ALTER TABLE junk.testcascade ADD COLUMNS( testcol1 int, testcol2 int) ;

INSERT OVERWRITE TABLE junk.testcascade PARTITION(d=3)
VALUES
    (1,1,1),
    (2,1,1)
;

INSERT OVERWRITE TABLE junk.testcascade PARTITION(d=2)
VALUES
    (1,1,1),
    (2,1,1)
;

--okay! because we created this table after altering the metadata
select * FROM junk.testcascade where d=3;
+-----------------------+-----------------------+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.testcol1  | testcascade.testcol2  | testcascade.d  |
+-----------------------+-----------------------+-----------------------+----------------+--+
| 1                     | 1                     | 1                     | 3              |
| 2                     | 1                     | 1                     | 3              |
+-----------------------+-----------------------+-----------------------+----------------+--+

--not okay even tho we inserted =( because the metadata isnt changed
select * FROM junk.testcascade where d=2;
+-----------------------+-----------------------+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.testcol1  | testcascade.testcol2  | testcascade.d  |
+-----------------------+-----------------------+-----------------------+----------------+--+
| 1                     | NULL                  | NULL                  | 2              |
| 2                     | NULL                  | NULL                  | 2              |
+-----------------------+-----------------------+-----------------------+----------------+--+

--cut back to original columns
ALTER TABLE junk.testcascade REPLACE COLUMNS( startcol int) CASCADE;

--add
ALTER table junk.testcascade ADD COLUMNS( testcol1 int, testcol2 int) CASCADE;

--it works!
select * FROM junk.testcascade where d=2;
+-----------------------+-----------------------+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.testcol1  | testcascade.testcol2  | testcascade.d  |
+-----------------------+-----------------------+-----------------------+----------------+--+
| 1                     | 1                     | 1                     | 2              |
| 2                     | 1                     | 1                     | 2              |
+-----------------------+-----------------------+-----------------------+----------------+--+
</code>```

Body:
alter table abc add columns (stats1 map<string,string>, stats2 map<string,string>)

i have altered my table with above query. But after while checking the data i got NULL's for the both extra columns. I'm not getting data.

screenshot

Body:
As others have noted CASCADE will change the metadata for all partitions. Without CASCADE, if you want to change old partitions to include the new columns, you'll need to DROP the old partitions first and then fill them, INSERT OVERWRITE without the DROP won't work, because the metadata won't update to the new default metadata.

Let's say you have already run alter table abc add columns (stats1 map<string,string>, stats2 map<string,string>) without CASCADE by accident and then you INSERT OVERWRITE an old partition without DROPPING first. The data will be stored in the underlying files, but if you query that table from hive for that partition, it won't show because the metadata wasn't updated. This can be fixed without having to rerun the insert overwrite using the following:

Run SHOW CREATE TABLE dbname.tblname and copy all the column definitions that existed before adding new columns

Run ALTER TABLE dbname.tblname REPLACE COLUMNS ({paste in col defs besides columns to add here}) CASCADE

Run ALTER TABLE dbname.tblname ADD COLUMNS (newcol1 int COMMENT "new col") CASCADE

be happy that the metadata has been changed for all partitions =)

As an example of steps 2-3:

DROP TABLE IF EXISTS  junk.testcascade ;
CREATE TABLE junk.testcascade (
startcol INT
)
partitioned by (d int)
stored as parquet
;
INSERT INTO TABLE junk.testcascade PARTITION(d=1)
VALUES
    (1),
    (2)
;

INSERT INTO TABLE junk.testcascade PARTITION(d=2)
VALUES
    (1),
    (2)
;

SELECT * FROM junk.testcascade ;
+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.d  |
+-----------------------+----------------+--+
| 1                     | 1              |
| 2                     | 1              |
| 1                     | 2              |
| 2                     | 2              |
+-----------------------+----------------+--+

 --no cascade! opps
ALTER TABLE junk.testcascade ADD COLUMNS( testcol1 int, testcol2 int) ;

INSERT OVERWRITE TABLE junk.testcascade PARTITION(d=3)
VALUES
    (1,1,1),
    (2,1,1)
;

INSERT OVERWRITE TABLE junk.testcascade PARTITION(d=2)
VALUES
    (1,1,1),
    (2,1,1)
;

--okay! because we created this table after altering the metadata
select * FROM junk.testcascade where d=3;
+-----------------------+-----------------------+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.testcol1  | testcascade.testcol2  | testcascade.d  |
+-----------------------+-----------------------+-----------------------+----------------+--+
| 1                     | 1                     | 1                     | 3              |
| 2                     | 1                     | 1                     | 3              |
+-----------------------+-----------------------+-----------------------+----------------+--+

--not okay even tho we inserted =( because the metadata isnt changed
select * FROM junk.testcascade where d=2;
+-----------------------+-----------------------+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.testcol1  | testcascade.testcol2  | testcascade.d  |
+-----------------------+-----------------------+-----------------------+----------------+--+
| 1                     | NULL                  | NULL                  | 2              |
| 2                     | NULL                  | NULL                  | 2              |
+-----------------------+-----------------------+-----------------------+----------------+--+

--cut back to original columns
ALTER TABLE junk.testcascade REPLACE COLUMNS( startcol int) CASCADE;

--add
ALTER table junk.testcascade ADD COLUMNS( testcol1 int, testcol2 int) CASCADE;

--it works!
select * FROM junk.testcascade where d=2;
+-----------------------+-----------------------+-----------------------+----------------+--+
| testcascade.startcol  | testcascade.testcol1  | testcascade.testcol2  | testcascade.d  |
+-----------------------+-----------------------+-----------------------+----------------+--+
| 1                     | 1                     | 1                     | 2              |
| 2                     | 1                     | 1                     | 2              |
+-----------------------+-----------------------+-----------------------+----------------+--+


问:
How do you extract IP addresses from a line matching a string from a file in bash?
Example:

I have a file name example.txt and inside it this text:

```<code>some text here INFO    200     cv 58687 http://saomesitehoere.com live connect ASDFG 61.215.80.6 07:16

some text here INFO    100     fv 582702687 http://saomesitehoere.org live connect 31.15.80.1 07:16:33

some text here INFO    00     ov 587 http://saomesitehoere.uk live connect ASGGGGFG 91.211.80.6 09:16

some text here INFO    800    kcv 277 http://saomesitehoere.za live connect AFG 71.215.81.5 09:14
</code>```

I want to extract the IP-address from the line which contain the string name "ASDFG", meaning 61.215.80.6

Anyone can help ?

答:
To extract all the "valid" IP addresses from the file:

```<code>gawk  '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/,a);split(a[0],b,".")} b[1]<=255&& b[2]<=255 && b[3]<=255 && b[4]<=255 &&length(a[0]){print a[0]}' input_file
</code>```

This will work in two steps:

First it will extract all the sub-strings having pattern line digits.digits.digits.digits

it will check if each set of digits is less then or equal to 255.

Note: needs gawk to use match() function.

Body:
Example:

I have a file name example.txt and inside it this text:

some text here INFO    200     cv 58687 http://saomesitehoere.com live connect ASDFG 61.215.80.6 07:16

some text here INFO    100     fv 582702687 http://saomesitehoere.org live connect 31.15.80.1 07:16:33

some text here INFO    00     ov 587 http://saomesitehoere.uk live connect ASGGGGFG 91.211.80.6 09:16

some text here INFO    800    kcv 277 http://saomesitehoere.za live connect AFG 71.215.81.5 09:14

I want to extract the IP-address from the line which contain the string name "ASDFG", meaning 61.215.80.6

Anyone can help ?

Body:
To extract all the "valid" IP addresses from the file:

gawk  '{match($0,/[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+/,a);split(a[0],b,".")} b[1]<=255&& b[2]<=255 && b[3]<=255 && b[4]<=255 &&length(a[0]){print a[0]}' input_file

This will work in two steps:

First it will extract all the sub-strings having pattern line digits.digits.digits.digits

it will check if each set of digits is less then or equal to 255.

Note: needs gawk to use match() function.


问:
scjp question regarding design
A team of programmers is reviewing a proposed API for a new utility class. After some
discussion, they realize that they can reduce the number of methods in the API without
losing any functionality. If they implement the new design, which two OO principles will
they be promoting?

```<code>A. Looser coupling
B. Tighter coupling
C. Lower cohesion
D. Higher cohesion
E. Weaker encapsulation
F. Stronger encapsulation
</code>```

Can somebody tell me what is the answer?

答:
My answer will be

Looser coupling and
Higher cohesion

If the next question is why? then I would suggest you to go through this article :

http://blog.sanaulla.info/2008/06/26/cohesion-and-coupling-two-oo-design-principles/

Title: scjp question regarding design

Body:
A team of programmers is reviewing a proposed API for a new utility class. After some
discussion, they realize that they can reduce the number of methods in the API without
losing any functionality. If they implement the new design, which two OO principles will
they be promoting?

A. Looser coupling
B. Tighter coupling
C. Lower cohesion
D. Higher cohesion
E. Weaker encapsulation
F. Stronger encapsulation

Can somebody tell me what is the answer?


问:
Apache resetting connection (?) on large file uploads
I have a site that used to be able to upload large files (large being > 10 or 20mb) but no longer can. I've been debugging this for hours at this point.

All php values are set ludicrously high:

```<code>post_max_size = 512M
upload_max_filesize = 512M
memory_limit = 1024M
max_execution_time = 600
max_input_time = 600
</code>```

I've also set TimeOut 600 in httpd.conf.

Essentially, if I add a large file to an upload field, it never uploads. I can witness the "Uploading (1%)..." in the lower left in chrome showing the file start uploading. It will count up, sometimes even reaching 100%, then start over again at 0 and start counting up again, eventually failing with an ERR_CONNECTION_RESET message.

The eventual failure seems to happen after a random amount of time, sometimes 24 seconds, simetimes 3 minutes.

I tried a 170mb file and it will always get to 16 or 17% before it restarts. That always takes something like 22 seconds. Then, it will restart at 0 and count up to 16 or 17% again, then restart again. It ultimately fails with the ERR_CONNECTION_RESET message sometimes after restarting once, sometimes after restarting 4 or 5 times.

I also tried a 30mb file. This one will always reach right around 100% before restarting.

df -h shows plenty of file space remaining, and I was able to upload files fine via SFTP confirming that there is indeed sufficient hard disk space.

Files also upload fine using the exact same application on my development server, so I can rule out any application issues.

Smaller files also upload fine on the production server, i've tried files as large as 3 or 5mb with no issue.

I'm able to execute code like:

```<code>echo "start";
sleep(60);
echo "stop";
</code>```

without any hiccup on production, so it isn't timing out all requests, only the uploads.

I've tried multiple browsers, and this is happening from multiple client locations.

There is never an error in any log I can find in /var/log/httpd.

I'm not running mod security. Nowhere in my application are any of the php settings overwritten. It's a pretty standard installation of apache and php.

The production server is Amazon Linux running Apache/2.4.39 and I've tried it on php 7.1 and php 7.2 and got the same result, both using mod_php.

I am well into the "banging head against wall" stage of this issue. Does anyone have any ideas what I can do to debug this?

答:
Finally got this to work. Thanks to net::ERR_CONNECTION_RESET when large file takes longer than a minute

I had to add RequestReadTimeout header=0 body=0 to my httpd.conf file

It couldn't be within a vhost definition, at least I tried that hours ago and nothing. But, circled back and tried it again in httpd.conf and it worked.

TG.

Body:
I have a site that used to be able to upload large files (large being > 10 or 20mb) but no longer can. I've been debugging this for hours at this point.

All php values are set ludicrously high:

post_max_size = 512M
upload_max_filesize = 512M
memory_limit = 1024M
max_execution_time = 600
max_input_time = 600

I've also set TimeOut 600 in httpd.conf.

Essentially, if I add a large file to an upload field, it never uploads. I can witness the "Uploading (1%)..." in the lower left in chrome showing the file start uploading. It will count up, sometimes even reaching 100%, then start over again at 0 and start counting up again, eventually failing with an ERR_CONNECTION_RESET message.

The eventual failure seems to happen after a random amount of time, sometimes 24 seconds, simetimes 3 minutes.

I tried a 170mb file and it will always get to 16 or 17% before it restarts. That always takes something like 22 seconds. Then, it will restart at 0 and count up to 16 or 17% again, then restart again. It ultimately fails with the ERR_CONNECTION_RESET message sometimes after restarting once, sometimes after restarting 4 or 5 times.

I also tried a 30mb file. This one will always reach right around 100% before restarting.

df -h shows plenty of file space remaining, and I was able to upload files fine via SFTP confirming that there is indeed sufficient hard disk space.

Files also upload fine using the exact same application on my development server, so I can rule out any application issues.

Smaller files also upload fine on the production server, i've tried files as large as 3 or 5mb with no issue.

I'm able to execute code like:

echo "start";
sleep(60);
echo "stop";

without any hiccup on production, so it isn't timing out all requests, only the uploads.

I've tried multiple browsers, and this is happening from multiple client locations.

There is never an error in any log I can find in /var/log/httpd.

I'm not running mod security. Nowhere in my application are any of the php settings overwritten. It's a pretty standard installation of apache and php.

The production server is Amazon Linux running Apache/2.4.39 and I've tried it on php 7.1 and php 7.2 and got the same result, both using mod_php.

I am well into the "banging head against wall" stage of this issue. Does anyone have any ideas what I can do to debug this?


问:
I have problem linking my css to html using external method of writing css
Have been trying to link my html and my css writing code using css external method, can anybody put me through please?</p>

答:
1.Rename your css file to style.css and html file should be index.html
 2.put your css and html file in the same directory.
 3.write this is your css file (for test)

```<code>body{
 background-color:red;
</code>```

}

4.and your html file should be like this :

```<code><html>
<head>
    <link rel='stylesheet' href='style.css'>
</head>
<body>
</body>
</code>```

5.run the index.html in your browser

Body:
1.Rename your css file to style.css and html file should be index.html
 2.put your css and html file in the same directory.
 3.write this is your css file (for test)

body{
 background-color:red;

}

4.and your html file should be like this :

<html>
<head>
    <link rel='stylesheet' href='style.css'>
</head>
<body>
</body>

5.run the index.html in your browser


问:
Overwrite file if new session but append if same session
I have a function to convert any write-hosts in the script (keeping them for coloring purposes later) to tee object

```<code>function Write-Host($object)
{
    $object | tee .\LOG.txt -Append
}
</code>```

This currently appends to the file if it exists (or creates one if it doesnt)

i want to create one everytime a NEW session is started. only append to the file if you are in the same session

how do i do that?

答:
This is one of the few cases where global variables are useful, because they can persist through the entire session. In this example I am using them to set the unique filename (in this case today's date), to log to:

```<code>function Write-Host($object)
{
    if($global:LogFile -eq $null)
    {
        $global:LogFile = ".\LOG-$(Get-Date -Format 'yyyy-MM-dd').txt"
    }

    $object | tee $global:LogFile -Append
}
</code>```

--- Edit: ---

From comments, if you want to have a new file on the start of session, and append during the session, we can still use the global variable to determine the start of a session, but we simply use the check to remove the file at the start, and leave the Append to the Tee:

```<code>function Write-Host($object)
{
    if($global:LogFile -eq $null)
    {
        $global:LogFile = ".\LOG.txt"
        Remove-Item $global:LogFile -ErrorAction SilentlyContinue
    }

    $object | tee $global:LogFile -Append
}
</code>```

--- Edit 2: ---

From second Comments:

Remove-Item is a different animal because it has no output by default. Indeed, the only way to get any output is to add the -Verbose parameter. But the Tee-Object doesn't capture the Verbose stream. To get around this, we have to use two tricks. First, we specify the -Verbose parameter (to get an output), with a redirect (about_Redirection), to redirect the Verbose stream (4) to the standard Success (1) / Information stream. This would allow the Tee-Object to capture the information from the Remove-Item cmdlet:

```<code>Remove-Item test.txt -Verbose 4>&1 | Tee-Object out.txt
</code>```

Body:
I have a function to convert any write-hosts in the script (keeping them for coloring purposes later) to tee object

function Write-Host($object)
{
    $object | tee .\LOG.txt -Append
}

This currently appends to the file if it exists (or creates one if it doesnt)

i want to create one everytime a NEW session is started. only append to the file if you are in the same session

how do i do that?

Body:
This is one of the few cases where global variables are useful, because they can persist through the entire session. In this example I am using them to set the unique filename (in this case today's date), to log to:

function Write-Host($object)
{
    if($global:LogFile -eq $null)
    {
        $global:LogFile = ".\LOG-$(Get-Date -Format 'yyyy-MM-dd').txt"
    }

    $object | tee $global:LogFile -Append
}

--- Edit: ---

From comments, if you want to have a new file on the start of session, and append during the session, we can still use the global variable to determine the start of a session, but we simply use the check to remove the file at the start, and leave the Append to the Tee:

function Write-Host($object)
{
    if($global:LogFile -eq $null)
    {
        $global:LogFile = ".\LOG.txt"
        Remove-Item $global:LogFile -ErrorAction SilentlyContinue
    }

    $object | tee $global:LogFile -Append
}

--- Edit 2: ---

From second Comments:

Remove-Item is a different animal because it has no output by default. Indeed, the only way to get any output is to add the -Verbose parameter. But the Tee-Object doesn't capture the Verbose stream. To get around this, we have to use two tricks. First, we specify the -Verbose parameter (to get an output), with a redirect (about_Redirection), to redirect the Verbose stream (4) to the standard Success (1) / Information stream. This would allow the Tee-Object to capture the information from the Remove-Item cmdlet:

Remove-Item test.txt -Verbose 4>&1 | Tee-Object out.txt


问:
How can I use an ES6 import in Node.js?
I'm trying to get the hang of ES6 imports in Node.js and am trying to use the syntax provided in this example:

Cheatsheet Link

I'm looking through the support table, but I was not able to find what version supports the new import statements (I tried looking for the text import/require). I'm currently running Node.js 8.1.2 and also believe that since the cheatsheet is referring to .js files it should work with .js files.

As I run the code (taken from the cheatsheet's first example):

```<code>import { square, diag } from 'lib';
</code>```

I get the error:

SyntaxError: Unexpected token import.

Reference to library I'm trying to import:

```<code>//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}
</code>```

What am I missing and how can I get node to recognize my import statement?

答:
Using Node.js v12.2.0, I can import all standard modules like this:

```<code>import * as Http from 'http'
import * as Fs from 'fs'
import * as Path from 'path'
import * as Readline from 'readline'
import * as Os from 'os'
</code>```

Versus what I did before:

```<code>const
  Http = require('http')
  ,Fs = require('fs')
  ,Path = require('path')
  ,Readline = require('readline')
  ,Os = require('os')
</code>```

Any module that is an ECMAScript module can be imported without having to use an .mjs extension as long as it has this field in its package.json file:

```<code>"type": "module"
</code>```

So make sure you put such a package.json file in the same folder as the module you're making.

And to import modules not updated with ECMAScript module support, you can do like this:

```<code>// Implement the old require function
import { createRequire } from 'module'
const require = createRequire(import.meta.url)

// Now you can require whatever
const
  WebSocket = require('ws')
  ,Mime = require('mime-types')
  ,Chokidar = require('chokidar')
</code>```

And of course, do not forget that this is needed to actually run a script using module imports (not needed after v13.2):

```<code>node --experimental-modules my-script-that-use-import.js
</code>```

And that the parent folder needs this package.json file for that script to not complain about the import syntax:

```<code>{
  "type": "module"
}
</code>```

If the module you want to use has not been updated to support being imported using the import syntax then you have no other choice than using require (but with my solution above that is not a problem).

I also want to share this piece of code which implements the missing __filename and __dirname constants in modules:

import {fileURLToPath} from 'url'
import {dirname} from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)
```

Title: How can I use an ES6 import in Node.js?

Body:
I'm trying to get the hang of ES6 imports in Node.js and am trying to use the syntax provided in this example:

Cheatsheet Link

I'm looking through the support table, but I was not able to find what version supports the new import statements (I tried looking for the text import/require). I'm currently running Node.js 8.1.2 and also believe that since the cheatsheet is referring to .js files it should work with .js files.

As I run the code (taken from the cheatsheet's first example):

import { square, diag } from 'lib';

I get the error:

SyntaxError: Unexpected token import.

Reference to library I'm trying to import:

//------ lib.js ------
export const sqrt = Math.sqrt;
export function square(x) {
    return x * x;
}
export function diag(x, y) {
    return sqrt(square(x) + square(y));
}

What am I missing and how can I get node to recognize my import statement?

Body:
Using Node.js v12.2.0, I can import all standard modules like this:

import * as Http from 'http'
import * as Fs from 'fs'
import * as Path from 'path'
import * as Readline from 'readline'
import * as Os from 'os'

Versus what I did before:

const
  Http = require('http')
  ,Fs = require('fs')
  ,Path = require('path')
  ,Readline = require('readline')
  ,Os = require('os')

Any module that is an ECMAScript module can be imported without having to use an .mjs extension as long as it has this field in its package.json file:

"type": "module"

So make sure you put such a package.json file in the same folder as the module you're making.

And to import modules not updated with ECMAScript module support, you can do like this:

// Implement the old require function
import { createRequire } from 'module'
const require = createRequire(import.meta.url)

// Now you can require whatever
const
  WebSocket = require('ws')
  ,Mime = require('mime-types')
  ,Chokidar = require('chokidar')

And of course, do not forget that this is needed to actually run a script using module imports (not needed after v13.2):

node --experimental-modules my-script-that-use-import.js

And that the parent folder needs this package.json file for that script to not complain about the import syntax:

{
  "type": "module"
}

If the module you want to use has not been updated to support being imported using the import syntax then you have no other choice than using require (but with my solution above that is not a problem).

I also want to share this piece of code which implements the missing __filename and __dirname constants in modules:

import {fileURLToPath} from 'url'
import {dirname} from 'path'
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)


问:
How to stop console window from closing immediately | GNAT - GPS
I have Ada program that runs and compile perfectly using GNAT - GPS. When I run its exe file and provide user input then instead of saying "Press any key to continue", the exe closes immediately.

I have searched for it online alot but i only found info related to c/c++/visual studio console window using system('pause'); OR Console.Readline().

Is there any way around for this in Ada lanaguage?

答:
The answer from @DeeDee is more portable and only Ada and the preferable way to go, so my answer is just if you are looking for a "windows" way to do it.

I think there is a linker option for it, but I couldn't find it.  A more manual way is to bind the system() command from C and give it a "pause" command and place it at the end of your program:

with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C.Strings;

procedure Main is

   function System(Str : Interfaces.c.strings.chars_ptr) return Interfaces.C.int
      with Import,
      Convention => C,
      External_Name => "system";

   procedure Pause is
      Command : Interfaces.c.Strings.chars_ptr
         := Interfaces.C.Strings.New_String("pause");
      Result  : Interfaces.C.int
         := System(Command);
   begin
      Interfaces.C.Strings.Free(Command);
   end Pause;

begin
   Put_Line("Hello World");
   Pause;
end Main;
```

I know you mentioned seeing about pause already, but just wanted to show an example.

Body:
The answer from @DeeDee is more portable and only Ada and the preferable way to go, so my answer is just if you are looking for a "windows" way to do it.

I think there is a linker option for it, but I couldn't find it.  A more manual way is to bind the system() command from C and give it a "pause" command and place it at the end of your program:

with Ada.Text_IO; use Ada.Text_IO;
with Interfaces.C.Strings;

procedure Main is

   function System(Str : Interfaces.c.strings.chars_ptr) return Interfaces.C.int
      with Import,
      Convention => C,
      External_Name => "system";

   procedure Pause is
      Command : Interfaces.c.Strings.chars_ptr
         := Interfaces.C.Strings.New_String("pause");
      Result  : Interfaces.C.int
         := System(Command);
   begin
      Interfaces.C.Strings.Free(Command);
   end Pause;

begin
   Put_Line("Hello World");
   Pause;
end Main;

I know you mentioned seeing about pause already, but just wanted to show an example.


问:
 border does not enclose all of the div's elements
i'm now starting designing with proper mark-up and organization.
and now, i have  problem with my div border. it does not enclose all ot the div's content.

this is my html snippet:

```<code>  <div id="paneMiddle">
  <div id="subPaneLatestItems">
        <p id="latestItemsTitle">Latest Shop Items:</p>
        <div>
        <img src="img/flower1.jpg" />
        <span id="itemName">Ballpen</span>
        <br/><span id="itemPrice">Php 90.00</span>
        </div>
     </div></div>
</code>```

and here's my css:

```<code>div#paneMiddle>div{
/*All divs that are children of div#paneMiddle*/
width:590px;
margin:5px 5px 5px 5px;
position:relative;
border-color:#FFCC33;
border-style:solid;
border-width:thin;
position:relative;
}
</code>```

why doesn't this work?
thanks

答:
Just something to note your image  doesn't have a title or more importantly alternate text maybe you haven't got around to this, but its point that needs looking into. Alternate text allows a users to understand what might have been there if for example the images don't load up or they have images turned off. It is also an accessbility issue if user are using a screen reader a description of the image is useful to them.</p>

```<code><img src="img/flower1.jpg" alt="Photo of a Daisy" title="This is a Daisy" />
</code>```

Title: <div> border does not enclose all of the div's elements

Body:
i'm now starting designing with proper mark-up and organization.
and now, i have  problem with my div border. it does not enclose all ot the div's content.

this is my html snippet:

Latest Shop Items:

        Ballpen

Php 90.00

and here's my css:

div#paneMiddle>div{
/*All divs that are children of div#paneMiddle*/
width:590px;
margin:5px 5px 5px 5px;
position:relative;
border-color:#FFCC33;
border-style:solid;
border-width:thin;
position:relative;
}

why doesn't this work?
thanks

LastEditorDisplayName: Pim Jager

Body:
Just something to note your image  doesn't have a title or more importantly alternate text maybe you haven't got around to this, but its point that needs looking into. Alternate text allows a users to understand what might have been there if for example the images don't load up or they have images turned off. It is also an accessbility issue if user are using a screen reader a description of the image is useful to them.

<img src="img/flower1.jpg" alt="Photo of a Daisy" title="This is a Daisy" />

OwnerDisplayName: Cool Hand Luke UK


问:
VBA changes Excel 2002 -> Excel 2007
Where can I find a complete list of changes in VBA from Excel XP (2002) to Excel 2007?  I have a workbook that relies heavily on VBA which I have been working on in 2002, and when I opened it in 2007, I noticed that some things had changed.  For instance, my workbook does lots of 3d rotation; I discovered that Shape.ThreeD.RotationX has become Shape.ThreeD.RotationY and vice-versa.  I also discovered that I have to negate the rotation values, so that

```<code>Shape.ThreeD.RotationX = 90
</code>```

becomes

```<code>Shape.ThreeD.RotationY = -90
</code>```

I am sure that there are other changes as well, which I have probably missed.  I haven't seen the above changes detailed anywhere, so I would like to know:

Which sites detail changes such as the ones I have outline above?

答: In my experience, you can try to make changes based on an incomplete "Exhaustive" list, but you still have to test the code and see what doesn't work the way you expect. After making changes so it works in 2007, you also need to test in the original version, so it still works for those users.</p>

Title: VBA changes Excel 2002 -> Excel 2007

Body:
Where can I find a complete list of changes in VBA from Excel XP (2002) to Excel 2007?  I have a workbook that relies heavily on VBA which I have been working on in 2002, and when I opened it in 2007, I noticed that some things had changed.  For instance, my workbook does lots of 3d rotation; I discovered that Shape.ThreeD.RotationX has become Shape.ThreeD.RotationY and vice-versa.  I also discovered that I have to negate the rotation values, so that

Shape.ThreeD.RotationX = 90

becomes

Shape.ThreeD.RotationY = -90

I am sure that there are other changes as well, which I have probably missed.  I haven't seen the above changes detailed anywhere, so I would like to know:

Which sites detail changes such as the ones I have outline above?


问:
Bash list comprehension or map
Say I have a string in bash -

NAMES="file1 file2 file3"
```

<p>How do I map it to the following string which I will then use as part of a command?</p>

<pre class="lang-sh prettyprint-override"><code>MAPPED="-i file1.txt -i file2.txt -i file3.txt"
</code>```

For an example of exactly what I mean, here's the equivalent python code -

names = "file1 file2 file3"
mapped = ' '.join("-i " + x + ".txt" for x in names.split())
```

答:
You should use arrays instead of strings:

```<code>names=(file1 file2 file3)

# Add suffix
names=("${names[@]/%/.txt}")

# Build new array with "-i" elements
for name in "${names[@]}"; do
    mapped+=(-i "$name")
done

# Show result
declare -p mapped
</code>```

resulting in this output:

```<code>declare -a mapped=([0]="-i" [1]="file1.txt" [2]="-i" [3]="file2.txt" [4]="-i" [5]="file3.txt")
</code>```

This can now be used in commands like this:

```<code>cmd "${mapped[@]}"
</code>```

See BashFAQ/050 regarding the rationale behind putting commands into strings vs. arrays.

Title: Bash list comprehension or map

Body:
Say I have a string in bash -

NAMES="file1 file2 file3"

How do I map it to the following string which I will then use as part of a command?

MAPPED="-i file1.txt -i file2.txt -i file3.txt"

For an example of exactly what I mean, here's the equivalent python code -

names = "file1 file2 file3"
mapped = ' '.join("-i " + x + ".txt" for x in names.split())

Body:
You should use arrays instead of strings:

names=(file1 file2 file3)

# Add suffix
names=("${names[@]/%/.txt}")

# Build new array with "-i" elements
for name in "${names[@]}"; do
    mapped+=(-i "$name")
done

# Show result
declare -p mapped

resulting in this output:

declare -a mapped=([0]="-i" [1]="file1.txt" [2]="-i" [3]="file2.txt" [4]="-i" [5]="file3.txt")

This can now be used in commands like this:

cmd "${mapped[@]}"

See BashFAQ/050 regarding the rationale behind putting commands into strings vs. arrays.


问:
How to pause C# code for ten minutes at the start of each hour
I'm trying to get my application to pause for nine to ten minutes at the start of each hour.

I've been able to get my application to pause for that amount of time

```<code>Random waitTime = new Random();
int milliseconds = waitTime.Next(3000, 5000);
System.Threading.Thread.Sleep(milliseconds);
</code>```

I shortened the time in my code for testing purposes.

Now I need to tie that into something that checks if the current time is in between (4:00, 4:10) or (5:00, 5:10) or (21:00, 1:00) and resume if it is not.

答:
You wish to continue with your current pattern of using Thread.Sleep(n), can use a simple loop.

```<code>while (DateTime.Now.Minute <=10)
{
    Thread.Sleep(1000);
}
</code>```

In general though it would be better to schedule the task or at least to use async instead of blocking the thread.

Body:
I'm trying to get my application to pause for nine to ten minutes at the start of each hour.

I've been able to get my application to pause for that amount of time

Random waitTime = new Random();
int milliseconds = waitTime.Next(3000, 5000);
System.Threading.Thread.Sleep(milliseconds);

I shortened the time in my code for testing purposes.

Now I need to tie that into something that checks if the current time is in between (4:00, 4:10) or (5:00, 5:10) or (21:00, 1:00) and resume if it is not.

Body:
You wish to continue with your current pattern of using Thread.Sleep(n), can use a simple loop.

while (DateTime.Now.Minute <=10)
{
    Thread.Sleep(1000);
}

In general though it would be better to schedule the task or at least to use async instead of blocking the thread.


问:
sstabloader compatibility between datastax cassandra and apache cassandra
Does sstabloader work between datastax cassandra and apache cassandra?

I'm trying to copy data from dse 5.0.7 to apache 3.11.1 cassandra version

答:
It shouldn't be an issue to use it to export between Datastax Cassandra and the open source version, if they are the same versions.

Having said that, please note that DSE 5.0.7 uses Apache 3.0.11, as explained in the release notes. This means that you should import the data to a cluster with that version, and once that this is completed, upgrade to 3.11.1.

Disclosure: I'm not a DSE user, I don't have a way to test this.