问:
Vue.Js / Vuex - how to declare id of elements
This is a simple shopping Cart
Actually, when we clic on items, it updated the total number in the Cart.

But i want now to make a better Cart: showing each items in the list. Like when we chose 2 croissiants, it adds 2 croissiants in the Cart.

My problem is, in this course, i didn't really learn how to make a Mutation dependings of the ID of the item. I'm looking for the syntax witch is sending the ID of the item where we clicked, to the store.

Here my my 3 files : (Store's "index", "Home" and it's children "MenuItem")

Store :

```<code>import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    restaurantName: 'Cafe with A Vue',
    shoppingCart: 0,
    croissiantNumber: 0,
    baguetteNumber: 0,
    eclairNumber: 0,
    simpleMenu: [
      {
        id: 1,
        name: 'Crossiant',
        image: {
          source: '/images/crossiant.jp',
          alt: 'A crossiant'
        },
        inStock: true,
        quantity: 1,
        price: 2.99
      },
      {
        id: 2,
        name: 'French Baguette',
        image: {
          source: '/images/french-baguette.jpe',
          alt: 'Four French Baguettes'
        },
        inStock: true,
        quantity: 1,
        price: 3.99
      },
      {
        id: 3,
        name: 'Éclair',
        image: {
          source: '/images/eclair.jp',
          alt: 'Chocolate Éclair'
        },
        inStock: false,
        quantity: 1,
        price: 4.99
      }
    ]
  },
  getters: {
    copyright: state => {
      const currentYear = new Date().getFullYear()

      return `Copyright ${state.restaurantName} ${currentYear}`
    }
  },
  mutations: {
    ADD_ITEMS_TO_SHOPPING_CART(state, amount) {
      state.shoppingCart += amount
    }
  },
  actions: {
    updateShoppingCart({ commit }, amount) {
      commit('ADD_ITEMS_TO_SHOPPING_CART', amount),
      commit('ADD_ITEM_TO_SHOPPING_CART', amount)
    }
  },
  modules: {}
})
</code>```

Home :

```<code><template>
  <div>
    <h1>{{ restaurantName }}</h1>
    <p class="description">
      Welcome to {{ restaurantName }}! We are known for our freshly baked bread
      and french pastries! Give you morning a warm start or treat yourself in
      the middle of the day. Our butter is imported from local farmers in
      France. Once you take your first bite, you will see why everyone can't get
      enough!
    </p>

    <section class="menu">
      <h2>Menu</h2>
      <MenuItem
        v-for="item in simpleMenu"
        :name="item.name"
        :image="item.image"
        :price="item.price"
        :quantity="item.quantity"
        :inStock="item.inStock"
        :key="item.name"
        :id="item.id"
      />
    </section>

    <div class="shopping-cart">
      <h2>Shopping Cart: {{ shoppingCart }} items</h2>
      <h2>Croissiant: {{ croissiantNumber }} items</h2>
      <h2 v-if="baguetteNumber">French Baguette: {{ baguetteNumber }} items</h2>
      <h2 v-if="eclairNumber">Eclair: {{ eclairNumber }}items</h2>
    </div>

    <footer class="footer">
      <p>{{ copyright }}</p>
    </footer>
  </div>
</template>

<script>
import MenuItem from '../components/MenuItem'
import { mapGetters, mapState } from 'vuex'

export default {
  name: 'Home',
  components: {
    MenuItem
  },
  computed: {
    ...mapGetters({
      copyright: 'copyright'
    }),
    ...mapState({
      restaurantName: 'restaurantName',
      shoppingCart: 'shoppingCart',
      croissiantNumber: 'croissiantNumber',
      baguetteNumber: 'baguetteNumber',
      eclairNumber: 'eclairNumber',
      simpleMenu: 'simpleMenu'
    })
  }
}
</script>
</code>```

MenuItem :

```<code><script>
import { mapActions } from 'vuex'
import BaseButton from './BaseButton.vue'

export default {
  name: 'MenuItem',
  components: {
    BaseButton
  },
  props: {
    image: {
      type: Object,
      required: true
    },
    inStock: {
      type: Boolean,
      required: true
    },
    name: {
      type: String,
      required: true
    },
    price: {
      type: Number,
      required: true
    },
    quantity: {
      type: Number,
      defaut: 1
    }
  },
  data() {
    return {
      onSale: false
    }
  },
  computed: {
    generatedPrice() {
      if (this.onSale) {
        return (this.price * 0.9).toFixed(2)
      } else {
        return this.price
      }
    }
  },
  methods: {
    ...mapActions(['updateShoppingCart'])
  },
  beforeMount() {
    const today = new Date().getDate()

    if (today % 2 === 0) {
      this.onSale = true
    }
  }
}
</script>

<template>
  <div class="menu-item">
    <img class="menu-item__image" :src="image.source" :alt="image.alt" />
    <div>
      <h3>{{ name }}</h3>
      <p>Price: {{ generatedPrice }} <span v-if="onSale">(10% off!)</span></p>
      <p v-if="inStock">In Stock</p>
      <p v-else>Out of Stock</p>
      <div>
        <label for="add-item-quantity">Quantity: {{ quantity }}</label>
        <input v-model.number="quantity" id="add-item-quantity" type="number" />
        <BaseButton @click="updateShoppingCart(quantity, id)" class="test">
          Add to shopping cart
        </BaseButton>
      </div>
    </div>
  </div>
</template>
</code>```

So i want to update this value for example :

```<code>Croissiant: 0 items
</code>```

Website preview

Thanks.

答:
You have to pass either object or array to your action to handle multiple parameters.

@click="updateShoppingCart({quantity, id})"

and then in store:

```<code> ...
  actions: {
    updateShoppingCart({ commit }, {quantity, id}) {
      commit('ADD_ITEMS_TO_SHOPPING_CART', amount),

      //here you have id that you can map to item type
    }
  },
</code>```

I would suggest having item type that is constant in simpleMenu and not depending on IDs.

Body:
This is a simple shopping Cart
Actually, when we clic on items, it updated the total number in the Cart.

But i want now to make a better Cart: showing each items in the list. Like when we chose 2 croissiants, it adds 2 croissiants in the Cart.

My problem is, in this course, i didn't really learn how to make a Mutation dependings of the ID of the item. I'm looking for the syntax witch is sending the ID of the item where we clicked, to the store.

Here my my 3 files : (Store's "index", "Home" and it's children "MenuItem")

Store :

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    restaurantName: 'Cafe with A Vue',
    shoppingCart: 0,
    croissiantNumber: 0,
    baguetteNumber: 0,
    eclairNumber: 0,
    simpleMenu: [
      {
        id: 1,
        name: 'Crossiant',
        image: {
          source: '/images/crossiant.jp',
          alt: 'A crossiant'
        },
        inStock: true,
        quantity: 1,
        price: 2.99
      },
      {
        id: 2,
        name: 'French Baguette',
        image: {
          source: '/images/french-baguette.jpe',
          alt: 'Four French Baguettes'
        },
        inStock: true,
        quantity: 1,
        price: 3.99
      },
      {
        id: 3,
        name: 'Éclair',
        image: {
          source: '/images/eclair.jp',
          alt: 'Chocolate Éclair'
        },
        inStock: false,
        quantity: 1,
        price: 4.99
      }
    ]
  },
  getters: {
    copyright: state => {
      const currentYear = new Date().getFullYear()

      return `Copyright ${state.restaurantName} ${currentYear}`
    }
  },
  mutations: {
    ADD_ITEMS_TO_SHOPPING_CART(state, amount) {
      state.shoppingCart += amount
    }
  },
  actions: {
    updateShoppingCart({ commit }, amount) {
      commit('ADD_ITEMS_TO_SHOPPING_CART', amount),
      commit('ADD_ITEM_TO_SHOPPING_CART', amount)
    }
  },
  modules: {}
})

Home :

<template>

{{ restaurantName }}

      Welcome to {{ restaurantName }}! We are known for our freshly baked bread
      and french pastries! Give you morning a warm start or treat yourself in
      the middle of the day. Our butter is imported from local farmers in
      France. Once you take your first bite, you will see why everyone can't get
      enough!

Menu

      <MenuItem
        v-for="item in simpleMenu"
        :name="item.name"
        :image="item.image"
        :price="item.price"
        :quantity="item.quantity"
        :inStock="item.inStock"
        :key="item.name"
        :id="item.id"
      />

Shopping Cart: {{ shoppingCart }} items

Croissiant: {{ croissiantNumber }} items

French Baguette: {{ baguetteNumber }} items

Eclair: {{ eclairNumber }}items

{{ copyright }}

</template>

MenuItem :

<template>

{{ name }}

Price: {{ generatedPrice }} (10% off!)

In Stock

