问:
Android Studio is giving errors and warnings after enabling view binding. How to fix?
I am getting errors after i enabled view binding in my project.

I have tried resyncing the project, invalidating cache.
My app gradle file:

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

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.learning.aboutme"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

    viewBinding.enabled = true

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}
</code>```

My project gradle file

```<code>// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
     ext.kotlin_version = '1.3.72'
     repositories {
          google()
          jcenter()

     }
     dependencies {
         classpath 'com.android.tools.build:gradle:3.6.3'
         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

          // NOTE: Do not place your application dependencies here; they belong
          // in the individual module build.gradle files
     }
}

allprojects {
     repositories {
          google()
          jcenter()

     }
}

task clean(type: Delete) {
     delete rootProject.buildDir
}
</code>```

My activity main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingStart="@dimen/padding"
    android:paddingEnd="@dimen/padding"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/name_text"
        style="@style/name_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textAlignment="center" />

    <EditText
        android:id="@+id/nickname_edit"
        style="@style/name_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/name_it_what_is_your_nickname"
        android:inputType="textPersonName"
        android:textAlignment="center" />

    <Button
        android:id="@+id/done_button"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/layout_margin"
        android:fontFamily="@font/roboto"
        android:text="@string/done" />

    <TextView
        android:id="@+id/nickname_text"
        style="@style/name_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/star_Image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/layout_margin"
        android:contentDescription="@string/yellow_star"
        app:srcCompat="@android:drawable/btn_star_big_on" />

    <ScrollView
        android:id="@+id/bio_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:lineSpacingMultiplier="@dimen/spacing_multiplier"
            android:text="@string/bio"
            android:textColor="@android:color/black" />
    </ScrollView>
</LinearLayout>
```

<p>Here the android studio gives a warning on <code>android:contentDescription</code>,<code>textAlignment</code>, <code>lineSpacingMultiplier</code>, <code>text</code> etc</p>

<p>Here is my main activity.kt file:</p>

<pre class="lang-kotlin prettyprint-override"><code>package com.learning.aboutme

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.learning.aboutme.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(R.layout.activity_main)
    }

    private fun addNickname(view: View) {

    }
}
</code>```

Here android studio says: Cannot access android.viewbinding.ViewBinding which is a supertype of com.learning.aboutme.databinding.ActivityMainBinding. On ActivityMainBinding.inflate()

I tried creating a new project and moving my files there but the same errors ( Tried moving activity_main.xml and the same errors.

How to fix this?

答:
Facing same issue exact error yesterday. Solution work for me is

Step 1- Remove .Idea Folder

Step 2- Close android studio

Step 3- Reopen android studio with same project path (This will genarate new
.Idea folder)

and Error is gone

Making sure

android.useAndroidX=true.  inside gradle.properties file

inside app build.gradle

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

Always Use folder structure with small case latter only class name is allowed to be Uppercase

If you are using any Copyright-Comment at top of xml or Layout tag without variable tag or we can say without any data then remove that and try to clean/rebuild project

Body:
I am getting errors after i enabled view binding in my project.

I have tried resyncing the project, invalidating cache.
My app gradle file:

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

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.3"

    defaultConfig {
        applicationId "com.learning.aboutme"
        minSdkVersion 19
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

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

    viewBinding.enabled = true

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
}

My project gradle file

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
     ext.kotlin_version = '1.3.72'
     repositories {
          google()
          jcenter()

     }
     dependencies {
         classpath 'com.android.tools.build:gradle:3.6.3'
         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

          // NOTE: Do not place your application dependencies here; they belong
          // in the individual module build.gradle files
     }
}

allprojects {
     repositories {
          google()
          jcenter()

     }
}

task clean(type: Delete) {
     delete rootProject.buildDir
}

My activity main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingStart="@dimen/padding"
    android:paddingEnd="@dimen/padding"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/name_text"
        style="@style/name_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/name"
        android:textAlignment="center" />

    <EditText
        android:id="@+id/nickname_edit"
        style="@style/name_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/name_it_what_is_your_nickname"
        android:inputType="textPersonName"
        android:textAlignment="center" />

    <Button
        android:id="@+id/done_button"
        style="@style/Widget.AppCompat.Button.Colored"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="@dimen/layout_margin"
        android:fontFamily="@font/roboto"
        android:text="@string/done" />

    <TextView
        android:id="@+id/nickname_text"
        style="@style/name_style"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textAlignment="center"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/star_Image"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="@dimen/layout_margin"
        android:contentDescription="@string/yellow_star"
        app:srcCompat="@android:drawable/btn_star_big_on" />

    <ScrollView
        android:id="@+id/bio_scroll"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:lineSpacingMultiplier="@dimen/spacing_multiplier"
            android:text="@string/bio"
            android:textColor="@android:color/black" />
    </ScrollView>
</LinearLayout>

Here the android studio gives a warning on android:contentDescription,textAlignment, lineSpacingMultiplier, text etc

Here is my main activity.kt file:

package com.learning.aboutme

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import com.learning.aboutme.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(R.layout.activity_main)
    }

    private fun addNickname(view: View) {

    }
}

Here android studio says: Cannot access android.viewbinding.ViewBinding which is a supertype of com.learning.aboutme.databinding.ActivityMainBinding. On ActivityMainBinding.inflate()

I tried creating a new project and moving my files there but the same errors ( Tried moving activity_main.xml and the same errors.

How to fix this?

Body:
Facing same issue exact error yesterday. Solution work for me is

Step 1- Remove .Idea Folder

Step 2- Close android studio

Step 3- Reopen android studio with same project path (This will genarate new
.Idea folder)

and Error is gone

Making sure

android.useAndroidX=true.  inside gradle.properties file

inside app build.gradle

 buildFeatures {
       viewBinding true
 }

Always Use folder structure with small case latter only class name is allowed to be Uppercase

If you are using any Copyright-Comment at top of xml or Layout tag without variable tag or we can say without any data then remove that and try to clean/rebuild project


来源: stackexchange

问:
How can I return users and roles in the same View?
I'm learning asp.net core MVC and I am trying to just make a simple user management model, but I cant seem to figure out how to make an algorithm that outputs the user and their role. I believe its due to the function outputting the user as a string, and the roles being output as a List. I cant seem to successfully call two model to make  the Model work. Or am I doing this incorrectly?

I can get it to successfully list the user and their info with this

```<code>        [Route("EditUser/{id?}")]
        public async Task<IActionResult> EditUser(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
                return View("NotFound");
            }

            return View(user);
}
</code>```

However since I have 3 or 4 different roles I cant just use List<>  right?

```<code>        var model = new List<ManageUserRolesViewModel>();

        foreach (var role in _roleManager.Roles)
        {
            var userRolesViewModel = new ManageUserRolesViewModel
            {
                RoleId = role.Id,
                RoleName = role.Name
            };
            if (await _userManager.IsInRoleAsync(user, role.Name))
            {
                userRolesViewModel.Selected = true;
            }
            else
            {
                userRolesViewModel.Selected = false;
            }
            model.Add(userRolesViewModel);
        }
</code>```

Which I cant output to view due to the string vs list issue.

```<code><div class="card-body">
            @for (int i = 0; i < Model.Count; i++)
            {
                <div class="form-check m-1">
                    <input type="hidden" asp-for="@Model[i].RoleId" />
                    <input type="hidden" asp-for="@Model[i].RoleName" />
                    <input asp-for="@Model[i].Selected" class="form-check-input" />
                    <label class="form-check-label" asp-for="@Model[i].Selected">
                        @Model[i].RoleName
                    </label>
                </div>
            }
            <div asp-validation-summary="All" class="text-danger"></div>
        </div>
</code>```

答:
There are multiple ways to that
1)You can store user data into Sessions and as per need, you can read at the view page.

```<code>Session["User"]=Users; // list of user or single logged user with role
</code>```

Make a common model or class with user data and view data.

The ViewModel

```<code>public class UserDetailsViewModel
{
    public string UserName { get; set; }
    public string UserRole { get; set; }
}
</code>```

The Action Method

```<code>[Route("EditUser/{id?}")]
 public async Task<IActionResult> EditUser(string id) {   //Your Logic

    var viewModel = new UserDetailsViewModel();
    viewModel.UserName = "UserName";
    viewModel.UserRole = "UserRole";
    return View(viewModel);
 }
</code>```

The View (Razor)

```<code>@model UserDetailsViewModel

// use Model.UserName and Model.UserRole
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm learning asp.net core MVC and I am trying to just make a simple user management model, but I cant seem to figure out how to make an algorithm that outputs the user and their role. I believe its due to the function outputting the user as a string, and the roles being output as a List. I cant seem to successfully call two model to make  the Model work. Or am I doing this incorrectly?

I can get it to successfully list the user and their info with this

        [Route("EditUser/{id?}")]
        public async Task<IActionResult> EditUser(string id)
        {
            var user = await _userManager.FindByIdAsync(id);
            if (user == null)
            {
                ViewBag.ErrorMessage = $"User with Id = {id} cannot be found";
                return View("NotFound");
            }

            return View(user);
}

However since I have 3 or 4 different roles I cant just use List<>  right?

        var model = new List<ManageUserRolesViewModel>();

        foreach (var role in _roleManager.Roles)
        {
            var userRolesViewModel = new ManageUserRolesViewModel
            {
                RoleId = role.Id,
                RoleName = role.Name
            };
            if (await _userManager.IsInRoleAsync(user, role.Name))
            {
                userRolesViewModel.Selected = true;
            }
            else
            {
                userRolesViewModel.Selected = false;
            }
            model.Add(userRolesViewModel);
        }

