问:
How to replace a text in pdf file with ITextPDF library?
I have a requirement to replace a placeholder like ${placeholder} with an actual value, but I could not find any working solution... I've ben following by https://itextpdf.com/en/resources/examples/itext-7/replacing-pdf-objects and it doesn't work. Does anybody know how to do it?</p>

答:
Sample code below for replace content in PDF using iText</p>

```<code>    File dir = new File("./");
    File [] files = dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".pdf");
        }
    });

    for (File pdffile : files) {
        System.out.println(pdffile.getName());
        PdfReader reader = null;
        reader = new PdfReader(pdffile.toString());

      PdfDictionary dict = reader.getPageN(1);
      PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
      if (object instanceof PRStream) {
          PRStream stream = (PRStream)object;
          byte[] data = PdfReader.getStreamBytes(stream);
          String dd = new String(data);
          dd = dd.replace("0 0 0 rg\n()Tj", "0 0 0 rg\n(Plan Advanced Payment)Tj");
          System.out.print(dd);
          stream.setData(dd.getBytes());
      }
      PdfStamper stamper = new PdfStamper(reader,
      new FileOutputStream("./output/"+pdffile.getName())); // output PDF
      stamper.close();
      reader.close();
    }
</code>```

Body:
Sample code below for replace content in PDF using iText

    File dir = new File("./");
    File [] files = dir.listFiles(new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".pdf");
        }
    });

    for (File pdffile : files) {
        System.out.println(pdffile.getName());
        PdfReader reader = null;
        reader = new PdfReader(pdffile.toString());

      PdfDictionary dict = reader.getPageN(1);
      PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
      if (object instanceof PRStream) {
          PRStream stream = (PRStream)object;
          byte[] data = PdfReader.getStreamBytes(stream);
          String dd = new String(data);
          dd = dd.replace("0 0 0 rg\n()Tj", "0 0 0 rg\n(Plan Advanced Payment)Tj");
          System.out.print(dd);
          stream.setData(dd.getBytes());
      }
      PdfStamper stamper = new PdfStamper(reader,
      new FileOutputStream("./output/"+pdffile.getName())); // output PDF
      stamper.close();
      reader.close();
    }


来源: stackexchange

问:
How to use a variable string with array in a foreach loop
I try to get the following code working.

foreach ($uniqueItems as $key => $value) {
 $output = "{$value->properties->property[10]->value}";
 echo $output;
}

```

<p>In the browser I see 24.99</p>

<p>Above code gives me the correct output. But I need the $output from outside this foreach. I try the following</p>

<pre class="lang-php prettyprint-override"><code>$output = "{\$value->properties->property[10]->value}";
foreach ($uniqueItems as $key => $value) {
 echo $output;
}
</code>```

In the browser I see {$value->properties->property[10]->value}

This is print_r($uniqueItems[$key]);

SimpleXMLElement Object
(
    [name] => Donnay joggingbroek zwart unisex
    [properties] => SimpleXMLElement Object
        (
            [property] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => deliveryTime
                                )

                            [value] => Voor 16.00 uur besteld, morgen in huis!
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => brand
                                )

                            [value] => Donnay
                        )

                    [2] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => size
                                )

                            [value] => SimpleXMLElement Object
                                (
                                )

                        )

                    [3] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => color
                                )

                            [value] => Zwart
                        )

                    [4] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => EAN
                                )

                            [value] => SimpleXMLElement Object
                                (
                                )

                        )

                    [5] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => categoryPath
                                )

                            [value] => Tenniskleding/Tenniskleding dames
                        )

                    [6] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => deliveryCosts
                                )

                            [value] => 4.95
                        )

                    [7] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => discount
                                )

                            [value] => 5.00
                        )

                    [8] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => subcategories
                                )

                            [value] => Tenniskleding dames
                        )

                    [9] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => SKU
                                )

                            [value] => 489000-TL-020
                        )

                    [10] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => fromPrice
                                )

                            [value] => 24.99
                        )
))
```

How to get the right output?

答: The second snippet won't work as php does not know that $value is to be interpolated until $value gets defined which is happening when the loop actually starts. Till then, it will just be a string. That's why it's just printing out it as a string

ContentLicense: CC BY-SA 4.0

Body:
I try to get the following code working.

foreach ($uniqueItems as $key => $value) {
 $output = "{$value->properties->property[10]->value}";
 echo $output;
}

In the browser I see 24.99

Above code gives me the correct output. But I need the $output from outside this foreach. I try the following

$output = "{\$value->properties->property[10]->value}";
foreach ($uniqueItems as $key => $value) {
 echo $output;
}

In the browser I see {$value->properties->property[10]->value}

This is print_r($uniqueItems[$key]);

SimpleXMLElement Object
(
    [name] => Donnay joggingbroek zwart unisex
    [properties] => SimpleXMLElement Object
        (
            [property] => Array
                (
                    [0] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => deliveryTime
                                )

                            [value] => Voor 16.00 uur besteld, morgen in huis!
                        )

                    [1] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => brand
                                )

                            [value] => Donnay
                        )

                    [2] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => size
                                )

                            [value] => SimpleXMLElement Object
                                (
                                )

                        )

                    [3] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => color
                                )

                            [value] => Zwart
                        )

                    [4] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => EAN
                                )

                            [value] => SimpleXMLElement Object
                                (
                                )

                        )

                    [5] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => categoryPath
                                )

                            [value] => Tenniskleding/Tenniskleding dames
                        )

                    [6] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => deliveryCosts
                                )

                            [value] => 4.95
                        )

                    [7] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => discount
                                )

                            [value] => 5.00
                        )

                    [8] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => subcategories
                                )

                            [value] => Tenniskleding dames
                        )

                    [9] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => SKU
                                )

                            [value] => 489000-TL-020
                        )

                    [10] => SimpleXMLElement Object
                        (
                            [@attributes] => Array
                                (
                                    [name] => fromPrice
                                )

                            [value] => 24.99
                        )
))

How to get the right output?


问:
How to redirect textfields enter command of going to form submit instead of button midway form?
I'm using material UI as my component library. I have a small dialog that has a "recover password" button placed somewhere inside the form.  - I notice that after adding this button the "enter" command in the textfields becomes the onClick command of the buttons.

The form is simply like:

```<code>type PropTy = {
    classes: any,
    submit: (Event) => mixed;
    handleClose: (Event) => mixed;
    handleRequestPasswordRecover: (Event) => mixed;
};

function SigninForm(props:PropTy) {
    const {classes, submit, handleClose, handleRequestPasswordRecover} = props;
    const signinRef = React.createRef();

    const actions = [
        <Button
            type="reset"
            label="Reset"
            color="secondary"
            style={{ float: 'left' }}
            key='reset'
        >Reset</Button>,
        <Button
            label="Cancel"
            color="primary"
            onClick={handleClose}
            key='cancel'
        >Cancel</Button>,
        <Button
            type="submit"
            label="Submit"
            variant="contained"
            color="primary"
            key='submit'
            autoFocus
        >Login</Button>,
    ];

    return (
        <form className={classes.form}
              onSubmit={submit}
              ref={signinRef}
        >
            <FormControl margin="normal" required fullWidth>
                <TextField id="username" name="username" autoComplete="username" autoFocus label={'Username'}/>
            </FormControl>
            <FormControl margin="normal" required fullWidth>
                <div style={{display: 'flex', justifyContent: 'space-between', alignItems: 'baseline'}}>
                    <FormLabel htmlFor="password">Password</FormLabel>
                    <button className={classes.linkButton} onClick={(e) => {
                        handleRequestPasswordRecover(e)
                    }}>{'Lost password?'}</button>
                </div>
                <Input
                    name="password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                />
            </FormControl>
            <FormControlLabel
                control={<Checkbox value="remember" color="primary" />}
                label="Remember me"
            />
            <div style={{ textAlign: 'right'}}>
                {actions}
            </div>
        </form>);
}
</code>```

The action that happens on "enter" is not "submit" as I expect - but rather the button's onClick event (handleRequestPasswordRecover). How do I redirect this?

答:
You can write the below code in your html on form tag. So you can prevent the form submission on hit the enter key while focus on textfield.

```<code><form className={classes.form}
          onSubmit={submit}
          ref={signinRef}
          onKeyPress={(event) => {
                if (event.key === "Enter") {
                   event.preventDefault();
                }
          }}>
