问:
node label expression in Jenkins Scripted Pipeline
I use a scripted Jenkins Pipeline and want to define a label expression like expr1 AND NOT expr2.

So I used node('expr1 && !expr2'){}, but that (sometimes) allocated a node which does have both expr1 and expr2.

I also tried with node('expr1' && '!expr2'){} but same result.

What is the correct syntax to say expr1 AND NOT expr2 in scripted pipeline?

答:
Try (label1) && !(label2)

Koshuke details label improvements to Jenkins here (old):
https://jenkins.io/blog/2010/09/02/recent-label-and-matrix-project-improvement/

But it is perhaps better summarized here:
https://kb.novaordis.com/index.php/Jenkins_Job_Label_Expression

Operators

Specified in the descending order of precedence:

(expression) - defines the associativity of the expression.

!expression - negation.

a && b - AND, both expressions must true.

a || b - OR, either of the expression a or b may be true.

a -> b - "implies" operator, equivalent with !a || b. For example if "linux -> x64" expression is used, it is interpreted as follows: if a Linux agent is used, then the agent must be 64 bit.

a <-> b - "if and only if" operator, equivalent to a && b || !a && !b

Also, in the official docs:
https://jenkins.io/doc/pipeline/steps/workflow-durable-task-step/#node-allocate-node


来源: stackexchange

问:
Apache Beam Python: How to implement MapState in the python apache beam sdk?
I am trying to create a stateful ParDo in apache beam that stores a dict of  values and updates that dict with data from subsequent windows.
The equivalent being MapState in java.
I have tried to implement it using a custom CombineFn

```<code>class DictCombineFn(beam.CombineFn):
    def create_accumulator(self):
        return {}

    def add_input(self, accumulator, element):
        accumulator[element["key"]] = element["value"]
        return accumulator

    def merge_accumulators(self, accumulators):
        return accumulators

    def extract_output(self, accumulator):
        return accumulator
</code>```

Which is used in the CombiningValueStateSpec of the following ParDo:

```<code>class EnrichDoFn(beam.DoFn):

    DICT_STATE = CombiningValueStateSpec(
        'dict',
        PickleCoder(),
        DictCombineFn()
    )

    def process(
              self,
              element,
              w=beam.DoFn.WindowParam,
              dict_state=beam.DoFn.StateParam(DICT_STATE)
        ):
           asks_state.add(element)
</code>```

However I get the following error during :

TypeError: '_ConcatIterable' object does not support item assignment

I think this might be as a result of using the wrong coder?
What would be the optimal strategy to implement the aforementioned logic?

Thanks

答: Merge accumulators should return one element, not iterable like in your case. You would do similar processing like in add element.</p>

ContentLicense: CC BY-SA 4.0

Body:
I am trying to create a stateful ParDo in apache beam that stores a dict of  values and updates that dict with data from subsequent windows.
The equivalent being MapState in java.
I have tried to implement it using a custom CombineFn

class DictCombineFn(beam.CombineFn):
    def create_accumulator(self):
        return {}

    def add_input(self, accumulator, element):
        accumulator[element["key"]] = element["value"]
        return accumulator

    def merge_accumulators(self, accumulators):
        return accumulators

    def extract_output(self, accumulator):
        return accumulator

Which is used in the CombiningValueStateSpec of the following ParDo:

class EnrichDoFn(beam.DoFn):

    DICT_STATE = CombiningValueStateSpec(
        'dict',
        PickleCoder(),
        DictCombineFn()
    )

    def process(
              self,
              element,
              w=beam.DoFn.WindowParam,
              dict_state=beam.DoFn.StateParam(DICT_STATE)
        ):
           asks_state.add(element)

However I get the following error during :

TypeError: '_ConcatIterable' object does not support item assignment

I think this might be as a result of using the wrong coder?
What would be the optimal strategy to implement the aforementioned logic?

Thanks


问:
Need to apply class based on the condition in the header of the table
I need to implement a specific class on the td based on if else condition. If you see my code I am looping through th and td elements.  I need to either blank the text in the th or set the color to white if the th class name equals Legal Class ID so that header text is not visible. I have created a class called cellbgcolor. I need to apply only if the header text is  Legal Class ID for all others it should apply class tableItem bold. How do I do that. I have shared the html and jsfiddle below

html

```<code>  <style>
      .cellbgcolor {
        color: white;
    }
   </style>

    <div *ngIf="LegalFundClasses && LegalFundClasses.LegalFundClassDetailsViewModel && ColumnNames">
         <table class="fundClassesTable table-striped">
          <tr *ngFor="let c of ColumnNames">
            <th class="tableItem bold">{{ c }}</th>
            <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
              <td class="tableItem" *ngIf="c == ColumnNames[0]">{{f.Description}}</td>
              <td class="tableItem" *ngIf="c == ColumnNames[1]">{{f.AuditSummary}}</td>
              <td class="tableItem" *ngIf="c == ColumnNames[2]">{{f.Id}}</td
            </ng-container>
          </tr>
        </table>
      </div>

 Component

  public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];
</code>```

Here is the JSFiddle

https://jsfiddle.net/zyk9xhd1/2/

答:
Try this, hope this helps..

```<code><th [ngClass]="{'cellbgcolor':c == ColumnNames[2],'tableItem bold':c != ColumnNames[2]}">{{ c }}</th>
</code>```

OR

```<code><th [ngClass]="c == ColumnNames[2] ? 'cellbgcolor' : 'tableItem bold'">...</th>
</code>```

Body:
I need to implement a specific class on the td based on if else condition. If you see my code I am looping through th and td elements.  I need to either blank the text in the th or set the color to white if the th class name equals Legal Class ID so that header text is not visible. I have created a class called cellbgcolor. I need to apply only if the header text is  Legal Class ID for all others it should apply class tableItem bold. How do I do that. I have shared the html and jsfiddle below

html

            {{ c }}
            <ng-container *ngFor="let f of LegalFundClasses.LegalFundClassDetailsViewModel; let i=index">
              {{f.Description}}
              {{f.AuditSummary}}
              {{f.Id}}</td
            </ng-container>

 Component

  public ColumnNames: string[] = ['Legal Class Name',
                                    'Last Edited',
                                    'Legal Class ID'
                                  ];

Here is the JSFiddle

https://jsfiddle.net/zyk9xhd1/2/

Body:
Try this, hope this helps..

<th [ngClass]="{'cellbgcolor':c == ColumnNames[2],'tableItem bold':c != ColumnNames[2]}">{{ c }}</th>

OR

<th [ngClass]="c == ColumnNames[2] ? 'cellbgcolor' : 'tableItem bold'">...</th>


问:
Saga alternative for Vue
I finished learning Vue.js, it has had almost all I wanted from it!
But I can't find something similar to redux-saga. It was a very great tool, and it would be nice to have something like this.

Can someone propose alternative library, or share experience how to manage big projects with complex data-flow without redux-saga.

Did someone try to connect Redux-saga to Vue and use it (e.g. with that library)?
What was the experience?

答:
Have the same problem. I created new package called vuex-coolstory cause other packages is outdated.

Plus I did not use vuex actions to dispatch saga actions. I created new function store.sagaDispatch() and mapSagaActions() helper function for that.
I had to stop using vuex actions for saga actions, cause I must define them in store. And there are will be a lot unused empty functions. If you not define it in store, vuex print error message every time when you dispact action.

Title: Saga alternative for Vue


问:
Change authorization / login page
For self-hosted Bitrix24

What is the approach to change the "authorization page" / login page?

Do we need to rebuild the whole Bitrix24 from the source just to change the login page?

答:
No, you need change templates for component system.auth.form.

All standart components of Bitrix are in /bitrix/components/bitrix.

If you want change template of component system.auth.form, put new theme (copy dir .default in /bitrix/components/bitrix/system.auth.form/templates/.default) to /local/templates/.default/components/bitrix/system.auth.form and edit it.

Title: Change authorization / login page


问:
decrypting p7m with CMS and Luna Hsm on Jboss
I'm decrypting a p7m file trough BouncyCastle api ,backed by Luna HSM. In a single istance all works like a charm.If i deploy the same code in a Jboss in domain mode or two single node i get the following:
"LunaException: Unable to inject key" and  function 'C_UnwrapKey' returns 0x110 on key=xxxxxxx"

Note that the key handle doesn't exist on the hsm

I've tried to use the LunaProvider.jar as a system global module in order to avoid classloader problems, and also tried without. The client is configured correctly. If i run the application with two Boot instances on the two fisical nodes separately all works.Running in standalone tomcat also works

```<code>    CMSEnvelopedData envelopedData = new CMSEnvelopedData(encEnvelopedData);

        log.info("get recipient infos");
        RecipientInformationStore recipients = envelopedData.getRecipientInfos();
        log.info("get recipients size:{}",recipients==null?"null":recipients.size());
        //avoid assigning keys to java attributes since the operations are on the hsm
        RecipientInformation recipient = recipients.get(new JceKeyTransRecipientId((java.security.cert.X509Certificate)jcaProvider.getKeystore().getCertificate(alias)));
        if (recipient != null) {

            JceKeyTransEnvelopedRecipient trans=new JceKeyTransEnvelopedRecipient((PrivateKey)jcaProvider.getKeystore().getKey(alias,jcaProvider.getPwd().toCharArray()));

            trans.setProvider("LunaProvider");

            CMSTypedStream cmsTs= recipient.getContentStream(trans);
            return cmsTs.getContentStream();

</code>```

答:
You need to have set the key as extractable in order to work.
This is due to the fact the translated key is temporarily stored on the hsm.

To do so one can either:

add in java.security com.safenetinc.luna.provider.createExtractableKeys=true

using LunaSlotManager class set the keys as extractable

Sample of code for the slot manager class:

```<code>slotManager = LunaSlotManager.getInstance();

            slotManager.login(user, pwd);

            slotManager.setSecretKeysExtractable(true);
</code>```

Body:
I'm decrypting a p7m file trough BouncyCastle api ,backed by Luna HSM. In a single istance all works like a charm.If i deploy the same code in a Jboss in domain mode or two single node i get the following:
"LunaException: Unable to inject key" and  function 'C_UnwrapKey' returns 0x110 on key=xxxxxxx"

Note that the key handle doesn't exist on the hsm

