问:
Search 'key' in nested object and display its value Javascript
I have nested object which holding details of DB server. from the nested object i have to search the key name called 'database' and I have display its value.

I found the solution by calling like this:

```<code>var database = (Object.entries((Object.entries(connection))[3]))[1][1].database;
</code>```

but some time position are getting changed. so could not able to get the value. so, how could i find the key in the nested object to find the value. plz help. thanks in advance.

```<code>    console.log("connection:",  Object.entries(connection) );
</code>```

Result

```<code>connection: [ [ '_events',
    [Object: null prototype] { end: [Function: _removeFromPool], error: [Function] } ],
  [ '_eventsCount', 2 ],
  [ 'config',
    ConnectionConfig {
      host: 'localhost',
      port: 336,
      localAddress: undefined,
      socketPath: undefined,
      user: 'user',
      password: 'password',
      database: 'dbname',
      connectTimeout: 10000,
      insecureAuth: false,
      supportBigNumbers: false,
      bigNumberStrings: false,
      dateStrings: false,
      debug: undefined,
      trace: true,
      stringifyObjects: false,
      timezone: 'local',
      flags: '',
      queryFormat: undefined,
      pool: [Pool],
      ssl: false,
      multipleStatements: true,
      typeCast: true,
      maxPacketSize: 0,
      charsetNumber: 33,
      clientFlags: 521167,
      protocol41: true } ],
  [ '_socket',
    Socket {
      connecting: false,
      _hadError: false,
      _handle: [TCP],
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      readable: true,
      _events: [Object],
      _eventsCount: 4,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: null,
      _server: null,
      timeout: 0,
      [Symbol(asyncId)]: 26,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]:
       Timeout {
         _called: false,
         _idleTimeout: -1,
         _idlePrev: null,
         _idleNext: null,
         _idleStart: 8926,
         _onTimeout: null,
         _timerArgs: undefined,
         _repeat: null,
         _destroyed: false,
         [Symbol(unrefed)]: true,
         [Symbol(asyncId)]: 29,
         [Symbol(triggerId)]: 25 },
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0 } ],
  [ '_protocol',
    Protocol {
      _events: [Object],
      _eventsCount: 6,
      _maxListeners: undefined,
      readable: true,
      writable: true,
      _config: [ConnectionConfig],
      _connection: [PoolConnection],
      _callback: null,
      _fatalError: null,
      _quitSequence: null,
      _handshake: true,
      _handshaked: true,
      _ended: false,
      _destroyed: false,
      _queue: [Array],
      _handshakeInitializationPacket: [HandshakeInitializationPacket],
      _parser: [Parser] } ],
  [ '_connectCalled', true ],
  [ 'state', 'authenticated' ],
  [ 'threadId', 2859 ],
  [ '_pool',
    Pool {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      config: [PoolConfig],
      _acquiringConnections: [],
      _allConnections: [Array],
      _freeConnections: [],
      _connectionQueue: [],
      _closed: false } ] ];
</code>```

and what is working now,

```<code>   var database = (Object.entries((Object.entries(connection))[3]))[1][1].database;

   console.log(database);

    output: dbname
</code>```

答:
let config = connection.filter(([key, value]) => key === "config")[0][1]
let database = config.database // dbname
```

Body:
I have nested object which holding details of DB server. from the nested object i have to search the key name called 'database' and I have display its value.

I found the solution by calling like this:

var database = (Object.entries((Object.entries(connection))[3]))[1][1].database;

but some time position are getting changed. so could not able to get the value. so, how could i find the key in the nested object to find the value. plz help. thanks in advance.

    console.log("connection:",  Object.entries(connection) );

Result

connection: [ [ '_events',
    [Object: null prototype] { end: [Function: _removeFromPool], error: [Function] } ],
  [ '_eventsCount', 2 ],
  [ 'config',
    ConnectionConfig {
      host: 'localhost',
      port: 336,
      localAddress: undefined,
      socketPath: undefined,
      user: 'user',
      password: 'password',
      database: 'dbname',
      connectTimeout: 10000,
      insecureAuth: false,
      supportBigNumbers: false,
      bigNumberStrings: false,
      dateStrings: false,
      debug: undefined,
      trace: true,
      stringifyObjects: false,
      timezone: 'local',
      flags: '',
      queryFormat: undefined,
      pool: [Pool],
      ssl: false,
      multipleStatements: true,
      typeCast: true,
      maxPacketSize: 0,
      charsetNumber: 33,
      clientFlags: 521167,
      protocol41: true } ],
  [ '_socket',
    Socket {
      connecting: false,
      _hadError: false,
      _handle: [TCP],
      _parent: null,
      _host: null,
      _readableState: [ReadableState],
      readable: true,
      _events: [Object],
      _eventsCount: 4,
      _maxListeners: undefined,
      _writableState: [WritableState],
      writable: true,
      allowHalfOpen: false,
      _sockname: null,
      _pendingData: null,
      _pendingEncoding: '',
      server: null,
      _server: null,
      timeout: 0,
      [Symbol(asyncId)]: 26,
      [Symbol(lastWriteQueueSize)]: 0,
      [Symbol(timeout)]:
       Timeout {
         _called: false,
         _idleTimeout: -1,
         _idlePrev: null,
         _idleNext: null,
         _idleStart: 8926,
         _onTimeout: null,
         _timerArgs: undefined,
         _repeat: null,
         _destroyed: false,
         [Symbol(unrefed)]: true,
         [Symbol(asyncId)]: 29,
         [Symbol(triggerId)]: 25 },
      [Symbol(kBytesRead)]: 0,
      [Symbol(kBytesWritten)]: 0 } ],
  [ '_protocol',
    Protocol {
      _events: [Object],
      _eventsCount: 6,
      _maxListeners: undefined,
      readable: true,
      writable: true,
      _config: [ConnectionConfig],
      _connection: [PoolConnection],
      _callback: null,
      _fatalError: null,
      _quitSequence: null,
      _handshake: true,
      _handshaked: true,
      _ended: false,
      _destroyed: false,
      _queue: [Array],
      _handshakeInitializationPacket: [HandshakeInitializationPacket],
      _parser: [Parser] } ],
  [ '_connectCalled', true ],
  [ 'state', 'authenticated' ],
  [ 'threadId', 2859 ],
  [ '_pool',
    Pool {
      _events: [Object: null prototype] {},
      _eventsCount: 0,
      _maxListeners: undefined,
      config: [PoolConfig],
      _acquiringConnections: [],
      _allConnections: [Array],
      _freeConnections: [],
      _connectionQueue: [],
      _closed: false } ] ];

and what is working now,

   var database = (Object.entries((Object.entries(connection))[3]))[1][1].database;

   console.log(database);

    output: dbname


来源: stackexchange

问:
How to shift each letter of the string by a given number of letters?
How can i shift each letter of a string by a given number of letters down or up in bash, without using a hardcoded dictionary?</p>

答:
If you want to rotate also the capitals you could use something like this:

```<code>cat data.txt | tr '[a-z]' '[n-za-m]' | tr '[A-Z]' '[N-ZA-M]'
</code>```

where data.txt has whatever you want to rotate.

ContentLicense: CC BY-SA 3.0

Body:
If you want to rotate also the capitals you could use something like this:

cat data.txt | tr '[a-z]' '[n-za-m]' | tr '[A-Z]' '[N-ZA-M]'

where data.txt has whatever you want to rotate.

ContentLicense: CC BY-SA 4.0


问:
console.log(this) following by console.log(this.props) don't show same common values
All is in the title.
I am using :"react": "16.8.6"

console.log(this) is showing good information

line following: console.log(this.props) is showing not expected data different from the one in console.log(this)

The plugin React dev tools gives me same good information as console.log(this)

Not the same "this" in both case? How is it possible?

答:
OK...the former code is not mine and comes from:

 https://github.com/EricLondon/Rails5-React-Token-Auth

I must say that code is working with old libraries

I did some refactoring because I don't trust "this" anymore from JS !!

Using Hooks and functions only code is much more readeable and 71 lines instead of 116 ! I am sold ....

New refactored code :

```<code>import React, { useState, useEffect } from 'react'
import { Container, Row, Col, Alert } from 'reactstrap'

const Api = require('../lib/Api.js')

export default function PageComponent(props)  {

  //states init n Hooks
  const [page, setPage] = useState({ id: props.match.params.id, content: ''})
  const [loading, setLoading] = useState(true)
  const [flashMessage, setFlashMessage] = useState({ message: undefined, style: 'success'})
  console.log(page.id)

  useEffect( () => {
    const pageId = props.match.params.id
    const getPage = () => {
      setLoading(true)
      setFlashMessage({
        message: undefined,
        style: 'success'
      })
      let jwt = props.appState.jwt
      console.log(jwt)

      Api.getPage(jwt, pageId).then(response => {
        if (response) {
          setPage(response)
          setLoading(false)
        }
        else {
          setPage({id:pageId, content: ''})
          setLoading(false)
          setFlashMessage({
            message: 'Access Denied.',
            style: 'danger'
          })
        }
      })
    }
    getPage()
  },[ props ])

  //rendering:

  if (loading) {
    return <div>Loading</div>
  }
  else {
    return (
      <Container>
        <Row>
          <Col xs="12" md="12">

            {flashMessage.message &&
              <Container>
                <Row>
                  <Col xs="12" md="12">
                    <Alert color={flashMessage.style}>
                      {flashMessage.message}
                    </Alert>
                  </Col>
                </Row>
              </Container>
            }

            <div>{page.content}</div>

          </Col>
        </Row>
      </Container>
    )}
}
</code>```

Body:
OK...the former code is not mine and comes from:

 https://github.com/EricLondon/Rails5-React-Token-Auth

I must say that code is working with old libraries

I did some refactoring because I don't trust "this" anymore from JS !!

Using Hooks and functions only code is much more readeable and 71 lines instead of 116 ! I am sold ....

New refactored code :

import React, { useState, useEffect } from 'react'
import { Container, Row, Col, Alert } from 'reactstrap'

const Api = require('../lib/Api.js')

export default function PageComponent(props)  {

  //states init n Hooks
  const [page, setPage] = useState({ id: props.match.params.id, content: ''})
  const [loading, setLoading] = useState(true)
  const [flashMessage, setFlashMessage] = useState({ message: undefined, style: 'success'})
  console.log(page.id)

  useEffect( () => {
    const pageId = props.match.params.id
    const getPage = () => {
      setLoading(true)
      setFlashMessage({
        message: undefined,
        style: 'success'
      })
      let jwt = props.appState.jwt
      console.log(jwt)

      Api.getPage(jwt, pageId).then(response => {
        if (response) {
          setPage(response)
          setLoading(false)
        }
        else {
          setPage({id:pageId, content: ''})
          setLoading(false)
          setFlashMessage({
            message: 'Access Denied.',
            style: 'danger'
          })
        }
      })
    }
    getPage()
  },[ props ])

  //rendering:

  if (loading) {
    return <div>Loading</div>
  }
  else {
    return (
      <Container>
        <Row>
          <Col xs="12" md="12">

            {flashMessage.message &&
              <Container>
                <Row>
                  <Col xs="12" md="12">
                    <Alert color={flashMessage.style}>
                      {flashMessage.message}
                    </Alert>
                  </Col>
                </Row>
              </Container>
            }

            <div>{page.content}</div>

          </Col>
        </Row>
      </Container>
    )}
}


问:
How to replace leading whitespace but retain multiple lines?
I'm trying to write a regex that removes all leading whitespace like this:

The following code does this, but also greedily removes multiple lines, like this:

How can I change the regex so that it removes preceding whitespace from each line, but leaves the multiple lines intact?

```<code>using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace test_regex_double_line
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> resources = new List<string>();

            resources.Add("Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.");

            foreach (var resource in resources)
            {
                var fixedResource = Regex.Replace(resource, @"^\s+", m => "", RegexOptions.Multiline);
                Console.WriteLine($"{resource}\n--------------\n{fixedResource}\n===========================");
            }
        }
    }
}
</code>```

答:
Let's try removing all whitespaces (\s) but \n and \r ones, i.e. [\s-[\r\n]]+ pattern

Code:

```<code>string resource =
  "Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.";