Which I cant output to view due to the string vs list issue.

            @for (int i = 0; i < Model.Count; i++)
            {

                    <input type="hidden" asp-for="@Model[i].RoleId" />
                    <input type="hidden" asp-for="@Model[i].RoleName" />
                    <input asp-for="@Model[i].Selected" class="form-check-input" />

                        @Model[i].RoleName

            }

Body:
There are multiple ways to that
1)You can store user data into Sessions and as per need, you can read at the view page.

Session["User"]=Users; // list of user or single logged user with role

Make a common model or class with user data and view data.

The ViewModel

public class UserDetailsViewModel
{
    public string UserName { get; set; }
    public string UserRole { get; set; }
}

The Action Method

[Route("EditUser/{id?}")]
 public async Task<IActionResult> EditUser(string id) {   //Your Logic

    var viewModel = new UserDetailsViewModel();
    viewModel.UserName = "UserName";
    viewModel.UserRole = "UserRole";
    return View(viewModel);
 }

The View (Razor)

@model UserDetailsViewModel

// use Model.UserName and Model.UserRole


问:
Rounding the corners of an SVG
I'm using a package that generates a rectangular Treemap with this structure:

svg (wrapper with width=100% and height=100%)

svg (the outer rectangle of the Treemap, also width=100% and height=100%)

g (one for each Treemap node)

rect

clipPath

text

I need to round the four corners of the entire Treemap (not the rx ry of each rect within).

Is it possible to do that by creating a clipPath either as a child of the wrapper or the inner svg that defines a rounded rectangle? If so, can it expose whatever the background color is behind the svg?

UPDATE: @web-tiki - here's what the code looks like...

<svg width="100%" height="100%" style="border-radius: 4px;">
  <svg width="100%" height="100%">

```

Looks great on Safari and Firefox but Chrome appears to ignore it. Wondering if it's a combination of Carbon Charts Treemap and Chrome?

答:
Found I could add this to the wrapper svg to get the effect I wanted:

<defs>
  <clipPath id="smallBox">
    <path d="M 0 4 A 4 4 0 0 1 4 0 L 446 0 A 4 4 0 0 1 450 4 L 450 346 A 4 4 0 0 1 446 350 L 4 350 A 4 4 0 0 1 0 346 Z"/>
  </clipPath>
</defs>
```
<p>then added <code>style="clip-path: url(#smallBox);"</code> to the inner svg.</p>
<p>The path was generated with this code (source: https://gist.github.com/danielpquinn/dd966af424030d47e476)</p>
<pre class="lang-js prettyprint-override"><code>const roundedRect = (w, h, r) =>
    'M 0 ' + r
    + ' A ' + r + ' ' + r + ' 0 0 1 ' + r + ' 0'
    + ' L ' + (w - r) + ' 0'
    + ' A ' + r + ' ' + r + ' 0 0 1 ' + w + ' ' + r
    + ' L ' + w + ' ' + (h - r)
    + ' A ' + r + ' ' + r + ' 0 0 1 ' + (w - r) + ' ' + h
    + ' L ' + r + ' ' + h
    + ' A ' + r + ' ' + r + ' 0 0 1 0 ' + (h - r)
    + ' Z'

console.log(roundedRect(450,350,4))
</code>```

Title: Rounding the corners of an SVG

Body:
I'm using a package that generates a rectangular Treemap with this structure:

svg (wrapper with width=100% and height=100%)

svg (the outer rectangle of the Treemap, also width=100% and height=100%)

g (one for each Treemap node)

rect

clipPath

text

I need to round the four corners of the entire Treemap (not the rx ry of each rect within).

Is it possible to do that by creating a clipPath either as a child of the wrapper or the inner svg that defines a rounded rectangle? If so, can it expose whatever the background color is behind the svg?

UPDATE: @web-tiki - here's what the code looks like...

<svg width="100%" height="100%" style="border-radius: 4px;">
  <svg width="100%" height="100%">

Looks great on Safari and Firefox but Chrome appears to ignore it. Wondering if it's a combination of Carbon Charts Treemap and Chrome?

Body:
Found I could add this to the wrapper svg to get the effect I wanted:

<defs>
  <clipPath id="smallBox">
    <path d="M 0 4 A 4 4 0 0 1 4 0 L 446 0 A 4 4 0 0 1 450 4 L 450 346 A 4 4 0 0 1 446 350 L 4 350 A 4 4 0 0 1 0 346 Z"/>
  </clipPath>
</defs>

then added style="clip-path: url(#smallBox);" to the inner svg.

The path was generated with this code (source: https://gist.github.com/danielpquinn/dd966af424030d47e476)

const roundedRect = (w, h, r) =>
    'M 0 ' + r
    + ' A ' + r + ' ' + r + ' 0 0 1 ' + r + ' 0'
    + ' L ' + (w - r) + ' 0'
    + ' A ' + r + ' ' + r + ' 0 0 1 ' + w + ' ' + r
    + ' L ' + w + ' ' + (h - r)
    + ' A ' + r + ' ' + r + ' 0 0 1 ' + (w - r) + ' ' + h
    + ' L ' + r + ' ' + h
    + ' A ' + r + ' ' + r + ' 0 0 1 0 ' + (h - r)
    + ' Z'

console.log(roundedRect(450,350,4))


问:
Typography component not accepting 'color' inside sx
I've been experiencing an issue in which I cannot apply 'color' inside the 'sx' property of a Typography component. Does anyone know what might be causing the issue?

Removing the 'color' key causes the color of the 2 line to be reverted to default (same as the 1st line).

```<code>import React from 'react';
import {Box, createTheme, CssBaseline, Typography} from '@mui/material';
import {ThemeProvider} from '@mui/styles';

const theme = createTheme({
  palette: {
    mode: 'dark',
  },
});

console.log(theme);

function App() {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box
        sx={{
          height: '100%',
          bgcolor: 'background.paper',
          color: 'text.primary',
        }}>
        1111111111111111
        <Typography sx={{color: 'text.secondary'}}>
          22222222222222222
        </Typography>
        <Box sx={{color: 'text.secondary'}}>333333333333</Box>
      </Box>
    </ThemeProvider>
  );
}

export default App;
</code>```

答:
Typography component doesn't directly support theming and color schemes you have to do it manually in your palette, or you can simply use Box component or rather don't give color inside sx property

or you can do something like that

```<code>  <Typography color='GrayText'>
          22222222222222222
  </Typography>