Out of Stock

        Quantity: {{ quantity }}
        <input v-model.number="quantity" id="add-item-quantity" type="number" />
        <BaseButton @click="updateShoppingCart(quantity, id)" class="test">
          Add to shopping cart
        </BaseButton>

</template>

So i want to update this value for example :

Croissiant: 0 items

Website preview

Thanks.

Body:
You have to pass either object or array to your action to handle multiple parameters.

@click="updateShoppingCart({quantity, id})"

and then in store:

 ...
  actions: {
    updateShoppingCart({ commit }, {quantity, id}) {
      commit('ADD_ITEMS_TO_SHOPPING_CART', amount),

      //here you have id that you can map to item type
    }
  },

I would suggest having item type that is constant in simpleMenu and not depending on IDs.


来源: stackexchange

问:
Replace dots in filename Python
im trying to replace all dots (and accents, but's already done) in filename with underscore except extension dot of course.
I saw a lot of solutions but mainly with bash. Cant find for python. Probably I should use regex but dont have much experience here. Below my code:</p>

```<code>path2 = 'xx'
dicto = {"ą":"a",
         "ś":"s",
         "ę":"e",
         "ć":"c",
         "ż":"z",
         "ź":"z",
         "ó":"o",
         "ł":"l",
         "ń":"n"}

def find_replace(string, dictionary):
    for item in string:
        if item in dictionary.keys():
            string = string.replace(item, dictionary[item])
    return string

def change_name(path=path2):
    for root, dirs, files in os.walk(path):
        for filename in files:
            if not filename.startswith('~'):
                os.rename(os.path.join(root,filename), os.path.join(root,find_replace(filename, dicto)))

change_name()

</code>```

答:
There are a number of existing answers here to remove diacritics from Unicode text in python. There is a unidecode library for python3 which does exactly what you need.

Removing diacritical marks using Python

What is the best way to remove accents in a Python unicode string?

ContentLicense: CC BY-SA 4.0

Title: Replace dots in filename Python

Body:
im trying to replace all dots (and accents, but's already done) in filename with underscore except extension dot of course.
I saw a lot of solutions but mainly with bash. Cant find for python. Probably I should use regex but dont have much experience here. Below my code:

path2 = 'xx'
dicto = {"ą":"a",
         "ś":"s",
         "ę":"e",
         "ć":"c",
         "ż":"z",
         "ź":"z",
         "ó":"o",
         "ł":"l",
         "ń":"n"}

def find_replace(string, dictionary):
    for item in string:
        if item in dictionary.keys():
            string = string.replace(item, dictionary[item])
    return string

def change_name(path=path2):
    for root, dirs, files in os.walk(path):
        for filename in files:
            if not filename.startswith('~'):
                os.rename(os.path.join(root,filename), os.path.join(root,find_replace(filename, dicto)))

change_name()


问:
TestNG XML: Groups still being executed although failure occurred in the dependent group
i've setup my xml so it will run groups which depends-on different group in order to run.
when the different group fails, i would expect that the groups won't run, but it is still running.
here is my code:

```<code><test name="Test1">
    <parameter name="testedApp" value="someValue"/>
    <groups>
        <run>
            **<include name="Test1"/>**
            <exclude name="TestX"/>
            <exclude name="TextY"/>
        </run>
        <dependencies>
            <!-- Service Health Check -->
            **<group name="Test1" depends-on="ServiceHealthCheck"/>**
        </dependencies>
    </groups>
    <packages>
        <package name="project.auto.tests.api...*"/>(package)
    </packages>
    <classes>
        <!-- Service Health Check -->
        <class name=".....PbServiceHealthCheckTest"/>(class)
    </classes>
</test>
</code>```

答:
Answer: TestNG 6.14.3 has a bug which prevenr the "depends-on" to work correctly.
Upgrade to TestNG 7.1.0 solved the issue.</p>

Body:
i've setup my xml so it will run groups which depends-on different group in order to run.
when the different group fails, i would expect that the groups won't run, but it is still running.
here is my code:

<test name="Test1">
    <parameter name="testedApp" value="someValue"/>
    <groups>
        <run>
            **<include name="Test1"/>**
            <exclude name="TestX"/>
            <exclude name="TextY"/>
        </run>
        <dependencies>

            **<group name="Test1" depends-on="ServiceHealthCheck"/>**
        </dependencies>
    </groups>
    <packages>
        <package name="project.auto.tests.api...*"/>(package)
    </packages>
    <classes>

        <class name=".....PbServiceHealthCheckTest"/>(class)
    </classes>
</test>


问:
Why my database is not working, I am using ways in official documentation?
I have a problem: Firebase Database is not working and I cannot understand why that happened (cannot post data to server, when I press button to send data- nothing happens, data does not saving in server).

Look my code:

```<code>private var db = FirebaseDatabase.getInstance()
private lateinit var dbReference: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 setSupportActionBar(toolbar)

 dbReference = db.reference.child("member")

 add_item_to_db_button.setOnClickListener {
     dbReference.push()
         .setValue(Member(item_name.text.toString(), item_description.text.toString()))

 }
}
</code>```

My constructor class to send data to a database:

```<code> class Member {
 lateinit var itemName: String
 lateinit var itemDescription: String

constructor()
constructor(itemName: String, itemDescription: String) {
    this.itemName = itemName
    this.itemDescription = itemDescription
  }

}
</code>```

My dependencies(google() and jcenter() Is enabled in top-level Gradle):

```<code>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'
implementation 'com.google.android.material:material:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

// Firebase
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.firebaseui:firebase-ui:0.6.2'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

}

apply plugin: 'com.google.gms.google-services'
</code>```

My XML file:

```<code> <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:padding="40dp"
 android:orientation="vertical"
 android:gravity="center"
 android:layout_height="match_parent">

 <ImageView
    android:layout_width="200dp"
    android:src="@color/cardview_dark_background"
    android:layout_marginBottom="30dp"
    android:layout_height="200dp"/>

 <EditText
    android:layout_width="match_parent"
    android:id="@+id/item_name"
    android:text="Description"
    android:layout_height="wrap_content"/>

 <EditText
    android:text="Name of product"
    android:layout_width="match_parent"
    android:id="@+id/item_description"
    android:layout_height="wrap_content"/>

 <Button
    android:id="@+id/add_item_to_db_button"
    android:layout_width="match_parent"
    android:text="Add"
    android:layout_height="wrap_content"/>

</LinearLayout>
</code>```

And finally, database rules:

```<code>"rules": {
   ".read": true,
   ".write": true
 }
</code>```

I'm do not understand why db is not working. Tried several ways was posted in StackOverflow - does not help.

答:
You need valid network and this permission in your manifest files. Cross check in your manifest file. </p>

```<code><uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
</code>```

Body:
I have a problem: Firebase Database is not working and I cannot understand why that happened (cannot post data to server, when I press button to send data- nothing happens, data does not saving in server).

Look my code:

private var db = FirebaseDatabase.getInstance()
private lateinit var dbReference: DatabaseReference

override fun onCreate(savedInstanceState: Bundle?) {
 super.onCreate(savedInstanceState)
 setContentView(R.layout.activity_main)
 setSupportActionBar(toolbar)

 dbReference = db.reference.child("member")

 add_item_to_db_button.setOnClickListener {
     dbReference.push()
         .setValue(Member(item_name.text.toString(), item_description.text.toString()))

 }
}

My constructor class to send data to a database:

 class Member {
 lateinit var itemName: String
 lateinit var itemDescription: String

constructor()
constructor(itemName: String, itemDescription: String) {
    this.itemName = itemName
    this.itemDescription = itemDescription
  }

}

My dependencies(google() and jcenter() Is enabled in top-level Gradle):

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'
implementation 'com.google.android.material:material:1.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

// Firebase
implementation 'com.google.firebase:firebase-analytics:17.2.2'
implementation 'com.google.firebase:firebase-database:19.2.1'
implementation 'com.google.firebase:firebase-auth:19.2.0'
implementation 'com.google.firebase:firebase-core:17.2.2'
implementation 'com.firebaseui:firebase-ui:0.6.2'
implementation 'com.google.android.gms:play-services-gcm:17.0.0'
implementation 'com.google.android.gms:play-services-auth:17.0.0'
implementation 'com.firebaseui:firebase-ui-auth:4.3.1'

}

apply plugin: 'com.google.gms.google-services'

My XML file:

 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:padding="40dp"
 android:orientation="vertical"
 android:gravity="center"
 android:layout_height="match_parent">

 <ImageView
    android:layout_width="200dp"
    android:src="@color/cardview_dark_background"
    android:layout_marginBottom="30dp"
    android:layout_height="200dp"/>

 <EditText
    android:layout_width="match_parent"
    android:id="@+id/item_name"
    android:text="Description"
    android:layout_height="wrap_content"/>

 <EditText
    android:text="Name of product"
    android:layout_width="match_parent"
    android:id="@+id/item_description"
    android:layout_height="wrap_content"/>

 <Button
    android:id="@+id/add_item_to_db_button"
    android:layout_width="match_parent"
    android:text="Add"
    android:layout_height="wrap_content"/>

</LinearLayout>

And finally, database rules:

"rules": {
   ".read": true,
   ".write": true
 }

I'm do not understand why db is not working. Tried several ways was posted in StackOverflow - does not help.

Body:
You need valid network and this permission in your manifest files. Cross check in your manifest file.

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


问:
Can't Add Icon To Electron App With Electron Builder
I have made an app with Electron and am trying to package it with Electron Builder.

Link to repository

Does not contain node_modules folder: Repo here

I have a folder named build with my icon.ico in it and my package.json is as follows:

```<code>{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "win": {
            "icon": "./build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}
</code>```

However, I receive the following error:

```<code>error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

Any ideas why this happening and how to fix it?

With the following package.json:

```<code>{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder build"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "directories": {
            "buildResources": "build"
        },
        "win": {
            "icon": "build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}
</code>```

I receive the error:

```<code>yarn dist
yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  ⨯ Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that
does not match the API schema.
 - configuration.win should be one of these:
   object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null
   -> Options related to how build Windows targets.
   Details:
    * configuration.win has an unknown property 'title'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
    * configuration.win has an unknown property 'msi'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
     How to fix:
     1. Open https://www.electron.build/configuration/win
     2. Search the option name on the page (or type in into Search to find across the docs).
       * Not found? The option was deprecated or not exists (check spelling).
       * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.
  stackTrace=

                                                                   ValidationError: Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that does not match the API schema.

                                                                    - configuration.win should be one of these:

                                                                      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null

                                                                      -> Options related to how build Windows targets.

                                                                      Details:

                                                                       * configuration.win has an unknown property 'title'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                       * configuration.win has an unknown property 'msi'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                        How to fix:

                                                                        1. Open https://www.electron.build/configuration/win

                                                                        2. Search the option name on the page (or type in into Search to find across the docs).

                                                                          * Not found? The option was deprecated
or not exists (check spelling).

                                                                          * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.

                                                                       at validate (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\@develar\schema-utils\dist\validate.js:50:11)

                                                                       at validateConfig (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\util\config.ts:229:3)

                                                                       at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:342:5)

                                                                       at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                                       at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
</code>```

Edit number 2

I am now receiving the following error:

```<code>yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  • writing effective config  file=dist\builder-effective-config.yaml
  • packaging       platform=win32 arch=x64 electron=8.0.1 appOutDir=dist\win-unpacked
  • asar usage is disabled — this is strongly not recommended  solution=enable asar and use asarUnpack to unpack
files that must be externally available
  ⨯ cannot execute  cause=exit status 1
                    errorOut=Fatal error: Unable to commit changes

                    command='C:\Users\alexr\AppData\Local\electron-builder\Cache\winCodeSign\winCodeSign-2.5.0\rcedit-x64.exe' 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\win-unpacked\Attendant.exe' --set-version-string FileDescription Attendant --set-version-string ProductName Attendant --set-version-string LegalCopyright 'Copyright © 2020 Attendant' --set-file-version 1.1.0 --set-product-version 1.1.0.0 --set-version-string InternalName Attendant --set-version-string OriginalFilename '' --set-icon 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\.icon-ico\icon.ico'
                    workingDir=
  ⨯ C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE  stackTrace=

                                                  Error: C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE

                                                      at ChildProcess.<anonymous> (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\util.ts:239:14)

                                                      at Object.onceWrapper (events.js:313:26)

                                                      at ChildProcess.emit (events.js:223:5)

                                                      at maybeClose (internal/child_process.js:1021:16)

                                                      at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)

                                                  From previous event:

                                                      at processImmediate (internal/timers.js:439:21)

                                                  From previous event:

                                                      at WinPackager.signApp (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\winPackager.ts:357:27)

                                                      at WinPackager.doPack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:243:16)

                                                      at WinPackager.pack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:114:5)

                                                      at Packager.doBuild (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:444:9)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)

                                                      at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:373:31)

                                                      at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

