问:
xpath returning empty text when web-scraping in r
I'm trying to scrape information from https://www.kff.org/interactive/subsidy-calculator. For instance, put state=California, zip=90001, income=20000, no coverage, 1 people, 1 adult, no children, age=21, no tobacco.

We get the following:
https://www.kff.org/interactive/subsidy-calculator/#state=ca&zip=94704&income-type=dollars&income=20000&employer-coverage=0&people=1&alternate-plan-family=individual&adult-count=1&adults%5B0%5D%5Bage%5D=21&adults%5B0%5D%5Btobacco%5D=0&child-count=0

I would like to get the numbers for "estimated financial help" and "your cost for a silver plan" (they are bolded-blue in the "Results" grey box, for some reason I can't upload the screenshot). When I use the xpath for the numbers, I get back empty string. This is not the case if I were to retrieve some other text (not in the grey box). I wonder what could be wrong with this. I have attached code below. Please forgive me if this is a stupid question since I'm very new to web-scraping. Thank you!

state = tolower('CA')
zip = 94704
income = 20000
people = 1
adult = 1
children = 0

url = paste0("https://www.kff.org/interactive/subsidy-calculator/#state=", state, "&zip=", zip, "&income-type=dollars&income=", income, "&employer-coverage=0&people=", people, "&alternate-plan-family=individual&adult-count=", adult, "&adults%5B0%5D%5Bage%5D=21&adults%5B0%5D%5Btobacco%5D=0&child-count=", children)

# This returns empty string
r = read_html(url) %>%
      html_nodes(xpath ='//*[@id="subsidy-calculator-new"]/div[5]/div/div/dl/dd[1]/span') %>% html_text()

# This returns "Number of children (20 and younger) enrolling in Marketplace coverage", a line that's not in the grey box.
r = read_html(url) %>%
  html_nodes(xpath = '//*[@id="subsidy-form"]/div[2]/div[3]/div[3]/p') %>%
  html_text()
```

答:
The values are generated through scripts that run on the page. Your current method won't allow for this hence your result. You are likely better off using a method which allows scripts to run such as RSelenium.

The form you complete #subsidy-form feeds values into a template in a script tag #results-template. The associated calculations are covered in this script https://www.kff.org/wp-content/themes/kaiser-foundation-2016/interactives/subsidy-calculator/2019/calculator.js?ver=1.7.7  where you will find the logic and the pre-set values such as poverty lines per year.

The simplest quick view is probably to inspect the javascript variables when the new SubsidyCalculator object is created to process the form i.e. js starting with var sc = new SubsidyCalculator. You could 'reverse engineer' those variables with your values plus the values returned from the json below which I think, but haven't confirmed, feed the 6 variables that begin with kff_sc, according to zipcode, into the calculator e.g. silver: kff_sc.silver . You get an idea of the ballpark figures given there are default values given at top of script.

Figures in relation to zipcode are retrieved from this: https://www.kff.org/wp-content/themes/kaiser-foundation-2016/interactives/subsidy-calculator/2019/json/zips/94.json  where the last two numbers before .json are the first two numbers of zipcode. You can determine this from the input validation script: https://www.kff.org/wp-content/themes/kaiser-foundation-2016/interactives/subsidy-calculator/2019/shared.js?ver=1.7.7

var bucket = $( this ).val().substring( 0, 2 );
  if ( kff_sc.buckets[bucket] ) return;
  $.ajax( '/wp-content/themes/vip/kaiser-foundation-2016/interactives/subsidy-calculator/2019/json/zips/' + bucket + '.json', ```

The first two digits determine the bucket.

All in all you could likely implement your own calculator but you would be re-inventing the wheel. Seems easier to just automate the browser and then extract the resultant values.

Body:
The values are generated through scripts that run on the page. Your current method won't allow for this hence your result. You are likely better off using a method which allows scripts to run such as RSelenium.

The form you complete #subsidy-form feeds values into a template in a script tag #results-template. The associated calculations are covered in this script https://www.kff.org/wp-content/themes/kaiser-foundation-2016/interactives/subsidy-calculator/2019/calculator.js?ver=1.7.7  where you will find the logic and the pre-set values such as poverty lines per year.

The simplest quick view is probably to inspect the javascript variables when the new SubsidyCalculator object is created to process the form i.e. js starting with var sc = new SubsidyCalculator. You could 'reverse engineer' those variables with your values plus the values returned from the json below which I think, but haven't confirmed, feed the 6 variables that begin with kff_sc, according to zipcode, into the calculator e.g. silver: kff_sc.silver . You get an idea of the ballpark figures given there are default values given at top of script.

Figures in relation to zipcode are retrieved from this: https://www.kff.org/wp-content/themes/kaiser-foundation-2016/interactives/subsidy-calculator/2019/json/zips/94.json  where the last two numbers before .json are the first two numbers of zipcode. You can determine this from the input validation script: https://www.kff.org/wp-content/themes/kaiser-foundation-2016/interactives/subsidy-calculator/2019/shared.js?ver=1.7.7

var bucket = $( this ).val().substring( 0, 2 );
  if ( kff_sc.buckets[bucket] ) return;
  $.ajax( '/wp-content/themes/vip/kaiser-foundation-2016/interactives/subsidy-calculator/2019/json/zips/' + bucket + '.json',

The first two digits determine the bucket.

All in all you could likely implement your own calculator but you would be re-inventing the wheel. Seems easier to just automate the browser and then extract the resultant values.


来源: stackexchange

问:
insert for $out failed
My documents in my DB are stored an array of results for each user.

Data types:

```<code>age: {type: Number},
gender: {type: String},
result: [{ game: String,time: Number, level: Number, mistakes: Number,moves: Number }]
</code>```

In order to analyze my data I want to unwind the results,
For example the following document:

```<code>{"_id":"5ce58a662f6fcb3b782013e3","age":10,"gender":"Male","result":[{"_id":"5ce58a662f6fcb3b782013e9","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e8","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e7","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e6","game":"memory","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e5","game":"memory","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e4","game":"memory","time":20,"level":3,"mistakes":5,"moves":50}],"__v":0}]
</code>```

will be devided to a 6 docs, and stored on a new collection with the same userId.

I've tried to run:

```<code> db.userschemes.aggregate([{ "$unwind": "$result"},{ $out : "newcollection" }])
</code>```

but got the following:

assert: command failed: {
          "ok" : 0,
          "errmsg" : "insert for $out failed: { connectionId: 1, err: \"E11000 dup licate key error index: vpdata.tmp.agg_out.2.$id dup
  key: { : ObjectId('5ce58a 662f6fcb3b782013e3') }\", code: 11000, n: 0,
  ok: 1.0 }",
          "code" : 16996 } : aggregate failed
  _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:16:14
  assert.commandWorked@src/mongo/shell/assert.js:290:5
  DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5
  @(shell):1:1

2019-05-26T19:04:05.395+0200 E QUERY    [thread1] Error: command
  failed: {
          "ok" : 0,
          "errmsg" : "insert for $out failed: { connectionId: 1, err: \"E11000 dup licate key error index: vpdata.tmp.agg_out.2.$id dup
  key: { : ObjectId('5ce58a 662f6fcb3b782013e3') }\", code: 11000, n: 0,
  ok: 1.0 }",
          "code" : 16996 } : aggregate failed :
  _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:16:14
  assert.commandWorked@src/mongo/shell/assert.js:290:5
  DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5
  @(shell):1:1