</code>```

Body:
I'm using material UI as my component library. I have a small dialog that has a "recover password" button placed somewhere inside the form.  - I notice that after adding this button the "enter" command in the textfields becomes the onClick command of the buttons.

The form is simply like:

type PropTy = {
    classes: any,
    submit: (Event) => mixed;
    handleClose: (Event) => mixed;
    handleRequestPasswordRecover: (Event) => mixed;
};

function SigninForm(props:PropTy) {
    const {classes, submit, handleClose, handleRequestPasswordRecover} = props;
    const signinRef = React.createRef();

    const actions = [
        <Button
            type="reset"
            label="Reset"
            color="secondary"
            style={{ float: 'left' }}
            key='reset'
        >Reset</Button>,
        <Button
            label="Cancel"
            color="primary"
            onClick={handleClose}
            key='cancel'
        >Cancel</Button>,
        <Button
            type="submit"
            label="Submit"
            variant="contained"
            color="primary"
            key='submit'
            autoFocus
        >Login</Button>,
    ];

    return (
        <form className={classes.form}
              onSubmit={submit}
              ref={signinRef}
        >
            <FormControl margin="normal" required fullWidth>
                <TextField id="username" name="username" autoComplete="username" autoFocus label={'Username'}/>
            </FormControl>
            <FormControl margin="normal" required fullWidth>

                    <FormLabel htmlFor="password">Password</FormLabel>
                    <button className={classes.linkButton} onClick={(e) => {
                        handleRequestPasswordRecover(e)
                    }}>{'Lost password?'}</button>

                <Input
                    name="password"
                    type="password"
                    id="password"
                    autoComplete="current-password"
                />
            </FormControl>
            <FormControlLabel
                control={<Checkbox value="remember" color="primary" />}
                label="Remember me"
            />

                {actions}

        </form>);
}

The action that happens on "enter" is not "submit" as I expect - but rather the button's onClick event (handleRequestPasswordRecover). How do I redirect this?

Body:
You can write the below code in your html on form tag. So you can prevent the form submission on hit the enter key while focus on textfield.

<form className={classes.form}
          onSubmit={submit}
          ref={signinRef}
          onKeyPress={(event) => {
                if (event.key === "Enter") {
                   event.preventDefault();
                }
          }}>


问:
Scrolling parent div overflow based on position of div within parent
I have 3 sections of the page:

```<code><div class="container" id="main-container">
    <div class="section" id="profile">
      Hello World
    </div>
    <div class="section" id="projects">
      Hello World 2
    </div>
    <div class="section" id="contact">
      Hello World 3
    </div>
  </div>
</code>```

I have 3 links in my navigation:

```<code><body onresize="scroll()">
  <div class="nav">
    <div class="nav-link" id="profile">
      <a>
        Profile
      </a>
    </div>
    <div class="nav-link" id="projects">
      <a>
        Projects
      </a>
    </div>
    <div class="nav-link" id="contact">
      <a>
        Contact
      </a>
    </div>
  </div>
</code>```

#main-container has overflow scroll and each of the sections takes up 100% width and height of the page.

I tried to make it so that when one of them links are clicked, it animates the scrolling effect to that section:

```<code>$(document).ready(function () {
  $('.nav-link').on('click', function () {
    if ($(window).width() < 768) {
      let section = $(".section#"+$(this).attr('id')).position();
      $('#main-container').animate({
          scrollTop: section.top
      }, 500);
    }
  });
});
</code>```

But this doesn't work, the value of position() changes based on where the user is scrolled to. How do i get the scroll position of a section of $main-container based on the #main-container? And how to do animate the scroll to it?

答:
just try offset()

let section = $(".section#"+$(this).attr('id')).offset();

Body:
I have 3 sections of the page:

      Hello World

      Hello World 2

      Hello World 3

I have 3 links in my navigation:

        Profile

        Projects

        Contact

#main-container has overflow scroll and each of the sections takes up 100% width and height of the page.

I tried to make it so that when one of them links are clicked, it animates the scrolling effect to that section:

$(document).ready(function () {
  $('.nav-link').on('click', function () {
    if ($(window).width() < 768) {
      let section = $(".section#"+$(this).attr('id')).position();
      $('#main-container').animate({
          scrollTop: section.top
      }, 500);
    }
  });
});

But this doesn't work, the value of position() changes based on where the user is scrolled to. How do i get the scroll position of a section of $main-container based on the #main-container? And how to do animate the scroll to it?


问:
LSTM Encoder-Decoder Inference Model
Many tutorials for seq2seq encoder-decoder architecture based on LSTM,  (for example English-French translation), define the model as follow:

```<code>encoder_inputs = Input(shape=(None,))
en_x=  Embedding(num_encoder_tokens, embedding_size)(encoder_inputs)

# Encoder lstm
encoder = LSTM(50, return_state=True)
encoder_outputs, state_h, state_c = encoder(en_x)

# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None,))

# french word embeddings
dex=  Embedding(num_decoder_tokens, embedding_size)
final_dex= dex(decoder_inputs)

# decoder lstm
decoder_lstm = LSTM(50, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(final_dex,
                                     initial_state=encoder_states)

decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

# While training, model takes eng and french words and outputs #translated french word
fullmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs)

# rmsprop is preferred for nlp tasks
fullmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])

fullmodel.fit([encoder_input_data, decoder_input_data], decoder_target_data,
          batch_size=128,
          epochs=100,
          validation_split=0.20)
</code>```

Then for prediction, they define infernce models as follow:

```<code># define the encoder model
encoder_model = Model(encoder_inputs, encoder_states)
encoder_model.summary()