</code>```

thanks for the support so far

答:
```<code>"build":{
    "productName":"yourProductName",
    "appId":"org.yourProductName",
    "dmg":{
        "contents":[
            {
                "x":130,
                "y":220
            },
            {
                "x":410,
                "y":220,
                "type":"link",
                "path":"/Applications"
            }
        ]
    },
    "win":{
        "target":[
            "nsis",
            "msi"
        ]
    },
    "linux":{
        "target":[
            "deb",
            "rpm",
            "snap",
            "AppImage"
        ],
        "category":"Development"
    },
    "directories":{
        "buildResources":"resources",
        "output":"release"
    },
    "files: ["resources/**/*"], // including buildResources folder in order to use this in the code
        },"
</code>```

I attached example electron-builder configuration that I configured for my project before.
Please consider this part

```<code>"directories": {
    "buildResources": "resources",
    "output": "release"
}
</code>```

buildResources should include resource files like icons. If you are not going to set this buildResources manually then the default will be build.
output is indicating where the packaged app will be after packaging and it's optional for your issue. Anyhow, I've set the project to generate release artifacts on the "release" folder.

In this project, I'm saving the icons in the project root directory like below. I don't know where your icon files are so I've attached the project structure that is working with this build configuration.

Body:
I have made an app with Electron and am trying to package it with Electron Builder.

Link to repository

Does not contain node_modules folder: Repo here

I have a folder named build with my icon.ico in it and my package.json is as follows:

{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "win": {
            "icon": "./build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}

However, I receive the following error:

error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Any ideas why this happening and how to fix it?

With the following package.json:

{
    "name": "attendant",
    "productName": "Attendant",
    "version": "0.1.0",
    "description": "A simple app to streamline web development by allowing you index.html to open on a live server in the default browser",
    "main": "main.js",
    "scripts": {
        "start": "electron .",
        "pack": "electron-builder --dir",
        "dist": "electron-builder build"
    },
    "devDependencies": {
        "electron": "^8.0.1",
        "electron-builder": "^22.3.2"
    },
    "build": {
        "appId": "com.attendant",
        "directories": {
            "buildResources": "build"
        },
        "win": {
            "icon": "build/icon.png",
            "title": "Attendant",
            "msi": true
        }
    }
}

I receive the error:

yarn dist
yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  ⨯ Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that
does not match the API schema.
 - configuration.win should be one of these:
   object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null
   -> Options related to how build Windows targets.
   Details:
    * configuration.win has an unknown property 'title'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
    * configuration.win has an unknown property 'msi'. These properties are valid:
      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?,
generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }
     How to fix:
     1. Open https://www.electron.build/configuration/win
     2. Search the option name on the page (or type in into Search to find across the docs).
       * Not found? The option was deprecated or not exists (check spelling).
       * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.
  stackTrace=

                                                                   ValidationError: Invalid configuration object. electron-builder 22.3.2 has been initialised using a configuration object that does not match the API schema.

                                                                    - configuration.win should be one of these:

                                                                      object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? } | null

                                                                      -> Options related to how build Windows targets.

                                                                      Details:

                                                                       * configuration.win has an unknown property 'title'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                       * configuration.win has an unknown property 'msi'. These properties are valid:

                                                                         object { additionalCertificateFile?, appId?, artifactName?, asar?, asarUnpack?, certificateFile?, certificatePassword?, certificateSha1?, certificateSubjectName?, compression?, cscKeyPassword?, cscLink?, detectUpdateChannel?, electronUpdaterCompatibility?, extraFiles?, extraResources?, fileAssociations?, files?, forceCodeSigning?, generateUpdatesFilesForAllChannels?, icon?, legalTrademarks?, protocols?, publish?, publisherName?, releaseInfo?, requestedExecutionLevel?, rfc3161TimeStampServer?, sign?, signAndEditExecutable?, signDlls?, signingHashAlgorithms?, target?, timeStampServer?, verifyUpdateCodeSignature? }

                                                                        How to fix:

                                                                        1. Open https://www.electron.build/configuration/win

                                                                        2. Search the option name on the page (or type in into Search to find across the docs).

                                                                          * Not found? The option was deprecated
or not exists (check spelling).

                                                                          * Found? Check that the option in the appropriate place. e.g. "title" only in the "dmg", not in the root.

                                                                       at validate (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\@develar\schema-utils\dist\validate.js:50:11)

                                                                       at validateConfig (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\util\config.ts:229:3)

                                                                       at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:342:5)

                                                                       at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                                       at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Edit number 2

I am now receiving the following error:

yarn run v1.22.0
warning package.json: No license field
$ electron-builder build
  • electron-builder  version=22.3.2 os=10.0.18363
  • loaded configuration  file=package.json ("build" field)
  • author is missed in the package.json  appPackageFile=C:\Users\alexr\Documents\GitHub\attendant-app\app\package.json
  • writing effective config  file=dist\builder-effective-config.yaml
  • packaging       platform=win32 arch=x64 electron=8.0.1 appOutDir=dist\win-unpacked
  • asar usage is disabled — this is strongly not recommended  solution=enable asar and use asarUnpack to unpack
files that must be externally available
  ⨯ cannot execute  cause=exit status 1
                    errorOut=Fatal error: Unable to commit changes

                    command='C:\Users\alexr\AppData\Local\electron-builder\Cache\winCodeSign\winCodeSign-2.5.0\rcedit-x64.exe' 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\win-unpacked\Attendant.exe' --set-version-string FileDescription Attendant --set-version-string ProductName Attendant --set-version-string LegalCopyright 'Copyright © 2020 Attendant' --set-file-version 1.1.0 --set-product-version 1.1.0.0 --set-version-string InternalName Attendant --set-version-string OriginalFilename '' --set-icon 'C:\Users\alexr\Documents\GitHub\attendant-app\app\dist\.icon-ico\icon.ico'
                    workingDir=
  ⨯ C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE  stackTrace=

                                                  Error: C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-bin\win\x64\app-builder.exe exited with code ERR_ELECTRON_BUILDER_CANNOT_EXECUTE

                                                      at ChildProcess.<anonymous> (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\util.ts:239:14)

                                                      at Object.onceWrapper (events.js:313:26)

                                                      at ChildProcess.emit (events.js:223:5)

                                                      at maybeClose (internal/child_process.js:1021:16)

                                                      at Process.ChildProcess._handle.onexit (internal/child_process.js:283:5)

                                                  From previous event:

                                                      at processImmediate (internal/timers.js:439:21)

                                                  From previous event:

                                                      at WinPackager.signApp (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\winPackager.ts:357:27)

                                                      at WinPackager.doPack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:243:16)

                                                      at WinPackager.pack (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\platformPackager.ts:114:5)

                                                      at Packager.doBuild (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:444:9)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)

                                                      at Packager._build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:373:31)

                                                      at Packager.build (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\src\packager.ts:337:12)

                                                      at executeFinally (C:\Users\alexr\Documents\GitHub\attendant-app\app\node_modules\app-builder-lib\node_modules\builder-util\src\promise.ts:12:14)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

thanks for the support so far

Body:
"build":{
    "productName":"yourProductName",
    "appId":"org.yourProductName",
    "dmg":{
        "contents":[
            {
                "x":130,
                "y":220
            },
            {
                "x":410,
                "y":220,
                "type":"link",
                "path":"/Applications"
            }
        ]
    },
    "win":{
        "target":[
            "nsis",
            "msi"
        ]
    },
    "linux":{
        "target":[
            "deb",
            "rpm",
            "snap",
            "AppImage"
        ],
        "category":"Development"
    },
    "directories":{
        "buildResources":"resources",
        "output":"release"
    },
    "files: ["resources/**/*"], // including buildResources folder in order to use this in the code
        },"

I attached example electron-builder configuration that I configured for my project before.
Please consider this part

"directories": {
    "buildResources": "resources",
    "output": "release"
}

buildResources should include resource files like icons. If you are not going to set this buildResources manually then the default will be build.
output is indicating where the packaged app will be after packaging and it's optional for your issue. Anyhow, I've set the project to generate release artifacts on the "release" folder.

In this project, I'm saving the icons in the project root directory like below. I don't know where your icon files are so I've attached the project structure that is working with this build configuration.


问:
VS 2017 Live Unit Testing persisted data directory is read only
I'm having an issue with live unit testing, and have found that the solution may be to set a different persisted data directory (seen below). I try to do this, but that field is read-only for me. Running VS as administrator does nothing. What could cause this?

答:
You have to stop Live Unit Testing in order to change the settings. </p>

<p>That's what worked for me. </p>

Body:
You have to stop Live Unit Testing in order to change the settings.

That's what worked for me.


问:
How to run sequential Tasks in an ExecutorService
I would like to execute different tasks for each player in an event executor, but make sure that the tasks submitted for each player are in order. Here is a picture to hopefully explain in better.

Extra Information:

I know which player will be effected for each task

I receive the tasks for each player in a pseudo-random order. (I will not know the order of task input before hand)

I need each player to basically have their own "thread" so that their tasks execute in order of insertion.

What I have tried:

Currently I am using Executors.newSingleThreadExecutor() inside of each player object to mimic this functionality, but I don't think this will scale well with a lot of players. Hence why I am asking here to find a better method.

答:
I see three main ways of achieving this.

Thread per player

This is a bit like what you are doing. Create a thread per player, dispatch work units to it; this is serial by nature.

It may not scale well to a few hundreds / thousands of players (a few hundred active threads usually do not scare mordern hardware - although it may not be really efficient).

But the readability and ligthness of the code will probably be unmatched by other solutions.

Shared threads with consistent routing

If a thread per player is not possible, then we will have to share threads, and a thread will deal with several players.

The key will be to have a given thread handle every task for a given player, so as to achieve serial execution.

Three ways of building this come to mind...

Create groups of players

If your players have something to allow for grouping (e.g. a Team, or even just a creation date)... then regroup your players by group, and implement a "Thread per group" pattern.

The only key issue is to have groups of roughly the same size, so as to share the load evenly.

Another issue, that you will have in almost every solution, will be to shutdown the thread for the group (how do you know when everything you wanted to process is finished ?).

Shared threads and ExecutorService

This is the "do it yourself way". The gist of it is

create a fixedThreadPool, say with 4 threads.

Create a 4 BlockingQueue that will hold every work units

Create 4 PlayerWorker instances and send them to the thread pool to being execution, one for each of the above BlockingQueue. The implementation of these workers is to pull data from one of the queues and execute it.

Dispatch your player work units by sending them to the queue. The key here is to always reuse the same queue for the same player (e.g. if your player has an identifier property, say a long, then dispatch all work units to the Math.abs(id % 4)th queue

Shut down the PlayerWorker and thread pool when everything is done

This is a lot of work, so...

Using a framework

Some people have already done it for you. The actor pattern is a very good fit for this problem. You should probably check out Akka and what is called ConsistentHashingRoutingLogic, which is a pretty much one to one mapping, conceptually at least, to what I just described.

The reactive way

If we step back a bit, we do not actually care about threads. We care about serial execution.

So we just need a way to perform some work after some other work is done. It should be just a call back !

And we have CompletableFuture for that (not to mention frameworks).

So why not create one CompletableFuture per player, and each time a new work unit is to be done for this player, use CompletableFuture.thenApply or thenApplyAsync.

By dispatching the executions to an appropriately sized execution pool, and letting the framework do the job, the tasks will be serially executed one after the other.


问:
Passing python logging handles through to sub modules
I'm trying to get logging calls in sub modules to use handles defined in a parent script. Is this possible without passing the logger instance through directly?

For example, if I have a parent script like this:

parent.py

```<code>import sys
import logging
from child import child_function

logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(10)

for _ in range(2):
    print('1. There was an old man named Michael Finnegan.')
    logger.info('2. He had whiskers on his chin-a-gen.')
    child_function()
</code>```

child.py

```<code>import logging

def child_function():
    logger = logging.getLogger(__name__)
    logger.info('3. The wind came up and blew them in again')
    print('4. Poor old Michael Finnegan, begin again.')
</code>```

Then when I run parent.py I get:

```<code>1. There was an old man named Michael Finnegan.
2020-02-20 11:48:48,646 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
4. Poor old Michael Finnegan, begin again.
1. There was an old man named Michael Finnegan.
2020-02-20 11:48:48,646 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
4. Poor old Michael Finnegan, begin again.
</code>```

So I'm missing line three! If I add logger as an argument to child_function()...

```<code>def child_function(parent_logger):
    logger = parent_logger.getChild(__name__)
    logger.info('3. The wind came up and blew them in again')
    print('4. Poor old Michael Finnegan, begin again.')
</code>```

Then I get the expected result:

```<code>1. There was an old man named Michael Finnegan.
2020-02-20 11:54:10,988 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
2020-02-20 11:54:10,988 - __main__.child - INFO - 3. The wind came up and blew them in again
4. Poor old Michael Finnegan, begin again.
1. There was an old man named Michael Finnegan.
2020-02-20 11:54:10,988 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
2020-02-20 11:54:10,988 - __main__.child - INFO - 3. The wind came up and blew them in again
4. Poor old Michael Finnegan, begin again.
</code>```

But I thought the idea of the getLogger(main) line was to get root loggers automatically. What have I misunderstood?

答:
First off, if you want the actual root logger, call getLogger() without any arguments.

For some additional background details on what will be described below, please refer to the documentation for how the logging module sets up the hierarchy.

What happened was that you called getLogger(__name__) in parent.py, that automatically gets a specific logger named with whatever that got assigned to __name__, rather than the root logger itself (since you executed the parent.py file directly, it becomes the __main__ module).  As for child.py, it was imported as child so the __name__ was set up as child, thus it really was one level down from the "root" logger and does not have any other parent.

Since the logging module use a dot (.) as the separator, this leads back to why you may have read some recommendation for the usage of getLogger(__name__) being a way to get a common parent to child loggers.  It may be noted that in Python, the namespace separator is also . such that __name__ that is automatically available to any given module will be the canonical import name.

To illustrate with an example, given the following example package structure:

```<code>.
├── example
│   ├── __init__.py
│   ├── lib.py
│   ├── main.py
│   └── submodule
│       ├── __init__.py
│       ├── demo1.py
│       └── demo2.py
└── setup.py
</code>```

Inside example/__init__.py, a logger may be set up as such (to borrow part of your example):

```<code>import logging
import sys