</code>```

for more deep information refer to this answer about why Typography doesn't change color on theme change

(Material-ui does not change Typography color according to theme)

Body:
I've been experiencing an issue in which I cannot apply 'color' inside the 'sx' property of a Typography component. Does anyone know what might be causing the issue?

Removing the 'color' key causes the color of the 2 line to be reverted to default (same as the 1st line).

import React from 'react';
import {Box, createTheme, CssBaseline, Typography} from '@mui/material';
import {ThemeProvider} from '@mui/styles';

const theme = createTheme({
  palette: {
    mode: 'dark',
  },
});

console.log(theme);

function App() {
  return (
    <ThemeProvider theme={theme}>
      <CssBaseline />
      <Box
        sx={{
          height: '100%',
          bgcolor: 'background.paper',
          color: 'text.primary',
        }}>
        1111111111111111
        <Typography sx={{color: 'text.secondary'}}>
          22222222222222222
        </Typography>
        <Box sx={{color: 'text.secondary'}}>333333333333</Box>
      </Box>
    </ThemeProvider>
  );
}

export default App;

Body:
Typography component doesn't directly support theming and color schemes you have to do it manually in your palette, or you can simply use Box component or rather don't give color inside sx property

or you can do something like that

  <Typography color='GrayText'>
          22222222222222222
  </Typography>

for more deep information refer to this answer about why Typography doesn't change color on theme change

(Material-ui does not change Typography color according to theme)


问:
Terraform ec2 userdata evaluation problem
I'm having trouble in putting userdata shell script to ec2 in startup process. I'm trying to run init.sh script when initializing my ec2 instance, with the terraform code below.

```<code>resource "aws_instance" "myinstance" {
  ...
  user_data = base64encode(templatefile(
    "${path.module}/templates/init.sh", {
      ...
      ADDITIONAL_IPS  = var.additional_ips
    }
    )
  )
</code>```

I have a init.sh as below,

```<code>ADDITIONAL_IPS="${ADDITIONAL_IPS}"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p $${IP} 255.255.255.255"
done
</code>```

However, when I create EC2 instance and check /var/log/cloud-init-output.log, I see the result below.

```<code>+ ADDITIONAL_IPS='1.1.1.1 2.2.2.2 3.3.3.3'
+ NLB_EIPS=()
+ for IP in $ADDITIONAL_IPS
+ NLB_EIPS+=' -p 1.1.1.1 2.2.2.2 3.3.3.3 255.255.255.255'
</code>```

The shell script below is the result I want to achieve,

```<code>#!/bin/bash

ADDITIONAL_IPS="1.1.1.1 2.2.2.2 3.3.3.3"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p $IP 255.255.255.255"
done

echo ${NLB_EIPS[@]}
</code>```

Result of the shell script above(And also intended result): -p 1.1.1.1 255.255.255.255 -p 2.2.2.2 255.255.255.255 -p 3.3.3.3 255.255.255.255

Just running the shell script loops successfully, but using Terraform seems to evaluate IP variable as the $ADDITIONAL_IPS itself.

Any help? Thanks.

答:
templatefile function does interpolate Terraform variables between ${ and } like ${VAR}. It will not touch $VAR (without curly braces). So you had that almost right, in your case this should work:

```<code>ADDITIONAL_IPS="${ADDITIONAL_IPS}"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p $IP 255.255.255.255"
done
</code>```

Body:
I'm having trouble in putting userdata shell script to ec2 in startup process. I'm trying to run init.sh script when initializing my ec2 instance, with the terraform code below.

resource "aws_instance" "myinstance" {
  ...
  user_data = base64encode(templatefile(
    "${path.module}/templates/init.sh", {
      ...
      ADDITIONAL_IPS  = var.additional_ips
    }
    )
  )

I have a init.sh as below,

ADDITIONAL_IPS="${ADDITIONAL_IPS}"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p $${IP} 255.255.255.255"
done

However, when I create EC2 instance and check /var/log/cloud-init-output.log, I see the result below.

+ ADDITIONAL_IPS='1.1.1.1 2.2.2.2 3.3.3.3'
+ NLB_EIPS=()
+ for IP in $ADDITIONAL_IPS
+ NLB_EIPS+=' -p 1.1.1.1 2.2.2.2 3.3.3.3 255.255.255.255'

The shell script below is the result I want to achieve,

#!/bin/bash

ADDITIONAL_IPS="1.1.1.1 2.2.2.2 3.3.3.3"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p $IP 255.255.255.255"
done

echo ${NLB_EIPS[@]}

Result of the shell script above(And also intended result): -p 1.1.1.1 255.255.255.255 -p 2.2.2.2 255.255.255.255 -p 3.3.3.3 255.255.255.255

Just running the shell script loops successfully, but using Terraform seems to evaluate IP variable as the $ADDITIONAL_IPS itself.

Any help? Thanks.

Body:
templatefile function does interpolate Terraform variables between ${ and } like ${VAR}. It will not touch $VAR (without curly braces). So you had that almost right, in your case this should work:

ADDITIONAL_IPS="${ADDITIONAL_IPS}"
NLB_EIPS=()
for IP in $ADDITIONAL_IPS; do
  NLB_EIPS+=" -p $IP 255.255.255.255"
done


问:
How to make change to a file inside a python-slim container?
I have a FROM python:3.8-slim-buster Dockerfile and I want to make a small change to the entrypoint.sh file. Unfortunately it seems there are no editors, neither vi or ed. Moreover, it is not possible to do apt-get update :(

What is the best way to have at least an editor?

答:
I had the same issue with alpine images.

I solved the problem using Multi-Stage Builds in the Dockerfile.

https://docs.docker.com/develop/develop-images/multistage-build/


问:
Reactjs dropdown menu and reusable components
I am following a tutorial to make a dropdown menu but I am stuck in the middle because instead of using the "props" keyword like The instructor did in the tutorial. I passed the props directly as arguments without props dot. When I wanted to implement {open && children} without props I got the Error that children are not defined

This is the tutorial I am following, And the minute when I get the Error https://youtu.be/IF6k0uZuypA?t=543

This is the NavItem.js component where I have the problem

```<code>import React, { useState, useEffect } from 'react';

function NavItem({ icon, title, ...props }) {
  const [opened, setOpened] = useState(false);

  return (
    <li className='nav-item'>

      <a
        href='#'
        target=''
        className='icon-button'
        onClick={() => setOpened(!open)}
      >

        {icon}
        <div>{title}</div>
      </a>
      {open && children}

    </li>
  );
}

export default NavItem;
</code>```

This is the Navbar.js Component where I call NavItem.js component

```<code>import React from 'react';
import NavItem from './NavItem';
import BellIcon from './icons/bell.svg';
import { ReactComponent as MessengerIcon } from './icons/messenger.svg';
import { ReactComponent as CaretIcon } from './icons/caret.svg';
import { ReactComponent as PlusIcon } from './icons/plus.svg';
import { ReactComponent as ChevronIcon } from './icons/chevron.svg';

function Navbar() {
  return (
    <>
      <nav className='h-20 bg-[#242526] py-0 px-4   border-b border-[#474a4d] '>
        <ul className='max-w-full h-full flex justify-end'>
          <NavItem icon={<PlusIcon />} />
          <NavItem icon={<BellIcon />} />
          <NavItem icon={<MessengerIcon />} />
          <NavItem icon={<CaretIcon />}>
            {/* Here where to render The dropdown menu Items */}
          </NavItem>
        </ul>
      </nav>
    </>
  );
}

export default Navbar;
</code>```

I am using Tailwindcss for styling
Thank you for your help

答:
You must either continue destruct props object:

({ icon, title, children, ...props })
```
<p>Or access via <code>props</code></p>
<pre class="lang-js prettyprint-override"><code>{opened && props.children}
</code>```

Body:
I am following a tutorial to make a dropdown menu but I am stuck in the middle because instead of using the "props" keyword like The instructor did in the tutorial. I passed the props directly as arguments without props dot. When I wanted to implement {open && children} without props I got the Error that children are not defined

This is the tutorial I am following, And the minute when I get the Error https://youtu.be/IF6k0uZuypA?t=543

This is the NavItem.js component where I have the problem

import React, { useState, useEffect } from 'react';

function NavItem({ icon, title, ...props }) {
  const [opened, setOpened] = useState(false);

  return (

       setOpened(!open)}
      >

        {icon}

{title}

      {open && children}

  );
}

export default NavItem;

This is the Navbar.js Component where I call NavItem.js component

import React from 'react';
import NavItem from './NavItem';
import BellIcon from './icons/bell.svg';
import { ReactComponent as MessengerIcon } from './icons/messenger.svg';
import { ReactComponent as CaretIcon } from './icons/caret.svg';
import { ReactComponent as PlusIcon } from './icons/plus.svg';
import { ReactComponent as ChevronIcon } from './icons/chevron.svg';

function Navbar() {
  return (
    <>

          <NavItem icon={<PlusIcon />} />
          <NavItem icon={<BellIcon />} />
          <NavItem icon={<MessengerIcon />} />
          <NavItem icon={<CaretIcon />}>
            {/* Here where to render The dropdown menu Items */}
          </NavItem>

    </>
  );
}

export default Navbar;

I am using Tailwindcss for styling
Thank you for your help

Body:
You must either continue destruct props object:

({ icon, title, children, ...props })

Or access via props

{opened && props.children}


问:
Maven Versions Plugin Not Ignoring 4 part version numbers e.g 19.2.1.3
Hi I'm using a maven version plugin rules file to exclude certain versions.

<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" comparisonMethod="maven" xsi:schemaLocation="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0 https://mojo.codehaus.org/versions-maven-plugin/xsd/rule-2.0.0.xsd">
    <ignoreVersions>
        <ignoreVersion type="regex">.*[aA]lpha.*</ignoreVersion>
        <ignoreVersion type="regex">.*\..*\.SP.*</ignoreVersion>
        <ignoreVersion type="regex">.*\..*\..*\..*</ignoreVersion>
    </ignoreVersions>
    <rules>
        <rule groupId="org.springframework.boot">
            <ignoreVersions>
                <ignoreVersion type="regex">2.6.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="io.micrometer">
            <ignoreVersions>
                <ignoreVersion type="regex">1.8.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="org.apache.tomcat.embed">
            <ignoreVersions>
                <ignoreVersion type="regex">10.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="au.com.dius.pact.provider">
            <ignoreVersions>
                <ignoreVersion type="regex">4.3.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="au.com.dius.pact.consumer">
            <ignoreVersions>
                <ignoreVersion type="regex">4.3.*</ignoreVersion>
            </ignoreVersions>
        </rule>
    </rules>
</ruleset>```

The 3rd  line is trying to exclude any version that has 4 parts. Sadly this regex is not working.

Have anyone cracked this issue.

Many thanks in advance

Richard

答:
Update: Running the mvn command locally, I was getting:

Failed to execute goal org.codehaus.mojo:versions-maven-plugin:2.8.1:use-latest-releases (default-cli) on project : Execution default-cli of goal org.codehaus.mojo:versions-maven-plugin:2.8.1:use-latest-releases failed: Invalid segment, 1, for the 1 segment version: '11.5.7.0'

The version number was set as a property value and not hard-coded in the <dependency> tag. Putting the version number within the <depenedency> tag, the reg ex worked. However, if your project has a transitive dependency version that has four parts, the regex will not work for these. Sadly, MVN dependency:tree does not reveal the source of the transitive dependencies.

Body:
Hi I'm using a maven version plugin rules file to exclude certain versions.

<?xml version="1.0" encoding="UTF-8"?>
<ruleset xmlns="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" comparisonMethod="maven" xsi:schemaLocation="http://mojo.codehaus.org/versions-maven-plugin/rule/2.0.0 https://mojo.codehaus.org/versions-maven-plugin/xsd/rule-2.0.0.xsd">
    <ignoreVersions>
        <ignoreVersion type="regex">.*[aA]lpha.*</ignoreVersion>
        <ignoreVersion type="regex">.*\..*\.SP.*</ignoreVersion>
        <ignoreVersion type="regex">.*\..*\..*\..*</ignoreVersion>
    </ignoreVersions>
    <rules>
        <rule groupId="org.springframework.boot">
            <ignoreVersions>
                <ignoreVersion type="regex">2.6.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="io.micrometer">
            <ignoreVersions>
                <ignoreVersion type="regex">1.8.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="org.apache.tomcat.embed">
            <ignoreVersions>
                <ignoreVersion type="regex">10.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="au.com.dius.pact.provider">
            <ignoreVersions>
                <ignoreVersion type="regex">4.3.*</ignoreVersion>
            </ignoreVersions>
        </rule>
        <rule groupId="au.com.dius.pact.consumer">
            <ignoreVersions>
                <ignoreVersion type="regex">4.3.*</ignoreVersion>
            </ignoreVersions>
        </rule>
    </rules>
</ruleset>

The 3rd  line is trying to exclude any version that has 4 parts. Sadly this regex is not working.

Have anyone cracked this issue.

Many thanks in advance

Richard


问:
Adding get-Method to POJO causes JsonMappingException
i have a POJO class, which is used for deserialization using Jackson. This class contains the default constructor and getter and setter methods for all class variables.

Because I need some advanced logic on the content of the POJO i added a method

```<code>public String getRootModuleName()
</code>```

But now my unit tests fail during deserialization with the following exception:

```<code>com.fasterxml.jackson.databind.JsonMappingException: No value present (through reference chain: com.POJO["rootModuleName"])
</code>```

To me it looks like Jackson recognizes a get-Method and thus derives, that there must be a similar JSON property for deserialization.

When i annotate the method with @JsonIgnore the tests succeed.

Can someone confirm that Jackson identifies required properties by get-prefix on method names?

Is @JsonIgnore a good solution or should i decouple the business logic from POJO design?

答: You are completely right, JSON Jackson recognizes property getters by "get" prefix. So, in your case the possible solutions are to use @JsonIgnore just like you did, or rename your method to have different prefix such as "retrieve", "extract" and so forth. I'd say using @JsonIgnore is the best way to go. So, in short your solution is correct

Body:
i have a POJO class, which is used for deserialization using Jackson. This class contains the default constructor and getter and setter methods for all class variables.

Because I need some advanced logic on the content of the POJO i added a method

public String getRootModuleName()

But now my unit tests fail during deserialization with the following exception:

com.fasterxml.jackson.databind.JsonMappingException: No value present (through reference chain: com.POJO["rootModuleName"])

To me it looks like Jackson recognizes a get-Method and thus derives, that there must be a similar JSON property for deserialization.

When i annotate the method with @JsonIgnore the tests succeed.

Can someone confirm that Jackson identifies required properties by get-prefix on method names?

Is @JsonIgnore a good solution or should i decouple the business logic from POJO design?


问:
How do I call a SQL Server stored procedure from PowerShell?
I have a large CSV file and I want to execute a stored procedure for each line.

What is the best way to execute a stored procedure from PowerShell?

答:
Adds CommandType and Parameters to @Santiago Cepas' answer:

```<code>function Execute-Stored-Procedure
{
    param($server, $db, $spname)
    $sqlConnection = new-object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db
    $sqlConnection.Open()
    $sqlCommand = new-object System.Data.SqlClient.SqlCommand
    $sqlCommand.CommandTimeout = 120
    $sqlCommand.Connection = $sqlConnection
    $sqlCommand.CommandType= [System.Data.CommandType]::StoredProcedure
    # If you have paramters, add them like this:
    # $sqlCommand.Parameters.AddWithValue("@paramName", "$param") | Out-Null
    $sqlCommand.CommandText= $spname
    $text = $spname.Substring(0, 50)
    Write-Progress -Activity "Executing Stored Procedure" -Status "Executing SQL => $text..."
    Write-Host "Executing Stored Procedure => $text..."
    $result = $sqlCommand.ExecuteNonQuery()
    $sqlConnection.Close()
}

# Call like this:
Execute-Stored-Procedure -server "enter-server-name-here" -db "enter-db-name-here" -spname "enter-sp-name-here"
</code>```

OwnerDisplayName: Andy J

ContentLicense: CC BY-SA 3.0

Body:
Adds CommandType and Parameters to @Santiago Cepas' answer:

function Execute-Stored-Procedure
{
    param($server, $db, $spname)
    $sqlConnection = new-object System.Data.SqlClient.SqlConnection
    $sqlConnection.ConnectionString = 'server=' + $server + ';integrated security=TRUE;database=' + $db
    $sqlConnection.Open()
    $sqlCommand = new-object System.Data.SqlClient.SqlCommand
    $sqlCommand.CommandTimeout = 120
    $sqlCommand.Connection = $sqlConnection
    $sqlCommand.CommandType= [System.Data.CommandType]::StoredProcedure
    # If you have paramters, add them like this:
    # $sqlCommand.Parameters.AddWithValue("@paramName", "$param") | Out-Null
    $sqlCommand.CommandText= $spname
    $text = $spname.Substring(0, 50)
    Write-Progress -Activity "Executing Stored Procedure" -Status "Executing SQL => $text..."
    Write-Host "Executing Stored Procedure => $text..."
    $result = $sqlCommand.ExecuteNonQuery()
    $sqlConnection.Close()
}

# Call like this:
Execute-Stored-Procedure -server "enter-server-name-here" -db "enter-db-name-here" -spname "enter-sp-name-here"


问:
Perl backticks using bash
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

```<code>`bash -c \"echo a b\"`
</code>```

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

```<code>echo "a'b"
</code>```

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

```<code>system("bash", "-c", qq(echo "a'b"));
</code>```

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

答:
I have the following sub that works

```<code>    sub bash_output {
       my ($cmd) = @_;

       open my $ifh, "-|", "bash", "-c", $cmd or die "cannot open file handler: $!";

       my $output = "";
       while (<$ifh>) {
          $output .= $_;
       }

       close $ifh;

       return $output;
    }

    print "test bash_output()\n";

    my @strings = (
         qq(echo "a'b"),
         'echo $BASH_VERSION',
         '[[ "abcde" =~ bcd ]] && echo matched',
         'i=1; ((i++)); echo $i',
   );

   for my $s (@strings) {
         print "bash_output($s) = ", bash_output($s), "\n";
   }
</code>```

The output is

```<code>bash_output(echo "a'b") = a'b

bash_output(echo $BASH_VERSION) = 4.4.20(1)-release

bash_output([[ "abcde" =~ bcd ]] && echo matched) = matched

bash_output(i=1; ((i++)); echo $i) = 2
</code>```

My answer is long-winded but it fills my need. I was hoping Perl has a built-in solution just like how it handles system() call and I am still hoping.

Title: Perl backticks using bash

Body:
In Perl, the default shell to execute backticks is sh. I'd like to switch to use bash for its richer syntax. So far I found that the suggested solution is

`bash -c \"echo a b\"`

The apparent drawback is that the escaped double quotes, which means I will have difficulty to use double quotes in my bash args. For example, if I wanted to run commands requiring double quotes in bash

echo "a'b"

The above method will be very awkward.

Perl's system() call has a solution for this problem: to use ARRAY args,

system("bash", "-c", qq(echo "a'b"));

This keeps my original bash command unmodified, and almost always.

I'd like to use ARRAY args in backticks too. Is it possible?

Body:
I have the following sub that works

    sub bash_output {
       my ($cmd) = @_;

       open my $ifh, "-|", "bash", "-c", $cmd or die "cannot open file handler: $!";

       my $output = "";
       while (<$ifh>) {
          $output .= $_;
       }

       close $ifh;

       return $output;
    }

    print "test bash_output()\n";

    my @strings = (
         qq(echo "a'b"),
         'echo $BASH_VERSION',
         '[[ "abcde" =~ bcd ]] && echo matched',
         'i=1; ((i++)); echo $i',
   );

   for my $s (@strings) {
         print "bash_output($s) = ", bash_output($s), "\n";
   }

The output is

bash_output(echo "a'b") = a'b

bash_output(echo $BASH_VERSION) = 4.4.20(1)-release

bash_output([[ "abcde" =~ bcd ]] && echo matched) = matched

bash_output(i=1; ((i++)); echo $i) = 2

My answer is long-winded but it fills my need. I was hoping Perl has a built-in solution just like how it handles system() call and I am still hoping.


问:
Deserializing JSON with numeric string keys in C#
```<code>{
  Items: [
    {
      "title": "Object1",
      "preview": {
        "2048": "preview_9212.jpg",
        "1024": "preview_6693.jpg",
      }
    },
    {
      "title": "Object2",
      "preview": {
        "2048": "preview_9888.jpg",
        "1024": "preview_6890.jpg",
      }
    },
    {
      "title": "Object3",
      "preview": {
        "2048": "preview_9822.jpg",
        "1024": "preview_6848.jpg",
      }
    }
  ]
}
</code>```

I usually deserialise like this:

```<code>[Serializable]
public class JsonParser
{
    public string title;
    public List<Preview> preview;
}

[Serializable]
class Preview
{
    public string 2048;
}
</code>```

But since 2048 is an Integer is not possible to use this way.
I tried to deserialize the JSON to get preview like these:

```<code>public class Preview
{
  [JsonProperty("2048")]
  public string imageNumber { get; set; }
}

var user = JsonConvert.DeserializeObject<Preview>(jsonValue);
</code>```

or

```<code>var json = JObject.Parse(jsonValue);
var preview = json["preview"].ToObject<Dictionary<string, string>>();
foreach (var entry in preview)
{
    Debug.Log(entry.Key);
    Debug.Log(entry.Value);
}
</code>```

I got: NullReferenceException: Object reference not set to an instance of an object.

I also tried Deserializing JSON that has an int as a key in C# but again NullReferenceException;

Thanks for any help!

答:
Since you have numeric string properties, you have 2 main choices:

Use something like [JsonProperty("2048")] and select valid name for the property

Or use a dictionary. This looks much more flexible for me, so you can try this code

```<code>Data data= JsonConvert.DeserializeObject<Data>(json);

string preview2048 = data.Items[0].Preview["2048"];  //preview_9212.jpg

</code>```

or more complicated search using Linq

```<code>string  obj3Preview2048 = data.Items.Where(i=> i.Title == "Object3")
.Select(i =>i.Preview["2048"]).FirstOrDefault(); //preview_9822.jpg
</code>```

classes

```<code>public partial class Data
{
    [JsonProperty("Items")]
    public List<Item> Items { get; set; }
}

public partial class Item
{
    [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
    public string Title { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }

    [JsonProperty("preview")]
    public Dictionary<string, string> Preview { get; set; }
}
</code>```

and you have some typos in json you posted, and I fix "type" to "title" in one of json objects.   This is a fixed version

```<code>{
    "Items": [{
            "title": "Object1",
            "token": "6561b1bbe5f1958848jhgd43d2",
            "preview": {
                "2048": "preview_9212.jpg",
                "1024": "preview_6693.jpg"
            }
        },
        {
            "title": "Object2",
            "token": "4a42eb54648DSFhUI664654d25",
            "preview": {
                "2048": "preview_9888.jpg",
                "1024": "preview_6890.jpg"
            }
        },
        {
            "type": "Object3",
            "token": "3fba64831dghkjgfkl5dfaegoj9",
            "preview": {
                "2048": "preview_9822.jpg",
                "1024": "preview_6848.jpg"
            }
        }
    ]
}
</code>```

Body:
{
  Items: [
    {
      "title": "Object1",
      "preview": {
        "2048": "preview_9212.jpg",
        "1024": "preview_6693.jpg",
      }
    },
    {
      "title": "Object2",
      "preview": {
        "2048": "preview_9888.jpg",
        "1024": "preview_6890.jpg",
      }
    },
    {
      "title": "Object3",
      "preview": {
        "2048": "preview_9822.jpg",
        "1024": "preview_6848.jpg",
      }
    }
  ]
}

I usually deserialise like this:

[Serializable]
public class JsonParser
{
    public string title;
    public List<Preview> preview;
}

[Serializable]
class Preview
{
    public string 2048;
}

But since 2048 is an Integer is not possible to use this way.
I tried to deserialize the JSON to get preview like these:

public class Preview
{
  [JsonProperty("2048")]
  public string imageNumber { get; set; }
}

var user = JsonConvert.DeserializeObject<Preview>(jsonValue);

or

var json = JObject.Parse(jsonValue);
var preview = json["preview"].ToObject<Dictionary<string, string>>();
foreach (var entry in preview)
{
    Debug.Log(entry.Key);
    Debug.Log(entry.Value);
}

I got: NullReferenceException: Object reference not set to an instance of an object.

I also tried Deserializing JSON that has an int as a key in C# but again NullReferenceException;

Thanks for any help!

Body:
Since you have numeric string properties, you have 2 main choices:

Use something like [JsonProperty("2048")] and select valid name for the property

Or use a dictionary. This looks much more flexible for me, so you can try this code

Data data= JsonConvert.DeserializeObject<Data>(json);

string preview2048 = data.Items[0].Preview["2048"];  //preview_9212.jpg

or more complicated search using Linq

string  obj3Preview2048 = data.Items.Where(i=> i.Title == "Object3")
.Select(i =>i.Preview["2048"]).FirstOrDefault(); //preview_9822.jpg

classes

public partial class Data
{
    [JsonProperty("Items")]
    public List<Item> Items { get; set; }
}

public partial class Item
{
    [JsonProperty("title", NullValueHandling = NullValueHandling.Ignore)]
    public string Title { get; set; }

    [JsonProperty("token")]
    public string Token { get; set; }

    [JsonProperty("preview")]
    public Dictionary<string, string> Preview { get; set; }
}

and you have some typos in json you posted, and I fix "type" to "title" in one of json objects.   This is a fixed version

{
    "Items": [{
            "title": "Object1",
            "token": "6561b1bbe5f1958848jhgd43d2",
            "preview": {
                "2048": "preview_9212.jpg",
                "1024": "preview_6693.jpg"
            }
        },
        {
            "title": "Object2",
            "token": "4a42eb54648DSFhUI664654d25",
            "preview": {
                "2048": "preview_9888.jpg",
                "1024": "preview_6890.jpg"
            }
        },
        {
            "type": "Object3",
            "token": "3fba64831dghkjgfkl5dfaegoj9",
            "preview": {
                "2048": "preview_9822.jpg",
                "1024": "preview_6848.jpg"
            }
        }
    ]
}


问:
SQLite matching on partial integer
I have the following code:

```<code>sic_code = int(input("Filter by SIC code (1-4 digits)? Default is all: ")

# Connect to the database file
conn = sqlite3.connect(db)
c = conn.cursor()

sql = ("SELECT Name "
       "FROM stock_data "
       "WHERE SIC_Code = {sc}".format(sc=sic_code))

# Run SQL query
c.execute(sql)
</code>```

And here is how the SIC codes look in the database.

Ideally I'd like to match 7372 regardless of whether the user enters 7, 73, 737 or 7372. I've tried starting with a simple query matching on a 4 digit code but I can not get this to work. The query returns no rows. Without the SIC query, everything works.

Both the SIC column and the user input variable is specified as integer.

Thanks in advance for any assistance.

答:
Use regexp_match() from SQLAlchemy 1.4:

It works on Integer type columns as well.

Title: SQLite matching on partial integer

Body:
I have the following code:

sic_code = int(input("Filter by SIC code (1-4 digits)? Default is all: ")

# Connect to the database file
conn = sqlite3.connect(db)
c = conn.cursor()

sql = ("SELECT Name "
       "FROM stock_data "
       "WHERE SIC_Code = {sc}".format(sc=sic_code))

# Run SQL query
c.execute(sql)

And here is how the SIC codes look in the database.

Ideally I'd like to match 7372 regardless of whether the user enters 7, 73, 737 or 7372. I've tried starting with a simple query matching on a 4 digit code but I can not get this to work. The query returns no rows. Without the SIC query, everything works.

Both the SIC column and the user input variable is specified as integer.

Thanks in advance for any assistance.


问:
Define incomplete Record, while retaining the constraints on mapped type
Say I have an interface S:

interface S {
  a: string;
  b: number;
  c: string;
}
```
<p>I want to create an incomplete mapping from <code>S</code> to some other <code>AllowedMappedType</code> type:</p>
<pre class="lang-js prettyprint-override"><code>type AllowedMappedType = "red" | "green" | "blue";
const map: Record<keyof S, AllowedMappedType> = {
  a: "red",
  c: "green",
};
</code>```

This doesn't work, because we don't define a mapping for all keys of S. You could avoid this by getting rid of type specialization:

const map = {
  a: "red",
  c: "green",
}; // map has a type of { a: string, c: string }, i.e. we lose the constraint on AllowedMappedType
```

But I want to retain the AllowedMappedType constraint. Partial doesn't work for me either because I want the type to not have optional properties.

How to achieve this?

答:
How about Pick?

interface S {
    a: string;
    b: number;
    c: string;
  }
type AllowedMappedType = "red" | "green" | "blue";
const map: Pick<Record<keyof S, AllowedMappedType>, 'a' | 'c'> = {
  a: "red",
  c: "green",
};
```
<p>Or Omit:</p>
<pre class="lang-js prettyprint-override"><code>const map: Omit<Record<keyof S, AllowedMappedType>, 'b'> = {
    a: "red",
    c: "green",
};
</code>```

Body:
Say I have an interface S:

interface S {
  a: string;
  b: number;
  c: string;
}

I want to create an incomplete mapping from S to some other AllowedMappedType type:

type AllowedMappedType = "red" | "green" | "blue";
const map: Record<keyof S, AllowedMappedType> = {
  a: "red",
  c: "green",
};

This doesn't work, because we don't define a mapping for all keys of S. You could avoid this by getting rid of type specialization:

const map = {
  a: "red",
  c: "green",
}; // map has a type of { a: string, c: string }, i.e. we lose the constraint on AllowedMappedType

But I want to retain the AllowedMappedType constraint. Partial doesn't work for me either because I want the type to not have optional properties.

How to achieve this?

Body:
How about Pick?

interface S {
    a: string;
    b: number;
    c: string;
  }
type AllowedMappedType = "red" | "green" | "blue";
const map: Pick<Record<keyof S, AllowedMappedType>, 'a' | 'c'> = {
  a: "red",
  c: "green",
};

Or Omit:

const map: Omit<Record<keyof S, AllowedMappedType>, 'b'> = {
    a: "red",
    c: "green",
};


问:
How to apply divider or view in Constraint layout
I want to apply a divider at some places in Constraint layout but when I do it by simple view, the whole layout get shifted to the top and everything gets merged. I want to use only constraints layout for the whole design.

```<code><TextView
    android:id="@+id/textView16"
    android:layout_width="0dp"
    android:layout_height="18dp"
    android:text="TextView"
    app:layout_constraintLeft_toRightOf="@+id/imageView11"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    android:layout_marginTop="13dp"
    app:layout_constraintTop_toBottomOf="@+id/textView14"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView20"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/textView16"
    app:layout_constraintLeft_toRightOf="@+id/imageView11"
    android:layout_marginLeft="8dp"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.0"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<View
    android:layout_width="0dp"
    android:layout_height="2dp"
    android:background="@android:color/background_dark"
    tools:layout_editor_absoluteY="98dp"
    android:id="@+id/view"
    tools:layout_editor_absoluteX="0dp" />

<TextView
    android:id="@+id/textView21"
    android:layout_width="wrap_content"
    android:layout_height="17dp"
    android:layout_marginBottom="8dp"
    android:layout_marginRight="8dp"
    android:text="Nivedita Parmar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.025"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/view"
    app:layout_constraintVertical_bias="0.035"
    android:layout_marginEnd="8dp" />
</code>```

Please give some idea regarding this.
Thanks in advance..

答:
Check out Guideline. I've found it to be useful when working with Constraint Views.

<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <androidx.constraintlayout.widget.Guideline
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/guideline"
            app:layout_constraintGuide_begin="100dp"
            android:orientation="vertical"/>

    <Button
            android:text="Button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/button"
            app:layout_constraintLeft_toLeftOf="@+id/guideline"
            android:layout_marginTop="16dp"
            app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>
```

Body:
I want to apply a divider at some places in Constraint layout but when I do it by simple view, the whole layout get shifted to the top and everything gets merged. I want to use only constraints layout for the whole design.

<TextView
    android:id="@+id/textView16"
    android:layout_width="0dp"
    android:layout_height="18dp"
    android:text="TextView"
    app:layout_constraintLeft_toRightOf="@+id/imageView11"
    android:layout_marginLeft="8dp"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintHorizontal_bias="1.0"
    android:layout_marginTop="13dp"
    app:layout_constraintTop_toBottomOf="@+id/textView14"
    app:layout_constraintBottom_toBottomOf="parent"
    android:layout_marginBottom="8dp"
    app:layout_constraintVertical_bias="0.0"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<TextView
    android:id="@+id/textView20"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:text="TextView"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/textView16"
    app:layout_constraintLeft_toRightOf="@+id/imageView11"
    android:layout_marginLeft="8dp"
    app:layout_constraintHorizontal_bias="0.0"
    app:layout_constraintVertical_bias="0.0"
    android:layout_marginRight="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp" />

<View
    android:layout_width="0dp"
    android:layout_height="2dp"
    android:background="@android:color/background_dark"
    tools:layout_editor_absoluteY="98dp"
    android:id="@+id/view"
    tools:layout_editor_absoluteX="0dp" />

<TextView
    android:id="@+id/textView21"
    android:layout_width="wrap_content"
    android:layout_height="17dp"
    android:layout_marginBottom="8dp"
    android:layout_marginRight="8dp"
    android:text="Nivedita Parmar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintHorizontal_bias="0.025"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/view"
    app:layout_constraintVertical_bias="0.035"
    android:layout_marginEnd="8dp" />

Please give some idea regarding this.
Thanks in advance..


问:
foreach response ajax create multi row table
I am trying to handle an ajax response where I have different results.

What I am doing is make an ajax call to my controller where I send an id;
I make filters via model laravel and it returns all matching results via json.

This is my blade:

```<code><div class="container-xxl show-order" hidden>
    <div class="row justify-content-center">
        <div class="col text-center">
            <table class="table table-bordered mt-5">
                <thead>
                  <tr>
                    <th scope="col">ID</th>
                    <th scope="col">quantita bottiglie</th>
                    <th scope="col">prezzo</th>
                    <th scope="col">Data ordine</th>
                    <th scope="col">Pagato</th>
                  </tr>
                </thead>
                <tbody>
                  <tr>
                    <th scope="row"><input class="idorder text-center" readonly value="" type="text" style="border:none;font-weight:900;"></th>
                    <td><input class="qty input-transition text-center" readonly value="" type="text" style="border:none;font-weight:900;"></td>
                    <td><input class="prezzo text-center" readonly value="" type="text" style="border:none;font-weight:900;"></td>
                    <td><input class="data_ordine text-center" value="" readonly type="text" style="border:none;font-weight:900;"></td>
                    <td><input class="pagato text-center" value="" readonly type="text" style="border:none;font-weight:900;"></td>
                  </tr>
                </tbody>
              </table>
        </div>
    </div>
</div>
</code>```

this is my ajax:

```<code>$('.vieworder').change(function (e) {
    e.preventDefault();
    if ($(this).is(':checked')) {
    let restaurant_id=$('.restaurant').val();

        $('.show-order').attr('hidden',false);

        $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
    $.ajax({
        method: "POST",
        url: "/filterorder",
        data: {
                'restaurant_id':restaurant_id,
              },
        success: function (response) {
            let res = JSON.stringify(response);
                let respons = JSON.parse(res);

                $.each(respons,function(key,value){

                        console.log(value[1]);
                        let idorder=$('.idorder').val(value['id']);
                        let qty=$('.qty').val(value['quantita']);
                        let prezzo=$('.prezzo').val(value['prezzo']);
                        let data_ordine=$('.data_ordine').val(value['data_ordine']);
                        if (value['pagato']==0) {
                        let pagato=$('.pagato').val('NO');
                        } else {
                            let pagato=$('.pagato').val('SI');
                        }

                });
        }
    });
    }else{
        $('.show-order').attr('hidden',true);

    }

});
</code>```

and this is my controller:

```<code>public function order(){
    $orderselected=Order::where('id_restaurant',$_POST['restaurant_id'])->get();
    return response()->json(['id'=>$orderselected]);
}
</code>```

what I want is to create a new row for each result at the moment only the last result is transcribed.

I know I need to use a foreach, but I'm not sure how to write it.

答:
As I can see your route method is post so change your controller like this</p>
```<code>public function order(Request $request){

        $orderselected=Order::where('id_restaurant',$request->restaurant_id)->get();
        return response()->json(['id'=>$orderselected]);
    }

</code>```

Body:
I am trying to handle an ajax response where I have different results.

What I am doing is make an ajax call to my controller where I send an id;
I make filters via model laravel and it returns all matching results via json.

This is my blade:

                    ID
                    quantita bottiglie
                    prezzo
                    Data ordine
                    Pagato

                    <input class="idorder text-center" readonly value="" type="text" style="border:none;font-weight:900;">
                    <input class="qty input-transition text-center" readonly value="" type="text" style="border:none;font-weight:900;">
                    <input class="prezzo text-center" readonly value="" type="text" style="border:none;font-weight:900;">
                    <input class="data_ordine text-center" value="" readonly type="text" style="border:none;font-weight:900;">
                    <input class="pagato text-center" value="" readonly type="text" style="border:none;font-weight:900;">

this is my ajax:

$('.vieworder').change(function (e) {
    e.preventDefault();
    if ($(this).is(':checked')) {
    let restaurant_id=$('.restaurant').val();

        $('.show-order').attr('hidden',false);

        $.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
                }
            });
    $.ajax({
        method: "POST",
        url: "/filterorder",
        data: {
                'restaurant_id':restaurant_id,
              },
        success: function (response) {
            let res = JSON.stringify(response);
                let respons = JSON.parse(res);

                $.each(respons,function(key,value){

                        console.log(value[1]);
                        let idorder=$('.idorder').val(value['id']);
                        let qty=$('.qty').val(value['quantita']);
                        let prezzo=$('.prezzo').val(value['prezzo']);
                        let data_ordine=$('.data_ordine').val(value['data_ordine']);
                        if (value['pagato']==0) {
                        let pagato=$('.pagato').val('NO');
                        } else {
                            let pagato=$('.pagato').val('SI');
                        }

                });
        }
    });
    }else{
        $('.show-order').attr('hidden',true);

    }

});