How can I avoid this? I'm understand the issue that I have multiple docs with the same id but this is exactly what I want.

Any workaround?

答:
Using $out you're creating new collection named newcollection. MongoDB requires every _id to be unique. That constraint cannot be dropped, so as you're $unwind-ing an array there might be duplicated _id values in a final result set.

As a workaround you can introduce $project stage and move current _id into different field so that there will be no unique constraint on it. MongoDB will generate new _id values for all documents, try:

```<code>db.userschemes.aggregate([
    { "$unwind": "$result"},
    { $addFields: { userId : "$_id" } },
    { $project: { _id: 0 } },
    { $out : "newcollection" }
])
</code>```

ContentLicense: CC BY-SA 4.0

Title: insert for $out failed

Body:
My documents in my DB are stored an array of results for each user.

Data types:

age: {type: Number},
gender: {type: String},
result: [{ game: String,time: Number, level: Number, mistakes: Number,moves: Number }]

In order to analyze my data I want to unwind the results,
For example the following document:

{"_id":"5ce58a662f6fcb3b782013e3","age":10,"gender":"Male","result":[{"_id":"5ce58a662f6fcb3b782013e9","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e8","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e7","game":"puzzle","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e6","game":"memory","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e5","game":"memory","time":20,"level":3,"mistakes":5,"moves":50},{"_id":"5ce58a662f6fcb3b782013e4","game":"memory","time":20,"level":3,"mistakes":5,"moves":50}],"__v":0}]

will be devided to a 6 docs, and stored on a new collection with the same userId.

I've tried to run:

 db.userschemes.aggregate([{ "$unwind": "$result"},{ $out : "newcollection" }])

but got the following:

assert: command failed: {
          "ok" : 0,
          "errmsg" : "insert for $out failed: { connectionId: 1, err: \"E11000 dup licate key error index: vpdata.tmp.agg_out.2.$id dup
  key: { : ObjectId('5ce58a 662f6fcb3b782013e3') }\", code: 11000, n: 0,
  ok: 1.0 }",
          "code" : 16996 } : aggregate failed
  _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:16:14
  assert.commandWorked@src/mongo/shell/assert.js:290:5
  DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5
  @(shell):1:1

2019-05-26T19:04:05.395+0200 E QUERY    [thread1] Error: command
  failed: {
          "ok" : 0,
          "errmsg" : "insert for $out failed: { connectionId: 1, err: \"E11000 dup licate key error index: vpdata.tmp.agg_out.2.$id dup
  key: { : ObjectId('5ce58a 662f6fcb3b782013e3') }\", code: 11000, n: 0,
  ok: 1.0 }",
          "code" : 16996 } : aggregate failed :
  _getErrorWithCode@src/mongo/shell/utils.js:25:13 doassert@src/mongo/shell/assert.js:16:14
  assert.commandWorked@src/mongo/shell/assert.js:290:5
  DBCollection.prototype.aggregate@src/mongo/shell/collection.js:1312:5
  @(shell):1:1

How can I avoid this? I'm understand the issue that I have multiple docs with the same id but this is exactly what I want.

Any workaround?

Body:
Using $out you're creating new collection named newcollection. MongoDB requires every _id to be unique. That constraint cannot be dropped, so as you're $unwind-ing an array there might be duplicated _id values in a final result set.

As a workaround you can introduce $project stage and move current _id into different field so that there will be no unique constraint on it. MongoDB will generate new _id values for all documents, try:

db.userschemes.aggregate([
    { "$unwind": "$result"},
    { $addFields: { userId : "$_id" } },
    { $project: { _id: 0 } },
    { $out : "newcollection" }
])


问:
Find the minimum of a sorted and shifted array with better than O(n) time complexity
We have an assignment to search for the minimum element of a sorted array that is shifted to the right afterwards. For example: [1, 5, 6, 19, 56, 101] becomes [19, 56, 101, 1, 5, 6]. The method should be implemented using a divide and conquer algorithm and it should have a better asymptotic time complexity than O(n).
EDIT: I forgot to add that the elements int the array are unique.

I already implemented a method and wanted to ask if this is better than O(n) and if there are ways to improve my method.

```<code>public class FindMinimum {
    public void findMinimum(int[] arr) {

        // the recursive method ends when the length of the array is smaller than 2
        if (arr.length < 2) {
            return;
        }

        int mid = arr.length / 2;

        /*
         * if the array length is greater or the same as two, check if the middle
         * element is smaller as the element before that. And print the middle element
         * if it's true.
         */
        if (arr.length >= 2) {
            if (arr[mid - 1] > arr[mid]) {
                System.out.println("Minimum: " + arr[mid]);
                return;
            }
        }

        /*
         * separate the array in two sub-arrays through the middle and start the method
         * with those two arrays again.
         */
        int[] leftArr = new int[mid];
        int[] rightArr = new int[arr.length - mid];
        for (int i = 0; i < mid; i++) {
            leftArr[i] = arr[i];
        }
        for (int i = mid; i < arr.length; i++) {
            rightArr[i - mid] = arr[i];
        }
        findMinimum(leftArr);
        findMinimum(rightArr);
    }
}
</code>```

答:
In Java you could use a List because than you can create a Sublist. </p>

```<code>private Integer findMinimum(List<Integer> list) {
    if (list.size() < 2)
        return list.get(0);

    int mid = list.size() / 2;

    // create left and right list
    List<Integer> leftList = list.subList(0, mid);
    List<Integer> rightList = list.subList(mid, list.size());

    if (leftList.get(leftList.size() - 1) <= rightList.get(rightList.size() - 1))
        return findMin(leftList);
    else
        return findMin(rightList);
}
</code>```

<p>When you create a Sublist with Java there is no copy. So to create a new Sublist takes a complexity of O(1).
So the function has a complexity of O(logn). </p>

Body:
We have an assignment to search for the minimum element of a sorted array that is shifted to the right afterwards. For example: [1, 5, 6, 19, 56, 101] becomes [19, 56, 101, 1, 5, 6]. The method should be implemented using a divide and conquer algorithm and it should have a better asymptotic time complexity than O(n).
EDIT: I forgot to add that the elements int the array are unique.

I already implemented a method and wanted to ask if this is better than O(n) and if there are ways to improve my method.

