问:
Redraw canvas in Android
I am making an Android 2.2 application using Eclipse. My application should draw
images by clicking on buttons.

I have two buttons at the bottom of the screen, and I need to draw the shape in the same screen that has the buttons. I used FrameLayout in which the shapes are drawn.

My problem is, the two shapes are overwriting, so I need to redraw the canvas.

My Code

```<code>package draw.tab;

import android.app.Activity;
//import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;

public class DrawActivity extends Activity implements OnClickListener
{
    DrawView drawview;
    CircleView circleView;
    FrameLayout Frame;
    Button square,circle;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Frame=(FrameLayout)findViewById(R.id.MyFrame);
        drawview=new DrawView(this);
        circleView=new CircleView(this);

        square=(Button)findViewById(R.id.buttonTest);
        square.setOnClickListener(this);
        circle=(Button)findViewById(R.id.circleButton);
        circle.setOnClickListener(this);
    }

    public void onClick(View v)
    {
        switch (v.getId()) {
            case R.id.circleButton:
                Frame.addView(circleView);
                /*circleView.setBackgroundColor(Color.rgb(40,100,20));
                circleView.findViewById(R.id.CircleViewId);
                setContentView(circleView);*/
                break;
            case R.id.buttonTest:
                Frame.addView(drawview);
                /*drawview.setBackgroundColor(Color.WHITE);
                drawview.findViewById(R.id.DrawViewId);
                drawview.layout(400,0,200,450);
                setContentView(drawview);*/
                break;
        }
    }
}
</code>```

DrawView.java

```<code>package draw.tab;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class DrawView extends View
{
    Paint paint=new Paint();
    Path pat=new Path();

    public DrawView(Context context)
    {
        super(context);
        paint.setColor(Color.RED);
        paint.setStyle(Style.STROKE);
        //context.clearRect(70,140,400,450);
        //pat.addRect(50,40,250,400,Path.Direction.CW);
    }

    public DrawView(Context con,AttributeSet atts)
    {
        super(con,atts);
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        //canvas.drawPath(pat,paint);
        canvas.drawLine(20,40,450,40,paint);//horizontal top
        canvas.drawRect(70,140,400,450,paint);
        canvas.drawLine(20,40,20,600,paint);//vertical left
        canvas.drawLine(20,600,450,600,paint);//horizontal bottom
        canvas.drawLine(450,40,450,600,paint);//vertical right
        //this.invalidate();
    }
}
</code>```

CircleView.java

```<code>package draw.tab;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class CircleView extends View
{
    Paint p=new Paint();
    Path path=new Path();

    public CircleView(Context context)
    {
        super(context);
        p.setColor(Color.BLUE);
        p.setStyle(Style.STROKE);
        //path.addCircle(250,250,50,Path.Direction.CW);
    }

    public CircleView(Context con,AttributeSet atts)
    {
        super(con,atts);
    }

    public void onDraw(Canvas c)
    {
        //c.drawPath(path,p);
        //c.save();
        c.drawLine(20,40,450,40, p);//horizontal top
        c.drawCircle(250,350,100,p);
        c.drawLine(20,40,20,600,p);//vertical left
        c.drawLine(20,600,450,600,p);//horizontal bottom
        c.drawLine(450,40,450,600,p);//vertical right
        //c.restore();
        this.invalidate();
    }
}
</code>```

main.xml

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

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:visibility="visible"
    android:id="@+id/MyFrame"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <draw.tab.DrawView
    android:id="@+id/DrawViewId"
    android:layout_width="320dp"
    android:layout_height="600dp">
    </draw.tab.DrawView>

    <draw.tab.CircleView
    android:id="@+id/CircleViewId"
    android:layout_width="320dp"
    android:layout_height="600dp">
    </draw.tab.CircleView>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:gravity="bottom">

     <Button
        android:layout_height="wrap_content"
        android:text="Circle"
        android:id="@+id/circleButton"
        android:layout_width="160dp">
    </Button>

    <Button
        android:layout_height="wrap_content"
        android:text="Square"
        android:id="@+id/buttonTest"
        android:layout_width="160dp">
    </Button>
</LinearLayout>

</FrameLayout>
</code>```

The above is all my code. The shapes are overwriting, so I want to remove and redraw the canvas or redraw without overwriting.

答: Try calling invalidate() on your view.</p>

Title: Redraw canvas in Android

Body:
I am making an Android 2.2 application using Eclipse. My application should draw
images by clicking on buttons.

I have two buttons at the bottom of the screen, and I need to draw the shape in the same screen that has the buttons. I used FrameLayout in which the shapes are drawn.

My problem is, the two shapes are overwriting, so I need to redraw the canvas.

My Code

package draw.tab;

import android.app.Activity;
//import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;

public class DrawActivity extends Activity implements OnClickListener
{
    DrawView drawview;
    CircleView circleView;
    FrameLayout Frame;
    Button square,circle;

    /** Called when the activity is first created. */

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Frame=(FrameLayout)findViewById(R.id.MyFrame);
        drawview=new DrawView(this);
        circleView=new CircleView(this);

        square=(Button)findViewById(R.id.buttonTest);
        square.setOnClickListener(this);
        circle=(Button)findViewById(R.id.circleButton);
        circle.setOnClickListener(this);
    }

    public void onClick(View v)
    {
        switch (v.getId()) {
            case R.id.circleButton:
                Frame.addView(circleView);
                /*circleView.setBackgroundColor(Color.rgb(40,100,20));
                circleView.findViewById(R.id.CircleViewId);
                setContentView(circleView);*/
                break;
            case R.id.buttonTest:
                Frame.addView(drawview);
                /*drawview.setBackgroundColor(Color.WHITE);
                drawview.findViewById(R.id.DrawViewId);
                drawview.layout(400,0,200,450);
                setContentView(drawview);*/
                break;
        }
    }
}

DrawView.java

package draw.tab;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class DrawView extends View
{
    Paint paint=new Paint();
    Path pat=new Path();

    public DrawView(Context context)
    {
        super(context);
        paint.setColor(Color.RED);
        paint.setStyle(Style.STROKE);
        //context.clearRect(70,140,400,450);
        //pat.addRect(50,40,250,400,Path.Direction.CW);
    }

    public DrawView(Context con,AttributeSet atts)
    {
        super(con,atts);
    }

    @Override
    public void onDraw(Canvas canvas)
    {
        //canvas.drawPath(pat,paint);
        canvas.drawLine(20,40,450,40,paint);//horizontal top
        canvas.drawRect(70,140,400,450,paint);
        canvas.drawLine(20,40,20,600,paint);//vertical left
        canvas.drawLine(20,600,450,600,paint);//horizontal bottom
        canvas.drawLine(450,40,450,600,paint);//vertical right
        //this.invalidate();
    }
}

CircleView.java

package draw.tab;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;

public class CircleView extends View
{
    Paint p=new Paint();
    Path path=new Path();

    public CircleView(Context context)
    {
        super(context);
        p.setColor(Color.BLUE);
        p.setStyle(Style.STROKE);
        //path.addCircle(250,250,50,Path.Direction.CW);
    }

    public CircleView(Context con,AttributeSet atts)
    {
        super(con,atts);
    }

    public void onDraw(Canvas c)
    {
        //c.drawPath(path,p);
        //c.save();
        c.drawLine(20,40,450,40, p);//horizontal top
        c.drawCircle(250,350,100,p);
        c.drawLine(20,40,20,600,p);//vertical left
        c.drawLine(20,600,450,600,p);//horizontal bottom
        c.drawLine(450,40,450,600,p);//vertical right
        //c.restore();
        this.invalidate();
    }
}

main.xml

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

<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:visibility="visible"
    android:id="@+id/MyFrame"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <draw.tab.DrawView
    android:id="@+id/DrawViewId"
    android:layout_width="320dp"
    android:layout_height="600dp">
    </draw.tab.DrawView>

    <draw.tab.CircleView
    android:id="@+id/CircleViewId"
    android:layout_width="320dp"
    android:layout_height="600dp">
    </draw.tab.CircleView>

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="horizontal"
    android:gravity="bottom">

     <Button
        android:layout_height="wrap_content"
        android:text="Circle"
        android:id="@+id/circleButton"
        android:layout_width="160dp">
    </Button>

    <Button
        android:layout_height="wrap_content"
        android:text="Square"
        android:id="@+id/buttonTest"
        android:layout_width="160dp">
    </Button>
</LinearLayout>

</FrameLayout>

The above is all my code. The shapes are overwriting, so I want to remove and redraw the canvas or redraw without overwriting.

Body: Try calling invalidate() on your view.


来源: stackexchange

问:
Connect Python to SQL Server from Ubuntu
My OS is Windows 10

I have SQL Server installed on my machine

I am trying to access SQL Server from Ubuntu bash

Here is my code

```<code>import pyodbc

ConnectionString = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=DELLG3;DATABASE=R3;UID=sa;PWD=******;"

conn = pyodbc.connect(ConnectionString)
</code>```

I am getting this error

```<code>asmgx@DELLG3:~$ python3 /mnt/c/py/28autosk.py
Traceback (most recent call last):
  File "/mnt/c/py/28autosk.py", line 58, in <module>
    conn = pyodbc.connect(ConnectionString)
pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')
</code>```

I tried all these links to help me fix the problem and have been googling and trying to resolve the problem

https://www.microsoft.com/en-us/sql-server/developer-get-started/python/ubuntu/?rtc=1

https://askubuntu.com/questions/1147280/how-to-install-mssql-server-in-ubuntu-19-04

https://askubuntu.com/questions/462094/unable-to-install-libssl1-0-0i386-due-to-unmet-dependencies

Anyone can help me connect to SQL Server from Ubuntu?

答:
You should try that

pyodbc.connect ('DRIVER={ODBC Driver 17 for SQL Server};SERVER=localhost;DATABASE=dbname;UID=sa;PWD=********')

ContentLicense: CC BY-SA 4.0

Body:
My OS is Windows 10

I have SQL Server installed on my machine

I am trying to access SQL Server from Ubuntu bash

Here is my code

import pyodbc

ConnectionString = "DRIVER={ODBC Driver 17 for SQL Server};SERVER=DELLG3;DATABASE=R3;UID=sa;PWD=******;"

conn = pyodbc.connect(ConnectionString)

I am getting this error

asmgx@DELLG3:~$ python3 /mnt/c/py/28autosk.py
Traceback (most recent call last):
  File "/mnt/c/py/28autosk.py", line 58, in <module>
    conn = pyodbc.connect(ConnectionString)
pyodbc.OperationalError: ('HYT00', '[HYT00] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0) (SQLDriverConnect)')

I tried all these links to help me fix the problem and have been googling and trying to resolve the problem

https://www.microsoft.com/en-us/sql-server/developer-get-started/python/ubuntu/?rtc=1

https://askubuntu.com/questions/1147280/how-to-install-mssql-server-in-ubuntu-19-04

https://askubuntu.com/questions/462094/unable-to-install-libssl1-0-0i386-due-to-unmet-dependencies

Anyone can help me connect to SQL Server from Ubuntu?


问:
Argument passed in must be a string of 24 hex characters - I think it is
I have a method to find a document in my database based on its ObjectID:

```<code>      console.log('id: ' + id + ' type: ' + typeof id);
      collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
        if (error) {
          callback(error);
        } else {
           callback(null, doc);
        }
      });