and this is my controller:

public function order(){
    $orderselected=Order::where('id_restaurant',$_POST['restaurant_id'])->get();
    return response()->json(['id'=>$orderselected]);
}

what I want is to create a new row for each result at the moment only the last result is transcribed.

I know I need to use a foreach, but I'm not sure how to write it.

Body:
As I can see your route method is post so change your controller like this

public function order(Request $request){

        $orderselected=Order::where('id_restaurant',$request->restaurant_id)->get();
        return response()->json(['id'=>$orderselected]);
    }


问:
Trace back output in VS Code
Programming in Python in Visual Studio Code, I was wondering if there exists a way, given an output, to trace back to the respective input. If, for example, a print is generated by a line in my code, does there exist a command, or a tool of VS Code, such that I can find exactly the line where this output was produced? Maybe it's a trivial question, but it would be useful for me if someone has a suggestion.</p>

答:
If I got your question correctly, you can use a function breakpoint() .</p>
```<code>def foo():
    a = input()
    breakpoint() #Put it and debug interface will be opened in terminal
    generated_result = a + 'abc'
    return generated_result
</code>```

Title: Trace back output in VS Code

Body:
If I got your question correctly, you can use a function breakpoint() .

def foo():
    a = input()
    breakpoint() #Put it and debug interface will be opened in terminal
    generated_result = a + 'abc'
    return generated_result