public class FindMinimum {
    public void findMinimum(int[] arr) {

        // the recursive method ends when the length of the array is smaller than 2
        if (arr.length < 2) {
            return;
        }

        int mid = arr.length / 2;

        /*
         * if the array length is greater or the same as two, check if the middle
         * element is smaller as the element before that. And print the middle element
         * if it's true.
         */
        if (arr.length >= 2) {
            if (arr[mid - 1] > arr[mid]) {
                System.out.println("Minimum: " + arr[mid]);
                return;
            }
        }

        /*
         * separate the array in two sub-arrays through the middle and start the method
         * with those two arrays again.
         */
        int[] leftArr = new int[mid];
        int[] rightArr = new int[arr.length - mid];
        for (int i = 0; i < mid; i++) {
            leftArr[i] = arr[i];
        }
        for (int i = mid; i < arr.length; i++) {
            rightArr[i - mid] = arr[i];
        }
        findMinimum(leftArr);
        findMinimum(rightArr);
    }
}

Body:
In Java you could use a List because than you can create a Sublist.

private Integer findMinimum(List<Integer> list) {
    if (list.size() < 2)
        return list.get(0);

    int mid = list.size() / 2;

    // create left and right list
    List<Integer> leftList = list.subList(0, mid);
    List<Integer> rightList = list.subList(mid, list.size());

    if (leftList.get(leftList.size() - 1) <= rightList.get(rightList.size() - 1))
        return findMin(leftList);
    else
        return findMin(rightList);
}

When you create a Sublist with Java there is no copy. So to create a new Sublist takes a complexity of O(1).
So the function has a complexity of O(logn).


问:
Make autotools add --std=c11 to CFLAGS
There is no mention of a AC_PROG_CC_C11 analogue to AC_PROG_CC_C99.

How can I get my autotools project to put --std=c11 into CFLAGS?

答:
```<code>AC_DEFUN([AX_CHECK_STDC],
[AX_CHECK_COMPILE_FLAG([-std=gnu11],
    [AX_APPEND_FLAG([-std=gnu11])],
    [AX_CHECK_COMPILE_FLAG([-std=c11],
        [AX_APPEND_FLAG([-std=c11])],
        [AX_CHECK_COMPILE_FLAG([-std=c99],
            [AX_APPEND_FLAG([-std=c99])],
            [AC_MSG_ERROR([C compiled does not support at least C99!])])
        ])
    ])
])
</code>```

Output:

```<code>checking whether C compiler accepts -std=gnu11... no
checking whether C compiler accepts -std=c11... no
checking whether C compiler accepts -std=c99... yes
</code>```

(when building using shit Microchip xc16 PIC compiler)

ContentLicense: CC BY-SA 3.0

Title: Make autotools add --std=c11 to CFLAGS

Body:
AC_DEFUN([AX_CHECK_STDC],
[AX_CHECK_COMPILE_FLAG([-std=gnu11],
    [AX_APPEND_FLAG([-std=gnu11])],
    [AX_CHECK_COMPILE_FLAG([-std=c11],
        [AX_APPEND_FLAG([-std=c11])],
        [AX_CHECK_COMPILE_FLAG([-std=c99],
            [AX_APPEND_FLAG([-std=c99])],
            [AC_MSG_ERROR([C compiled does not support at least C99!])])
        ])
    ])
])

Output:

checking whether C compiler accepts -std=gnu11... no
checking whether C compiler accepts -std=c11... no
checking whether C compiler accepts -std=c99... yes

(when building using shit Microchip xc16 PIC compiler)


问:
Cannot import name 'Merge' from 'keras.layers'
I have try run a code but I find a problem with merge layers of Keras. I'm using python 3 and keras 2.2.4

This is de code part of code

import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Embedding, TimeDistributed, Dense, RepeatVector, Merge, Activation
from keras.preprocessing import image, sequence
import cPickle as pickle

    def create_model(self, ret_model = False):

        image_model = Sequential()
        image_model.add(Dense(EMBEDDING_DIM, input_dim = 4096, activation='relu'))
        image_model.add(RepeatVector(self.max_length))

        lang_model = Sequential()
        lang_model.add(Embedding(self.vocab_size, 256, input_length=self.max_length))
        lang_model.add(LSTM(256,return_sequences=True))
        lang_model.add(TimeDistributed(Dense(EMBEDDING_DIM)))

        model = Sequential()
        model.add(Merge([image_model, lang_model], mode='concat'))
        model.add(LSTM(1000,return_sequences=False))
        model.add(Dense(self.vocab_size))
        model.add(Activation('softmax'))

        print ("Model created!")

