问:
Excel VBA Dictionary Data Integrity Issue
I appear to have a significant data integrity issue using Dictionaries in Excel VBA which I use extensively in my code. I have a routine where I use a Dictionary to capture the best results from an optimization routine. Once captured, I then update an existing data table, using the results in calculations where a zero value will cause errors. This routine has been used extensively in the past with no errors. Therefore, I was surprised when errors started occurring. I tracked the error to what appears to be a Dictionary's data being corrupted outside of the actual code.

The Dictionary with the error is loaded by another Dictionary that continually looks for updates and only keeps the values that are better than previous ones, thus the optimization. Once these values have been captured, the Dictionary (DataItems) that causes the error loads the new values into a data table a variable at a time. Here is the code I used to trap the error:

```<code>If KeyCount <> DataItems.Count Then: Stop
NewValue = DataItems(NewData)
If KeyCount <> DataItems.Count Then: Stop
</code>```

I captured the count of Items in DataItems prior to reading the data into the NewValue variable. Prior to reading the data the Dictionary had a count of 1, but after reading the data, the count went to 2. The original key became the key of a new record with an item value of zero and the original item obtained a new key that appears to be a value in the original bulk data being scanned. This appears to occur almost always with only one record in the DataItems dictionary.

I can use the same routine with other calling applications with absolutely no problems, so the problem appears to be tied to the calling application which makes no sense since the dictionaries being used originated in the routine where the error occurs. I have tried eliminating potential timing issues by stepping through the code and other debugging actions, but I remain extremely puzzled. It really makes me question the potential data integrity of using Dictionaries in Excel for application critical data. Any insights would be appreciated.

答:
I'm guessing that you're using the Watch window and/or the Immediate pane while debugging, and that's what's causing the problem (or at least making it worse)... If you add specific expressions such as DataItems("keyHere") to the Watch list then when code is paused that watch will actually add that key if it doesn't exist.

Similarly, if when paused you do something like ? DataItems("thisKeyDoesNotExist") in the Immediate window, you will not see any output, but that key will silently get created.

To illustrate:

```<code>Sub DictWatch()

    Dim d As Object, k

    Set d = CreateObject("scripting.dictionary")

    d.Add "one", 1
    Stop 'add a watch on the expression d("one") before proceeding
    d.RemoveAll

    Stop  'enter "? d("test")" in Immediate pane and hit enter before proceeding

    For Each k In d.keys
        Debug.Print k  'output is "one" and "test"
    Next k

End Sub
</code>```

Body:
I appear to have a significant data integrity issue using Dictionaries in Excel VBA which I use extensively in my code. I have a routine where I use a Dictionary to capture the best results from an optimization routine. Once captured, I then update an existing data table, using the results in calculations where a zero value will cause errors. This routine has been used extensively in the past with no errors. Therefore, I was surprised when errors started occurring. I tracked the error to what appears to be a Dictionary's data being corrupted outside of the actual code.

The Dictionary with the error is loaded by another Dictionary that continually looks for updates and only keeps the values that are better than previous ones, thus the optimization. Once these values have been captured, the Dictionary (DataItems) that causes the error loads the new values into a data table a variable at a time. Here is the code I used to trap the error:

If KeyCount <> DataItems.Count Then: Stop
NewValue = DataItems(NewData)
If KeyCount <> DataItems.Count Then: Stop

I captured the count of Items in DataItems prior to reading the data into the NewValue variable. Prior to reading the data the Dictionary had a count of 1, but after reading the data, the count went to 2. The original key became the key of a new record with an item value of zero and the original item obtained a new key that appears to be a value in the original bulk data being scanned. This appears to occur almost always with only one record in the DataItems dictionary.

I can use the same routine with other calling applications with absolutely no problems, so the problem appears to be tied to the calling application which makes no sense since the dictionaries being used originated in the routine where the error occurs. I have tried eliminating potential timing issues by stepping through the code and other debugging actions, but I remain extremely puzzled. It really makes me question the potential data integrity of using Dictionaries in Excel for application critical data. Any insights would be appreciated.

Body:
I'm guessing that you're using the Watch window and/or the Immediate pane while debugging, and that's what's causing the problem (or at least making it worse)... If you add specific expressions such as DataItems("keyHere") to the Watch list then when code is paused that watch will actually add that key if it doesn't exist.

Similarly, if when paused you do something like ? DataItems("thisKeyDoesNotExist") in the Immediate window, you will not see any output, but that key will silently get created.

To illustrate:

Sub DictWatch()

    Dim d As Object, k

    Set d = CreateObject("scripting.dictionary")

    d.Add "one", 1
    Stop 'add a watch on the expression d("one") before proceeding
    d.RemoveAll

    Stop  'enter "? d("test")" in Immediate pane and hit enter before proceeding

    For Each k In d.keys
        Debug.Print k  'output is "one" and "test"
    Next k

End Sub


来源: stackexchange

问:
How to find what exception some library code might throw
I am new to Kotlin and I have the following problem: In my project I am using a small library (JAR, no sources). In it there are few custom exception classes defined which inherit Exception class. Some methods throw these exceptions.

In my code I bump into the problem that I don't know what exception the library code might throw so I can catch it and thus sometimes the exception goes trough the roof.

What it is the usual way to handle such situations in Kotlin?

答:
I don't exactly know the right approach in kotlin, but you may use the following idea from scala:
Try -

```<code>try Success(r) catch {
  case NonFatal(e) => Failure(e)
}
</code>```

If exception is not fatal:

```<code> case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
 case _ => true
</code>```

then just return Failure(e) otherwise throw it.
How can you use it? At least you will not end up like this:

```<code>try {
...
} catch {
    case _ : Throwable => ... // catch all exceptions
}
</code>```

Yes, you still don't know which exceptions code may throw, but using this approach you can control the general execution flow.

But of course, it will be much better if docs list exceptions which may be thrown.

ContentLicense: CC BY-SA 4.0

Body:
I don't exactly know the right approach in kotlin, but you may use the following idea from scala:
Try -

try Success(r) catch {
  case NonFatal(e) => Failure(e)
}

If exception is not fatal:

 case _: VirtualMachineError | _: ThreadDeath | _: InterruptedException | _: LinkageError | _: ControlThrowable => false
 case _ => true

then just return Failure(e) otherwise throw it.
How can you use it? At least you will not end up like this:

try {
...
} catch {
    case _ : Throwable => ... // catch all exceptions
}

Yes, you still don't know which exceptions code may throw, but using this approach you can control the general execution flow.

But of course, it will be much better if docs list exceptions which may be thrown.


问:
How to use ValueListenableProvider
I'm trying to understand how to use ValueListenableProvider but I'm quite confused, let's follow the example on the linked page:

ValueListenable<int> foo;

ValueListenableProvider<int>.value(
  valueListenable: foo,
  child: Container(),
);
```

Ok, this provides foo to all child widgets, but how do I recover it?

 For example, in ChangeNotifierProvider I use the type to get my reference back e.g. Provider.of<SomeType>(context). What would be SomeType here? int?

答:
ValueListenableProvider exposes ValueListenable.value.

As such to read from a ValueListenableProvider<int>, you need to use Provider.of<int>(context)

Title: How to use ValueListenableProvider

Body:
I'm trying to understand how to use ValueListenableProvider but I'm quite confused, let's follow the example on the linked page:

ValueListenable<int> foo;

ValueListenableProvider<int>.value(
  valueListenable: foo,
  child: Container(),
);

Ok, this provides foo to all child widgets, but how do I recover it?

 For example, in ChangeNotifierProvider I use the type to get my reference back e.g. Provider.of<SomeType>(context). What would be SomeType here? int?


问:
how to edit xml file in C#
```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

```<code><Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>
</code>```

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin

答:
You should read the documentation on XmlDocument and XmlNode and it's associated classes.  There is also plenty of examples of how to use them online.

Here is an introduction to XML with C#.

ContentLicense: CC BY-SA 3.0

Title: how to edit xml file in C#

Body:
<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>
  </FamilyCategory>

  <FamilyCategory>Curtain Panels
    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>
  </FamilyCategory>
  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

i want create only one FamilyCategory tag based on its value as above is 'Curtain Panels'
so output will be

<Family_Inventory>
  <FamilyCategory>Curtain Panels
    <FamilyName>System Panel
        <FamilySymbol>Glazed</FamilySymbol>
        <FamilySymbol>Wall</FamilySymbol>
    </FamilyName>

    <FamilyName>Rectangular Mullion
      <FamilySymbol>2.5" x 5" rectangular</FamilySymbol>
    </FamilyName>

  </FamilyCategory>

  ...........
  ...........// many other family categories
  ...........

</Family_Inventory>

Please tell me how Can i do this?.

Thanks in Advance
Regards,
Nitin


问:
How to preg_match a PCRE expression?
```<code>$key="`client` asc";
preg_match('
                ~(?J)
                    \s*
                    (?:`(?P<col>(?:[^`\\\\]|\\\\.|``)*)`|(?P<col>\S+))
                    (?:\s+(?P<dir>asc|desc))?
                    \s*
                \z~Axi', $key, $m);
print_r($m);
</code>```

This regular expression fills the col key when tested here

https://regex101.com/r/i00sEn/1

It does not work correctly on my local PHP 5.6 machine, or this 7.3 interpreter.

http://sandbox.onlinephpfunctions.com/code/915a26b741c6d086f21129f60af2420c74cf9f89

It works everywhere if I remove the backticks, but as the purpose of this code is to parse SQL ORDER BY clauses, I need the backticks.

Why does this work?  How can I get it to match backticks correctly?

答:
You use an alternation for both groups. What you might do using your pattern is to create a branch reset group (?| instead of a non capturing group.

Thanks to the comment of Wiktor Stribiżew your pattern could look like:

```<code>(?J)
                    \s*
                    (?|`(?P<col>(?:[^`\\]|\\.|``)*)`|(?P<col>\S+))
                    (?:\s+(?P<dir>asc|desc))?
                    \s*
                \z
</code>```

Regex demo | Php demo

Title: How to preg_match a PCRE expression?