I've tried to use the LunaProvider.jar as a system global module in order to avoid classloader problems, and also tried without. The client is configured correctly. If i run the application with two Boot instances on the two fisical nodes separately all works.Running in standalone tomcat also works

    CMSEnvelopedData envelopedData = new CMSEnvelopedData(encEnvelopedData);

        log.info("get recipient infos");
        RecipientInformationStore recipients = envelopedData.getRecipientInfos();
        log.info("get recipients size:{}",recipients==null?"null":recipients.size());
        //avoid assigning keys to java attributes since the operations are on the hsm
        RecipientInformation recipient = recipients.get(new JceKeyTransRecipientId((java.security.cert.X509Certificate)jcaProvider.getKeystore().getCertificate(alias)));
        if (recipient != null) {

            JceKeyTransEnvelopedRecipient trans=new JceKeyTransEnvelopedRecipient((PrivateKey)jcaProvider.getKeystore().getKey(alias,jcaProvider.getPwd().toCharArray()));

            trans.setProvider("LunaProvider");

            CMSTypedStream cmsTs= recipient.getContentStream(trans);
            return cmsTs.getContentStream();

Body:
You need to have set the key as extractable in order to work.
This is due to the fact the translated key is temporarily stored on the hsm.

To do so one can either:

add in java.security com.safenetinc.luna.provider.createExtractableKeys=true

using LunaSlotManager class set the keys as extractable

Sample of code for the slot manager class:

slotManager = LunaSlotManager.getInstance();

            slotManager.login(user, pwd);

            slotManager.setSecretKeysExtractable(true);


问:
Boolean Value cannot be stored in database (laravel)
so, i want to store a boolean value to database, but it always stored its default value (false). what i am doing is using Function Store as default

This is my UserController:

```<code> public function store(Request $request)
{
     $request->validate([
        'name'      =>'required',
        'email'     =>'required',
        'is_active'     =>'required',
        'password'  => 'required|string|min:6|max:191|confirmed',
        'password_confirmation' => 'required|same:password',
    ]);
      $user = new User;
      $user->name     = $request->name;
      $user->email    = $request->email;
      $user->password = Hash::make($request->password);
    $user->save();

    return redirect()->route('users.index')->with('success','Users created successfully');
}
</code>```

And this is my create form to submit:

```<code> <form action="{{ route('users.store') }}" method="POST">
              @csrf
              <div class="col-sm-9 form-left">
                <div class="form-group form-box">
                  <label for="name">Name</label>
                  <input type="text" class="form-control" id="name" name="name" placeholder="Name">
                </div>

                <div class="form-group form-box">
                  <label for="email">Email</label>
                  <input type="text" class="form-control" id="email" name="email" placeholder="Email">
                </div>

                <div class="form-group form-box">
                  <label for="password">Password</label>
                  <input type="password" class="form-control" id="password" name="password" placeholder="Password">
                </div>

                <div class="form-group form-box">
                  <label for="password_confirmation">Password Confirmation</label>
                  <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" placeholder="Password Confirmation">
                </div>

              </div>

              <div class="col-sm-3 form-right">
               <div class="form-group form-box">
                  <label for="is_active">Status</label>
                  <div class="radio">
                    <label><input type="radio" name="is_active" id="is_active" value="0" checked> Not Verified</label>
                  </div>
                  <div class="radio">
                    <label><input type="radio" name="is_active" id="is_active" value="1" > Verified</label>
                  </div>
                </div>

                <button type="submit" class="btn btn-default">Save</button>
              </div>

          </form>
</code>```

Did i Miss something?

答:
You forget to add this line. So it automatically saves the default value</p>

```<code>$user=$request->is_active;
</code>```

Body:
so, i want to store a boolean value to database, but it always stored its default value (false). what i am doing is using Function Store as default

This is my UserController:

 public function store(Request $request)
{
     $request->validate([
        'name'      =>'required',
        'email'     =>'required',
        'is_active'     =>'required',
        'password'  => 'required|string|min:6|max:191|confirmed',
        'password_confirmation' => 'required|same:password',
    ]);
      $user = new User;
      $user->name     = $request->name;
      $user->email    = $request->email;
      $user->password = Hash::make($request->password);
    $user->save();

    return redirect()->route('users.index')->with('success','Users created successfully');
}

And this is my create form to submit:

 <form action="{{ route('users.store') }}" method="POST">
              @csrf

                  Name
                  <input type="text" class="form-control" id="name" name="name" placeholder="Name">

                  Email
                  <input type="text" class="form-control" id="email" name="email" placeholder="Email">

                  Password
                  <input type="password" class="form-control" id="password" name="password" placeholder="Password">

                  Password Confirmation
                  <input type="password" class="form-control" id="password_confirmation" name="password_confirmation" placeholder="Password Confirmation">

                  Status

                    <input type="radio" name="is_active" id="is_active" value="0" checked> Not Verified

                    <input type="radio" name="is_active" id="is_active" value="1" > Verified

                <button type="submit" class="btn btn-default">Save</button>

          </form>

Did i Miss something?

Body:
You forget to add this line. So it automatically saves the default value

$user=$request->is_active;


问:
What event should i use to check when an input box loses focus in jquery
I have a function that is executed when a textbox gains focus and another function when it loses focus. problem is i dont know where to attach the function for the lost focus event. For the focus i am using</p>

```<code> $(" :input[class='Txtbox']").focus(function(){
        $(this).val("");

    });
</code>```

答:
```<code>$(" :input[class='Txtbox']").blur(function() {
});
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a function that is executed when a textbox gains focus and another function when it loses focus. problem is i dont know where to attach the function for the lost focus event. For the focus i am using

 $(" :input[class='Txtbox']").focus(function(){
        $(this).val("");

    });


问:
Setting up multiple services that can interact with one another WITHOUT docker-compose
I'm setting up ElasticsSearch, Kibana and Logstash in single docker container.
Every tutorial that I've found used docker-compose to configure services, however due to corporate machine's limitations I can't use docker-compose. How do I configure services (namely ES, kibana and logstash) so that these build properly, can run within single container and talk to one another?

I've tested building ElasticSearch and Kibana within single docker container on my local machine by describing services in docker-compose.yml and that succeeded.

```<code>version: "2"

services:

  elasticsearch:
    image: elasticsearch:6.5.4
    ports:
      - "9200:9200"
    volumes:
      - ./esdata/:/usr/share/elasticsearch/data/

  kibana:
    image: kibana:6.5.4
    ports:
      - "5601:5601"
    environment:
      - ELASTICSEARCH_URL=http://elasticsearch:9200
</code>```

The expected outcome would be to be able to build and run ES, Kibana and Logstash. These would be able to communicate with one another.
I currently know how to build these as completely separate containers, but don't know how to configure them to "cooperate" with one another without  docker-compose.

答:
The only important detail is that the two containers need to be on the same Docker network.  Docker Compose automatically creates a network for you, but if you're not using that tool, you'll need to do it manually.

docker network create elk
docker run --net elk --name elasticsearch ...
docker run --net elk --name kibana \
  -e ELASTICSEARCH_URL=http://elasticsearch:9200 ...
```

Body:
I'm setting up ElasticsSearch, Kibana and Logstash in single docker container.
Every tutorial that I've found used docker-compose to configure services, however due to corporate machine's limitations I can't use docker-compose. How do I configure services (namely ES, kibana and logstash) so that these build properly, can run within single container and talk to one another?

I've tested building ElasticSearch and Kibana within single docker container on my local machine by describing services in docker-compose.yml and that succeeded.

version: "2"

services:

  elasticsearch:
    image: elasticsearch:6.5.4
    ports:
      - "9200:9200"
    volumes:
      - ./esdata/:/usr/share/elasticsearch/data/

  kibana:
    image: kibana:6.5.4
    ports:
      - "5601:5601"
    environment:
      - ELASTICSEARCH_URL=http://elasticsearch:9200

The expected outcome would be to be able to build and run ES, Kibana and Logstash. These would be able to communicate with one another.
I currently know how to build these as completely separate containers, but don't know how to configure them to "cooperate" with one another without  docker-compose.


问:
Trouble Importing in Ipython: ImportError: No module named 'ipdb'
I've run pip install ipdb but when I run import ipdb in iPython I still get the error: ImportError: No module named 'ipdb'

What does this mean?

Similarly, when I'm importing files (with .py extension) in iPython, I'm also getting this error (ImportError: No module named Chapter_1_Python_Syntax) though I've checked the path to the directory and it's correct.

答:
ipdb comes with ipython, so if you already have ipython installed, you can access ipdb through that package using:

```<code>from IPython.core.debugger import Pdb
ipdb = Pdb()
</code>```

Then you could use ipdb just as you though you had done import ipdb, like:

```<code>ipdb.runcall(self, fun, *args, **kwds)
ipdb.run(self, cmd, globals = None, locals = None)
</code>```

If you don't have ipython installed, you can just use pdb which is the built-in debugger.

Body:
ipdb comes with ipython, so if you already have ipython installed, you can access ipdb through that package using:

from IPython.core.debugger import Pdb
ipdb = Pdb()

Then you could use ipdb just as you though you had done import ipdb, like:

ipdb.runcall(self, fun, *args, **kwds)
ipdb.run(self, cmd, globals = None, locals = None)

If you don't have ipython installed, you can just use pdb which is the built-in debugger.


问:
Correct names, but "dereferencing pointer to incomplete type"
I'm stuck with this error:

```<code>cities.c: In function ‘main’:
cities.c:7:48: error: dereferencing pointer to incomplete type ‘struct Graph’
  printf("well, it got here. nodeCount: %d\n", x->nodeCount);

</code>```

All other solutions point out that names are misspelled and thus undefined, however, if I move the struct Graph definition to the header, it works just fine.

I had previously used this mechanic in my other library and it still compiles just fine, I've spent hours trying to move things around to no avail.

graph.h:

```<code>#ifndef GRAPH_H
#define GRAPH_H

typedef struct Graph * Graph;

int graphCreate(Graph*, int);
int graphAddPath(Graph, int, int, unsigned int);
int graphRemovePath(Graph, int, int);
int graphDestroy(Graph*);

#endif /* GRAPH_H */
</code>```

graph.c: https://pastebin.com/FzkaJJwP

cities.c:

```<code>#include "graph.h"
#include <stdio.h>

int main() {
    Graph x;
    graphCreate(&x, 5);
    printf("well, it got here. nodeCount: %d\n", x->nodeCount);
}
</code>```

Output is as expected in my library at https://git.mif.vu.lt/emiliskiskis/c_deck.

Thank you for you help.

答:
The definition of the struct Graph is in the graph.c file. When you compile the cities.c file this definition is not visible.  You need to move the definition to graph.h

```<code>struct Graph {
   unsigned int **matrix;
   int nodeCount;
};
</code>```

As suggested by Blaze, the below definition is confusing. typedef struct Graph * Graph. A better solution would be to

```<code>typedef struct Graph Graph;
</code>```

and then in the code you can use

```<code>int graphCreate(Graph **, int);
int graphAddPath(Graph *, int, int, unsigned int);
int graphRemovePath(Graph *, int, int);
int graphDestroy(Graph **);
</code>```

Body:
I'm stuck with this error:

cities.c: In function ‘main’:
cities.c:7:48: error: dereferencing pointer to incomplete type ‘struct Graph’
  printf("well, it got here. nodeCount: %d\n", x->nodeCount);

All other solutions point out that names are misspelled and thus undefined, however, if I move the struct Graph definition to the header, it works just fine.

I had previously used this mechanic in my other library and it still compiles just fine, I've spent hours trying to move things around to no avail.

graph.h:

#ifndef GRAPH_H
#define GRAPH_H

typedef struct Graph * Graph;

int graphCreate(Graph*, int);
int graphAddPath(Graph, int, int, unsigned int);
int graphRemovePath(Graph, int, int);
int graphDestroy(Graph*);

#endif /* GRAPH_H */

graph.c: https://pastebin.com/FzkaJJwP

cities.c:

#include "graph.h"
#include <stdio.h>

int main() {
    Graph x;
    graphCreate(&x, 5);
    printf("well, it got here. nodeCount: %d\n", x->nodeCount);
}

Output is as expected in my library at https://git.mif.vu.lt/emiliskiskis/c_deck.

Thank you for you help.

Body:
The definition of the struct Graph is in the graph.c file. When you compile the cities.c file this definition is not visible.  You need to move the definition to graph.h

struct Graph {
   unsigned int **matrix;
   int nodeCount;
};

As suggested by Blaze, the below definition is confusing. typedef struct Graph * Graph. A better solution would be to

typedef struct Graph Graph;

and then in the code you can use

int graphCreate(Graph **, int);
int graphAddPath(Graph *, int, int, unsigned int);
int graphRemovePath(Graph *, int, int);
int graphDestroy(Graph **);


问:
datepicker beforeshowday return not working
I'm trying to use beforeShowDay to disable and highlight days from the calendar. I found this Fiddle code that works. When I return false it works and disables that day, but I am trying to return [false, 'holiday', ''] with a CSS class, but it's not working or not disabling dates.

        function add_zero(num){
        if(num<10){
            return '0'+num;
        }else{
            return num;
        }
    }
$('.date').datepicker({
  format: "mm-dd-yyyy",
  autoclose: true,
  daysOfWeekDisabled: [0],
  weekStart: [1],
  beforeShowDay: function(Date) {
    var array = <?php echo json_encode($arry); ?>;
    var curr_day = add_zero(Date.getDate());
    var curr_month = add_zero(Date.getMonth() + 1);
    var curr_year = Date.getFullYear();
    var curr_date = curr_month + '-' + curr_day + '-' + curr_year;

    for (i = 0; i < array.length; i++) {
      if (curr_date == array[i]) {
        // return false;
        return [false, 'holiday', ''];
      }
    }
    //return [true,''];
    return true;
  }
}).on('changeDate', cal_date);
```

答:
Mostly issue seems in your php date formats.

jsfiddle Link

```<code>var highlight = ['2019/05/19', '2019/05/20'];
//tips are optional but good to have
var tips = ['some description', 'some other description'];
var disable_dates = ['2019/05/01', '2019/05/08', '2019/05/15', '2019/05/22', '2019/05/29']
$('.date').datepicker({

  format: "mm-dd-yyyy",
  autoclose: true,
  daysOfWeekDisabled: [0],
  weekStart: [1],
  beforeShowDay: function (date) {
        var datestring = jQuery.datepicker.formatDate('yy/mm/dd', date);
        var hindex = $.inArray(datestring, highlight);
        if (hindex > -1) {
            return [true, 'highlight yourcustomcss', tips[hindex]];
        }
        var aindex = $.inArray(datestring, disable_dates);
                if(aindex == -1)
                    return [true,'custom_enabled']
                else
          return [false,'custom_disabled']
    }
})
</code>```

Body:
Mostly issue seems in your php date formats.

jsfiddle Link

var highlight = ['2019/05/19', '2019/05/20'];
//tips are optional but good to have
var tips = ['some description', 'some other description'];
var disable_dates = ['2019/05/01', '2019/05/08', '2019/05/15', '2019/05/22', '2019/05/29']
$('.date').datepicker({

  format: "mm-dd-yyyy",
  autoclose: true,
  daysOfWeekDisabled: [0],
  weekStart: [1],
  beforeShowDay: function (date) {
        var datestring = jQuery.datepicker.formatDate('yy/mm/dd', date);
        var hindex = $.inArray(datestring, highlight);
        if (hindex > -1) {
            return [true, 'highlight yourcustomcss', tips[hindex]];
        }
        var aindex = $.inArray(datestring, disable_dates);
                if(aindex == -1)
                    return [true,'custom_enabled']
                else
          return [false,'custom_disabled']
    }
})


问:
jQuery parents() and parent().parent() only see one level up?
I am having some issues with getting the list of parents of an element with jQuery.

Perhaps I am missing something, but I have a link inside several nested divs, and am trying to get a list of siblings of the parent's parent.

I only seem to be able to go one level up from the link though, so I can't

The HTML is as follows:

```<code><div class="alertcontainer">
   <div id="alertnode_1" class="alertnode">
      <div class="alertnodeheader">Escalate to Level 1</div>
      <div class="alertnodebody">
         <div class="bold">Alert these people:</div><br/>
         <div class="alertnodebodycontactlist">
            <div class="alertnodebodycontact">187
               <a id="d0.9659762698410487"
                  onclick="RemoveNode(this, 187)"
                  href="#">Remove Me...</a>
            </div>
            <div class="alertnodebodycontact">185
               <a id="d0.6609632486132389"
                  onclick="RemoveNode(this, 185)"
                  href="#">Remove Me...</a>
            </div>
            <div class="alertnodebodycontact">184
               <a id="d0.13180038199138278"
                  onclick="RemoveNode(this, 184)"
                  href="#">Remove Me...</a>
            </div>
            <div class="alertnodebodycontact">186
               <a id="d0.6364304467227213"
                  onclick="RemoveNode(this, 186)"
                  href="#">Remove Me...</a>
            </div>
            <select class="esccontactlist" id="esc_contact_list_1">
               <option>Also alert...</option>
            </select>
         </div>
         <br/>
      </div>
   </div>
</div>
</code>```

JS/jQuery as follows:

```<code>function RemoveNode(e, id)
{
   // Remove the contact
   $(e).parents().filter('.alertnodebodycontact').remove();

   // Add it back into the list.
   for ( var i = 0; i < ContactList.length; i++)
   {
      if ( id == ContactList[i]["ContactID"] )
      {
         $('#esc_contact_list_1')
            .append("<option value='"
               +ContactList[i]["ContactID"]
               +"'>  "
               +ContactList[i]["ContactName"]
               +" ("
               +ContactList[i]["PrimaryEmail"]
               +")</option>");
      }

      // Here, I want to count the number of '.alertnodebodycontact' divs.
      // However, $(e).parents() only returns a single item, which is the
      // '.alertnodebodycontact'  that the link is in.
      //  Likewise, $(e).parent().parent() returns nothing.

      // Anyone have any idea why the outer divs aren't being returned?

   }
}
</code>```

答: Nevermind... I am trying to access it after removing it.  Just need to re-order my tasks.</p>

OwnerDisplayName: Eli

ContentLicense: CC BY-SA 2.5

Body:
I am having some issues with getting the list of parents of an element with jQuery.

Perhaps I am missing something, but I have a link inside several nested divs, and am trying to get a list of siblings of the parent's parent.

I only seem to be able to go one level up from the link though, so I can't

The HTML is as follows:

Escalate to Level 1

Alert these people:

187
               Remove Me...

185
               Remove Me...

184
               Remove Me...

186
               Remove Me...

            <select class="esccontactlist" id="esc_contact_list_1">
               <option>Also alert...</option>
            </select>

JS/jQuery as follows:

function RemoveNode(e, id)
{
   // Remove the contact
   $(e).parents().filter('.alertnodebodycontact').remove();

   // Add it back into the list.
   for ( var i = 0; i < ContactList.length; i++)
   {
      if ( id == ContactList[i]["ContactID"] )
      {
         $('#esc_contact_list_1')
            .append("<option value='"
               +ContactList[i]["ContactID"]
               +"'>  "
               +ContactList[i]["ContactName"]
               +" ("
               +ContactList[i]["PrimaryEmail"]
               +")</option>");
      }

      // Here, I want to count the number of '.alertnodebodycontact' divs.
      // However, $(e).parents() only returns a single item, which is the
      // '.alertnodebodycontact'  that the link is in.
      //  Likewise, $(e).parent().parent() returns nothing.

      // Anyone have any idea why the outer divs aren't being returned?

   }
}


答:
The compiler message is pretty clear. The type is incomplete, which basically means that the compiler only knows that it exists a struct named Graph, but it does not know what it looks like. The consequence of this is that you cannot access the fields.

So, first you have to answer this question. Do you want the programmer that is using the library to be able to access the fields of Graph? If no, put the definition in the .c file. If yes, put the definition in the .h file.

One more thing to consider is typedef struct Graph * Graph. You're hiding an awful lot of information when typedefing a struct, and the same goes for when you are typedefing a pointer. Now you're doing both. My personal opinion is that you really should avoid doing this, unless the answer to the above question is "no".

My suggestion is, if you want the user of the library to be able to access the fields of struct Graph, remove the typedef completely. If you want to hide it from the user, code access functions, like this:

```<code>// cities.h
int getNodeCount(Graph g);
</code>```

```<code>// cities.c
int getNodeCount(struct Graph * g) {
    return g->nodeCount;
}
</code>```

And use it like this:

```<code>Graph g;
int nodeCount = getNodeCount(g);
</code>```

Do note that i did NOT use the typedef in the function definition. Only in it's prototype.

Title: Correct names, but "dereferencing pointer to incomplete type"

Body:
The compiler message is pretty clear. The type is incomplete, which basically means that the compiler only knows that it exists a struct named Graph, but it does not know what it looks like. The consequence of this is that you cannot access the fields.

So, first you have to answer this question. Do you want the programmer that is using the library to be able to access the fields of Graph? If no, put the definition in the .c file. If yes, put the definition in the .h file.

One more thing to consider is typedef struct Graph * Graph. You're hiding an awful lot of information when typedefing a struct, and the same goes for when you are typedefing a pointer. Now you're doing both. My personal opinion is that you really should avoid doing this, unless the answer to the above question is "no".

My suggestion is, if you want the user of the library to be able to access the fields of struct Graph, remove the typedef completely. If you want to hide it from the user, code access functions, like this:

// cities.h
int getNodeCount(Graph g);

// cities.c
int getNodeCount(struct Graph * g) {
    return g->nodeCount;
}

And use it like this:

Graph g;
int nodeCount = getNodeCount(g);

Do note that i did NOT use the typedef in the function definition. Only in it's prototype.


问:
How to stop a function from running with another function through class Objects
I just started learning about Object Oriented Javascript and i need some help figuring out how to cancel/stop a function from executing through another function.
I'm building (not really building just practicing) a class Music with a constructor holding a few parameters and basically i want to play and pause the music when i want.

I thought of making it bit interesting if i could count the seconds the moment i play the song and if i reach the amount of the seconds the song lasts to stop/pause the counter and continue playing it later on at the time i stopped.

The issue i'm having is I want to pause the counter but it seems that the counter continues to execute.

I have two functions within my class object. a play() and pause() functions.
At first i execute the play() function and before the "music" ends i execute the pause() which is suppose to stop the counter.

I tried adding to the constructor a patameter: this.isPlaying = false and when play() runs this.isPlaying becomes true and if i run pause() this.isPlaying becomes false again, stops the counter and gives me the amount of seconds it counted.

I do get the seconds back when i run pause() but the play() function is still running regardless.

```<code>class Music {
  constructor(title, uploader, seconds, isPlaying, startTime) {
    this.title = title;
    this.uploader = uploader;
    this.seconds = seconds;
    this.isPlaying = false;
    this.startTime = 0;
  }

  play() {
    if (!this.isPlaying && this.startTime == 0) {
      this.isPlaying = true;
      console.log('The song: ' + this.title + ' Started');
      var startSong = setInterval(() => {
        this.startTime++;
        if (this.startTime == this.seconds) {
          this.isPlaying = false;
          clearInterval(startSong);
          console.log("song ended");
        }
      }, 1000);
    } else {
      console.log(this.startTime);
      return;
    }
  }

  pause() {
    // console.log(this.isPlaying);
    console.log("executed pause");
    this.isPlaying = false;
  }
}

var fstSong = new Music('Stairways to Heaven', 'Pablo Fransisco', 15);
fstSong.play();
</code>```

I'm looking for the pause() to stop the counter and set the fstSong.startTime to the second that it stopped to.

答:
You can clear the interval declaring a global variable which you are using for setting up the interval and clearing the interval calling the pause function</p>

```<code>class Music {
  constructor(title, uploader, seconds, isPlaying, startTime) {
    this.title = title;
    this.uploader = uploader;
    this.seconds = seconds;
    this.isPlaying = false;
    this.startTime = 0;
  }

  play() {
    if (!this.isPlaying && this.startTime == 0) {
      this.isPlaying = true;
      console.log('The song: ' + this.title + ' Started');
      //setting a global variable
      window.startSong = setInterval(() => {
        this.startTime++;
        if (this.startTime == this.seconds) {
          this.isPlaying = false;
          clearInterval(window.startSong);
          console.log("song ended");
        }
      }, 1000);
    } else {
      console.log(this.startTime);
      return;
    }
  }

  pause() {
    // console.log(this.isPlaying);
    console.log("executed pause");
    this.isPlaying = false;
    clearInterval(window.startSong);// clearing the interval on click function
  }
}

var fstSong = new Music("song title","song uploader", 15);
fstSong.play();

//Calling pause function on click.
fstSong.pause();
</code>```

Body:
I just started learning about Object Oriented Javascript and i need some help figuring out how to cancel/stop a function from executing through another function.
I'm building (not really building just practicing) a class Music with a constructor holding a few parameters and basically i want to play and pause the music when i want.

I thought of making it bit interesting if i could count the seconds the moment i play the song and if i reach the amount of the seconds the song lasts to stop/pause the counter and continue playing it later on at the time i stopped.

The issue i'm having is I want to pause the counter but it seems that the counter continues to execute.

I have two functions within my class object. a play() and pause() functions.
At first i execute the play() function and before the "music" ends i execute the pause() which is suppose to stop the counter.

I tried adding to the constructor a patameter: this.isPlaying = false and when play() runs this.isPlaying becomes true and if i run pause() this.isPlaying becomes false again, stops the counter and gives me the amount of seconds it counted.

I do get the seconds back when i run pause() but the play() function is still running regardless.

class Music {
  constructor(title, uploader, seconds, isPlaying, startTime) {
    this.title = title;
    this.uploader = uploader;
    this.seconds = seconds;
    this.isPlaying = false;
    this.startTime = 0;
  }

  play() {
    if (!this.isPlaying && this.startTime == 0) {
      this.isPlaying = true;
      console.log('The song: ' + this.title + ' Started');
      var startSong = setInterval(() => {
        this.startTime++;
        if (this.startTime == this.seconds) {
          this.isPlaying = false;
          clearInterval(startSong);
          console.log("song ended");
        }
      }, 1000);
    } else {
      console.log(this.startTime);
      return;
    }
  }

  pause() {
    // console.log(this.isPlaying);
    console.log("executed pause");
    this.isPlaying = false;
  }
}

var fstSong = new Music('Stairways to Heaven', 'Pablo Fransisco', 15);
fstSong.play();

I'm looking for the pause() to stop the counter and set the fstSong.startTime to the second that it stopped to.

Body:
You can clear the interval declaring a global variable which you are using for setting up the interval and clearing the interval calling the pause function

class Music {
  constructor(title, uploader, seconds, isPlaying, startTime) {
    this.title = title;
    this.uploader = uploader;
    this.seconds = seconds;
    this.isPlaying = false;
    this.startTime = 0;
  }

  play() {
    if (!this.isPlaying && this.startTime == 0) {
      this.isPlaying = true;
      console.log('The song: ' + this.title + ' Started');
      //setting a global variable
      window.startSong = setInterval(() => {
        this.startTime++;
        if (this.startTime == this.seconds) {
          this.isPlaying = false;
          clearInterval(window.startSong);
          console.log("song ended");
        }
      }, 1000);
    } else {
      console.log(this.startTime);
      return;
    }
  }

  pause() {
    // console.log(this.isPlaying);
    console.log("executed pause");
    this.isPlaying = false;
    clearInterval(window.startSong);// clearing the interval on click function
  }
}

var fstSong = new Music("song title","song uploader", 15);
fstSong.play();

//Calling pause function on click.
fstSong.pause();


问:
How do I deploy monorepo code to AWS Lambda using lerna?
I am attempting to make two AWS Lambda functions (written in typescript). Both of these functions share the same code for interacting with an API. In order to not have to copy the same code to two different Lambdas, I would like to move my shared code to a local module, and have both my Lambdas depend on said module.

My initial attempt at staring code between the two lambdas was to use a monorepo and lerna.  My current project structure looks like this:

```<code>- lerna.json
- package.json
- packages
  - api
    - package.json
  - lambdas
    - funcA
      - package.json
    - func B
      - package.json
</code>```

lerna.json:

```<code>{
  "packages": [
    "packages/api",
    "packages/lambdas/*"
  ],
  "version": "1.0.0"
}
</code>```

In each of my package.json for my Lambda functions, I am able to include my local api module as such:

```<code>"dependencies": {
    "@local/api": "*"
}
</code>```

With this, I've been able to move the common code to its own module. However, I'm now not sure how to bundle my functions to deploy to AWS Lambda. Is there a way for lerna to be able to create a bundle that can be deployed?

答:
As cp -rL doesn't work on the mac I had to come up with something similar.

Here is a workflow that works if all of your packages belong to one scope (@org):

In the package.json of your lerna repo:

```<code>"scripts": {
    "deploy": "lerna exec \"rm -rf node_modules\" && lerna bootstrap -- --production && lerna run deploy && lerna bootstrap"
}
</code>```

In the package that contains your lambda function:

```<code>"scripts":{
    "deploy": "npm pack && tar zxvf packagename-version.tgz && rm -rf node_modules/@org && cp -r node_modules/* package/node_modules && cd package && npm dedupe"
}
</code>```

Now replace "packagename-version" and "@org" with the respective values of your project. Also add all of the dependent packages to "bundledDependencies".

After running npm run deploy in the root of your lerna mono repo you end up with a folder "package" in the package that contains your lambda function. It has all the dependencies needed to run your function. Take it from there.

I had hoped that using npm pack would allow me to utilize .npmignore files but it seems that that doesn't work. If anyone has an idea how to make it work let me know.

Body:
I am attempting to make two AWS Lambda functions (written in typescript). Both of these functions share the same code for interacting with an API. In order to not have to copy the same code to two different Lambdas, I would like to move my shared code to a local module, and have both my Lambdas depend on said module.

My initial attempt at staring code between the two lambdas was to use a monorepo and lerna.  My current project structure looks like this:

- lerna.json
- package.json
- packages
  - api
    - package.json
  - lambdas
    - funcA
      - package.json
    - func B
      - package.json

lerna.json:

{
  "packages": [
    "packages/api",
    "packages/lambdas/*"
  ],
  "version": "1.0.0"
}

In each of my package.json for my Lambda functions, I am able to include my local api module as such:

"dependencies": {
    "@local/api": "*"
}

With this, I've been able to move the common code to its own module. However, I'm now not sure how to bundle my functions to deploy to AWS Lambda. Is there a way for lerna to be able to create a bundle that can be deployed?

Body:
As cp -rL doesn't work on the mac I had to come up with something similar.

Here is a workflow that works if all of your packages belong to one scope (@org):

In the package.json of your lerna repo:

"scripts": {
    "deploy": "lerna exec \"rm -rf node_modules\" && lerna bootstrap -- --production && lerna run deploy && lerna bootstrap"
}

In the package that contains your lambda function:

"scripts":{
    "deploy": "npm pack && tar zxvf packagename-version.tgz && rm -rf node_modules/@org && cp -r node_modules/* package/node_modules && cd package && npm dedupe"
}

Now replace "packagename-version" and "@org" with the respective values of your project. Also add all of the dependent packages to "bundledDependencies".

After running npm run deploy in the root of your lerna mono repo you end up with a folder "package" in the package that contains your lambda function. It has all the dependencies needed to run your function. Take it from there.

I had hoped that using npm pack would allow me to utilize .npmignore files but it seems that that doesn't work. If anyone has an idea how to make it work let me know.


问:
How to perform a GET request to cross origin using vertx?
I am using vert.x with JAVA on the server side.
when client goes to http://localhost:8080/hello,  I want the browser to go to "google.com".
I get an error when executing the GET request

```<code>    router.route("/hello").handler(routingContext -> {
        String url = "google.com";
        WebClient client = WebClient.create(vertx, new WebClientOptions().setSsl(true).setTrustAll(true).setDefaultPort(8080).setKeepAlive(true).setDefaultHost(url));
        client.get(url).as(BodyCodec.string()).send(ar -> {
            if(ar.succeeded()) {
                HttpResponse<String> response = ar.result();
                System.out.println("Got HTTP response body");
                System.out.println(response.body().toString());
            }
            else {
                ar.cause().printStackTrace();
            }
        });

    });
</code>```

Error:

```<code>io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection timed out: no further information: google.com/172.217.16.142:8080
</code>```

答:
Let's sort out some things.

First, cross origin is relevant to browsers. You're issuing a server-to-server request, so it's not relevant here.

Second, I hope you don't actually need to issue request to google.com, as Google actually tries to stop others to use its search page that way.

Third, you're using your url argument twice. Once when you set your default host, and second time when issuing a get() request. Then you also set port to 8080, which google.com doesn't expose last time I checked.

Which produces something like:

https://google.com:8080/google.com

To receive response that makes a little bit more sense, you can try this code (I removed the routing part):

```<code>Vertx vertx = Vertx.vertx();

    String url = "api.openweathermap.org";
    WebClient client = WebClient.create(vertx, new WebClientOptions().setDefaultPort(80).setDefaultHost(url));
    client.get("/data/2.5/weather?q=london,uk&units=metric&appid=e38f373567e83d2ba1b6928384435689").as(BodyCodec.string()).send(ar -> {
        if(ar.succeeded()) {
            HttpResponse<String> response = ar.result();
            System.out.println("Got HTTP response body");
            System.out.println(response.body());
        }
        else {
            ar.cause().printStackTrace();
        }
    });
</code>```

Body:
I am using vert.x with JAVA on the server side.
when client goes to http://localhost:8080/hello,  I want the browser to go to "google.com".
I get an error when executing the GET request

    router.route("/hello").handler(routingContext -> {
        String url = "google.com";
        WebClient client = WebClient.create(vertx, new WebClientOptions().setSsl(true).setTrustAll(true).setDefaultPort(8080).setKeepAlive(true).setDefaultHost(url));
        client.get(url).as(BodyCodec.string()).send(ar -> {
            if(ar.succeeded()) {
                HttpResponse<String> response = ar.result();
                System.out.println("Got HTTP response body");
                System.out.println(response.body().toString());
            }
            else {
                ar.cause().printStackTrace();
            }
        });

    });

Error:

io.netty.channel.AbstractChannel$AnnotatedConnectException: Connection timed out: no further information: google.com/172.217.16.142:8080

Body:
Let's sort out some things.

First, cross origin is relevant to browsers. You're issuing a server-to-server request, so it's not relevant here.

Second, I hope you don't actually need to issue request to google.com, as Google actually tries to stop others to use its search page that way.

Third, you're using your url argument twice. Once when you set your default host, and second time when issuing a get() request. Then you also set port to 8080, which google.com doesn't expose last time I checked.

Which produces something like:

https://google.com:8080/google.com

To receive response that makes a little bit more sense, you can try this code (I removed the routing part):

Vertx vertx = Vertx.vertx();

    String url = "api.openweathermap.org";
    WebClient client = WebClient.create(vertx, new WebClientOptions().setDefaultPort(80).setDefaultHost(url));
    client.get("/data/2.5/weather?q=london,uk&units=metric&appid=e38f373567e83d2ba1b6928384435689").as(BodyCodec.string()).send(ar -> {
        if(ar.succeeded()) {
            HttpResponse<String> response = ar.result();
            System.out.println("Got HTTP response body");
            System.out.println(response.body());
        }
        else {
            ar.cause().printStackTrace();
        }
    });


问:
Unable to make public long com.sun.management.internal.OperatingSystemImpl.getOpenFileDescriptorCount()
I am getting the below error in server log in Java 11. Is there any solution for it?</p>

```<code>[2019-05-02 18:06:18 IST] [] ERROR com.codahale.metrics.ScheduledReporter [SID= UID= BGCD=] - Exception thrown from Slf4jReporter#report. Exception was suppressed.
java.lang.reflect.InaccessibleObjectException: Unable to make public long com.sun.management.internal.OperatingSystemImpl.getOpenFileDescriptorCount() accessible: module jdk.management does not "opens com.sun.management.internal" to unnamed module @489448ac
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:198)
    at java.base/java.lang.reflect.Method.setAccessible(Method.java:192)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.invoke(FileDescriptorRatioGauge.java:48)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.getRatio(FileDescriptorRatioGauge.java:35)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:64)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:11)
    at deployment.myPage.war//com.codahale.metrics.DerivativeGauge.getValue(DerivativeGauge.java:23)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.logGauge(Slf4jReporter.java:306)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.report(Slf4jReporter.java:220)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter.report(ScheduledReporter.java:243)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter$1.run(ScheduledReporter.java:182)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