logger = logging.getLogger(__name__)
handler = logging.StreamHandler(sys.stdout)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
</code>```

This would in fact set up the "parent" logger for all loggers prefixed with 'example.', as __name__ would resolve to example when another module does an import example.

Incidentally, this would also mean that the other modules such as example.main and even example.submodule.demo1 (which those respective modules will also acquire their loggers with the same code, getLogger(__name__)), will now actually benefit from the handler and level that was set up by their relative root logger done inside the example module.  Likewise inside example/submodule/__init__.py, this module can acquire a common parent to everything logger prefixed with 'example.submodule.' simply by assigning the result of getLogger(__name__) to a variable and make use of that.

Body:
I'm trying to get logging calls in sub modules to use handles defined in a parent script. Is this possible without passing the logger instance through directly?

For example, if I have a parent script like this:

parent.py

import sys
import logging
from child import child_function

logger = logging.getLogger(__name__)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(10)

for _ in range(2):
    print('1. There was an old man named Michael Finnegan.')
    logger.info('2. He had whiskers on his chin-a-gen.')
    child_function()

child.py

import logging

def child_function():
    logger = logging.getLogger(__name__)
    logger.info('3. The wind came up and blew them in again')
    print('4. Poor old Michael Finnegan, begin again.')

Then when I run parent.py I get:

1. There was an old man named Michael Finnegan.
2020-02-20 11:48:48,646 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
4. Poor old Michael Finnegan, begin again.
1. There was an old man named Michael Finnegan.
2020-02-20 11:48:48,646 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
4. Poor old Michael Finnegan, begin again.

So I'm missing line three! If I add logger as an argument to child_function()...

def child_function(parent_logger):
    logger = parent_logger.getChild(__name__)
    logger.info('3. The wind came up and blew them in again')
    print('4. Poor old Michael Finnegan, begin again.')

Then I get the expected result:

1. There was an old man named Michael Finnegan.
2020-02-20 11:54:10,988 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
2020-02-20 11:54:10,988 - __main__.child - INFO - 3. The wind came up and blew them in again
4. Poor old Michael Finnegan, begin again.
1. There was an old man named Michael Finnegan.
2020-02-20 11:54:10,988 - __main__ - INFO - 2. He had whiskers on his chin-a-gen.
2020-02-20 11:54:10,988 - __main__.child - INFO - 3. The wind came up and blew them in again
4. Poor old Michael Finnegan, begin again.

But I thought the idea of the getLogger(main) line was to get root loggers automatically. What have I misunderstood?

Body:
First off, if you want the actual root logger, call getLogger() without any arguments.

For some additional background details on what will be described below, please refer to the documentation for how the logging module sets up the hierarchy.

What happened was that you called getLogger(__name__) in parent.py, that automatically gets a specific logger named with whatever that got assigned to __name__, rather than the root logger itself (since you executed the parent.py file directly, it becomes the __main__ module).  As for child.py, it was imported as child so the __name__ was set up as child, thus it really was one level down from the "root" logger and does not have any other parent.

Since the logging module use a dot (.) as the separator, this leads back to why you may have read some recommendation for the usage of getLogger(__name__) being a way to get a common parent to child loggers.  It may be noted that in Python, the namespace separator is also . such that __name__ that is automatically available to any given module will be the canonical import name.

To illustrate with an example, given the following example package structure:

.
├── example
│   ├── __init__.py
│   ├── lib.py
│   ├── main.py
│   └── submodule
│       ├── __init__.py
│       ├── demo1.py
│       └── demo2.py
└── setup.py

Inside example/__init__.py, a logger may be set up as such (to borrow part of your example):

import logging
import sys

logger = logging.getLogger(__name__)
handler = logging.StreamHandler(sys.stdout)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)

This would in fact set up the "parent" logger for all loggers prefixed with 'example.', as __name__ would resolve to example when another module does an import example.

Incidentally, this would also mean that the other modules such as example.main and even example.submodule.demo1 (which those respective modules will also acquire their loggers with the same code, getLogger(__name__)), will now actually benefit from the handler and level that was set up by their relative root logger done inside the example module.  Likewise inside example/submodule/__init__.py, this module can acquire a common parent to everything logger prefixed with 'example.submodule.' simply by assigning the result of getLogger(__name__) to a variable and make use of that.


问:
Table without a identity column but this column can't have repeated values
I'm creating a table that needs to have 2 columns. The first column can't be repeated. The thing is, I will insert the value of the first column. How do I create this column?
SQLServer 2005</p>

答: Set the column as a primary key. I doesn't have to be an identity column to has a PK.</p>

ContentLicense: CC BY-SA 3.0


问:
What does **node.borrow() do?

/// Traverses the network of nodes and returns the input node
fn get_input(node: Rc<RefCell<Box<Node>>>) -> Rc<RefCell<Box<Node>>> {
    match **node.borrow() { // here
        Node::Input { .. } => Rc::clone(&node),
        _ => { ... },
    }
}
```

I'm confused as to why this edit was suggested and why it works. What I think is most confusing are the implicit dereferences that sometimes happen.

For example, .borrow() is a method of RefCell, yet I'm allowed to call it directly on an Rc. Moreover this works too: **(*node).borrow().

答:
let node = *(*((*node).borrow())) is equivalent to:

let node = *node; // Rc implements Deref, node is now RefCell<Box<Node>>
let node =  node.borrow(); // a RefCell method, node is now Ref<<'empty>, Box<Node>>
let node = *node; // Ref implements Deref, node is now Box<Node>
let node = *node; // Box implements Deref, node is now Node
```

The explicit form *(*((*node).borrow())) is equivalent to the implicit **node.borrow() because (of operator precedence and) Deref coercion, whereby Rc is automatically dereferenced for the call of .borrow() to apply to what it's pointing to.

Title: What does **node.borrow() do?

Body:
/// Traverses the network of nodes and returns the input node
fn get_input(node: Rc<RefCell<Box<Node>>>) -> Rc<RefCell<Box<Node>>> {
    match **node.borrow() { // here
        Node::Input { .. } => Rc::clone(&node),
        _ => { ... },
    }
}

I'm confused as to why this edit was suggested and why it works. What I think is most confusing are the implicit dereferences that sometimes happen.

For example, .borrow() is a method of RefCell, yet I'm allowed to call it directly on an Rc. Moreover this works too: **(*node).borrow().

Body:
let node = *(*((*node).borrow())) is equivalent to:

let node = *node; // Rc implements Deref, node is now RefCell<Box<Node>>
let node =  node.borrow(); // a RefCell method, node is now Ref<<'empty>, Box<Node>>
let node = *node; // Ref implements Deref, node is now Box<Node>
let node = *node; // Box implements Deref, node is now Node

The explicit form *(*((*node).borrow())) is equivalent to the implicit **node.borrow() because (of operator precedence and) Deref coercion, whereby Rc is automatically dereferenced for the call of .borrow() to apply to what it's pointing to.


问:
Email template - table background image not displaying in MS Office Outlook 365
For the purpose of an email template, I need to implement a background image in the
 and its contain texts over image. Now I have tried:

https://stackoverflow.com/a/15620571/6191987

```<code><!--[if gte mso 9]>
<v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
<v:fill type="tile" src="http://i.imgur.com/n8Q6f.png" color="#f6f6f6"/>
</v:background>
<![endif]-->
</code>```

Its not working latest versions of MS Outlook (Version 16005.11029.20108.0 & Version 1908 Build 11929.20562),

But working fine with older versions.

Any new method to solve this problem?

答:
Found this solution

From: https://litmus.com/community/discussions/357-outlook-07-13-full-width-background-image

This works in Outlook, Office 365, Gmail etc. also in normal & 4k screens.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <title>Test</title>

        Text goes here!

```

Body:
For the purpose of an email template, I need to implement a background image in the
 and its contain texts over image. Now I have tried:

https://stackoverflow.com/a/15620571/6191987