string fixedResource = Regex.Replace(resource, @"^[\s-[\r\n]]+", "", RegexOptions.Multiline);

Console.Write(fixedResource);
</code>```

Outcome:

```<code>Jim Smith
123 Main St.
Wherever, ST 99999

First line of information.

Second line of information.
</code>```

Edit: If you want to process a collection (say, List<string>) it's reasonable to define Regex outside the loop (Linq) etc. for performance reasons (see Panagiotis Kanavos comment):

```<code>List<string> resources = new List<string>() {
  "Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.",
};

Regex regex = new Regex(@"^[\s-[\r\n]]+", RegexOptions.Multiline);

List<string> fixedResources = resources
  .Select(resource => regex.Replace(resource, ""))
  .ToList();
</code>```

Body:
I'm trying to write a regex that removes all leading whitespace like this:

The following code does this, but also greedily removes multiple lines, like this:

How can I change the regex so that it removes preceding whitespace from each line, but leaves the multiple lines intact?

using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace test_regex_double_line
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> resources = new List<string>();

            resources.Add("Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.");

            foreach (var resource in resources)
            {
                var fixedResource = Regex.Replace(resource, @"^\s+", m => "", RegexOptions.Multiline);
                Console.WriteLine($"{resource}\n--------------\n{fixedResource}\n===========================");
            }
        }
    }
}

Body:
Let's try removing all whitespaces (\s) but \n and \r ones, i.e. [\s-[\r\n]]+ pattern

Code:

string resource =
  "Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.";

string fixedResource = Regex.Replace(resource, @"^[\s-[\r\n]]+", "", RegexOptions.Multiline);

Console.Write(fixedResource);

Outcome:

Jim Smith
123 Main St.
Wherever, ST 99999

First line of information.

Second line of information.

Edit: If you want to process a collection (say, List<string>) it's reasonable to define Regex outside the loop (Linq) etc. for performance reasons (see Panagiotis Kanavos comment):

List<string> resources = new List<string>() {
  "Jim Smith\n\t123 Main St.\n\t\tWherever, ST 99999\n\nFirst line of information.\n\nSecond line of information.",
};

Regex regex = new Regex(@"^[\s-[\r\n]]+", RegexOptions.Multiline);

List<string> fixedResources = resources
  .Select(resource => regex.Replace(resource, ""))
  .ToList();


问:
Why is the std::map insertion so slow compared to c# Dictionary insertion?
I am converting my C# library to C++. I am using a C# Dictionary variable across the app, and when I tried using std::map instead with string as key in both scenarios, I felt drastic difference in performance.

C# Dictionary took 0.022717 seconds with the below code. C++ map takes around 3 seconds.

C# Dictionary:

```<code>Stopwatch stopWatch = new Stopwatch();
Dictionary<string, int> dict = new Dictionary<string, int>();
stopWatch.Start();
for (int i = 0; i < 100000; i++)
{
    dict.Add(i.ToString(), i);
}
stopWatch.Stop();
var op = stopWatch.Elapsed.TotalSeconds.ToString();
</code>```

C++ map:

```<code>#include <iostream>
#include <map>
#include <string>
#include <chrono>

using namespace std;

int main()
{
    std::map<std::string, int> objMap;

    tm* timetr = new tm();
    time_t t1 = time(NULL);
    localtime_s(timetr, &t1);

    for (size_t i = 0; i < 100000; i++)
    {
        objMap.emplace(std::to_string(i), i);
    }

    tm* timetr2 = new tm();
    time_t t2 = time(NULL);
    localtime_s(timetr2, &t2);

    time_t tt = t2 - t1;
    cout << tt;

    string sss = "";
    cin >> sss;
}
</code>```

Why is there such a difference? What should be an equivalent alternative to achieve the same results?

答:
Add my two cents here.

C# dictionary is a HashMap, but C++ std::map is a Red-Black trees. HashMap performs better than tree. If you want to use HashMap in c++, please use std::unordered_map.

Not sure 100% this is the reason, but you can find it out after switch to std::unordered_map.

Body:
I am converting my C# library to C++. I am using a C# Dictionary variable across the app, and when I tried using std::map instead with string as key in both scenarios, I felt drastic difference in performance.

C# Dictionary took 0.022717 seconds with the below code. C++ map takes around 3 seconds.

C# Dictionary:

Stopwatch stopWatch = new Stopwatch();
Dictionary<string, int> dict = new Dictionary<string, int>();
stopWatch.Start();
for (int i = 0; i < 100000; i++)
{
    dict.Add(i.ToString(), i);
}
stopWatch.Stop();
var op = stopWatch.Elapsed.TotalSeconds.ToString();

C++ map:

#include <iostream>
#include <map>
#include <string>
#include <chrono>

using namespace std;

int main()
{
    std::map<std::string, int> objMap;

    tm* timetr = new tm();
    time_t t1 = time(NULL);
    localtime_s(timetr, &t1);

    for (size_t i = 0; i < 100000; i++)
    {
        objMap.emplace(std::to_string(i), i);
    }

    tm* timetr2 = new tm();
    time_t t2 = time(NULL);
    localtime_s(timetr2, &t2);

    time_t tt = t2 - t1;
    cout << tt;

    string sss = "";
    cin >> sss;
}

Why is there such a difference? What should be an equivalent alternative to achieve the same results?


问:
Split text in cells and create additional rows for the tokens
Let's suppose that I have the following in a DataFrame in pandas:

```<code>id  text
1   I am the first document and I am very happy.
2   Here is the second document and it likes playing tennis.
3   This is the third document and it looks very good today.
</code>```

and I want to split the text of each id in tokens of 3 words so I finally want to have the following:

```<code>id  text
1   I am the
1   first document and
1   I am very
1   happy
2   Here is the
2   second document and
2   it likes playing
2   tennis
3   This is the
3   third document and
3   it looks very
3   good today
</code>```

Keep in mind that my dataframe may also have other columns except for these two which should be simply copied at the new dataframe in the same way as id above.

What is the most efficient way to do this?

I reckon that the solution to my question is quite close to the solution given here: Tokenise text and create more rows for each row in dataframe.

This may help too: Python: Split String every n word in smaller Strings.

答:
A self contained solution, maybe a little slower:

```<code># Split every n words
n = 3

# incase id is not index yet
df.set_index('id', inplace=True)

new_df = df.text.str.split(' ', expand=True).stack().reset_index()