</code>```

答:
This issue was fixed in Dropwizard metrics 4.0.0, see
https://github.com/dropwizard/metrics/pull/1236

So you need to raise the version of your dependency.
In case you are using Spring Boot, you can raise the parent version to 2.1.

If raising the version is not an option, follow @senjin.hajrulahovic's answer to open com.sun.management.internal module.

Body:
I am getting the below error in server log in Java 11. Is there any solution for it?

[2019-05-02 18:06:18 IST] [] ERROR com.codahale.metrics.ScheduledReporter [SID= UID= BGCD=] - Exception thrown from Slf4jReporter#report. Exception was suppressed.
java.lang.reflect.InaccessibleObjectException: Unable to make public long com.sun.management.internal.OperatingSystemImpl.getOpenFileDescriptorCount() accessible: module jdk.management does not "opens com.sun.management.internal" to unnamed module @489448ac
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:340)
    at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:280)
    at java.base/java.lang.reflect.Method.checkCanSetAccessible(Method.java:198)
    at java.base/java.lang.reflect.Method.setAccessible(Method.java:192)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.invoke(FileDescriptorRatioGauge.java:48)
    at deployment.myPage.war//com.codahale.metrics.jvm.FileDescriptorRatioGauge.getRatio(FileDescriptorRatioGauge.java:35)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:64)
    at deployment.myPage.war//com.codahale.metrics.RatioGauge.getValue(RatioGauge.java:11)
    at deployment.myPage.war//com.codahale.metrics.DerivativeGauge.getValue(DerivativeGauge.java:23)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.logGauge(Slf4jReporter.java:306)
    at deployment.myPage.war//com.codahale.metrics.Slf4jReporter.report(Slf4jReporter.java:220)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter.report(ScheduledReporter.java:243)
    at deployment.myPage.war//com.codahale.metrics.ScheduledReporter$1.run(ScheduledReporter.java:182)
    at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
    at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305)
    at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)


问:
Reusing maven module as dependencies
I was hoping to be able to split my projects into Maven sub Modules, and reuse them as Maven dependency for other projects.

As I understand from the doc, the child modules must specify their parent project. This makes them unsuitable for reusing as dependencies.

This render the split in module far less attractive IMHO. Or am I missing something?

I tend to split projects in components when I need to share them. Otherwise, why bother?

Can someone elaborate on that?

Is it possible to declare a module that do not specify it's parent?
How can you refactor a dependency and all it's dependant projects if you cannot?

cheers

答:
Parent poms, and pom project are useful, not doubt. But the doc says you have to specify the parent in a module. So if you want to reuse, say a server module of a project for another project, how can you do it?

```<code>|
--- server
     |
     --- pom.xml