</code>```

When I run it I get the following error:

```<code>/myPath/node_modules/monk/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/base.js:245
    throw message;
          ^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/myPath/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:38:11)
at /myPath/collectionDriver.js:134:41
</code>```

This refers to the collection.findOne() line above.

The console log I have before that call outputs the id as a string of 24 hex characters:

```<code>id: "55153a8014829a865bbf700d" type: string
</code>```

Before this I convert the id from an object to a string using JSON.stringify() but it appears to work successfully as shown in my console.log.

Running db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")}) in Robomongo brings back the expected result.

答:
Actually the Id you are fetching have whitespaces in it so adding trim() to your id will work

```<code>const id = (req.params.id).trim();
const result =  await deleteOne({_id:new mongodb.ObjectId(id)});
</code>```

while using this code keep in mind that your function should be async and mongodb should have been imported.

ContentLicense: CC BY-SA 3.0

Body:
I have a method to find a document in my database based on its ObjectID:

      console.log('id: ' + id + ' type: ' + typeof id);
      collection.findOne({'_id':new ObjectID(id)}, function(error,doc) {
        if (error) {
          callback(error);
        } else {
           callback(null, doc);
        }
      });

When I run it I get the following error:

/myPath/node_modules/monk/node_modules/mongoskin/node_modules/mongodb/lib/mongodb/connection/base.js:245
    throw message;
          ^
Error: Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
at new ObjectID (/myPath/node_modules/mongodb/node_modules/bson/lib/bson/objectid.js:38:11)
at /myPath/collectionDriver.js:134:41

This refers to the collection.findOne() line above.

The console log I have before that call outputs the id as a string of 24 hex characters:

id: "55153a8014829a865bbf700d" type: string

Before this I convert the id from an object to a string using JSON.stringify() but it appears to work successfully as shown in my console.log.

Running db.myCollection.findOne({_id : ObjectId("55153a8014829a865bbf700d")}) in Robomongo brings back the expected result.

Body:
Actually the Id you are fetching have whitespaces in it so adding trim() to your id will work

const id = (req.params.id).trim();
const result =  await deleteOne({_id:new mongodb.ObjectId(id)});

while using this code keep in mind that your function should be async and mongodb should have been imported.


问:
In Parse() function, why the time.ANSIC layout didn't work in Go?
I am currently studying time library and I am not sure why the time.ANSIC at layout part didn't work what I expected.
In Parse() function there is a syntax  func Parse (layout, value string) and based on my understanding I can use in layout part like time.UnixDate, ANSIC, RFC3339 etc.

When I code like below

```<code>const layout = "Jan 2, 2006 at 3:04pm (MST)"
    sm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")
    fmt.Println(sm)
</code>```

It works as well and I got 2014-02-04 18:05:00 +0000 PST.

However, when I add time.ANSIC at layout part

```<code>tm, _ := time.Parse(time.ANSIC, "Feb 4, 2014 at 6:05pm (PST)")
    fmt.Println(tm)
</code>```

I got 0001-01-01 00:00:00 +0000 UTC.

I am not sure why do I get any time. I really appreciate your help!

答:
It is not idiomatic Go to discard errors returned from any of the methods in standard library. Always check them before processing your returned value.

If you had noticed the error from your parse function, you would see that the layout for time.ANSIC is not compatible with the date string that you are trying to parse

parsing time "Feb 4, 2014 at 6:05pm (PST)" as "Mon Jan _2 15:04:05 2006": cannot parse "Feb 4, 2014 at 6:05pm (PST)" as "Mon"

From https://pkg.go.dev/time#Parse

The second argument must be parseable using the format string (layout) provided as the first argument.

https://go.dev/play/p/jU-EvL5W3Hp

Body:
I am currently studying time library and I am not sure why the time.ANSIC at layout part didn't work what I expected.
In Parse() function there is a syntax  func Parse (layout, value string) and based on my understanding I can use in layout part like time.UnixDate, ANSIC, RFC3339 etc.

When I code like below

const layout = "Jan 2, 2006 at 3:04pm (MST)"
    sm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)")
    fmt.Println(sm)

It works as well and I got 2014-02-04 18:05:00 +0000 PST.

However, when I add time.ANSIC at layout part

tm, _ := time.Parse(time.ANSIC, "Feb 4, 2014 at 6:05pm (PST)")
    fmt.Println(tm)

I got 0001-01-01 00:00:00 +0000 UTC.

I am not sure why do I get any time. I really appreciate your help!


问:
When is it appropriate to use df.value_counts() vs df.groupby('...').count()?
I've heard in Pandas there's often multiple ways to do the same thing, but I was wondering –

If I'm trying to group data by a value within a specific column and count the number of items with that value, when does it make sense to use df.groupby('colA').count() and when does it make sense to use df['colA'].value_counts() ?

答:
in simple words: .value_counts() Return a Series containing counts of unique rows in the DataFrame which means it counts up the individual values in a specific row and reports how many of the values are in the column:
imagine we have a dataframe like:

```<code>df = pd.DataFrame({'first_name': ['John', 'Anne', 'John', 'Beth'],

                   'middle_name': ['Smith', pd.NA, pd.NA, 'Louise']})

first_name  middle_name
0   John    Smith
1   Anne    <NA>
2   John    <NA>
3   Beth    Louise
</code>```

then we apply value_counts on it:

```<code>    df.value_counts()

first_name  middle_name
Beth        Louise         1
John        Smith          1
dtype: int64
</code>```

as you can see it didn't count rows with NA values.
however count() count non-NA cells for each column or row.
in our example:

```<code>df.count()

first_name     4
middle_name    2
dtype: int64
</code>```

Body:
in simple words: .value_counts() Return a Series containing counts of unique rows in the DataFrame which means it counts up the individual values in a specific row and reports how many of the values are in the column:
imagine we have a dataframe like:

df = pd.DataFrame({'first_name': ['John', 'Anne', 'John', 'Beth'],

                   'middle_name': ['Smith', pd.NA, pd.NA, 'Louise']})

first_name  middle_name
0   John    Smith
1   Anne    <NA>
2   John    <NA>
3   Beth    Louise

then we apply value_counts on it:

    df.value_counts()

first_name  middle_name
Beth        Louise         1
John        Smith          1
dtype: int64

as you can see it didn't count rows with NA values.
however count() count non-NA cells for each column or row.
in our example:

df.count()

first_name     4
middle_name    2
dtype: int64


问:
Expo-react-native :Couldn't adb reverse: device 'adb' not found
I am using react-native-expo for mobile app development.
I use an android emulator for the app, vscode editor for development.
It started showing me this error from  few days.

```<code>› Opening on Android...
Couldn't adb reverse: device 'adb' not found
› Opening exp://10.0.46.81:19000 on Device adb
Couldn't start project on Android: Error running adb: device 'adb' not found
› Press ? │ show all commands
</code>```

I tried wiping the emulator, tapping on the build number in the emulator, but nothing worked out.

I've deleted the virtual devices and created new one. It worked for one time and again this process isn't working.
there isn't much about this on the internet.
need help.

答:
I had the same problem. Emulator started working after this:

Delete caches from Android Studio

Wipe data from your emulator

Cold boot to restart

When I was solving this problem I also ended up doing these:

Check Android studio updates

Reinstalled Android studio

Check SDK updates from SDK tools: SDK Manager -> Android SDK -> SDK tools. You can see if there is a new update available on the right.

Body:
I am using react-native-expo for mobile app development.
I use an android emulator for the app, vscode editor for development.
It started showing me this error from  few days.

› Opening on Android...
Couldn't adb reverse: device 'adb' not found
› Opening exp://10.0.46.81:19000 on Device adb
Couldn't start project on Android: Error running adb: device 'adb' not found
› Press ? │ show all commands

I tried wiping the emulator, tapping on the build number in the emulator, but nothing worked out.

I've deleted the virtual devices and created new one. It worked for one time and again this process isn't working.
there isn't much about this on the internet.
need help.


问:
Improve Query to not have to run multiple times?
I currently have this working query. However, I have to run it multiple times with different parameters to get the total result. I'm wondering if there's a way I can run a loop or create a column for each query within one query so I can get the complete result without commenting in specific params and then commenting out (Running it multiple times). Is there a way to create a column for ether, BTC, tether, and usd coin?</p>
```<code>SELECT DISTINCT
  contact.account_id,
  contact.email,
  contact.tax_country,
  crypto.total_crypto
FROM
  (
    SELECT DISTINCT
      account_id,
      SUM(ABS(unit_count)) as total_crypto
    FROM
      beta.asset_transaction
    GROUP BY
      account_id, comments_1
    HAVING
    -- ((comments_1 = 'Sell Bitcoin' OR comments_1 = 'Buy Bitcoin') AND SUM(ABS(unit_count)) > '0.025')
    ((comments_1 = 'Sell Ether' OR comments_1 = 'Buy Ether') AND SUM(ABS(unit_count)) > '0.4')
    -- ((comments_1 = 'Sell Tether USD' OR comments_1 = 'Buy Tether USD') AND SUM(ABS(unit_count)) > '0.4')
      -- ((comments_1 = 'Sell USD Coin' OR comments_1 = 'Buy USD Coin') AND SUM(ABS(unit_count)) > '0.4')--   (asset_transfer_type = 'Sell Tether USD' AND SUM(ABS(unit_count)) > '1000')
  ) AS crypto
  INNER JOIN contact ON contact.account_id = crypto.account_id
  ORDER BY total_crypto DESC;