Body:
$key="`client` asc";
preg_match('
                ~(?J)
                    \s*
                    (?:`(?P<col>(?:[^`\\\\]|\\\\.|``)*)`|(?P<col>\S+))
                    (?:\s+(?P<dir>asc|desc))?
                    \s*
                \z~Axi', $key, $m);
print_r($m);

This regular expression fills the col key when tested here

https://regex101.com/r/i00sEn/1

It does not work correctly on my local PHP 5.6 machine, or this 7.3 interpreter.

http://sandbox.onlinephpfunctions.com/code/915a26b741c6d086f21129f60af2420c74cf9f89

It works everywhere if I remove the backticks, but as the purpose of this code is to parse SQL ORDER BY clauses, I need the backticks.

Why does this work?  How can I get it to match backticks correctly?

Body:
You use an alternation for both groups. What you might do using your pattern is to create a branch reset group (?| instead of a non capturing group.

Thanks to the comment of Wiktor Stribiżew your pattern could look like:

(?J)
                    \s*
                    (?|`(?P<col>(?:[^`\\]|\\.|``)*)`|(?P<col>\S+))
                    (?:\s+(?P<dir>asc|desc))?
                    \s*
                \z

Regex demo | Php demo


问:
return not working properly when calling non-async function from async function
I am trying to do a validation where each 2 seconds, the app checks into the database for a certain value, until said value is found

let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = this.checkSession(hash);
  console.log(conf);
} while (!conf);
```

<pre class="lang-js prettyprint-override"><code>checkSessao(hash) {
  let sql = "SELECT usuario_id FROM sessao WHERE hash='" + hash + "';";

  this.db.selectGenerico(sql).then(response => {
    if (response[0].usuario_id !== null) {
      console.log("suposed to return true");
      return true;
    }

  }).catch(ex => {
    return false;
  });

  return false;
}
</code>```

the thing is, the function ALWAYS return false, even though console.log("suposed to return true"); fires. I believe its related to the fact that i am calling a non-async function inside a async function. Any ideas?

答:
Your assumption is correct. You need to return a Promise in your checkSessao function and wait until it's resolved in your loop.

```<code>checkSessao(hash) {
  return new Promise((resolve, reject) => {
    let sql = "SELECT usuario_id FROM sessao WHERE hash='" + hash + "';";
    this.db.selectGenerico(sql).then(response => {
      if(response[0].usuario_id !== null) {
        console.log("suposed to return true");
        resolve(true);
      } else {
        resolve(false);
      }
    }).catch(ex => {
      resolve(false);
    });
  })
}
</code>```

Usage:

```<code>let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = await this.checkSession(hash);
  console.log(conf);
} while (!conf);
</code>```

Body:
I am trying to do a validation where each 2 seconds, the app checks into the database for a certain value, until said value is found

let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = this.checkSession(hash);
  console.log(conf);
} while (!conf);

checkSessao(hash) {
  let sql = "SELECT usuario_id FROM sessao WHERE hash='" + hash + "';";

  this.db.selectGenerico(sql).then(response => {
    if (response[0].usuario_id !== null) {
      console.log("suposed to return true");
      return true;
    }

  }).catch(ex => {
    return false;
  });

  return false;
}

the thing is, the function ALWAYS return false, even though console.log("suposed to return true"); fires. I believe its related to the fact that i am calling a non-async function inside a async function. Any ideas?

Body:
Your assumption is correct. You need to return a Promise in your checkSessao function and wait until it's resolved in your loop.

checkSessao(hash) {
  return new Promise((resolve, reject) => {
    let sql = "SELECT usuario_id FROM sessao WHERE hash='" + hash + "';";
    this.db.selectGenerico(sql).then(response => {
      if(response[0].usuario_id !== null) {
        console.log("suposed to return true");
        resolve(true);
      } else {
        resolve(false);
      }
    }).catch(ex => {
      resolve(false);
    });
  })
}

Usage:

let conf = false;
do {
  await this.sleep(2 * 1000);
  conf = await this.checkSession(hash);
  console.log(conf);
} while (!conf);


问:
How to debug a problem with GET Express Router
I develop a game with a MEAN stack, so I need to create the API with Node & MongoDB to store scores and using this API in a Angular client.

The database is OK and I can add a score with POST but now I try to query the database with the API and the GET method not working.

I try to create a simple response (route /) but the response is the Angular client (index.html) in Postman, the POST work but the GET not !

```<code>classRouter.post('/add', (req, res) => {
  // Check request body
  if (typeof req.body === 'undefined' || req.body === null) {
    sendBodyError(res, Vocabulary.errors.noBody)
  };
  // Check fields in the body
  const {
    miss,
    extra,
    ok
  } = checkFields(Mandatory.game, req.body);

  //=> Error: bad fields provided
  if (!ok) {
    sendFieldsError(res, Vocabulary.errors.badFields, miss, extra)
  }
  else {
    //=> Request is valid: use controller
    createScore(req.body)
      .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
      .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
  };
});

// Route for all score
classRouter.get('/all', (req, res) => {
  getAllScores()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
});

classRouter.get('/', function(req, res) {
  res.send('GET request to the homepage');
});
</code>```

```<code>const createScore = body => {
  return new Promise((resolve, reject) => {
    // Register new user
    ScoreModel.create(body)
      .then(mongoResponse => resolve(mongoResponse))
      .catch(mongoResponse => reject(mongoResponse))
  });
};

// Get all scores from the database
const getAllScores = () => {
  return new Promise((resolve, reject) => {
    ScoreModel.find((error, item) => {
      // Request error
      if (error) {
        return reject(error)
      } else {
        return resolve(item)
      };
    });
  });
};
</code>```

If someone can help me ?

Thanks

答: Personally, I like to use some kind of IDE to provide it to me. I use WebStorm</p>

Body:
I develop a game with a MEAN stack, so I need to create the API with Node & MongoDB to store scores and using this API in a Angular client.

The database is OK and I can add a score with POST but now I try to query the database with the API and the GET method not working.

I try to create a simple response (route /) but the response is the Angular client (index.html) in Postman, the POST work but the GET not !

classRouter.post('/add', (req, res) => {
  // Check request body
  if (typeof req.body === 'undefined' || req.body === null) {
    sendBodyError(res, Vocabulary.errors.noBody)
  };
  // Check fields in the body
  const {
    miss,
    extra,
    ok
  } = checkFields(Mandatory.game, req.body);

  //=> Error: bad fields provided
  if (!ok) {
    sendFieldsError(res, Vocabulary.errors.badFields, miss, extra)
  }
  else {
    //=> Request is valid: use controller
    createScore(req.body)
      .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
      .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
  };
});

// Route for all score
classRouter.get('/all', (req, res) => {
  getAllScores()
    .then(apiResponse => sendApiSuccessResponse(res, Vocabulary.request.success, apiResponse))
    .catch(apiResponse => sendApiErrorResponse(res, Vocabulary.request.error, apiResponse))
});

classRouter.get('/', function(req, res) {
  res.send('GET request to the homepage');
});

const createScore = body => {
  return new Promise((resolve, reject) => {
    // Register new user
    ScoreModel.create(body)
      .then(mongoResponse => resolve(mongoResponse))
      .catch(mongoResponse => reject(mongoResponse))
  });
};

// Get all scores from the database
const getAllScores = () => {
  return new Promise((resolve, reject) => {
    ScoreModel.find((error, item) => {
      // Request error
      if (error) {
        return reject(error)
      } else {
        return resolve(item)
      };
    });
  });
};

If someone can help me ?

Thanks


问:
How to copy specific files from directories, while the directories name was extracted from an excel file using Bash script
I'm new in Bash and I have a list of names of directories stored in an excel file. I'd like to find those directories (they are located in different location at the computer) and to copy from each directory specific files (list of 4 files that ends with specific endings) to a remote computer.

For examples:

For a name of directory at the excel sheet - "NA123", I'd like to find it and copy it's partial content to a remote computer, for example copy the files: samples-sheet.csv, toInfo.xml, newfiles.gz, todo.csv to the remote computer, under a folder name "NA123".

How do I begin to do that?

****Editing to give an example of how it needs to be*****

A short example of the csv is as below:

```<code>         A
1  14RD00129_TS1_01
2  SD-2015-06_01
3  US-005
4  RA99
</code>```

All the names at the csv are directories that can be found under /home/bella/samples under 3 different folders: some will be at /home/bella/samples/gruop_1, some at:/home/bella/samples/gruop_2, and some at:/home/bella/samples/gruop_3

So first I need to iterate through the csv file, to locate the match directory at my computer, then I need to copy 4 specific files to a remote computer with the same name of directory. Hope this is clearer...

答:
I guess you CSV file should only consist of directory names then, since there's only one column. I assume there is no header line in the CSV (A in your example) and no line number. You can take this as a starting point:

samples='/home/bella/samples'
while IFS= read -r line; do
    dir=$(find "$samples"/gruop_{1..3} -type d -name "$line")
    scp "$dir"/{samples-sheet.csv,toInfo.xml,newfiles.gz,todo.csv} \
        user@host.com:"/path/to/$line"