|
--- client
     |
     --- pom.xml
|
--- webapp
     |
     --- pom.xml
|
--- Pom project 1
     |
     <modules>
        <module>../server
        <module>../client
|
--- Pom project 2
     |
     <modules>
        <module>../server
        <module>../webapp
</code>```

With the above example, according to the doc, server project is supposed to specify pom project 1 as parent, and pom project 2 as well.

How do you handle a mix of modules and dependencies notion in such a case?

Title: Reusing maven module as dependencies

Body:
Parent poms, and pom project are useful, not doubt. But the doc says you have to specify the parent in a module. So if you want to reuse, say a server module of a project for another project, how can you do it?

|
--- server
     |
     --- pom.xml
|
--- client
     |
     --- pom.xml
|
--- webapp
     |
     --- pom.xml
|
--- Pom project 1
     |
     <modules>
        <module>../server
        <module>../client
|
--- Pom project 2
     |
     <modules>
        <module>../server
        <module>../webapp

With the above example, according to the doc, server project is supposed to specify pom project 1 as parent, and pom project 2 as well.

How do you handle a mix of modules and dependencies notion in such a case?


问:
TextArea with 10 lines and 35 characters per line
I have an HTML page with many elements. The page is scrollable, that means the page has a scrollbar in it. Down to the page I have a HTML textarea with a specified rows and columns attribute.
Now I want a simple JavaScript solution which will help me to validate the the following points each time user enters any character:

The number of lines in the textarea is not greater than 10

Each line has less than or equal to 35 characters

If user crosses 35 character limit for any particular line then the 36th character will be automatically start from next line only if the total line numbers does not exceed 10, else it will show an error popup message and stops there.

User should be able to modify any lines(it may be last line or any middle lines) and still should follow all the above 3 points.

答:
I have done a similar case :

MaxLenght of textarea = 1875 ;
  MaxLenght of row      = 75 ;
  Disable Enter, because over 75's multiple, SW automatically wrap text ;

This is it, with onkeydown trigger:

```<code>function wrapTextArea(event,id,maxLineLenght){

    // delete and canc
    if((recuperaKeyCode(event)!=8) && (recuperaKeyCode(event)!=46))  {

        var field =  document.getElementById(id).value;
        var nextIndex = 0;
        for(var i=0; field.length>nextIndex; i++){
            nextIndex=maxLineLenght*(i+1)+i;
            if(field.length==nextIndex){
                if(field.charAt(nextIndex)!= "\n"){
                    field=field.substring(0, nextIndex)+"\n"+field.substring(nextIndex, field.lenght);
                }
            }
        }
        document.getElementById(id).value = field;
    }
}
</code>```

This is how I disabled enter key, where key = 13 :

```<code>function disableKey(event,key){

    if(recuperaKeyCode(event)==key){
        event.preventDefault();
    }
}
</code>```

Body:
I have done a similar case :

MaxLenght of textarea = 1875 ;
  MaxLenght of row      = 75 ;
  Disable Enter, because over 75's multiple, SW automatically wrap text ;

This is it, with onkeydown trigger:

function wrapTextArea(event,id,maxLineLenght){

    // delete and canc
    if((recuperaKeyCode(event)!=8) && (recuperaKeyCode(event)!=46))  {

        var field =  document.getElementById(id).value;
        var nextIndex = 0;
        for(var i=0; field.length>nextIndex; i++){
            nextIndex=maxLineLenght*(i+1)+i;
            if(field.length==nextIndex){
                if(field.charAt(nextIndex)!= "\n"){
                    field=field.substring(0, nextIndex)+"\n"+field.substring(nextIndex, field.lenght);
                }
            }
        }
        document.getElementById(id).value = field;
    }
}

This is how I disabled enter key, where key = 13 :

function disableKey(event,key){

    if(recuperaKeyCode(event)==key){
        event.preventDefault();
    }
}


问:
Angular2 HostListener check URL change
I have a navbar component that is called in every pages of my website.

I want it to check when the URL change with a HostListener.

```<code>@HostListener('window:hashchange', ['$event'])
onHashChange(event) {
    this.checkCurrentURL();
}