Its not working latest versions of MS Outlook (Version 16005.11029.20108.0 & Version 1908 Build 11929.20562),

But working fine with older versions.

Any new method to solve this problem?

Body:
Found this solution

From: https://litmus.com/community/discussions/357-outlook-07-13-full-width-background-image

This works in Outlook, Office 365, Gmail etc. also in normal & 4k screens.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word">

<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="format-detection" content="telephone=no" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="apple-mobile-web-app-capable" content="yes" />
  <meta name="apple-mobile-web-app-status-bar-style" content="black" />
  <title>Test</title>
  <style>
    v\:* {
      behavior: url(#default#VML);
      display: inline-block
    }

    o\:* {
      behavior: url(#default#VML);
      display: inline-block
    }

    w\:* {
      behavior: url(#default#VML);
      display: inline-block
    }

    body {
      margin: 0;
      padding: 0;
      width: 100%;
      -webkit-text-size-adjust: none !important;
      -ms-text-size-adjust: none !important;
    }
  </style>

  <!--[if gte mso 9]><xml>
 <o:OfficeDocumentSettings>
  <o:AllowPNG/>
  <o:PixelsPerInch>96</o:PixelsPerInch>
 </o:OfficeDocumentSettings>
</xml><![endif]-->

</head>

<body style="padding: 0; margin: 0; -webkit-text-size-adjust: none !important;color:#fff;font-family:sans-serif;font-size: 18px;">
  <table cellspacing="0" cellpadding="0" border="0" bgcolor="#0058a5" width="100%">
    <tr>
      <td height="50">&nbsp;</td>
    </tr>
  </table>
  <table width="100%" cellspacing="0" cellpadding="0" border="0">
    <tr>
      <td height="150" bgcolor="#0086cc" background="http://i.imgur.com/HzZCJei.png" style="height: 150px;" align="center">
        <!--[if gte mso 9]>
        <v:rect stroke="f" fill="t" style="mso-width-percent: 1000;height:150px; position: relative; z-index: 0; mso-width-relative:margin;">
        <v:fill type="frame" src="http://i.imgur.com/HzZCJei.png" color="#0086cc" />
        </v:rect>
        <![endif]-->
        Text goes here!
      </td>
    </tr>
  </table>
</body>

</html>


问:
Difference between print(<variable_name>) and <variable_name> in python shell?
When i was going through the codes i found an interesting thing, if we initialize a variable in python shell, and we print that variable we get the value, if we use type the variable and press enter we get the same value. I could't figure out the reason behind it?? Can anyone help....</p>

```<code>>a = 5
>print(a)
>5
>a
5
</code>```

答:
The Python console is a Read Evaluate Print Loop (REPL). It first reads your input, evaluates it, prints any output, and repeats until you exit. It's a very common way to interact with a language, and exists for many many languages.

Another example of what you've observed is

```<code>>>> 1+2
3
</code>```

Here the console evaluates 1+2 and prints the returned result. Try it with any function or expression.

print() works as expected because when it is evaluated, it does its own printing before returning None, just how any other function does all of its own code before returning to the console whatever will be printed. You could try this, for example

```<code>>>> type(print('test'))
test
<class 'NoneType'>
</code>```

Here the console evaluates print('test'), which causes the first, manual print, and then automatically prints the return of the type call, resulting in the second line.

To answer your question, the difference between >>> print(a) and >>> a is that, in the first case, the console evaluates the print and has no return value to print, and in the second case, the console evaluates the expression and prints the result, which is a's value.

Body:
When i was going through the codes i found an interesting thing, if we initialize a variable in python shell, and we print that variable we get the value, if we use type the variable and press enter we get the same value. I could't figure out the reason behind it?? Can anyone help....

>a = 5
>print(a)
>5
>a
5

Body:
The Python console is a Read Evaluate Print Loop (REPL). It first reads your input, evaluates it, prints any output, and repeats until you exit. It's a very common way to interact with a language, and exists for many many languages.

Another example of what you've observed is

>>> 1+2
3

Here the console evaluates 1+2 and prints the returned result. Try it with any function or expression.

print() works as expected because when it is evaluated, it does its own printing before returning None, just how any other function does all of its own code before returning to the console whatever will be printed. You could try this, for example

>>> type(print('test'))
test
<class 'NoneType'>

Here the console evaluates print('test'), which causes the first, manual print, and then automatically prints the return of the type call, resulting in the second line.

To answer your question, the difference between >>> print(a) and >>> a is that, in the first case, the console evaluates the print and has no return value to print, and in the second case, the console evaluates the expression and prints the result, which is a's value.


答:
I don't know why pandas is allergic to computing mean() on a DataFrame, but here is a workaround:

>>> df = pd.DataFrame({'col1': [np.array([[1,3],[4,2]]), np.array([[1,1],[3,2]])],
...                    'col2': [np.array([[1,3],[3,3]]), np.array([[2,3],[3,1]])]})
>>> np.mean([df[col].mean() for col in df.columns], axis=0)
array([[1.25, 2.5 ],
       [3.25, 2.  ]])
```

<p>Doing <code>df.mean(axis=0).mean(axis=1)</code> throws an exception:</p>

```ValueError: If using all scalar values, you must pass an index
```

Title: Calculate mean numpy array in pandas DataFrame

Body:
My DataFrame consists of numpy arrays as:

                                                col1  \
0  [[[0.878617777607, 0.712102459231, 0.652479557...
1  [[[0.0815294305642, 0.793893471424, 0.24718091...
2  [[[0.611498467162, 0.880551635123, 0.949764900...

                                                col2  \
0  [[[0.390629506277, 0.0318899771374, 0.28308523...
1  [[[0.578710371447, 0.385239304185, 0.330119601...
2  [[[0.843661601339, 0.402833961663, 0.535083132...

                                                col3
0  [[[0.162446865578, 0.165619948624, 0.622459063...
1  [[[0.859362904741, 0.415994003318, 0.706308170...
2  [[[0.0559589731135, 0.307840549475, 0.80023067...

How can I calculate the mean numpy array in this DataFrame? The result should be a numpy array that represents the mean of all numpy arrays inside my DataFrame.

Code

import numpy as np
import pandas as pd

df = pd.DataFrame({'col1': [np.random.rand(4,4,4) for i in range(3)],
                   'col2': [np.random.rand(4,4,4) for i in range(3)],
                   'col3': [np.random.rand(4,4,4) for i in range(3)]})

Expected Output (For the code above): A numpy array that represents the mean of all numpy arrays

array([[[ 0.44091592,  0.81509111,  0.94968265,  0.60255149],
        [ 0.49263418,  0.69519008,  0.05023616,  0.67871942],
        [ 0.72771491,  0.9593636 ,  0.84673578,  0.43407915],
        [ 0.5884133 ,  0.63940507,  0.53364733,  0.51271129]],

       [[ 0.55612852,  0.58847166,  0.37781843,  0.7693527 ],
        [ 0.40610198,  0.05897461,  0.945253  ,  0.66332715],
        [ 0.74352406,  0.34969614,  0.50384616,  0.90582012],
        [ 0.38734233,  0.85533348,  0.94869219,  0.2863428 ]],

       [[ 0.81782769,  0.8856158 ,  0.68744406,  0.76579709],
        [ 0.05843924,  0.83090709,  0.99446694,  0.74937771],
        [ 0.11898717,  0.38715644,  0.50348724,  0.41903257],
        [ 0.21359555,  0.93407981,  0.20531033,  0.71017461]],

       [[ 0.88758803,  0.40433699,  0.02888434,  0.91075114],
        [ 0.84047283,  0.87119432,  0.14844659,  0.87643422],
        [ 0.06412383,  0.60458874,  0.47277274,  0.12969607],
        [ 0.31917517,  0.15647266,  0.89773897,  0.77962999]]])

I tried df.mean(), but it returns Series([], dtype: float64)

Also tried df.mean(axis=1).mean() and it returns NaN

UPDATE:

A much simpler example

df = pd.DataFrame({'col1': [np.array([[1,3],[4,2]]), np.array([[1,1],[3,2]])],
                   'col2': [np.array([[1,3],[3,3]]), np.array([[2,3],[3,1]])]})

DataFrame

Out[31]:
               col1              col2
0  [[1, 3], [4, 2]]  [[1, 3], [3, 3]]
1  [[1, 1], [3, 2]]  [[2, 3], [3, 1]]

Expected output:

In[42]: (df.iloc[0,0]+df.iloc[0,1]+df.iloc[1,0]+df.iloc[1,1])/4.

Out[42]:
array([[ 1.25,  2.5 ],
       [ 3.25,  2.  ]])

Body:
I don't know why pandas is allergic to computing mean() on a DataFrame, but here is a workaround:

>>> df = pd.DataFrame({'col1': [np.array([[1,3],[4,2]]), np.array([[1,1],[3,2]])],
...                    'col2': [np.array([[1,3],[3,3]]), np.array([[2,3],[3,1]])]})
>>> np.mean([df[col].mean() for col in df.columns], axis=0)
array([[1.25, 2.5 ],
       [3.25, 2.  ]])

Doing df.mean(axis=0).mean(axis=1) throws an exception:

ValueError: If using all scalar values, you must pass an index


问:
How do I made a relation in two entities if one entity has arrays data
I have two tables name users and requests in MYSQL database here is json example of each sequelize model which I need to map to my models:

user:

```<code>{
   "username": "",
   "profileImage": "",
   "deleted": false,
   "active": false,
   "id": 9,
   "uuid": "9a6d5a15-8e11-42aa-ac56-0bec272c9287",
   "firstName": "M",
   "lastName": "Aslam",
   "email": "hang@outlook.com",
   "isGuest": false
}
</code>```

and request

```<code>{
  "id": 5,
  "requestUUID": "ab966593-95e5-4fd8-b433-01b116e3edee",
  "socialLinks": [
    {
      "url": "https://synavos.com",
      "socialLinks": [
        {
          "platform": "facebook",
          "handle": "https://www.facebook.com/synavos/"
        },
        {
          "platform": "instagram",
          "handle": "https://www.instagram.com/synavosbusiness/"
        },
        {
          "platform": "youtube",
          "handle": "https://www.youtube.com/channel/UCrZxxAV_OiRb9N3wIe3N94w"
        }
      ]
    },
    {
      "url": "https://www.confiz.com/",
      "socialLinks": [
        {
          "platform": "facebook",
          "handle": "http://www.facebook.com/ConfizCareers"
        },
        {
          "platform": "youtube",
          "handle": "https://www.youtube.com/channel/UCG64lwoDIbwtkZK8E_s140A"
        }
      ]
    }
  ]
}
</code>```

while a user can have many requests while a request belongs to one user.

答: if the relation is one to mant (user can have many requests while a request belongs to one user) you can add to request a user_id field. then you can search all request of the user by SELECT * FROM requests where user_id = ?, [user.id], and if you want find the user of a specific request use SELECT ALL FROM users WHERE id = ?, [request.user_id]

Body:
I have two tables name users and requests in MYSQL database here is json example of each sequelize model which I need to map to my models:

user:

{
   "username": "",
   "profileImage": "",
   "deleted": false,
   "active": false,
   "id": 9,
   "uuid": "9a6d5a15-8e11-42aa-ac56-0bec272c9287",
   "firstName": "M",
   "lastName": "Aslam",
   "email": "hang@outlook.com",
   "isGuest": false
}

and request

{
  "id": 5,
  "requestUUID": "ab966593-95e5-4fd8-b433-01b116e3edee",
  "socialLinks": [
    {
      "url": "https://synavos.com",
      "socialLinks": [
        {
          "platform": "facebook",
          "handle": "https://www.facebook.com/synavos/"
        },
        {
          "platform": "instagram",
          "handle": "https://www.instagram.com/synavosbusiness/"
        },
        {
          "platform": "youtube",
          "handle": "https://www.youtube.com/channel/UCrZxxAV_OiRb9N3wIe3N94w"
        }
      ]
    },
    {
      "url": "https://www.confiz.com/",
      "socialLinks": [
        {
          "platform": "facebook",
          "handle": "http://www.facebook.com/ConfizCareers"
        },
        {
          "platform": "youtube",
          "handle": "https://www.youtube.com/channel/UCG64lwoDIbwtkZK8E_s140A"
        }
      ]
    }
  ]
}

while a user can have many requests while a request belongs to one user.


问:
Creating a list column in a dataframe based on values in another dataframe
I have two DataFrames:

df1:

```<code>       node        ids
0   ab          [978]
1   bc          [978, 121]
</code>```

df2:

```<code>       name        id
0   alpha          978
1   bravo          121
</code>```

I would like to add a new column called names in df1 where I get the list of names corresponding to ids column like this

```<code>   node            ids             names
0   ab            [978]            [alpha]
1   bc            [978, 121]       [alpha,bravo]
</code>```

Would apprreciate help.

答:
How about you try with this alternative solution?

```<code>df1 = (df1.reset_index()).merge(
        ((df1['ids'].explode().reset_index()).merge(
                df2,how='left',left_on='ids',right_on='id').groupby('index')['name','ids'].agg(
                        lambda x: list(x)).reset_index()),
                how='left',on='index').drop(
                        columns=['index','ids_y']).rename(
                                columns={'ids_x':'ids'})
print(df1)
</code>```

Output:

```<code>  node         ids            name
0   ab       [978]         [alpha]
1   bc  [978, 121]  [alpha, bravo]
</code>```

Body:
I have two DataFrames:

df1:

       node        ids
0   ab          [978]
1   bc          [978, 121]

df2:

       name        id
0   alpha          978
1   bravo          121

I would like to add a new column called names in df1 where I get the list of names corresponding to ids column like this

   node            ids             names
0   ab            [978]            [alpha]
1   bc            [978, 121]       [alpha,bravo]

Would apprreciate help.

Body:
How about you try with this alternative solution?

df1 = (df1.reset_index()).merge(
        ((df1['ids'].explode().reset_index()).merge(
                df2,how='left',left_on='ids',right_on='id').groupby('index')['name','ids'].agg(
                        lambda x: list(x)).reset_index()),
                how='left',on='index').drop(
                        columns=['index','ids_y']).rename(
                                columns={'ids_x':'ids'})
print(df1)

Output:

  node         ids            name
0   ab       [978]         [alpha]
1   bc  [978, 121]  [alpha, bravo]


问:
How can i code the Title of a UIButton to change across two View Controllers?
This is what i have but it does not work. I want the bbutton on vc3 to change title depending on what image is displayed on VC2</p>

```<code>@IBAction func buttonPressed(_ sender: UIButton) {

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if imageDisplayed == UIImage(named: "sad") && segue.identifier == "goToActive"{
        let vc3 = segue.destination as! ThirdViewController
            vc3.buttonTitle.titleLabel?.text = "no"
    }
else if imageDisplayed == UIImage(named: "happy") && segue.identifier == "goToActive" {
let vc3 = segue.destination as! ThirdViewController
    vc3.buttonTitle.titleLabel?.text = "happy"

} }
</code>```

答:
In the IBAction call the performSegue</p>

```<code>@IBAction func buttonPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "goToActive", sender: nil)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if imageDisplayed == UIImage(named: "sad") && segue.identifier == "goToActive"{
        let vc3 = segue.destination as! ThirdViewController
        vc3.buttonTitle.("no", for: .normal)
    }
    else if imageDisplayed == UIImage(named: "happy") && segue.identifier == "goToActive" {
        let vc3 = segue.destination as! ThirdViewController
        vc3.buttonTitle.("happy", for: .normal)
    }
}
</code>```

Body:
This is what i have but it does not work. I want the bbutton on vc3 to change title depending on what image is displayed on VC2

@IBAction func buttonPressed(_ sender: UIButton) {

    func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if imageDisplayed == UIImage(named: "sad") && segue.identifier == "goToActive"{
        let vc3 = segue.destination as! ThirdViewController
            vc3.buttonTitle.titleLabel?.text = "no"
    }
else if imageDisplayed == UIImage(named: "happy") && segue.identifier == "goToActive" {
let vc3 = segue.destination as! ThirdViewController
    vc3.buttonTitle.titleLabel?.text = "happy"

} }

Body:
In the IBAction call the performSegue

@IBAction func buttonPressed(_ sender: UIButton) {
    performSegue(withIdentifier: "goToActive", sender: nil)
}

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if imageDisplayed == UIImage(named: "sad") && segue.identifier == "goToActive"{
        let vc3 = segue.destination as! ThirdViewController
        vc3.buttonTitle.("no", for: .normal)
    }
    else if imageDisplayed == UIImage(named: "happy") && segue.identifier == "goToActive" {
        let vc3 = segue.destination as! ThirdViewController
        vc3.buttonTitle.("happy", for: .normal)
    }
}


问:
How to open owl ng datepicker via icon trigger
Right now I am using owl ng datepicker - as shown in the image(https://daniel-projects.firebaseapp.com/owlng/date-time-picker). But it is opening on input field click. I want it to be opened on datepicker icon click in my input box.

here is the html code for the same.

```<code> <input id="fromDate"
            name="fromDate"
            type="text"
            placeholder="From Date"
            class="form-control"
            tooltip="From Date"
            delay="500"
            triggers=""
            #fromDateToolTip="bs-tooltip"
            (mouseenter)="fromDateToolTip.show()"
            (mouseleave)="fromDateToolTip.hide()"
            [(ngModel)]="fromDatePicker"
            [owlDateTime]="dt1"
            [owlDateTimeTrigger]="dt1"
            readonly="readonly"
            (ngModelChange)="dateFilter()"
            (keydown.backspace)="clear()">
        <owl-date-time
            [pickerType]="'calendar'"
            [startAt]="startAtFromDate"
            [showSecondsTimer]="true"
            (afterPickerClosed)="setFromDateSelected($event,dt1)"
            (afterPickerOpen)="fromDatePickerOpen()"
             #dt1>
        </owl-date-time>
</code>```

答:
You can use the owlDateTimeTrigger property.
The date time picker that this trigger is associated with.

Try with this:

```<code><input id="fromDate" placeholder="From Date" ... [owlDateTime]="dt1 [owlDateTimeTrigger]="dt1">

<span [owlDateTimeTrigger]="dt1"><i class="fa fa-calendar"></i></span>

<owl-date-time [pickerType]="'calendar'" [startAt]="startAtFromDate [showSecondsTimer]="true" (afterPickerClosed)="setFromDateSelected($event,dt1)" (afterPickerOpen)="fromDatePickerOpen()" #dt1></owl-date-time>
</code>```

Body:
Right now I am using owl ng datepicker - as shown in the image(https://daniel-projects.firebaseapp.com/owlng/date-time-picker). But it is opening on input field click. I want it to be opened on datepicker icon click in my input box.

here is the html code for the same.

 <input id="fromDate"
            name="fromDate"
            type="text"
            placeholder="From Date"
            class="form-control"
            tooltip="From Date"
            delay="500"
            triggers=""
            #fromDateToolTip="bs-tooltip"
            (mouseenter)="fromDateToolTip.show()"
            (mouseleave)="fromDateToolTip.hide()"
            [(ngModel)]="fromDatePicker"
            [owlDateTime]="dt1"
            [owlDateTimeTrigger]="dt1"
            readonly="readonly"
            (ngModelChange)="dateFilter()"
            (keydown.backspace)="clear()">
        <owl-date-time
            [pickerType]="'calendar'"
            [startAt]="startAtFromDate"
            [showSecondsTimer]="true"
            (afterPickerClosed)="setFromDateSelected($event,dt1)"
            (afterPickerOpen)="fromDatePickerOpen()"
             #dt1>
        </owl-date-time>

Body:
You can use the owlDateTimeTrigger property.
The date time picker that this trigger is associated with.

Try with this:

<input id="fromDate" placeholder="From Date" ... [owlDateTime]="dt1 [owlDateTimeTrigger]="dt1">

<span [owlDateTimeTrigger]="dt1"><i class="fa fa-calendar"></i></span>

<owl-date-time [pickerType]="'calendar'" [startAt]="startAtFromDate [showSecondsTimer]="true" (afterPickerClosed)="setFromDateSelected($event,dt1)" (afterPickerOpen)="fromDatePickerOpen()" #dt1></owl-date-time>


问:
Print Matching line and one line before from the matched line
looking forward to print Matching line in a file on Linux host and one line before from the matched line included into one line.

Below is just the content from the log file:

```<code>[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)
  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info)
  smbldap_search_domain_info: Problem during LDAPsearch: Timed out