```

<p>This is the message of error</p>

```from keras.layers import LSTM, Embedding, TimeDistributed, Dense, RepeatVector, Merge, Activation
ImportError: cannot import name 'Merge' from 'keras.layers'
```

答:
Merge is not supported in Keras +2. Instead, you need to use Concatenate layer:

```<code>merged = Concatenate()([x1, x2]) # NOTE: the layer is first constructed and then it's called on its input
</code>```

or it's equivalent functional interface concatenate (starting with lowercase c):

```<code>merged = concatenate([x1,x2]) # NOTE: the input of layer is passed as an argument, hence named *functional interface*
</code>```

If you are interested in other forms of merging, e.g. addition, subtration, etc., then you can use the relevant layers. See the documentation for a comprehensive list of merge layers.

Body:
I have try run a code but I find a problem with merge layers of Keras. I'm using python 3 and keras 2.2.4

This is de code part of code

import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Embedding, TimeDistributed, Dense, RepeatVector, Merge, Activation
from keras.preprocessing import image, sequence
import cPickle as pickle

    def create_model(self, ret_model = False):

        image_model = Sequential()
        image_model.add(Dense(EMBEDDING_DIM, input_dim = 4096, activation='relu'))
        image_model.add(RepeatVector(self.max_length))

        lang_model = Sequential()
        lang_model.add(Embedding(self.vocab_size, 256, input_length=self.max_length))
        lang_model.add(LSTM(256,return_sequences=True))
        lang_model.add(TimeDistributed(Dense(EMBEDDING_DIM)))

        model = Sequential()
        model.add(Merge([image_model, lang_model], mode='concat'))
        model.add(LSTM(1000,return_sequences=False))
        model.add(Dense(self.vocab_size))
        model.add(Activation('softmax'))

        print ("Model created!")

This is the message of error

from keras.layers import LSTM, Embedding, TimeDistributed, Dense, RepeatVector, Merge, Activation
ImportError: cannot import name 'Merge' from 'keras.layers'

Body:
Merge is not supported in Keras +2. Instead, you need to use Concatenate layer:

merged = Concatenate()([x1, x2]) # NOTE: the layer is first constructed and then it's called on its input

or it's equivalent functional interface concatenate (starting with lowercase c):

merged = concatenate([x1,x2]) # NOTE: the input of layer is passed as an argument, hence named *functional interface*

If you are interested in other forms of merging, e.g. addition, subtration, etc., then you can use the relevant layers. See the documentation for a comprehensive list of merge layers.


问:
Running "go get github.com/libp2p/go-libp2p" results in error messages
I'm a beginner with golang. When trying to run "go get github.com/libp2p/go-libp2p" I get an error message that prevents me from being able to run tests & benchmarks.

Here is the error:

github.com/libp2p/go-libp2p/p2p/host/routed

../../libp2p/go-libp2p/p2p/host/routed/routed.go:153:20: cannot use
  rh.host.Mux() (type
  "github.com/libp2p/go-libp2p-core/protocol".Switch) as type
  *multistream.MultistreamMuxer in return argument: need type assertion ../../libp2p/go-libp2p/p2p/host/routed/routed.go:190:5: cannot use
  (*RoutedHost)(nil) (type *RoutedHost) as type
  "github.com/libp2p/go-libp2p-core/host".Host in assignment:
          *RoutedHost does not implement "github.com/libp2p/go-libp2p-core/host".Host (wrong type for Mux
  method)
                  have Mux() *multistream.MultistreamMuxer
                  want Mux() "github.com/libp2p/go-libp2p-core/protocol".Switch

github.com/libp2p/go-libp2p/p2p/host/basic

../../libp2p/go-libp2p/p2p/host/basic/basic_host.go:145:32: cannot use
  h (type *BasicHost) as type host.Host in argument to
  identify.NewIDService:
          *BasicHost does not implement host.Host (wrong type for Mux method)
                  have Mux() *multistream.MultistreamMuxer
                  want Mux() "github.com/libp2p/go-libp2p-core/protocol".Switch
  ../../libp2p/go-libp2p/p2p/host/basic/basic_host.go:172:32: cannot use
  h (type *BasicHost) as type host.Host in argument to
  ping.NewPingService:
          *BasicHost does not implement host.Host (wrong type for Mux method)
                  have Mux() *multistream.MultistreamMuxer
                  want Mux() "github.com/libp2p/go-libp2p-core/protocol".Switch

I don't understand why the error messages. It looks like go-libp2p does not compile. any ideas?

答:
They've been performing a refactor, which resulted in this issue being submitted.

A solution was provided:


问:
Java [unchecked] unchecked case warning
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

```<code>Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }
</code>```

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?

答:
It is not "uncatched", but "unchecked". The JVM cannot tell at runtime, i.e. when the cast is done, whether the ArrayList really contains Dot elements.

This warning occurs whenever you cast from a raw type to a generic type. If you are sure the cast is ok, you can suppress the warning with annotation

```<code>@SuppressWarnings("unchecked")
</code>```

For this, it is good to encapsulate the cast in a small, separate method.

Title: Java [unchecked] unchecked case warning

Body:
Ok, I've been looking around and done alot of google searching, but I still can't find a way to avoid this warning.

Integer result = chooser.showOpenDialog(null);
if (result.equals(0))
{
    String tempHolder = chooser.getSelectedFile().getPath();
    filenameLoad = new File(tempHolder);
    filenameSave = filenameLoad;
    FileInputStream fis = null;
    ObjectInputStream in = null;
    try
    {
        fis = new FileInputStream(filenameLoad);
        in = new ObjectInputStream(fis);;
    }
    catch(IOException ex)
    {
        ex.printStackTrace();
    }

    try
    {
        loadFile = (ArrayList<Dot>)in.readObject();
    }
    catch(IOException ex)
    {
        System.out.println("Cast fail");
    }
    catch(ClassNotFoundException ex)
    {
        System.out.println("Cast fail");
    }
    catch (ClassCastException ex)
    {
        System.out.println("Cast fail");
    }

    try
    {
        in.close();
    }
    catch(Exception ex)
    {
        System.out.println("failed to close in");
    }
    save.setEnabled(true);
      gpanel.setDotList(loadFile);
  }

It gives me the warning at the line loadFile = (ArrayList)in.readObject();  I've added in the catchs so i'm not sure why it still says its uncatched.  Any help?  thanks?

Body:
It is not "uncatched", but "unchecked". The JVM cannot tell at runtime, i.e. when the cast is done, whether the ArrayList really contains Dot elements.

This warning occurs whenever you cast from a raw type to a generic type. If you are sure the cast is ok, you can suppress the warning with annotation

@SuppressWarnings("unchecked")

For this, it is good to encapsulate the cast in a small, separate method.


问:
C Structures Explain push_vlan = (struct vlan_header *)((uint8_t *)new_eth + eth_size);
Can someone explain what is line of code does

```<code>struct name* push_tag = (struct name *)((uint8_t *)name2 + int_size);
</code>```

where name and name2 are different structures .

答:
Taking a clue from your heading that this is networking code, what you are likely looking at is a packet decoder.   In this case, it has noticed that the ethernet frame (wikipedia) has had a vlan header pre-pended to it.  The code is skipping past this header to inspect the encapsulated packet.

Somebody pointed out that this is the dreaded Undefined Behaviour.  I am not certain whether the observation that virtually all systems code, including the internet, relies on what is now Undefined Behaviour speak more about the integrity of the worlds computers and networks or the delusional belief that standards bodies are somehow beyond reproach.   I have been on standards working groups; and am living evidence that they aren't that bright.

Body:
Can someone explain what is line of code does

struct name* push_tag = (struct name *)((uint8_t *)name2 + int_size);

where name and name2 are different structures .


问:
How to install api-platform in existing symfony 3.4 application without flex?
I try to install api-platform on an existing Symfony 3.4 application, which is installed without flex.

When I try to install it with composer require api-platform/core, an error occured:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install api-platform/core v2.4.3
    - Conclusion: don't install api-platform/core v2.4.2
    - Conclusion: don't install api-platform/core v2.4.1
    - Conclusion: remove symfony/symfony v3.4.21
    - Installation request for api-platform/core ^2.4 -> satisfiable by api-platform/core[v2.4.0, v2.4.1, v2.4.2, v2.4.3].
    - Conclusion: don't install symfony/symfony v3.4.21
    - api-platform/core v2.4.0 requires symfony/web-link ^4.1 -> satisfiable by symfony/web-link[v4.1.0, v4.1.1, v4.1.10, v4.1.11, v4.1.12, v4.1.2, v4.1.3, v4.1.4, v4.1.5, v4.1.6, v4.1.7, v4.1.8, v4.1.9, v4.2.0, v4.2.1, v4.2.2, v4.2.3, v4.2.4, v4.2.5, v4.2.6, v4.2.7, v4.2.8].
    - don't install symfony/web-link v4.1.0|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.1|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.10|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.11|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.12|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.2|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.3|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.4|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.5|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.6|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.7|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.8|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.9|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.0|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.1|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.2|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.3|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.4|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.5|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.6|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.7|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.8|don't install symfony/symfony v3.4.21
    - Installation request for symfony/symfony 3.4.21 -> satisfiable by symfony/symfony[v3.4.21].

Installation failed, reverting ./composer.json to its original content.
```

<p>This is my current composer require (and require-dev) parts:</p>