private checkCurrentURL(){
    console.log("loaction : "+window.location.pathname)
}
</code>```

However it doesn't work.
Any ideas ?

EDIT: SOLUTION

The solution I found is without HostListener, but it works.

```<code>constructor(private router : Router){
 router.events.subscribe((val) => {
  this.checkCurrentURL();
 });
}
</code>```

答:
As Angular is Single page Application ,
so you can define a global variable window in one of the component  and using window global variable  we can track each and every route ,   ,

window.location.href

window.location.href will return the current Url , and thus we can check when the URL change

```<code>constructor(private router : Router){
 router.events.subscribe((val) => {
    console.log(window.location.href);
 });
}
</code>```

Title: Angular2 HostListener check URL change

Body:
I have a navbar component that is called in every pages of my website.

I want it to check when the URL change with a HostListener.

@HostListener('window:hashchange', ['$event'])
onHashChange(event) {
    this.checkCurrentURL();
}

private checkCurrentURL(){
    console.log("loaction : "+window.location.pathname)
}

However it doesn't work.
Any ideas ?

EDIT: SOLUTION

The solution I found is without HostListener, but it works.

constructor(private router : Router){
 router.events.subscribe((val) => {
  this.checkCurrentURL();
 });
}

Body:
As Angular is Single page Application ,
so you can define a global variable window in one of the component  and using window global variable  we can track each and every route ,   ,

window.location.href

window.location.href will return the current Url , and thus we can check when the URL change

constructor(private router : Router){
 router.events.subscribe((val) => {
    console.log(window.location.href);
 });
}


问:
Setting up Django with docker
I am tried setting up django using docker but I am getting this error.

I have set up my Dockerfile and the docker-compose.yml.

docker-compose.yml

```<code>version: "3"

