问:
Dynamic flex item width
I made a working example what I want to achieve: Tabs fill up the given space evenly, if the text is too long, it is truncated with ellipsis.

The problem starts, if I wrap it into flex div. (It is a legacy code and part of complex template, and I want ot make as little change as possible)

.box {
  border: 2px dotted rgb(96, 139, 168);
}

.box div {
  min-width: 0px;
  display: flex;
  align-items: center;
  border: 2px solid rgb(96, 139, 168);
  border-radius: 5px;
  background-color: rgba(96, 139, 168, .2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.tailwindcss.com"></script>

<b>Expected</b>
<div class="box h-16 flex items-stretch">
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
</div>

<b>Wrong</b>
<div id="wrapper" class="w-full mb-8 flex items-stretch">
  <div class='mr-2 flex items-center'>
    Link 1
    Link 2
  </div>
  <div class="box h-16 flex items-stretch">
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  </div>
</div></code>```

The problem, that in the second example the tabs do not shrink, they expand the viewport with a scrollbar.

Here is the jsbin

答:
You just need to add width and overflow properties to the ".box" div. working example below.

.box {
  border: 2px dotted rgb(96, 139, 168);

  /* ADD THESE PROPERTIES */
  width: 100%;
  overflow: hidden;
}

.box div {
  min-width: 0px;
  display: flex;
  align-items: center;
  border: 2px solid rgb(96, 139, 168);
  border-radius: 5px;
  background-color: rgba(96, 139, 168, .2);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.tailwindcss.com"></script>

<b>Expected</b>
<div class="box h-16 flex items-stretch">
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
</div>

<b>Wrong</b>
<div id="wrapper" class="w-full mb-8 flex items-stretch">
  <div class='mr-2 flex items-center'>
    Link 1
    Link 2
  </div>
  <div class="box h-16 flex items-stretch">
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  </div>
</div></code>```

Title: Dynamic flex item width

Body:
I made a working example what I want to achieve: Tabs fill up the given space evenly, if the text is too long, it is truncated with ellipsis.

The problem starts, if I wrap it into flex div. (It is a legacy code and part of complex template, and I want ot make as little change as possible)

.box {
  border: 2px dotted rgb(96, 139, 168);
}

.box div {
  min-width: 0px;
  display: flex;
  align-items: center;
  border: 2px solid rgb(96, 139, 168);
  border-radius: 5px;
  background-color: rgba(96, 139, 168, .2);
}

Expected

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Wrong

    Link 1
    Link 2

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

The problem, that in the second example the tabs do not shrink, they expand the viewport with a scrollbar.

Here is the jsbin

Body:
You just need to add width and overflow properties to the ".box" div. working example below.

.box {
  border: 2px dotted rgb(96, 139, 168);

  /* ADD THESE PROPERTIES */
  width: 100%;
  overflow: hidden;
}

.box div {
  min-width: 0px;
  display: flex;
  align-items: center;
  border: 2px solid rgb(96, 139, 168);
  border-radius: 5px;
  background-color: rgba(96, 139, 168, .2);
}

<script src="https://cdn.tailwindcss.com"></script>

<b>Expected</b>
<div class="box h-16 flex items-stretch">
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
</div>

<b>Wrong</b>
<div id="wrapper" class="w-full mb-8 flex items-stretch">
  <div class='mr-2 flex items-center'>
    <a class="truncate">Link 1</a>
    <a class="truncate">Link 2</a>
  </div>
  <div class="box h-16 flex items-stretch">
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
    <div><span class="truncate">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </span></div>
  </div>
</div>


来源: stackexchange

问:
I am getting error "cmdline-tools component is missing" after installing Flutter and Android Studio... I added the Android SDK. How can I solve them?
Android toolchain - I develop for Android devices (Android SDK version 30.0.3):

X cmdline-tools component is missing
  Run `path/to/sdkmanager --install "cmdline-tools;latest"`
  See https://developer.android.com/studio/command-line for more details.
```

答:
Since my Android Studio starting screen looks different from the answers above I want to share my solution:

Open Android Studio and click on 'more actions' on the welcome screen.

Click on 'SDK Manager'

In the '*Preferences' window go to the '*SDK Tools•' tab

Select the 'Android SDK Command-line Tools (latest)' checkbox.

Click on 'Apply'.

ContentLicense: CC BY-SA 4.0


答:
A dplyr solution:

Data:

```<code>df <- fread(" year max1 max2 max3
2001   10  101   87
2002  103   19   88
2003   21   23   89
2004   27   28   91 ")
</code>```

Code:

```<code>library(dplyr)
df %>%
  rowwise() %>%
  mutate(MAX = max(max1, max2, max3)) %>%
  select(year, MAX)
</code>```

Output:

```<code># A tibble: 4 x 2
# Rowwise:
   year   MAX
  <int> <int>
1  2001   101
2  2002   103
3  2003    89
4  2004    91
</code>```

Title: how to get max from multiple columns in R

Body:
INPUT:-
 year max1 max2 max3
2001   10  101   87
2002  103   19   88
2003   21   23   89
2004   27   28   91

OUTPUT:-

YEAR    MAX

2001     101

2002     103

2003      89

2004      91

Body:
A dplyr solution:

Data:

df <- fread(" year max1 max2 max3
2001   10  101   87
2002  103   19   88
2003   21   23   89
2004   27   28   91 ")

Code:

library(dplyr)
df %>%
  rowwise() %>%
  mutate(MAX = max(max1, max2, max3)) %>%
  select(year, MAX)

Output:

# A tibble: 4 x 2
# Rowwise:
   year   MAX
  <int> <int>
1  2001   101
2  2002   103
3  2003    89
4  2004    91


问:
ESP32 reduce BLE connection distance
i need to connect my phone to the esp32 with BLE(Bluetooth Low Energy). But only when you are close to just 1 meters. So, how can i reduce the meters? And also if you go far away from 1 meter, it has to disconnect. I would be happy, if you answer...</p>

答: Connect if the RSSI more than 40 and keep updating the RSSI for 2 seconds, get the average if it's more than -30 then you're too close to the device.</p>

Title: ESP32 reduce BLE connection distance


问:
How to type the 'name' html attribute to ant design select?
I have an component that have an ant design select, and a form component where I use this select, i'm trying to set the 'name' attribute in the ant design select but I'm getting this error

Ant design Select Component

```<code>interface Props {
  name?: string;
  value?: string;

}
export const Select = ({ name, ...props }: Props) => {
  const { Option } = SelecteAntd;

     import {Select } from 'antd';

                   <Select
                      bordered={false}
                      {...props}
                      name={name}
                    >
                      <Option value="Youth">under 24</Option>
                      <Option value="Adult">25 - 64</Option>
                      <Option value="Senior">64+</Option>
            </Select>
</code>```

Form Component

```<code>import { Select } from '../shared/Select';

                 <Select
                        value={surveyData.age}
                        name='age' <------
                        onChange={handleChange}
                    />
</code>```

答:
I got one solution but and its is working fine for me.

import React from "react";
import { useState } from "react";

const App =()=>{
  const [selectedState, setSelectedState] = useState(')

const handleInputChange =(selectedData,option)=>{
    console.log("[selected Data] ",selectedData);
    console.log("[selected option]",option);
   // setSelectedState(date.name)
  }
 // Note Please use antd select
return (<Select value={selectedState} onChange={handleChange}>
      <Option name="state" value="jack">Jack</Option>
      <Option name="state" value="lucy">Lucy</Option>
      <Option value="Yiminghe">yiminghe</Option>
    </Select>)
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script></code>```

For the dynamic data

```<code>import { Select } from 'antd';
import React from 'react';
const { Option } = Select;

const DropdownComponent=({errMsg,optionList,...props})=>{
return <div>
   <Select   style={{ width: 120 }} {...props}>
 {optionList.map(({state,name})=>{
    return <Option name={props.name}  key={state} value=.
 {state}>{name}</Option>
 })}
</Select>
{errMsg&&<p>{errMsg}</p>}
</div>;
};
export default DropdownComponent;
</code>```

Body:
I have an component that have an ant design select, and a form component where I use this select, i'm trying to set the 'name' attribute in the ant design select but I'm getting this error

Ant design Select Component

interface Props {
  name?: string;
  value?: string;

}
export const Select = ({ name, ...props }: Props) => {
  const { Option } = SelecteAntd;

     import {Select } from 'antd';

                   <Select
                      bordered={false}
                      {...props}
                      name={name}
                    >
                      <Option value="Youth">under 24</Option>
                      <Option value="Adult">25 - 64</Option>
                      <Option value="Senior">64+</Option>
            </Select>

Form Component

import { Select } from '../shared/Select';

                 <Select
                        value={surveyData.age}
                        name='age' <------
                        onChange={handleChange}
                    />

Body:
I got one solution but and its is working fine for me.

import React from "react";
import { useState } from "react";

const App =()=>{
  const [selectedState, setSelectedState] = useState(')

const handleInputChange =(selectedData,option)=>{
    console.log("[selected Data] ",selectedData);
    console.log("[selected option]",option);
   // setSelectedState(date.name)
  }
 // Note Please use antd select
return (<Select value={selectedState} onChange={handleChange}>
      <Option name="state" value="jack">Jack</Option>
      <Option name="state" value="lucy">Lucy</Option>
      <Option value="Yiminghe">yiminghe</Option>
    </Select>)
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

For the dynamic data

import { Select } from 'antd';
import React from 'react';
const { Option } = Select;

const DropdownComponent=({errMsg,optionList,...props})=>{
return <div>
   <Select   style={{ width: 120 }} {...props}>
 {optionList.map(({state,name})=>{
    return <Option name={props.name}  key={state} value=.
 {state}>{name}</Option>
 })}
</Select>
{errMsg&&<p>{errMsg}</p>}
</div>;
};
export default DropdownComponent;


问:
How to change a parent by validating a child?
I have a DockPanel that is composed of a button and a textbox. These controls are enclosed by a border. Now I would like to validate the textbox and change the color of the border if the validation fails.

However, in my current application, the validation only affects the textbox itself.

```<code><Border>
    <DockPanel>
        <Button Command="{Binding GetFolder}">
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Assets/Icons/Folder.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <TextBox
            Text="{Binding
            Path=DataFolder,
            ValidatesOnDataErrors=True,
            Mode=TwoWay,
            UpdateSourceTrigger=PropertyChanged,
            NotifyOnSourceUpdated=True}">
        </TextBox>
    </DockPanel>
</Border>
</code>```

I know that I can give the Border an ErrorTemplate:

```<code><Border Validation.ErrorTemplate="{StaticResource errorTemplate}">...,
</code>```

But how do I tell it the result of the validation of the textbox?

答:
You could use a Style with a DataTrigger that binds to the attached Validation.HasError property of the TextBox:

```<code><Border>
    <Border.Style>
        <Style TargetType="Border">
            <Style.Triggers>
                <DataTrigger Binding="{Binding (Validation.HasError),ElementName=tb}"
                             Value="True">
                    <Setter Property="BorderThickness" Value="1" />
                    <Setter Property="BorderBrush" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <DockPanel>
        <Button Command="{Binding GetFolder}">
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Assets/Icons/Folder.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <TextBox x:Name="tb"
                    Text="{Binding
                    Path=DataFolder,
                    ValidatesOnDataErrors=True,
                    Mode=TwoWay,
                    UpdateSourceTrigger=PropertyChanged,
                    NotifyOnSourceUpdated=True}">
        </TextBox>
    </DockPanel>
</Border>
</code>```

Body:
I have a DockPanel that is composed of a button and a textbox. These controls are enclosed by a border. Now I would like to validate the textbox and change the color of the border if the validation fails.

However, in my current application, the validation only affects the textbox itself.

<Border>
    <DockPanel>
        <Button Command="{Binding GetFolder}">
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Assets/Icons/Folder.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <TextBox
            Text="{Binding
            Path=DataFolder,
            ValidatesOnDataErrors=True,
            Mode=TwoWay,
            UpdateSourceTrigger=PropertyChanged,
            NotifyOnSourceUpdated=True}">
        </TextBox>
    </DockPanel>
</Border>

I know that I can give the Border an ErrorTemplate:

<Border Validation.ErrorTemplate="{StaticResource errorTemplate}">...,

But how do I tell it the result of the validation of the textbox?

Body:
You could use a Style with a DataTrigger that binds to the attached Validation.HasError property of the TextBox:

<Border>
    <Border.Style>
        <Style TargetType="Border">
            <Style.Triggers>
                <DataTrigger Binding="{Binding (Validation.HasError),ElementName=tb}"
                             Value="True">
                    <Setter Property="BorderThickness" Value="1" />
                    <Setter Property="BorderBrush" Value="Red" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </Border.Style>
    <DockPanel>
        <Button Command="{Binding GetFolder}">
            <Button.Template>
                <ControlTemplate>
                    <Image Source="/Assets/Icons/Folder.png"/>
                </ControlTemplate>
            </Button.Template>
        </Button>
        <TextBox x:Name="tb"
                    Text="{Binding
                    Path=DataFolder,
                    ValidatesOnDataErrors=True,
                    Mode=TwoWay,
                    UpdateSourceTrigger=PropertyChanged,
                    NotifyOnSourceUpdated=True}">
        </TextBox>
    </DockPanel>
</Border>


问:
cannot access 'androidx.dataBinding.observable' (even though data binding class is generated)
I'm having trouble implementing data binding in my Android Studio project. I get the following error:

Cannot access 'androidx.databinding.Observable' which is a supertype
of 'com.russ.beatbox.databinding.MainActivityBinding'. Check your
module classpath for missing or conflicting dependencies

Even though i have all the Gradle dependencies and the binding class is generated. I've tried rebuilding, invalidate cache/restart, clean project, renaming the file, and using different Gradle import syntax, nothing seems to work. Is this Android Studio bug?

Here's my MainActivity, the error comes from binding.recView.apply:

package com.russ.beatbox

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.russ.beatbox.databinding.MainActivityBinding

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding: MainActivityBinding =
            DataBindingUtil.setContentView(this, R.layout.main_activity)

        binding.recView.apply{
            layoutManager = GridLayoutManager(context, 3)
        }
    }
}
```
<p>My layout:</p>
<pre class="lang-xml prettyprint-override"><code><?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/rec_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</layout>
</code>```

And my module Gradle file:

```<code>apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.russ.beatbox"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures{
        dataBinding = true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}
</code>```

答:
Try with removing layout tag  form xml file it is used when you have data that need to bind with views

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

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rec_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>
</code>```

also try to update build file like

```<code> buildFeatures {
        viewBinding true
        dataBinding true
    }
</code>```

Body:
I'm having trouble implementing data binding in my Android Studio project. I get the following error:

Cannot access 'androidx.databinding.Observable' which is a supertype
of 'com.russ.beatbox.databinding.MainActivityBinding'. Check your
module classpath for missing or conflicting dependencies

Even though i have all the Gradle dependencies and the binding class is generated. I've tried rebuilding, invalidate cache/restart, clean project, renaming the file, and using different Gradle import syntax, nothing seems to work. Is this Android Studio bug?

Here's my MainActivity, the error comes from binding.recView.apply:

package com.russ.beatbox

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.GridLayoutManager
import com.russ.beatbox.databinding.MainActivityBinding

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        val binding: MainActivityBinding =
            DataBindingUtil.setContentView(this, R.layout.main_activity)

        binding.recView.apply{
            layoutManager = GridLayoutManager(context, 3)
        }
    }
}

My layout:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <androidx.recyclerview.widget.RecyclerView

        android:id="@+id/rec_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</layout>

And my module Gradle file:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

android {
    compileSdk 31

    defaultConfig {
        applicationId "com.russ.beatbox"
        minSdk 23
        targetSdk 31
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

    buildFeatures{
        dataBinding = true
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.3.1'
    implementation 'com.google.android.material:material:1.4.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.1'
    androidTestImplementation 'androidx.test.ext:junit:1.1.3'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0'
}

Body:
Try with removing layout tag  form xml file it is used when you have data that need to bind with views

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

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rec_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

also try to update build file like

 buildFeatures {
        viewBinding true
        dataBinding true
    }


问:
Prefer charset declaration in HTML meta tag or HTTP header?
I'm parsing a lot of sites. All works fine, I'm reading also charset declarations to convert encodings. Now I've a problem with http://celleheute.de/sonntagsfuhrung-3/.

The HTML meta tag says, that the content is encoded as ISO-8859-2, but the HTTP header says, it's UTF-8. And really, the content is UTF encoded, so when my parser tries to convert the content to ISO it will break some chars.

Now my question is, which declaration should I prefer? Should I ignore meta tags, when I can find the declaration in HTTP header or vice versa? What will most web browsers do?

答:
To understand what modern browsers do, you should start reading at http://w3c.github.io/html/syntax.html#determining-the-character-encoding

Steps one and two are most relevant to the question. They say

If the user has explicitly instructed the user agent to override
  the document's character encoding with a specific encoding, optionally
  return that encoding with the confidence certain and abort these
  steps.

If the transport layer specifies an encoding, and it is supported,
  return that encoding with the confidence certain, and abort these
  steps.

which means that the real HTTP header takes precedence over everything except user over-ride.

Beyond that it can get complex. A byte order mark, can for example, take precedence over the meta tag.

UPDATE: Since this answer was written, the spec changed (around mid-2012) so that the byte order mark now takes precedence over the HTTP header.

ContentLicense: CC BY-SA 3.0


问:
How to sum value in javascript array obj from specific search category to useState
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

```<code>const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]
</code>```

How can i interate arr to get this effect ?

```<code>const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)
</code>```

Thanks you for your help ;-)

答:
You can find the total cost without iterating over another time using filter.

Using reduce, we can add the cost with respect to category

const arr = [
  { id: "222", cost: 2, category: "fit" },
  { id: "333", cost: 3, category: "fat" },
  { id: "11", cost: 1, category: "fat" },
  { id: "11", cost: 0, category: "fit" },
  { id: "33", cost: 55, category: "slim" },
  { id: "55", cost: 33, category: "slim" },
  { id: "123", cost: 4, category: "slim" }
];

const result = arr.reduce((acc, { category, cost }) => {
  !acc[category] ? (acc[category] = cost) : (acc[category] += cost);
  return acc;
}, {});

console.log(result);```
</div>
</div>
</p>
<p><strong>Result</strong></p>
```result =  { fit: 2, fat: 4, slim: 92 }
```
<p>You can directly set that as a single state and access it as <code>data.fit</code>,<code>data.fat</code>, <code>data.slim</code>.</p>
```const [data,setData] = useState(result)
```
<p>or</p>
```const [fit, setFit] = useState(result.fit)
const [fat, setFat] = useState(result.fat)
const [slim, setSlim] = useState(result.slim)
```

Body:
I have js arr obj as below. My need is to sum value to useState base on category in the arr obj.

const [fit, setFit] = useState(0)
const [fat, setFat] = useState(0)
const [slim, setSlim] = useState(0)
const [test, setTest] = useState(0)

const arr = [
{id: '222', cost: 2, category: 'fit'},
{id: '333', cost: 3, category: 'fat'},
{id: '11', cost: 1, category: 'fat'},
{id: '11', cost: 0, category: 'fit'},
{id: '33', cost: 55, category: 'slim'},
{id: '55', cost: 33, category: 'slim'},
{id: '123', cost: 4, category: 'slim'}
]

How can i interate arr to get this effect ?

const [fit, setFit] = useState(2)
const [fat, setFat] = useState(4)
const [slim, setSlim] = useState(92)
const [test, setTest] = useState(0)

Thanks you for your help ;-)