```    "require": {
        "php": ">=7.2",
        "ext-curl": "*",
        "ext-exif": "*",
        "ext-json": "*",
        "accord/mandrill-swiftmailer-bundle": "^1.3",
        "beberlei/DoctrineExtensions": "^1.0",
        "braincrafted/bootstrap-bundle": "^2.2",
        "bukashk0zzz/hellosign-bundle": "^1.0",
        "callr/sdk-php": "^0.11.1",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/doctrine-migrations-bundle": "^1.3",
        "doctrine/orm": "^2.5",
        "dopiaza/slack-exception-logger-bundle": "^2.0",
        "facebook/graph-sdk": "^5.6",
        "friendsofsymfony/oauth-server-bundle": "^1.6",
        "friendsofsymfony/rest-bundle": "^2.3",
        "friendsofsymfony/user-bundle": "2.0.*",
        "google/apiclient": "^2.2",
        "google/cloud-storage": "^1.10",
        "hpatoio/bitly-bundle": "^1.0",
        "incenteev/composer-parameter-handler": "^2.0",
        "jms/serializer-bundle": "^2.3",
        "knplabs/knp-paginator-bundle": "^2.7",
        "liip/imagine-bundle": "^1.9",
        "nelmio/api-doc-bundle": "^3.3",
        "nelmio/cors-bundle": "^1.5",
        "phobetor/rabbitmq-supervisor-bundle": "^3.1",
        "php-amqplib/rabbitmq-bundle": "^1.14",
        "predis/predis": "^1.1",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^5.0.0",
        "sentry/sentry-symfony": "^2.0",
        "snc/redis-bundle": "^2.0",
        "stof/doctrine-extensions-bundle": "^1.3",
        "symfony/assetic-bundle": "^2.8",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.6.4",
        "symfony/symfony": "3.4.21",
        "twig/extensions": "^1.5",
        "twig/twig": "^1.0||^2.0"
    },
    "require-dev": {
        "brianium/paratest": "^1.1",
        "doctrine/doctrine-fixtures-bundle": "^3.0",
        "escapestudios/symfony2-coding-standard": "3.x-dev",
        "friendsofphp/php-cs-fixer": "^2.14",
        "liip/functional-test-bundle": "^1.9",
        "phpmd/phpmd": "^2.6",
        "phpunit/phpunit": "^6",
        "sensio/generator-bundle": "^3.1",
        "squizlabs/php_codesniffer": "*",
        "symfony/phpunit-bridge": "^4.0"
    },
```

I can't find any way to solve my problem and the composer error is not really explicit, so I didn't understand what I missing.

答: It looks like api-platform/core ^2.4 is not compatible with symfony/symfony v3.4.21 because it requires symfony/web-link v4.1.0 and I'm pretty sure all symfony v4 branch bundles are for symfony 4, try using api-platform/core v2.2 it doesn't appear to have any dependencies on any strictly v4 branch bundle. https://github.com/api-platform/core/blob/2.2/composer.json

Body:
I try to install api-platform on an existing Symfony 3.4 application, which is installed without flex.

When I try to install it with composer require api-platform/core, an error occured:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: don't install api-platform/core v2.4.3
    - Conclusion: don't install api-platform/core v2.4.2
    - Conclusion: don't install api-platform/core v2.4.1
    - Conclusion: remove symfony/symfony v3.4.21
    - Installation request for api-platform/core ^2.4 -> satisfiable by api-platform/core[v2.4.0, v2.4.1, v2.4.2, v2.4.3].
    - Conclusion: don't install symfony/symfony v3.4.21
    - api-platform/core v2.4.0 requires symfony/web-link ^4.1 -> satisfiable by symfony/web-link[v4.1.0, v4.1.1, v4.1.10, v4.1.11, v4.1.12, v4.1.2, v4.1.3, v4.1.4, v4.1.5, v4.1.6, v4.1.7, v4.1.8, v4.1.9, v4.2.0, v4.2.1, v4.2.2, v4.2.3, v4.2.4, v4.2.5, v4.2.6, v4.2.7, v4.2.8].
    - don't install symfony/web-link v4.1.0|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.1|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.10|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.11|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.12|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.2|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.3|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.4|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.5|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.6|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.7|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.8|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.1.9|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.0|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.1|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.2|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.3|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.4|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.5|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.6|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.7|don't install symfony/symfony v3.4.21
    - don't install symfony/web-link v4.2.8|don't install symfony/symfony v3.4.21
    - Installation request for symfony/symfony 3.4.21 -> satisfiable by symfony/symfony[v3.4.21].

Installation failed, reverting ./composer.json to its original content.

This is my current composer require (and require-dev) parts:

    "require": {
        "php": ">=7.2",
        "ext-curl": "*",
        "ext-exif": "*",
        "ext-json": "*",
        "accord/mandrill-swiftmailer-bundle": "^1.3",
        "beberlei/DoctrineExtensions": "^1.0",
        "braincrafted/bootstrap-bundle": "^2.2",
        "bukashk0zzz/hellosign-bundle": "^1.0",
        "callr/sdk-php": "^0.11.1",
        "doctrine/doctrine-bundle": "^1.6",
        "doctrine/doctrine-migrations-bundle": "^1.3",
        "doctrine/orm": "^2.5",
        "dopiaza/slack-exception-logger-bundle": "^2.0",
        "facebook/graph-sdk": "^5.6",
        "friendsofsymfony/oauth-server-bundle": "^1.6",
        "friendsofsymfony/rest-bundle": "^2.3",
        "friendsofsymfony/user-bundle": "2.0.*",
        "google/apiclient": "^2.2",
        "google/cloud-storage": "^1.10",
        "hpatoio/bitly-bundle": "^1.0",
        "incenteev/composer-parameter-handler": "^2.0",
        "jms/serializer-bundle": "^2.3",
        "knplabs/knp-paginator-bundle": "^2.7",
        "liip/imagine-bundle": "^1.9",
        "nelmio/api-doc-bundle": "^3.3",
        "nelmio/cors-bundle": "^1.5",
        "phobetor/rabbitmq-supervisor-bundle": "^3.1",
        "php-amqplib/rabbitmq-bundle": "^1.14",
        "predis/predis": "^1.1",
        "sensio/distribution-bundle": "^5.0.19",
        "sensio/framework-extra-bundle": "^5.0.0",
        "sentry/sentry-symfony": "^2.0",
        "snc/redis-bundle": "^2.0",
        "stof/doctrine-extensions-bundle": "^1.3",
        "symfony/assetic-bundle": "^2.8",
        "symfony/monolog-bundle": "^3.1.0",
        "symfony/polyfill-apcu": "^1.0",
        "symfony/swiftmailer-bundle": "^2.6.4",
        "symfony/symfony": "3.4.21",
        "twig/extensions": "^1.5",
        "twig/twig": "^1.0||^2.0"
    },
    "require-dev": {
        "brianium/paratest": "^1.1",
        "doctrine/doctrine-fixtures-bundle": "^3.0",
        "escapestudios/symfony2-coding-standard": "3.x-dev",
        "friendsofphp/php-cs-fixer": "^2.14",
        "liip/functional-test-bundle": "^1.9",
        "phpmd/phpmd": "^2.6",
        "phpunit/phpunit": "^6",
        "sensio/generator-bundle": "^3.1",
        "squizlabs/php_codesniffer": "*",
        "symfony/phpunit-bridge": "^4.0"
    },

I can't find any way to solve my problem and the composer error is not really explicit, so I didn't understand what I missing.


问:
Question about ASM execution flow
I'm not sure how to interpret an ASM execution flow. Until now, all of the files I've looked at have had explicit jumps (Intel x86 AT&T syntax, i.e jmp or jl) to labels within the ASM file.