问:
PHP curl not getting the intended page content, Firefox does. Possible causes?
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

```<code>// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);
</code>```

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

```<code># Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK
</code>```

答:
This page uses a lot of cookies, I would not be surprised a session cookie is required to load the page. See what happens when enabling that</p>

```<code>curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');
</code>```

Body:
When I use the curl to fetch a page on an ecommerce site, it always gives me the same front page (ignoring the starting item parameter); whereas when I go to the url in a browser it works as usual.

Simplified code:

// s is the starting item count, no idea what yp4p_page is for exactly yet.
$url = 'http://list.taobao.com/market/baobao.htm?cat=40&yp4p_page=4&s=176';

$ch = curl_init($url);

$header[0] = 'Accept: text/xml,application/xml,application/xhtml+xml,'
                . 'text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5';
$header[] = 'Cache-Control: max-age=0';
$header[] = 'Connection: keep-alive';
$header[] = 'Keep-Alive: 300';
$header[] = 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7';
$header[] = 'Accept-Language: en-us,en;q=0.5';

//$cookieFile = tempnam('/tmp', 'curlcookie');
$cookieFile = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'curlcookies.txt';

$options = array(
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_HEADER => false,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_ENCODING => 'gzip,deflate',
            CURLOPT_USERAGENT => 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0) Gecko/20100101 Firefox/6.0 FirePHP/0.6',
            CURLOPT_AUTOREFERER => true,
            CURLOPT_CONNECTTIMEOUT => 120,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_VERBOSE => 1,
            CURLOPT_HTTPHEADER => $header,
            CURLOPT_COOKIEFILE => $cookieFile,
            CURLOPT_COOKIEJAR => $cookieFile,
);