# Redefine the decoder model with decoder will be getting below inputs from encoder while in prediction
decoder_state_input_h = Input(shape=(50,))
decoder_state_input_c = Input(shape=(50,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
final_dex2= dex(decoder_inputs)

decoder_outputs2, state_h2, state_c2 = decoder_lstm(final_dex2, initial_state=decoder_states_inputs)

decoder_states2 = [state_h2, state_c2]
decoder_outputs2 = decoder_dense(decoder_outputs2)

# sampling model will take encoder states and decoder_input(seed initially) and output the predictions(french word index) We dont care about decoder_states2
decoder_model = Model(
    [decoder_inputs] + decoder_states_inputs,
    [decoder_outputs2] + decoder_states2)
</code>```

Then predict using:

```<code># Reverse-lookup token index to decode sequences back to
# something readable.
reverse_input_char_index = dict(
    (i, char) for char, i in input_token_index.items())
reverse_target_char_index = dict(
    (i, char) for char, i in target_token_index.items())

def decode_sequence(input_seq):
    # Encode the input as state vectors.
    states_value = encoder_model.predict(input_seq)

    # Generate empty target sequence of length 1.
    target_seq = np.zeros((1,1))
    # Populate the first character of target sequence with the start character.
    target_seq[0, 0] = target_token_index['START_']

   # Sampling loop for a batch of sequences
    # (to simplify, here we assume a batch of size 1).
    stop_condition = False
    decoded_sentence = ''
    while not stop_condition:
        output_tokens, h, c = decoder_model.predict(
            [target_seq] + states_value)

        # Sample a token
        sampled_token_index = np.argmax(output_tokens[0, -1, :])
        sampled_char = reverse_target_char_index[sampled_token_index]
        decoded_sentence += ' '+sampled_char

        # Exit condition: either hit max length
        # or find stop character.
        if (sampled_char == '_END' or
           len(decoded_sentence) > 52):
            stop_condition = True

       # Update the target sequence (of length 1).
        target_seq = np.zeros((1,1))
        target_seq[0, 0] = sampled_token_index

        # Update states
        states_value = [h, c]
return decoded_sentence
</code>```

My question is, they trained the model with the name 'fullmodel' to get best weights ... in prediction part, they used the inference models with names (encoder_model & decoder_model) ... so they didn't use any weights from the 'fullmodel' ?!

I don't understand how they benefit from the trained model!

答:
If you notice carefully, the trained layer weights are being reused.
For example, while creating decoder_model we use decoder_lstm layer which was defined as a part of full model,
decoder_outputs2, state_h2, state_c2 = decoder_lstm(final_dex2, initial_state=decoder_states_inputs),

and encoder model too uses, encoder_inputs and encoder_states layer defined previously.
encoder_model = Model(encoder_inputs, encoder_states)

Due to the architecture of the encoder-decoder model, we need to perform these implementations hacks.
Also, as the keras documentation mentions, With the functional API, it is easy to reuse trained models: you can treat any model as if it were a layer, by calling it on a tensor. Note that by calling a model you aren't just reusing the architecture of the model, you are also reusing its weights. For more details refer - https://keras.io/getting-started/functional-api-guide/#all-models-are-callable-just-like-layers

Title: LSTM Encoder-Decoder Inference Model

Body:
Many tutorials for seq2seq encoder-decoder architecture based on LSTM,  (for example English-French translation), define the model as follow:

encoder_inputs = Input(shape=(None,))
en_x=  Embedding(num_encoder_tokens, embedding_size)(encoder_inputs)

# Encoder lstm
encoder = LSTM(50, return_state=True)
encoder_outputs, state_h, state_c = encoder(en_x)

# We discard `encoder_outputs` and only keep the states.
encoder_states = [state_h, state_c]

# Set up the decoder, using `encoder_states` as initial state.
decoder_inputs = Input(shape=(None,))

# french word embeddings
dex=  Embedding(num_decoder_tokens, embedding_size)
final_dex= dex(decoder_inputs)

# decoder lstm
decoder_lstm = LSTM(50, return_sequences=True, return_state=True)
decoder_outputs, _, _ = decoder_lstm(final_dex,
                                     initial_state=encoder_states)

decoder_dense = Dense(num_decoder_tokens, activation='softmax')
decoder_outputs = decoder_dense(decoder_outputs)

# While training, model takes eng and french words and outputs #translated french word
fullmodel = Model([encoder_inputs, decoder_inputs], decoder_outputs)

# rmsprop is preferred for nlp tasks
fullmodel.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['acc'])

fullmodel.fit([encoder_input_data, decoder_input_data], decoder_target_data,
          batch_size=128,
          epochs=100,
          validation_split=0.20)

Then for prediction, they define infernce models as follow:

# define the encoder model
encoder_model = Model(encoder_inputs, encoder_states)
encoder_model.summary()

# Redefine the decoder model with decoder will be getting below inputs from encoder while in prediction
decoder_state_input_h = Input(shape=(50,))
decoder_state_input_c = Input(shape=(50,))
decoder_states_inputs = [decoder_state_input_h, decoder_state_input_c]
final_dex2= dex(decoder_inputs)

decoder_outputs2, state_h2, state_c2 = decoder_lstm(final_dex2, initial_state=decoder_states_inputs)

decoder_states2 = [state_h2, state_c2]
decoder_outputs2 = decoder_dense(decoder_outputs2)

# sampling model will take encoder states and decoder_input(seed initially) and output the predictions(french word index) We dont care about decoder_states2
decoder_model = Model(
    [decoder_inputs] + decoder_states_inputs,
    [decoder_outputs2] + decoder_states2)

Then predict using:

# Reverse-lookup token index to decode sequences back to
# something readable.
reverse_input_char_index = dict(
    (i, char) for char, i in input_token_index.items())
reverse_target_char_index = dict(
    (i, char) for char, i in target_token_index.items())

def decode_sequence(input_seq):
    # Encode the input as state vectors.
    states_value = encoder_model.predict(input_seq)

    # Generate empty target sequence of length 1.
    target_seq = np.zeros((1,1))
    # Populate the first character of target sequence with the start character.
    target_seq[0, 0] = target_token_index['START_']

   # Sampling loop for a batch of sequences
    # (to simplify, here we assume a batch of size 1).
    stop_condition = False
    decoded_sentence = ''
    while not stop_condition:
        output_tokens, h, c = decoder_model.predict(
            [target_seq] + states_value)

        # Sample a token
        sampled_token_index = np.argmax(output_tokens[0, -1, :])
        sampled_char = reverse_target_char_index[sampled_token_index]
        decoded_sentence += ' '+sampled_char

        # Exit condition: either hit max length
        # or find stop character.
        if (sampled_char == '_END' or
           len(decoded_sentence) > 52):
            stop_condition = True

       # Update the target sequence (of length 1).
        target_seq = np.zeros((1,1))
        target_seq[0, 0] = sampled_token_index

        # Update states
        states_value = [h, c]
return decoded_sentence

My question is, they trained the model with the name 'fullmodel' to get best weights ... in prediction part, they used the inference models with names (encoder_model & decoder_model) ... so they didn't use any weights from the 'fullmodel' ?!

I don't understand how they benefit from the trained model!


问:
Removing time from a Date object?
I want to remove time from Date object.

```<code>DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format
</code>```

But when I'm converting this date (which is in String format) it is appending time also.

I don't want time at all. What I want is simply "21/03/2012".

答:
If you are using Java 8+, use  java.time.LocalDate type instead.

```<code>LocalDate now = LocalDate.now();
System.out.println(now.toString());
</code>```

The output:

```<code>2019-05-30
</code>```

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html

ContentLicense: CC BY-SA 3.0

Title: Removing time from a Date object?

Body:
I want to remove time from Date object.

DateFormat df;
String date;
df = new SimpleDateFormat("dd/MM/yyyy");
d = eventList.get(0).getStartDate(); // I'm getting the date using this method
date = df.format(d); // Converting date in "dd/MM/yyyy" format

But when I'm converting this date (which is in String format) it is appending time also.

I don't want time at all. What I want is simply "21/03/2012".

Body:
If you are using Java 8+, use  java.time.LocalDate type instead.

LocalDate now = LocalDate.now();
System.out.println(now.toString());

The output:

2019-05-30

https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html


问:
this class is not key value coding-compliant for the key Project1.'
I am new to iOS development , can you help me anyone in bug point of you. thank you for advance.

uncaught exception 'NSUnknownKeyException', reason:
  '[ setValue:forUndefinedKey:]:
  this class is not key value coding-compliant for the key Project1.'

```<code> let  context  = appdelegate.persistentContainer.viewContext
 let proj = Project()
        let arrProj = dic.object(forKey: "Projects") as! NSArray
        for n in 0..<arrProj.count {
            let subDic = arrProj.object(at: n) as! NSDictionary
            let item = ProjectItem(dict: subDic)
            proj.arrProjs.append( item )

           let projects = NSEntityDescription.entity(forEntityName: "Projects", in: context)
            projects?.setValue(item.Project, forKey: "project1")
            projects?.setValue(item.Project2, forKey: "project2")
            projects?.setValue(item.ID, forKey: "projectid")
            projects?.setValue(item.radius, forKey: "radius")
            projects?.setValue(item.GeofenceType, forKey: "geo_Type")
            projects?.setValue(item.Geofence, forKey: "geofence")
            projects?.setValue(item.Coordinates, forKey: "coordinates")
        }
</code>```

答:
Please check this using insertobject query you can save your data in core data.</p>

```<code>    let  context  = appdelegate.persistentContainer.viewContext
    let projects = NSEntityDescription.insertNewObject(forEntityName: "Projects", into: context) as! Projects

    projects.project1 = item.Project
    projects.project2 = item.Project2
    or
    projects?.setValue(item.Project, forKey: "project1")
    projects?.setValue(item.Project2, forKey: "project2")
    projects?.setValue(item.ID, forKey: "projectid")
    projects?.setValue(item.radius, forKey: "radius")

    do{
    try context.save()
    }catch{
    print("error")
    }
</code>```

Body:
I am new to iOS development , can you help me anyone in bug point of you. thank you for advance.

uncaught exception 'NSUnknownKeyException', reason:
  '[ setValue:forUndefinedKey:]:
  this class is not key value coding-compliant for the key Project1.'

 let  context  = appdelegate.persistentContainer.viewContext
 let proj = Project()
        let arrProj = dic.object(forKey: "Projects") as! NSArray
        for n in 0..<arrProj.count {
            let subDic = arrProj.object(at: n) as! NSDictionary
            let item = ProjectItem(dict: subDic)
            proj.arrProjs.append( item )

           let projects = NSEntityDescription.entity(forEntityName: "Projects", in: context)
            projects?.setValue(item.Project, forKey: "project1")
            projects?.setValue(item.Project2, forKey: "project2")
            projects?.setValue(item.ID, forKey: "projectid")
            projects?.setValue(item.radius, forKey: "radius")
            projects?.setValue(item.GeofenceType, forKey: "geo_Type")
            projects?.setValue(item.Geofence, forKey: "geofence")
            projects?.setValue(item.Coordinates, forKey: "coordinates")
        }

Body:
Please check this using insertobject query you can save your data in core data.

    let  context  = appdelegate.persistentContainer.viewContext
    let projects = NSEntityDescription.insertNewObject(forEntityName: "Projects", into: context) as! Projects

    projects.project1 = item.Project
    projects.project2 = item.Project2
    or
    projects?.setValue(item.Project, forKey: "project1")
    projects?.setValue(item.Project2, forKey: "project2")
    projects?.setValue(item.ID, forKey: "projectid")
    projects?.setValue(item.radius, forKey: "radius")

    do{
    try context.save()
    }catch{
    print("error")
    }


问:
How to use didFinish navigation on an WKWebView passed to another class
I'm setting up an app, where the WKWebView object is created in one class, and then passed to another class for handling, but when I use didFinish navigation in the second class, it never gets called.

I have added the WKNavigationDelegate protocol, and set  navigationDelegate = self

```<code>class one: UIViewController {
   var webView: WKWebView = WKWebView();

    override func viewDidLoad(){
      var second = Second()
      second.web = webView;
      second.test()
   }
}

class second: NSObject, WKNavigationDelegate {
  var web: WKWebView? = nil;

  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
     print("Test")
  }

  func test(){
     self.web!.load(URLRequest(url: URL(string: "https://google.com")!))
  }
}
</code>```

I never see the "Test" message.

答:
Make it an instance var to retain the object so delegate to be called </p>

```<code>var second = Second() /// << here

override func viewDidLoad(){
  super.viewDidLoad()
  ......
}
</code>```

<hr>

```<code>func test(){
   self.web!.navigationDelegate = self
   self.web!.load(URLRequest(url: URL(string: "https://google.com")!))
}
</code>```

Body:
I'm setting up an app, where the WKWebView object is created in one class, and then passed to another class for handling, but when I use didFinish navigation in the second class, it never gets called.

I have added the WKNavigationDelegate protocol, and set  navigationDelegate = self

class one: UIViewController {
   var webView: WKWebView = WKWebView();

    override func viewDidLoad(){
      var second = Second()
      second.web = webView;
      second.test()
   }
}

class second: NSObject, WKNavigationDelegate {
  var web: WKWebView? = nil;

  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
     print("Test")
  }

  func test(){
     self.web!.load(URLRequest(url: URL(string: "https://google.com")!))
  }
}

I never see the "Test" message.

Body:
Make it an instance var to retain the object so delegate to be called

var second = Second() /// << here

override func viewDidLoad(){
  super.viewDidLoad()
  ......
}

func test(){
   self.web!.navigationDelegate = self
   self.web!.load(URLRequest(url: URL(string: "https://google.com")!))
}


问:
Replicate a data frame by group
I have the following data frame:

```<code>df = structure(list(Group = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3,
3), index = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3)), row.names = c(NA,
-13L), class = c("tbl_df", "tbl", "data.frame"))
</code>```

I would like to replicate the column index according to the Group column, one time with each number appearing n consecutive times, and a second time all the numbers appear as a group n times, where n is the size of the group (similarly to rep versus rep with each).

So the output would look like this (lets look only at Group 1 because it is too long):

First option:

```<code>df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4,
4, 4, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