Body:
You can find the total cost without iterating over another time using filter.

Using reduce, we can add the cost with respect to category

const arr = [
  { id: "222", cost: 2, category: "fit" },
  { id: "333", cost: 3, category: "fat" },
  { id: "11", cost: 1, category: "fat" },
  { id: "11", cost: 0, category: "fit" },
  { id: "33", cost: 55, category: "slim" },
  { id: "55", cost: 33, category: "slim" },
  { id: "123", cost: 4, category: "slim" }
];

const result = arr.reduce((acc, { category, cost }) => {
  !acc[category] ? (acc[category] = cost) : (acc[category] += cost);
  return acc;
}, {});

console.log(result);

Result

result =  { fit: 2, fat: 4, slim: 92 }

You can directly set that as a single state and access it as data.fit,data.fat, data.slim.

const [data,setData] = useState(result)

or

const [fit, setFit] = useState(result.fit)
const [fat, setFat] = useState(result.fat)
const [slim, setSlim] = useState(result.slim)


问:
Pouch DB data is not inserted in sorted order
I am working on small form in electron and pouchdb.

When inserting a data into db, until the ninth doc it inserting perfectly, but on 10th doc it is inserting to second position of doc instead on inserting into last

before inserting the 10th doc

{
  "total_rows": 9,
  "offset": 0,
    "rows": [
    { "id": "1", "key": "1", "value": {...} },
    { "id": "2", "key": "2", "value": {...} },
    { "id": "3", "key": "3", "value": {...} },
    { "id": "4", "key": "4", "value": {...} }
    { "id": "5", "key": "5", "value": {...} },
    { "id": "6", "key": "6", "value": {...} },
    { "id": "7", "key": "7", "value": {...} },
    { "id": "8", "key": "8", "value": {...} },
    { "id": "9", "key": "9", "value": {...} }
  ]
}
```
<p>After inserting 10th doc</p>
<pre class="lang-json prettyprint-override"><code>{
  "total_rows": 10,
  "offset": 0,
    "rows": [
    { "id": "1", "key": "1", "value": {...} },
    { "id": "10", "key": "10", "value": {...} },
    { "id": "2", "key": "2", "value": {...} },
    { "id": "3", "key": "3", "value": {...} },
    { "id": "4", "key": "4", "value": {...} }
    { "id": "5", "key": "5", "value": {...} },
    { "id": "6", "key": "6", "value": {...} },
    { "id": "7", "key": "7", "value": {...} },
    { "id": "8", "key": "8", "value": {...} },
    { "id": "9", "key": "9", "value": {...} }
  ]
}
</code>```