done < 'file.csv'
```

Body:
I'm new in Bash and I have a list of names of directories stored in an excel file. I'd like to find those directories (they are located in different location at the computer) and to copy from each directory specific files (list of 4 files that ends with specific endings) to a remote computer.

For examples:

For a name of directory at the excel sheet - "NA123", I'd like to find it and copy it's partial content to a remote computer, for example copy the files: samples-sheet.csv, toInfo.xml, newfiles.gz, todo.csv to the remote computer, under a folder name "NA123".

How do I begin to do that?

****Editing to give an example of how it needs to be*****

A short example of the csv is as below:

         A
1  14RD00129_TS1_01
2  SD-2015-06_01
3  US-005
4  RA99

All the names at the csv are directories that can be found under /home/bella/samples under 3 different folders: some will be at /home/bella/samples/gruop_1, some at:/home/bella/samples/gruop_2, and some at:/home/bella/samples/gruop_3

So first I need to iterate through the csv file, to locate the match directory at my computer, then I need to copy 4 specific files to a remote computer with the same name of directory. Hope this is clearer...


问:
what is the max array size in Javascript and which arrays to use
I wanted t create a large array in Javascript and wrote the following code but it did not work due to OOM

```<code>let N = 125000000;
let numbers = [];
for (let i = 0; i < N; i++) {
    numbers[i] = Math.round(Math.random()*10000);
}
</code>```

Then I wrote "let numbers = new Array(N);" instead, which worked for the N (125000000) but did not work with larger N (200000000). Then I used Uint32Array, which worked for even larger N. It worked up to N = 2^31-1.
Is there any limit on size in [], new Array(size), Uint32Array in Javascript? I guess the max size o Uint32Array is 2^31-1. I also want to know why new Array(N) has higher limit than [].
Thank you

答:
NodeJS follows the ECMAScript specification, that is implemented via the V8 engine.

The maximum you can fit inside is 4,294,967,295 = 4.29 billion elements.

You ran out of memory because V8 sets a memory limit, you can bypass this limit by invoking Node with 'max-old-space-size' parameter, like so:

node --max-old-space-size=1024 yourscript.js

Where 1024 is 1GB, 2048  2GB and so goes on.

Body:
I wanted t create a large array in Javascript and wrote the following code but it did not work due to OOM

let N = 125000000;
let numbers = [];
for (let i = 0; i < N; i++) {
    numbers[i] = Math.round(Math.random()*10000);
}

Then I wrote "let numbers = new Array(N);" instead, which worked for the N (125000000) but did not work with larger N (200000000). Then I used Uint32Array, which worked for even larger N. It worked up to N = 2^31-1.
Is there any limit on size in [], new Array(size), Uint32Array in Javascript? I guess the max size o Uint32Array is 2^31-1. I also want to know why new Array(N) has higher limit than [].
Thank you


问:
Google Cloud Platform: Temporary Server error?
Google Cloud Platform is raising an error like:
Error: Server Error The server encountered a temporary error and could not complete your request. Please try again in 30 seconds.

We have GCP, CDN and Google Cloud Load Balancing with GCP.

How can we fix this server error?

答: Try changing instance type to backend instances to increase the request timeout. Frontend instances have a timeout of ~60 seconds. Here is a detailed list of errors in GCP docs </p>


问:
NativeScript android BetterVideoPlayer implement
I am trying to implement BetterVideoPlayer (implementation 'com.github.halilozercan:BetterVideoPlayer:1.2.alpha1') for NativeScript Android. So, in an Angular project I have created separate component like this:

```<code>import { View } from "tns-core-modules/ui/core/view";

declare var com, android;

export class BetterPlayer extends View {

    public mediaPlayer;

    public createNativeView(): any {

        const nativeView = new android.widget.FrameLayout(this._context);

        nativeView.addView(this._openVideo());

        // or return this._openVideo(); // still not working..

        return nativeView;
    }

    public _openVideo() {
        let url = android.net.Uri.parse("http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4");

        this.mediaPlayer = new com.halilibo.bettervideoplayer.BetterVideoPlayer(this._context);

        console.dir(this.mediaPlayer);

        this.mediaPlayer.setSource(url);
        this.mediaPlayer.setAutoPlay(true);
        this.mediaPlayer.setHideControlsOnPlay(true);

        return this.mediaPlayer;
    }
}
</code>```

Then from component I have registered it using registerElement

```<code>registerElement("BetterPlayer", () => BetterPlayer);
</code>```

HTML:

```<code><BetterPlayer height="200"></BetterPlayer>
</code>```

But the problem is, it isn't showing the player. Only showing a black area. In where I did mistake? Please give me advice. Thanks in advance.

答: BetterVideoPlayer creates the actual media player within at onFinishInflate(), is a method called only when a View element is initiated via Android XML, programatic creation like you do in {N} won't trigger this method. So you could simply do this.mediaPlayer.onFinishInflate(); to force creating the media player and it should work, I was able to watch the video on device once I did.

Body:
I am trying to implement BetterVideoPlayer (implementation 'com.github.halilozercan:BetterVideoPlayer:1.2.alpha1') for NativeScript Android. So, in an Angular project I have created separate component like this:

import { View } from "tns-core-modules/ui/core/view";

declare var com, android;

export class BetterPlayer extends View {

    public mediaPlayer;

    public createNativeView(): any {

        const nativeView = new android.widget.FrameLayout(this._context);

        nativeView.addView(this._openVideo());

        // or return this._openVideo(); // still not working..

        return nativeView;
    }

    public _openVideo() {
        let url = android.net.Uri.parse("http://jzvd.nathen.cn/c6e3dc12a1154626b3476d9bf3bd7266/6b56c5f0dc31428083757a45764763b0-5287d2089db37e62345123a1be272f8b.mp4");

        this.mediaPlayer = new com.halilibo.bettervideoplayer.BetterVideoPlayer(this._context);

        console.dir(this.mediaPlayer);

        this.mediaPlayer.setSource(url);
        this.mediaPlayer.setAutoPlay(true);
        this.mediaPlayer.setHideControlsOnPlay(true);

        return this.mediaPlayer;
    }
}

Then from component I have registered it using registerElement

registerElement("BetterPlayer", () => BetterPlayer);

HTML:

<BetterPlayer height="200"></BetterPlayer>

But the problem is, it isn't showing the player. Only showing a black area. In where I did mistake? Please give me advice. Thanks in advance.


问:
how to open new window in place of current window in Electron
I am have been able to open a new window when i click a button, however, its a new pop up window. How can I have the new window open up in place of the main window?

```<code>var app = require('app')
var BrowserWindow = require('browser-window')
var ipc = require('ipc')