Second option:

```<code>df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1,
2, 3, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))
</code>```

How do I do this with group_by?

答:
You could use rep and slice like this

```<code>library(dplyr)
</code>```

Option 1:

```<code>df %>%
  group_by(Group) %>%
  slice(rep(seq_len(n()), each = n()))
</code>```

Option 2 :

```<code>df %>%
  group_by(Group) %>%
  slice(rep(seq_len(n()), n()))
</code>```

Title: Replicate a data frame by group

Body:
I have the following data frame:

df = structure(list(Group = c(1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3,
3), index = c(1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 1, 2, 3)), row.names = c(NA,
-13L), class = c("tbl_df", "tbl", "data.frame"))

I would like to replicate the column index according to the Group column, one time with each number appearing n consecutive times, and a second time all the numbers appear as a group n times, where n is the size of the group (similarly to rep versus rep with each).

So the output would look like this (lets look only at Group 1 because it is too long):

First option:

df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4,
4, 4, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))

Second option:

df = structure(list(Group = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1), index = c(1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1,
2, 3, 4)), row.names = c(NA, -16L), class = c("tbl_df", "tbl",
"data.frame"))

How do I do this with group_by?

Body:
You could use rep and slice like this

library(dplyr)

Option 1:

df %>%
  group_by(Group) %>%
  slice(rep(seq_len(n()), each = n()))

Option 2 :

df %>%
  group_by(Group) %>%
  slice(rep(seq_len(n()), n()))


问:
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?!

答:
What fixed my problem you may ask ?!

I added the (onRowUnselect) event to the
, where I cleared the Url parameters and voilà.

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?!

Body:
What fixed my problem you may ask ?!

I added the (onRowUnselect) event to the <p-table>, where I cleared the Url parameters and voilà.


问:
How to check if element in list matches with another element in a list of strings?

Input lists

```<code>list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']
</code>```

Output list

```<code>output=['Google','AU-KBC Research Centre']
</code>```

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

答:
Try this: </p>

```<code>[name  for name in list1 if not any(x.lower() in name.lower() for x in set(exclusion_list)) ]
</code>```

Body:
Input lists

list1 = ['Google', 'Stanford University', 'Karlsruhe Institute of Technology (KIT) / University of Karlsruhe (TH)', 'AU-KBC Research Centre']
exclusion_list = ['university','institute','school','University','Institute','School']

Output list

output=['Google','AU-KBC Research Centre']

The output should have only those elements which do not contain the words(elements) from the exclusion_list
I have searched all of SO. But, none of them give an answer to specifically this problem. I have tried using filter() and also a dumb function. But, I am looking for a non-brute-force solution. Also, I am curious about an extra solution which uses regex to solve the problem.

Basically

I am looking for an optimal way to remove any sort of university, school or institute from the list1

EDIT: I want to preserve the order of the list as well. I apologize for not making this point clear.

Body:
Try this:

[name  for name in list1 if not any(x.lower() in name.lower() for x in set(exclusion_list)) ]


问:
Scaffolding an Oracle database with EF Core failing with logon denied error
I am trying to scaffold some classes from an Oracle database for use with a .NET Core Web API. I have installed the following nuget packages:

Oracle.EntityFrameworkCore - v2.18.0-beta3

Oracle.ManagedDataAccess.Core - v2.18.6

I have tried scaffolding with both providers, and I get two different errors.

Scaffold command - Scaffold-DbContext "Data Source=(DESCRIPTION=(ADDRESS_LIST= (ADDRESS=(COMMUNITY=tcpcom.world)(PROTOCOL=tcp)(HOST={Host})(PORT={Port})))(CONNECT_DATA=(SID={SID}))); User ID={UserId};Password={Password}" {Provider} -o Models

Oracle.EntityFrameworkCore scaffold error

ORA-01017: invalid username/password; logon denied

I have confirmed my login details to be correct

Oracle.ManagedDataAccess scaffold error

Unable to find expected assembly attribute named DesignTimeProviderServicesAttribute in provider assembly
Oracle.ManagedDataAccess. This attribute is required to identify the class which acts as the design-time service provider factory.

I have tried implementing the IDesignTimeDbContextFactory<T> interface with no luck

I've tried countless things from google today with no luck. Could this be a problem with the Oracle drivers?

EDIT

I have created a .NET Core console app, installed EF Core and Oracle.EntityFrameworkCore and tried to scaffold but get the same error. Also confirmed connection string is correct by using it to create a DbContext and query a table, returning records.

答:
The issue turned out to be a dollar sign $ in the password. The VS Package Manager console provides a PowerShell interface, and the $ is a reserved symbol in PowerShell, so it needed to be escaped by placing a backtick ` in front of the $.

Answer from Oracle Community forums.


问:
Custom header content animate while scrolling in swift
I have created custom header but I don't know how to animate while scrolling.

Please check below image and let me know how to animate while scrolling.
This animated header in Fotmob app.

答:
First of all add header view as UIvVew and add UIScrollView or UITableView below headerView same as screenshot and follow below step.

set a fixed height constraint to the header view (125 for example) and attach it to top, left and right.

make the UIScrollView below to use all the available space so set to zero top, bottom, left and right constraints.

 connect the header view height constraint to the ViewController in order to have something like:

```<code> @IBOutlet var headerViewHeightConstraint: NSLayoutConstraint!
</code>```

set the UIScrollView delegate to the ViewController

declare two properties to limit the maximum and the minimum height of the header view, fox example:

```<code>let headerViewMaxHeight: CGFloat = 125
let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height
</code>```

The entire workaround is based on update the header view height constraint while the UIScrollView is scrolling, so let’s implement the UIScrollViewDelegate and the most important delegate for our case, the scrollViewDidScroll:

```<code>func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height

    let yPos = mainScrollView.contentOffset.y
    let newHeaderViewHeight: CGFloat = headerViewHeightConstraint.constant - yPos

    if newHeaderViewHeight > headerViewMaxHeight {
        // Here, Manage Your Score Format View
        headerViewHeightConstraint.constant = max(headerViewMaxHeight, newHeaderViewHeight)

    } else if newHeaderViewHeight < headerViewMinHeight {

    headerViewHeightConstraint.constant = headerViewMinHeight

    } else {

        headerViewHeightConstraint.constant = newHeaderViewHeight
        scrollView.contentOffset.y = 0 // block scroll view

    }
}
</code>```

Body:
First of all add header view as UIvVew and add UIScrollView or UITableView below headerView same as screenshot and follow below step.

set a fixed height constraint to the header view (125 for example) and attach it to top, left and right.

make the UIScrollView below to use all the available space so set to zero top, bottom, left and right constraints.

 connect the header view height constraint to the ViewController in order to have something like:

 @IBOutlet var headerViewHeightConstraint: NSLayoutConstraint!

set the UIScrollView delegate to the ViewController

declare two properties to limit the maximum and the minimum height of the header view, fox example:

let headerViewMaxHeight: CGFloat = 125
let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height

The entire workaround is based on update the header view height constraint while the UIScrollView is scrolling, so let’s implement the UIScrollViewDelegate and the most important delegate for our case, the scrollViewDidScroll:

func scrollViewDidScroll(_ scrollView: UIScrollView) {

    let headerViewMinHeight: CGFloat = 44 + UIApplication.shared.statusBarFrame.height

    let yPos = mainScrollView.contentOffset.y
    let newHeaderViewHeight: CGFloat = headerViewHeightConstraint.constant - yPos

    if newHeaderViewHeight > headerViewMaxHeight {
        // Here, Manage Your Score Format View
        headerViewHeightConstraint.constant = max(headerViewMaxHeight, newHeaderViewHeight)

    } else if newHeaderViewHeight < headerViewMinHeight {

    headerViewHeightConstraint.constant = headerViewMinHeight

    } else {

        headerViewHeightConstraint.constant = newHeaderViewHeight
        scrollView.contentOffset.y = 0 // block scroll view

    }
}


问:
how to see modern view in Sencha Ext.js Universal application
Im using sencha ext-6.5.3.57 and creating a universal application using the below command.
sencha -sdk C:\Users\AANANTHA\sencha-sdks\ext-6.5.3.57 generate app MyApp

Once i build and launch the app using sencha app watch command i can see and modify only classic view , if i change anything in modern view its not reflecting in the app.

Please suggest as i'm new to sencha.

I tried changing the code in classic view and modern view js files .But i can see changes reflecting only in classic view .

答:
You have to define a condition to select a specific profile to show to the user.
If you have just made a fresh universal app, this condition is located in index.html, in Ext.beforeLoad you'll see the profile is set based on the url.

So for testing purposes you can change your profile putting ?classic or ?modern at the end of your url, if you need or want to create other profiles, you can define them in app.json in the builds part.


问:
Crystal Reports V11 Showing different boolean values per machine
I'm getting a weird issue with Crystal - I have a basic report that displays records dependant on a boolean value ('open') being true.  However, on some PCs it works fine, on others it just shows displays a blank report.

Having done a bit of checking into this, viewing the SQL query seems to indicate that there's an issue with how Crystal is interpreting the boolean value on different machines.

If we select 'Show SQL query' on each of the machines, the ones that don't work show the boolean section as:

```<code>`support`.`open`=1
</code>```

The ones that work show:

```<code> `support`.`open`=.T.
</code>```

...which seems more realistic due to the datasource being a VFP table via an ODBC driver.

I can't quite figure this one out - I suppose it's possible it's something to do with the ODBC driver.  Does anybody have any clues as to why this might be happening?

Thanks

答:
The boolean should be directly interpreted through the ODBC...  I would change the query to just have

Where 'support.open'

If logical, it will only be .T. / .F.   or  true / false   or 1 / 0... Let the ODBC handler handle it for you.

--- Edit via comment.

I wasn't referring to Crystal's report formula, but the query...  But if thats the issue in Crystal, I would change the query that is RETRIEVING the data to be...

IIF( support.open, "YES", "NO " ) as ItemIsOpen

VFP OleDB / ODBC should recognize the IIF() and return the column to a string of "YES" or "NO " respectively... Then use the "ItemIsOpen" column in your report instead of the "support.open" column.

Body:
I'm getting a weird issue with Crystal - I have a basic report that displays records dependant on a boolean value ('open') being true.  However, on some PCs it works fine, on others it just shows displays a blank report.

Having done a bit of checking into this, viewing the SQL query seems to indicate that there's an issue with how Crystal is interpreting the boolean value on different machines.

If we select 'Show SQL query' on each of the machines, the ones that don't work show the boolean section as:

`support`.`open`=1

The ones that work show:

 `support`.`open`=.T.

...which seems more realistic due to the datasource being a VFP table via an ODBC driver.

I can't quite figure this one out - I suppose it's possible it's something to do with the ODBC driver.  Does anybody have any clues as to why this might be happening?

Thanks


问:
Why is this query slow, where id in (sub select that returns null)
I'm having a hard time understanding why this query is taking more than 1ms.

```<code>EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (SELECT "city_locations"."id"
                                         FROM "city_locations"
                                         WHERE "city_locations"."type" IN ('Arrondissement')
                                        AND "city_locations"."arrondissement_city_id" = 56));