here attached the js code

// form submit
const form = document.getElementById("form1");
form.addEventListener("submit", dbsubmit);

function dbsubmit(e) {
   e.preventDefault();
   //   getting values from form
   var Sno = document.getElementById("number").value
   var date = document.getElementById("date").value;
   var Time = document.getElementById("time").value;
   var Trip = document.querySelector('input[name="Trip"]:checked').value;
   var TripType = document.querySelector('input[name="Type"]:checked').value;

 // assigning form values to db table names
  var doc = {
    _id: Sno,
    Date: date,
    time: Time,
    trip: Trip,
    triptype: TripType,
  };

   // inserting to db
  db.put(doc, function(err, response) {
    if (err) {
      return console.log(err);
    } else {
      console.log("Document created Successfully", response);
    }
  });
}
```

Inserting until ninth 9th doc it's perfectly inserting but when inserting the 10th doc it is inserting in second position.

The doc should be sorted by id and want to use it to view in another page.

I debugged but cannot find a solution, can anyone help me with the solution?

Thank you

答:
You have an errant notion regarding document insertion, whether as if the order of insertion with respect to time matters which is to be expected from say an RDBMS like MS/SQL, or a belief that a string representation of a numeric value should be sorted according to the implied numerical value (which would be wild guessing by the db).

As explicitly stated here, here and here, and as specified by the CouchDB documentation 3.2.2.5. Collation Specification

Comparison of strings is done using ICU which implements the Unicode Collation Algorithm, giving a dictionary sorting of keys. This can give surprising results if you were expecting ASCII ordering.

Documents are not returned by order of insertion rather they are returned according to the collation rules applied to the document ids, and document ids are strings.

For example you expect this ordering:

row #
id

0
1

1
2

2
3

3
4

4
5

5
6

6
7

7
8

8
9

9
10

BUT that is not according to the collation rules, which yields

row #
id

0
1

1
10

2
2

3
3

4
4

5
5

6
6

7
7

8
8

9
9

Again, it cannot be emphasized enough that the order of insertion, much less  an implied numeric value, does not affect the order of results.  From an RDBMS perspective it is helpful to approach _all_docs results as being ordered by an index on _id which is sorted according to collation rules (again, for strings since all _ids are of type string).

The snippet below demonstrates this by creating 100 documents with ids ranging from 1 to 100.

// generate canned test documents with doc _id's in the range 1 to 100.
function getDocsToInstall() {
  let docs = [];
  for (let i = 1; i < 101; i++) {
    //  _id must be a string type because that's the way it is, period.
    docs.push({
      _id: i.toString()
    });
  }
  return docs;
}

let db;

// init db instance
async function initDb() {

  db = new PouchDB('test', {
    adapter: 'memory'
  });
  await db.bulkDocs(getDocsToInstall());
}

initDb().then(async() => {
  let options = {
    limit: 25,
    include_docs: false,
    reduce: false
  };

  const result = await db.allDocs(options);
  showResult(result);

});

function gel(id) {
  return document.getElementById(id);
}

function cel(name) {
  return document.createElement(name);
}

function addColumn(tr, value) {
  const td = cel('td');
  td.innerText = value;
  tr.append(td);
}

function addRow(row, index) {
  const tr = cel('tr');
  [index, row.id].forEach(value => addColumn(tr, value));
  gel('table').append(tr);
}

function showResult(result) {
  const table = gel('table');
  result.rows.forEach((row, index) => {
    addRow(row, index);
  });
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>th,
td {
  padding: .5em;
  text-align: left;
  min-width: 4em;
}

table {
  border-collapse: collapse;
}</code>```

    row #
    id

```
</div>
</div>
</p>
<p>The must-get takeaway from the snippet is that the first 3 documents returned are</p>
<div class="s-table-container">
<table class="s-table">
<thead>
<tr>
<th>row #</th>
<th>id</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>1</td>
</tr>
<tr>
<td>1</td>
<td>10</td>
</tr>
<tr>
<td>2</td>
<td>100</td>
</tr>
</tbody>
</table>
</div>
<p>As janl pointed out here if you need to access documents in terms of numerical ordering, then creating a view is a good option, which the following snippet demonstrates.</p>
<p>The snippet shows results from _all_docs and the my_index view side by side.</p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="false" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>// generate canned test documents with doc _id's in the range 1 to 100.
function getDocsToInstall() {
  let docs = [];
  for (let i = 1; i < 101; i++) {
    //  _id must be a string type because that's the way it is, period.
    docs.push({
      _id: i.toString()
    });
  }
  // add a design doc/view for numerically ordered documents
  docs.push({
    _id: '_design/my_ddoc',
    views: {
      my_index: {
        map: function(doc) {
          emit(Number(doc._id));
        }.toString()
      }
    }
  })
  return docs;
}

let db;

// init db instance
async function initDb() {

  db = new PouchDB('test', {
    adapter: 'memory'
  });
  await db.bulkDocs(getDocsToInstall());
}

initDb().then(async() => {
  let options = {
    limit: 25,
    include_docs: false,
    reduce: false
  };

  const allDocs = await db.allDocs(options);
  const view = await db.query('my_ddoc/my_index');
  showResult(allDocs, view);

});

function gel(id) {
  return document.getElementById(id);
}

function cel(name) {
  return document.createElement(name);
}

function addColumn(tr, value) {
  const td = cel('td');
  td.innerText = value;
  tr.append(td);
}

function addRow(index, allDocs, view) {
  const tr = cel('tr');
  [index, allDocs.rows[index].key, view.rows[index].key].forEach(value => addColumn(tr, value));
  gel('table').append(tr);
}
// show allDocs and view results side by side
function showResult(allDocs, view) {
  const table = gel('table');
  for (let i = 0; i < allDocs.rows.length; i++) {
    addRow(i, allDocs, view);
  };
}</code>```

th,
td {
  padding: .5em;
  text-align: left;
  min-width: 4em;
}