services:

  db:

    image: postgres

  web:

    build: .

    command: python manage.py runserver 0.0.0.0:8000

    volumes:

      - .:/code

    ports:

      - "8000:8000"

    depends_on:

      - db
</code>```

Dockerfile

```<code>FROM python:3

ENV PYTHONUNBUFFERED 1

RUN mkdir /code

WORKDIR /code

COPY requirements.txt /code/

RUN pip install --no-cache-dir -r requirements.txt

COPY . /code/
</code>```

This is the error I am getting.

```<code>Watching for file changes with StatReloader
web_1  | Exception in thread django-main-thread:
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.7/threading.py", line 917, in _bootstrap_inner
</code>```

答:
I think This particular error was fixed in django 2.1

You'll want to upgrade your requirements to be django>=2.1 to ensure you get this new version.

The comments on the commit indicate that this patch will not be backported to django 1.11.x which does not support python3

after change django version re-ran docker-compose build.

Per the FAQ, Django 1.11.x is not compatible with Python 3

Django 1.11.x reached end of mainstream support on December 2, 2017
  and it receives only data loss and security fixes until its end of
  life.

Title: Setting up Django with docker

Body:
I am tried setting up django using docker but I am getting this error.

I have set up my Dockerfile and the docker-compose.yml.

docker-compose.yml

version: "3"

services:

  db:

    image: postgres

  web:

    build: .

    command: python manage.py runserver 0.0.0.0:8000

    volumes:

      - .:/code

    ports:

      - "8000:8000"

    depends_on:

      - db

Dockerfile

FROM python:3

ENV PYTHONUNBUFFERED 1

RUN mkdir /code

WORKDIR /code

COPY requirements.txt /code/

RUN pip install --no-cache-dir -r requirements.txt

COPY . /code/

This is the error I am getting.

Watching for file changes with StatReloader
web_1  | Exception in thread django-main-thread:
web_1  | Traceback (most recent call last):
web_1  |   File "/usr/local/lib/python3.7/threading.py", line 917, in _bootstrap_inner


问:
concatenate columns based on blank columns
I am having three columns,- and / should be used as separator  result should come in new column(File Index-sub Index/Year),if sub index is blank then result should be (File Index/Year).</p>

```<code>  SELECT
[ File Index].[File Index]
, [ File Index].[Sub Index]
, [ File Index].[Financial Year]
, [ File Index].[File Index] & [Sub Index] & [Financial Year] AS [Composite Index]
  FROM [File Index];