My question: what happens when you reach the end of a label without an explicit jump to some other label. Does execution continue into the next label?

Example:

```<code>foo:
    opcodes
    ...

nextLablel:
    moreopcodes
    ...
</code>```

After executing the opcodes under the 'foo' label, does the assembler move onto 'nextLablel'?

Thanks in advance!

答:
The labels are non existent to the actual code, so yes, if there is no branch, the code will execute naturally. The assembler will just continue with the code, ignoring any labels. The labels are just there as a convenient way to branching after a jmp, je and the likes.

If your code did not have any branches, you could still have as many labels as you wanted. They would not do anything and it would be a very bad practice, but you this illustrates the idea that they do not cause any problems with the natural code flow.

Title: Question about ASM execution flow

Body:
I'm not sure how to interpret an ASM execution flow. Until now, all of the files I've looked at have had explicit jumps (Intel x86 AT&T syntax, i.e jmp or jl) to labels within the ASM file.

My question: what happens when you reach the end of a label without an explicit jump to some other label. Does execution continue into the next label?

Example:

foo:
    opcodes
    ...

nextLablel:
    moreopcodes
    ...

After executing the opcodes under the 'foo' label, does the assembler move onto 'nextLablel'?

Thanks in advance!


问:
JQuery validation on not existing checkbox
I have a JQuery DataTable that has checkboxes to select items in it. I added j
JQuery validation such that you can't submit the form without having at least selected one checkbox. Here is what my validation looks like:

```<code>jQuery.validator.addMethod("noApplicationSelected", function(value, element, params) { return $('.cbDisplay').length != 0; },'{0}');
$('[name="cbDisplay"]').rules('add', { noApplicationSelected: ['No checkbox selected'] });
</code>```

Everything works fine but my problem is that if I for example add a filter in my DataTable search such that no entries are present (empty DataTable), and I try to submit the form, it submits even though I haven't selected any checkboxes.
The reason for that I think is because the validation can't bind the rules on the checkboxes because they do not exist.

How can I fix this problem?

Edit 1:
Would adding some validation that checks for whether the DataTable is empty and a checkbox is selected fix my problem? But the issue I see with that is what do I bind this validation to? I guess I could bind it to the select all/deselect all checkbox but that doesn't make sense

Edit 2:

Demo of the probelm: https://jsfiddle.net/mu79L32w/14/

答:
If you try to find the inputs/checkboxes inside the displayed document, you only get the rendered elements of the datatables-element. This means it is possible that you will not find any checkbox-element in the document if the filter of datatables is used. If a row is not displayed in the datatables-element it is removed from the rendered table and as a result all elements inside that row are also not available for a wrapping form-element.

But you can iterate over the data/rows of the DataTable-Object with javascript.

Here is an example on how to test if any checkbox is checked when the form submits by using jquery-validates submitHandler.