curl_setopt_array($ch, $options);

$strPageHTML = curl_exec($ch);

curl_close($ch);

I'm sorry for the Chinese site, but if you look at the items listed and their url as returned by curl, their id's are always the same as the ones on the front page (where s = 0) when they should be different.

What am I doing wrong?

Edit 1: added cookie to code, still doesn't work.

Edit 2: edited the cookie line to clear any confusion. Also the contents of the cookies are as follows:

# Netscape HTTP Cookie File
# http://curl.haxx.se/rfc/cookie_spec.html
# This file was generated by libcurl! Edit at your own risk.

#HttpOnly_.taobao.com   TRUE    /   FALSE   0   cookie2 d686d4be95b4b56b61292118b43e1333
#HttpOnly_.taobao.com   TRUE    /   FALSE   1316321978  _tb_token_  eeab7e3e5ea9e
.taobao.com TRUE    /   FALSE   1321505978  t   3c473872e51e93b0cf172375b31f503a
.taobao.com TRUE    /   FALSE   0   uc1 cookie14=UoLdHCGrCsSKAg%3D%3D
.taobao.com TRUE    /   FALSE   0   v   0
.taobao.com TRUE    /   FALSE   0   _lang   zh_CN:GBK

Body:
This page uses a lot of cookies, I would not be surprised a session cookie is required to load the page. See what happens when enabling that