QUERY PLAN

 Aggregate  (cost=6583.49..6583.50 rows=1 width=32) (actual time=21.702..21.702 rows=1 loops=1)
   ->  Seq Scan on adverts  (cost=6.31..6533.88 rows=19842 width=4) (actual time=0.462..21.684 rows=44 loops=1)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text) AND ((city_location_id = 56) OR (hashed SubPlan 1)))
         Rows Removed by Filter: 46217
         SubPlan 1
           ->  Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.008..0.008 rows=0 loops=1)
                 Index Cond: (arrondissement_city_id = 56)
                 Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.173 ms
 Execution Time: 21.739 ms
</code>```

The execution time is 21ms

If I execute the sub request I get:

```<code>EXPLAIN ANALYZE SELECT "city_locations"."id" FROM "city_locations" WHERE "city_locations"."type" IN ('Arrondissement') AND "city_locations"."arrondissement_city_id" = 56;
 id
----
(0 rows)

QUERY PLAN

 Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.028..0.028 rows=0 loops=1)
   Index Cond: (arrondissement_city_id = 56)
   Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.233 ms
 Execution Time: 0.075 ms
</code>```

execution time is: 0.075ms, super fast and the result is NULL.

When I replace the sub request by its result NULL it is super fast.

```<code>EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (NULL));

QUERY PLAN

 Aggregate  (cost=162.66..162.67 rows=1 width=32) (actual time=0.309..0.310 rows=1 loops=1)
   ->  Bitmap Heap Scan on adverts  (cost=4.72..162.55 rows=42 width=4) (actual time=0.082..0.278 rows=44 loops=1)
         Recheck Cond: (city_location_id = 56)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text))
         Heap Blocks: exact=42
         ->  Bitmap Index Scan on index_adverts_on_city_location_id_and_visible  (cost=0.00..4.71 rows=42 width=0) (actual time=0.043..0.044 rows=44 loops=1)
               Index Cond: ((city_location_id = 56) AND (visible = true))
 Planning Time: 0.395 ms
 Execution Time: 0.412 ms
</code>```

The execution time is 0.412 ms

My question is why is the first request slow when its separate requests are fast?

Do I miss some optimization due to the WHERE IN clause?

答:
First:simplify

```<code>EXPLAIN ANALYZE
SELECT AVG(ad.price)
FROM adverts a
WHERE a.type IN ('Businesses::Restaurant')
AND a.discarded_at IS NULL
AND a.visible = true
AND (a.city_location_id = 56
     OR a.city_location_id IN (
        SELECT c.id
        FROM city_locations c
        WHERE c.type IN ('Arrondissement')
        AND c.arrondissement_city_id = 56))
        ;
</code>```

Next:rewrite theIN(...) into EXISTS(...)

```<code>EXPLAIN ANALYZE
SELECT AVG(a.price)
FROM adverts a
WHERE a.type IN ('Businesses::Restaurant')
AND a.discarded_at IS NULL
AND a.visible = true
AND (a.city_location_id = 56
     OR EXISTS(
        SELECT *
        FROM city_locations c
        WHERE a.city_location_id = c.id
        AND c.type IN ('Arrondissement')
        AND c.arrondissement_city_id = 56))
        ;