table {
  border-collapse: collapse;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdn.jsdelivr.net/npm/pouchdb@7.1.1/dist/pouchdb.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
<table id="table" border="1">
  <tr>
    <th>row #</th>
    <th>_all_docs key</th>
    <th>my_index key</th>
  </tr>
</table></code>```

Note that for _all_docs, key and id are the document _id.  It's important to understand that _all_docs is in fact a built-in view which explains why key and id are present in _all_docs results.

If in fact you want documents ordered with respect to time, then add a creation timestamp to documents and build a view based on that timestamp, e.g. the map function might look like this if creationTime is an integer representing a point in time (milliseconds) in the Unix epoch.

function(doc) {
   emit(doc.creationTime);
}
```

Body:
I am working on small form in electron and pouchdb.

When inserting a data into db, until the ninth doc it inserting perfectly, but on 10th doc it is inserting to second position of doc instead on inserting into last

before inserting the 10th doc

{
  "total_rows": 9,
  "offset": 0,
    "rows": [
    { "id": "1", "key": "1", "value": {...} },
    { "id": "2", "key": "2", "value": {...} },
    { "id": "3", "key": "3", "value": {...} },
    { "id": "4", "key": "4", "value": {...} }
    { "id": "5", "key": "5", "value": {...} },
    { "id": "6", "key": "6", "value": {...} },
    { "id": "7", "key": "7", "value": {...} },
    { "id": "8", "key": "8", "value": {...} },
    { "id": "9", "key": "9", "value": {...} }
  ]
}

After inserting 10th doc

{
  "total_rows": 10,
  "offset": 0,
    "rows": [
    { "id": "1", "key": "1", "value": {...} },
    { "id": "10", "key": "10", "value": {...} },
    { "id": "2", "key": "2", "value": {...} },
    { "id": "3", "key": "3", "value": {...} },
    { "id": "4", "key": "4", "value": {...} }
    { "id": "5", "key": "5", "value": {...} },
    { "id": "6", "key": "6", "value": {...} },
    { "id": "7", "key": "7", "value": {...} },
    { "id": "8", "key": "8", "value": {...} },
    { "id": "9", "key": "9", "value": {...} }
  ]
}

here attached the js code

// form submit
const form = document.getElementById("form1");
form.addEventListener("submit", dbsubmit);

function dbsubmit(e) {
   e.preventDefault();
   //   getting values from form
   var Sno = document.getElementById("number").value
   var date = document.getElementById("date").value;
   var Time = document.getElementById("time").value;
   var Trip = document.querySelector('input[name="Trip"]:checked').value;
   var TripType = document.querySelector('input[name="Type"]:checked').value;

 // assigning form values to db table names
  var doc = {
    _id: Sno,
    Date: date,
    time: Time,
    trip: Trip,
    triptype: TripType,
  };

   // inserting to db
  db.put(doc, function(err, response) {
    if (err) {
      return console.log(err);
    } else {
      console.log("Document created Successfully", response);
    }
  });
}

Inserting until ninth 9th doc it's perfectly inserting but when inserting the 10th doc it is inserting in second position.

The doc should be sorted by id and want to use it to view in another page.

I debugged but cannot find a solution, can anyone help me with the solution?

Thank you

Body:
You have an errant notion regarding document insertion, whether as if the order of insertion with respect to time matters which is to be expected from say an RDBMS like MS/SQL, or a belief that a string representation of a numeric value should be sorted according to the implied numerical value (which would be wild guessing by the db).

As explicitly stated here, here and here, and as specified by the CouchDB documentation 3.2.2.5. Collation Specification

Comparison of strings is done using ICU which implements the Unicode Collation Algorithm, giving a dictionary sorting of keys. This can give surprising results if you were expecting ASCII ordering.

Documents are not returned by order of insertion rather they are returned according to the collation rules applied to the document ids, and document ids are strings.

For example you expect this ordering:

row #
id

0
1

1
2

2
3

3
4

4
5

5
6

6
7

7
8

8
9

9
10

BUT that is not according to the collation rules, which yields

row #
id

0
1

1
10

2
2

3
3

4
4

5
5

6
6

7
7

8
8

9
9

Again, it cannot be emphasized enough that the order of insertion, much less  an implied numeric value, does not affect the order of results.  From an RDBMS perspective it is helpful to approach _all_docs results as being ordered by an index on _id which is sorted according to collation rules (again, for strings since all _ids are of type string).

The snippet below demonstrates this by creating 100 documents with ids ranging from 1 to 100.

// generate canned test documents with doc _id's in the range 1 to 100.
function getDocsToInstall() {
  let docs = [];
  for (let i = 1; i < 101; i++) {
    //  _id must be a string type because that's the way it is, period.
    docs.push({
      _id: i.toString()
    });
  }
  return docs;
}

let db;

// init db instance
async function initDb() {

  db = new PouchDB('test', {
    adapter: 'memory'
  });
  await db.bulkDocs(getDocsToInstall());
}

initDb().then(async() => {
  let options = {
    limit: 25,
    include_docs: false,
    reduce: false
  };

  const result = await db.allDocs(options);
  showResult(result);

});

function gel(id) {
  return document.getElementById(id);
}

function cel(name) {
  return document.createElement(name);
}

function addColumn(tr, value) {
  const td = cel('td');
  td.innerText = value;
  tr.append(td);
}

function addRow(row, index) {
  const tr = cel('tr');
  [index, row.id].forEach(value => addColumn(tr, value));
  gel('table').append(tr);
}

function showResult(result) {
  const table = gel('table');
  result.rows.forEach((row, index) => {
    addRow(row, index);
  });
}

th,
td {
  padding: .5em;
  text-align: left;
  min-width: 4em;
}

table {
  border-collapse: collapse;
}

<script src="https://cdn.jsdelivr.net/npm/pouchdb@7.1.1/dist/pouchdb.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
<table id="table" border="1">
  <tr>
    <th>row #</th>
    <th>id</th>

  </tr>
</table>

The must-get takeaway from the snippet is that the first 3 documents returned are

row #
id

0
1

1
10

2
100

As janl pointed out here if you need to access documents in terms of numerical ordering, then creating a view is a good option, which the following snippet demonstrates.

The snippet shows results from _all_docs and the my_index view side by side.

// generate canned test documents with doc _id's in the range 1 to 100.
function getDocsToInstall() {
  let docs = [];
  for (let i = 1; i < 101; i++) {
    //  _id must be a string type because that's the way it is, period.
    docs.push({
      _id: i.toString()
    });
  }
  // add a design doc/view for numerically ordered documents
  docs.push({
    _id: '_design/my_ddoc',
    views: {
      my_index: {
        map: function(doc) {
          emit(Number(doc._id));
        }.toString()
      }
    }
  })
  return docs;
}

let db;

// init db instance
async function initDb() {

  db = new PouchDB('test', {
    adapter: 'memory'
  });
  await db.bulkDocs(getDocsToInstall());
}

initDb().then(async() => {
  let options = {
    limit: 25,
    include_docs: false,
    reduce: false
  };

  const allDocs = await db.allDocs(options);
  const view = await db.query('my_ddoc/my_index');
  showResult(allDocs, view);

});

function gel(id) {
  return document.getElementById(id);
}

function cel(name) {
  return document.createElement(name);
}

function addColumn(tr, value) {
  const td = cel('td');
  td.innerText = value;
  tr.append(td);
}

function addRow(index, allDocs, view) {
  const tr = cel('tr');
  [index, allDocs.rows[index].key, view.rows[index].key].forEach(value => addColumn(tr, value));
  gel('table').append(tr);
}
// show allDocs and view results side by side
function showResult(allDocs, view) {
  const table = gel('table');
  for (let i = 0; i < allDocs.rows.length; i++) {
    addRow(i, allDocs, view);
  };
}

th,
td {
  padding: .5em;
  text-align: left;
  min-width: 4em;
}

table {
  border-collapse: collapse;
}

<script src="https://cdn.jsdelivr.net/npm/pouchdb@7.1.1/dist/pouchdb.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
<table id="table" border="1">
  <tr>
    <th>row #</th>
    <th>_all_docs key</th>
    <th>my_index key</th>
  </tr>
</table>

Note that for _all_docs, key and id are the document _id.  It's important to understand that _all_docs is in fact a built-in view which explains why key and id are present in _all_docs results.

If in fact you want documents ordered with respect to time, then add a creation timestamp to documents and build a view based on that timestamp, e.g. the map function might look like this if creationTime is an integer representing a point in time (milliseconds) in the Unix epoch.

function(doc) {
   emit(doc.creationTime);
}


问:
How to deploy React (with solidity smart contracts) to S3 without error
So we wrote a Dapp with React in frontend and Solidity to write smart contracts. The smart contracts are deployed in infura polygon testnet. Now we wanted to deploy the S3 to Amazon S3, but when we try we get an error. The error is:

Creating an optimized production build... 254Failed to compile.
255256./src/components/MarketPlace/MarketPlace.js 257Cannot find file '../artifacts/MillMarket' in './src/components/MarketPlace'.
258259260npm ERR! code ELIFECYCLE 261npm ERR! errno 1 262npm ERR!
milliondollar@0.1.0 build: npm run build:css && react-scripts build
263npm ERR! Exit status 1 264npm ERR! 265npm ERR! Failed at the
milliondollar@0.1.0 build script. 266npm ERR! This is probably not a
problem with npm. There is likely additional logging output above.
267268npm ERR! A complete log of this run can be found in: 269npm ERR!
/root/.npm/_logs/2021-10-01T12_32_04_354Z-debug.log 270271[Container]
2021/10/01 12:32:04 Command did not exit successfully npm run build
exit status 1 272[Container] 2021/10/01 12:32:04 Phase complete: BUILD
State: FAILED 273[Container] 2021/10/01 12:32:04 Phase context status
code: COMMAND_EXECUTION_ERROR Message: Error while executing command:
npm run build. Reason: exit status 1274[Container] 2021/10/01 12:32:04
Entering phase POST_BUILD275[Container] 2021/10/01 12:32:04 Phase
complete: POST_BUILD State: SUCCEEDED 276[Container] 2021/10/01
12:32:04 Phase context status code: Message: 277[Container] 2021/10/01
12:32:04 Expanding base directory path: build 278[Container]
2021/10/01 12:32:04 Assembling file list 279[Container] 2021/10/01
12:32:04 Expanding build 280[Container] 2021/10/01 12:32:04 Expanding
file paths for base directory build 281[Container] 2021/10/01 12:32:04
Assembling file list 282[Container] 2021/10/01 12:32:04 Expanding */
283[Container] 2021/10/01 12:32:04 Found 8 file(s) 284[Container]
2021/10/01 12:32:04 Phase complete: UPLOAD_ARTIFACTS State: SUCCEEDED
285[Container] 2021/10/01 12:32:04 Phase context status code: Message:
286

Any idea what I can do to fix this? I think the "Cannot find file '../artifacts/MillMarket' in './src/components/MarketPlace'" part of the error is what is breaking deployment. I have a feeling that Create React App is missing the artifacts folder for some reason in the build file, but I am not sure. Stuck for 2 days.

Thanks!

答:
It is likely the contract "artifacts" directory is in gitignore.
If that is the case you could either remove "artifacts" from gitignore (which could mess with your repo) or place all relevant artifacts in a directory and import them into your frontend pages from the said directory.


问:
How to add second part to a discord command
I am trying to create a command for my discord.py bot. It is: ".see". The user who executes the command must specify the user that he'd like to see, by adding the user's name after the command. Ex: .see [user] | .see HelloWorld

My question is... how can I do this? How can I add this second part to the command?
This is all I have at the moment:

```<code>@bot.command()
async def see(ctx):
</code>```

答:
This is done by adding arguments to the python function. And there is even a way to automatically make the argument by a discord.Member so the command could be executed with .see @Member, .see member_id, .see MemberName#Discriminator and so on:

@bot.command()
async def see(ctx, person:discord.Member):
    ctx.send(person.display_name) # Person is now the member object the command has to be executed with
```

Body:
I am trying to create a command for my discord.py bot. It is: ".see". The user who executes the command must specify the user that he'd like to see, by adding the user's name after the command. Ex: .see [user] | .see HelloWorld

My question is... how can I do this? How can I add this second part to the command?
This is all I have at the moment:

@bot.command()
async def see(ctx):


问:
Get all contacts from sendgrid via api
I'm working on a app where I add the user to sendgrid during sign up using the api:

```<code>PUT /marketing/contacts
</code>```

I also add the user to specific list based on the status(DB data) of the user during signup.

Say I've 3 lists in sendgrid List A, List B, List C

Now I run a cron on every hour and check the status of the user and based on the condition I want to move the user from say List A to List B

As I checked I can add the user to the new list using the same api:

```<code>PUT /marketing/contacts
</code>```

And I can remove the user from the previous list I can use the api:

```<code>DELETE /marketing/lists/{id}/contacts
</code>```

But to in which list the user was previously added and to get the contact id from sendgrid I need to get the contacts from sendgrid, I'm using the api:

```<code>GET /marketing/contacts
</code>```

But this api is only returning last 50 data and pagination option is also not there.

I also tried the api:

```<code>GET https://api.sendgrid.com/v3/contactdb/recipients?page_size=100&page=1
</code>```

But this api is also returning me error

```<code>error:
{
  "errors": [
     {
       "field": null,
       "message": "access forbidden"
     }
  ]
}
</code>```

But the api key is fine because the marketing apis works with the same api key and the api key is generated with full access.

https://sendgrid.com/docs/API_Reference/api_v3.html
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html

Can someone please help me to get all contacts from sendgrid via any other api or if there is any params I'm missing in the above mentioned apis.

答:
I recently went through the same thing so want to add what I did in the hopes that this helps anyone with the same issue.

This is quick and dirty code that I used to test out how to grab an entire contact list without actually needing to open the file outside the script.

```<code>request = {
    "list_ids": [list_id]
}
response = sg.client.marketing.contacts.exports.post(
    request_body=request
)

export_json = response.body.decode('utf8').replace("'", '"')
export_data = json.loads(export_json)

export_id = export_data['id']

urls = []
while True:
    response = sg.client.marketing.contacts.exports._(export_id).get()
    export_status_json = response.body.decode('utf8').replace("'", '"')
    export_status_data = json.loads(export_status_json)
    urls = export_status_data['urls']

    if len(urls) == 0:
        time.sleep(10)
    else:
        break

for url in urls:
    response = requests.get(url)
    out_file = gzip.decompress(response.content).decode('utf8'))
    pd = pandas.read_csv(io.StringIO(out_file), dtype=str)