new_df = (new_df.groupby(['id', new_df.level_1//n])[0]
                .apply(lambda x: ' '.join(x))
                .reset_index(level=1, drop=True)
         )
</code>```

new_df is a series:

```<code>id
1               I am the
1     first document and
1              I am very
1                 happy.
2            Here is the
2    second document and
2       it likes playing
2                tennis.
3            This is the
3     third document and
3          it looks very
3            good today.
Name: 0, dtype: object
</code>```

Body:
Let's suppose that I have the following in a DataFrame in pandas:

id  text
1   I am the first document and I am very happy.
2   Here is the second document and it likes playing tennis.
3   This is the third document and it looks very good today.

and I want to split the text of each id in tokens of 3 words so I finally want to have the following:

id  text
1   I am the
1   first document and
1   I am very
1   happy
2   Here is the
2   second document and
2   it likes playing
2   tennis
3   This is the
3   third document and
3   it looks very
3   good today

Keep in mind that my dataframe may also have other columns except for these two which should be simply copied at the new dataframe in the same way as id above.

What is the most efficient way to do this?

I reckon that the solution to my question is quite close to the solution given here: Tokenise text and create more rows for each row in dataframe.

This may help too: Python: Split String every n word in smaller Strings.

Body:
A self contained solution, maybe a little slower:

# Split every n words
n = 3

# incase id is not index yet
df.set_index('id', inplace=True)

new_df = df.text.str.split(' ', expand=True).stack().reset_index()

new_df = (new_df.groupby(['id', new_df.level_1//n])[0]
                .apply(lambda x: ' '.join(x))
                .reset_index(level=1, drop=True)
         )

new_df is a series:

id
1               I am the
1     first document and
1              I am very
1                 happy.
2            Here is the
2    second document and
2       it likes playing
2                tennis.
3            This is the
3     third document and
3          it looks very
3            good today.
Name: 0, dtype: object


问:
How to get dependencies right for WorkManager and LocationServices?
I've been unable to get the dependencies right for an app that uses a worker for obtaining device locations. I suspect that I'm using the wrong location service with androidx, but I haven't found anything else. Here's my build.gradle:

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

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.exelor.laytrax"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha1'
    implementation 'androidx.work:work-runtime:2.1.0-alpha02'

    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation ('com.google.android.gms:play-services-location:16.0.0') {
        exclude group: 'com.android.support'
    }

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
</code>```

I'm excluding com.android.support to avoid build exceptions, such as

```<code>Duplicate class android.support.v4.os.ResultReceiver$MyRunnable found in modules classes.jar (androidx.core:core:1.1.0-beta01) and classes.jar (com.android.support:support-compat:26.1.0)
</code>```

At runtime in worker doWork():

```<code>fusedLocationClient = LocationServices.getFusedLocationProviderClient(context.applicationContext)
</code>```

throws this exception:

```<code>Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/util/ArraySet;
        at com.google.android.gms.common.api.internal.GoogleApiManager.<init>(Unknown Source:29)

</code>```

答:
My problem was not having a gradle.properties file containing</p>

```<code>android.enableJetifier=true
android.useAndroidX=true
</code>```

Body:
I've been unable to get the dependencies right for an app that uses a worker for obtaining device locations. I suspect that I'm using the wrong location service with androidx, but I haven't found anything else. Here's my build.gradle:

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

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.exelor.laytrax"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
    implementation 'androidx.core:core-ktx:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-alpha1'
    implementation 'androidx.work:work-runtime:2.1.0-alpha02'

    implementation 'com.google.android.material:material:1.1.0-alpha06'
    implementation ('com.google.android.gms:play-services-location:16.0.0') {
        exclude group: 'com.android.support'
    }

    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}

I'm excluding com.android.support to avoid build exceptions, such as

Duplicate class android.support.v4.os.ResultReceiver$MyRunnable found in modules classes.jar (androidx.core:core:1.1.0-beta01) and classes.jar (com.android.support:support-compat:26.1.0)

At runtime in worker doWork():

fusedLocationClient = LocationServices.getFusedLocationProviderClient(context.applicationContext)

throws this exception:

Caused by: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/support/v4/util/ArraySet;
        at com.google.android.gms.common.api.internal.GoogleApiManager.<init>(Unknown Source:29)

Body:
My problem was not having a gradle.properties file containing

android.enableJetifier=true
android.useAndroidX=true


问:
Constraint Failed - SQLite 3 - Android
I has the following table on my SQLite.

```<code>    StringBuilder createSql = new StringBuilder();
    createSql.append("create table LIBRARY ( ");
    createSql.append("id integer primary key, ");
    createSql.append("title text, ");
    createSql.append("author text, ");
    createSql.append("publisher text, ");
    createSql.append("thumbnailUrl text, ");
    createSql.append("formatType text, ");
    createSql.append("contentUrl text, ");
    createSql.append("publicationType text, ");
    createSql.append("favorite text, ");
    createSql.append("started text, ");
    createSql.append("normalizedTitle text, ");
    createSql.append("downloaded integer, ");
    createSql.append("wasDownloaded text ");
    createSql.append(");");
</code>```

And the following code to inser a value on that Table.

```<code>public void addLibrary(LibraryItem item) {
    ContentValues row = new ContentValues();
    row.put("title", item.getTitle());
    row.put("author", item.getAuthor());
    row.put("publisher", item.getPublisher());
    row.put("thumbnailUrl", item.getThumbnail());
    row.put("formatType", item.getFormat());
    row.put("contentUrl", item.getContentUrl());
    row.put("publicationType", item.getPublicationType());
    row.put("favorite", item.isFavorite() ? "YES" : "NO");
    row.put("id", item.getItemId());
    row.put("normalizedTitle", StringUtil.normalize(item.getTitle()));
    row.put("downloaded", Calendar.getInstance().getTimeInMillis());
    row.put("wasdownloaded", item.hasContent() ? "YES" : "NO");

    long id = db.insert("LIBRARY", null, row);
    add(id, item.getCategories());
}
</code>```

But when executing it, I got the following error.

```<code>Error inserting id=255 formatType=null author=null title=A Cabana contentUrl=/sdcard/Digital Editions/A Cabana.pdf publicationType=Livro thumbnailUrl=https://api-dls.homolog.abrildigital.com.br/images/22/android_cover_201103092041.jpg wasdownloaded=NO downloaded=1302631109426 normalizedTitle=A Cabana favorite=NO publisher=null
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed
</code>```

What's wrong?

答:
Your primary key isn't auto incrementing. Then you are inserting first row it is got a key, and then you are inserting another one it is got the same one but the primary key can't be same!

Then you are inserting an item with specified key i think the error means what item with this key is already exists.

Title: Constraint Failed - SQLite 3 - Android

Body:
I has the following table on my SQLite.

    StringBuilder createSql = new StringBuilder();
    createSql.append("create table LIBRARY ( ");
    createSql.append("id integer primary key, ");
    createSql.append("title text, ");
    createSql.append("author text, ");
    createSql.append("publisher text, ");
    createSql.append("thumbnailUrl text, ");
    createSql.append("formatType text, ");
    createSql.append("contentUrl text, ");
    createSql.append("publicationType text, ");
    createSql.append("favorite text, ");
    createSql.append("started text, ");
    createSql.append("normalizedTitle text, ");
    createSql.append("downloaded integer, ");
    createSql.append("wasDownloaded text ");
    createSql.append(");");

And the following code to inser a value on that Table.

public void addLibrary(LibraryItem item) {
    ContentValues row = new ContentValues();
    row.put("title", item.getTitle());
    row.put("author", item.getAuthor());
    row.put("publisher", item.getPublisher());
    row.put("thumbnailUrl", item.getThumbnail());
    row.put("formatType", item.getFormat());
    row.put("contentUrl", item.getContentUrl());
    row.put("publicationType", item.getPublicationType());
    row.put("favorite", item.isFavorite() ? "YES" : "NO");
    row.put("id", item.getItemId());
    row.put("normalizedTitle", StringUtil.normalize(item.getTitle()));
    row.put("downloaded", Calendar.getInstance().getTimeInMillis());
    row.put("wasdownloaded", item.hasContent() ? "YES" : "NO");

    long id = db.insert("LIBRARY", null, row);
    add(id, item.getCategories());
}

But when executing it, I got the following error.

Error inserting id=255 formatType=null author=null title=A Cabana contentUrl=/sdcard/Digital Editions/A Cabana.pdf publicationType=Livro thumbnailUrl=https://api-dls.homolog.abrildigital.com.br/images/22/android_cover_201103092041.jpg wasdownloaded=NO downloaded=1302631109426 normalizedTitle=A Cabana favorite=NO publisher=null
android.database.sqlite.SQLiteConstraintException: error code 19: constraint failed

What's wrong?


问:
How can I set a timezone in the datetimepicker?
I'm using this datetimepicker jquery plugin: http://xdsoft.net/jqplugins/datetimepicker/ and I didn't get it how to use timezone.
I saw the documentation, but I couldn't find it.

What I tried to do is something like that:

serviceDateTime.datetimepicker({
  lang: 'pt-BR',
  format: 'd/m/Y H:i',
  mask: true,
  step: 30,
  showTimezone: true,
  timezone: "-0200"
});
```

Any help?
Thanks in advance!

答:
This was difficult to find in the documentation, but you can pass O in format to tell the plugin to pass the GMT offset.

```<code>serviceDateTime.datetimepicker({
    lang: 'pt-BR',
    format: 'd/m/Y H:i O',
    mask: true,
    step: 30,
    showTimezone: true,
});
</code>```

The detective work was to find

https://xdsoft.net/jqplugins/datetimepicker/#use_other_date_parser

Then from there https://github.com/kartik-v/php-date-formatter#features

Then follow http://php.net/manual/en/function.date.php and search page for

```<code>"Difference to Greenwich time (GMT) in hours"
</code>```

Body:
I'm using this datetimepicker jquery plugin: http://xdsoft.net/jqplugins/datetimepicker/ and I didn't get it how to use timezone.
I saw the documentation, but I couldn't find it.

What I tried to do is something like that:

serviceDateTime.datetimepicker({
  lang: 'pt-BR',
  format: 'd/m/Y H:i',
  mask: true,
  step: 30,
  showTimezone: true,
  timezone: "-0200"
});

Any help?
Thanks in advance!

Body:
This was difficult to find in the documentation, but you can pass O in format to tell the plugin to pass the GMT offset.

serviceDateTime.datetimepicker({
    lang: 'pt-BR',
    format: 'd/m/Y H:i O',
    mask: true,
    step: 30,
    showTimezone: true,
});

The detective work was to find

https://xdsoft.net/jqplugins/datetimepicker/#use_other_date_parser

Then from there https://github.com/kartik-v/php-date-formatter#features

Then follow http://php.net/manual/en/function.date.php and search page for

"Difference to Greenwich time (GMT) in hours"


问:
How to print an array in php?
I need to print some cards in html, but I'll receive a php array with the number of days I'll have to print.
I've tried this, but isn't working.

```<code><div>
<div class="row" style="padding: 0px 30px">
    <?php foreach ($array as $num):?>
        <div class="col">
            <div class="card">
                <div class="card-header">
                    <h3 class="card-title"><?php $num ?></h3>
                </div>
                <div class="card-body">
                    <p class="card-text">With supporting text below as a natural lead-in to additional content.</p>
                </div>
            </div>
        </div>
    <?php endforeach ?>
</div>
</code>```

答:
Maybe one of these loops will help:</p>

```<code>foreach ($array as $mykey=>$myval) {
    echo $myval;
}

foreach ($array as $mykey=>$myval) {
    echo $array[$mykey];
}
</code>```

Title: How to print an array in php?

Body:
I need to print some cards in html, but I'll receive a php array with the number of days I'll have to print.
I've tried this, but isn't working.

    <?php foreach ($array as $num):?>

<?php $num ?>

With supporting text below as a natural lead-in to additional content.

    <?php endforeach ?>

Body:
Maybe one of these loops will help:

foreach ($array as $mykey=>$myval) {
    echo $myval;
}

foreach ($array as $mykey=>$myval) {
    echo $array[$mykey];
}


问:
How to deploy ASPNET Core site to Azure Linux Web App (no container)
I have a web app, and I've setup VSTS to create a package in build, and then deploy it using release management.

It puts all of the result in the wwwroot of the site if I look at it in ftp so I get:

/site/wwwroot/
                /wwroot
                /

This doesn't run and I get a 404 error.

If I use the URL and go say /wwwroot/images/ it returns it just fine.

The app is set to use .net core and I'm doing a self-contained package.

How do I get VSTS release to put the files in the right place and what is the right place ? I can't find any documentation on this anywhere. Everything is to do with Windows.

Also, what linux target should the dotnet application be set to for self-contained? I have it using ubuntu but I'm sure that's wrong and it's something else.

答:
I had a similar issue and I responded here. Essentially you need to have a startup command pointing to your DLL because Dev Ops deploys the package in a different way than VS.

Deploying .Net Core to Linux WebApps on Azure with DevOps


答:
To answer your direct question:

```<code>var db = ''
Object.entries(connection).foreach(item => {
  if (item[0] === 'config') db = item[1].database
})
</code>```

However, you should be able to access the value directly without turning the connection object in an array:

```<code>connection.config.database
</code>```

Title: Search 'key' in nested object and display its value Javascript

Body:
To answer your direct question:

var db = ''
Object.entries(connection).foreach(item => {
  if (item[0] === 'config') db = item[1].database
})

However, you should be able to access the value directly without turning the connection object in an array:

connection.config.database


问:
Flat JSON result from FOR JSON on SQL Server with joined query
I have a query that I need to send to SQL Server and use FOR JSON to get the result back as JSON. This query can include one or more JOINs.

The problem is that I want the result back as a simple flat json with each column as a column, but FOR JSON AUTO automatically nests it (Duh) and FOR JSON PATH is not appropriate because it use the dot-syntax but I want it to completely ignore any of that.

Of course, this could be done on the application server quite easily but I would highly prefer to do this in the database.

Query:

```<code>SELECT
    [Product].[ProductName] AS [Product.ProductName],
    [Category].[CategoryName] AS [Category.CategoryName],
    [Supplier].[CompanyName] AS [Supplier.CompanyName]
FROM
    [Products] AS [Product]
    INNER JOIN [Categories] AS [Category] ON [Category].[CategoryID] = [Product].[CategoryID]
    LEFT JOIN [Suppliers] AS [Supplier] ON [Supplier].[SupplierID] = [Product].[SupplierID]
FOR JSON AUTO
</code>```

Result (For 1):

```<code>[
    {
        "Product.ProductName":"Test prod",
        "Category":[
            {
                "Category.CategoryName":"Condiments!!!",
                "Supplier":[
                    {
                        "Supplier.CompanyName":"Exotic Liquids"
                    }
                ]
            }
        ]
    }
]
</code>```

Result I'm looking for:

```<code>[
    {
        "Product.ProductName":"Test Prod",
        "Category.CategoryName":"Condiments!!!",
        "Supplier.CompanyName":"Exotic Liquids"
    }
]
</code>```

答:
Another way to do it only in 1 to 1 relationship:</p>

```<code>SELECT
    [Product].[ProductName] AS [Product.ProductName],
    (SELECT [Category].[CategoryName] FROM [Categories] WHERE [Category].[CategoryID] = [Product].[CategoryID]) AS [Category.CategoryName],
    (SELECT [Supplier].[CompanyName] FROM [Suppliers] WHERE [Supplier].[SupplierID] = [Product].[SupplierID]) AS [Supplier.CompanyName]
FROM
    [Products] AS [Product]
FOR JSON AUTO
</code>```

Body:
I have a query that I need to send to SQL Server and use FOR JSON to get the result back as JSON. This query can include one or more JOINs.

The problem is that I want the result back as a simple flat json with each column as a column, but FOR JSON AUTO automatically nests it (Duh) and FOR JSON PATH is not appropriate because it use the dot-syntax but I want it to completely ignore any of that.

Of course, this could be done on the application server quite easily but I would highly prefer to do this in the database.

Query:

SELECT
    [Product].[ProductName] AS [Product.ProductName],
    [Category].[CategoryName] AS [Category.CategoryName],
    [Supplier].[CompanyName] AS [Supplier.CompanyName]
FROM
    [Products] AS [Product]
    INNER JOIN [Categories] AS [Category] ON [Category].[CategoryID] = [Product].[CategoryID]
    LEFT JOIN [Suppliers] AS [Supplier] ON [Supplier].[SupplierID] = [Product].[SupplierID]
FOR JSON AUTO

Result (For 1):

[
    {
        "Product.ProductName":"Test prod",
        "Category":[
            {
                "Category.CategoryName":"Condiments!!!",
                "Supplier":[
                    {
                        "Supplier.CompanyName":"Exotic Liquids"
                    }
                ]
            }
        ]
    }
]

Result I'm looking for:

[
    {
        "Product.ProductName":"Test Prod",
        "Category.CategoryName":"Condiments!!!",
        "Supplier.CompanyName":"Exotic Liquids"
    }
]

Body:
Another way to do it only in 1 to 1 relationship:

SELECT
    [Product].[ProductName] AS [Product.ProductName],
    (SELECT [Category].[CategoryName] FROM [Categories] WHERE [Category].[CategoryID] = [Product].[CategoryID]) AS [Category.CategoryName],
    (SELECT [Supplier].[CompanyName] FROM [Suppliers] WHERE [Supplier].[SupplierID] = [Product].[SupplierID]) AS [Supplier.CompanyName]
FROM
    [Products] AS [Product]
FOR JSON AUTO


问:
How to get a random sub-tensor from a tensor?
I want to get a random sub-tensor from a tensor, and the shape is fixed. For example,
I need to get the right tensor from the left tensor, and index is random for every row, just like this:

```<code>[[1 4 3]         [[3]     [[4]
 [3 2 1]  ----->  [2]  or  [1] (generate randomly)
 [0 3 4]]         [3]]     [0]]
</code>```

I tried tf.slice and tf.gather, It doesn't work. And I tried to write a code testcase like this：

```<code>import random
import tensorflow as tf

a = tf.convert_to_tensor([[[1, 4, 3]],
                          [[3, 2, 1]],
                          [[0, 3, 4]]])

T = a.get_shape().as_list()[0]

result_list = []

for i in range(T):
    idx = random.randint(0, 2)  # get a random idx
    result_list.append(a[i][0][idx])

y_hat = tf.reshape(tf.convert_to_tensor(result_list), shape=(T, 1))

with tf.Session() as sess:
    print(sess.run(y_hat))

    # y_hat: [[4]
    #         [1]
    #         [4]]

</code>```

In this testcase, It worked. But in a real environment, 'a'.shape=(None, 3), so

'T = a.get_shape().as_list()[0]' is not a int value, i can't iterate T by range(T).
For example:

```<code>import random
import tensorflow as tf

a = tf.placeholder(shape=(None, 3), dtype=tf.int32)

result_list = []
T = a.get_shape().as_list()[0]

for i in range(T):
    idx = random.randint(0, 2)  # get a random idx
    result_list.append(a[i][0][idx])

y_hat = tf.reshape(tf.convert_to_tensor(result_list), shape=(T, 1))

with tf.Session() as sess:

    a_instance = [[[1, 4, 3]],
                  [[3, 2, 1]],
                  [[0, 3, 4]]]

    print(sess.run(y_hat, feed_dict={a: a_instance}))

</code>```

In this case, it doesn't work. Who can tell me what should i do?

答:
This is how you can do that with tf.gather_nd:

```<code>import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    tf.random.set_random_seed(0)
    a = tf.constant([[1, 4, 3],
                     [3, 2, 1],
                     [0, 3, 4]])
    s = tf.shape(a)
    rows, cols = s[0], s[1]
    # Row indices
    ii = tf.expand_dims(tf.range(rows), 1)
    # Column indices
    jj = tf.random.uniform((rows, 1), 0, cols, dtype=ii.dtype)
    # Gather result
    result = tf.gather_nd(a, tf.stack([ii, jj], axis=-1))
    # Print some results
    print(sess.run(result))
    # [[3]
    #  [2]
    #  [4]]
    print(sess.run(result))
    # [[4]
    #  [1]
    #  [0]]
    print(sess.run(result))
    # [[3]
    #  [2]
    #  [0]]
</code>```

Body:
I want to get a random sub-tensor from a tensor, and the shape is fixed. For example,
I need to get the right tensor from the left tensor, and index is random for every row, just like this:

[[1 4 3]         [[3]     [[4]
 [3 2 1]  ----->  [2]  or  [1] (generate randomly)
 [0 3 4]]         [3]]     [0]]

I tried tf.slice and tf.gather, It doesn't work. And I tried to write a code testcase like this：

import random
import tensorflow as tf

a = tf.convert_to_tensor([[[1, 4, 3]],
                          [[3, 2, 1]],
                          [[0, 3, 4]]])

T = a.get_shape().as_list()[0]

result_list = []

for i in range(T):
    idx = random.randint(0, 2)  # get a random idx
    result_list.append(a[i][0][idx])

y_hat = tf.reshape(tf.convert_to_tensor(result_list), shape=(T, 1))

with tf.Session() as sess:
    print(sess.run(y_hat))

    # y_hat: [[4]
    #         [1]
    #         [4]]

In this testcase, It worked. But in a real environment, 'a'.shape=(None, 3), so

'T = a.get_shape().as_list()[0]' is not a int value, i can't iterate T by range(T).
For example:

import random
import tensorflow as tf

a = tf.placeholder(shape=(None, 3), dtype=tf.int32)

result_list = []
T = a.get_shape().as_list()[0]

for i in range(T):
    idx = random.randint(0, 2)  # get a random idx
    result_list.append(a[i][0][idx])

y_hat = tf.reshape(tf.convert_to_tensor(result_list), shape=(T, 1))

with tf.Session() as sess:

    a_instance = [[[1, 4, 3]],
                  [[3, 2, 1]],
                  [[0, 3, 4]]]

    print(sess.run(y_hat, feed_dict={a: a_instance}))

In this case, it doesn't work. Who can tell me what should i do?

Body:
This is how you can do that with tf.gather_nd:

import tensorflow as tf

with tf.Graph().as_default(), tf.Session() as sess:
    tf.random.set_random_seed(0)
    a = tf.constant([[1, 4, 3],
                     [3, 2, 1],
                     [0, 3, 4]])
    s = tf.shape(a)
    rows, cols = s[0], s[1]
    # Row indices
    ii = tf.expand_dims(tf.range(rows), 1)
    # Column indices
    jj = tf.random.uniform((rows, 1), 0, cols, dtype=ii.dtype)
    # Gather result
    result = tf.gather_nd(a, tf.stack([ii, jj], axis=-1))
    # Print some results
    print(sess.run(result))
    # [[3]
    #  [2]
    #  [4]]
    print(sess.run(result))
    # [[4]
    #  [1]
    #  [0]]
    print(sess.run(result))
    # [[3]
    #  [2]
    #  [0]]


问:
change the state of the child component
I am having a Parent Component and a child component

```<code>export default class CityPart extends Component {
    constructor(props)
    {
        super(props);
        this.state ={
            citylist: citylist
            selectedflag:1
        }

    }
    Clickme(idd){
     this.setstate({selectedflag:idd})
}
    render() {
        return (
        <div className="CityPartMain">
            {this.state.citylist.map((item)=>{
                return (
                <EachCity name ={item.name} key={item.id}
                id={item.id}
                selected={this.state.selected}
                Clickme ={this.Clickme}
                />
                )
            })}
        </div>
        );

    }
}
</code>```

```<code>export default class EachCity extends Component {
    render() {
        const {name,id,selected,Clickme} = this.props;
        return (
            <button
            onClick={this.Clickme(id)}
            className={selected===parseInt(id,10)?"selectedcity": "EachCityMain"}>
            <p>{name}</p>
            </button>
        );
    }
}
</code>```

whenever i click on the button i want that id should come to my parent component and it should get updated in the selectedflag of the parent state.

Thanks for help in advance.

答:
Your Clickme callback is getting called right away (remember, function() is called right then) and you are just storing the result of that call in the onClick handler. You're also using this. Try instead setting it as a callback using an anonymous arrow function.

```<code>export default class EachCity extends Component {
  render() {
    const { name, id, selected, Clickme} = this.props;
    return (
      <button
        onClick={() => Clickme(id)}
        className={selected===parseInt(id,10) ? "selectedcity" : "EachCityMain"}
      >
        <p>{name}</p>
      </button>
    );
  }
}
</code>```

If this is unclear to you and how and why it works, I can add a codesandbox example with more detail.

Title: change the state of the child component

Body:
I am having a Parent Component and a child component

export default class CityPart extends Component {
    constructor(props)
    {
        super(props);
        this.state ={
            citylist: citylist
            selectedflag:1
        }

    }
    Clickme(idd){
     this.setstate({selectedflag:idd})
}
    render() {
        return (

            {this.state.citylist.map((item)=>{
                return (
                <EachCity name ={item.name} key={item.id}
                id={item.id}
                selected={this.state.selected}
                Clickme ={this.Clickme}
                />
                )
            })}

        );

    }
}

export default class EachCity extends Component {
    render() {
        const {name,id,selected,Clickme} = this.props;
        return (
            <button
            onClick={this.Clickme(id)}
            className={selected===parseInt(id,10)?"selectedcity": "EachCityMain"}>

{name}

            </button>
        );
    }
}

whenever i click on the button i want that id should come to my parent component and it should get updated in the selectedflag of the parent state.

Thanks for help in advance.

Body:
Your Clickme callback is getting called right away (remember, function() is called right then) and you are just storing the result of that call in the onClick handler. You're also using this. Try instead setting it as a callback using an anonymous arrow function.

export default class EachCity extends Component {
  render() {
    const { name, id, selected, Clickme} = this.props;
    return (
      <button
        onClick={() => Clickme(id)}
        className={selected===parseInt(id,10) ? "selectedcity" : "EachCityMain"}
      >
        <p>{name}</p>
      </button>
    );
  }
}

If this is unclear to you and how and why it works, I can add a codesandbox example with more detail.


问:
Replace table column value using part of same column
I am updating a column in my table, replacing a column with part of its existing value:

```<code>Update Table_Name Set VarName '12345' where VarName = 'AA-BB-12345';
Update Table_Name Set VarName '99999' where VarName = 'XX-AR-99999';
...
</code>```

How to do this in a loop so it makes changes through entire Table_Name table pulling out the last element of VarName and using that to update? There are 500 rows to be updated in the table, too many to do single update lines, so I need a loop to accomplish this.

I think this is close:

```<code>Update Table_Name
set VarName = ( select regexp_substr(VarName, '[^-]+,1,3 ) from Table_Name );
</code>```

答:
You aren't that far off, but your subquery isn't correlated - there is no link between the value(s) the subquery finds and the row being updated, so you're probably getting an ORA-01427 error. But you don't need the subquery since you're updating the same row:

```<code>update table_name set varname = regexp_substr(varname, '[^-]+', 1, 3);
</code>```

You can do it without a regular expression too:

```<code>update table_name set varname = substr(varname, instr(varname, '-', -1) + 1);
</code>```

which also has the advantage of not nulling any rows which aren't the expected pattern. Even so, you could reduce unnecessary work by only updating values with dashes:

```<code>update table_name set varname = substr(varname, instr(varname, '-', -1) + 1)
where instr(varname, '-', -1) > 0;
</code>```

or

```<code>update table_name set varname = regexp_substr(varname, '[^-]+', 1, 3)
where regexp_substr(varname, '[^-]+', 1, 3) is not null;
</code>```

which will only update rows where the old value has (at least) three elements.

The two updates will behave differently if there are two elements - the first one with substr/instr will always take the last part after a dash if there are any; The second one with rexexp_substr will not update one with a single dash. You've only shown one fixed pattern so none of that may be relevant to you. At least, until you run the same update again against that data...

Body:
I am updating a column in my table, replacing a column with part of its existing value:

Update Table_Name Set VarName '12345' where VarName = 'AA-BB-12345';
Update Table_Name Set VarName '99999' where VarName = 'XX-AR-99999';
...

How to do this in a loop so it makes changes through entire Table_Name table pulling out the last element of VarName and using that to update? There are 500 rows to be updated in the table, too many to do single update lines, so I need a loop to accomplish this.

I think this is close:

Update Table_Name
set VarName = ( select regexp_substr(VarName, '[^-]+,1,3 ) from Table_Name );

Body:
You aren't that far off, but your subquery isn't correlated - there is no link between the value(s) the subquery finds and the row being updated, so you're probably getting an ORA-01427 error. But you don't need the subquery since you're updating the same row:

update table_name set varname = regexp_substr(varname, '[^-]+', 1, 3);

You can do it without a regular expression too:

update table_name set varname = substr(varname, instr(varname, '-', -1) + 1);

which also has the advantage of not nulling any rows which aren't the expected pattern. Even so, you could reduce unnecessary work by only updating values with dashes:

update table_name set varname = substr(varname, instr(varname, '-', -1) + 1)
where instr(varname, '-', -1) > 0;

or

update table_name set varname = regexp_substr(varname, '[^-]+', 1, 3)
where regexp_substr(varname, '[^-]+', 1, 3) is not null;

which will only update rows where the old value has (at least) three elements.

The two updates will behave differently if there are two elements - the first one with substr/instr will always take the last part after a dash if there are any; The second one with rexexp_substr will not update one with a single dash. You've only shown one fixed pattern so none of that may be relevant to you. At least, until you run the same update again against that data...


问:
Android Device Hardware Back Button is not working in ionic4 Apps
I am new to ionic framework. I have developed a simple app using ionic 4. It is working fine but Android Hardware back button is not working inside ionic app. Please suggest me how can i fix this issue. Thank you!</p>

答:
Here is the solution : in homepage.ts </p>

```<code> ionViewDidEnter(){
  this.subscription = this.platform.backButton.subscribe(()=>{
  navigator['app'].exitApp(); }); }

ionViewWillLeave(){
   this.subscription.unsubscribe();
 }
</code>```

Body:
Here is the solution : in homepage.ts

 ionViewDidEnter(){
  this.subscription = this.platform.backButton.subscribe(()=>{
  navigator['app'].exitApp(); }); }

ionViewWillLeave(){
   this.subscription.unsubscribe();
 }


问:
Stopping a conditional loop once the first TRUE condition is achieved
I am running the following loop in python. However, I want the loop to stop once it finds the first condition that is TRUE. I do not want the whole loop executed if for instance the first condition is true.I want the rest of the loops ignore.

So far i am using if, elif and else. Please do you have any suggestions on how i can better handle this.

See sample code below

```<code>if report_sheet1.cell(107,154).value == '': ot = report_sheet1.cell(i + 8, 134 + j * 3).value
elif report_sheet1.cell(107,141).value == '': ot = report_sheet1.cell(i + 8, 121 + j * 3).value
elif report_sheet1.cell(107,128).value == '': ot = report_sheet1.cell(i + 8, 108 + j * 3).value
elif report_sheet1.cell(107,115).value == '': ot = report_sheet1.cell(i + 8, 95 + j * 3).value
elif report_sheet1.cell(107,102).value == '': ot = report_sheet1.cell(i + 8, 82 + j * 3).value
else ot = report_sheet1.cell(i + 8, 69 + j * 3).value
</code>```

Currently, the whole loop runs and the FALSE overrides conditions that are TRUE

答:
If you want to stop the execution after the first condition is true, use the break statement after each test. The moment one condition is true, the program exists the entire structure.

I suggest to improve formatting of your code, as python cares about such a thing. I also suggest to keep practicing coding with the language, because loops are actually for and while, not if, elif or else.

Body:
I am running the following loop in python. However, I want the loop to stop once it finds the first condition that is TRUE. I do not want the whole loop executed if for instance the first condition is true.I want the rest of the loops ignore.

So far i am using if, elif and else. Please do you have any suggestions on how i can better handle this.

See sample code below

if report_sheet1.cell(107,154).value == '': ot = report_sheet1.cell(i + 8, 134 + j * 3).value
elif report_sheet1.cell(107,141).value == '': ot = report_sheet1.cell(i + 8, 121 + j * 3).value
elif report_sheet1.cell(107,128).value == '': ot = report_sheet1.cell(i + 8, 108 + j * 3).value
elif report_sheet1.cell(107,115).value == '': ot = report_sheet1.cell(i + 8, 95 + j * 3).value
elif report_sheet1.cell(107,102).value == '': ot = report_sheet1.cell(i + 8, 82 + j * 3).value
else ot = report_sheet1.cell(i + 8, 69 + j * 3).value

Currently, the whole loop runs and the FALSE overrides conditions that are TRUE


问:
Android Preventing Double Click On A Button
What is the best way to prevent double clicks on a button in Android?  </p>

答:
for any one using data-binding : </p>

```<code>@BindingAdapter("onClickWithDebounce")
fun onClickWithDebounce(view: View, listener: android.view.View.OnClickListener) {
    view.setClickWithDebounce {
        listener.onClick(view)
    }
}

object LastClickTimeSingleton {
    var lastClickTime: Long = 0
}

fun View.setClickWithDebounce(action: () -> Unit) {
    setOnClickListener(object : View.OnClickListener {

        override fun onClick(v: View) {
            if (SystemClock.elapsedRealtime() - LastClickTimeSingleton.lastClickTime < 500L) return
            else action()
            LastClickTimeSingleton.lastClickTime = SystemClock.elapsedRealtime()
        }
    })
}

<androidx.appcompat.widget.AppCompatButton
                    ..
  android:text="@string/signup_signin"
  app:onClickWithDebounce="@{() -> viewModel.onSignUpClicked()}"
                   ... />
</code>```

Body:
for any one using data-binding :

@BindingAdapter("onClickWithDebounce")
fun onClickWithDebounce(view: View, listener: android.view.View.OnClickListener) {
    view.setClickWithDebounce {
        listener.onClick(view)
    }
}

object LastClickTimeSingleton {
    var lastClickTime: Long = 0
}

fun View.setClickWithDebounce(action: () -> Unit) {
    setOnClickListener(object : View.OnClickListener {

        override fun onClick(v: View) {
            if (SystemClock.elapsedRealtime() - LastClickTimeSingleton.lastClickTime < 500L) return
            else action()
            LastClickTimeSingleton.lastClickTime = SystemClock.elapsedRealtime()
        }
    })
}

<androidx.appcompat.widget.AppCompatButton
                    ..
  android:text="@string/signup_signin"
  app:onClickWithDebounce="@{() -> viewModel.onSignUpClicked()}"
                   ... />


问:
ISSUE: Kendo tooltip with custom angularjs directive and kendoConfirm
My current situation:
kendo tooltip works fine alone.
my new custom angularjs directive with kendoConfirm works fine alone.

but once i try to use them both together on an element, then only the kendo tooltip stops working.

```<code>   <button type="button" title="Disable Item" k-confirm-disable k-confirm-disable-title="'Confirm Disable'" k-confirm-disable-msg="'Are you sure you want to disable this item?'" ng-click="disable(dataItem.id)"  class="btn btn-danger" kendo-tooltip k-content="'Disable Item'" k-options="kendoTooltipOptions">

 $scope.kendoTooltipOptions = {
showAfter: 600,     //time for tooltip appear
position : 'top',
width    : 100
}
</code>```

kendo tooltip only works when I remove the custom angular directive from the element.

```<code>function kConfirmDisable($compile){
return {
    restrict: 'A',
    scope: {
        kConfirmDisableTitle:   '@',
        kConfirmDisableMsg: '@'
    },
    link: function(scope, element, attrs){

        var clickHandlers = $._data(element[0]).events.click;

        clickHandlers.reverse(); //reverse the click event handlers list

        var onClick = function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();
            if(!scope.kConfirmDisableTitle) {
                scope.kConfirmDisableTitle = "Confirm";
            }

            if(!scope.kConfirmDisableMsg) {
                scope.kConfirmDisableMsg = "Are you sure?";
            }

            angular.element("<div></div>").kendoConfirm({
                title: scope.kConfirmDisableTitle.replace(/['"]+/g, ''),
                content: scope.kConfirmDisableMsg.replace(/['"]+/g, ''),
                buttonLayout: "normal",
                visible: false,
                actions: [
                     {
                        text: "No",
                        Primary: false,
                        action: function(){

                            evt.preventDefault();
                            evt.stopImmediatePropagation();
                        }
                    },
                    {
                        text: "Yes",
                        Primary: true,
                        action: function(){

                            element.unbind(this);
                            setTimeout(function() {
                                element.unbind("click", onClick);
                                element.click();
                                evt.preventDefault();
                                evt.stopImmediatePropagation();
                                element.on("click", onClick);
                            },0);
                        }
                    },

                ],
                animation: {
                    open:{
                        effects: "zoom:in",
                        duration: 250
                    },
                    close:{
                        effects: "fade:out",
                        duration: 250
                    }
                },
                open: function(e) {
                   $("html, body").css("overflow", "hidden");
                },
                close: function() {
                    $("html, body").css("overflow", "visible");
                }
            }).data("kendoConfirm").open().result;
        };
        element.on("click", onClick);

        clickHandlers.reverse();
    }
}
}
</code>```

答:
my solution is I removed the "k-" from the "k-confirm-disable" directive and it worked.
i think its because kendo has "k-" reserved.</p>

Body:
My current situation:
kendo tooltip works fine alone.
my new custom angularjs directive with kendoConfirm works fine alone.

but once i try to use them both together on an element, then only the kendo tooltip stops working.

   <button type="button" title="Disable Item" k-confirm-disable k-confirm-disable-title="'Confirm Disable'" k-confirm-disable-msg="'Are you sure you want to disable this item?'" ng-click="disable(dataItem.id)"  class="btn btn-danger" kendo-tooltip k-content="'Disable Item'" k-options="kendoTooltipOptions">

 $scope.kendoTooltipOptions = {
showAfter: 600,     //time for tooltip appear
position : 'top',
width    : 100
}

kendo tooltip only works when I remove the custom angular directive from the element.

function kConfirmDisable($compile){
return {
    restrict: 'A',
    scope: {
        kConfirmDisableTitle:   '@',
        kConfirmDisableMsg: '@'
    },
    link: function(scope, element, attrs){

        var clickHandlers = $._data(element[0]).events.click;

        clickHandlers.reverse(); //reverse the click event handlers list

        var onClick = function(evt) {
            evt.preventDefault();
            evt.stopImmediatePropagation();
            if(!scope.kConfirmDisableTitle) {
                scope.kConfirmDisableTitle = "Confirm";
            }

            if(!scope.kConfirmDisableMsg) {
                scope.kConfirmDisableMsg = "Are you sure?";
            }

            angular.element("

").kendoConfirm({
                title: scope.kConfirmDisableTitle.replace(/['"]+/g, ''),
                content: scope.kConfirmDisableMsg.replace(/['"]+/g, ''),
                buttonLayout: "normal",
                visible: false,
                actions: [
                     {
                        text: "No",
                        Primary: false,
                        action: function(){

                            evt.preventDefault();
                            evt.stopImmediatePropagation();
                        }
                    },
                    {
                        text: "Yes",
                        Primary: true,
                        action: function(){

                            element.unbind(this);
                            setTimeout(function() {
                                element.unbind("click", onClick);
                                element.click();
                                evt.preventDefault();
                                evt.stopImmediatePropagation();
                                element.on("click", onClick);
                            },0);
                        }
                    },

                ],
                animation: {
                    open:{
                        effects: "zoom:in",
                        duration: 250
                    },
                    close:{
                        effects: "fade:out",
                        duration: 250
                    }
                },
                open: function(e) {
                   $("html, body").css("overflow", "hidden");
                },
                close: function() {
                    $("html, body").css("overflow", "visible");
                }
            }).data("kendoConfirm").open().result;
        };
        element.on("click", onClick);

        clickHandlers.reverse();
    }
}
}


问:
Is it possible to view secret variable declared in angular in browser, after build and run?
I want to use an a decryption algorithm on the data I receive through REST-API, for that I am storing the secret-key in angular component ts file.

I want to know that after I build and deploy the code. Will my secret key be visible somewhere in the browser, because the built code is pure javascript which is fetched by server.

I am using crypto-js library for decryption of data.

```<code>var secret_key = "super-secret";

CryptoJS.AES.decrypt(ciphertext, secret_key)
</code>```

答:
Yes it will be visible to individuals looking for it.  You should never store secrets in any client-side code.

The key should be acquired from a server once the client authenticates.

Good post on key storage options
https://pomcor.com/2017/06/02/keys-in-browser/

Section 5.2 of WebCryptoAPI discusses a bit about key storage

https://www.w3.org/TR/WebCryptoAPI/

Body:
I want to use an a decryption algorithm on the data I receive through REST-API, for that I am storing the secret-key in angular component ts file.

I want to know that after I build and deploy the code. Will my secret key be visible somewhere in the browser, because the built code is pure javascript which is fetched by server.

I am using crypto-js library for decryption of data.

var secret_key = "super-secret";

CryptoJS.AES.decrypt(ciphertext, secret_key)


问:
BoolToVisibilityConverter not firing in UWP
I am completely stumped by this.  I have a UserControl in UWP/C# that contains several Border objects which are meant to be doors to rooms.  I have 4 DependencyProperties (one for each direction - N,S,E,W), with a type of bool, each of them connected to a BoolToVisibilityConverter.  The concept is that the doors can be toogled between Visible and Collapsed by setting the HasDirectionDoor Property either true or false.  As far as I can tell, everything is set up correctly, but it simply doesn't work.  If I place a breakpoint on the Convert and ConvertBack methods of the BoolToVisConverter, those breakpoints never fire, meaning that it's not even reaching the Converter.  Yet looking over what I've written, and comparing it to what I've found in various guides, everything looks identical and correct.  Could somebody please look at the code, I'm sure it's something simple I'm missing, but I just can't see it.

BoolToVis:

```<code>namespace Crawler.Converters
{
    public class BoolToVisibilityConverter : IValueConverter
    {
        public BoolToVisibilityConverter()
        {

        }

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            //return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;

            if (value is bool && (bool)value)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return (value is Visibility && (Visibility)value == Visibility.Visible);
        }
    }
}
</code>```

UserControl XAML:

```<code><UserControl
    x:Class="Crawler.DungeonRoom"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Crawler"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:BooleanToVisibility="using:Crawler.Converters"
    mc:Ignorable="d" Background="White" Height="110" Width="110"
    d:DesignHeight="110" d:DesignWidth="110">
    <UserControl.Resources>
        <BooleanToVisibility:BoolToVisibilityConverter x:Key="BoolToVis" />
    </UserControl.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="5" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="5" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="5" />
        </Grid.RowDefinitions>
        <Border Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="4" Grid.RowSpan="4" Background="White" />
        <Border x:Name="westDoor" Grid.Column="0" Grid.Row="2" Grid.RowSpan="2" Background="SaddleBrown" Visibility="{Binding HasWestDoor, Converter={StaticResource ResourceKey=BoolToVis}}" />
        <Border x:Name="northDoor" Grid.Column="2" Grid.Row="0" Grid.ColumnSpan="2" Background="SaddleBrown" />
        <Border x:Name="eastDoor" Grid.Column="5" Grid.Row="2" Grid.RowSpan="2" Background="SaddleBrown" />
        <Border x:Name="southDoor" Grid.Column="2" Grid.Row="5" Grid.ColumnSpan="2" Background="SaddleBrown" />
        <Border x:Name="roomIcon" Grid.Column="4" Grid.Row="1" BorderBrush="DimGray" BorderThickness="1 0 0 1">
            <Image Source="Assets\MapTiles\Camp.png" />
        </Border>
    </Grid>
</UserControl>
</code>```

UserControl C#:

```<code>using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Crawler
{
    public sealed partial class DungeonRoom : UserControl
    {
        public static readonly DependencyProperty HasWestDoorProperty =
            DependencyProperty.Register("HasWestDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty HasNorthDoorProperty =
            DependencyProperty.Register("HasNorthDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty HasEastDoorProperty =
            DependencyProperty.Register("HasEastDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty HasSouthDoorProperty =
            DependencyProperty.Register("HasSouthDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty TypeProperty =
            DependencyProperty.Register("Type", typeof(RoomType), typeof(DungeonRoom), new PropertyMetadata(0));

        public bool HasWestDoor
        {
            get { return (bool)GetValue(HasWestDoorProperty); }
            set { SetValue(HasWestDoorProperty, value); }
        }
        public bool HasNorthDoor
        {
            get { return (bool)GetValue(HasNorthDoorProperty); }
            set { SetValue(HasNorthDoorProperty, value); }
        }

        public bool HasEastDoor
        {
            get { return (bool)GetValue(HasEastDoorProperty); }
            set { SetValue(HasEastDoorProperty, value); }
        }

        public bool HasSouthDoor
        {
            get { return (bool)GetValue(HasSouthDoorProperty); }
            set { SetValue(HasSouthDoorProperty, value); }
        }

        public RoomType Type
        {
            get { return (RoomType)GetValue(TypeProperty); }
            set { SetValue(TypeProperty, value); }
        }

        public DungeonRoom()
        {
            this.InitializeComponent();
        }
    }
}
</code>```

答:
Your binding probably fails because you haven't set the source for it or set the DataContext of the Border to the UserControl where the source property is defined.

Try to give the UserControl a Name and bind to it using the ElementName property:

```<code><UserControl .... Name="uc">
...
    <Border x:Name="westDoor" ... Visibility="{Binding HasWestDoor, ElementName=uc,
         Converter={StaticResource ResourceKey=BoolToVis}}" />
</code>```

Or use a compiled binding:

```<code><Border x:Name="westDoor" ... Visibility="{x:Bind HasWestDoor, Mode=OneWay,
     Converter={StaticResource ResourceKey=BoolToVis}}" />
</code>```

This should give you a compilation error if the binding fails.

Body:
I am completely stumped by this.  I have a UserControl in UWP/C# that contains several Border objects which are meant to be doors to rooms.  I have 4 DependencyProperties (one for each direction - N,S,E,W), with a type of bool, each of them connected to a BoolToVisibilityConverter.  The concept is that the doors can be toogled between Visible and Collapsed by setting the HasDirectionDoor Property either true or false.  As far as I can tell, everything is set up correctly, but it simply doesn't work.  If I place a breakpoint on the Convert and ConvertBack methods of the BoolToVisConverter, those breakpoints never fire, meaning that it's not even reaching the Converter.  Yet looking over what I've written, and comparing it to what I've found in various guides, everything looks identical and correct.  Could somebody please look at the code, I'm sure it's something simple I'm missing, but I just can't see it.

BoolToVis:

namespace Crawler.Converters
{
    public class BoolToVisibilityConverter : IValueConverter
    {
        public BoolToVisibilityConverter()
        {

        }

        public object Convert(object value, Type targetType, object parameter, string language)
        {
            //return (value is bool && (bool)value) ? Visibility.Visible : Visibility.Collapsed;

            if (value is bool && (bool)value)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            return (value is Visibility && (Visibility)value == Visibility.Visible);
        }
    }
}

UserControl XAML:

<UserControl
    x:Class="Crawler.DungeonRoom"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Crawler"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:BooleanToVisibility="using:Crawler.Converters"
    mc:Ignorable="d" Background="White" Height="110" Width="110"
    d:DesignHeight="110" d:DesignWidth="110">
    <UserControl.Resources>
        <BooleanToVisibility:BoolToVisibilityConverter x:Key="BoolToVis" />
    </UserControl.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="5" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="25" />
            <ColumnDefinition Width="5" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="5" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="25" />
            <RowDefinition Height="5" />
        </Grid.RowDefinitions>
        <Border Grid.Column="1" Grid.Row="1" Grid.ColumnSpan="4" Grid.RowSpan="4" Background="White" />
        <Border x:Name="westDoor" Grid.Column="0" Grid.Row="2" Grid.RowSpan="2" Background="SaddleBrown" Visibility="{Binding HasWestDoor, Converter={StaticResource ResourceKey=BoolToVis}}" />
        <Border x:Name="northDoor" Grid.Column="2" Grid.Row="0" Grid.ColumnSpan="2" Background="SaddleBrown" />
        <Border x:Name="eastDoor" Grid.Column="5" Grid.Row="2" Grid.RowSpan="2" Background="SaddleBrown" />
        <Border x:Name="southDoor" Grid.Column="2" Grid.Row="5" Grid.ColumnSpan="2" Background="SaddleBrown" />
        <Border x:Name="roomIcon" Grid.Column="4" Grid.Row="1" BorderBrush="DimGray" BorderThickness="1 0 0 1">
            <Image Source="Assets\MapTiles\Camp.png" />
        </Border>
    </Grid>
</UserControl>

UserControl C#:

using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace Crawler
{
    public sealed partial class DungeonRoom : UserControl
    {
        public static readonly DependencyProperty HasWestDoorProperty =
            DependencyProperty.Register("HasWestDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty HasNorthDoorProperty =
            DependencyProperty.Register("HasNorthDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty HasEastDoorProperty =
            DependencyProperty.Register("HasEastDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty HasSouthDoorProperty =
            DependencyProperty.Register("HasSouthDoor", typeof(Boolean), typeof(DungeonRoom), new PropertyMetadata(false));

        public static readonly DependencyProperty TypeProperty =
            DependencyProperty.Register("Type", typeof(RoomType), typeof(DungeonRoom), new PropertyMetadata(0));

        public bool HasWestDoor
        {
            get { return (bool)GetValue(HasWestDoorProperty); }
            set { SetValue(HasWestDoorProperty, value); }
        }
        public bool HasNorthDoor
        {
            get { return (bool)GetValue(HasNorthDoorProperty); }
            set { SetValue(HasNorthDoorProperty, value); }
        }

        public bool HasEastDoor
        {
            get { return (bool)GetValue(HasEastDoorProperty); }
            set { SetValue(HasEastDoorProperty, value); }
        }

        public bool HasSouthDoor
        {
            get { return (bool)GetValue(HasSouthDoorProperty); }
            set { SetValue(HasSouthDoorProperty, value); }
        }

        public RoomType Type
        {
            get { return (RoomType)GetValue(TypeProperty); }
            set { SetValue(TypeProperty, value); }
        }

        public DungeonRoom()
        {
            this.InitializeComponent();
        }
    }
}

Body:
Your binding probably fails because you haven't set the source for it or set the DataContext of the Border to the UserControl where the source property is defined.

Try to give the UserControl a Name and bind to it using the ElementName property:

<UserControl .... Name="uc">
...
    <Border x:Name="westDoor" ... Visibility="{Binding HasWestDoor, ElementName=uc,
         Converter={StaticResource ResourceKey=BoolToVis}}" />

Or use a compiled binding:

<Border x:Name="westDoor" ... Visibility="{x:Bind HasWestDoor, Mode=OneWay,
     Converter={StaticResource ResourceKey=BoolToVis}}" />

This should give you a compilation error if the binding fails.


问:
CSVHELPER Conditionally ignore writing fields when values null or empty
Im currently writing a flattened DTO object to CSV using the csvhelper's csvwriter. Is there a way to conditionally ignore certain fields if they havent yet been initialised or are null in the mapper ? I see the ignore flag takes a boolean , but how would i get access to the field in question to test for this.

Apologies if this has been answered elsewhere but have searched both teh github issues aswell as stackoverflow.

答:
I was a little bit confused by the question, because Ignore is all or nothing.  You can't ignore a field line by line.  You either include the field or you don't. You could ignore a field if say all of the records had a null or empty value for a particular member variable.

public static void Main(string[] args)
{
    var records = new List<Foo> { new Foo { Id = 1, Name = "" }, new Foo { Id = 2 } };

    using (var csv = new CsvWriter(Console.Out))
    {
        var shouldIgnoreName = records.All(foo => string.IsNullOrEmpty(foo.Name));

        var classMap = new DefaultClassMap<Foo>();
        classMap.AutoMap();
        classMap.Map(m => m.Name).Ignore(shouldIgnoreName);

        csv.Configuration.RegisterClassMap(classMap);
        csv.WriteRecords(records);
    }

    Console.ReadKey();
}

public class Foo
{
    public int Id { get; set; }
    public string Name { get; set; }
}
```


答: The best practice here is to execute encrypt/decrypt operation on backend (server-side) and get the decrypted value from you API </p>

Title: Is it possible to view secret variable declared in angular in browser, after build and run?


问:
Assert the text present in a disable text box using selenium webdriver
I have the following text field and is disabled. It will have a text value say 'City1'. I need to verify 'City1' is displayed in this text box. .getAttribute('value') and .getText is not working.   </p>

```<code> <input type="text" autofocus="" disabled="disabled" ng-model="siteDetails.streetAddr" class="form-control ic-filterdropdown ng-pristine ng-valid">
</code>```

答:
```<code>attribut = element.getAttribute(nom_attribut)
</code>```

https://developer.mozilla.org/fr/docs/Web/API/Element/getAttribute

Body:
I have the following text field and is disabled. It will have a text value say 'City1'. I need to verify 'City1' is displayed in this text box. .getAttribute('value') and .getText is not working.

 <input type="text" autofocus="" disabled="disabled" ng-model="siteDetails.streetAddr" class="form-control ic-filterdropdown ng-pristine ng-valid">

Body:
attribut = element.getAttribute(nom_attribut)

https://developer.mozilla.org/fr/docs/Web/API/Element/getAttribute


问:
Why Intel TBB didn't provide conditional variable like boost?
Like conditional signal mechanism, I want one task to wait until some signal is received or some variable becomes true.
Boost lib provide this mechanism, but TBB didn't.

How to implement this case in TBB?

答:
Are you using a very old TBB ?

Having tasks "wait" is something TBB hasn't handled well in the past, but the current TBB news contains this:

ISO C++ thread class – A thin portable
  wrapper around OS threads. It's a
  close approximation of the ISO C++
  200x class thread (Section 30.2 of
  http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2691.pdf).
  Now TBB lets you choose which is best,
  task-based versus thread-based, for
  your situation. Threads are typically
  better than tasks when the "work" is
  really more waiting than computation,
  such as for:

```<code>* GUI, I/O or network interface threads.
* Threads that need to wait on external events.
* Programs that previously needed to use both native threads and Intel® TBB tasks.
</code>```

ie they're admitting TBB's task parallelism isn't a universal panacea and you need something more like the "traditional" threading model sometimes for I/O.  And indeed if you check the latest reference manual you'll find TBB does now contain condition variables!  (See section 8.4)

Body:
Are you using a very old TBB ?

Having tasks "wait" is something TBB hasn't handled well in the past, but the current TBB news contains this:

ISO C++ thread class – A thin portable
  wrapper around OS threads. It's a
  close approximation of the ISO C++
  200x class thread (Section 30.2 of
  http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2691.pdf).
  Now TBB lets you choose which is best,
  task-based versus thread-based, for
  your situation. Threads are typically
  better than tasks when the "work" is
  really more waiting than computation,
  such as for:

* GUI, I/O or network interface threads.
* Threads that need to wait on external events.
* Programs that previously needed to use both native threads and Intel® TBB tasks.

ie they're admitting TBB's task parallelism isn't a universal panacea and you need something more like the "traditional" threading model sometimes for I/O.  And indeed if you check the latest reference manual you'll find TBB does now contain condition variables!  (See section 8.4)


问:
How to analyse time series which contains multiple sources (e.g. weather data time series of multiple weather stations)
I am trying to build a machine learning model to predict VAR1 for each neighborhood across time. Using time series data (Year and month). However, the data contains many neighborhoods (which are the basis of the analysis). So each neighborhood will be repeated 3 yrs * 12 months= 36 times.

I need to merge this data with other datasets. All the other datasets have the same number of areas and have Year but do not have month.

I need help on how to go about joining these datasets together and analysis. I am working in R.

On joining the datasets, I will try to transfer the rows in the other datasets into columns so I would have less instances for each area.

Here's an example of some the head of some of the datasets (in R):

```<code>head(df)
  Year     Month          District         Neighborhood          Gender       VAR1
1 2017    January             1                 1                   M          2000
2 2017    January             1                 2                   M          350
3 2017    January             1                 3                   M          700
4 2017    January             1                 4                   M          400
5 2017    January             2                 5                   M          1000
6 2017    January             2                 6                   M          200

</code>```

```<code>tail(df)
      Year  Month          District           Neighborhood      Gender       VAR1
10577 2015 December            10                   69              F         200
10578 2015 December            10                   70              F         1000
10579 2015 December            10                   71              F         500
10580 2015 December            10                   72              F         350
10581 2015 December            10                   73              F         300
10582 2015 December            99                   99              F         770

</code>```

I need help on two things:

First, I need to know how I can merge the example above with the other datasets which don't have month.

I am stuck on how to go about doing EDA and analysing this dataset and would appreciate help here.

答: You can build separate models for each source then simply concatenate them together. Here is a quick video for this. </p>

Body:
I am trying to build a machine learning model to predict VAR1 for each neighborhood across time. Using time series data (Year and month). However, the data contains many neighborhoods (which are the basis of the analysis). So each neighborhood will be repeated 3 yrs * 12 months= 36 times.

I need to merge this data with other datasets. All the other datasets have the same number of areas and have Year but do not have month.

I need help on how to go about joining these datasets together and analysis. I am working in R.

On joining the datasets, I will try to transfer the rows in the other datasets into columns so I would have less instances for each area.

Here's an example of some the head of some of the datasets (in R):

head(df)
  Year     Month          District         Neighborhood          Gender       VAR1
1 2017    January             1                 1                   M          2000
2 2017    January             1                 2                   M          350
3 2017    January             1                 3                   M          700
4 2017    January             1                 4                   M          400
5 2017    January             2                 5                   M          1000
6 2017    January             2                 6                   M          200

tail(df)
      Year  Month          District           Neighborhood      Gender       VAR1
10577 2015 December            10                   69              F         200
10578 2015 December            10                   70              F         1000
10579 2015 December            10                   71              F         500
10580 2015 December            10                   72              F         350
10581 2015 December            10                   73              F         300
10582 2015 December            99                   99              F         770

I need help on two things:

First, I need to know how I can merge the example above with the other datasets which don't have month.

I am stuck on how to go about doing EDA and analysing this dataset and would appreciate help here.


问:
How to spread tab items evenly?
I'm developing new administration page. On that registration page I need to have a menu with five tabs for each administration section. We are using ant for angular and for tab menu we are using component from ant library.

I have tried to override style for ant tabs as described here:

How To Evenly Space Tabs Across the Whole Tab Bar

and here

https://github.com/NG-ZORRO/ng-zorro-antd/issues/2242

None of those articles helped.

Here is code example

```<code>    <nz-tab nzTitle="LAN STATUS">
      Content of Tab Pane 1
    </nz-tab>
    <nz-tab nzTitle="DHCP">
      Content of Tab Pane 2
    </nz-tab>
    <nz-tab nzTitle="DNS">
        Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="USERS">
          Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="AMAZON SERVICES">
          Content of Tab Pane 2
      </nz-tab>
  </nz-tabset>
</code>```

I would like to have a evenly spaced  element inside

答:
The solution posted in your link solves your problem. You just to add this scss to your project:

```<code>.ant-tabs {
  &-nav {
    display: flex;

    .ant-tabs-tab {
      flex-grow: 1;
      margin-right: 0px;
      width: 100%;
      text-align: center;
    }
  }
}
</code>```

(make sure you are really using *.scss in your angular project, default is *.css)

You then have two places to add it:

In the global stylesheet. Your project comes with a style.scss file. just add the snippet there and all your tabs will be evenly divide

Inside your component styles. The same styles, but because of angular view encapsulation, your scss starts like this: :host ::ng-deep .ant-tabs {. (you can finde a demo here: https://stackblitz.com/edit/ng-zorro-antd-zmmkth). You can also disable the view encapsulation on your component with:

@Component({
...
  encapsulation: ViewEncapsulation.None,
})

Title: How to spread tab items evenly?

Body:
I'm developing new administration page. On that registration page I need to have a menu with five tabs for each administration section. We are using ant for angular and for tab menu we are using component from ant library.

I have tried to override style for ant tabs as described here:

How To Evenly Space Tabs Across the Whole Tab Bar

and here

https://github.com/NG-ZORRO/ng-zorro-antd/issues/2242

None of those articles helped.

Here is code example

    <nz-tab nzTitle="LAN STATUS">
      Content of Tab Pane 1
    </nz-tab>
    <nz-tab nzTitle="DHCP">
      Content of Tab Pane 2
    </nz-tab>
    <nz-tab nzTitle="DNS">
        Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="USERS">
          Content of Tab Pane 2
      </nz-tab>
      <nz-tab nzTitle="AMAZON SERVICES">
          Content of Tab Pane 2
      </nz-tab>
  </nz-tabset>

I would like to have a evenly spaced  element inside

Body:
The solution posted in your link solves your problem. You just to add this scss to your project:

.ant-tabs {
  &-nav {
    display: flex;

    .ant-tabs-tab {
      flex-grow: 1;
      margin-right: 0px;
      width: 100%;
      text-align: center;
    }
  }
}

(make sure you are really using *.scss in your angular project, default is *.css)

You then have two places to add it:

In the global stylesheet. Your project comes with a style.scss file. just add the snippet there and all your tabs will be evenly divide

Inside your component styles. The same styles, but because of angular view encapsulation, your scss starts like this: :host ::ng-deep .ant-tabs {. (you can finde a demo here: https://stackblitz.com/edit/ng-zorro-antd-zmmkth). You can also disable the view encapsulation on your component with:

@Component({
...
  encapsulation: ViewEncapsulation.None,
})


问:
OpenPyXL - Identify range of cells styled Centered Across Selection
I am parsing spreadsheets via OpenPyXL and I wish to know if one or more non-merged cells is configured to be centered across selection, and to get the extents of that selection.

This is quite straight-forward with merged cells (using worksheet.merged_cells ranges), but is there any way to similarly identify the extents of a horizontal group of non-merged cells where text is centered across the group of cells?

答:
To the best of my knowledge, there is no way in OpenPyXL to identify the extents of a horizontal group of non-merged cells where text is centered across the group of cells.

As you pointed out, it is possible to get this information for merged cells (using the worksheet.merged_cells ranges), but no way to do so for non-merged cells.

I believe that Charlie's answer to your earlier (deleted) question attempted to say that, but I agree that the response could have been more clear.