</code>```

Now,you can push the ugly OR into the subquery:
(assuming the subquery has lower cardinality)

-> The optimizer will probably not be smart enough to push this OR term down

```<code>EXPLAIN ANALYZE
SELECT AVG(a.price)
FROM adverts a
WHERE a.type IN ('Businesses::Restaurant')
AND a.discarded_at IS NULL
AND a.visible = true
AND EXISTS(
        SELECT *
        FROM city_locations c
        WHERE a.city_location_id = c.id
        AND (c.type IN ('Arrondissement') AND c.arrondissement_city_id = 56
            OR c.city_location_id = 56
                )
        ;
</code>```

If the subquery has a small enough result set, you could try to move it to a CTE.

Body:
I'm having a hard time understanding why this query is taking more than 1ms.

EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (SELECT "city_locations"."id"
                                         FROM "city_locations"
                                         WHERE "city_locations"."type" IN ('Arrondissement')
                                        AND "city_locations"."arrondissement_city_id" = 56));

QUERY PLAN

 Aggregate  (cost=6583.49..6583.50 rows=1 width=32) (actual time=21.702..21.702 rows=1 loops=1)
   ->  Seq Scan on adverts  (cost=6.31..6533.88 rows=19842 width=4) (actual time=0.462..21.684 rows=44 loops=1)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text) AND ((city_location_id = 56) OR (hashed SubPlan 1)))
         Rows Removed by Filter: 46217
         SubPlan 1
           ->  Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.008..0.008 rows=0 loops=1)
                 Index Cond: (arrondissement_city_id = 56)
                 Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.173 ms
 Execution Time: 21.739 ms

The execution time is 21ms

If I execute the sub request I get:

EXPLAIN ANALYZE SELECT "city_locations"."id" FROM "city_locations" WHERE "city_locations"."type" IN ('Arrondissement') AND "city_locations"."arrondissement_city_id" = 56;
 id
----
(0 rows)

QUERY PLAN

 Index Scan using index_city_locations_on_arrondissement_city_id on city_locations  (cost=0.29..6.31 rows=1 width=8) (actual time=0.028..0.028 rows=0 loops=1)
   Index Cond: (arrondissement_city_id = 56)
   Filter: ((type)::text = 'Arrondissement'::text)
 Planning Time: 0.233 ms
 Execution Time: 0.075 ms

execution time is: 0.075ms, super fast and the result is NULL.

When I replace the sub request by its result NULL it is super fast.

EXPLAIN ANALYZE SELECT AVG("adverts"."price")
FROM "adverts" WHERE "adverts"."type" IN ('Businesses::Restaurant')
AND "adverts"."discarded_at" IS NULL AND "adverts"."visible" = true
AND ("adverts"."city_location_id" = 56
     OR "adverts"."city_location_id" IN (NULL));

QUERY PLAN

 Aggregate  (cost=162.66..162.67 rows=1 width=32) (actual time=0.309..0.310 rows=1 loops=1)
   ->  Bitmap Heap Scan on adverts  (cost=4.72..162.55 rows=42 width=4) (actual time=0.082..0.278 rows=44 loops=1)
         Recheck Cond: (city_location_id = 56)
         Filter: ((discarded_at IS NULL) AND visible AND ((type)::text = 'Businesses::Restaurant'::text))
         Heap Blocks: exact=42
         ->  Bitmap Index Scan on index_adverts_on_city_location_id_and_visible  (cost=0.00..4.71 rows=42 width=0) (actual time=0.043..0.044 rows=44 loops=1)
               Index Cond: ((city_location_id = 56) AND (visible = true))
 Planning Time: 0.395 ms
 Execution Time: 0.412 ms

The execution time is 0.412 ms

My question is why is the first request slow when its separate requests are fast?

Do I miss some optimization due to the WHERE IN clause?

Body:
First:simplify

EXPLAIN ANALYZE
SELECT AVG(ad.price)
FROM adverts a
WHERE a.type IN ('Businesses::Restaurant')
AND a.discarded_at IS NULL
AND a.visible = true
AND (a.city_location_id = 56
     OR a.city_location_id IN (
        SELECT c.id
        FROM city_locations c
        WHERE c.type IN ('Arrondissement')
        AND c.arrondissement_city_id = 56))
        ;

Next:rewrite theIN(...) into EXISTS(...)

EXPLAIN ANALYZE
SELECT AVG(a.price)
FROM adverts a
WHERE a.type IN ('Businesses::Restaurant')
AND a.discarded_at IS NULL
AND a.visible = true
AND (a.city_location_id = 56
     OR EXISTS(
        SELECT *
        FROM city_locations c
        WHERE a.city_location_id = c.id
        AND c.type IN ('Arrondissement')
        AND c.arrondissement_city_id = 56))
        ;

Now,you can push the ugly OR into the subquery:
(assuming the subquery has lower cardinality)

-> The optimizer will probably not be smart enough to push this OR term down

EXPLAIN ANALYZE
SELECT AVG(a.price)
FROM adverts a
WHERE a.type IN ('Businesses::Restaurant')
AND a.discarded_at IS NULL
AND a.visible = true
AND EXISTS(
        SELECT *
        FROM city_locations c
        WHERE a.city_location_id = c.id
        AND (c.type IN ('Arrondissement') AND c.arrondissement_city_id = 56
            OR c.city_location_id = 56
                )
        ;

If the subquery has a small enough result set, you could try to move it to a CTE.


问:
Is there a way for a client side app to work with server, which doesn't have CORS set
I want to make a call to a 3rd party desktop app running, in a user's system, which has a port open at 3000, and when user opens my website, I make a request to his localhost:3000 port and fetch data, but the 3rd party app doesn't have response headers set for CORS, so I am not able to use this strategy to sync, Do anyone know a way to do this?
In here, I have used ngrok to tunnel and still not able to do it.</p>

```<code>xhr.open("POST", 'https://576b4cc1.ngrok.io', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onreadystatechange = function () { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
        console.log("In ready state exchange: " + xhr.responseText);
        resolve();
    }
}
xhr.onload = function (data) {
    console.log("In onload : " + data);
}
xhr.onerror = function (err) {
    console.log("In error: " + JSON.stringify(err, ["message", "arguments", "type", "name"]));
    console.log('Data incase : ' + xhr.statusText);
}
xhr.send(reqObj.data);
</code>```

答:
You could launch your browser from command line with the flag for disabling web security, for example with chrome you can do the following:

```<code>chrome --disable-web-security
</code>```

There are also chrome plugins who allows you to do this like https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf

Body:
I want to make a call to a 3rd party desktop app running, in a user's system, which has a port open at 3000, and when user opens my website, I make a request to his localhost:3000 port and fetch data, but the 3rd party app doesn't have response headers set for CORS, so I am not able to use this strategy to sync, Do anyone know a way to do this?
In here, I have used ngrok to tunnel and still not able to do it.

xhr.open("POST", 'https://576b4cc1.ngrok.io', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onreadystatechange = function () { // Call a function when the state changes.
    if (this.readyState === XMLHttpRequest.DONE && this.status === 200) {
        // Request finished. Do processing here.
        console.log("In ready state exchange: " + xhr.responseText);
        resolve();
    }
}
xhr.onload = function (data) {
    console.log("In onload : " + data);
}
xhr.onerror = function (err) {
    console.log("In error: " + JSON.stringify(err, ["message", "arguments", "type", "name"]));
    console.log('Data incase : ' + xhr.statusText);
}
xhr.send(reqObj.data);

Body:
You could launch your browser from command line with the flag for disabling web security, for example with chrome you can do the following:

chrome --disable-web-security

There are also chrome plugins who allows you to do this like https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf


问:
Get the summation of values at column level in a text file using shell
My query is simple to get the summation of values at column level in a text file using shell -- i.e. to add a new record in the text file which includes the sum.

For example here below:

```<code>name usersToday usersTommorrow
Data1 92 181
DataTwo 5 7
Something 61 73
Something_with_long_name 0 0
</code>```

the desired output is

```<code>name usersToday usersTommorrow
Data1 92 181
DataTwo 5 7
Something 61 73
Something_with_long_name 0 0
Total 158 262
</code>```

Please note that the text file will be updated with a new data column periodically everyday.

so on day 2 - post the commands for summation are updated the file will be like

```<code>name usersToday day2
Data1 92 181
DataTwo 5 7
Something 61 73
Something_with_long_name 0 0
Total 158 262
</code>```

On day 3 - post new data is appended the file will be like

```<code>name usersToday day2 day3
Data1 92 181 52
DataTwo 5 7 53
Something 61 73 25
Something_with_long_name 0 0 26
Total 158 262
</code>```

so I want the summation for day3 needs to be updated.

答:
Considering that your actual Input_file will be same as shown samples, could you please try following then.</p>

```<code>awk 'FNR>1 && NF{first+=$2;second+=$3} 1; END{print "Total "first,second}' Input_file
</code>```

Body:
My query is simple to get the summation of values at column level in a text file using shell -- i.e. to add a new record in the text file which includes the sum.

For example here below:

name usersToday usersTommorrow
Data1 92 181
DataTwo 5 7
Something 61 73
Something_with_long_name 0 0

the desired output is

name usersToday usersTommorrow
Data1 92 181
DataTwo 5 7
Something 61 73
Something_with_long_name 0 0
Total 158 262

Please note that the text file will be updated with a new data column periodically everyday.

so on day 2 - post the commands for summation are updated the file will be like

name usersToday day2
Data1 92 181
DataTwo 5 7
Something 61 73
Something_with_long_name 0 0
Total 158 262

On day 3 - post new data is appended the file will be like

name usersToday day2 day3
Data1 92 181 52
DataTwo 5 7 53
Something 61 73 25
Something_with_long_name 0 0 26
Total 158 262

so I want the summation for day3 needs to be updated.

Body:
Considering that your actual Input_file will be same as shown samples, could you please try following then.

awk 'FNR>1 && NF{first+=$2;second+=$3} 1; END{print "Total "first,second}' Input_file


问:
RewriteEngine URL to php _get arguments
On my website I want to internally execute a url like mydomain.com/dir/test as mydomain.com/dir/process.php?arg=test

I already created a htaccess file within the folder "dir", and when I try to access mydomain.com/dir/test, it displays the page of process.php, but when I try to access $_GET["arg"], it does not contain the string test but the string process.php.

My .htaccess:

```<code>RewriteEngine On
RewriteRule ^(.*)$ process.php?arg=$1 [L]
</code>```

答:
Reason for your result is a rewriting loop. You try to stop the rewriting process by using the [L] flag, but as many others you miss understand what that flag actually does. It does not end the rewriting process, but only the current run of that process. In your case the rewriting process starts another run and again rewrites your already rewritten request. In the second run the pattern ^(.*)$ matches what you have rewritten to in the first run, that explains your outcome.

You have two options to solve this.

1) use a condition to prevent the second rewriting run:

```<code>RewriteEngine On
RewriteCond %{REQEUEST_URI} !/process\.php$
RewriteRule ^(.*)$ process.php?arg=$1 [L]
</code>```

2) use the END flag which is provided by newer versions of the apache http server:

```<code>RewriteEngine On
RewriteRule ^(.*)$ process.php?arg=$1 [END]
</code>```

In case you receive an internal server error (http status 500) using that second rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Title: RewriteEngine URL to php _get arguments

Body:
On my website I want to internally execute a url like mydomain.com/dir/test as mydomain.com/dir/process.php?arg=test

I already created a htaccess file within the folder "dir", and when I try to access mydomain.com/dir/test, it displays the page of process.php, but when I try to access $_GET["arg"], it does not contain the string test but the string process.php.

My .htaccess:

RewriteEngine On
RewriteRule ^(.*)$ process.php?arg=$1 [L]

Body:
Reason for your result is a rewriting loop. You try to stop the rewriting process by using the [L] flag, but as many others you miss understand what that flag actually does. It does not end the rewriting process, but only the current run of that process. In your case the rewriting process starts another run and again rewrites your already rewritten request. In the second run the pattern ^(.*)$ matches what you have rewritten to in the first run, that explains your outcome.

You have two options to solve this.

1) use a condition to prevent the second rewriting run:

RewriteEngine On
RewriteCond %{REQEUEST_URI} !/process\.php$
RewriteRule ^(.*)$ process.php?arg=$1 [L]

2) use the END flag which is provided by newer versions of the apache http server:

RewriteEngine On
RewriteRule ^(.*)$ process.php?arg=$1 [END]

In case you receive an internal server error (http status 500) using that second rule above then chances are that you operate a very old version of the apache http server. You will see a definite hint to an unsupported [END] flag in your http servers error log file in that case.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).


问:
Explicit specialization of member function with variadic template arguments
I am writing a templated Event Handler that allows the user to send events (in the form of structs) to connected listeners.

I have an "emit" member function that will construct an Event object from the provided variadic template parameters and forward the event. However, I would like to provide a specialised "emit" function that will detect if the provided argument is a pre-constructed Event object, in which case I could forward the event without making a superfluous copy.

My initial attempt...

template <typename T_Event>
class EventHandler
{
public:

  template <typename... T_Args>
  void emit(T_Args&&... args)
  {
    printf("variadic\n");
    deliver(T_Event {std::forward<T_Args>(args)...});
  }

  void emit(const T_Event& event)
  {
    printf("reference\n");
    deliver(event);
  }

  ...
};
```

<p>I used the following logic to try out both of the emit functions, but it turns out the variadic template function always takes precedence over the const reference function.</p>

```struct Event { int x; };

EventHandler<Event> handler;
Event event {1};
handler.emit(event);
handler.emit(2);
```

<p>After some more research I managed to acheive my goal by defining two versions of the variadic template function and using enable_if to execute the correct one.</p>

```  template <typename... T_Args>
  void emit(T_Args&&... args)
  {
    printf("variadic\n");
    T_Event event {std::forward<T_Args>(args)...};
    deliver(event);
  }

  template <typename... T_Args, typename = std::enable_if<std::is_same<const T_Event&, T_Args...>::value>>
  void emit(T_Args&&... args)
  {
    printf("reference\n");
    deliver(std::forward<T_Args>(args)...);
  }
```

<p>This solution worked exactly as I need when I compile with GCC, but if I compile with CLANG I get the following error message:</p>

```  call to member function 'emit' is ambiguous
handler.emit(event);

  candidate function [with T_Args = <EventB &>]
void emit(T_Args&&... args)

  candidate function [with T_Args = <EventB &>, $1 =
  std::__1::enable_if<false, void>]
void emit(T_Args&&... args)
```

I assume that I am close to the correct solution, can anyone explain what I am doing wrong?

答:
The trick is to force the variadic template to fail overload resolution for the parameter pack that consists of a single (optional reference to an optional const-qualified) parameter.

This is done by dropping references and const-qualifiers from each type in the parameter pack, assembling a tuple out of them, and using std::is_same, just like in your attempt, to compare the resulting type to std::tuple<T_Event>, and then fail overload resolution in that case by negating the type traits (it is not a std::tuple<T_Event>.

```<code>#include <type_traits>
#include <tuple>
#include <iostream>

template <typename T_Event>
class EventHandler
{
public:

    template <typename... T_Args,
          typename=std::enable_if_t
          <std::negation<std::is_same
                 <std::tuple<std::remove_const_t
                         <std::remove_reference_t
                          <T_Args>>...>,
                          std::tuple<T_Event>>
                              >::value>>
    void emit(T_Args&&... args)
    {
        std::cout << "Variadic" << std::endl;
    }

    void emit(const T_Event& event)
    {
        std::cout << "Reference" << std::endl;
    }
};

int main()
{
    EventHandler<const char *> foo;
    const char *bar="foobar";

    foo.emit(4);
    foo.emit(4, "bar");
    foo.emit(bar);
    return 0;
}
</code>```

Tested with g++ with -std=c++17. This should be doable with C++11 and C++14 by reimplementing some of the missing type traits. End result:

```<code>$ g++ -o t -std=c++17 t.C
$ ./t
Variadic
Variadic
Reference
</code>```

Body:
I am writing a templated Event Handler that allows the user to send events (in the form of structs) to connected listeners.

I have an "emit" member function that will construct an Event object from the provided variadic template parameters and forward the event. However, I would like to provide a specialised "emit" function that will detect if the provided argument is a pre-constructed Event object, in which case I could forward the event without making a superfluous copy.

My initial attempt...

template <typename T_Event>
class EventHandler
{
public:

  template <typename... T_Args>
  void emit(T_Args&&... args)
  {
    printf("variadic\n");
    deliver(T_Event {std::forward<T_Args>(args)...});
  }

  void emit(const T_Event& event)
  {
    printf("reference\n");
    deliver(event);
  }

  ...
};

I used the following logic to try out both of the emit functions, but it turns out the variadic template function always takes precedence over the const reference function.

struct Event { int x; };

EventHandler<Event> handler;
Event event {1};
handler.emit(event);
handler.emit(2);

After some more research I managed to acheive my goal by defining two versions of the variadic template function and using enable_if to execute the correct one.

  template <typename... T_Args>
  void emit(T_Args&&... args)
  {
    printf("variadic\n");
    T_Event event {std::forward<T_Args>(args)...};
    deliver(event);
  }

  template <typename... T_Args, typename = std::enable_if<std::is_same<const T_Event&, T_Args...>::value>>
  void emit(T_Args&&... args)
  {
    printf("reference\n");
    deliver(std::forward<T_Args>(args)...);
  }

This solution worked exactly as I need when I compile with GCC, but if I compile with CLANG I get the following error message:

  call to member function 'emit' is ambiguous
handler.emit(event);

  candidate function [with T_Args = <EventB &>]
void emit(T_Args&&... args)

  candidate function [with T_Args = <EventB &>, $1 =
  std::__1::enable_if<false, void>]
void emit(T_Args&&... args)

I assume that I am close to the correct solution, can anyone explain what I am doing wrong?

Body:
The trick is to force the variadic template to fail overload resolution for the parameter pack that consists of a single (optional reference to an optional const-qualified) parameter.

This is done by dropping references and const-qualifiers from each type in the parameter pack, assembling a tuple out of them, and using std::is_same, just like in your attempt, to compare the resulting type to std::tuple<T_Event>, and then fail overload resolution in that case by negating the type traits (it is not a std::tuple<T_Event>.

#include <type_traits>
#include <tuple>
#include <iostream>

template <typename T_Event>
class EventHandler
{
public:

    template <typename... T_Args,
          typename=std::enable_if_t
          <std::negation<std::is_same
                 <std::tuple<std::remove_const_t
                         <std::remove_reference_t
                          <T_Args>>...>,
                          std::tuple<T_Event>>
                              >::value>>
    void emit(T_Args&&... args)
    {
        std::cout << "Variadic" << std::endl;
    }

    void emit(const T_Event& event)
    {
        std::cout << "Reference" << std::endl;
    }
};

int main()
{
    EventHandler<const char *> foo;
    const char *bar="foobar";

    foo.emit(4);
    foo.emit(4, "bar");
    foo.emit(bar);
    return 0;
}

Tested with g++ with -std=c++17. This should be doable with C++11 and C++14 by reimplementing some of the missing type traits. End result:

$ g++ -o t -std=c++17 t.C
$ ./t
Variadic
Variadic
Reference


问:
How to make POST request on BamBhooHr Api in C#
I want to add Employee on BamBhooHr using Bambhoohr REST API in MVC C#.

I have tried 2 content types to post as shown in the code but not succeed.

1==>

```<code>public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
  {
         var _resultModel = new BBHEmployee();
         var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
         var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
         var _url = $"{_bambhoohrApi}";

         var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
         var base64encodedData = System.Convert.ToBase64String(plainTextBytes);

            using (var _client = new HttpClient())
            {
                var _postData = new Dictionary<string, string>
                        {
                            { "firstName", fn },
                            { "lastName", ln }
                        };
                _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);

var _response = await _client.PostAsync(_url, new FormUrlEncodedContent(_postData));
                var _content = await _response.Content.ReadAsStringAsync();
                _resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
            }
            return Json(_resultModel, JsonRequestBehavior.AllowGet);
        }
</code>```

2==>

```<code>public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
        {
            var _resultModel = new BBHEmployee();
            var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
            var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
            var _url = $"{_bambhoohrApi}";

            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
            var base64encodedData = System.Convert.ToBase64String(plainTextBytes);

            using (var _client = new HttpClient())
            {
                                _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);
                _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var jsonString = "{\"firstName\":\"" + fn + "\",\"lastName\":\"" + ln + "\"}";
                StringContent _contt = new StringContent(jsonString, Encoding.UTF8, "application/json");

                var _response = await _client.PostAsync(_url, _contt);
                var _content = await _response.Content.ReadAsStringAsync();
                _resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
            }
            return Json(_resultModel, JsonRequestBehavior.AllowGet);
        }
</code>```

with both ways, it returns StatusCode 400(BadRequeest)

答:
in that case, this BambhooHr API endpoint requires XML data to post,
 so I use this and it's working fine.</p>

```<code>var xmlString = "<employee><field id = \"firstName\">"+fn+"</field><field id = \"lastName\">"+ln+"</field></employee>";
var _contt = new StringContent(xmlString,Encoding.UTF8, "text/xml");
var _response = await _client.PostAsync(_url, _contt);
</code>```

Body:
I want to add Employee on BamBhooHr using Bambhoohr REST API in MVC C#.

I have tried 2 content types to post as shown in the code but not succeed.

1==>

public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
  {
         var _resultModel = new BBHEmployee();
         var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
         var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
         var _url = $"{_bambhoohrApi}";

         var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
         var base64encodedData = System.Convert.ToBase64String(plainTextBytes);

            using (var _client = new HttpClient())
            {
                var _postData = new Dictionary<string, string>
                        {
                            { "firstName", fn },
                            { "lastName", ln }
                        };
                _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);

var _response = await _client.PostAsync(_url, new FormUrlEncodedContent(_postData));
                var _content = await _response.Content.ReadAsStringAsync();
                _resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
            }
            return Json(_resultModel, JsonRequestBehavior.AllowGet);
        }

2==>

public async System.Threading.Tasks.Task<JsonResult> AddEmployee(string fn,string ln)
        {
            var _resultModel = new BBHEmployee();
            var _bambhoohrApi = "https://epicsoftsandbox.bamboohr.com/api/gateway.php/epicsoftsandbox/v1/employees";
            var _apiKey = "b2aef724a48603468bfe85dce9e417ac8cf15fdf";
            var _url = $"{_bambhoohrApi}";

            var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(_apiKey + ":x");
            var base64encodedData = System.Convert.ToBase64String(plainTextBytes);

            using (var _client = new HttpClient())
            {
                                _client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encodedData);
                _client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                var jsonString = "{\"firstName\":\"" + fn + "\",\"lastName\":\"" + ln + "\"}";
                StringContent _contt = new StringContent(jsonString, Encoding.UTF8, "application/json");

                var _response = await _client.PostAsync(_url, _contt);
                var _content = await _response.Content.ReadAsStringAsync();
                _resultModel = JsonConvert.DeserializeObject<BBHEmployee>(_content);
            }
            return Json(_resultModel, JsonRequestBehavior.AllowGet);
        }

with both ways, it returns StatusCode 400(BadRequeest)

Body:
in that case, this BambhooHr API endpoint requires XML data to post,
 so I use this and it's working fine.

var xmlString = "<employee><field id = \"firstName\">"+fn+"</field><field id = \"lastName\">"+ln+"</field></employee>";
var _contt = new StringContent(xmlString,Encoding.UTF8, "text/xml");
var _response = await _client.PostAsync(_url, _contt);


问:
Browser not prompting for credentials using basic authentication
My goal is to provide authentication to a single resource on the server, for this I am using custom filter. I am not using @NameBinding because of constraint of using JAVA 1.6.Using Response.header(HttpHeaders.WWW_AUTHENTICATE,"Basic") is not prompting for credentials.

Using ContainerRequestFilter is not helping my cause as it will put filter on every resource of server.

Filter

```<code>@Provider
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        System.out.println("Entered authentication filter");

        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
                .header(HttpHeaders.AUTHORIZATION,"Basic")
                .entity("Credentials are required to access this resource.")
                .build());

//      chain.doFilter(req, resp);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {}

    @Override
    public void destroy() {}
}
</code>```

web.xml mapping

```<code><filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>Utils.LDAPAuthentication.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/download</url-pattern>
  </filter-mapping>
</code>```

The response I am getting on hitting the webservice is

答:
So as suggested by Paul , I used HttpServletResponse.

```<code>HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if(request.getHeader("Authorization")==null){
    response.setHeader(HttpHeaders.WWW_AUTHENTICATE,"Basic");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
else{
    String credentials = request.getHeader("Authorization");
}
</code>```

Body:
My goal is to provide authentication to a single resource on the server, for this I am using custom filter. I am not using @NameBinding because of constraint of using JAVA 1.6.Using Response.header(HttpHeaders.WWW_AUTHENTICATE,"Basic") is not prompting for credentials.

Using ContainerRequestFilter is not helping my cause as it will put filter on every resource of server.

Filter

@Provider
public class AuthenticationFilter implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp,
            FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;

        System.out.println("Entered authentication filter");

        throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED)
                .header(HttpHeaders.AUTHORIZATION,"Basic")
                .entity("Credentials are required to access this resource.")
                .build());