$(document).ready(function() {

  let table = $('#example').DataTable({
    "columns": [
      { "data": "column_a" },
      { "data": "column_b" }
    ]
  });

  function isAnythingChecked() {
    let foundChecked = false;
    let inputs = table.rows().nodes().to$().find('input');
    for (let input of inputs) {
      if (input.checked) foundChecked = true;
    }
    return foundChecked;
  }

  $("#myForm").validate({
    submitHandler: function(form) {
      if (isAnythingChecked()) {
        alert('Yeah! A checkbox is selected');
        //form.submit();
      } else {
        alert('Oh no! No checkbox selected');
      }
    }
  });

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.0/dist/jquery.validate.min.js"></script>

<link href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>

<form id="myForm">

  <table id="example" class="display" style="width:100%">
    <thead>
      <tr>
        <th>Column A</th>
        <th>Column B</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="checkbox"> Checkbox 1</td>
        <td>Test</td>
      </tr>
      <tr>
        <td><input type="checkbox"> Checkbox 2</td>
        <td>Lorem</td>
      </tr>
      <tr>
        <td><input type="checkbox"> Checkbox 3</td>
        <td>ipsum</td>
      </tr>
    </tbody>
  <table>

  <button id="btn" type="submit">Submit</button>

</form></code>```

Body:
I have a JQuery DataTable that has checkboxes to select items in it. I added j
JQuery validation such that you can't submit the form without having at least selected one checkbox. Here is what my validation looks like:

jQuery.validator.addMethod("noApplicationSelected", function(value, element, params) { return $('.cbDisplay').length != 0; },'{0}');
$('[name="cbDisplay"]').rules('add', { noApplicationSelected: ['No checkbox selected'] });

Everything works fine but my problem is that if I for example add a filter in my DataTable search such that no entries are present (empty DataTable), and I try to submit the form, it submits even though I haven't selected any checkboxes.
The reason for that I think is because the validation can't bind the rules on the checkboxes because they do not exist.

How can I fix this problem?

Edit 1:
Would adding some validation that checks for whether the DataTable is empty and a checkbox is selected fix my problem? But the issue I see with that is what do I bind this validation to? I guess I could bind it to the select all/deselect all checkbox but that doesn't make sense

Edit 2:

Demo of the probelm: https://jsfiddle.net/mu79L32w/14/

Body:
If you try to find the inputs/checkboxes inside the displayed document, you only get the rendered elements of the datatables-element. This means it is possible that you will not find any checkbox-element in the document if the filter of datatables is used. If a row is not displayed in the datatables-element it is removed from the rendered table and as a result all elements inside that row are also not available for a wrapping form-element.

But you can iterate over the data/rows of the DataTable-Object with javascript.

Here is an example on how to test if any checkbox is checked when the form submits by using jquery-validates submitHandler.

$(document).ready(function() {

  let table = $('#example').DataTable({
    "columns": [
      { "data": "column_a" },
      { "data": "column_b" }
    ]
  });

  function isAnythingChecked() {
    let foundChecked = false;
    let inputs = table.rows().nodes().to$().find('input');
    for (let input of inputs) {
      if (input.checked) foundChecked = true;
    }
    return foundChecked;
  }

  $("#myForm").validate({
    submitHandler: function(form) {
      if (isAnythingChecked()) {
        alert('Yeah! A checkbox is selected');
        //form.submit();
      } else {
        alert('Oh no! No checkbox selected');
      }
    }
  });

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery-validation@1.19.0/dist/jquery.validate.min.js"></script>

<link href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css" rel="stylesheet"/>
<script src="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.js"></script>

<form id="myForm">

  <table id="example" class="display" style="width:100%">
    <thead>
      <tr>
        <th>Column A</th>
        <th>Column B</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="checkbox"> Checkbox 1</td>
        <td>Test</td>
      </tr>
      <tr>
        <td><input type="checkbox"> Checkbox 2</td>
        <td>Lorem</td>
      </tr>
      <tr>
        <td><input type="checkbox"> Checkbox 3</td>
        <td>ipsum</td>
      </tr>
    </tbody>
  <table>

  <button id="btn" type="submit">Submit</button>

</form>


问:
Issues using bitbucket git repository source for downloading a module over SSH
When calling a module over from a local source everything went alright, however I decided to refactor the Terraform code to use a git repository for modules.

I created a new repository in our BitBucket account with the name terraform-modules, and refactored the source attribute of the modules to have the following structure:

```<code>source     = "git::ssh://git@bitbucket.org:carepaydev/terraform-modules.git//modules/iam/iam_roles/assumable_role"
</code>```

When calling terraform init I get the following error:

```<code>Error downloading modules: Error loading modules: error downloading 'ssh://git@bitbucket.org:<username>/terraform-modules.git': /usr/local/bin/git exited with 128: Cloning into '.terraform/modules/caf541f5e5ccbb1d204bce3b94091014'...
ssh: Could not resolve hostname bitbucket.org:<username>: nodename nor servname provided, or not known
fatal: Could not read from remote repository.
</code>```

Cloning the repository using git clone does work. I tried setting the TF_LOG env var to TRACE to see if that would give me more insight, but that did not help.

Any clue why this fails?

答:
You have a similar error with hashicorp/terraform issue 12696, when trying to access a private repository.

At least, try and set git config --global core.sshCommand "ssh -Tvv", in order to see what private key is actually used by Terraform durong the git clone process.

Body:
When calling a module over from a local source everything went alright, however I decided to refactor the Terraform code to use a git repository for modules.

I created a new repository in our BitBucket account with the name terraform-modules, and refactored the source attribute of the modules to have the following structure:

source     = "git::ssh://git@bitbucket.org:carepaydev/terraform-modules.git//modules/iam/iam_roles/assumable_role"

When calling terraform init I get the following error:

Error downloading modules: Error loading modules: error downloading 'ssh://git@bitbucket.org:<username>/terraform-modules.git': /usr/local/bin/git exited with 128: Cloning into '.terraform/modules/caf541f5e5ccbb1d204bce3b94091014'...
ssh: Could not resolve hostname bitbucket.org:<username>: nodename nor servname provided, or not known
fatal: Could not read from remote repository.

Cloning the repository using git clone does work. I tried setting the TF_LOG env var to TRACE to see if that would give me more insight, but that did not help.

Any clue why this fails?


问:
Output of git branch in tree like fashion
Right now, when I type "git branch"

it lists my branches in an arbitrary order.

What I would prefer would be if "git branch" listed my output in a tree like fasion, somethign like:

```<code>master
|-- foo
  |-- foo1
  |-- foo2
|-- bar
  |-- bar4
</code>```

Where here, foo & bar were branched from master; foo1 & foo2 were branched from foo; bar4 was branched from bar.

Is this easy to accomplish?

[Command line utilities only. This needs to fit into my zsh/vim workflow.]

答: For those who use Github, they have a branch network viewer that seems easier to read</p>

ContentLicense: CC BY-SA 2.5

Body:
Right now, when I type "git branch"

it lists my branches in an arbitrary order.

What I would prefer would be if "git branch" listed my output in a tree like fasion, somethign like:

master
|-- foo
  |-- foo1
  |-- foo2
|-- bar
  |-- bar4

Where here, foo & bar were branched from master; foo1 & foo2 were branched from foo; bar4 was branched from bar.

Is this easy to accomplish?

[Command line utilities only. This needs to fit into my zsh/vim workflow.]


问:
How to convert the float32Array format of native html5 recorded audio to proper bytes for Google Speech-to-Text service?
If you follow this tutorial: https://medium.com/ideas-at-igenius/delivering-a-smooth-cross-browser-speech-to-text-experience-b1e1f1f194a2 you will manage to create a script processor to which you add a listener

```<code>scriptProcessor = inputPoint.context.createScriptProcessor(bufferSize, in_channels, out_channels)
//...
scriptProcessor.addEventListener('audioprocess', streamAudioData)
</code>```

Inside the callback by calling this line: callback_param.inputBuffer.getChannelData(0) one receives a javascript Float32Array which by looking at the data seems to contain float numbers from -1.0 to +1.0

Therefore streaming this to the backend which in turn streams it to Google Speech-To-Text service you are getting nothing (as expected)

Google Speech-To-Text service, at least in Python, for streaming input expects a byte-string in a wav format which contains the sound in the rate that it was specified (i.e. 16000Hz). Note that if in the backend you stream it a file this is working ok.

This conversion has failed: Float32Array -> Int16Array -> byte-string

Has anyone find what are the appropriate conversions for the above to work ?

Alternatively are you aware of a simpler more robust path for: Microphone in browser -> stream data via websocket to backend server -> stream data to Google Speech-To-Input service -> get responses as expected ?

Edit: Adding python code for Recognition Config of Google speech api

```<code>config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code=self.language_code)
</code>```

答:
Ok, did some digging, found the actual documentation which has the proper information.

LINEAR16 - Uncompressed 16-bit signed little-endian samples (Linear PCM).

The key parts being:

16-bits per sample

Signed

Little-endian

So, what you need to do is scale your floating point values (-1.0 ... 1.0) to integers between -32786 and 32767.

There isn't any built-in JavaScript method to do this for you.  Your conversions between Float32Array and Int16Array don't work because you'll just end up with values approximating -1, 0, and 1.  The other reason you can't use Int16Array is because it's endianness is platform dependent!

What you need to do is get cozy with ArrayBuffers and manipulate them with a DataView.  Take each sample, do some math, write the bytes, move to the next sample.  When you're done, both XHR and the Fetch API support sending an ArrayBuffer as the HTTP request body.  Or, you can instantiate a new Blob with that ArrayBuffer and do other things with it.

Body:
If you follow this tutorial: https://medium.com/ideas-at-igenius/delivering-a-smooth-cross-browser-speech-to-text-experience-b1e1f1f194a2 you will manage to create a script processor to which you add a listener

scriptProcessor = inputPoint.context.createScriptProcessor(bufferSize, in_channels, out_channels)
//...
scriptProcessor.addEventListener('audioprocess', streamAudioData)

Inside the callback by calling this line: callback_param.inputBuffer.getChannelData(0) one receives a javascript Float32Array which by looking at the data seems to contain float numbers from -1.0 to +1.0

Therefore streaming this to the backend which in turn streams it to Google Speech-To-Text service you are getting nothing (as expected)

Google Speech-To-Text service, at least in Python, for streaming input expects a byte-string in a wav format which contains the sound in the rate that it was specified (i.e. 16000Hz). Note that if in the backend you stream it a file this is working ok.

This conversion has failed: Float32Array -> Int16Array -> byte-string

Has anyone find what are the appropriate conversions for the above to work ?

Alternatively are you aware of a simpler more robust path for: Microphone in browser -> stream data via websocket to backend server -> stream data to Google Speech-To-Input service -> get responses as expected ?

Edit: Adding python code for Recognition Config of Google speech api

config = types.RecognitionConfig(
        encoding=enums.RecognitionConfig.AudioEncoding.LINEAR16,
        sample_rate_hertz=16000,
        language_code=self.language_code)


问:
[Vue warn]: Unknown custom element: <network> - did you register the component correctly? vue-social-share
Trying to use the vue-social-sharing (latest version 2.4.3) library but keep getting the following:

[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I've followed the guides looked at code examples. But, can't seem to figure out what I'm missing or getting wrong.

I've created a separate component and just followed the sample provided by vue-social-share. But still keep getting the error.

Here is my main.js:

```<code>import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

let SocialSharing = require('vue-social-sharing');
Vue.use(SocialSharing);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');
</code>```

Here is my component (SocialSharingTest.vue):

<template>
<social-sharing url="https://vuejs.org/"
                      title="The Progressive JavaScript Framework"
                      description="Intuitive, Fast and Composable MVVM for building interactive interfaces."
                      quote="Vue is a progressive framework for building user interfaces."
                      hashtags="vuejs,javascript,framework"
                      twitter-user="vuejs"
                      inline-template>

      <network network="email">
           Email
      </network>
      <network network="facebook">
        <v-icon class="mr-3" style="color: #3b5998">fab fa-facebook</v-icon>
      </network>
      <network network="googleplus">
         Google +
      </network>

</social-sharing>
</template>

```

Component isn't working as expected and keeping getting the **[Vue Warn] as described above. I see a working example here for what I would expect to see:

https://codesandbox.io/s/3yv7q36lq?from-embed

答:
I also started to receive a [Vue warn]: Unknown custom element: v-icon  on this component only (not in other components that use v-icon). To fix that to my main.js I added:

```<code>const Vuetify = require('vuetify');
Vue.use(Vuetify);
</code>```

But now trying to incorporate social-sharing into a component that I already had created is giving me [Vue warn]: Failed to mount component: template or render function not defined.

Haven't looked into that much yet. Might have something to do with Vuetify (I'm trying to include  into a ? I'll keep digging for what is happening there, but will take any help if someone knows what it could be.

Thanks. Just to be clear the above worked for original issue. It all seems to work within its own component, just not working as I would expect when trying to incorporate into the component I wish to use it in.

UPDATE - all working for the above I simply didn't include inline-template in my social sharing tag like:

<social-sharing url="https://vuejs.org/" inline-template>
```

Body:
Trying to use the vue-social-sharing (latest version 2.4.3) library but keep getting the following:

[Vue warn]: Unknown custom element:  - did you register the component correctly? For recursive components, make sure to provide the "name" option.

I've followed the guides looked at code examples. But, can't seem to figure out what I'm missing or getting wrong.

I've created a separate component and just followed the sample provided by vue-social-share. But still keep getting the error.

Here is my main.js:

import Vue from 'vue'
import './plugins/vuetify'
import App from './App.vue'
import router from './router'
import store from './store'

Vue.config.productionTip = false;

let SocialSharing = require('vue-social-sharing');
Vue.use(SocialSharing);

new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app');

Here is my component (SocialSharingTest.vue):

<template>
<social-sharing url="https://vuejs.org/"
                      title="The Progressive JavaScript Framework"
                      description="Intuitive, Fast and Composable MVVM for building interactive interfaces."
                      quote="Vue is a progressive framework for building user interfaces."
                      hashtags="vuejs,javascript,framework"
                      twitter-user="vuejs"
                      inline-template>

      <network network="email">
           Email
      </network>
      <network network="facebook">
        <v-icon class="mr-3" style="color: #3b5998">fab fa-facebook</v-icon>
      </network>
      <network network="googleplus">
         Google +
      </network>

</social-sharing>
</template>

Component isn't working as expected and keeping getting the **[Vue Warn] as described above. I see a working example here for what I would expect to see:

https://codesandbox.io/s/3yv7q36lq?from-embed

Body:
I also started to receive a [Vue warn]: Unknown custom element: v-icon  on this component only (not in other components that use v-icon). To fix that to my main.js I added:

const Vuetify = require('vuetify');
Vue.use(Vuetify);

But now trying to incorporate social-sharing into a component that I already had created is giving me [Vue warn]: Failed to mount component: template or render function not defined.

Haven't looked into that much yet. Might have something to do with Vuetify (I'm trying to include  into a ? I'll keep digging for what is happening there, but will take any help if someone knows what it could be.

Thanks. Just to be clear the above worked for original issue. It all seems to work within its own component, just not working as I would expect when trying to incorporate into the component I wish to use it in.

UPDATE - all working for the above I simply didn't include inline-template in my social sharing tag like:

<social-sharing url="https://vuejs.org/" inline-template>


问:
How to check if an id value exists in an object array
Given an array "posts" of objects {id: "x", title: "title"}, i need to verify whether there is a previously entered id before entering a new post (via form in which id is a field).

I tried looping through posts, but it causes problems on entering repeated new data. Thank you for your help, this is driving me mad.

```<code>// ADD NEW POST FROM FORM TO ARRAY
$("#form").submit(function(event) {
    event.preventDefault();
    var id = Number($("#idPost").val());
    var title = $("#titlePost").val();
    var date = new Date($("#data").val());
// CHECK IF id ALREADY EXISTS, IF YES, BLOCK ENTRY
    for(num of posts){
        console.log (id, num.id);
        if(id === num.id){
            console.log("error");
        } else {
            var post = new Post(id, title, date);
        }
    };
});
</code>```

答:
I think you should use the JSON object, it will help you to identify easily, that how to identify, is key present in JSON object list or not

```<code>JSON_Object.hasOwnProperty(ID)
</code>```

```<code>var x = {};
x[1] = "{'title1':'title1'}";
x[2] = "{'title2':'title2'}";
x[3] = "{'title3':'title3'}";

if(x.hasOwnProperty(1)){
 console.log('value present');
}

if(x.hasOwnProperty(5)){
 console.log('value not present');
}
</code>```

This may help you.

This is just a way to resolve your problem.
Use this, thanks me later, cheers :)

Body:
Given an array "posts" of objects {id: "x", title: "title"}, i need to verify whether there is a previously entered id before entering a new post (via form in which id is a field).

I tried looping through posts, but it causes problems on entering repeated new data. Thank you for your help, this is driving me mad.

// ADD NEW POST FROM FORM TO ARRAY
$("#form").submit(function(event) {
    event.preventDefault();
    var id = Number($("#idPost").val());
    var title = $("#titlePost").val();
    var date = new Date($("#data").val());
// CHECK IF id ALREADY EXISTS, IF YES, BLOCK ENTRY
    for(num of posts){
        console.log (id, num.id);
        if(id === num.id){
            console.log("error");
        } else {
            var post = new Post(id, title, date);
        }
    };
});

Body:
I think you should use the JSON object, it will help you to identify easily, that how to identify, is key present in JSON object list or not

JSON_Object.hasOwnProperty(ID)

var x = {};
x[1] = "{'title1':'title1'}";
x[2] = "{'title2':'title2'}";
x[3] = "{'title3':'title3'}";

if(x.hasOwnProperty(1)){
 console.log('value present');
}

if(x.hasOwnProperty(5)){
 console.log('value not present');
}

This may help you.

This is just a way to resolve your problem.
Use this, thanks me later, cheers :)