curl_setopt($DATA_POST, CURLOPT_COOKIEFILE, 'cookiefile.txt');
curl_setopt($DATA_POST, CURLOPT_COOKIEJAR, 'cookiefile.txt');


问:
How to group columns and sum them, in a large CSV?
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1
```
<ul>
<li><code>{ID: 1, Location: Loc1, Date: 2022-01-27}</code> is one such group, and its sub values <code>5</code> and <code>4</code> should be summed to <code>9</code></li>
<li><code>{ID: 3, Location: Loc1, Date: 2022-01-28}</code> is another group and its sum should be <code>18</code></li>
</ul>
<p>Here's what that sample input should look like, processed/summed, and written to a new CSV:</p>
<pre class="lang-none prettyprint-override"><code>ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1
</code>```

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

答:
You could use the built in csv library and build up the output line by line. A Counter can be used to combine and count rows with the same entries:

```<code>from collections import Counter
import csv

data = Counter()

with open('input.csv') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)

    for row in csv_input:
        data[tuple(row[:3])] += int(row[3])

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(header)

    for key, value in data.items():
        csv_output.writerow([*key, value])
</code>```

Giving the output:

ID,Location,Date,Value
1,Loc1,2022-01-27,9
1,Loc1,2022-01-28,7
1,Loc2,2022-01-29,8
2,Loc1,2022-01-27,11
2,Loc2,2022-01-28,4
2,Loc2,2022-01-29,6
3,Loc1,2022-01-28,18
3,Loc2,2022-01-29,1
```
<p>This avoids storing the input CSV in memory, only the output CSV data.</p>
<hr />
<p>If this is also too large, a slight variation would be to output <code>data</code> whenever the <code>ID</code> column changes. This would though assume the input is in <code>ID</code> order:</p>
```from collections import Counter
import csv

def write_id(csv_output, data):
    for key, value in data.items():
        csv_output.writerow([*key, value])
    data.clear()

data = Counter()
current_id = None

with open('input.csv') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    header = next(csv_input)
    csv_output.writerow(header)

    for row in csv_input:
        if current_id and row[0] != current_id:
            write_id(csv_output, data)

        data[tuple(row[:3])] += int(row[3])
        current_id = row[0]

    write_id(csv_output, data)