//      chain.doFilter(req, resp);

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {}

    @Override
    public void destroy() {}
}

web.xml mapping

<filter>
    <filter-name>AuthenticationFilter</filter-name>
    <filter-class>Utils.LDAPAuthentication.AuthenticationFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>AuthenticationFilter</filter-name>
    <url-pattern>/download</url-pattern>
  </filter-mapping>

The response I am getting on hitting the webservice is

Body:
So as suggested by Paul , I used HttpServletResponse.

HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if(request.getHeader("Authorization")==null){
    response.setHeader(HttpHeaders.WWW_AUTHENTICATE,"Basic");
    response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
}
else{
    String credentials = request.getHeader("Authorization");
}


问:
How to fix - Promise { <pending> } in Node.js and use it as variable anywhere
I'm accessing google API for converting coordinates into detailed objects using node-geocoder library from npmjs. Everything went well and I'm getting the expected object from geocoder API. The problem started the moment when I thought of using the data outside the promise function. I want to use the values outside the promise/async-await function.
Below is the code I've tried, Pls take a look and help me. TIA...

```<code>function goecoderPromiseFunction() {

    return new Promise(function (resolve, reject) {

        geocoder.reverse({ lat: 45.767, lon: 4.833 })

            .then(data => {

                cityName = data[0].city;

                resolve(cityName);

            })
            .catch(err => {

                console.log(err);

            });
    });

}

async function app() {

    var a = await goecoderPromiseFunction();
    return a;

}

var a = app();

console.log("a->", a);
</code>```