</code>```

What i have tried:

I have tried following with grep and sed which somehow works..

```<code>$ egrep -B 1 "failed|Timed" /var/log/samba/smbd.log.old |tr -d "\n" | sed "s/--/\n/g"

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info) smbldap_search_domain_info: Problem during LDAPsearch: Timed out
</code>```

This does not looks to be a cleaner solution, i'm looking forward some expert one lines, one liner is acceptable with awk, sed, grep or even python.

答:
Could you please try following tac + awk solution:

```<code>tac Input_file | awk '/failed/{found=1;val=$0;next} found && NF{print $0,val;val=found=""}'
</code>```

OR adding a non-one liner form of solution:

```<code>tac Input_file |
awk '
  /failed/{
    found=1
    val=$0
    next
  }
  found && NF{
    print $0,val
    val=found=""
  }
'
</code>```

Body:
looking forward to print Matching line in a file on Linux host and one line before from the matched line included into one line.

Below is just the content from the log file:

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)
  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info)
  smbldap_search_domain_info: Problem during LDAPsearch: Timed out

What i have tried:

I have tried following with grep and sed which somehow works..

$ egrep -B 1 "failed|Timed" /var/log/samba/smbd.log.old |tr -d "\n" | sed "s/--/\n/g"

[2020/02/18 08:25:21.229198,  1] ../source3/lib/smbldap.c:1206(get_cached_ldap_connect)  Connection to LDAP server failed for the 1 try!
[2020/02/18 08:25:21.229221,  2] ../source3/passdb/pdb_ldap_util.c:287(smbldap_search_domain_info) smbldap_search_domain_info: Problem during LDAPsearch: Timed out

This does not looks to be a cleaner solution, i'm looking forward some expert one lines, one liner is acceptable with awk, sed, grep or even python.

Body:
Could you please try following tac + awk solution:

tac Input_file | awk '/failed/{found=1;val=$0;next} found && NF{print $0,val;val=found=""}'

OR adding a non-one liner form of solution:

tac Input_file |
awk '
  /failed/{
    found=1
    val=$0
    next
  }
  found && NF{
    print $0,val
    val=found=""
  }
'


问:
Attempting to pass JSON body for deletion through AngularJS
I've currently got an endpoint that relies on a JSON body in order for deletion to happen. This is the following code:

```<code>if (toDeleteValue.length > 0) {
    var deleteRequest = [];

    for (var i = 0; i < toDeleteValue.length; i++) {
        var service = {};
        service.serviceId = $scope.siteServices[toDeleteService[i]].serviceId;
        toDeleteValue.push(service);
    }
    var deleteUrl = "api/class/" + $scope.targetEntity.serviceId+ "/student";

    await asyncDeleteUrl(deleteUrl, deleteRequest);

}