</code>```

If you want json, add that to the request body and read it as

```<code>for url in urls:
    response = requests.get(url)
    out_file = gzip.decompress(response.content).decode('utf8').replace("'", '"')

    print(out_file)
</code>```

Title: Get all contacts from sendgrid via api

Body:
I'm working on a app where I add the user to sendgrid during sign up using the api:

PUT /marketing/contacts

I also add the user to specific list based on the status(DB data) of the user during signup.

Say I've 3 lists in sendgrid List A, List B, List C

Now I run a cron on every hour and check the status of the user and based on the condition I want to move the user from say List A to List B

As I checked I can add the user to the new list using the same api:

PUT /marketing/contacts

And I can remove the user from the previous list I can use the api:

DELETE /marketing/lists/{id}/contacts

But to in which list the user was previously added and to get the contact id from sendgrid I need to get the contacts from sendgrid, I'm using the api:

GET /marketing/contacts

But this api is only returning last 50 data and pagination option is also not there.

I also tried the api:

GET https://api.sendgrid.com/v3/contactdb/recipients?page_size=100&page=1

But this api is also returning me error

error:
{
  "errors": [
     {
       "field": null,
       "message": "access forbidden"
     }
  ]
}

But the api key is fine because the marketing apis works with the same api key and the api key is generated with full access.

https://sendgrid.com/docs/API_Reference/api_v3.html
https://sendgrid.com/docs/API_Reference/Web_API_v3/Marketing_Campaigns/contactdb.html

Can someone please help me to get all contacts from sendgrid via any other api or if there is any params I'm missing in the above mentioned apis.

Body:
I recently went through the same thing so want to add what I did in the hopes that this helps anyone with the same issue.

This is quick and dirty code that I used to test out how to grab an entire contact list without actually needing to open the file outside the script.

request = {
    "list_ids": [list_id]
}
response = sg.client.marketing.contacts.exports.post(
    request_body=request
)

export_json = response.body.decode('utf8').replace("'", '"')
export_data = json.loads(export_json)

export_id = export_data['id']

urls = []
while True:
    response = sg.client.marketing.contacts.exports._(export_id).get()
    export_status_json = response.body.decode('utf8').replace("'", '"')
    export_status_data = json.loads(export_status_json)
    urls = export_status_data['urls']

    if len(urls) == 0:
        time.sleep(10)
    else:
        break

for url in urls:
    response = requests.get(url)
    out_file = gzip.decompress(response.content).decode('utf8'))
    pd = pandas.read_csv(io.StringIO(out_file), dtype=str)

If you want json, add that to the request body and read it as

for url in urls:
    response = requests.get(url)
    out_file = gzip.decompress(response.content).decode('utf8').replace("'", '"')

    print(out_file)


问:
How to update table from JSON flowfile
I have a flow-files with the below structure

```<code>{
  "PN" : "U0-WH",
  "INPUT_DATE" : "44252.699895833335",
  "LABEL" : "Marker",
  "STATUS" : "Approved",
}
</code>```

and I need to execute an update statement using some fields

```<code>update table1 set column1 = 'value' where pn=${PN}
</code>```

I found convertJsonToSQL but am not sure how to use it in this case

答:
You can use a processor namely ConvertjSONToSQL. Using this you can convert your json into an update query.

ConvertjSONToSQL Description

It takes the following parameters :

1. JDBC Connection Pool : Create a JDBC pool which takes DB connection information as input.

2. Statement Type : Here you need to provide type of statement you want to create. In your case its 'UPDATE'.

3. Table Name : Name of the table for which update query needed to be created

4. Schema Name : Name of the schema of your database.

5. Translate Field Names : If true, the Processor will attempt to translate JSON field names into the appropriate column names for the table specified. If false, the JSON field names must match the column names exactly, or the column will not be updated

6. Unmatched Field Behaviour : if an incoming JSON element has a field that does not map to any of the database table's columns, this property specifies how to handle the situation

7. Unmatched Column Behaviour : If an incoming JSON element does not have a field mapping for all of the database table's columns, this property specifies how to handle the situation

8. Update Keys : A comma-separated list of column names that uniquely identifies a row in the database for UPDATE statements. If the Statement Type is UPDATE and this property is not set, the table's Primary Keys are used. In this case, if no Primary Key exists, the conversion to SQL will fail if Unmatched Column Behaviour is set to FAIL. This property is ignored if the Statement Type is INSERT
Supports Expression Language: true (will be evaluated using flow file attributes and variable registry)

Read the description above and try to use the properties given. Detailed description of the processor is given in the link.
ConvertjSONToSQL Description

Title: How to update table from JSON flowfile

Body:
I have a flow-files with the below structure

{
  "PN" : "U0-WH",
  "INPUT_DATE" : "44252.699895833335",
  "LABEL" : "Marker",
  "STATUS" : "Approved",
}

and I need to execute an update statement using some fields

update table1 set column1 = 'value' where pn=${PN}

I found convertJsonToSQL but am not sure how to use it in this case


问:
Python Unittest Allow Multiple Possible Return Values
I'm writing a unittest that will be run on my class's code. For one of the functions they must write, there are two possible return values that they could return and either one is okay for my purposes.

I've been using

```<code>actual = my_function_call(arg1, arg2)
self.assertEqual(actual, expected)
</code>```

But this doesn't work for accepting one of two valid return values, so I've changed it to:

```<code>actual = my_function_call(arg1, arg2)
self.assertEqual(actual == expected1 or actual == expected2, True)
</code>```

Is there a way to do this that isn't as hacky?

答:
There exists assertIn test, which you could use in this case as follows

```<code>self.assertIn(actual,[expected1,expected2])
</code>```

it does check if actual is present in list holding expected1,expected2.

Body:
I'm writing a unittest that will be run on my class's code. For one of the functions they must write, there are two possible return values that they could return and either one is okay for my purposes.

I've been using

actual = my_function_call(arg1, arg2)
self.assertEqual(actual, expected)

But this doesn't work for accepting one of two valid return values, so I've changed it to:

actual = my_function_call(arg1, arg2)
self.assertEqual(actual == expected1 or actual == expected2, True)

Is there a way to do this that isn't as hacky?

Body:
There exists assertIn test, which you could use in this case as follows

self.assertIn(actual,[expected1,expected2])

it does check if actual is present in list holding expected1,expected2.


问:
Append data in one dimenssional list to a multidimensional list
I have a list as follows:

```<code>List<String> responseList = new ArrayList<>();
 responseList.add("test1")
 responseList.add("test2")
 responseList.add("test3")
 responseList.add("test4")
</code>```

I need to add the data in the above list to the below list in which 0 th row should have values test1 and test2 . 1 st row should have test3 and test4

```<code>List<List<String>> ActualEmployeeList  = new ArrayList<>();
</code>```

答:
You can do something like this. The key to this is that you do not always need to do i++ in your for loop. Also, I think it would make sense to create the lists separately instead of just adding everything to response list.</p>
```<code>        List<String> responseList = new ArrayList<>();
        responseList.add("test1");
        responseList.add("test2");
        responseList.add("test3");
        responseList.add("test4");

        List<List<String>> actualEmployeeList = new ArrayList<>();

        for(int i = 0; i < responseList.size(); i+=2) {
            actualEmployeeList.add(responseList.subList(i, i+2));
        }
</code>```

Body:
I have a list as follows:

List<String> responseList = new ArrayList<>();
 responseList.add("test1")
 responseList.add("test2")
 responseList.add("test3")
 responseList.add("test4")

I need to add the data in the above list to the below list in which 0 th row should have values test1 and test2 . 1 st row should have test3 and test4

List<List<String>> ActualEmployeeList  = new ArrayList<>();

Body:
You can do something like this. The key to this is that you do not always need to do i++ in your for loop. Also, I think it would make sense to create the lists separately instead of just adding everything to response list.

        List<String> responseList = new ArrayList<>();
        responseList.add("test1");
        responseList.add("test2");
        responseList.add("test3");
        responseList.add("test4");

        List<List<String>> actualEmployeeList = new ArrayList<>();

        for(int i = 0; i < responseList.size(); i+=2) {
            actualEmployeeList.add(responseList.subList(i, i+2));
        }


问:
Text inside bars dynamic and responsive
I want to achieve something like this:

Im trying to have the bars dynamic in addition to the length of the text and it should be fully responsive. Im interested in your approaches.

答:
Try this one.

.container{
  display:flex;
  flex-direction:column;
  align-items:flex-start;
  font-weight:bold;
}
.res{
  background-color: gainsboro;
  padding:0.5rem;
  margin:5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="container">
  <p class="res">Hello World </p>
  <p class="res">This is my Task for you </p>
  <p class="res">guys, hope you enjoy it </p>
</div></code>```