I expect the variable "a" should print the city name "Lyon", but it prints

a-> Promise { < pending > }

答:
It prints  because console.log("a->", a); runs while promise haven't returned answer for a variable "a"
Note: you haven't used reject function, if there is an error you wont notice and may be that error was the required answer to be carried by variable "a" that's why it still pending i.e still waiting.
For more idea try to use reject function inside the catch block example reject(err)
instead of console it out as you've done</p>

Body:
I'm accessing google API for converting coordinates into detailed objects using node-geocoder library from npmjs. Everything went well and I'm getting the expected object from geocoder API. The problem started the moment when I thought of using the data outside the promise function. I want to use the values outside the promise/async-await function.
Below is the code I've tried, Pls take a look and help me. TIA...

function goecoderPromiseFunction() {

    return new Promise(function (resolve, reject) {

        geocoder.reverse({ lat: 45.767, lon: 4.833 })

            .then(data => {

                cityName = data[0].city;

                resolve(cityName);

            })
            .catch(err => {

                console.log(err);

            });
    });

}

async function app() {

    var a = await goecoderPromiseFunction();
    return a;

}

var a = app();

console.log("a->", a);

I expect the variable "a" should print the city name "Lyon", but it prints

a-> Promise { < pending > }


问:
BigQuery Querying Events Table
Objective : To take the users count which has event_name= 'Wallet'

Problem : I have limited the query's result to 100 to check so the expected result must be 100 but when I use count(params.value.string_value) it shows 124 .

Code : SELECT count(params.value.string_value) FROM "myproj.analytics_197163127.events_20190528",UNNEST(event_params) as params where event_name ='Wallet' and params.key = 'UserId' limit 100

Expected Result : if the query is returning 100 records the count should be 100 but how is it showing 124?

Hope the question is clear

答:
limit is applied to the result set produced by the query.

Your query is an aggregation query with no group by.  Such an aggregation always returns one row.  So, the limit does not affect the results.

If you want to see 100 for the result set, use a CTE or subquery:

```<code>SELECT count(params.value.string_value)
FROM (SELECT params
      FROM "myproj.analytics_197163127.events_20190528" e CROSS JOIN
           UNNEST(e.event_params) params
      WHERE e.event_name ='Wallet' AND params.key = 'UserId'
      LIMIT 100
     ) ep
</code>```

Title: BigQuery Querying Events Table

Body:
limit is applied to the result set produced by the query.

Your query is an aggregation query with no group by.  Such an aggregation always returns one row.  So, the limit does not affect the results.

If you want to see 100 for the result set, use a CTE or subquery:

SELECT count(params.value.string_value)
FROM (SELECT params
      FROM "myproj.analytics_197163127.events_20190528" e CROSS JOIN
           UNNEST(e.event_params) params
      WHERE e.event_name ='Wallet' AND params.key = 'UserId'
      LIMIT 100
     ) ep