</code>```

答:
As Nick mentioned in the comments , the "group by" has "comments_1" but it is not there in column projection which needs fixed.
"Filter" clause can be used to create a column for each type of metrics. Here is the SQL which needs validated(could not validate as there is no sample data). From the output of this SQL , the column of interest can be visually chosen.</p>
```<code>with cte_unit_count
as
(
 select SUM(ABS(unit_count)) cnt from  beta.asset_transaction
)
SELECT DISTINCT
  contact.account_id,
  contact.email,
  contact.tax_country,
  crypto.crypto_bitcoin,
  crypto.crypto_ether,
  crypto.crypto_tether,
  crypto.usd_coin,
  crypto.usd_tether
FROM
  (
    SELECT DISTINCT
      account_id,
      SUM(ABS(unit_count)) filter (where  (comments_1 = 'Sell Bitcoin' OR comments_1 = 'Buy Bitcoin') and  cte_unit_count.cnt > '0.025' ) crypto_bitcoin,
      SUM(ABS(unit_count)) filter (where (comments_1 = 'Sell Ether' OR comments_1 = 'Buy Ether') and  cte_unit_count.cnt > '0.4' ) crypto_ether,
      SUM(ABS(unit_count)) filter (where(comments_1 = 'Sell Tether USD' OR comments_1 = 'Buy Tether USD') and  cte_unit_count.cnt > '0.4' ) crypto_tether,
      SUM(ABS(unit_count)) filter (where(comments_1 = 'Sell USD Coin' OR comments_1 = 'Buy USD Coin') AND cte_unit_count.cnt > '0.4') usd_coin ,
      SUM(ABS(unit_count)) filter (where asset_transfer_type = 'Sell Tether USD' AND cte_unit_count.cnt > '1000') ) usd_tether
    FROM
      beta.asset_transaction , cte_unit_count
    GROUP BY
      account_id, <...verify --->comments_1>
  ) AS crypto
  INNER JOIN contact ON contact.account_id = crypto.account_id
  order by <...whichever column you desire...>
</code>```

Body:
I currently have this working query. However, I have to run it multiple times with different parameters to get the total result. I'm wondering if there's a way I can run a loop or create a column for each query within one query so I can get the complete result without commenting in specific params and then commenting out (Running it multiple times). Is there a way to create a column for ether, BTC, tether, and usd coin?

SELECT DISTINCT
  contact.account_id,
  contact.email,
  contact.tax_country,
  crypto.total_crypto
FROM
  (
    SELECT DISTINCT
      account_id,
      SUM(ABS(unit_count)) as total_crypto
    FROM
      beta.asset_transaction
    GROUP BY
      account_id, comments_1
    HAVING
    -- ((comments_1 = 'Sell Bitcoin' OR comments_1 = 'Buy Bitcoin') AND SUM(ABS(unit_count)) > '0.025')
    ((comments_1 = 'Sell Ether' OR comments_1 = 'Buy Ether') AND SUM(ABS(unit_count)) > '0.4')
    -- ((comments_1 = 'Sell Tether USD' OR comments_1 = 'Buy Tether USD') AND SUM(ABS(unit_count)) > '0.4')
      -- ((comments_1 = 'Sell USD Coin' OR comments_1 = 'Buy USD Coin') AND SUM(ABS(unit_count)) > '0.4')--   (asset_transfer_type = 'Sell Tether USD' AND SUM(ABS(unit_count)) > '1000')
  ) AS crypto
  INNER JOIN contact ON contact.account_id = crypto.account_id
  ORDER BY total_crypto DESC;

Body:
As Nick mentioned in the comments , the "group by" has "comments_1" but it is not there in column projection which needs fixed.
"Filter" clause can be used to create a column for each type of metrics. Here is the SQL which needs validated(could not validate as there is no sample data). From the output of this SQL , the column of interest can be visually chosen.

with cte_unit_count
as
(
 select SUM(ABS(unit_count)) cnt from  beta.asset_transaction
)
SELECT DISTINCT
  contact.account_id,
  contact.email,
  contact.tax_country,
  crypto.crypto_bitcoin,
  crypto.crypto_ether,
  crypto.crypto_tether,
  crypto.usd_coin,
  crypto.usd_tether
FROM
  (
    SELECT DISTINCT
      account_id,
      SUM(ABS(unit_count)) filter (where  (comments_1 = 'Sell Bitcoin' OR comments_1 = 'Buy Bitcoin') and  cte_unit_count.cnt > '0.025' ) crypto_bitcoin,
      SUM(ABS(unit_count)) filter (where (comments_1 = 'Sell Ether' OR comments_1 = 'Buy Ether') and  cte_unit_count.cnt > '0.4' ) crypto_ether,
      SUM(ABS(unit_count)) filter (where(comments_1 = 'Sell Tether USD' OR comments_1 = 'Buy Tether USD') and  cte_unit_count.cnt > '0.4' ) crypto_tether,
      SUM(ABS(unit_count)) filter (where(comments_1 = 'Sell USD Coin' OR comments_1 = 'Buy USD Coin') AND cte_unit_count.cnt > '0.4') usd_coin ,
      SUM(ABS(unit_count)) filter (where asset_transfer_type = 'Sell Tether USD' AND cte_unit_count.cnt > '1000') ) usd_tether
    FROM
      beta.asset_transaction , cte_unit_count
    GROUP BY
      account_id, <...verify --->comments_1>
  ) AS crypto
  INNER JOIN contact ON contact.account_id = crypto.account_id
  order by <...whichever column you desire...>


问:
JAVASCRIPT: change background color of a div, when hover over it while pressing the mouse click down
I am trying to change the div background color when i hover over them clicking my mouse button.This is what i did so far. I want to make it like a drawing pen, so it won't change color when hover over but it will when hover over while pressing the mouse key.

const container = document.querySelector('.container');

function canvas(size) {
    container.style.setProperty('--grid-column', size);
    container.style.setProperty('--grid-row', size);

    for (let i = 0; i < size*size; i++) {
        const cell = document.createElement('div');
        cell.addEventListener('mouseover', changeColor);
        cell.addEventListener('mousedown', changeColor);
        container.appendChild(cell).className = 'grid-items';
    }
}
canvas(16)

function changeColor(e) {
    if (e.type == 'mouseover' && !mousedown) return
    else{
        let color1 = Math.floor(Math.random() * 256);
        let color2 = Math.floor(Math.random() * 256);
        let color3 = Math.floor(Math.random() * 256);

        e.target.style.backgroundColor = `rgb(${color1},${color2},${color3})`
    }
}```

live site : https://alucard2169.github.io/Etch-a-Sketch/

repo: https://github.com/Alucard2169/Etch-a-Sketch.git

答:
I found this to work the best

const container = document.querySelector('.container');
const button = document.createElement('button');
let size;

button.classList.add('clear');
button.innerText = 'CLEAR';
document.body.appendChild(button);

var mouseDown = false;
document.body.onmousedown = function() {
  mouseDown = true;
};
document.body.onmouseup = function() {
  mouseDown = false;
};

button.addEventListener('click', function() {
  container.innerHTML = '';
  size = prompt('what size do you want your grid to be: ');
  checkSize(size);
});

function canvas(size) {
  container.style.setProperty('--grid-column', size);
  container.style.setProperty('--grid-row', size);

  for (let i = 0; i < size * size; i++) {
    const cell = document.createElement('div');
    cell.addEventListener('mouseover', changeColor);
    cell.addEventListener('mousedown', changeColor);
    container.appendChild(cell).className = 'grid-items';
  }
}
canvas(16);

function changeColor(e) {
  if (mouseDown) {
    let color1 = Math.floor(Math.random() * 256);
    let color2 = Math.floor(Math.random() * 256);
    let color3 = Math.floor(Math.random() * 256);

    e.target.style.backgroundColor = `rgb(${color1},${color2},${color3})`;
  }
}