```

For the given example, this would give the same output.

Body:
I have a large CSV (hundreds of millions of rows) and I need to sum the Value column based on the grouping of the ID, Location, and Date columns.

My CSV is similar to:

    ID Location        Date  Value
 1   1     Loc1  2022-01-27      5
 2   1     Loc1  2022-01-27      4
 3   1     Loc1  2022-01-28      7
 4   1     Loc2  2022-01-29      8
 5   2     Loc1  2022-01-27     11
 6   2     Loc2  2022-01-28      4
 7   2     Loc2  2022-01-29      6
 8   3     Loc1  2022-01-28      9
 9   3     Loc1  2022-01-28      9
10   3     Loc2  2022-01-29      1

{ID: 1, Location: Loc1, Date: 2022-01-27} is one such group, and its sub values 5 and 4 should be summed to 9

{ID: 3, Location: Loc1, Date: 2022-01-28} is another group and its sum should be 18

Here's what that sample input should look like, processed/summed, and written to a new CSV:

ID Location        Date  Value
1     Loc1  2022-01-27      9
1     Loc1  2022-01-28      7
1     Loc2  2022-01-29      8
2     Loc1  2022-01-27     11
2     Loc2  2022-01-28      4
2     Loc2  2022-01-29      6
3     Loc1  2022-01-28     18
3     Loc2  2022-01-29      1

I know using df.groupby([columns]).sum() would give the desired result, but the CSV is so big I keep getting memory errors. I've tried looking at other ways to read/manipulate CSV data but have still not been successful, so if anyone knows a way I can do this in python without maxing out my memory that would be great!

NB: I know there is a unnamed first column in my initial csv, this is irrelevant and doesn't need to be in the outputted, but doesn't matter if it is :)

Body:
You could use the built in csv library and build up the output line by line. A Counter can be used to combine and count rows with the same entries:

from collections import Counter
import csv

data = Counter()

with open('input.csv') as f_input:
    csv_input = csv.reader(f_input)
    header = next(csv_input)

    for row in csv_input:
        data[tuple(row[:3])] += int(row[3])

with open('output.csv', 'w', newline='') as f_output:
    csv_output = csv.writer(f_output)
    csv_output.writerow(header)

    for key, value in data.items():
        csv_output.writerow([*key, value])

Giving the output:

ID,Location,Date,Value
1,Loc1,2022-01-27,9
1,Loc1,2022-01-28,7
1,Loc2,2022-01-29,8
2,Loc1,2022-01-27,11
2,Loc2,2022-01-28,4
2,Loc2,2022-01-29,6
3,Loc1,2022-01-28,18
3,Loc2,2022-01-29,1

This avoids storing the input CSV in memory, only the output CSV data.

If this is also too large, a slight variation would be to output data whenever the ID column changes. This would though assume the input is in ID order:

from collections import Counter
import csv

def write_id(csv_output, data):
    for key, value in data.items():
        csv_output.writerow([*key, value])
    data.clear()

data = Counter()
current_id = None

with open('input.csv') as f_input, open('output.csv', 'w', newline='') as f_output:
    csv_input = csv.reader(f_input)
    csv_output = csv.writer(f_output)

    header = next(csv_input)
    csv_output.writerow(header)

    for row in csv_input:
        if current_id and row[0] != current_id:
            write_id(csv_output, data)

        data[tuple(row[:3])] += int(row[3])
        current_id = row[0]

    write_id(csv_output, data)

For the given example, this would give the same output.


问:
"Failed to add the host to the list of known hosts" Windows prompt
I wanted to try and use git in my regular Windows prompt instead of in Git Bash. Simply for the reason that I could then use the terminal that IntelliJ provides. I figured it to be a 1 minute fix but I guess not.

When I try to git pull origin <branch> I get the following error message:

```<code>C:\Users\Username\Documents\Bitbucket\java-project>git pull
Could not create directory '/c/Username/.ssh'.
The authenticity of host 'bitbucket.org (131.103.20.167)' can't be established.
RSA key fingerprint is 12:8c:1b:f2:6d:14:6b:5c:3b:ec:aa:46:46:xy:7c:40.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/c/Username/.ssh/known_hosts).
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.
</code>```

I have set the permissions on the existing .ssh folder such that all Users have full access, administrators and SYSTEM. So that should be okay.

I also tried to run the prompt as Administrator to see if that was the issue but that's not the case either.

What I do notice now is that it says: Could not create directory '/c/Username/.ssh'.. However, my .ssh directory is located at C:\Users\Username\.ssh. I might need to change my configuration then.

Git version: 1.9.0.msysgit.0
Windows version: Windows 8.1

答:
Open Git Bash console.

Perform the command below to enable read and write;
chmod 776 your local path here/known_hosts

More details here

Body:
I wanted to try and use git in my regular Windows prompt instead of in Git Bash. Simply for the reason that I could then use the terminal that IntelliJ provides. I figured it to be a 1 minute fix but I guess not.

When I try to git pull origin <branch> I get the following error message:

C:\Users\Username\Documents\Bitbucket\java-project>git pull
Could not create directory '/c/Username/.ssh'.
The authenticity of host 'bitbucket.org (131.103.20.167)' can't be established.
RSA key fingerprint is 12:8c:1b:f2:6d:14:6b:5c:3b:ec:aa:46:46:xy:7c:40.
Are you sure you want to continue connecting (yes/no)? yes
Failed to add the host to the list of known hosts (/c/Username/.ssh/known_hosts).
Permission denied (publickey).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

I have set the permissions on the existing .ssh folder such that all Users have full access, administrators and SYSTEM. So that should be okay.

I also tried to run the prompt as Administrator to see if that was the issue but that's not the case either.

What I do notice now is that it says: Could not create directory '/c/Username/.ssh'.. However, my .ssh directory is located at C:\Users\Username\.ssh. I might need to change my configuration then.

Git version: 1.9.0.msysgit.0
Windows version: Windows 8.1


问:
Deleting dynamically created component?
In the OnCreate event, I have code which adds menu items to a std::vector (for the purposes of this question, it could be buttons, or any other components we create dynamically with the new operator):

```<code>// Iterrate through styles and hints and construct menu
for (int i=0; i<styleNamesAndHints->Count; i++) {
    TMenuItem* miTheme = new TMenuItem(miRoot);
    miTheme->Caption = styleNamesAndHints->Strings[i].SubString(0, styleNamesAndHints->Strings[i].Pos(styleNamesAndHints_Delimeter)-1);
    miTheme->AutoCheck = false;
    miTheme->AutoHotkeys = maManual;
    miTheme->RadioItem = false;
    miTheme->GroupIndex = MENU_GROUP_INDEX_STYLES;

    miTheme->OnClick = &miStyles_Click;
    miTheme->OnDrawItem = &miStyles_DrawItem;
    miTheme->OnMeasureItem = &miStyles_MeasureItem;
    miTheme->ImageIndex = IL_MENU_A_THEME;
    miTheme->Tag = miStyleArray.size();

    miStyleArray.push_back(miTheme);

    miRoot->Add(miTheme);
}
</code>```

Then in the OnDestroy event, we clean up the vector miStyleArray:

```<code>// Clean up miStyleArray vector, delete each element
while(miStyleArray.empty()==false) {
    delete miStyleArray.back();
    miStyleArray.pop_back();
}
</code>```

This code works... I have no errors, everything works perfectly....

Now, someone told me that code like this could lead to errors and that, I quote, I should not use operator delete on objects that have parent, parent of the object is responsible for destroying and clean up..

As a matter of fact, the person that told me this is a moderator at a C++Builder forum, and warned me that I could be banned next time for such code! Here is the post link.

Who is right, who is wrong??

答:
It is perfectly safe to manually delete a component instance that has an Owner or Parent assigned. The component's destructor will remove the instance from its Owner/Parent's internal list so the instance is not freed a 2nd time.

On the other hand, a component instance with an Owner assigned does not need to be delete'd manually, it will be freed when its Owner is freed, so your OnDestroy code is redundant and can be removed.

On a side note: you should NOT use the Form's OnCreate and OnDestroy events in C++Builder.  They are a Delphi idiom that can lead to undefined behavior in C++ if you are not careful.  OnCreate can fire before your Form's constructor, and OnDestroy can fire after your Form's destructor. As such, you should use the Form's actual constructor and destructor instead.

Title: Deleting dynamically created component?

Body:
In the OnCreate event, I have code which adds menu items to a std::vector (for the purposes of this question, it could be buttons, or any other components we create dynamically with the new operator):

// Iterrate through styles and hints and construct menu
for (int i=0; i


问:
Make an image look like it is placed over 2
 boxes with CSS

Hello I need to position an image as in the example. Theoretically it looks like it is positioned over 2 seperate  boxes with different background colors, that is the goal, but practically it is not possible, at least for me. How to solve the problem?

答:
The simplest solution will be using a combination of an  of z-index and position:absolute.

*A small suggestion if you may encounter the problem: you must use z-index with specifying the position (position: static will not work)

img {
  width: 100px;
  height: 100px;
  z-index: 99;
  position: absolute;
}

div {
  background-color: black;
  z-index: 1;
  width: 200px;
  height: 100px;
  position: absolute;
  top: 10px;
  left: 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src='https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/1200px-Wikipedia-logo-v2.svg.png'>
<div></div></code>```

Title: Make an image look like it is placed over 2 <div> boxes with CSS

Body:
The simplest solution will be using a combination of an  of z-index and position:absolute.

*A small suggestion if you may encounter the problem: you must use z-index with specifying the position (position: static will not work)

img {
  width: 100px;
  height: 100px;
  z-index: 99;
  position: absolute;
}

div {
  background-color: black;
  z-index: 1;
  width: 200px;
  height: 100px;
  position: absolute;
  top: 10px;
  left: 5px;
}

<img src='https://upload.wikimedia.org/wikipedia/en/thumb/8/80/Wikipedia-logo-v2.svg/1200px-Wikipedia-logo-v2.svg.png'>
<div></div>


问:
Any reason why I shouldn't use couchdb for message passing or realtime activity streams?
While using ampq or xmpp (rabbitmq or ejabbered that could have couchdb as backends) seems like a good fit to deliver real time updates about friend state in a social gaming platform where updates are small but frequent, I can't help but think why wouldn't couchdb be a good platform to deliver such updates?

The main advantage I could think of is its ability to filter updates based on friends and availability of changes api, which makes developing such an application and managing it (including replication) quite easy compared to ampq or xmpp where you have to think about how to manage the pubsub nodes and who is subscribed to them at any point in time.

However, I can't help but think this is too good to be true, I can't find information on what couchdb's shortcomings are. Somehow, it feels like using MySQL for message passing which is why I am hesitant to using it.

Anyone have any experience in using couchdb for such applications? would you recommend another platform to use?

答:
However, I can't help but think this is too good to be true, I can't
  find information on what couchdb's shortcomings are. Somehow, it feels
  like using MySQL for message passing which is why I am hesitant to
  using it.

Try to look at why Databases suck for Messaging presentation. Although it's mainly targeted against databases such as MySQL, it can give you a bigger picturer on this topic.

ContentLicense: CC BY-SA 2.5


问:
Automatic sorting of new folders Windows
I know about setting sorting for parent folders and stuff.
But when creating a new folder in Windows, sorting is by name. Is it possible to change some value in the registry or create some script for the action of creating a folder - so that sorting by date is automatically set.
That is, I would like it to be without any additional actions, well, there must be system settings somewhere in Windows? Even setting for all folders in the system of such a value will do.
Thanks.</p>

答:
1.Open file explorer

2.Open any folder, then select View from the top menu

3.Click on Date modified to sort by most recent

4.Select Options from the far right top menu then choose Change folder and search options

5.Select View tab, Apply to all folders

6.Create a test folder and refresh to see if it gets sorted by date

You can also refer to this answer

https://superuser.com/questions/49591/how-do-i-change-the-default-sort-order-on-windows-explorer-and-the-file-dialogs


问:
Hex and Int bitwise operation confict
Why in Kotlin bitwise operation is not possible with 4-byte hex and Int?

At the same time, there is no problem in Java

As far as I know, in JVM int takes 4 bytes.

// Kotlin
val num = 0
val n = 0xff000000 or num    // <-- 'num' ERROR
```
<pre class="lang-java prettyprint-override"><code>// Java
int num = 0;
int n = 0xff000000 | num;    // <-- 'num' OK
</code>```

答:
0xFF000000 is a Long, not an Int. It's outside the Int range since it is using 32 bits to represent a positive number, but Int only uses 31 bits for the number, and one bit for the sign. Any six-digit hexadecimal number where the first digit is greater than 7 requires 32 bits to represent the number, so it is interpreted as a Long.

Kotlin doesn't do implicit number conversions like Java because they can easily lead to obscure bugs. You have to manually convert it to an Int.

```<code>val num = 0
val n = 0xff000000.toInt() or num
</code>```

Title: Hex and Int bitwise operation confict

Body:
Why in Kotlin bitwise operation is not possible with 4-byte hex and Int?

At the same time, there is no problem in Java

As far as I know, in JVM int takes 4 bytes.

// Kotlin
val num = 0
val n = 0xff000000 or num    // <-- 'num' ERROR

// Java
int num = 0;
int n = 0xff000000 | num;    // <-- 'num' OK

Body:
0xFF000000 is a Long, not an Int. It's outside the Int range since it is using 32 bits to represent a positive number, but Int only uses 31 bits for the number, and one bit for the sign. Any six-digit hexadecimal number where the first digit is greater than 7 requires 32 bits to represent the number, so it is interpreted as a Long.

Kotlin doesn't do implicit number conversions like Java because they can easily lead to obscure bugs. You have to manually convert it to an Int.

val num = 0
val n = 0xff000000.toInt() or num