app.on('ready', function () {
    var mainWindow = new BrowserWindow ({
        width: 800,
        height: 600
    })
    mainWindow.loadURL('file://' + __dirname + '/main.html')
    //mainWindow.openDevTools() //opens inspect console

    var prefsWindow = new BrowserWindow ({
        width: 400,
        height: 400,
        show: false
    })
    prefsWindow.loadURL('file://' + __dirname + '/prefs.html')
</code>```

With the code above, a new window pops up. Ive attached a screenshot to show what I mean.

popup window

Instead of that popup window, i want 'prefs' to replace the main window (and other options to replace the main window once added).

答:
I was fighting the same issue as you did until I found a simple solution.
Here's the JS code:</p>

```<code>const electron = require('electron');
let rootPath = "src/Page/index.html" //Path to the html file

LoadNewWindowInCurrent(rootPath); //Opens new html file in current window

//Here's the ready function for you to use
function LoadNewWindowInCurrent (PathToHtml){
   let localWindow = electron.remote.getCurrentWindow();
   localWindow.LoadFile(PathToHtml);
}
</code>```

Body:
I am have been able to open a new window when i click a button, however, its a new pop up window. How can I have the new window open up in place of the main window?

var app = require('app')
var BrowserWindow = require('browser-window')
var ipc = require('ipc')

app.on('ready', function () {
    var mainWindow = new BrowserWindow ({
        width: 800,
        height: 600
    })
    mainWindow.loadURL('file://' + __dirname + '/main.html')
    //mainWindow.openDevTools() //opens inspect console

    var prefsWindow = new BrowserWindow ({
        width: 400,
        height: 400,
        show: false
    })
    prefsWindow.loadURL('file://' + __dirname + '/prefs.html')

With the code above, a new window pops up. Ive attached a screenshot to show what I mean.

popup window

Instead of that popup window, i want 'prefs' to replace the main window (and other options to replace the main window once added).

Body:
I was fighting the same issue as you did until I found a simple solution.
Here's the JS code:

const electron = require('electron');
let rootPath = "src/Page/index.html" //Path to the html file

LoadNewWindowInCurrent(rootPath); //Opens new html file in current window

//Here's the ready function for you to use
function LoadNewWindowInCurrent (PathToHtml){
   let localWindow = electron.remote.getCurrentWindow();
   localWindow.LoadFile(PathToHtml);
}


问:
jquery/javascript wait for a function to complete
I have script that performs from DOM manipulation to change the way a div looks. The way the application is, when the page loads, the div is rendered in its original state, the function manipulates the DIV. The problem is it renders the original div before rendering the changed div.

I tried:

```<code>//Make div invisible

//Call function to change the DIV

//Make div visible
</code>```

This does not work

答:
Are you using the visibility attribute?

```<code><div id="divy" style="display:none;">Wee</div>
</code>```

or set the style in a .css file

```<code>$(document).ready(function(){
   $("#divy").css("color", "#424242");
   $("#divy").show();
});
</code>```

OwnerDisplayName: Bob Smith

ContentLicense: CC BY-SA 2.5

Body:
I have script that performs from DOM manipulation to change the way a div looks. The way the application is, when the page loads, the div is rendered in its original state, the function manipulates the DIV. The problem is it renders the original div before rendering the changed div.

I tried:

//Make div invisible

//Call function to change the DIV

//Make div visible

This does not work

Body:
Are you using the visibility attribute?

<div id="divy" style="display:none;">Wee</div>

or set the style in a .css file

$(document).ready(function(){
   $("#divy").css("color", "#424242");
   $("#divy").show();
});

OwnerDisplayName: Hunter


问:
Ext-Gwt gui designer
guys!
I am very interested with ext gwt. Do you know any darg and drop designers for this framework?
Does ext gwt work with ext designer?

Thanks

答:
No, Ext GWT won't work with Ext Designer. It will, however, work with GWT Designer in Eclipse.

Instructions:
http://code.google.com/intl/en-US/webtoolkit/tools/gwtdesigner/features/gwt/gxt.html

Some people had problems with that one, in that case you might find a workaround here:
How to configure Ext GWT with GWT Designer?

And the last word from me: I haven't used that, working with GXT components the old fashioned way isn't a big pain, too.

Title: Ext-Gwt gui designer


问:
gradle 5: project.distsDir deprecated, replacement?
gradle 5: project.distsDir deprecated. What is the replacement?

```<code>new File(project.buildDir, project.distsDirName)
</code>```

Why is it deprecated?

答: This is a consequence of Gradle adopting the Provider API to enable lazy evaluation of properties.

Body:
gradle 5: project.distsDir deprecated. What is the replacement?

new File(project.buildDir, project.distsDirName)

Why is it deprecated?


问:
How slicing in Python works
How does Python's slice notation work? That is: when I write code like a[x:y:z], a[:], a[::2] etc., how can I understand which elements end up in the slice? Please include references where appropriate.

See Why are slice and range upper-bound exclusive? for more discussion of the design decisions behind the notation.

See Pythonic way to return list of every nth item in a larger list for the most common practical usage of slicing (and other ways to solve the problem): getting every Nth element of a list. Please use that question instead as a duplicate target where appropriate.

For more specific answers about slice assignment, see How does assignment work with list slices? (although this is also addressed here).

答:
I don't think that the Python tutorial diagram (cited in various other answers) is good as this suggestion works for positive stride, but does not for a negative stride.

This is the diagram:

```<code> +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

</code>```

From the diagram, I expect a[-4,-6,-1] to be yP but it is ty.

>>> a = "Python"
>>> a[2:4:1] # as expected
'th'
>>> a[-4:-6:-1] # off by 1
'ty'
```

<p>What always work is to think in characters or slots and use indexing as a half-open interval -- right-open if positive stride, left-open if negative stride.</p>

<p>This way, I can think of <code>a[-4:-6:-1]</code> as <code>a(-6,-4]</code> in interval terminology.</p>

``` +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5
  -6  -5  -4  -3  -2  -1

 +---+---+---+---+---+---+---+---+---+---+---+---+
 | P | y | t | h | o | n | P | y | t | h | o | n |
 +---+---+---+---+---+---+---+---+---+---+---+---+
  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5
```

OwnerDisplayName: Simon

Title: How slicing in Python works

Body:
I don't think that the Python tutorial diagram (cited in various other answers) is good as this suggestion works for positive stride, but does not for a negative stride.

This is the diagram:

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
 0   1   2   3   4   5   6
-6  -5  -4  -3  -2  -1

From the diagram, I expect a[-4,-6,-1] to be yP but it is ty.

>>> a = "Python"
>>> a[2:4:1] # as expected
'th'
>>> a[-4:-6:-1] # off by 1
'ty'

What always work is to think in characters or slots and use indexing as a half-open interval -- right-open if positive stride, left-open if negative stride.

This way, I can think of a[-4:-6:-1] as a(-6,-4] in interval terminology.

 +---+---+---+---+---+---+
 | P | y | t | h | o | n |
 +---+---+---+---+---+---+
   0   1   2   3   4   5
  -6  -5  -4  -3  -2  -1

 +---+---+---+---+---+---+---+---+---+---+---+---+
 | P | y | t | h | o | n | P | y | t | h | o | n |
 +---+---+---+---+---+---+---+---+---+---+---+---+
  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5


问:
Scheduled Cloud Functions Firebase
I am trying to schedule a function to run based on DateTime object field in my Firestore database.

Example, I have a collection of events in the Database and each event has a DateTime field (Start time) for the start of the event. The event also has a list of users that are subscribed to the event.

Is there a way to use Cloud Functions to notify the subscribed users that the event is about to start at the start time of the event or 5 or 10 mins before the event starts?

I am currently using Cloud Functions for notification and its working fine but that is based writes to specific portions of the database, not time event.

Thank you in advance.

答:
The only way to do this with a scheduled Cloud Function for this sort of work is to schedule it run periodically (every 1 minute is the most often), and query for documents that meet the criteria for when you want to send the notification at the moment that the function is currently running.  This means you should be looking for documents where the time is in the 5-10 minute near future from the current time.

You can't use scheduled Cloud Functions to delay some work to happen later.  But you can integrate with Cloud Tasks for that.

Title: Scheduled Cloud Functions Firebase


问:
Deserialize variable saved on GPU on GPU
I saved the parameter variable on my computer (equipped with GPU and CUDA). The weights were saved with the GPU mode. Then when attempting to load the weights on the same computer, I still get an error:

```<code>RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location='cpu' to map your storages to the CPU.
</code>```

The issue is related to the fact that torch.cuda.is_available() returns False.

The issue disappears after restarting the computer but then reappears after some time.

答:
Try adding map_location argument to torch.load, i.e.,modify your code

from torch.load(model_weights)

to torch.load(model_weights, map_location=torch.device('cuda:0'))

Body:
I saved the parameter variable on my computer (equipped with GPU and CUDA). The weights were saved with the GPU mode. Then when attempting to load the weights on the same computer, I still get an error:

RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location='cpu' to map your storages to the CPU.

The issue is related to the fact that torch.cuda.is_available() returns False.

The issue disappears after restarting the computer but then reappears after some time.


问:
Is there a way to enable calendar option as an input in V4 chat bot C# other than using Adaptive cards?
Is there a way to enable Date and Time input in other words calendar options in Chat Bot without using Adaptive cards as i understand from below link the Adaptive cards are not supported in all channels except for Microsoft channels.

How to add custom choices displayed through Prompt options inside Cards & trigger actions on choice click in BOT V4 using c#?

I had enabled Adaptive cards using the below inputs:

[BotFramework]: How to capture/extract the values submitted through Adaptive card rendered in C# Web Chat bot in a waterfall dialog?

Then my query: Is how can i enable the Date Time input in a BOT other than using Adaptive Cards like Hero Card or any other card(except Adaptive card)?

Language: C#
SDK: V4
Channel: Web Chat Channel
Deployed in : Azure

If there is a way i request you to please provide a detailed step by step guide as I am new to BOT and coding.

Thanks & Regards
-ChaitanyaNG

I could not try the below from GitHub as this is related to React but my code is written in C# and SDK V4 from AZURE:

https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/10.a.customization-card-components

Expected Result: Display calendar option and time option to select date and time such that i can capture the input values and proceed with my process in waterfall dialog C#

Actual Result: Unable to achieve it as Adaptive card seems to be not supported in Web Chat channel and only in Microsoft Channels like Skype

@mrichardson-MSFT: Thanks for all the help till now.

Issue Description:

I have BOT program with multiple waterfall dialog classes the last dialog class
STEP #1: I am showing the adaptive card with two date and time inputs one for start and another for Stop
Actual Result:
The adaptive is displayed successfully both in Emulator and web chat channel without any issues
STEP #2: When i click on SetSchedule on the Adaptive card displayed in step 1 the values should be captured in step #2 and displayed on the screen
Actual Result:
Works perfectly fine in emulator but not in Web Chat channel bot. I get an error in the Webchat Channel BOT.
Please find the HTML file for accessing bot, the waterfall dialog class and the Adaptive card json file attached for reference. Along with it please find the error screenshot attached in webchat channel for reference.

Can you please guide me to solve this issue as you done for the sign in issue? Request your immediate help a this is blocking my work.

Thanks & Regards
-ChaitanyaNG

```<code>using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace EchoBot.Dialogs
{
    public class Adaptivecarddialog : WaterfallDialog
    {
        public const string cards = @"./AdaptiveCard.json";

        public Adaptivecarddialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
            : base(dialogId, steps)
        {
            AddStep(async (stepContext, cancellationToken) =>
            {
                var cardAttachment = CreateAdaptiveCardAttachment(cards);

                var reply = stepContext.Context.Activity.CreateReply();
                reply.Attachments = new List<Attachment>() { cardAttachment };

                await stepContext.Context.SendActivityAsync(reply, cancellationToken);
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        // You can comment this out if you don't want to display any text. Still works.
                    }
                };

                // Display a Text Prompt and wait for input
                return await stepContext.PromptAsync(nameof(TextPrompt), opts);
            });

            AddStep(async (stepContext, cancellationToken) =>
            {
                var res = stepContext.Result.ToString();
                dynamic jobject = JsonConvert.DeserializeObject(res);
                string NewStartDateTime = jobject.Startdate + " " + jobject.Starttime;
                string NewStopDateTime = jobject.Stopdate + " " + jobject.Stoptime;
                await stepContext.Context.SendActivityAsync($"StartDateTime:{NewStartDateTime}", cancellationToken: cancellationToken);
                await stepContext.Context.SendActivityAsync($"StopDateTime:{NewStopDateTime}", cancellationToken: cancellationToken);

                return await stepContext.EndDialogAsync();
            });

        }

        public static new string Id => "Adaptivecarddialog";

        public static Adaptivecarddialog Instance { get; } = new Adaptivecarddialog(Id);

        public static Attachment CreateAdaptiveCardAttachment(string filePath)
        {
            var adaptiveCardJson = File.ReadAllText(filePath);
            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content = JsonConvert.DeserializeObject(adaptiveCardJson),
            };
            return adaptiveCardAttachment;
        }
    }
}
</code>```

{
  "type": "AdaptiveCard",
  "body": [
    {
      "type": "TextBlock",
      "id": "Start date text",
      "separator": true,
      "text": "Schedule Start DateTime:"
    },
    {
      "type": "Input.Date",
      "id": "Startdate",
      "separator": true,
      "value": "2019-05-24"
    },
    {
      "type": "Input.Time",
      "id": "Starttime",
      "separator": true,
      "value": "08:00"
    },
    {
      "type": "TextBlock",
      "id": "Stop date text",
      "separator": true,
      "text": "Schedule Stop DateTime:"
    },
    {
      "type": "Input.Date",
      "id": "Stopdate",
      "separator": true,
      "value": "2019-05-25"
    },
    {
      "type": "Input.Time",
      "id": "Stoptime",
      "separator": true,
      "value": "08:00"
    }
  ],
  "actions": [
    {
      "type": "Action.Submit",
      "id": "SubmitBtn",
      "title": "SetSchedule"
    }
  ],
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.0"
}```
</div>
</div>
</p>

<p>Error Messages when tried twice:
<strong>First Try</strong>
{error: {code: "BotError", message: "Failed to send activity: bot timed out"}, httpStatusCode: 504}
error: {code: "BotError", message: "Failed to send activity: bot timed out"}
code: "BotError"
message: "Failed to send activity: bot timed out"
httpStatusCode: 504</p>

<p><img src="https://i.stack.imgur.com/fShIc.jpg" alt="enter image description here"><strong>SecondTry</strong>
{error: {code: "BotError", message: "Failed to send activity: bot returned an error"},…}
error: {code: "BotError", message: "Failed to send activity: bot returned an error"}
code: "BotError"
message: "Failed to send activity: bot returned an error"
httpStatusCode: 500</p>

<p>HTML File:</p>

```<!DOCTYPE html>

    <title>Web Chat: Custom style options</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

```

答:
The short answer is that this feature isn't available. Adaptive Cards are the best route to go for any kind of UI-based date/time picker. And yes, Adaptive Cards are fully supported on Microsoft channels (which includes WebChat), and less so on other channels.

The best option you have would be to use the DateTime Prompt.

There's a lot of different methods with varying complexity to implement this, but the Virtual Assistant Calendar Skill uses it pretty extensively. Its DatePrompt and TimePrompt might be good places to start.

CoreBot also has a DateResolverDialog that may help and is a little easier to understand.

DateTime is pretty complex to work with in chat bots because "Wednesday at 4 o'clock" can mean Wednesday at 4AM or 4PM. The Timex Resolution Sample should provide additional ideas for dealing with this, if you're going with a text-based input.

It's possible that this isn't working for you in WebChat because of your other issue. I just tested the Date and Time inputs for this card and it's working:

```<code>{
    "type": "AdaptiveCard",
    "actions": [{
        "type": "Action.Submit",
        "id": "submit",
        "title": "Submit"
    }],
    "body": [
        {
            "type": "Input.Date",
            "id": "date",
            "title": "New Input.Toggle"
        },
        {
            "type": "Container",
            "items": [
                {
                    "type": "Input.Time",
                    "id": "time",
                    "title": "New Input.Toggle"
                }
            ]
        }
    ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.0"
}
</code>```

Body:
Is there a way to enable Date and Time input in other words calendar options in Chat Bot without using Adaptive cards as i understand from below link the Adaptive cards are not supported in all channels except for Microsoft channels.

How to add custom choices displayed through Prompt options inside Cards & trigger actions on choice click in BOT V4 using c#?

I had enabled Adaptive cards using the below inputs:

[BotFramework]: How to capture/extract the values submitted through Adaptive card rendered in C# Web Chat bot in a waterfall dialog?

Then my query: Is how can i enable the Date Time input in a BOT other than using Adaptive Cards like Hero Card or any other card(except Adaptive card)?

Language: C#
SDK: V4
Channel: Web Chat Channel
Deployed in : Azure

If there is a way i request you to please provide a detailed step by step guide as I am new to BOT and coding.

Thanks & Regards
-ChaitanyaNG

I could not try the below from GitHub as this is related to React but my code is written in C# and SDK V4 from AZURE:

https://github.com/microsoft/BotFramework-WebChat/tree/master/samples/10.a.customization-card-components

Expected Result: Display calendar option and time option to select date and time such that i can capture the input values and proceed with my process in waterfall dialog C#

Actual Result: Unable to achieve it as Adaptive card seems to be not supported in Web Chat channel and only in Microsoft Channels like Skype

@mrichardson-MSFT: Thanks for all the help till now.

Issue Description:

I have BOT program with multiple waterfall dialog classes the last dialog class
STEP #1: I am showing the adaptive card with two date and time inputs one for start and another for Stop
Actual Result:
The adaptive is displayed successfully both in Emulator and web chat channel without any issues
STEP #2: When i click on SetSchedule on the Adaptive card displayed in step 1 the values should be captured in step #2 and displayed on the screen
Actual Result:
Works perfectly fine in emulator but not in Web Chat channel bot. I get an error in the Webchat Channel BOT.
Please find the HTML file for accessing bot, the waterfall dialog class and the Adaptive card json file attached for reference. Along with it please find the error screenshot attached in webchat channel for reference.

Can you please guide me to solve this issue as you done for the sign in issue? Request your immediate help a this is blocking my work.

Thanks & Regards
-ChaitanyaNG

using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Schema;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace EchoBot.Dialogs
{
    public class Adaptivecarddialog : WaterfallDialog
    {
        public const string cards = @"./AdaptiveCard.json";

        public Adaptivecarddialog(string dialogId, IEnumerable<WaterfallStep> steps = null)
            : base(dialogId, steps)
        {
            AddStep(async (stepContext, cancellationToken) =>
            {
                var cardAttachment = CreateAdaptiveCardAttachment(cards);

                var reply = stepContext.Context.Activity.CreateReply();
                reply.Attachments = new List<Attachment>() { cardAttachment };

                await stepContext.Context.SendActivityAsync(reply, cancellationToken);
                var opts = new PromptOptions
                {
                    Prompt = new Activity
                    {
                        Type = ActivityTypes.Message,
                        // You can comment this out if you don't want to display any text. Still works.
                    }
                };

                // Display a Text Prompt and wait for input
                return await stepContext.PromptAsync(nameof(TextPrompt), opts);
            });

            AddStep(async (stepContext, cancellationToken) =>
            {
                var res = stepContext.Result.ToString();
                dynamic jobject = JsonConvert.DeserializeObject(res);
                string NewStartDateTime = jobject.Startdate + " " + jobject.Starttime;
                string NewStopDateTime = jobject.Stopdate + " " + jobject.Stoptime;
                await stepContext.Context.SendActivityAsync($"StartDateTime:{NewStartDateTime}", cancellationToken: cancellationToken);
                await stepContext.Context.SendActivityAsync($"StopDateTime:{NewStopDateTime}", cancellationToken: cancellationToken);

                return await stepContext.EndDialogAsync();
            });

        }

        public static new string Id => "Adaptivecarddialog";

        public static Adaptivecarddialog Instance { get; } = new Adaptivecarddialog(Id);

        public static Attachment CreateAdaptiveCardAttachment(string filePath)
        {
            var adaptiveCardJson = File.ReadAllText(filePath);
            var adaptiveCardAttachment = new Attachment()
            {
                ContentType = "application/vnd.microsoft.card.adaptive",
                Content = JsonConvert.DeserializeObject(adaptiveCardJson),
            };
            return adaptiveCardAttachment;
        }
    }
}

{
  "type": "AdaptiveCard",
  "body": [
    {
      "type": "TextBlock",
      "id": "Start date text",
      "separator": true,
      "text": "Schedule Start DateTime:"
    },
    {
      "type": "Input.Date",
      "id": "Startdate",
      "separator": true,
      "value": "2019-05-24"
    },
    {
      "type": "Input.Time",
      "id": "Starttime",
      "separator": true,
      "value": "08:00"
    },
    {
      "type": "TextBlock",
      "id": "Stop date text",
      "separator": true,
      "text": "Schedule Stop DateTime:"
    },
    {
      "type": "Input.Date",
      "id": "Stopdate",
      "separator": true,
      "value": "2019-05-25"
    },
    {
      "type": "Input.Time",
      "id": "Stoptime",
      "separator": true,
      "value": "08:00"
    }
  ],
  "actions": [
    {
      "type": "Action.Submit",
      "id": "SubmitBtn",
      "title": "SetSchedule"
    }
  ],
  "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
  "version": "1.0"
}

Error Messages when tried twice:
First Try
{error: {code: "BotError", message: "Failed to send activity: bot timed out"}, httpStatusCode: 504}
error: {code: "BotError", message: "Failed to send activity: bot timed out"}
code: "BotError"
message: "Failed to send activity: bot timed out"
httpStatusCode: 504

SecondTry
{error: {code: "BotError", message: "Failed to send activity: bot returned an error"},…}
error: {code: "BotError", message: "Failed to send activity: bot returned an error"}
code: "BotError"
message: "Failed to send activity: bot returned an error"
httpStatusCode: 500

HTML File:

<!DOCTYPE html>

    <title>Web Chat: Custom style options</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

Body:
The short answer is that this feature isn't available. Adaptive Cards are the best route to go for any kind of UI-based date/time picker. And yes, Adaptive Cards are fully supported on Microsoft channels (which includes WebChat), and less so on other channels.

The best option you have would be to use the DateTime Prompt.

There's a lot of different methods with varying complexity to implement this, but the Virtual Assistant Calendar Skill uses it pretty extensively. Its DatePrompt and TimePrompt might be good places to start.

CoreBot also has a DateResolverDialog that may help and is a little easier to understand.

DateTime is pretty complex to work with in chat bots because "Wednesday at 4 o'clock" can mean Wednesday at 4AM or 4PM. The Timex Resolution Sample should provide additional ideas for dealing with this, if you're going with a text-based input.

It's possible that this isn't working for you in WebChat because of your other issue. I just tested the Date and Time inputs for this card and it's working:

{
    "type": "AdaptiveCard",
    "actions": [{
        "type": "Action.Submit",
        "id": "submit",
        "title": "Submit"
    }],
    "body": [
        {
            "type": "Input.Date",
            "id": "date",
            "title": "New Input.Toggle"
        },
        {
            "type": "Container",
            "items": [
                {
                    "type": "Input.Time",
                    "id": "time",
                    "title": "New Input.Toggle"
                }
            ]
        }
    ],
    "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
    "version": "1.0"
}


问:
router navigate causing information to disappear
So I have a
 on a page, which displays "users", their full names, statuses and buttons to change statuses.

I have three buttons: "Accept", "Reject" and "Ambiguous". Each of these buttons have functions, which look like this:

```<code>onAcceptUser(user: UserModel) {
    const data = Utils.cloneObject(user, UserModel);

    data.status = UserStatusEnum.Accept;

    this.userService.userStatusUpdate(data).subscribe(c => {
      user.status = data.status
    });
}
</code>```

When clicking a row, the information for the corresponding user is displayed(it's displayed on the same page on the other side of the table) and for this I use router.navigate()(router is injected).

```<code>onSelectUser(event) {
    const user = event.data.user;

    let url = ['user-reports/user-list', this.userListId, 'user', user.userId];

    this.router.navigate(url);
}
</code>```

Problem:

When I change the status of my user two things might happen.

Everything will happen as planned.

Everything will happen as planned, but all the information about the user will disappear visually.

When the second option occurs, this is where things get blurry for me:

If I then select the other user, the last selected one will be displayed and I get an error:

Same thing happens when I just select, then deselect the row and after that I select the other row.

I don't know what is going on, some other answers said that something was wrong with routing, but I think in my case it is fine:

```<code>{
    path: 'user-list/:listid',
    component: ViewUserListComponent,
    children: [
      {
        path: 'user/:id',
        component: UserViewEditComponent
      }
    ]
 }
</code>```

Questions:

Why is this error happening?!

What can I do?!

答: Would you mind adding html to let me look at the whole picture?</p>

Body:
So I have a
 on a page, which displays "users", their full names, statuses and buttons to change statuses.

I have three buttons: "Accept", "Reject" and "Ambiguous". Each of these buttons have functions, which look like this:

onAcceptUser(user: UserModel) {
    const data = Utils.cloneObject(user, UserModel);

    data.status = UserStatusEnum.Accept;

    this.userService.userStatusUpdate(data).subscribe(c => {
      user.status = data.status
    });
}

When clicking a row, the information for the corresponding user is displayed(it's displayed on the same page on the other side of the table) and for this I use router.navigate()(router is injected).

onSelectUser(event) {
    const user = event.data.user;

    let url = ['user-reports/user-list', this.userListId, 'user', user.userId];

    this.router.navigate(url);
}

Problem:

When I change the status of my user two things might happen.

Everything will happen as planned.

Everything will happen as planned, but all the information about the user will disappear visually.

When the second option occurs, this is where things get blurry for me:

If I then select the other user, the last selected one will be displayed and I get an error:

Same thing happens when I just select, then deselect the row and after that I select the other row.

I don't know what is going on, some other answers said that something was wrong with routing, but I think in my case it is fine:

{
    path: 'user-list/:listid',
    component: ViewUserListComponent,
    children: [
      {
        path: 'user/:id',
        component: UserViewEditComponent
      }
    ]
 }

Questions:

Why is this error happening?!

What can I do?!


问:
Invalid SQL type: sqlKind = UNINITIALIZED error is shown
```<code>    String s1 = PasswordText4.getText();
    String s2 = ConfirmText4.getText();
    String s3 = NameText4.getText();
    String s4 = UsernameText4.getText();
    String s5 = jLabel16.getText();

    if (PasswordText4.getText().equals(ConfirmText4.getText()) && s1.length() != 0 && s3.length() != 0 && s1.length() >= 4 && s2.length() >= 4) {
        try {
            String sql
                    = "BEGIN"
                    + "UPDATE LOGIN SET USERNAME = ?, PASSWORD = ?, NAME = ?"
                    + "WHERE USERNAME = ?;"
                    + "commit;"
                    + "END;";
            CallableStatement cstmt = conn.prepareCall(sql);
            cstmt.setString(1, UsernameText4.getText());
            cstmt.setString(2, PasswordText4.getText());
            cstmt.setString(3, NameText4.getText());
            cstmt.setString(4, jLabel16.getText());

            //System.out.println(jLabel16.getText());

            int dialogButton = JOptionPane.YES_NO_OPTION;
            int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure you want to update?", "Warning", dialogButton);
            if (dialogResult == JOptionPane.YES_OPTION) {
                cstmt.execute();
                JOptionPane.showMessageDialog(null, "Information Updated");
                jLabel15.setText(NameText4.getText());
                jLabel16.setText(UsernameText4.getText());
                jLabel17.setText(PasswordText4.getText());
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }
</code>```

What's wrong with this code? When I try to update my data, the Invalid SQL type:

sqlKind = UNINITIALIZED error is shown.

Please help me find solution for my problem.

Thank you in advance for answer.

答:
Friends,

I too encountered the same issue when I execute a sequence of SQL queries (few queries are commented thru my Java program

Solution: Remove all commented SQL lines and then execute, you will not get "UNINITIALIED" error any more.

Body:
    String s1 = PasswordText4.getText();
    String s2 = ConfirmText4.getText();
    String s3 = NameText4.getText();
    String s4 = UsernameText4.getText();
    String s5 = jLabel16.getText();

    if (PasswordText4.getText().equals(ConfirmText4.getText()) && s1.length() != 0 && s3.length() != 0 && s1.length() >= 4 && s2.length() >= 4) {
        try {
            String sql
                    = "BEGIN"
                    + "UPDATE LOGIN SET USERNAME = ?, PASSWORD = ?, NAME = ?"
                    + "WHERE USERNAME = ?;"
                    + "commit;"
                    + "END;";
            CallableStatement cstmt = conn.prepareCall(sql);
            cstmt.setString(1, UsernameText4.getText());
            cstmt.setString(2, PasswordText4.getText());
            cstmt.setString(3, NameText4.getText());
            cstmt.setString(4, jLabel16.getText());

            //System.out.println(jLabel16.getText());

            int dialogButton = JOptionPane.YES_NO_OPTION;
            int dialogResult = JOptionPane.showConfirmDialog(null, "Are you sure you want to update?", "Warning", dialogButton);
            if (dialogResult == JOptionPane.YES_OPTION) {
                cstmt.execute();
                JOptionPane.showMessageDialog(null, "Information Updated");
                jLabel15.setText(NameText4.getText());
                jLabel16.setText(UsernameText4.getText());
                jLabel17.setText(PasswordText4.getText());
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }

What's wrong with this code? When I try to update my data, the Invalid SQL type:

sqlKind = UNINITIALIZED error is shown.

Please help me find solution for my problem.

Thank you in advance for answer.


问:
How to indicate which model's field raised a ValidationError?
Let's say I have a simple Django model:

```<code>class Transaction(models.Model):
    description = models.CharField('description', max_length=150,
                                   validators=[MinLengthValidator(2, 'Description\'s min length is 2'), ])
    amount = models.DecimalField('amount', max_digits=10, decimal_places=2,
                                 validators=[MinValueValidator(1, 'Min value is 1'), ])
    user = models.ForeignKey(User)

    # to trigger model fields' validation
    def clean(self, *args, **kwargs):
        super(Transaction, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Transaction, self).save(*args, **kwargs)
</code>```

And I'd like to have a unit test, which precisely checks whether ValidationError is raised by description field and not by amount field (or any other).

So I have this piece of test, which in a primitive way checks if description field is present in e.exception:

```<code>def test_model_requires_description_min_2_characters(self):
    with self.assertRaises(ValidationError) as e:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    err_dict = eval(str(e.exception))
    self.assertIn('description', err_dict.keys())
</code>```

But I don't really like to use eval() and I believe there is more elegant way to indicate the source of ValidationError. How can I do this?

EDIT: my model class also includes overriden clean() and save() methods, so validators are running fine.

答:
I would do something like this, ValidationError has an attribute error_dict that we can already use to test for this

```<code>def test_model_requires_description_min_2_characters(self):
    try:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    except ValidationError as e:
        # A ValidationError was raised, now we test to see if our field is in it
        self.assertIn('description', e.error_dict.keys())
    else:
        # No exception was raised, raise our own exception
        raise Exception('The test failed')
</code>```

Body:
Let's say I have a simple Django model:

class Transaction(models.Model):
    description = models.CharField('description', max_length=150,
                                   validators=[MinLengthValidator(2, 'Description\'s min length is 2'), ])
    amount = models.DecimalField('amount', max_digits=10, decimal_places=2,
                                 validators=[MinValueValidator(1, 'Min value is 1'), ])
    user = models.ForeignKey(User)

    # to trigger model fields' validation
    def clean(self, *args, **kwargs):
        super(Transaction, self).clean(*args, **kwargs)

    def save(self, *args, **kwargs):
        self.full_clean()
        super(Transaction, self).save(*args, **kwargs)

And I'd like to have a unit test, which precisely checks whether ValidationError is raised by description field and not by amount field (or any other).

So I have this piece of test, which in a primitive way checks if description field is present in e.exception:

def test_model_requires_description_min_2_characters(self):
    with self.assertRaises(ValidationError) as e:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    err_dict = eval(str(e.exception))
    self.assertIn('description', err_dict.keys())

But I don't really like to use eval() and I believe there is more elegant way to indicate the source of ValidationError. How can I do this?

EDIT: my model class also includes overriden clean() and save() methods, so validators are running fine.

Body:
I would do something like this, ValidationError has an attribute error_dict that we can already use to test for this

def test_model_requires_description_min_2_characters(self):
    try:
        Transaction.objects.create(description='a', amount="50", user=self.user1)
    except ValidationError as e:
        # A ValidationError was raised, now we test to see if our field is in it
        self.assertIn('description', e.error_dict.keys())
    else:
        # No exception was raised, raise our own exception
        raise Exception('The test failed')


问:
What is the use of the hackers.txt file?

First

No I am not asking you to teach me hacking, I am just curious about this file and its content.

My journey

When I dived into the new HTML5 Boilerplate I came accross the humans.txt. I googled for it and I came at this site http://humanstxt.org/.

Immediately my attention went to this picture:

Do I read this correctly? Hackers.txt?

So I resumed my journey in google and stopped at this articles

When I started reading this I had the feeling that its about the difference between Hackers and Crackers. Later I got the feeling that I'm might be wrong and that this place is that this hackers.txt file is a sort of guestbook for hackers?

Also other examples about hackers.txt files I found here

Some files contain code, others have just hurtfull information.

Now I'm realy confused, guestbook, hack tutorials or just history?

Question

What is the use of this hackers.txt file?

答:
Commonly known as Eduardo Vela, Eduardo A. Vela Nava (or sirdarckcat on Github and Twitter) has been a Security Engineer at Google since 2010. (He currently has the role of Product Security Response Team Lead).

As other security experts before him, he pondered the issue of effectively communicating the details of a site's vulnerability reward program to white hat hackers/pen-testers.

One specific such person is Chema Alonso (also on Twitter).

He is well-known enough to warrant a Spanish Wikipedia entry

Between 2005 and 2011 Alonso was awarded the Microsoft Most Valuable Professional Award for Enterprise Security 6 years in a row. That should tell you something about his "skillz".

On February 3rd 2011 Alonso wrote about his frustrations regarding the topic of communication between the administrators and/or developers of a site and hackers.

He proposes a similar initiative as humans.txt but for hackers. As he mentions this hackers.txt initiative in his blog-post.

In April 2011 The humanstxt.org website got a new design which includes the image which mentions the hackers.txt file.

At this point, I must sadly submit to conjecture, but... consider:

The team behind humans.txt are all from Spain (mostly Barcelona)

At this point Alonso is already quite well known in the Spanish developer community

Would it be such a far stretch to imagine that they got to know of each other's efforts?

On May 14th 2014 Vela, already working at Google, commented on a blog-post by Alonso. It is most likely that they had further contact in a professional setting. Whether or not thay extively shared their idea's regarding anything related to hackers.txt is unknown.

On July 6th 2017 Vela posted a question to this extent on twitter:

How about we create a /hackers.txt that says whether something is in scope or not of a vulnerability reward program and where to report it?

Subsequently, an empty git repository was created for hackerstxt.org on github
and an email thread was opened at Google Groups to discuss this idea further.

On August 13 2017, Edwin Foudil (or EdOverflow on Github and Twitter) created a git repository for security.txt on Github and responded to the mailing list:

I have published a similar project to the one being discussed in this group (https://github.com/EdOverflow/security-txt) and would love to get some of your feedback and ideas.

The project is the equivalent of robots.txt, but for defining a security policy. Companies can add a security.txt to their website and define clear guidelines of what security researchers must do when they discover a security issue. security.txt also allows bug bounty programs to add their scope there. security.txt uses a similar syntax to robots.txt, which should make it easier for machines to parse.

He was, in part, inspired by an open-source project he was working on at the time called GratiPay. GratiPay had a SECURITY.txt file since 2013.

His inspiration also drew from the SECURITY.md files that more and more open-source projects were adding to their repositories.

On September 10th 2017, Foudil submitted a first draft for security.txt to the Internet Engineering Task Force.

On September 14th 2017 Alonso wrote a blog post with the title (translated from Spanish) "Security.TXT an IETF draft for my Hackers.TXT".

Beyond the title, Alonso does not allude to the fact that his 2011 idea was the origin of the draft but he does state his approval of the effort.

On February 3rd 2018, the mail group was informed to concede to security.txt and Vela tweeted that Google had already implemented one.

Further information

Details and a nifty tool to generate your own security.txt can be found at
https://securitytxt.org/

Adoptation

Even though the RFC is still in draft, the standard is already being adopted quite well by major players on the web.

Besides the security.txt at Google, there is also one on the website of:

1password

BBC

bit.ly - http://bit.ly/security.txt (can't be linked because StackOverflow blacklist the use of common link shorteners in posts)

CERT NZ

DailyMotion

Dropbox

Facebook

Github

haveibeenpwned

NodeJs

NPM

Open SSL

Shopify

(Feel free to add more from well-known sites, if you find 'm)


问:
Using Docker in interactive mode using an official Microsoft .Net Core SDK image
I'm trying to enter interactive mode using an official Microsoft .Net Core image and use typical .Net commands such as 'dotnet build', but all I get is an '>' cursor. What am I doing wrong?

I'm using the following command:

```<code>docker run -it -v $(pwd):/app' -w '/app' -p 8000:80 mcr.microsoft.com/dotnet/core/sdk /bin/bash
</code>```

I was hoping to get a root command prompt, but all I'm getting is '>'

答:
You are misssing the initial quote here:

```<code>-v $(pwd):/app'
</code>```

That should be:

```<code>-v "$(pwd):/app"
</code>```

It needs to be a double-quote for $(pwd) to be evaluated correctly by the shell. Otherwise the shell will send the literal $(pwd) which is not a valid path.

Body:
I'm trying to enter interactive mode using an official Microsoft .Net Core image and use typical .Net commands such as 'dotnet build', but all I get is an '>' cursor. What am I doing wrong?

I'm using the following command:

docker run -it -v $(pwd):/app' -w '/app' -p 8000:80 mcr.microsoft.com/dotnet/core/sdk /bin/bash

I was hoping to get a root command prompt, but all I'm getting is '>'

Body:
You are misssing the initial quote here:

-v $(pwd):/app'

That should be:

-v "$(pwd):/app"

It needs to be a double-quote for $(pwd) to be evaluated correctly by the shell. Otherwise the shell will send the literal $(pwd) which is not a valid path.


问:
Clicking on button shifts entire page a few pixels to the left
I'm trying to fix an issue where when a user clicks a button it causes the entire page to shift to the left. The issue only seems to appear when the browser is maximized.

You can try it yourself here: https://professionallyspeaking.oct.ca/exemplary.aspx

Click on the "Great Teachers- Alphabetical +" button to see the shift in action.

答:
The page is adding a vertical scroll bar when the content height exceeds that of the browser window. It is default behaviour, but if the shift seems odd to you, the only way to "fix" it is to force the scroll bar on the  when the content doesn't fill the page, by adding the following css:

```<code>body{
  overflow-y: scroll;
}
</code>```

Body:
The page is adding a vertical scroll bar when the content height exceeds that of the browser window. It is default behaviour, but if the shift seems odd to you, the only way to "fix" it is to force the scroll bar on the <body> when the content doesn't fill the page, by adding the following css:

body{
  overflow-y: scroll;
}


问:
Trying to Buy an Item from an External Website with Post Request
I'm trying to buy an item from an external website using their private API and the python requests module. The problem is that for the request form data it wants the cart items which basically I construct manually to be the exact same as the cart would make them, they are exactly the same as far as I can tell. When I post the request I get an error from the server saying that it isn't getting any cart items.

I've tried matching the headers encoding(the original request uses application/x-www-form-urlencoded), using requests JSON kwarg instead of data, and also adding items to the cart manually, fetching them, and then sending those.  I'm thinking it may be that I need to encode them first, but I have no clue to what.

Here's some code

login_data = {'email': 'email', 'password': 'password123'}
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                         'Chrome/74.0.3729.157 Safari/537.36',
           'Content-type': 'application/x-www-form-urlencoded'}

s = requests.Session()
login_response = s.post(url, data=login_data, headers=headers)  # login
data_charge = {'cartItems':[cartItems], # This is a list of dicts
               'key': 'licensing',
               'nonce': credit_card_token,  # I have to get the card token which works fine
               'cardholder': 'John Smith'}
purchase_response = s.post(url_charge, data=data_charge, headers=headers)
```

The purchase_response.json() content returns "content":[{"error":"No cart items sent."}].
It should respond with order numbers and all the items that were purchased.

Let me know if I'm missing any important details.
Thank you!

答:
Try replacing:

```<code>purchase_response = s.post(url_charge, data=data_charge, headers=headers)
</code>```

With:

```<code>purchase_response = s.post(url_charge, json=data_charge, headers=headers)
</code>```

hope this helps

Body:
I'm trying to buy an item from an external website using their private API and the python requests module. The problem is that for the request form data it wants the cart items which basically I construct manually to be the exact same as the cart would make them, they are exactly the same as far as I can tell. When I post the request I get an error from the server saying that it isn't getting any cart items.

I've tried matching the headers encoding(the original request uses application/x-www-form-urlencoded), using requests JSON kwarg instead of data, and also adding items to the cart manually, fetching them, and then sending those.  I'm thinking it may be that I need to encode them first, but I have no clue to what.

Here's some code

login_data = {'email': 'email', 'password': 'password123'}
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) '
                         'Chrome/74.0.3729.157 Safari/537.36',
           'Content-type': 'application/x-www-form-urlencoded'}

s = requests.Session()
login_response = s.post(url, data=login_data, headers=headers)  # login
data_charge = {'cartItems':[cartItems], # This is a list of dicts
               'key': 'licensing',
               'nonce': credit_card_token,  # I have to get the card token which works fine
               'cardholder': 'John Smith'}
purchase_response = s.post(url_charge, data=data_charge, headers=headers)

The purchase_response.json() content returns "content":[{"error":"No cart items sent."}].
It should respond with order numbers and all the items that were purchased.

Let me know if I'm missing any important details.
Thank you!

Body:
Try replacing:

purchase_response = s.post(url_charge, data=data_charge, headers=headers)

With:

purchase_response = s.post(url_charge, json=data_charge, headers=headers)

hope this helps


问:
can't scape a value from Beautifulsoup in python
I am creating a website where I display the current wind. when I go to https://www.windguru.cz/station/219 (and click on inspect element at the max:{wind}) I can see this:

```<code><span class="wgs_wind_max_value">12</span>
</code>```

the 12 is the value I need but when I try to scrape it with bs4 and requests, this appears as output:

```<code><span class="wgs_wind_max_value"></span>
</code>```

as you can see there is no '12' value.
can someone help me with that?

```<code>from bs4 import BeautifulSoup
import requests

page = requests.get('https://www.windguru.cz/3323')
soup = BeautifulSoup(page.content, "lxml")
table = soup.find_all("span",{"class","wgs_wind_max_value"})
print(table)
</code>```

答:
Use the same API as page does to get json to populate those values. Notice the querystring construction passed to the API.</p>

```<code>import requests

headers = {'Referer' : 'https://www.windguru.cz/station/219'}
r = requests.get('https://www.windguru.cz/int/iapi.php?q=station_data_current&id_station=219&date_format=Y-m-d%20H%3Ai%3As%20T&_mha=f4d18b6c', headers = headers).json()
print(r)
print(r['wind_max'])
</code>```

Body:
I am creating a website where I display the current wind. when I go to https://www.windguru.cz/station/219 (and click on inspect element at the max:{wind}) I can see this:

12

the 12 is the value I need but when I try to scrape it with bs4 and requests, this appears as output:

as you can see there is no '12' value.
can someone help me with that?

from bs4 import BeautifulSoup
import requests

page = requests.get('https://www.windguru.cz/3323')
soup = BeautifulSoup(page.content, "lxml")
table = soup.find_all("span",{"class","wgs_wind_max_value"})
print(table)

Body:
Use the same API as page does to get json to populate those values. Notice the querystring construction passed to the API.

import requests

headers = {'Referer' : 'https://www.windguru.cz/station/219'}
r = requests.get('https://www.windguru.cz/int/iapi.php?q=station_data_current&id_station=219&date_format=Y-m-d%20H%3Ai%3As%20T&_mha=f4d18b6c', headers = headers).json()
print(r)
print(r['wind_max'])


问:
Make some submodules optional in git
We have a git repo that is serving multiple projects/targets.
In addition there are 3 submodules for separately developed modules that are referenced and pulled into the workspace.

Are are going to have a 4th repo for a module that will be needed only for a specific project and only specific engineers have permissions to access it.
Is there any way to make this 4th submodule optional or it's all-or-nothing?

Thanks a lot,

Guy.

答:
You can use something like following in your .gitmodules:

```<code>[submodule "secrets"]
    path = secrets
    url = ./secrets
</code>```

Then, after checkout, you can clone the optional repositories like:

```<code>rm -rf secrets
git clone git://... secrets
</code>```

Title: Make some submodules optional in git

Body:
You can use something like following in your .gitmodules:

[submodule "secrets"]
    path = secrets
    url = ./secrets

Then, after checkout, you can clone the optional repositories like:

rm -rf secrets
git clone git://... secrets


问:
How to return an HTML <div> tag from a javascript function in React?
I am working on a React application where I am trying to render text on the screen when a button is clicked. I have defined a function onButtonClick which gets triggered whenever the button is clicked. However, the HTML that I am returning from the function is not rendered on the screen. I am in the learning stages of React so please excuse me if the question seems silly.</p>

```<code>class App extends Component {

constructor() {
  super();

  this.state = {
    blockno:0

  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1})
  return(
      <div>
          <h3>Some text</h3>
      </div>
    );

}

render() {
return(
    <div>
        <Button onButtonClick={this.OnButtonClick}/>
    </div>
    );
}

}

</code>```

答:
The value is being returned, but the framework/browser/etc. has no reason to do anything with that value.

Try thinking about this a different way, a "more React way".  You don't want to return the value to be rendered, you want to update state.  Something like this:

```<code>constructor() {
  super();

  this.state = {
    blockno:0,
    showDiv: false // <-- note the new property in state
  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1, showDiv: true})
}
</code>```

Now you're not returning anything, but rather updating the state of the component.  Then in your render method you conditionally render the UI based on the current state:

```<code>render() {
  return(
    <div>
        <Button onButtonClick={this.OnButtonClick}/>
        {
            this.state.showDiv
              ?
                <div>
                  <h3>Some text</h3>
                </div>
             : ''
        }
    </div>
    );
}
</code>```

The click handler doesn't modify the page, it just modifies the state of the component you're writing.  The render method is responsible for rendering the UI based on that state.  Any time state changes, render will be called again to re-render the output.

(Note: It's not 100% clear if this is exactly the functionality you're looking for in the UI, since it's not really clear what you're trying to build.  But the point here is to illustrate how to update state and render output in React.  Your logic can be tweaked as needed from there.)

Body:
I am working on a React application where I am trying to render text on the screen when a button is clicked. I have defined a function onButtonClick which gets triggered whenever the button is clicked. However, the HTML that I am returning from the function is not rendered on the screen. I am in the learning stages of React so please excuse me if the question seems silly.

class App extends Component {

constructor() {
  super();

  this.state = {
    blockno:0

  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1})
  return(

Some text

    );

}

render() {
return(

        <Button onButtonClick={this.OnButtonClick}/>

    );
}

}

Body:
The value is being returned, but the framework/browser/etc. has no reason to do anything with that value.

Try thinking about this a different way, a "more React way".  You don't want to return the value to be rendered, you want to update state.  Something like this:

constructor() {
  super();

  this.state = {
    blockno:0,
    showDiv: false // <-- note the new property in state
  }
}

OnButtonClick = () => {
  this.setState({blockno: this.state.blockno + 1, showDiv: true})
}

Now you're not returning anything, but rather updating the state of the component.  Then in your render method you conditionally render the UI based on the current state:

render() {
  return(
    <div>
        <Button onButtonClick={this.OnButtonClick}/>
        {
            this.state.showDiv
              ?
                <div>
                  <h3>Some text</h3>
                </div>
             : ''
        }
    </div>
    );
}

The click handler doesn't modify the page, it just modifies the state of the component you're writing.  The render method is responsible for rendering the UI based on that state.  Any time state changes, render will be called again to re-render the output.

(Note: It's not 100% clear if this is exactly the functionality you're looking for in the UI, since it's not really clear what you're trying to build.  But the point here is to illustrate how to update state and render output in React.  Your logic can be tweaked as needed from there.)


答:
You can start from the following code:

```<code>makelist(A,N,0,M,[X]) :- X is mod(A^N,M).
makelist(A,N,K,M,[X|L]) :-
        Max is N + K,
        N <  Max,
        N1 is  N + 1,
        K1 is K-1,
        X is mod(A^N, M),
        makelist(A, N1, K1, M, L).
</code>```

And then apply more constraints such as M>= 2.

Title: Prolog - make list

Body:
Given the argument makelist(A,N,K,M,L) :- , should expand ,and it should return true if A,N,K,M,L>0 Integer numbers with M>=2 and L list :

[A^N mod M , A^(N+1) mod M , A^(N+2) mod M , ... , A*(N+K) mod M]

Expected results :

| ?- makelist(10,2,1,10000,L).
L = [100,1000]
| ?- makelist(2,6,10,100,L).
L = [64,28,56,12,24,48,96,92,84,68,36]
| ?- makelist(12345678,3,8,100,L).
L = [52,56,68,4,12,36,8,24,72]
| ?- makelist(2,3000,5,7,L).
L = [1,2,4,1,2,4]
| ?- makelist(2,555000,5,17,L).
L = [1,2,4,8,16,15]
| ?- makelist(2,3000000,5,21,L).
L = [1,2,4,8,16,11]
| ?- makelist(142857,98765432,9,100,L).
L = [1,57,49,93,1,57,49,93,1,57]

i thought a starting would be implementing the K element of exponent (N+K) by taking the numbers from 0 to K

bet(N, M, K) :- N =< M, K = N.
bet(N, M, K) :- N < M, N1 is N+1, bet(N1, M, K).

makelist(A,N,K,M,L) :- bet(0,K,(N+K)),

Body:
You can start from the following code:

makelist(A,N,0,M,[X]) :- X is mod(A^N,M).
makelist(A,N,K,M,[X|L]) :-
        Max is N + K,
        N <  Max,
        N1 is  N + 1,
        K1 is K-1,
        X is mod(A^N, M),
        makelist(A, N1, K1, M, L).

And then apply more constraints such as M>= 2.


问:
Populating stateless child component props from parent component state to display nested unordered list in React (with Firebase)
I'm probably missing something very simple here, but I can't get my code to run properly. I'm trying to display a nested unordered list of referenceListItems for every referenceList. The main question I guess is how do I pass the state variable referenceListItems into the child component ReferenceListItems?

```<code>const ReferencePage = () => (
  <div>
    <h1>Reference</h1>
    <Reference />
  </div>
);

class ReferenceBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      referenceLists: [],
      referenceListItems: [],
    };
  }

  componentDidMount() {
    this.onListenForReferenceLists();
    this.onListenForReferenceListItems();
  }

  onListenForReferenceLists() {
    this.setState({ loading: true });

    this.unsubscribeReferenceLists = this.props.firebase
      .referenceLists()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceLists = [];
          snapshot.forEach(doc =>
            referenceLists.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceLists: referenceLists,
            loading: false
          });
        } else {
          this.setState({ referenceLists: null, loading: false });
        }
    });
  }

  onListenForReferenceListItems() {
    this.unsubscribeReferenceListsItems = this.props.firebase
      .referenceListItems()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceListItems = [];
          snapshot.forEach(doc =>
            referenceListItems.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceListItems: referenceListItems,
            loading: false
          });
        } else {
          this.setState({ referenceListItems: null, loading: false });
        }
    });
  }

  componentWillUnmount() {
    this.unsubscribeReferenceLists();
    this.unsubscribeReferenceListsItems();
  }

  render() {
    const { referenceLists, referenceListItems, loading } = this.state;
    return (
      <div>
        {loading && <div>Loading ...</div>}
        {referenceLists ? (
          <ReferenceLists referenceLists={referenceLists} />
        ):(
          <div>There are no reference items ...</div>
        )}
      </div>
    );
  }
}

const Reference = withFirebase(ReferenceBase);

const ReferenceLists = ({ referenceLists }) => (
  <ul className="reference-lists">
    {referenceLists.map( referenceList => (
      <ReferenceList key={referenceList.uid} referenceList={referenceList} />
    ))}
  </ul>
);

const ReferenceList = ({ referenceList }) => (
  <li className="reference">
    <strong>{referenceList.userId}</strong> {referenceList.name}
    <ReferenceListItems />
  </li>
);

const ReferenceListItems =({ referenceListItems }) => (
  <ul className="reference-list-items">
    {referenceListItems.map( referenceListItem => (
      <ReferenceListItem key={referenceListItem.uid} referenceListItem={referenceListItem} />
    ))}
  </ul>
);

const ReferenceListItem = ({ referenceListItem }) => (
  <li className="reference-list-item">
    <strong>{referenceListItem.userId}</strong> {referenceListItem.name}
  </li>
);
</code>```

答:
By redeclaring referenceList

```<code>let referenceLists = [];
</code>```

it never gets set in your class. you either need to return the referenceLists inside the closure or set the class level variable in your callback

```<code>this.referenceLists.push({ ...doc.data(), uid: doc.id })
</code>```

Body:
I'm probably missing something very simple here, but I can't get my code to run properly. I'm trying to display a nested unordered list of referenceListItems for every referenceList. The main question I guess is how do I pass the state variable referenceListItems into the child component ReferenceListItems?

const ReferencePage = () => (

Reference

    <Reference />

);

class ReferenceBase extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      referenceLists: [],
      referenceListItems: [],
    };
  }

  componentDidMount() {
    this.onListenForReferenceLists();
    this.onListenForReferenceListItems();
  }

  onListenForReferenceLists() {
    this.setState({ loading: true });

    this.unsubscribeReferenceLists = this.props.firebase
      .referenceLists()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceLists = [];
          snapshot.forEach(doc =>
            referenceLists.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceLists: referenceLists,
            loading: false
          });
        } else {
          this.setState({ referenceLists: null, loading: false });
        }
    });
  }

  onListenForReferenceListItems() {
    this.unsubscribeReferenceListsItems = this.props.firebase
      .referenceListItems()
      .onSnapshot(snapshot => {
        if (snapshot.size) {
          let referenceListItems = [];
          snapshot.forEach(doc =>
            referenceListItems.push({ ...doc.data(), uid: doc.id }),
          );
          this.setState({
            referenceListItems: referenceListItems,
            loading: false
          });
        } else {
          this.setState({ referenceListItems: null, loading: false });
        }
    });
  }

  componentWillUnmount() {
    this.unsubscribeReferenceLists();
    this.unsubscribeReferenceListsItems();
  }

  render() {
    const { referenceLists, referenceListItems, loading } = this.state;
    return (

        {loading &&
Loading ...
}
        {referenceLists ? (
          <ReferenceLists referenceLists={referenceLists} />
        ):(

There are no reference items ...

        )}

    );
  }
}