function checkSize(e) {
  if (e > 100) {
    alert("size can't be greater than 100");
    canvas(16);
  } else {
    canvas(e);
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: black;
  display: flex;
  height: 100vh;
  align-items: center;
  justify-content: center;
}

.container {
  display: grid;
  width: 25rem;
  height: 30rem;
  background: white;
  grid-template-columns: repeat(var(--grid-column), 1fr);
  grid-template-rows: repeat(var(--grid-row), 1fr)
}

.grid-items {}

.clear {
  padding: 1rem 2rem;
  border: none;
  border-radius: 10px;
  margin: 5rem 0 0 5rem;
}</code>```

```

In this if the user is pressing the mouse down over the canvas, the color changes as the mouse moves.

Body:
I am trying to change the div background color when i hover over them clicking my mouse button.This is what i did so far. I want to make it like a drawing pen, so it won't change color when hover over but it will when hover over while pressing the mouse key.

const container = document.querySelector('.container');

function canvas(size) {
    container.style.setProperty('--grid-column', size);
    container.style.setProperty('--grid-row', size);

    for (let i = 0; i < size*size; i++) {
        const cell = document.createElement('div');
        cell.addEventListener('mouseover', changeColor);
        cell.addEventListener('mousedown', changeColor);
        container.appendChild(cell).className = 'grid-items';
    }
}
canvas(16)

function changeColor(e) {
    if (e.type == 'mouseover' && !mousedown) return
    else{
        let color1 = Math.floor(Math.random() * 256);
        let color2 = Math.floor(Math.random() * 256);
        let color3 = Math.floor(Math.random() * 256);

        e.target.style.backgroundColor = `rgb(${color1},${color2},${color3})`
    }
}

live site : https://alucard2169.github.io/Etch-a-Sketch/

repo: https://github.com/Alucard2169/Etch-a-Sketch.git

Body:
I found this to work the best

const container = document.querySelector('.container');
const button = document.createElement('button');
let size;

button.classList.add('clear');
button.innerText = 'CLEAR';
document.body.appendChild(button);

var mouseDown = false;
document.body.onmousedown = function() {
  mouseDown = true;
};
document.body.onmouseup = function() {
  mouseDown = false;
};

button.addEventListener('click', function() {
  container.innerHTML = '';
  size = prompt('what size do you want your grid to be: ');
  checkSize(size);
});

function canvas(size) {
  container.style.setProperty('--grid-column', size);
  container.style.setProperty('--grid-row', size);

  for (let i = 0; i < size * size; i++) {
    const cell = document.createElement('div');
    cell.addEventListener('mouseover', changeColor);
    cell.addEventListener('mousedown', changeColor);
    container.appendChild(cell).className = 'grid-items';
  }
}
canvas(16);

function changeColor(e) {
  if (mouseDown) {
    let color1 = Math.floor(Math.random() * 256);
    let color2 = Math.floor(Math.random() * 256);
    let color3 = Math.floor(Math.random() * 256);

    e.target.style.backgroundColor = `rgb(${color1},${color2},${color3})`;
  }
}

function checkSize(e) {
  if (e > 100) {
    alert("size can't be greater than 100");
    canvas(16);
  } else {
    canvas(e);
  }
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background: black;
  display: flex;
  height: 100vh;
  align-items: center;
  justify-content: center;
}

.container {
  display: grid;
  width: 25rem;
  height: 30rem;
  background: white;
  grid-template-columns: repeat(var(--grid-column), 1fr);
  grid-template-rows: repeat(var(--grid-row), 1fr)
}

.grid-items {}

.clear {
  padding: 1rem 2rem;
  border: none;
  border-radius: 10px;
  margin: 5rem 0 0 5rem;
}

<div class="container"></div>

In this if the user is pressing the mouse down over the canvas, the color changes as the mouse moves.


问:
How to get the day of the week from the day number in JavaScript?
Given dayNumber is from 0 - 6 representing Monday - Sunday respectively.

Can the Date / String objects be used to get the day of the week from dayNumber?

答:
```<code>const language = 'en-us';
const options = {  weekday: 'long' };
const today = new Date().toLocaleString(language, options)
cosnsole.log(today)
</code>```


问:
Reading group of lines in HUGE files
I have no idea how to do the following: I want to process a really huge textfile (almost 5 gigabytes). Since I cannot copy the file into temporarily memory, I thought of reading the first 500 lines (or as many as fit into the memory, I am not sure about that yet), do something with them, then go on to the next 500 until I am done with the whole file.

Could you post an example of the "loop" or command that you need for that? Because all the ways I tried resulted in starting from the beginning again but I want to go on after finishing the previous 500 lines.

Help appreciated.

答:
Ok so you indicated in a comment above that you only want to keep certain lines, writing them to a new file based on certain logic. You can read in one line at a time, decide whether to keep it and if so write it to the new file. This approach will use very little memory since you are only holding one line at a time in memory. Here is one way to do that:</p>

```<code>BufferedReader br = new BufferedReader(new FileReader(file));
String lineRead = null;
FileWriter fw = new FileWriter(new File("newfile.txt"), false);

while((lineRead = br.readLine()) != null)
{
     if (true) // put your test conditions here
     {
         fw.write(lineRead);
         fw.flush();
     }
}
fw.close();
br.close();
</code>```

Title: Reading group of lines in HUGE files

Body:
Ok so you indicated in a comment above that you only want to keep certain lines, writing them to a new file based on certain logic. You can read in one line at a time, decide whether to keep it and if so write it to the new file. This approach will use very little memory since you are only holding one line at a time in memory. Here is one way to do that:

BufferedReader br = new BufferedReader(new FileReader(file));
String lineRead = null;
FileWriter fw = new FileWriter(new File("newfile.txt"), false);

while((lineRead = br.readLine()) != null)
{
     if (true) // put your test conditions here
     {
         fw.write(lineRead);
         fw.flush();
     }
}
fw.close();
br.close();


问:
awk/sed replace multiple newlines in the record except end of record
I have file where:

field delimiter is \x01

the record delimiter is \n

Some lines contain multiple newlines I need to remove them, however I don't want to remove the legitimate newlines at the end of each lines. I have tried this with awk:

```<code>awk -F '\x01' 'NF < 87 {getline s; $0 = $0 s} 1' infile > outfile
</code>```

But this is only working when the line contains one newline in the record (except end of line newline). This does not work for multiple newlines.

Note: the record contains 87 fields.

What am I doing wrong here?

Example of file:

```<code>PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000
test^A00000000
 Test^A^A^A^A
PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000
test^A00000000
 Test^A^A^A^A
SL^ANov-21^A30-11-2021^AB^A0000^A1234567^A00000
test^A12102120^A00000^A00^A^A
</code>```

NOTE: The file contains 11 fields; field separate \x01; record separator \n

Expected result:

```<code>PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A
PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A
SL^ANov-21^A30-11-2021^AB^A0000^A1234567^A00000test^A12102120^A00000^A00^A^A
</code>```

Note: I need to preserve the field delimiter (\x01) and record delimiter (\n)

Thank you very much in advance for looking into this.

The file always contains 87 fields;
The fild delimiter is '\x01', but when viewing in Linux it is represented as '^A'
Some lines contain newlines - I need to remove them, but I don't want to remove the legitimate newlines at the end of each line.
The newline appears twice in the 1st and second record and once in third record - this are the newlines I want to remove.

In the examples/expected results there are 11 delimiters "x01" represented as "^A",
I expect to have 3 records and not 6, i.e.:

First record:

test^A00000000 should be joined to the previous line

Test^A^A^A^A should be joined to the first line as well

forming one record:

PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A

Second record

test^A00000000 should be joined to the previous line

Test^A^A^A^A should be joined to that previous line as well

forming one record:

PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A

Third record:

test^A12102120^A00000^A00^A^A should be joined to the previous line

forming one record:

SL^ANov-21^A30-11-2021^AB^A0000^A1234567^A00000test^A12102120^A00000^A00^A^A

Note:
The example of awk - provided works when there is one unwanted newline in the record  but not when there are multiple newlines

Thank you so very much. It works perfectly. Thank you for explaining it so well to me too.

答:
What's wrong with your attempt is that you concatenate two lines, print the result and move to the next line. NF is then reset to the next fields count. As all your lines have less than 87 fields the NF < 87 condition is useless, your script would work the same without it.

Try this awk script:

$ awk -F'\x01' -vn=87 -vi=0 '
    {printf("%s", $0); i+=NF; if(i==n) {i=0; print "";} else i-=1;}' file
```
<p>Here, we use the real <code>\x01</code> field separator and the <code>NF</code> fields count. Variable <code>i</code> counts the number of already printed fields. We first print the current line without the trailing newline (<code>printf("%s", $0)</code>). Then we update our <code>i</code> fields counter. If it is equal to <code>n</code> we reset it and print a newline. Else we decrement it such that we do not count the last field of this line and the first of the next as 2 separate fields.</p>
<p>Demo with <code>n=12</code> instead of 87 and your own input file (with <code>\x01</code> field separators):</p>
<pre class="lang-sh prettyprint-override"><code>$ awk -F'\x01' -vn=12 -vi=0 '
    {printf("%s", $0); i+=NF; if(i==n) {i=0; print "";} else i-=1;}' file |
  sed 's/\x01/|/g'
PL|Nov-21|29-11-2021|0|00|00|0000000test|00000000 Test||||
PL|Nov-21|29-11-2021|0|00|00|0000000test|00000000 Test||||
SL|Nov-21|30-11-2021|B|0000|1234567|00000test|12102120|00000|00||
</code>```

The sed command shows the result with the \x01 replaced by | for easier viewing.

Body:
I have file where:

field delimiter is \x01

the record delimiter is \n

Some lines contain multiple newlines I need to remove them, however I don't want to remove the legitimate newlines at the end of each lines. I have tried this with awk:

awk -F '\x01' 'NF < 87 {getline s; $0 = $0 s} 1' infile > outfile

But this is only working when the line contains one newline in the record (except end of line newline). This does not work for multiple newlines.

Note: the record contains 87 fields.

What am I doing wrong here?

Example of file:

PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000
test^A00000000
 Test^A^A^A^A
PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000
test^A00000000
 Test^A^A^A^A
SL^ANov-21^A30-11-2021^AB^A0000^A1234567^A00000
test^A12102120^A00000^A00^A^A

NOTE: The file contains 11 fields; field separate \x01; record separator \n

Expected result:

PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A
PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A
SL^ANov-21^A30-11-2021^AB^A0000^A1234567^A00000test^A12102120^A00000^A00^A^A

Note: I need to preserve the field delimiter (\x01) and record delimiter (\n)

Thank you very much in advance for looking into this.

The file always contains 87 fields;
The fild delimiter is '\x01', but when viewing in Linux it is represented as '^A'
Some lines contain newlines - I need to remove them, but I don't want to remove the legitimate newlines at the end of each line.
The newline appears twice in the 1st and second record and once in third record - this are the newlines I want to remove.

In the examples/expected results there are 11 delimiters "x01" represented as "^A",
I expect to have 3 records and not 6, i.e.:

First record:

test^A00000000 should be joined to the previous line

Test^A^A^A^A should be joined to the first line as well

forming one record:

PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A

Second record

test^A00000000 should be joined to the previous line

Test^A^A^A^A should be joined to that previous line as well

forming one record:

PL^ANov-21^A29-11-2021^A0^A00^A00^A0000000test^A00000000 Test^A^A^A^A

Third record:

test^A12102120^A00000^A00^A^A should be joined to the previous line

forming one record:

SL^ANov-21^A30-11-2021^AB^A0000^A1234567^A00000test^A12102120^A00000^A00^A^A

Note:
The example of awk - provided works when there is one unwanted newline in the record  but not when there are multiple newlines

Thank you so very much. It works perfectly. Thank you for explaining it so well to me too.

Body:
What's wrong with your attempt is that you concatenate two lines, print the result and move to the next line. NF is then reset to the next fields count. As all your lines have less than 87 fields the NF < 87 condition is useless, your script would work the same without it.

Try this awk script:

$ awk -F'\x01' -vn=87 -vi=0 '
    {printf("%s", $0); i+=NF; if(i==n) {i=0; print "";} else i-=1;}' file

Here, we use the real \x01 field separator and the NF fields count. Variable i counts the number of already printed fields. We first print the current line without the trailing newline (printf("%s", $0)). Then we update our i fields counter. If it is equal to n we reset it and print a newline. Else we decrement it such that we do not count the last field of this line and the first of the next as 2 separate fields.

Demo with n=12 instead of 87 and your own input file (with \x01 field separators):

$ awk -F'\x01' -vn=12 -vi=0 '
    {printf("%s", $0); i+=NF; if(i==n) {i=0; print "";} else i-=1;}' file |
  sed 's/\x01/|/g'
PL|Nov-21|29-11-2021|0|00|00|0000000test|00000000 Test||||
PL|Nov-21|29-11-2021|0|00|00|0000000test|00000000 Test||||
SL|Nov-21|30-11-2021|B|0000|1234567|00000test|12102120|00000|00||

The sed command shows the result with the \x01 replaced by | for easier viewing.


问:
How to fix error in React-Native@0.59.9 IOS Build
I want to use epubjs-rn library. [link:https://github.com/futurepress/epubjs-rn]

So, I set up all libraries just like that epubjs-rn.

when I downgrade react-native version 0.59.9, it makes errors

1.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening ViewerTest.xcworkspace

Invalid Podfile file: cannot load such file -- /myPath/node_modules/react-native/scripts/react_native_pods

I try to fix it.

1.
React Native - pod install issue "cannot load such file.......node_modules/react-native/scripts/react_native_pods"

delete code in ios/podfile
delete code in ios pod file

my package.json is

```<code>  {
  "name": "ViewerTest",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@lightbase/react-native-orientation": "^3.2.1",
    "@react-native-community/async-storage": "^1.5.0",
    "epubjs-rn": "^0.1.5",
    "metro": "^0.67.0",
    "react": "^16.8.3",
    "react-native": "^0.59.9",
    "react-native-static-server": "^0.5.0",
    "react-native-webview": "^5.12.0",
    "react-native-zip-archive": "^4.1.1",
    "rn-fetch-blob": "^0.10.15"
  },
  "devDependencies": {
    "@babel/core": "^7.17.0",
    "@babel/runtime": "^7.17.0",
    "@react-native-community/eslint-config": "^3.0.1",
    "babel-jest": "^27.5.0",
    "eslint": "^8.8.0",
    "jest": "^27.5.0",
    "metro-react-native-babel-preset": "^0.67.0",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}
</code>```

When I install react-native@0.59.9, there is no podfile in ios directory

my Xcode version is 12.5.1 :(

plz help me and sorry about that i'm not good at english.

thanks !

答:
I faced this issue with React Native version 0.61.2 and this worked for me.
Navigate to the ios folder of the app and run the command pod install
Once that is done, go back to the root directory and run react-native run-ios

OR

```<code>cd ios
rm -rf build/
pod install
cd ..
</code>```

Try these solutions.

Body:
I want to use epubjs-rn library. [link:https://github.com/futurepress/epubjs-rn]

So, I set up all libraries just like that epubjs-rn.

when I downgrade react-native version 0.59.9, it makes errors

1.

error Failed to build iOS project. We ran "xcodebuild" command but it exited with error code 65. To debug build logs further, consider building your app with Xcode.app, by opening ViewerTest.xcworkspace

Invalid Podfile file: cannot load such file -- /myPath/node_modules/react-native/scripts/react_native_pods

I try to fix it.

1.
React Native - pod install issue "cannot load such file.......node_modules/react-native/scripts/react_native_pods"

delete code in ios/podfile
delete code in ios pod file

my package.json is

  {
  "name": "ViewerTest",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "android": "react-native run-android",
    "ios": "react-native run-ios",
    "start": "react-native start",
    "test": "jest",
    "lint": "eslint ."
  },
  "dependencies": {
    "@lightbase/react-native-orientation": "^3.2.1",
    "@react-native-community/async-storage": "^1.5.0",
    "epubjs-rn": "^0.1.5",
    "metro": "^0.67.0",
    "react": "^16.8.3",
    "react-native": "^0.59.9",
    "react-native-static-server": "^0.5.0",
    "react-native-webview": "^5.12.0",
    "react-native-zip-archive": "^4.1.1",
    "rn-fetch-blob": "^0.10.15"
  },
  "devDependencies": {
    "@babel/core": "^7.17.0",
    "@babel/runtime": "^7.17.0",
    "@react-native-community/eslint-config": "^3.0.1",
    "babel-jest": "^27.5.0",
    "eslint": "^8.8.0",
    "jest": "^27.5.0",
    "metro-react-native-babel-preset": "^0.67.0",
    "react-test-renderer": "17.0.2"
  },
  "jest": {
    "preset": "react-native"
  }
}

When I install react-native@0.59.9, there is no podfile in ios directory

my Xcode version is 12.5.1 :(

plz help me and sorry about that i'm not good at english.

thanks !

Body:
I faced this issue with React Native version 0.61.2 and this worked for me.
Navigate to the ios folder of the app and run the command pod install
Once that is done, go back to the root directory and run react-native run-ios

OR

cd ios
rm -rf build/
pod install
cd ..

Try these solutions.


问:
Unable to add/update config variables in heroku?
I keep getting an error when I'm trying to add config variables in heroku. This used to work, but now it doesn't work anymore. It just says: "Item could not be updated: Unknown Error. Please contact support." Has anybody else experienced this? I also tried opening the dev console while trying to update the config variables, seems like a bunch of CORS related errors.

答:
I was able to solve this problem using the CLI.

Here's an example:

```<code>heroku config:set MY_CONFIG_VARIABLE=config_var_value --app appname
</code>```

Body:
I was able to solve this problem using the CLI.

Here's an example:

heroku config:set MY_CONFIG_VARIABLE=config_var_value --app appname


问:
Java.Jmeter. SSL unexpected server Message "server_hello"
I try to use Jmeter with plugin "DI-fakfa meter" to load my kafka using SSL.

I got the following certificates from VAULT system:
-CA
-Issuing CA
-Private key
In PEM format.

For Jmeter i import it with keytool:
1.merged files Issuing CA and private key, import it with
keytool in JKS format next command:"keytool -import -trustcacerts -alias root -file "name_file" -keystore privatekey.jks"

Add privatekey.jks as keystore in Jmeter

import file CA.pem in Jks and add it to truststore in Jmeter.

Start Jmeter with -Djavax.net.debug = SSL,handshake.

in console i got error:
"Fatal (UNEXPECTED_MESSAGE): Unexpected handshake message: server hello".

In python code this certificates works normaly in pem format.

答:
Given you're able to successfully run the request in Python code you should be able to do this in JMeter, enable tracing of the SSL handshake for both Python and JMeter and compare the packets and especially the certificate chain - they need to be the same.

Also I don't know what "DI-fakfa meter" is, I recall using Pepper-Box - Kafka Load Generator for load testing the system where SSL-enabled Kafka was used as the transport chain between microservices without any issues.

The relevant setup would be something like:

More information:

Debugging SSL/TLS Connections

Apache Kafka - How to Load Test with JMeter


问:
Include One Yaml File Inside Another
I want to have a base config file which is used by other config files to share common config.

E.g if I have one file base.yml with

```<code>foo: 1

bar:
  - 2
  - 3
</code>```

And then a second file some_file.yml with

```<code>foo: 2

baz: "baz"
</code>```

What I'd want to end up with a merged config file with

```<code>foo: 2

bar:
  - 2
  - 3

baz: "baz"
</code>```

It's easy enough to write a custom loader that handles an !include tag.

```<code>class ConfigLoader(yaml.SafeLoader):

    def __init__(self, stream):
        super().__init__(stream)
        self._base = Path(stream.name).parent

    def include(self, node):
        file_name = self.construct_scalar(node)
        file_path = self._base.joinpath(file_name)

        with file_path.open("rt") as fh:
            return yaml.load(fh, IncludeLoader)
</code>```

Then I can parse an !include tag. So if my file is

```<code>inherit:
   !include base.yml

foo: 2

baz: "baz"
</code>```

But now the base config is a mapping. I.e. if I load the the file I'll end up with

config = {'a': [42], 'c': [3.6, [1, 2, 3]], 'include': [{'a': 1, 'b': [1.43, 543.55]}]}
```
<p>But if I don't make the tag part of a mapping, e.g.</p>
```!include base.yml

foo: 2

baz: "baz"
```
<p>I get an error. <code>yaml.scanner.ScannerError: mapping values are not allowed here</code>.</p>
<p>But I know that the yaml parser can parse tags without needing a mapping. Because I can do things like</p>
```!!python/object:foo.Bar
x: 1.0
y: 3.14
```

So how do I write a loader and/or structure my YAML file so that I can include another file in my configuration?

答:
In YAML you cannot mix scalars, mapping keys and sequence elements. This is invalid YAML:

```<code>- abc
d: e
</code>```

and so is this

```<code>some_file_name
a: b
</code>```

and that you have that scalar quoted, and provide a tag does of course not change the fact
that it is invalid YAML.

As you can already found out, you can trick the loader into returning a dict instead of
the string (just like the parser already has built in constructors for non-primitive types like datetime.date).

That this:

```<code>!!python/object:foo.Bar
x: 1.0
y: 3.14
</code>```

works is because the whole mapping is tagged, where you just tag a scalar value.

What also would be invalid syntax:

```<code>!include base.yaml
foo: 2
baz: baz
</code>```

but you could do:

```<code>!include
filename: base.yaml
foo: 2
baz: baz
</code>```

and process the 'filename' key in a special way, or make
the !include tag an empty key:

```<code>!include : base.yaml  # : is a valid tag character, so you need the space
foo: 2
baz: baz
</code>```

I would however look at using merge keys, as merging is essentially what
you are trying to do. The following YAML works:

```<code>import sys
import ruamel.yaml
from pathlib import Path

yaml_str = """
<<: {x: 42, y: 196, foo: 3}
foo: 2
baz: baz
"""
yaml = ruamel.yaml.YAML(typ='safe')
yaml.default_flow_style = False
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
</code>```

which gives:

```<code>baz: baz
foo: 2
x: 42
y: 196
</code>```

So you should be able to do:

```<code><<: !load base.yaml
foo: 2
baz: baz
</code>```

and anyone with knowledge of merge keys would know what happens if base.yaml does include the key foo with value 3,
and would also understand:

```<code><<: [!load base.yaml, !load config.yaml]
foo: 2
baz: baz
</code>```

(As I tend to associate "including" with textual including as in the C preprocessor, I think `!load' might be a
more appropriate tag, but that is probably a matter of taste).

To get the merge keys to work, it is probably easiest to just sublass the Constructor, as merging is done before tag resolving:

```<code>import sys
import ruamel.yaml
from ruamel.yaml.nodes import MappingNode, SequenceNode, ScalarNode
from ruamel.yaml.constructor import ConstructorError
from ruamel.yaml.compat import _F
from pathlib import Path

class MyConstructor(ruamel.yaml.constructor.SafeConstructor):
    def flatten_mapping(self, node):
        # type: (Any) -> Any
        """
        This implements the merge key feature http://yaml.org/type/merge.html
        by inserting keys from the merge dict/list of dicts if not yet
        available in this node
        """
        merge = []  # type: List[Any]
        index = 0
        while index < len(node.value):
            key_node, value_node = node.value[index]
            if key_node.tag == 'tag:yaml.org,2002:merge':
                if merge:  # double << key
                    if self.allow_duplicate_keys:
                        del node.value[index]
                        index += 1
                        continue
                    args = [
                        'while constructing a mapping',
                        node.start_mark,
                        'found duplicate key "{}"'.format(key_node.value),
                        key_node.start_mark,
                        """
                        To suppress this check see:
                           http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
                        """,
                        """\
                        Duplicate keys will become an error in future releases, and are errors
                        by default when using the new API.
                        """,
                    ]
                    if self.allow_duplicate_keys is None:
                        warnings.warn(DuplicateKeyFutureWarning(*args))
                    else:
                        raise DuplicateKeyError(*args)
                del node.value[index]
                if isinstance(value_node, ScalarNode) and value_node.tag == '!load':
                    file_path = None
                    try:
                        if self.loader.reader.stream is not None:
                            file_path = Path(self.loader.reader.stream.name).parent / value_node.value
                    except AttributeError:
                        pass
                    if file_path is None:
                        file_path = Path(value_node.value)
                    # there is a bug in ruamel.yaml<=0.17.20 that prevents
                    # the use of a Path as argument to compose()
                    with file_path.open('rb') as fp:
                        merge.extend(ruamel.yaml.YAML().compose(fp).value)
                elif isinstance(value_node, MappingNode):
                    self.flatten_mapping(value_node)
                    print('vn0', type(value_node.value), value_node.value)
                    merge.extend(value_node.value)
                elif isinstance(value_node, SequenceNode):
                    submerge = []
                    for subnode in value_node.value:
                        if not isinstance(subnode, MappingNode):
                            raise ConstructorError(
                                'while constructing a mapping',
                                node.start_mark,
                                _F(
                                    'expected a mapping for merging, but found {subnode_id!s}',
                                    subnode_id=subnode.id,
                                ),
                                subnode.start_mark,
                            )
                        self.flatten_mapping(subnode)
                        submerge.append(subnode.value)
                    submerge.reverse()
                    for value in submerge:
                        merge.extend(value)
                else:
                    raise ConstructorError(
                        'while constructing a mapping',
                        node.start_mark,
                        _F(
                            'expected a mapping or list of mappings for merging, '
                            'but found {value_node_id!s}',
                            value_node_id=value_node.id,
                        ),
                        value_node.start_mark,
                    )
            elif key_node.tag == 'tag:yaml.org,2002:value':
                key_node.tag = 'tag:yaml.org,2002:str'
                index += 1
            else:
                index += 1
        if bool(merge):
            node.merge = merge  # separate merge keys to be able to update without duplicate
            node.value = merge + node.value

yaml = ruamel.yaml.YAML(typ='safe', pure=True)
yaml.default_flow_style = False
yaml.Constructor = MyConstructor

yaml_str = """\
<<: !load base.yaml
foo: 2
baz: baz
"""

data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
print('---')

file_name = Path('test.yaml')
file_name.write_text("""\
<<: !load base.yaml
bar: 2
baz: baz
""")

data = yaml.load(file_name)
yaml.dump(data, sys.stdout)
</code>```

this prints:

```<code>bar:
- 2
- 3
baz: baz
foo: 2
---
bar: 2
baz: baz
foo: 1
</code>```

Notes:

don't open YAML files as text. They are written binary (UTF-8), and you should load them as such (open(filename, 'rb')).

If you had included a full working program in your question (or at least included the text of IncludeLoader, it
would have
been possible to provide a full working example with the merge keys (or find out for you that it
doesn't work for some reason)

as it is, it is unclear if your yaml.load() is an instance method call (import ruamel.yaml; yaml = ruamel.yaml.YAML()) or calling a function (from ruamel import yaml). You should not use the latter as it is deprecated.

Title: Include One Yaml File Inside Another

Body:
I want to have a base config file which is used by other config files to share common config.

E.g if I have one file base.yml with

foo: 1

bar:
  - 2
  - 3

And then a second file some_file.yml with

foo: 2

baz: "baz"

What I'd want to end up with a merged config file with

foo: 2

bar:
  - 2
  - 3

baz: "baz"

It's easy enough to write a custom loader that handles an !include tag.

class ConfigLoader(yaml.SafeLoader):

    def __init__(self, stream):
        super().__init__(stream)
        self._base = Path(stream.name).parent

    def include(self, node):
        file_name = self.construct_scalar(node)
        file_path = self._base.joinpath(file_name)

        with file_path.open("rt") as fh:
            return yaml.load(fh, IncludeLoader)

Then I can parse an !include tag. So if my file is

inherit:
   !include base.yml

foo: 2

baz: "baz"

But now the base config is a mapping. I.e. if I load the the file I'll end up with

config = {'a': [42], 'c': [3.6, [1, 2, 3]], 'include': [{'a': 1, 'b': [1.43, 543.55]}]}

But if I don't make the tag part of a mapping, e.g.

!include base.yml

foo: 2

baz: "baz"

I get an error. yaml.scanner.ScannerError: mapping values are not allowed here.

But I know that the yaml parser can parse tags without needing a mapping. Because I can do things like

!!python/object:foo.Bar
x: 1.0
y: 3.14

So how do I write a loader and/or structure my YAML file so that I can include another file in my configuration?

Body:
In YAML you cannot mix scalars, mapping keys and sequence elements. This is invalid YAML:

- abc
d: e

and so is this

some_file_name
a: b

and that you have that scalar quoted, and provide a tag does of course not change the fact
that it is invalid YAML.

As you can already found out, you can trick the loader into returning a dict instead of
the string (just like the parser already has built in constructors for non-primitive types like datetime.date).

That this:

!!python/object:foo.Bar
x: 1.0
y: 3.14

works is because the whole mapping is tagged, where you just tag a scalar value.

What also would be invalid syntax:

!include base.yaml
foo: 2
baz: baz

but you could do:

!include
filename: base.yaml
foo: 2
baz: baz

and process the 'filename' key in a special way, or make
the !include tag an empty key:

!include : base.yaml  # : is a valid tag character, so you need the space
foo: 2
baz: baz

I would however look at using merge keys, as merging is essentially what
you are trying to do. The following YAML works:

import sys
import ruamel.yaml
from pathlib import Path

yaml_str = """
<<: {x: 42, y: 196, foo: 3}
foo: 2
baz: baz
"""
yaml = ruamel.yaml.YAML(typ='safe')
yaml.default_flow_style = False
data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)

which gives:

baz: baz
foo: 2
x: 42
y: 196

So you should be able to do:

<<: !load base.yaml
foo: 2
baz: baz

and anyone with knowledge of merge keys would know what happens if base.yaml does include the key foo with value 3,
and would also understand:

<<: [!load base.yaml, !load config.yaml]
foo: 2
baz: baz

(As I tend to associate "including" with textual including as in the C preprocessor, I think `!load' might be a
more appropriate tag, but that is probably a matter of taste).

To get the merge keys to work, it is probably easiest to just sublass the Constructor, as merging is done before tag resolving:

import sys
import ruamel.yaml
from ruamel.yaml.nodes import MappingNode, SequenceNode, ScalarNode
from ruamel.yaml.constructor import ConstructorError
from ruamel.yaml.compat import _F
from pathlib import Path

class MyConstructor(ruamel.yaml.constructor.SafeConstructor):
    def flatten_mapping(self, node):
        # type: (Any) -> Any
        """
        This implements the merge key feature http://yaml.org/type/merge.html
        by inserting keys from the merge dict/list of dicts if not yet
        available in this node
        """
        merge = []  # type: List[Any]
        index = 0
        while index < len(node.value):
            key_node, value_node = node.value[index]
            if key_node.tag == 'tag:yaml.org,2002:merge':
                if merge:  # double << key
                    if self.allow_duplicate_keys:
                        del node.value[index]
                        index += 1
                        continue
                    args = [
                        'while constructing a mapping',
                        node.start_mark,
                        'found duplicate key "{}"'.format(key_node.value),
                        key_node.start_mark,
                        """
                        To suppress this check see:
                           http://yaml.readthedocs.io/en/latest/api.html#duplicate-keys
                        """,
                        """\
                        Duplicate keys will become an error in future releases, and are errors
                        by default when using the new API.
                        """,
                    ]
                    if self.allow_duplicate_keys is None:
                        warnings.warn(DuplicateKeyFutureWarning(*args))
                    else:
                        raise DuplicateKeyError(*args)
                del node.value[index]
                if isinstance(value_node, ScalarNode) and value_node.tag == '!load':
                    file_path = None
                    try:
                        if self.loader.reader.stream is not None:
                            file_path = Path(self.loader.reader.stream.name).parent / value_node.value
                    except AttributeError:
                        pass
                    if file_path is None:
                        file_path = Path(value_node.value)
                    # there is a bug in ruamel.yaml<=0.17.20 that prevents
                    # the use of a Path as argument to compose()
                    with file_path.open('rb') as fp:
                        merge.extend(ruamel.yaml.YAML().compose(fp).value)
                elif isinstance(value_node, MappingNode):
                    self.flatten_mapping(value_node)
                    print('vn0', type(value_node.value), value_node.value)
                    merge.extend(value_node.value)
                elif isinstance(value_node, SequenceNode):
                    submerge = []
                    for subnode in value_node.value:
                        if not isinstance(subnode, MappingNode):
                            raise ConstructorError(
                                'while constructing a mapping',
                                node.start_mark,
                                _F(
                                    'expected a mapping for merging, but found {subnode_id!s}',
                                    subnode_id=subnode.id,
                                ),
                                subnode.start_mark,
                            )
                        self.flatten_mapping(subnode)
                        submerge.append(subnode.value)
                    submerge.reverse()
                    for value in submerge:
                        merge.extend(value)
                else:
                    raise ConstructorError(
                        'while constructing a mapping',
                        node.start_mark,
                        _F(
                            'expected a mapping or list of mappings for merging, '
                            'but found {value_node_id!s}',
                            value_node_id=value_node.id,
                        ),
                        value_node.start_mark,
                    )
            elif key_node.tag == 'tag:yaml.org,2002:value':
                key_node.tag = 'tag:yaml.org,2002:str'
                index += 1
            else:
                index += 1
        if bool(merge):
            node.merge = merge  # separate merge keys to be able to update without duplicate
            node.value = merge + node.value

yaml = ruamel.yaml.YAML(typ='safe', pure=True)
yaml.default_flow_style = False
yaml.Constructor = MyConstructor

yaml_str = """\
<<: !load base.yaml
foo: 2
baz: baz
"""

data = yaml.load(yaml_str)
yaml.dump(data, sys.stdout)
print('---')

file_name = Path('test.yaml')
file_name.write_text("""\
<<: !load base.yaml
bar: 2
baz: baz
""")

data = yaml.load(file_name)
yaml.dump(data, sys.stdout)

this prints:

bar:
- 2
- 3
baz: baz
foo: 2
---
bar: 2
baz: baz
foo: 1

Notes:

don't open YAML files as text. They are written binary (UTF-8), and you should load them as such (open(filename, 'rb')).

If you had included a full working program in your question (or at least included the text of IncludeLoader, it
would have
been possible to provide a full working example with the merge keys (or find out for you that it
doesn't work for some reason)

as it is, it is unclear if your yaml.load() is an instance method call (import ruamel.yaml; yaml = ruamel.yaml.YAML()) or calling a function (from ruamel import yaml). You should not use the latter as it is deprecated.


问:
How to add a lable to an object value in javascript
I have an array of objects that is grouped by index and would like to restructure and add labels to the response.

This is my original array:

```<code>let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]
</code>```

Here is the source code used to group the array by make:

```<code>var groupedByMake = _.groupBy(
          cars,
          "make"
        );
</code>```

The response looks like this:

```<code>{
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}
</code>```

My desired outcome should look like this:

```<code>[{
  'make': 'audi',
   'types': [{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}]
  },{
  'make': 'bmw',
  'types': [{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}]
</code>```

Is this possible to achieve using JavaScript? If so can I get assistance to achieve this task.

答:
If you want to keep your groupby as-is (using lodash):

  // Result from lodash
var groupedByMake = {
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}

const result = Object.keys(groupedByMake).map(make => ({make, types: groupedByMake [make]}));

console.log(result);```

Body:
I have an array of objects that is grouped by index and would like to restructure and add labels to the response.

This is my original array:

let cars = [{'make': 'audi', 'model': 'RS3', 'transmition': 'automatic'}, {'make': 'audi', 'model': 'RS7', 'transmition': 'dual-clutch'}, {'make': 'bmw', 'model': '325is', 'transmition': 'manual'}, {'make': 'bmw', 'model': 'M2', 'transmition': 'dual-clutch'}]

Here is the source code used to group the array by make:

var groupedByMake = _.groupBy(
          cars,
          "make"
        );

The response looks like this:

{
  'audi':[{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}],
  'bmw':[{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}

My desired outcome should look like this:

[{
  'make': 'audi',
   'types': [{'model': 'RS3', 'transmition': 'automatic'}, {'model': 'RS7', 'transmition': 'dual-clutch'}]
  },{
  'make': 'bmw',
  'types': [{'model': '325is', 'transmition': 'manual'}, {'model': 'M2', 'transmition': 'dual-clutch'}]
}]

Is this possible to achieve using JavaScript? If so can I get assistance to achieve this task.


问:
How to compare large text files?
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

```<code>mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT
</code>```

file_2looks like this:

```<code>mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT
</code>```

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

答:
In an ideal world, you would be able to read in every line of file_2 into memory (probably using a fast lookup object like a HashSet, depending on your needs), then read in each line from file_1 one at a time and compare it to your data structure holding the lines from file_2.

As you have said you run out of memory however, I think a divide-and-conquer type strategy would be best. You could use the same method as I mentioned above, but read in a half (or a third, a quarter... depending on how much memory you can use) of the lines from file_2 and store them, then compare all of the lines in file_1. Then read in the next half/third/quarter/whatever into memory (replacing the old lines) and go through file_1 again. It means you have to go through file_1 more, but you have to work with your memory constraints.

EDIT: In response to the added detail in your question, I would change my answer in part. Instead of reading in all of file_2 (or in chunks) and reading in file_1 a line at a time, reverse that, as file_1 holds the data to check against.

Also, with regards searching the matching lines. I think the best way would be to do some processing on file_1. Create a HashMap<List<Range>> that maps a String ("mat1" - "mat50") to a list of Ranges (just a wrapper for a startOfRange int and an endOfRange int) and populate it with the data from file_1. Then write a function like (ignoring error checking)

```<code>boolean isInRange(String material, int value)
{
    List<Range> ranges = hashMapName.get(material);
    for (Range range : ranges)
    {
        if (value >= range.getStart() && value <= range.getEnd())
        {
            return true;
        }
    }
    return false;
}
</code>```

and call it for each (parsed) line of file_2.

Title: How to compare large text files?

Body:
I have a general question on your opinion about my "technique".

There are 2 textfiles (file_1 and file_2) that need to be compared to each other. Both are very huge (3-4 gigabytes, from 30,000,000 to 45,000,000 lines each).
My idea is to read several lines (as many as possible) of file_1 to the memory, then compare those to all lines of file_2. If there's a match, the lines from both files that match shall be written to a new file. Then go on with the next 1000 lines of file_1 and also compare those to all lines of file_2 until I went through file_1 completely.

But this sounds actually really, really time consuming and complicated to me.
Can you think of any other method to compare those two files?

How long do you think the comparison could take?
For my program, time does not matter that much. I have no experience in working with such huge files, therefore I have no idea how long this might take. It shouldn't take more than a day though. ;-) But I am afraid my technique could take forever...

Antoher question that just came to my mind: how many lines would you read into the memory? As many as possible? Is there a way to determine the number of possible lines before actually trying it?
I want to read as many as possible (because I think that's faster) but I've ran out of memory quite often.

Thanks in advance.

EDIT
I think I have to explain my problem a bit more.

The purpose is not to see if the two files in general are identical (they are not).
There are some lines in each file that share the same "characteristic".
Here's an example:
file_1 looks somewhat like this:

mat1 1000 2000 TEXT      //this means the range is from 1000 - 2000
mat1 2040 2050 TEXT
mat3 10000 10010 TEXT
mat2 20 500 TEXT

file_2looks like this:

mat3 10009 TEXT
mat3 200 TEXT
mat1 999 TEXT

TEXT refers to characters and digits that are of no interest for me, mat can go from mat1 - mat50 and are in no order; also there can be 1000x mat2 (but the numbers in the next column are different). I need to find the fitting lines in a way that: matX is the same in both compared lines an the number mentioned in file_2 fits into the range mentioned in file_1.
So in my example I would find one match: line 3 of file_1and line 1 of file_2 (because both are mat3 and 10009 is between 10000 and 10010).
I hope this makes it clear to you!

So my question is: how would you search for the matching lines?

Yes, I use Java as my programming language.

EDIT
I now divided the huge files first so that I have no problems with being out of memory. I also think it is faster to compare (many) smaller files to each other than those two huge files. After that I can compare them the way I mentioned above. It may not be the perfect way, but I am still learning ;-)
Nonentheless all your approaches were very helpful to me, thank you for your replies!

Body:
In an ideal world, you would be able to read in every line of file_2 into memory (probably using a fast lookup object like a HashSet, depending on your needs), then read in each line from file_1 one at a time and compare it to your data structure holding the lines from file_2.

As you have said you run out of memory however, I think a divide-and-conquer type strategy would be best. You could use the same method as I mentioned above, but read in a half (or a third, a quarter... depending on how much memory you can use) of the lines from file_2 and store them, then compare all of the lines in file_1. Then read in the next half/third/quarter/whatever into memory (replacing the old lines) and go through file_1 again. It means you have to go through file_1 more, but you have to work with your memory constraints.

EDIT: In response to the added detail in your question, I would change my answer in part. Instead of reading in all of file_2 (or in chunks) and reading in file_1 a line at a time, reverse that, as file_1 holds the data to check against.

Also, with regards searching the matching lines. I think the best way would be to do some processing on file_1. Create a HashMap<List<Range>> that maps a String ("mat1" - "mat50") to a list of Ranges (just a wrapper for a startOfRange int and an endOfRange int) and populate it with the data from file_1. Then write a function like (ignoring error checking)

boolean isInRange(String material, int value)
{
    List<Range> ranges = hashMapName.get(material);
    for (Range range : ranges)
    {
        if (value >= range.getStart() && value <= range.getEnd())
        {
            return true;
        }
    }
    return false;
}

and call it for each (parsed) line of file_2.


问:
Merge blocked: merge conflicts must be resolved
I am trying to merge my master branch to a production branch in Gitlab for my CI/CD pipeline.

I get a warning that the source branch is 1 commit behind the target branch. I tried the recommended fix from gitlab(Here and Youtube), but I am having no luck.

In my local environment, I created a production branch. I tried to merge my master to production, but continue to get errors. These are some of the commands I have been using(not in that order) that have been ineffective.

```<code>git pull master production --allow-unrelated-histories
git ls-tree production
git config pull.rebase false
git ls-tree production
git rebase master/production
git push -u  origin production
git merge --no-ff 'master'
git rebase --continue
</code>```

Thanks in advance

答:
You would need at least to make sure you are in the right branch before any merge:

```<code>git fetch
git switch production
git pull production
git merge --no-ff master
git push
</code>```

That would update production first, then merge master to it.

And it does not prevent possible conflicts to be resolved during the merge.

Body:
I am trying to merge my master branch to a production branch in Gitlab for my CI/CD pipeline.

I get a warning that the source branch is 1 commit behind the target branch. I tried the recommended fix from gitlab(Here and Youtube), but I am having no luck.

In my local environment, I created a production branch. I tried to merge my master to production, but continue to get errors. These are some of the commands I have been using(not in that order) that have been ineffective.

git pull master production --allow-unrelated-histories
git ls-tree production
git config pull.rebase false
git ls-tree production
git rebase master/production
git push -u  origin production
git merge --no-ff 'master'
git rebase --continue

Thanks in advance

Body:
You would need at least to make sure you are in the right branch before any merge:

git fetch
git switch production
git pull production
git merge --no-ff master
git push

That would update production first, then merge master to it.

And it does not prevent possible conflicts to be resolved during the merge.


问:
restarting animation from current point
```<code><script>
 document.querySelector("body").addEventListener("keydown",venstre);
      function venstre(e)
      {
          if (e.keyCode===37)
          {
              document.querySelector(".bil").style.animation = "venstre 1s linear forwards, venstre 1s"
              window.setTimeout(kjørvens,0);
          }
      }
      function kjørvens()
      {
        document.querySelector(".bil").style.animation = "venstre 1s linear forwards";

      }
</code>```

I thought I could make this animation repeat from where it was on every press of left arrow, as in holding it down and having my car move continously. sorry if im formatting my question weird or doing my code in the least usable way

答:
You could use a css property animation-play-state to pause or resume your animation.

Here is the documentation you should check out: https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state

Title: restarting animation from current point


问:
Does using Wikipedia content harm a page/sites SEO rankings?
Wikipedia allows you to reproduce its content.

If you want to use Wikipedia materials in your own books/articles/websites or other publications, you can do so -- but only in compliance with the GFDL.
See here.

I am considering using some wikipedia content to pad out pages on my website. For example - just taking the first couple of paragraphs. The motivation for this is not for SEO , but to provide information to the website user.

My question is: by doing this will I hurt my own page SEO? I have googled around and mentions of Google Supplemental index keeps cropping up.

答: The answer is yes.  You and wikipedia will both be penalized by Google's algorithms for having identical content.  Google allows the actual copyright owner to submit a DMCA request to remove the plagiairizing site from Google's index.</p>

OwnerDisplayName: will

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Codingscape


问:
How to add a value in all NULL rows in a column in phpmyadmin
In my database, there is a column expiry date that has expire date of users' accounts, but some users have NULL value in expiry date due to an earlier bug. So I want to change expiry date of all rows in that column, but do not want to make change to rows that has expiry date added already. How can I accomplish that?</p>

答:
To test for NULL values, use the IS NULL and IS NOT NULL.

You did not provided more details about your table so I will give you generic example:

To find NULL values use WHERE expiry IS NULL aka

```<code>SELECT * FROM thetablename WHERE expiry IS NULL;
</code>```

To update the NULL values use the same logic as above aka:

```<code>UPDATE thetablename SET expiry = '2022-01-01' WHERE expiry IS NULL;
</code>```

Always do the SELECT statement with the same condition in WHERE part to see what records will be impacted with the UPDATE statement.

To name at least two references about working with NULL values are mariadb.com and dev.mysql.com.

Body:
To test for NULL values, use the IS NULL and IS NOT NULL.

You did not provided more details about your table so I will give you generic example:

To find NULL values use WHERE expiry IS NULL aka

SELECT * FROM thetablename WHERE expiry IS NULL;

To update the NULL values use the same logic as above aka:

UPDATE thetablename SET expiry = '2022-01-01' WHERE expiry IS NULL;

Always do the SELECT statement with the same condition in WHERE part to see what records will be impacted with the UPDATE statement.

To name at least two references about working with NULL values are mariadb.com and dev.mysql.com.


问:
Group together individuals based on commonalities(direct or indirect) in two other columns for 7.5 million dataset in python
I have a dataframe which contains

```<code>cust_id|phone|email
1   678   a
2   NaN   c
3   987   b
4   456   NaN
5   NaN   d
7   456   c
</code>```

All the cust_ids with either matching phone or email are directly related.eg.cust_id 1 is directly related to 2 and 2 is directly related to 3.

Cust_id 1 is indirectly related to 3- they don't have same phone or email but are related through 2.

I want to club and give a unique number to a group which is directly related or is indirectly related

Desired output:

```<code>Cust_id|phone|email | group_no
1     678   a   1
2     NaN   c   2
3     987   b   3
4     456   NaN 2
5     NaN   d   4
7     456   c   2
</code>```

Obtained output:

```<code>Cust_id|phone|email | group_no

1     678   a    1
2     NaN   c    2
3     987   b    3
4     456   NaN  2
5     NaN   d    2
7     456   c    2
</code>```

how do i do this for a dataset that has 7.5 million rows without compromising on speed.

I used the following code in the picture.

答:
Here you go Chaitanya

```<code># custom class sub-classed from Graph for low-memory requirements as you don't need edge weights
    class ThinGraph(nx.Graph):
        all_edge_dict = {"weight": 1}
        def single_edge_dict(self):
            return self.all_edge_dict
            edge_attr_dict_factory = single_edge_dict
    # create a blank Graph object from the Networkx library
    G = ThinGraph()
    # add nodes to G
    nodes_array =[]
    customer_id_phone_edges_array = []
    customer_id_email_edges_array = []
    for _,row in df.iterrows():
        nodes_array.append((row["cust_id"],{"label":"Customer ID"}))
        nodes_array.append((row["phone"],{"label":"Phone"}))
        nodes_array.append((row["email"],{"label":"Email"}))
        # Create your customer_ID, phone graph edges
        customer_id_phone_edges_array.append((row["cust_id"],row["phone"]))
        # Create your customer_ID, email graph edges
        customer_id_email_edges_array.append((row["cust_id"],row["email"]))
    #Add the nodes and edges
    G.add_nodes_from(nodes_array)
    G.add_edges_from(customer_id_phone_edges_array)
    G.add_edges_from(customer_id_email_edges_array)
    # delete objects to free up memory
    del nodes_array
    del customer_id_phone_edges_array
    del customer_id_email_edges_array
    # run the connected components algorithm
    components = nx.connected_components(G)
    comp_dict = {idx: comp for idx, comp in enumerate(components)}
    attr = {n: comp_id for comp_id, nodes in comp_dict.items() for n in nodes}
    nx.set_node_attributes(G,  attr,"component")
    # Examine the result
    G.nodes(data=True)
</code>```

For your given data, you will get the output

```<code>NodeDataView({1: {'label': 'Customer ID', 'component': 0}, 678: {'label': 'Phone', 'component': 0}, 'a': {'label': 'Email', 'component': 0}, 2: {'label': 'Customer ID', 'component': 0}, 'b': {'label': 'Email', 'component': 0}, 3: {'label': 'Customer ID', 'component': 0}, 987: {'label': 'Phone', 'component': 0}, 4: {'label': 'Customer ID', 'component': 1}, 456: {'label': 'Phone', 'component': 1}, 'd': {'label': 'Email', 'component': 1}, 5: {'label': 'Customer ID', 'component': 1}, 654: {'label': 'Phone', 'component': 1}, 7: {'label': 'Customer ID', 'component': 1}, 'f': {'label': 'Email', 'component': 1}})
</code>```

Body:
I have a dataframe which contains

cust_id|phone|email
1   678   a
2   NaN   c
3   987   b
4   456   NaN
5   NaN   d
7   456   c

All the cust_ids with either matching phone or email are directly related.eg.cust_id 1 is directly related to 2 and 2 is directly related to 3.

Cust_id 1 is indirectly related to 3- they don't have same phone or email but are related through 2.

I want to club and give a unique number to a group which is directly related or is indirectly related

Desired output:

Cust_id|phone|email | group_no
1     678   a   1
2     NaN   c   2
3     987   b   3
4     456   NaN 2
5     NaN   d   4
7     456   c   2

Obtained output:

Cust_id|phone|email | group_no

1     678   a    1
2     NaN   c    2
3     987   b    3
4     456   NaN  2
5     NaN   d    2
7     456   c    2

how do i do this for a dataset that has 7.5 million rows without compromising on speed.

I used the following code in the picture.

Body:
Here you go Chaitanya

# custom class sub-classed from Graph for low-memory requirements as you don't need edge weights
    class ThinGraph(nx.Graph):
        all_edge_dict = {"weight": 1}
        def single_edge_dict(self):
            return self.all_edge_dict
            edge_attr_dict_factory = single_edge_dict
    # create a blank Graph object from the Networkx library
    G = ThinGraph()
    # add nodes to G
    nodes_array =[]
    customer_id_phone_edges_array = []
    customer_id_email_edges_array = []
    for _,row in df.iterrows():
        nodes_array.append((row["cust_id"],{"label":"Customer ID"}))
        nodes_array.append((row["phone"],{"label":"Phone"}))
        nodes_array.append((row["email"],{"label":"Email"}))
        # Create your customer_ID, phone graph edges
        customer_id_phone_edges_array.append((row["cust_id"],row["phone"]))
        # Create your customer_ID, email graph edges
        customer_id_email_edges_array.append((row["cust_id"],row["email"]))
    #Add the nodes and edges
    G.add_nodes_from(nodes_array)
    G.add_edges_from(customer_id_phone_edges_array)
    G.add_edges_from(customer_id_email_edges_array)
    # delete objects to free up memory
    del nodes_array
    del customer_id_phone_edges_array
    del customer_id_email_edges_array
    # run the connected components algorithm
    components = nx.connected_components(G)
    comp_dict = {idx: comp for idx, comp in enumerate(components)}
    attr = {n: comp_id for comp_id, nodes in comp_dict.items() for n in nodes}
    nx.set_node_attributes(G,  attr,"component")
    # Examine the result
    G.nodes(data=True)

For your given data, you will get the output

NodeDataView({1: {'label': 'Customer ID', 'component': 0}, 678: {'label': 'Phone', 'component': 0}, 'a': {'label': 'Email', 'component': 0}, 2: {'label': 'Customer ID', 'component': 0}, 'b': {'label': 'Email', 'component': 0}, 3: {'label': 'Customer ID', 'component': 0}, 987: {'label': 'Phone', 'component': 0}, 4: {'label': 'Customer ID', 'component': 1}, 456: {'label': 'Phone', 'component': 1}, 'd': {'label': 'Email', 'component': 1}, 5: {'label': 'Customer ID', 'component': 1}, 654: {'label': 'Phone', 'component': 1}, 7: {'label': 'Customer ID', 'component': 1}, 'f': {'label': 'Email', 'component': 1}})