async function asyncDeleteUrl(deleteUrl, toBeDeleted) {
    return new Promise(function (resolve, reject) {
        $http.delete(deleteUrl, toBeDeleted)
        .then(function (response) {
            resolve(response);
        },
        function (errorResponse) {
            reject(errorResponse);
            $scope.statusDialog('Bad Modification Interrupted', errorResponse);
        });
   });
}
</code>```

I keep getting an error saying the required rest body is missing but I'm not sure why that would be the case. Any help would be appreciated, thank you.

答:
The second argument of the $http.delete method is a config object. Send data using the data property of that object:

```<code>function asyncDeleteUrl(deleteUrl, toBeDeleted) {
    var config = { data: toBeDeleted };
    return $http.delete(deleteUrl, config)
    .catch(function (errorResponse) {
         $scope.statusDialog('Bad Modification Interrupted', errorResponse);
         throw errorResponse;
    });
}
</code>```

For more information, see

AngularJS $http Service API Reference - delete

Body:
I've currently got an endpoint that relies on a JSON body in order for deletion to happen. This is the following code:

if (toDeleteValue.length > 0) {
    var deleteRequest = [];

    for (var i = 0; i < toDeleteValue.length; i++) {
        var service = {};
        service.serviceId = $scope.siteServices[toDeleteService[i]].serviceId;
        toDeleteValue.push(service);
    }
    var deleteUrl = "api/class/" + $scope.targetEntity.serviceId+ "/student";

    await asyncDeleteUrl(deleteUrl, deleteRequest);

}

async function asyncDeleteUrl(deleteUrl, toBeDeleted) {
    return new Promise(function (resolve, reject) {
        $http.delete(deleteUrl, toBeDeleted)
        .then(function (response) {
            resolve(response);
        },
        function (errorResponse) {
            reject(errorResponse);
            $scope.statusDialog('Bad Modification Interrupted', errorResponse);
        });
   });
}

I keep getting an error saying the required rest body is missing but I'm not sure why that would be the case. Any help would be appreciated, thank you.

Body:
The second argument of the $http.delete method is a config object. Send data using the data property of that object:

function asyncDeleteUrl(deleteUrl, toBeDeleted) {
    var config = { data: toBeDeleted };
    return $http.delete(deleteUrl, config)
    .catch(function (errorResponse) {
         $scope.statusDialog('Bad Modification Interrupted', errorResponse);
         throw errorResponse;
    });
}

For more information, see

AngularJS $http Service API Reference - delete


答:
Why not just put a unique constraint on it:</p>

```<code>ALTER TABLE <table_name>
 ADD CONSTRAINT <constraint_name>
 UNIQUE(<column_name>)
</code>```

Title: Table without a identity column but this column can't have repeated values

Body:
I'm creating a table that needs to have 2 columns. The first column can't be repeated. The thing is, I will insert the value of the first column. How do I create this column?
SQLServer 2005

Body:
Why not just put a unique constraint on it:

ALTER TABLE <table_name>
 ADD CONSTRAINT <constraint_name>
 UNIQUE(<column_name>)