Title: Text inside bars dynamic and responsive

Body:
Try this one.

.container{
  display:flex;
  flex-direction:column;
  align-items:flex-start;
  font-weight:bold;
}
.res{
  background-color: gainsboro;
  padding:0.5rem;
  margin:5px;
}

<div class="container">
  <p class="res">Hello World </p>
  <p class="res">This is my Task for you </p>
  <p class="res">guys, hope you enjoy it </p>
</div>


问:
Use hook in class component React
Hello I have checked the few articles on the subject, but I was not successful in doing the same.
I would like if possible an example if possible.

import React from 'react'
import { useInView } from 'react-intersection-observer'

const Component = () => {
  const [ref, inView, entry] = useInView({
    /* Optional options */
    threshold: 0,
  })

  return (

{`Header inside viewport ${inView}.`}

  )
}```
</div>
</div>
</p>
<p>it's ok</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class Nameclasse extends Component
{
   constructor(props)
    {
      super(props);

      const [ref, inView, entry] = useInView({
        /* Optional options */
        threshold: 0,
      })
    }
     render()
    {

      return (<div></div>);
    }

}</code>```

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

You might have mismatching versions of React and the renderer (such as React DOM)

You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app
See fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

答:
State management with a Hook is exclusive to development by function, for any change of a state in a class you must go through the inherited function this.setState();

Function ex :

```<code>function Counter() {
    const [count,setCount] = useInView(0)
    return (<div> <button onclick={() => {setCount(count + 1)}}>Click me + 1</button> {count}</div>);
}
</code>```

Title: Use hook in class component React

Body:
Hello I have checked the few articles on the subject, but I was not successful in doing the same.
I would like if possible an example if possible.

import React from 'react'
import { useInView } from 'react-intersection-observer'

const Component = () => {
  const [ref, inView, entry] = useInView({
    /* Optional options */
    threshold: 0,
  })

  return (

{`Header inside viewport ${inView}.`}

  )
}

it's ok

class Nameclasse extends Component
{
   constructor(props)
    {
      super(props);

      const [ref, inView, entry] = useInView({
        /* Optional options */
        threshold: 0,
      })
    }
     render()
    {

      return (

);
    }

}

Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

You might have mismatching versions of React and the renderer (such as React DOM)

You might be breaking the Rules of Hooks

You might have more than one copy of React in the same app
See fb.me/react-invalid-hook-call for tips about how to debug and fix this problem.

Body:
State management with a Hook is exclusive to development by function, for any change of a state in a class you must go through the inherited function this.setState();

Function ex :

function Counter() {
    const [count,setCount] = useInView(0)
    return (<div> <button onclick={() => {setCount(count + 1)}}>Click me + 1</button> {count}</div>);
}


问:
Format Sitemap Style Memaid JS
I am using the following Mermaid MD to create a sitemap.

Example

      flowchart TD
        A(Home)-->B(Col 1 - Level 1)
        A-->C(Col 2 - Level 1)
        C-->F(Col 2 - Level 2)
        A-->G(Col 3 - Level 1)
        G-->H(Col 3 - Level 2)
        H-->I(Col 3 - Level 3)
        A-->J(Col 4 - Level 1)
        J-->K(Col 4 - Level 2)
        A-->L(Col 5 - Level 1)
        B-->E(End)
        F-->E
        I-->E
        K-->E

```

Which renders like the image below. See the Codepen.

I would like it to respect the column order and align it more like an old school sitemap.

Does anybody know if this is possible?

答:
You can accomplish this using the built-in subgraph functionality. The following appears to do what you want:</p>
```<code>      flowchart TD
      subgraph one
        A(Home)-->B(Col 1 - Level 1)
        A-->C(Col 2 - Level 1)
        A-->G(Col 3 - Level 1)
        A-->J(Col 4 - Level 1)
        A-->L(Col 5 - Level 1)
      end
      subgraph two
        C-->F(Col 2 - Level 2)
        J-->K(Col 4 - Level 2)
        G-->H(Col 3 - Level 2)
      end
        H-->I(Col 3 - Level 3)
        B-->E(End)
        F-->E
        I-->E
        K-->E
</code>```

Title: Format Sitemap Style Memaid JS

Body:
I am using the following Mermaid MD to create a sitemap.

Example

      flowchart TD
        A(Home)-->B(Col 1 - Level 1)
        A-->C(Col 2 - Level 1)
        C-->F(Col 2 - Level 2)
        A-->G(Col 3 - Level 1)
        G-->H(Col 3 - Level 2)
        H-->I(Col 3 - Level 3)
        A-->J(Col 4 - Level 1)
        J-->K(Col 4 - Level 2)
        A-->L(Col 5 - Level 1)
        B-->E(End)
        F-->E
        I-->E
        K-->E

Which renders like the image below. See the Codepen.

I would like it to respect the column order and align it more like an old school sitemap.

Does anybody know if this is possible?

Body:
You can accomplish this using the built-in subgraph functionality. The following appears to do what you want:

      flowchart TD
      subgraph one
        A(Home)-->B(Col 1 - Level 1)
        A-->C(Col 2 - Level 1)
        A-->G(Col 3 - Level 1)
        A-->J(Col 4 - Level 1)
        A-->L(Col 5 - Level 1)
      end
      subgraph two
        C-->F(Col 2 - Level 2)
        J-->K(Col 4 - Level 2)
        G-->H(Col 3 - Level 2)
      end
        H-->I(Col 3 - Level 3)
        B-->E(End)
        F-->E
        I-->E
        K-->E


问:
Android folder monitor
Am using sdcard for saving data ,my problem is that when app is running and  some one delete this folder then the application fail. Is there anyway to notify the app , when this folder get deleted ?. Please help me</p>

答:
Try like this.   </p>

```<code> private static File logFile = null;
    String SD_CARD_PATH = Environment.getExternalStorageDirectory().toString();
    logFile = new File(SD_CARD_PATH + "/" + "folderName");
    if (logFile.exists()){
       //exist.so do your work
    }
    else{
      //not exists
    }
</code>```

Title: Android folder monitor

Body:
Try like this.

 private static File logFile = null;
    String SD_CARD_PATH = Environment.getExternalStorageDirectory().toString();
    logFile = new File(SD_CARD_PATH + "/" + "folderName");
    if (logFile.exists()){
       //exist.so do your work
    }
    else{
      //not exists
    }


问:
github pages ignoring 2022 dates in liquid {{ page.date }}?? fine in local host
Using Jekyll to build a site, I have discrepancies between my local build and what GitHub pages renders.

I have a .html layout that uses the date property of the page for the title:

```<code><h1>Meeting notes - {{ page.date | date_to_string }}</h1>
</code>```

and the date is obtained thanks to the page's name YYYY-MM-DD-notes.html.

I then use a for loop to parse through all the meetings I have in site.meetings and display all meeting notes after one another in a meetings.html page.

My last two files are called: 2021-12-07-notes.html and 2022-01-18-notes.html so the first two titles in my meetings page should be:

Meeting notes - 18 Jan 2022

Meeting notes - 07 Dec 2021

Which is indeed what I get in my local build (along with all the previous ones, first meeting being in 2019).

But what GitHub pages renders is:

Meeting notes -

Meeting notes - 07 Dec 2021

As if he couldn't 'see' the 2022 date. Still working fine with all previous dates btw and again, on the local build.

Could someone explain this weird behavior?

答:
Ok this was simply because I didn't have the right file name.

The file was actually called 2022-01-18_notes.md and not 2022-01-18-notes.md which made GitHub pages not recognise the date. Apparently my local jekyll is a bit more tolerant.

Body:
Using Jekyll to build a site, I have discrepancies between my local build and what GitHub pages renders.

I have a .html layout that uses the date property of the page for the title:

Meeting notes - {{ page.date | date_to_string }}

and the date is obtained thanks to the page's name YYYY-MM-DD-notes.html.

I then use a for loop to parse through all the meetings I have in site.meetings and display all meeting notes after one another in a meetings.html page.

My last two files are called: 2021-12-07-notes.html and 2022-01-18-notes.html so the first two titles in my meetings page should be:

Meeting notes - 18 Jan 2022

Meeting notes - 07 Dec 2021

Which is indeed what I get in my local build (along with all the previous ones, first meeting being in 2019).

But what GitHub pages renders is:

Meeting notes -

Meeting notes - 07 Dec 2021

As if he couldn't 'see' the 2022 date. Still working fine with all previous dates btw and again, on the local build.

Could someone explain this weird behavior?


问:
How to add two conditions in merge statement using rowid and rownum
```<code>CREATE SEQUENCE e_demo2_tab_sq;

CREATE TABLE e_demo2_tab
(
    tab_id   NUMBER(10) DEFAULT e_demo2_tab_sq.nextval NOT NULL,
    e_id     NUMBER(10),
    e_uuid   NUMBER(10),
    seq_cnt  NUMBER(10)
);

INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 13, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 13, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 16, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 15, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 14, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 14, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 15, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 16, null);
</code>```

Query to load the sequence for e_uuid 13 & 15

```<code>merge into e_demo2_tab a
      using (select
               rowid rid,
               row_number() over (partition by e_id, e_uuid order by rowid) rn
             from e_demo2_tab where e_uuid in(13,15)
            ) x
    on (a.rowid = x.rid)
    when matched then update set a.seq_cnt = x.rn;
</code>```

Then I want to merge into the same table for e_uuid 14 & 16
For 14: It should check e_uuid = 13 and maximum seq_cnt. Here(after executing my merge statement) maximum seq_cnt is 2 then the seq_cnt for 14 will come as 3 & 4. And if there are any null values then need to give by default 1 in seq_cnt

For 16: It should check e_uuid = 15 and maximum seq_cnt. Here(after executing my merge statement) maximum seq_cnt is 2 then the seq_cnt for 16 will come as 3 & 4.

Output after executing the merge statement given above

```<code>+--------+------+--------+---------+
| TAB_ID | E_ID | E_UUID | SEQ_CNT |
+--------+------+--------+---------+
|      1 | 11   |     13 | 1       |
|      2 | 11   |     13 | 2       |
|      3 | 11   |     16 | null    |
|      4 | 11`  |     15 | 1       |
|      5 | 11   |     14 | null    |
|      6 | 11   |     14 | null    |
|      7 | 11   |     15 | 2       |
|      8 | 11   |     16 | null    |
+--------+------+--------+---------+
</code>```