</code>```

答:
You can use IIF function: IIF(Condition;ConcatenationIfTrue;ConcatenationIfFalse)

```<code>  SELECT
[ File Index].[File Index]
, [ File Index].[Sub Index]
, [ File Index].[Financial Year]
, IIF(ISNULL([Sub Index];[ File Index].[File Index] & "/" & [Financial Year];[ File Index].[File Index] & [Sub Index] & [Financial Year]) AS [Composite Index]
  FROM [File Index];
</code>```

Body:
I am having three columns,- and / should be used as separator  result should come in new column(File Index-sub Index/Year),if sub index is blank then result should be (File Index/Year).

  SELECT
[ File Index].[File Index]
, [ File Index].[Sub Index]
, [ File Index].[Financial Year]
, [ File Index].[File Index] & [Sub Index] & [Financial Year] AS [Composite Index]
  FROM [File Index];

Body:
You can use IIF function: IIF(Condition;ConcatenationIfTrue;ConcatenationIfFalse)

  SELECT
[ File Index].[File Index]
, [ File Index].[Sub Index]
, [ File Index].[Financial Year]
, IIF(ISNULL([Sub Index];[ File Index].[File Index] & "/" & [Financial Year];[ File Index].[File Index] & [Sub Index] & [Financial Year]) AS [Composite Index]
  FROM [File Index];


问:
error: field 'ctx' has incomplete type EVP_CIPHER_CTX
Problem: I need to install Cepstral (tts engine) into Freeswitch running Debian 8. Freeswitch is already up and running, but I needed to build it from source in order for it create the mod_cepstral module.

When I run make this is the error I get:

```<code>In file included from ./crypto/include/prng.h:17:0,
                 from ./crypto/include/crypto_kernel.h:50,
                 from ./include/srtp.h:53,
                 from srtp/srtp.c:46:
./crypto/include/aes_icm_ossl.h:66:20: error: field ‘ctx’ has incomplete type
     EVP_CIPHER_CTX ctx;
                    ^~~
In file included from srtp/srtp.c:50:0:
./crypto/include/aes_gcm_ossl.h:58:18: error: field ‘ctx’ has incomplete type
   EVP_CIPHER_CTX ctx;
                  ^~~
Makefile:646: recipe for target 'srtp.lo' failed
make[1]: *** [srtp.lo] Error 1
make[1]: Leaving directory '/usr/src/freeswitch/libs/srtp'
Makefile:3931: recipe for target 'libs/srtp/libsrtp.la' failed
make: *** [libs/srtp/libsrtp.la] Error 2
</code>```

I have been scouring the internet for solutions, but I am not a developer and this is way over my head. Any help would be appreciated.

答:
cause newer OpenSSL don't expose struct EVP_CIPHER_CTX ,

try this

```<code>EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
//do sth here
//...
EVP_CIPHER_CTX_free(ctx);
</code>```

Body:
Problem: I need to install Cepstral (tts engine) into Freeswitch running Debian 8. Freeswitch is already up and running, but I needed to build it from source in order for it create the mod_cepstral module.

When I run make this is the error I get:

In file included from ./crypto/include/prng.h:17:0,
                 from ./crypto/include/crypto_kernel.h:50,
                 from ./include/srtp.h:53,
                 from srtp/srtp.c:46:
./crypto/include/aes_icm_ossl.h:66:20: error: field ‘ctx’ has incomplete type
     EVP_CIPHER_CTX ctx;
                    ^~~
In file included from srtp/srtp.c:50:0:
./crypto/include/aes_gcm_ossl.h:58:18: error: field ‘ctx’ has incomplete type
   EVP_CIPHER_CTX ctx;
                  ^~~
Makefile:646: recipe for target 'srtp.lo' failed
make[1]: *** [srtp.lo] Error 1
make[1]: Leaving directory '/usr/src/freeswitch/libs/srtp'
Makefile:3931: recipe for target 'libs/srtp/libsrtp.la' failed
make: *** [libs/srtp/libsrtp.la] Error 2

I have been scouring the internet for solutions, but I am not a developer and this is way over my head. Any help would be appreciated.

Body:
cause newer OpenSSL don't expose struct EVP_CIPHER_CTX ,

try this

EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
EVP_CIPHER_CTX_init(ctx);
//do sth here
//...
EVP_CIPHER_CTX_free(ctx);


问:
Install4J VM detection fails on Mac
We're getting ready to deploy our app (Cytoscape) using Install4J7's feature that detects the installed JVM and offers to download a new one. We find that if we download a JVM, let the installer finish, then run the installer again, it offers to download a new JVM again. I would have thought it would have detected the one it just downloaded.

Have we misconfigured something?? Or is there a later version of Install4J?

Our JVM range is 1.8.0_152 .. 1.9.

The JVM we're downloading is here: http://chianti.ucsd.edu/jres/macosx-amd64-1.8.0_162.tar.gz

What could be going wrong??

Thanks!

答: Check that you have not selected 32-bit for your application and then downloaded a 64-bit JDK. Or vice versa.</p>

Title: Install4J VM detection fails on Mac


问:
Save localstorage data to server using PHP
I'm trying to implement a "save later" functionality in jquery using localstorage. the idea is saving every form event in localstorage and using a button to sync them and save to the server.

I manage to save form data to localstorage and retrieve all the localstorage saved. Currently i'm struggling on how i can be able to submit specific values only to the server using PHP

Here's my code for saving form data to localstorage

```<code>$('#systemInventory').on("submit", function(e) {
        e.preventDefault(); // prevent the form from attempting to send to the web server
        let $inputs = $('#systemInventory :input');

        let values = {};
        $inputs.each(function() {
            values[$(this).attr("name")] = $(this).val();
        });

        let title = 'systemInventory' + $.now();
        localStorage.setItem(title, JSON.stringify(values));
        $('#systemInventory')[0].reset();
        mdtoast('Successfully Saved',
            { type: mdtoast.INFO });
    });
</code>```

and here's the one i used for retrieving data from the localstorage

```<code>function allStorage() {

    let values = [],
        keys = Object.keys(localStorage),
        i = keys.length;

    while ( i-- ) {
        values.push( localStorage.getItem(keys[i]) );
    }

    return values;
}
</code>```

Here's the one i'm trying to do to save specific data in the PHP storage

```<code>$.each(allStorage(), function (key, value) {
        let data = JSON.parse(value);
        console.log(data);
        $.ajax({
            url: "sync.php",
            method: 'POST',
            data: {data: data},
            success: function (response) {
                console.log(response);
            },
            error: function (response) {
                console.log(response);
            }
        });
    });
</code>```

and my php code is

```<code>if (isset($_POST['data'])){

    foreach ($_POST['data'] as $key => $value){

        $data[] = array(
            $key => $value
        );

    }

    $dataForm = call_user_func_array('array_merge', $data);

    print_r($dataForm);

//    print_r($data);

}
</code>```

When console logging all the localstorage saved i have this result

and when clicking the sync, the one that is sending on the server i'm having this issue

what i really want to happen is when i submit the localstorage data to php it will automatically form specific array for example

```<code>$data = array(
'type'=>'product',
'beginning'=>1,
'delivery'=>1

);
</code>```

答:
The problem is your allStorage() function is returning an indexed array, not an object, so you're getting only the values from local storage, not the keys too.

This means when you come to pass the data to PHP, it's ending up as an indexed, not associative, array, i.e. without keys. This would be apparent if you ran print_r() on the received data, for example.

allStorage() can be fixed (and simplified) as:

```<code>function allStorage() {
    let data = {}; //<-- note object, not array
    for (var key in localStorage) data[key] = localStrage[key];
    return data;
}
</code>```

Body:
I'm trying to implement a "save later" functionality in jquery using localstorage. the idea is saving every form event in localstorage and using a button to sync them and save to the server.

I manage to save form data to localstorage and retrieve all the localstorage saved. Currently i'm struggling on how i can be able to submit specific values only to the server using PHP

Here's my code for saving form data to localstorage

$('#systemInventory').on("submit", function(e) {
        e.preventDefault(); // prevent the form from attempting to send to the web server
        let $inputs = $('#systemInventory :input');

        let values = {};
        $inputs.each(function() {
            values[$(this).attr("name")] = $(this).val();
        });

        let title = 'systemInventory' + $.now();
        localStorage.setItem(title, JSON.stringify(values));
        $('#systemInventory')[0].reset();
        mdtoast('Successfully Saved',
            { type: mdtoast.INFO });
    });

and here's the one i used for retrieving data from the localstorage

function allStorage() {

    let values = [],
        keys = Object.keys(localStorage),
        i = keys.length;

    while ( i-- ) {
        values.push( localStorage.getItem(keys[i]) );
    }

    return values;
}

Here's the one i'm trying to do to save specific data in the PHP storage

$.each(allStorage(), function (key, value) {
        let data = JSON.parse(value);
        console.log(data);
        $.ajax({
            url: "sync.php",
            method: 'POST',
            data: {data: data},
            success: function (response) {
                console.log(response);
            },
            error: function (response) {
                console.log(response);
            }
        });
    });

and my php code is

if (isset($_POST['data'])){

    foreach ($_POST['data'] as $key => $value){

        $data[] = array(
            $key => $value
        );

    }

    $dataForm = call_user_func_array('array_merge', $data);

    print_r($dataForm);

//    print_r($data);

}

When console logging all the localstorage saved i have this result

and when clicking the sync, the one that is sending on the server i'm having this issue

what i really want to happen is when i submit the localstorage data to php it will automatically form specific array for example

$data = array(
'type'=>'product',
'beginning'=>1,
'delivery'=>1

);

Body:
The problem is your allStorage() function is returning an indexed array, not an object, so you're getting only the values from local storage, not the keys too.

This means when you come to pass the data to PHP, it's ending up as an indexed, not associative, array, i.e. without keys. This would be apparent if you ran print_r() on the received data, for example.

allStorage() can be fixed (and simplified) as:

function allStorage() {
    let data = {}; //<-- note object, not array
    for (var key in localStorage) data[key] = localStrage[key];
    return data;
}


问:
How to work with the url of a fileReader object?

Hello! I'am trying to make it work a function called loadDocument, who need a url of the loaded files from the user local computer to work. I'm writing an API to load document from local user computer, and show it on a web reader.

This is my upload button :
  <input type="file" id="input" onchange="module.onLoadSelection();" alt="Browse" name="upload"/>

This is my function without fileReader :

var onLoadSelection = function () {
    var select = document.getElementById('input');
    if (select && select.value) {
        var id= '';
        var url = select.files.item(0).name;
        module.loadDocument(url,id);
    }
};
```

<p>This is my function with fileReader :</p>

<pre class="lang-js prettyprint-override"><code>var loadTest = function (input) {
    var file = document.querySelector('input[type=file]').files[0];
    console.log("file loaded! ->", file); // i can read the obj of my file
    var reader = new FileReader();

    var id = ''; // don't need rightnow
    var url = reader.readAsDataURL(file);
    console.log("url :", url); // show me undefined....
    module.loadDocument(url,id);
}
</code>```

What i am trying is to get the url of the loaded file from user computer to get my function loadDocument working. She need a url parameter to work.

loadDocument is an API function, i assume i can't get the filepath of my user due to security reason.

What do i need to change/update on my loadDocument(); function to work?

Edit : In fact, nothing to change. The correct way to read my file was :
<input type="file" id="input" onchange="module.onLoadSelection(this.files);" alt="Browse" name="upload"/>

var onLoadSelection = function (files) {
    if (files && files.length == 1) {
       var id = '';
       var url = URL.createObjectURL(files[0]);
       module.loadDocument(url,id);
    }
};
```

答:
Don't use a FileReader at all.

When you want to display a File (or a Blob) that is in the browser's memory or on user's disk, then all you need is to generate an URL that do point to this memory slot.

That's exactly what URL.createObjectURL(blob) does: it returns a Blob URI (blob://) that points to the data either in memory or on the disk, acting exactly as a simple pointer.

This method has various advantages over the FileReader.readAsDataURL() method. To name a few:

Store the data in memory only once, when FileReader would need it at reading, then generate a copy as an base64 encoded, and an other one at displaying...

Synchronous. Since all it does is to generate a pointer, no need to make it async.

Cleaner code.

const module = {
  loadDocument: (url) => {
    document.body.append(
      Object.assign(
        document.createElement('iframe'),
        { src: url }
      )
    )
  }
};

document.querySelector('input[type=file]').addEventListener('input', function (evt) {
    var file = this.files[0];
    var url = URL.createObjectURL(file);
    module.loadDocument(url);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="file"></code>```

Body:
Hello! I'am trying to make it work a function called loadDocument, who need a url of the loaded files from the user local computer to work. I'm writing an API to load document from local user computer, and show it on a web reader.

This is my upload button :
  <input type="file" id="input" onchange="module.onLoadSelection();" alt="Browse" name="upload"/>

This is my function without fileReader :

var onLoadSelection = function () {
    var select = document.getElementById('input');
    if (select && select.value) {
        var id= '';
        var url = select.files.item(0).name;
        module.loadDocument(url,id);
    }
};

This is my function with fileReader :

var loadTest = function (input) {
    var file = document.querySelector('input[type=file]').files[0];
    console.log("file loaded! ->", file); // i can read the obj of my file
    var reader = new FileReader();

    var id = ''; // don't need rightnow
    var url = reader.readAsDataURL(file);
    console.log("url :", url); // show me undefined....
    module.loadDocument(url,id);
}

What i am trying is to get the url of the loaded file from user computer to get my function loadDocument working. She need a url parameter to work.

loadDocument is an API function, i assume i can't get the filepath of my user due to security reason.

What do i need to change/update on my loadDocument(); function to work?

Edit : In fact, nothing to change. The correct way to read my file was :
<input type="file" id="input" onchange="module.onLoadSelection(this.files);" alt="Browse" name="upload"/>

var onLoadSelection = function (files) {
    if (files && files.length == 1) {
       var id = '';
       var url = URL.createObjectURL(files[0]);
       module.loadDocument(url,id);
    }
};

Body:
Don't use a FileReader at all.

When you want to display a File (or a Blob) that is in the browser's memory or on user's disk, then all you need is to generate an URL that do point to this memory slot.

That's exactly what URL.createObjectURL(blob) does: it returns a Blob URI (blob://) that points to the data either in memory or on the disk, acting exactly as a simple pointer.

This method has various advantages over the FileReader.readAsDataURL() method. To name a few:

Store the data in memory only once, when FileReader would need it at reading, then generate a copy as an base64 encoded, and an other one at displaying...

Synchronous. Since all it does is to generate a pointer, no need to make it async.

Cleaner code.

const module = {
  loadDocument: (url) => {
    document.body.append(
      Object.assign(
        document.createElement('iframe'),
        { src: url }
      )
    )
  }
};

document.querySelector('input[type=file]').addEventListener('input', function (evt) {
    var file = this.files[0];
    var url = URL.createObjectURL(file);
    module.loadDocument(url);
});

<input type="file">


问:
How to create a custom WebView Control Xamarin forms
I am trying to create a custom control for webview, i am trying to get a checkbox inside a webview Reason :- we have a bunch of text to be displayed and unless the user reaches the end of the scroll he cannot move to the next page and at the end of the scroll there is a checkbox where user has to check the the checkbox and then he can process. here i have tried putting the checkbox and webview inside the stacklayout but the issue is webview have its own scroll bar and and stacklayout scroll bar does not work when a user try to scroll as the webview scroller scrolls out also when i try to close the Webview Page with back button the webview gets close and not the page

i am not sure what approach should i apply here.

i am getting my html data from my webapi.

anyone with some solution would be appreciable

here is my custom renderer which i have wrote but the piece missing here is how can i add another xamarin control inside this

```<code>public class CustomPdfViewRenderer : WebViewRenderer
{

    public CustomPdfViewRenderer(Context context) : base(context)
    {

    }

    protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.Settings.BuiltInZoomControls = true;
            Control.Settings.DisplayZoomControls = false;

            Control.Settings.LoadWithOverviewMode = true;
            Control.Settings.UseWideViewPort = true;
        }
    }
}
</code>```

答:
You can try the following approach:

Add checkbox to HTML

When the user check checkbox call some JavaScript function

When JavaScript function is called, call C# function (Xamarin) which will enable the user to process to the next page (or some other Xamarin side stuff)

Here is how you can call C# function from JavaScript :HybridWebView

Body:
I am trying to create a custom control for webview, i am trying to get a checkbox inside a webview Reason :- we have a bunch of text to be displayed and unless the user reaches the end of the scroll he cannot move to the next page and at the end of the scroll there is a checkbox where user has to check the the checkbox and then he can process. here i have tried putting the checkbox and webview inside the stacklayout but the issue is webview have its own scroll bar and and stacklayout scroll bar does not work when a user try to scroll as the webview scroller scrolls out also when i try to close the Webview Page with back button the webview gets close and not the page

i am not sure what approach should i apply here.

i am getting my html data from my webapi.

anyone with some solution would be appreciable

here is my custom renderer which i have wrote but the piece missing here is how can i add another xamarin control inside this

public class CustomPdfViewRenderer : WebViewRenderer
{

    public CustomPdfViewRenderer(Context context) : base(context)
    {

    }

    protected override void OnElementChanged(ElementChangedEventArgs<WebView> e)
    {
        base.OnElementChanged(e);
        if (Control != null)
        {
            Control.Settings.BuiltInZoomControls = true;
            Control.Settings.DisplayZoomControls = false;

            Control.Settings.LoadWithOverviewMode = true;
            Control.Settings.UseWideViewPort = true;
        }
    }
}


问:
Bullet color in Xaringan presentation
Is it possible to change the bullet colors in Xaringan presentation? The text should have a different color.

I have not find any option in xaringanthemer package neither going through the css file. I could not find any information  remark.js documentation.

答:
xaringan output is html so you can change any parts by css (e.g. using this guide to change bullet color to a red dot. Taking this as a template, you can add this chunk soon after the YAML of the Rmd to change it to a red bullet:

```<code>```{css, echo=F}
ul {
  list-style: none; /* Remove default bullets */
}

ul li::before {
  content: "\2022";  /* Add content: \2022 is the CSS Code/unicode for a bullet */
  color: red; /* Change the color */
  font-weight: bold; /* If you want it to be bold */
  display: inline-block; /* Needed to add space between the bullet and the text */
  width: 1em; /* Also needed for space (tweak if needed) */
  margin-left: -1em; /* Also needed for space (tweak if needed) */
}
```
</code>```

Separate style from content

Or more preferably (since it separates out the style component from slide content), create a css file, say style.css which contains:

```<code>ul {
  list-style: none; /* Remove default bullets */
}

ul li::before {
  content: "\2022";  /* Add content: \2022 is the CSS Code/unicode for a bullet */
  color: red; /* Change the color */
  font-weight: bold; /* If you want it to be bold */
  display: inline-block; /* Needed to add space between the bullet and the text */
  width: 1em; /* Also needed for space (tweak if needed) */
  margin-left: -1em; /* Also needed for space (tweak if needed) */
}
</code>```

then add in the YAML, making sure that style.css is in the same path as your Rmd,

```<code>css: [xaringan-themer.css, style.css]
</code>```

Tweaking the bullet shape

You can change the shape the bullet using a different unicode supplied in content (e.g. use \2023 for a triangle bullet - see other common types here).

Changing the bullet color

You just need to replace red with the color of your choice. You can replace it with the hex color code instead too.

Title: Bullet color in Xaringan presentation

Body:
xaringan output is html so you can change any parts by css (e.g. using this guide to change bullet color to a red dot. Taking this as a template, you can add this chunk soon after the YAML of the Rmd to change it to a red bullet:

```{css, echo=F}
ul {
  list-style: none; /* Remove default bullets */
}

ul li::before {
  content: "\2022";  /* Add content: \2022 is the CSS Code/unicode for a bullet */
  color: red; /* Change the color */
  font-weight: bold; /* If you want it to be bold */
  display: inline-block; /* Needed to add space between the bullet and the text */
  width: 1em; /* Also needed for space (tweak if needed) */
  margin-left: -1em; /* Also needed for space (tweak if needed) */
}
```

Separate style from content

Or more preferably (since it separates out the style component from slide content), create a css file, say style.css which contains:

ul {
  list-style: none; /* Remove default bullets */
}

ul li::before {
  content: "\2022";  /* Add content: \2022 is the CSS Code/unicode for a bullet */
  color: red; /* Change the color */
  font-weight: bold; /* If you want it to be bold */
  display: inline-block; /* Needed to add space between the bullet and the text */
  width: 1em; /* Also needed for space (tweak if needed) */
  margin-left: -1em; /* Also needed for space (tweak if needed) */
}

then add in the YAML, making sure that style.css is in the same path as your Rmd,

css: [xaringan-themer.css, style.css]

Tweaking the bullet shape

You can change the shape the bullet using a different unicode supplied in content (e.g. use \2023 for a triangle bullet - see other common types here).

Changing the bullet color

You just need to replace red with the color of your choice. You can replace it with the hex color code instead too.


问:
hsts deprecated The "includeSubdomain" paramter is deprecated
I have a loopback 3 application. When I start the application with . node I get this in my console.

```<code>hsts deprecated The "includeSubdomain" parameter is deprecated. Use "includeSubDomains" (with a capital D) instead. node_modules/loopback/lib/server-app.js:74:25
</code>```

I searched in my node_modules folder, but there isn't a loopback folder. So how can I fix this?

答: It's due to the helmet config in middleware.json. Just open it, then find and replace includeSubdomain to includeSubDomains.

Body:
I have a loopback 3 application. When I start the application with . node I get this in my console.

hsts deprecated The "includeSubdomain" parameter is deprecated. Use "includeSubDomains" (with a capital D) instead. node_modules/loopback/lib/server-app.js:74:25

I searched in my node_modules folder, but there isn't a loopback folder. So how can I fix this?


问:
How to get N consecutive digits from a string?
I am trying to get 4 consecutive digits from a string wherever it is matched.

when I am trying re.sub('[^\d]+', ',', "abc 23 [1981] ghj [5656]") it returns ,23,1981,5656,.so when i do re.sub('[\d]{4}+', ',', "abc 23 [2021]") it returns an error "multiple repeat at position 7"

Since I am keeping {4}, shouldn't it match for 4 occurrences of [\d] and return ,1981,5656, ?

Body:
Use re.findall

Ex:

import re

s = "abc 23 [1981] ghj [5656]"
print(re.findall(r"\[(\d{4})\]", s))

Output:

['1981', '5656']


问:
Extra field of ModelForm without label, does not render in InlineModelAdmin
To add an extra field in the admin add page, the following code will work:

models.py:

class Parent(models.Model):
    pass

class Child(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.PROTECT)
```

<p>forms.py:</p>

<pre class="lang-py prettyprint-override"><code>class ChildForm(forms.ModelForm):
    extra_field = forms.CharField()

    class Meta:
        model = Child
        fields = '__all__'
</code>```

admin.py:

@admin.register(models.Child)
class ChildAdmin(admin.ModelAdmin):
    form = forms.ChildForm
```

<hr>

<p><strong>How</strong> can I add the same extra field when <code>Child</code> is an inline to <code>Parent</code> in the <code>Parent</code> <code>add</code> page?</p>

<hr>

<p>The following admin.py:</p>

<pre class="lang-py prettyprint-override"><code>class ChildInline(admin.TabularInline):
    model = models.Child
    form = forms.ChildForm

@admin.register(models.Parent)
class ParentAdmin(admin.ModelAdmin):
    inlines = (ChildInline,)
</code>```

results in:

```<code>Traceback (most recent call last):
  File "django/db/models/options.py", line 617, in get_field
    return self.fields_map[field_name]
KeyError: 'extra_field'

...

django.core.exceptions.FieldDoesNotExist: Child has no field named 'extra_field'

...

AttributeError: Unable to lookup 'extra_field' on Child or ChildInline
</code>```

答:
As per this answer, adding a label, will make the inlines work as expected:

```<code>class ChildForm(forms.ModelForm):
    extra_field = forms.CharField(label='Extra Field')

    class Meta:
        model = Child
        fields = '__all__'
</code>```

Relevant ticket: https://code.djangoproject.com/ticket/30520#ticket

Body:
To add an extra field in the admin add page, the following code will work:

models.py:

class Parent(models.Model):
    pass

class Child(models.Model):
    parent = models.ForeignKey(Parent, on_delete=models.PROTECT)

forms.py:

class ChildForm(forms.ModelForm):
    extra_field = forms.CharField()

    class Meta:
        model = Child
        fields = '__all__'

admin.py:

@admin.register(models.Child)
class ChildAdmin(admin.ModelAdmin):
    form = forms.ChildForm

How can I add the same extra field when Child is an inline to Parent in the Parent add page?

The following admin.py:

class ChildInline(admin.TabularInline):
    model = models.Child
    form = forms.ChildForm

@admin.register(models.Parent)
class ParentAdmin(admin.ModelAdmin):
    inlines = (ChildInline,)

results in:

Traceback (most recent call last):
  File "django/db/models/options.py", line 617, in get_field
    return self.fields_map[field_name]
KeyError: 'extra_field'

...

django.core.exceptions.FieldDoesNotExist: Child has no field named 'extra_field'

...

AttributeError: Unable to lookup 'extra_field' on Child or ChildInline

Body:
As per this answer, adding a label, will make the inlines work as expected:

class ChildForm(forms.ModelForm):
    extra_field = forms.CharField(label='Extra Field')

    class Meta:
        model = Child
        fields = '__all__'

Relevant ticket: https://code.djangoproject.com/ticket/30520#ticket