const Reference = withFirebase(ReferenceBase);

const ReferenceLists = ({ referenceLists }) => (

    {referenceLists.map( referenceList => (
      <ReferenceList key={referenceList.uid} referenceList={referenceList} />
    ))}

);

const ReferenceList = ({ referenceList }) => (

    {referenceList.userId} {referenceList.name}
    <ReferenceListItems />

);

const ReferenceListItems =({ referenceListItems }) => (

    {referenceListItems.map( referenceListItem => (
      <ReferenceListItem key={referenceListItem.uid} referenceListItem={referenceListItem} />
    ))}

);

const ReferenceListItem = ({ referenceListItem }) => (

    {referenceListItem.userId} {referenceListItem.name}

);

Body:
By redeclaring referenceList

let referenceLists = [];

it never gets set in your class. you either need to return the referenceLists inside the closure or set the class level variable in your callback

this.referenceLists.push({ ...doc.data(), uid: doc.id })


问:
Always Running Python Script on Google Cloud
I want to host a python script on Google Cloud which would run indefinitely.

Which Google Cloud Products can be used to achieve this reliably and economically?

is this possible on AppEngine?

答:
It is possible on appengine, try shifting to instance type backend in the app.yaml<br>
You can learn more about backend/frontend instances here </p>

Body:
It is possible on appengine, try shifting to instance type backend in the app.yaml

You can learn more about backend/frontend instances here