Expected Output:

```<code>+--------+------+--------+---------+
| TAB_ID | E_ID | E_UUID | SEQ_CNT |
+--------+------+--------+---------+
|      1 | 11   |     13 |       1 |
|      2 | 11   |     13 |       2 |
|      3 | 11   |     16 |       3 |
|      4 | 11`  |     15 |       1 |
|      5 | 11   |     14 |       3 |
|      6 | 11   |     14 |       4 |
|      7 | 11   |     15 |       2 |
|      8 | 11   |     16 |       4 |
+--------+------+--------+---------+
</code>```

答:
If you're wanting to group an odd and a consecutive even e_uuid together, you could always change the partition by clause to group on ceil(e_uuid/2), like so:

```<code>merge into e_demo2_tab a
      using (select
               rowid rid,
               row_number() over (partition by e_id, ceil(e_uuid/2) order by e_uuid, rowid) rn
             from e_demo2_tab) x
    on (a.rowid = x.rid)
    when matched then update set a.seq_cnt = x.rn;
</code>```

db<>fiddle

This works because 13/2 = 6.5, and the ceiling value of 6.5 = 7. 14/2 = 7, the ceiling value of which is also 7, since it's already an integer. That makes 13 and 14 grouped together - same logic applies to 15 and 16 - the ceiling of them divided by two comes to 8 for both values.

So that explains the logic behind grouping them together (13 is odd, and 14 is the next consecutive even number).

The rows are then ordered by e_uuid, and then rowid to get the ordering you were after.

If you are only ever concerned about the 13, 14, 15, and 16 e_uuids, you might want to have a filter in your x subquery of where e_uuid in (13, 14, 15, 16), depending on if there are other values of e_uuid in your table.

Body:
CREATE SEQUENCE e_demo2_tab_sq;

CREATE TABLE e_demo2_tab
(
    tab_id   NUMBER(10) DEFAULT e_demo2_tab_sq.nextval NOT NULL,
    e_id     NUMBER(10),
    e_uuid   NUMBER(10),
    seq_cnt  NUMBER(10)
);

INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 13, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 13, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 16, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 15, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 14, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 14, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 15, null);
INSERT INTO e_demo2_tab VALUES(e_demo2_tab_sq.nextval, 11, 16, null);

Query to load the sequence for e_uuid 13 & 15

merge into e_demo2_tab a
      using (select
               rowid rid,
               row_number() over (partition by e_id, e_uuid order by rowid) rn
             from e_demo2_tab where e_uuid in(13,15)
            ) x
    on (a.rowid = x.rid)
    when matched then update set a.seq_cnt = x.rn;

Then I want to merge into the same table for e_uuid 14 & 16
For 14: It should check e_uuid = 13 and maximum seq_cnt. Here(after executing my merge statement) maximum seq_cnt is 2 then the seq_cnt for 14 will come as 3 & 4. And if there are any null values then need to give by default 1 in seq_cnt

For 16: It should check e_uuid = 15 and maximum seq_cnt. Here(after executing my merge statement) maximum seq_cnt is 2 then the seq_cnt for 16 will come as 3 & 4.

Output after executing the merge statement given above

+--------+------+--------+---------+
| TAB_ID | E_ID | E_UUID | SEQ_CNT |
+--------+------+--------+---------+
|      1 | 11   |     13 | 1       |
|      2 | 11   |     13 | 2       |
|      3 | 11   |     16 | null    |
|      4 | 11`  |     15 | 1       |
|      5 | 11   |     14 | null    |
|      6 | 11   |     14 | null    |
|      7 | 11   |     15 | 2       |
|      8 | 11   |     16 | null    |
+--------+------+--------+---------+

Expected Output:

+--------+------+--------+---------+
| TAB_ID | E_ID | E_UUID | SEQ_CNT |
+--------+------+--------+---------+
|      1 | 11   |     13 |       1 |
|      2 | 11   |     13 |       2 |
|      3 | 11   |     16 |       3 |
|      4 | 11`  |     15 |       1 |
|      5 | 11   |     14 |       3 |
|      6 | 11   |     14 |       4 |
|      7 | 11   |     15 |       2 |
|      8 | 11   |     16 |       4 |
+--------+------+--------+---------+

Body:
If you're wanting to group an odd and a consecutive even e_uuid together, you could always change the partition by clause to group on ceil(e_uuid/2), like so:

merge into e_demo2_tab a
      using (select
               rowid rid,
               row_number() over (partition by e_id, ceil(e_uuid/2) order by e_uuid, rowid) rn
             from e_demo2_tab) x
    on (a.rowid = x.rid)
    when matched then update set a.seq_cnt = x.rn;

db<>fiddle

This works because 13/2 = 6.5, and the ceiling value of 6.5 = 7. 14/2 = 7, the ceiling value of which is also 7, since it's already an integer. That makes 13 and 14 grouped together - same logic applies to 15 and 16 - the ceiling of them divided by two comes to 8 for both values.

So that explains the logic behind grouping them together (13 is odd, and 14 is the next consecutive even number).

The rows are then ordered by e_uuid, and then rowid to get the ordering you were after.

If you are only ever concerned about the 13, 14, 15, and 16 e_uuids, you might want to have a filter in your x subquery of where e_uuid in (13, 14, 15, 16), depending on if there are other values of e_uuid in your table.


问:
The input is not a valid Base64 string as it contains a non-base 64 character
I am receiving below token to my  asp.net core api from flutter mobile app , which I need to send to firebase api to verify my token and get firebase uid. My code in .net core is

```<code>   FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(token);
   string uid = decodedToken.Uid;
</code>```

I get the error as

The input is not a valid Base-64 string as it contains a non-base 64
character, more than two padding characters, or an illegal character
among the padding characters.

I tried adding '=' at the end to make the length divisible by 4 . But didnt work . Can anyone help ?

```<code>token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjZjZmMyMzViZDYxMGZhY2FlYzVlYjBhZGU5NTg5ZGE5NTI4MmRlY2QiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiUHJhYmhha2FyIiwiYWRtaW4iOnRydWUsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9ydXRodW1hbmEtYXBwIiwiYXVkIjoicnV0aHVtYW5hLWFwcCIsImF1dGhfdGltZSI6MTU5NTE3MTE4MCwidXNlcl9pZCI6IjVVTUVoY1pGUklQUVRZSXYyUkt4Tk01cTdHbzIiLCJzdWIiOiI1VU1FaGNaRlJJUFFUWUl2MlJLeE5NNXE3R28yIiwiaWF0IjoxNTk1MzYxNDQyLCJleHAiOjE1OTUzNjUwNDIsImVtYWlsIjoicHJhYmhha2FyYmhhdEBsaXZlLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaG9uZV9udW1iZXIiOiIrOTE4NTUzNzUyNzQyIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJwaG9uZSI6WyIrOTE4NTUzNzUyNzQyIl0sImVtYWlsIjpbInByYWJoYWthcmJoYXRAbGl2ZS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwaG9uZSJ9fQ.N-fFCQHnJkdVcSqRQQ7XetEPQEeLCjOofjv3UogJlehLlUiJZhoKO6UWnb_liNxuTaFQ7tzvl03rHbm12na6KkhMup0J_UkC7HCyG6EtZmCgc8KmFRoYtHbztiCNI9v26QLPI_5C-KCnMDJdnvmGfuhh5NmmR5gC1LVuXMxZxaQFzcs1fkuA_8mCY1t4s0x0mQyeBUdrLVZnWdVSzM9-g1WZ0xrCrcsf7WTdWpuWeRmSIJSmNagP_l7R-uYUnTtwNISgFVn4mhSz4O1dqav7167TK2Z1PQD1QDhMA3FTIoYsc9izdlXQvmkbLxkq8dvhgxYVY"
</code>```

答:
A possible cause of this issue is that the idToken you received was truncated in the console output, resulting in an invalid token. This is a reported issue, see here, Flutter's print() method seems to only print a maximum of 1024-bit so a idToken is likely to be truncated. If you wish to get the token to appear fully, either:

With debug mode, inspect the idToken value

Without debug mode, use the log(token) method by import 'dart:developer'; instead of print()

Body:
I am receiving below token to my  asp.net core api from flutter mobile app , which I need to send to firebase api to verify my token and get firebase uid. My code in .net core is

   FirebaseToken decodedToken = await FirebaseAuth.DefaultInstance.VerifyIdTokenAsync(token);
   string uid = decodedToken.Uid;

I get the error as

The input is not a valid Base-64 string as it contains a non-base 64
character, more than two padding characters, or an illegal character
among the padding characters.

I tried adding '=' at the end to make the length divisible by 4 . But didnt work . Can anyone help ?

token = "eyJhbGciOiJSUzI1NiIsImtpZCI6IjZjZmMyMzViZDYxMGZhY2FlYzVlYjBhZGU5NTg5ZGE5NTI4MmRlY2QiLCJ0eXAiOiJKV1QifQ.eyJuYW1lIjoiUHJhYmhha2FyIiwiYWRtaW4iOnRydWUsImlzcyI6Imh0dHBzOi8vc2VjdXJldG9rZW4uZ29vZ2xlLmNvbS9ydXRodW1hbmEtYXBwIiwiYXVkIjoicnV0aHVtYW5hLWFwcCIsImF1dGhfdGltZSI6MTU5NTE3MTE4MCwidXNlcl9pZCI6IjVVTUVoY1pGUklQUVRZSXYyUkt4Tk01cTdHbzIiLCJzdWIiOiI1VU1FaGNaRlJJUFFUWUl2MlJLeE5NNXE3R28yIiwiaWF0IjoxNTk1MzYxNDQyLCJleHAiOjE1OTUzNjUwNDIsImVtYWlsIjoicHJhYmhha2FyYmhhdEBsaXZlLmNvbSIsImVtYWlsX3ZlcmlmaWVkIjp0cnVlLCJwaG9uZV9udW1iZXIiOiIrOTE4NTUzNzUyNzQyIiwiZmlyZWJhc2UiOnsiaWRlbnRpdGllcyI6eyJwaG9uZSI6WyIrOTE4NTUzNzUyNzQyIl0sImVtYWlsIjpbInByYWJoYWthcmJoYXRAbGl2ZS5jb20iXX0sInNpZ25faW5fcHJvdmlkZXIiOiJwaG9uZSJ9fQ.N-fFCQHnJkdVcSqRQQ7XetEPQEeLCjOofjv3UogJlehLlUiJZhoKO6UWnb_liNxuTaFQ7tzvl03rHbm12na6KkhMup0J_UkC7HCyG6EtZmCgc8KmFRoYtHbztiCNI9v26QLPI_5C-KCnMDJdnvmGfuhh5NmmR5gC1LVuXMxZxaQFzcs1fkuA_8mCY1t4s0x0mQyeBUdrLVZnWdVSzM9-g1WZ0xrCrcsf7WTdWpuWeRmSIJSmNagP_l7R-uYUnTtwNISgFVn4mhSz4O1dqav7167TK2Z1PQD1QDhMA3FTIoYsc9izdlXQvmkbLxkq8dvhgxYVY"


问:
Branch from the past in mercurial
I'm a single developer using Mercurial to create a program.  I have so far committed at every step of developing, and I have messed things up and want to work on something else.

How shall I go to a previous state (ie. rollback) and then create a branch, maintaining the newer states?

Does rollback ever delete anything?  Should that be all I do? Just rollback untill I'm at the place where I want, edit, then commit?  Will I be able to merge the changesets later, or at least look at them?  Of course I can just save this repository, rollback, and then create new changesets, then merge the two repositories?

I'm new to SCM and of course DSCM, so be gentle :)

答:
You don't want to use hg rollback, that only erases exactly one change (the most recent). See You Can Only Roll Back Once in the hg book.

To make a branch from an earlier revision, you need to find the revision number you want to branch from and run:

```<code>hg clone -r <revnum> <source repository> <destination repository>
</code>```

You can then do your changes in the newly-cloned repository (which will not contain any of the history that came after the revision number you specified) and then merge those changes back into the original later, if you wish.

ContentLicense: CC BY-SA 2.5

Title: Branch from the past in mercurial

LastEditorDisplayName: Chad Birch

Body:
You don't want to use hg rollback, that only erases exactly one change (the most recent). See You Can Only Roll Back Once in the hg book.

To make a branch from an earlier revision, you need to find the revision number you want to branch from and run:

hg clone -r <revnum> <source repository> <destination repository>

You can then do your changes in the newly-cloned repository (which will not contain any of the history that came after the revision number you specified) and then merge those changes back into the original later, if you wish.

OwnerDisplayName: Chad Birch


问:
Im trying to create an array of user Objects in local Storage using vanilla JS
I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead</p>
```<code>//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))

}

storeUsers(newUser);
</code>```

答:
You are missing quotes around users :

```<code>if (localStorage.getItem("users") === null) {
</code>```

Body:
I'm creating a simple quiz app and i would like to store an object of each user and their score in an array stored in local Storage. The problem is every time I initiate the function instead of adding a new object to the array the existing object values are changed instead

//JS code

function storeUsers(userObject) {
    if (localStorage.getItem(users) === null) {
        users = []
    } else {
        users = JSON.parse(localStorage.getItem(users))
    }

     const userScoreTemplate = function (usersName, usersScore) {
            this.user = usersName;
            this.score = usersScore;
        }

        newUser = new userScoreTemplate(userName, score);

    users.push(userObject);
    localStorage.setItem("users", JSON.stringify(users))

}

storeUsers(newUser);

Body:
You are missing quotes around users :

if (localStorage.getItem("users") === null) {


问:
Javascript onclick event out of phase in Angular
Using Angular framework to build my website's front-end, I'm trying to include a button/icon capable of opening and closing this sidenav:

```<code><nav id="left-sidenav" class="sidenav">
<div class="local_nav">
    <a class="link" href="#">About</a>
    <a class="link" href="#">Services</a>
    <a class="link" href="#">Clients</a>
    <a class="link" href="#">Contact</a>
</div>
</nav>
</code>```

I found a cool hamburger fold-out menu on codepen.io, and I ended up modelling the HTML code this way.

```<code><div id="menuToggle">
<input type="checkbox" onclick="toggleNav()" />
<span></span>
<span></span>
<span></span>
<ul id="menu"></ul>
</div>
</code>```

With this being the toggleNav() function (added to index.html head):

```<code><script>
    //sidenav-width: 150px (this is defined in sidenav.component.scss)
    function toggleNav() {
        var x = document.getElementById("left-sidenav");
        if (x.style.width === "0px") {
            //openNav
            x.style.width = "150px";
        } else {
            //closeNav
            x.style.width = "0px";
        }
    }
</script>
</code>```

So when the page is loaded, it looks like this [please don't mind the image, it's my first time using Angular and I'm trying to get better :) ]:
Reloaded page

Now, for some reason, when trying to use this burger menu the first click doesn't trigger the onclick event, and the icon ends up transforming (as it should do) in a cross (see the codepen.io CSS).
Page after the first click

On the second click though, the event seems to start working and the sidenav finally shows up, with the cross reverting into the burger icon. If I keep clicking on the burger, it just works as it should, with the icon being out of phase.
Page after the second click;
Page after the third click

This makes no sense to me, and I initially wanted to get the cross when the sidenav is shown, not when it's hidden.
Does anyone know how to actually fix this?

答:
You can change the implementation of the function toggleNav() for this:

In your .ts file add this.

```<code>toggle: boolean = false;

toggleNav() {
    this.toggle = !this.toggle;
    window.scrollTo(0, 0);
  }
</code>```

Body:
Using Angular framework to build my website's front-end, I'm trying to include a button/icon capable of opening and closing this sidenav:

    About
    Services
    Clients
    Contact

I found a cool hamburger fold-out menu on codepen.io, and I ended up modelling the HTML code this way.

<input type="checkbox" onclick="toggleNav()" />

With this being the toggleNav() function (added to index.html head):

So when the page is loaded, it looks like this [please don't mind the image, it's my first time using Angular and I'm trying to get better :) ]:
Reloaded page

Now, for some reason, when trying to use this burger menu the first click doesn't trigger the onclick event, and the icon ends up transforming (as it should do) in a cross (see the codepen.io CSS).
Page after the first click

On the second click though, the event seems to start working and the sidenav finally shows up, with the cross reverting into the burger icon. If I keep clicking on the burger, it just works as it should, with the icon being out of phase.
Page after the second click;
Page after the third click

This makes no sense to me, and I initially wanted to get the cross when the sidenav is shown, not when it's hidden.
Does anyone know how to actually fix this?

Body:
You can change the implementation of the function toggleNav() for this:

In your .ts file add this.

toggle: boolean = false;

toggleNav() {
    this.toggle = !this.toggle;
    window.scrollTo(0, 0);
  }


问:
Using two case statements in SQL Server
I want to create a separate column from 1st case statement (let's say A) and 2nd separate column from 2nd case statement (say B). Then use these columns to perform division. But this query gives the result in 1 single column renamed as pym.

```<code>select
    WFMGrade,
    case
       when WFMGrade IN ('P/PA','PAT','A')
          then sum(TotalFTE)
       when WFMGrade IN ('SA','M','SM','AD','D','SD','AVP','VP','SVP','EVP')
          then sum(TotalFTE)
       else 0
    end as pym
from
    dw_UtilizationPredictionReport
group by
    (WFMGrade)
</code>```

How do I create separate columns for these two case statements?

答:
thanks advance
its work for me :</p>
```<code> UPDATE products
SET product_price = (
    CASE `product_home_id`
    WHEN 368794 THEN 3853070
    WHEN 368769 THEN 938000
    ELSE product_home_id END
),

    product_old_price = (
        CASE product_home_id
        WHEN 368794 THEN 4000000
        WHEN 368769 THEN 1100000
        ELSE product_old_price END
    )

WHERE `product_home_id` IN (368794,368769)
AND `product_vendor_id` =105
</code>```

Title: Using two case statements in SQL Server

Body:
I want to create a separate column from 1st case statement (let's say A) and 2nd separate column from 2nd case statement (say B). Then use these columns to perform division. But this query gives the result in 1 single column renamed as pym.

select
    WFMGrade,
    case
       when WFMGrade IN ('P/PA','PAT','A')
          then sum(TotalFTE)
       when WFMGrade IN ('SA','M','SM','AD','D','SD','AVP','VP','SVP','EVP')
          then sum(TotalFTE)
       else 0
    end as pym
from
    dw_UtilizationPredictionReport
group by
    (WFMGrade)

How do I create separate columns for these two case statements?

Body:
thanks advance
its work for me :

 UPDATE products
SET product_price = (
    CASE `product_home_id`
    WHEN 368794 THEN 3853070
    WHEN 368769 THEN 938000
    ELSE product_home_id END
),

    product_old_price = (
        CASE product_home_id
        WHEN 368794 THEN 4000000
        WHEN 368769 THEN 1100000
        ELSE product_old_price END
    )

WHERE `product_home_id` IN (368794,368769)
AND `product_vendor_id` =105


问:
Sort the odd numbers in the list
How can I sort ascending the odd numbers in a list of integers, but leaving the even numbers in their original places?

Example:

```<code>sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]
</code>```

My code:

```<code>def sort_array(source_array):
    odd_numbers = [n for n in source_array if n%2!=0]
    odd_numbers = sorted(odd_numbers)
</code>```

How do I switch the indices of the odd numbers in source_array with the ones in odd_numbers?

答:
```<code>def sort_array(source_array):
    sorted_array = [i for i in source_array if i % 2 != 0]
    sorted_array.sort()
    for index, item in enumerate(source_array):
        if item % 2 == 0:
            sorted_array.insert(index, item)
    return sorted_array
</code>```

Title: Sort the odd numbers in the list

Body:
How can I sort ascending the odd numbers in a list of integers, but leaving the even numbers in their original places?

Example:

sortArray([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4]

My code:

def sort_array(source_array):
    odd_numbers = [n for n in source_array if n%2!=0]
    odd_numbers = sorted(odd_numbers)

How do I switch the indices of the odd numbers in source_array with the ones in odd_numbers?