问:
Rails not possible dynamic add another input field in nested form (two level) association has many through
I'm working in Rails, and I have a problem in formular

Formular

Models

I have 3 models probably with wrong association

```<code>class TagCondition < ApplicationRecord
  has_many :tag_percents
  has_many :tags, through: :tag_percents
  accepts_nested_attributes_for :tag_percents
end

class TagPercent < ApplicationRecord
  belongs_to :tag_condition, optional: true
  belongs_to :tag, optional: true
  accepts_nested_attributes_for :tag
end

class Tag < ApplicationRecord
     belongs_to :tag_percent, dependent: :destroy
end
</code>```

Controller

```<code>class TagConditionsController < ApplicationController
  before_action :set_tag_condition, only: [:show, :edit, :update, :destroy]

  def new
    @tag_condition = TagCondition.new
    per = @tag_condition.tag_percents.build
    per.build_tag (maybe wrong, but "per.tags.build" get error)
  end

  def tag_condition_params
      params.require(:tag_condition).permit(
        :condition,
        tag_percents_attributes: [ :id, :percent,
        {tag_attributes: [ :id, :name]}] )
    end
</code>```

View

```<code><%= form_for(tag_condition) do |f| %>
  <div class="field">
    <%= f.label :condition %>
    <%= f.text_field :condition %>
  </div>

...
  <tbody class="fields">
     <%= f.fields_for :tag_percents do |builder| %>
       <%= render 'tag_percent_fields' , :f => builder %>
     <% end %>
  </tbody>
...

and in partial _tag_percent...
  <td>
    <%= f.fields_for **:tag** do |builder| %>
      <%= builder.text_field :name, class: "form-control" %>
    <% end %>
  </td>

  <td>
      <%= f.number_field :percent, in: 1..100, placeholder: 100, class: "form-control" %>
  </td>
</code>```

When I change in partial from ":tag" to ":tags", it works in formular, but unfortunately I have a problem with save records to database ... INSERT INTO table TAGS is missing, I have only INSERTS to tag_percent and ta_conditions

Can you help me please? Or show some tutorial (or a simple project on Github) with same case (everything in Youtube is only with one level nested form no my case has many through with field percent in "middle" table Tag_percent and dynamic add rows).

答:
Solved!
With help this demo project
https://github.com/nathanvda/cocoon_simple_form_demo</p>

Body:
I'm working in Rails, and I have a problem in formular

Formular

Models

I have 3 models probably with wrong association

class TagCondition < ApplicationRecord
  has_many :tag_percents
  has_many :tags, through: :tag_percents
  accepts_nested_attributes_for :tag_percents
end

class TagPercent < ApplicationRecord
  belongs_to :tag_condition, optional: true
  belongs_to :tag, optional: true
  accepts_nested_attributes_for :tag
end

class Tag < ApplicationRecord
     belongs_to :tag_percent, dependent: :destroy
end

Controller

class TagConditionsController < ApplicationController
  before_action :set_tag_condition, only: [:show, :edit, :update, :destroy]

  def new
    @tag_condition = TagCondition.new
    per = @tag_condition.tag_percents.build
    per.build_tag (maybe wrong, but "per.tags.build" get error)
  end

  def tag_condition_params
      params.require(:tag_condition).permit(
        :condition,
        tag_percents_attributes: [ :id, :percent,
        {tag_attributes: [ :id, :name]}] )
    end

View

<%= form_for(tag_condition) do |f| %>

    <%= f.label :condition %>
    <%= f.text_field :condition %>

...

     <%= f.fields_for :tag_percents do |builder| %>
       <%= render 'tag_percent_fields' , :f => builder %>
     <% end %>

...

and in partial _tag_percent...

    <%= f.fields_for **:tag** do |builder| %>
      <%= builder.text_field :name, class: "form-control" %>
    <% end %>

      <%= f.number_field :percent, in: 1..100, placeholder: 100, class: "form-control" %>

When I change in partial from ":tag" to ":tags", it works in formular, but unfortunately I have a problem with save records to database ... INSERT INTO table TAGS is missing, I have only INSERTS to tag_percent and ta_conditions

Can you help me please? Or show some tutorial (or a simple project on Github) with same case (everything in Youtube is only with one level nested form no my case has many through with field percent in "middle" table Tag_percent and dynamic add rows).


来源: stackexchange

问:
Define task / step and run it many times / alternative to include_tasks
I have a task which I want to run many times throughout my play

```<code>e.g.
    - name: run_many
      debug:
        msg: "I have been run"
</code>```

Now rather than adding this step is there a way I can pre-can / define this so I can just say:

```<code>- < run this pre-defined step >
</code>```

The reason for this is I need to run this many times and I don't want to have to update it in x number of places should it ever need changing.

At the moment I am doing an include_tasks: which is, obviously, adding that to my output as a step - but is this the best / standard way to do something like this?

current setup that works:

```<code>$ls ./roles/demo/tasks/
main.yml  run_many.yml
$cat main.yml
---

-  include_tasks: run_many.yml
-  include_tasks: run_many.yml
</code>```

Play output:

```<code>TASK [demo: include_tasks] *******************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/main.yml:3
included: /home/ansible/roles/demo/tasks/run_many.yml for localhost

TASK [demo: run_many] ************************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/run_many.yml:1
ok: [localhost] => {
    "msg": "I have been run"
}

TASK [demo: include_tasks] *******************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/main.yml:4
included: /home/ansible/roles/demo/tasks/run_many.yml for localhost

TASK [demo: run_many] ************************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/run_many.yml:1
ok: [localhost] => {
    "msg": "I have been run"
}
</code>```

答:
It will depend on the task you want to perform.
For example if you want to make config changes to linux apache and then restart apache
and you have multiple such changes then it makes no sense to put restart logic in a yml and call it using - include

Instead, use handlers,
https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#handlers-running-operations-on-change

notify: <handler name> will help in triggering a handler.

Note: handler name should be same as the task name to be triggered from the handlers directory or if you define handlers normally.
/handlers/tasks/main.yml

```<code>  - name: OS handler
    debug: msg='test'
    when: ansible_distribution == "RedHat"
</code>```

you can let it run a check on some global variable and call it every task using notify. It will run the check and execute if the check is success

Instead of ansible_distribution you can have some other global variable

Otherwise use - include
Let me know if this answers your question

ContentLicense: CC BY-SA 4.0

Body:
I have a task which I want to run many times throughout my play

e.g.
    - name: run_many
      debug:
        msg: "I have been run"

Now rather than adding this step is there a way I can pre-can / define this so I can just say:

- < run this pre-defined step >

The reason for this is I need to run this many times and I don't want to have to update it in x number of places should it ever need changing.

At the moment I am doing an include_tasks: which is, obviously, adding that to my output as a step - but is this the best / standard way to do something like this?

current setup that works:

$ls ./roles/demo/tasks/
main.yml  run_many.yml
$cat main.yml
---

-  include_tasks: run_many.yml
-  include_tasks: run_many.yml

Play output:

TASK [demo: include_tasks] *******************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/main.yml:3
included: /home/ansible/roles/demo/tasks/run_many.yml for localhost

TASK [demo: run_many] ************************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/run_many.yml:1
ok: [localhost] => {
    "msg": "I have been run"
}

TASK [demo: include_tasks] *******************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/main.yml:4
included: /home/ansible/roles/demo/tasks/run_many.yml for localhost

TASK [demo: run_many] ************************************************************************************************************************************
task path: /home/ansible/roles/demo/tasks/run_many.yml:1
ok: [localhost] => {
    "msg": "I have been run"
}

Body:
It will depend on the task you want to perform.
For example if you want to make config changes to linux apache and then restart apache
and you have multiple such changes then it makes no sense to put restart logic in a yml and call it using - include

Instead, use handlers,
https://docs.ansible.com/ansible/latest/user_guide/playbooks_intro.html#handlers-running-operations-on-change

notify: <handler name> will help in triggering a handler.

Note: handler name should be same as the task name to be triggered from the handlers directory or if you define handlers normally.
/handlers/tasks/main.yml

  - name: OS handler
    debug: msg='test'
    when: ansible_distribution == "RedHat"

you can let it run a check on some global variable and call it every task using notify. It will run the check and execute if the check is success

Instead of ansible_distribution you can have some other global variable

Otherwise use - include
Let me know if this answers your question


问:
Network request failed when fetch post with multipart form data
I've tried following https://stackoverflow.com/a/40714217/9957948 and https://stackoverflow.com/a/35206069/9957948 with no success.  I am still getting Network request failed.

Here is my cURL request that works:

```<code>curl -X POST "url" -H  "Content-Type: multipart/form-data; boundary=--CUSTOM" -H "Content-Length: 237" -d $'----CUSTOM\nContent-Disposition: form-data; name="fileToUpload"; filename="t006"\nContent-Type: application/octet-stream\n\nset shiftwidth=4\nset autoindent\n\n----CUSTOM\nContent-Disposition: form-data; name="submit"\n\nUpload Image\n----CUSTOM--\n'
</code>```

And here is what I tried to convert it to, and it is returning Network request failed.

```<code>uploadFile(){
        const formData = new FormData()
        formData.append('blob', new Blob(['set shiftwidth=4\nset autoindent\n']), 't006')

        fetch('url', {
          method: 'POST',
          body: formData
        })
        .then(data => {
          console.log(data)
        })
        .catch(error => {
            console.log('error:' + error.message);
        })
</code>```

Is Content-Length or the body Content-Type: application/octet-stream required?

I'm fairly new to all this so any help would be appreciated.  Thanks

答: Try to use PUT instead of POST method. Add FLIPPER_VERSION=0.41.0 in your gradle.properties. If this does not work then comment a code from ReactNativeFlipper.java class path to this file yourProject\node_modules\react-native\ReactAndroid\src\debug\java\com\facebook\flipper.

Body:
I've tried following https://stackoverflow.com/a/40714217/9957948 and https://stackoverflow.com/a/35206069/9957948 with no success.  I am still getting Network request failed.

Here is my cURL request that works:

curl -X POST "url" -H  "Content-Type: multipart/form-data; boundary=--CUSTOM" -H "Content-Length: 237" -d $'----CUSTOM\nContent-Disposition: form-data; name="fileToUpload"; filename="t006"\nContent-Type: application/octet-stream\n\nset shiftwidth=4\nset autoindent\n\n----CUSTOM\nContent-Disposition: form-data; name="submit"\n\nUpload Image\n----CUSTOM--\n'

And here is what I tried to convert it to, and it is returning Network request failed.

uploadFile(){
        const formData = new FormData()
        formData.append('blob', new Blob(['set shiftwidth=4\nset autoindent\n']), 't006')

        fetch('url', {
          method: 'POST',
          body: formData
        })
        .then(data => {
          console.log(data)
        })
        .catch(error => {
            console.log('error:' + error.message);
        })

Is Content-Length or the body Content-Type: application/octet-stream required?

I'm fairly new to all this so any help would be appreciated.  Thanks


问:
how can i read with jquery a file csv that has been uploaded with html form?
I am trying to read a csv file with jquery. I have passed the file with input tag of html but i am having some problems to read it. Below the code that i have written.

HTML code:

```<code><div id="insertCSV" class = "formblacktransparent">
                                <input id="csv" type="file" accept=".csv" class="form-control"  placeholder="Insert csv"> </input>
                                <button type="button" class="log-btn" id="confCsv"> Confirm </button>

                            </div>
</code>```

Jquery code:

```<code>$("#confCsv").click(function(data){
                var input = document.getElementById('csv');
                var file = input.files[0];
                alert(file[0]);
                 var fr = new FileReader();
                fr.readAsDataURL(data);
                alert(fr);

                });
</code>```

I don 't understand if in this way the file has been uploaded and how i can accede to it.
Any ideas? thank you in advance!!

答:
I write below the code that i have used to resolve my problem. I hope it can be useful. Hello!</p>

```<code>document.querySelector("#confCsv").addEventListener('click', function() {
                if(document.querySelector("#csv").files.length == 0) {
                alert('Error : No file selected');
                return;
                }

                 // first file selected by user
                var file = document.querySelector("#csv").files[0];

                 // perform validation on file type & size if required

                 // read the file
                 var reader = new FileReader();

                // file reading started
                reader.addEventListener('loadstart', function() {
                console.log('File reading started');
                });

                 // file reading finished successfully
                 reader.addEventListener('load', function(e) {
                   // contents of file in variable
                 var text = e.target.result;
                  var row =  text.split('\n');

                  row.forEach(function(e) {

                  var datiGiornalieri = e.split(';');
                socket.emit('parameterRegistrationFile', {ID: patientID, paramdata: datiGiornalieri[0], parametername: 'alfa',parametervalue: datiGiornalieri[1] });

                  });
    });

                reader.readAsText(file);
    });
</code>```

Body:
I am trying to read a csv file with jquery. I have passed the file with input tag of html but i am having some problems to read it. Below the code that i have written.

HTML code:

                                <input id="csv" type="file" accept=".csv" class="form-control"  placeholder="Insert csv"> </input>
                                <button type="button" class="log-btn" id="confCsv"> Confirm </button>

Jquery code:

$("#confCsv").click(function(data){
                var input = document.getElementById('csv');
                var file = input.files[0];
                alert(file[0]);
                 var fr = new FileReader();
                fr.readAsDataURL(data);
                alert(fr);

                });

I don 't understand if in this way the file has been uploaded and how i can accede to it.
Any ideas? thank you in advance!!

Body:
I write below the code that i have used to resolve my problem. I hope it can be useful. Hello!

document.querySelector("#confCsv").addEventListener('click', function() {
                if(document.querySelector("#csv").files.length == 0) {
                alert('Error : No file selected');
                return;
                }

                 // first file selected by user
                var file = document.querySelector("#csv").files[0];

                 // perform validation on file type & size if required

                 // read the file
                 var reader = new FileReader();

                // file reading started
                reader.addEventListener('loadstart', function() {
                console.log('File reading started');
                });

                 // file reading finished successfully
                 reader.addEventListener('load', function(e) {
                   // contents of file in variable
                 var text = e.target.result;
                  var row =  text.split('\n');

                  row.forEach(function(e) {

                  var datiGiornalieri = e.split(';');
                socket.emit('parameterRegistrationFile', {ID: patientID, paramdata: datiGiornalieri[0], parametername: 'alfa',parametervalue: datiGiornalieri[1] });

                  });
    });

                reader.readAsText(file);
    });


问:
why should i use @classmethod when i can call the constructor in the without the annotation?
I was looking into the advantages of @classmethods and figured that we can directly call the constructor from any method, in that case, why do we need a class method. Are there some advantages which i have missed.

Why this code, what are the advantages?

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)
</code>```

and not this code :-

```<code>class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)
</code>```

答:
Given

```<code>from datetime import date
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"
</code>```

your code works find, as long as you don't access fromBirthYear via an instance of Person:

```<code>>>> Person("bob", 2010)
Person('bob', 10)
</code>```

However, invoking it from an instance of Person will not:

```<code>>>> Person("bob", 2010).fromBirthYear("bob again", 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fromBirthYear() takes 2 positional arguments but 3 were given
</code>```

This is due to how the function type implements the descriptor protocol: access through an instance calls its __get__ method (which returns the method object that "prepasses" the instance to the underlying function), while access through the class returns the function itself.

To make things more consistent, you can define fromBirthYear as a static method, which always gives access to the underlying function whether accessed from the class or an instance:

```<code>from datetime import date
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

>>> Person.fromBirthYear("bob", 2010)
Person('bob', 10)
>>> Person.fromBirthYear("bob", 2010).fromBirthYear("bob again", 2015)
Person('bob again', 5)
</code>```

Finally, a class method behaves somewhat like a static method, being consistent in the arguments received whether invoked from the class or an instance of the class. But, like an instance method, it does receive one implicit argument: the class itself, rather than the instance of the class. The benefit here is that the instance returned by the class method can be determined at runtime. Say you have a subclass of Person

```<code>from datetime import date
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

class DifferentPerson(Person):
    pass
</code>```

Both classes can be used to call fromBirthYear, but the return value now depends on the class which calls it.

```<code>>>> type(Person.fromBirthYear("bob", 2010))
<class '__main__.Person'>
>>> type(DifferentPerson.fromBirthYear("other bog", 2010))
<class '__main__.DifferentPerson'>
</code>```

Body:
I was looking into the advantages of @classmethods and figured that we can directly call the constructor from any method, in that case, why do we need a class method. Are there some advantages which i have missed.

Why this code, what are the advantages?

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)

and not this code :-

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)

Body:
Given

from datetime import date
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

your code works find, as long as you don't access fromBirthYear via an instance of Person:

>>> Person("bob", 2010)
Person('bob', 10)

However, invoking it from an instance of Person will not:

>>> Person("bob", 2010).fromBirthYear("bob again", 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: fromBirthYear() takes 2 positional arguments but 3 were given

This is due to how the function type implements the descriptor protocol: access through an instance calls its __get__ method (which returns the method object that "prepasses" the instance to the underlying function), while access through the class returns the function itself.

To make things more consistent, you can define fromBirthYear as a static method, which always gives access to the underlying function whether accessed from the class or an instance:

from datetime import date
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @staticmethod
    def fromBirthYear(name, year):
        return Person(name, date.today().year - year)

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

>>> Person.fromBirthYear("bob", 2010)
Person('bob', 10)
>>> Person.fromBirthYear("bob", 2010).fromBirthYear("bob again", 2015)
Person('bob again', 5)

Finally, a class method behaves somewhat like a static method, being consistent in the arguments received whether invoked from the class or an instance of the class. But, like an instance method, it does receive one implicit argument: the class itself, rather than the instance of the class. The benefit here is that the instance returned by the class method can be determined at runtime. Say you have a subclass of Person

from datetime import date
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def fromBirthYear(cls, name, year):
        return cls(name, date.today().year - year)

    def __repr__(self):
        return f"Person('{self.name}', {self.age})"

class DifferentPerson(Person):
    pass

Both classes can be used to call fromBirthYear, but the return value now depends on the class which calls it.

>>> type(Person.fromBirthYear("bob", 2010))
<class '__main__.Person'>
>>> type(DifferentPerson.fromBirthYear("other bog", 2010))
<class '__main__.DifferentPerson'>


问:
C++ elapsed time = 0
I have a code written in C++ in Visual Studio:

```<code>    auto start = std::chrono::high_resolution_clock::now();
    result = function(-1, 1, 9999999);
    auto end = std::chrono::high_resolution_clock::now();

    double time_taken = chrono::duration_cast<chrono::microseconds>(end - start).count();
    time_taken *= 1e-6;
    std::cout << "result: " << result << "time : " << fixed << time_taken << setprecision(6) << " sec" << endl;
</code>```

The problem is: I run the code in Release mode and time_taken always equals 0. When I switch to the Debug mode time_taken is between 1 and 2 seconds. I tried different ways to pinpoint time but time_taken always equals 0. How can I fix this?
Thanks in advance for your help!

答:
Apparently you are lacking clock resolution. Or the function was partly or fully optimized away.

Generally it is not trivial to profile small functions.

One thing you should do is to call it a lot of times, and measure time of whole run, then divide this time by number of calls.

Also make sure the function is actually fully computed at runtime by stroing result in a volatile variable, and taking input from volatile variables.

Title: C++ elapsed time = 0

Body:
I have a code written in C++ in Visual Studio:

    auto start = std::chrono::high_resolution_clock::now();
    result = function(-1, 1, 9999999);
    auto end = std::chrono::high_resolution_clock::now();

    double time_taken = chrono::duration_cast<chrono::microseconds>(end - start).count();
    time_taken *= 1e-6;
    std::cout << "result: " << result << "time : " << fixed << time_taken << setprecision(6) << " sec" << endl;

The problem is: I run the code in Release mode and time_taken always equals 0. When I switch to the Debug mode time_taken is between 1 and 2 seconds. I tried different ways to pinpoint time but time_taken always equals 0. How can I fix this?
Thanks in advance for your help!


问:
launching a Windows app on client side (triggered by click on webpage)
is that possible to launch a preinstalled application from a webpage.

i can see that steam has created its own protocol steam:// by installing something into my registry and now whenever i click a steam://ip link .. it tries to launch a file. so i was wondering if its possible to launch an application from a webpage, may be register an application to a URL protocol?

example: lets say i have link to a media file on my webpage(lets say divx). now one choice is divx webplayer or other choices. but i want that given a choice the user can launch vlc directly by clicking a link (vlc:// http://...), is that possible?

i read a little about this here
but it doesnt clicks clearly to me.

答:
Yes: you would need to build/register a URL handler and tie it to the right application. The simplest explanation is previously answered at How can I add a custom url handler on Windows. Like iTunes itms://.

More complex URL handlers will require you to do native code of your very own: the document you linked to is completely correct. You will need some familiarity with writing registry files, but otherwise it is quite doable.

ContentLicense: CC BY-SA 3.0


问:
New project xamarin.form prism Error NETSDK1004 - Prism 2.2.1
when generating a new project xamarin.form prism I get this error when running. With the previous version 2.1.7 it worked for me OK.
It does not allow me to open the Nuget Package since it also gives an error.
Any recommendation?
I saw the 2 posts of this error but they do not apply to me.

Error   NETSDK1004  Assets file 'C:\Empresas\Job_Facu\Job\Job.Prism\Job.Prism\obj\project.assets.json' not found. Run a NuGet package restore to generate this file.    Job.Prism   C:\Program Files\dotnet\sdk\3.1.202\Sdks\Microsoft.NET.Sdk\targets\Microsoft.PackageDependencyResolution.targets    234

答:
The error tells you what to do. Run a NuGet restore. Visual Studio should help you do this automatically. Note that if this occurred after updating dependencies sometimes Visual Studio gets confused and it's best to close Visual Studio and reopen it. This usually gets it to refresh itself so you get the updated package restore.

If that's not working for you, you can download the latest nuget.exe and from the command line navigate to the solution directory and execute the command {path to nuget.exe} restore.

When NuGet performs a restore it generates the project.assets.json file in the obj folder of each project it has restored. This in turn provides MSBuild with the reference information it needs to properly reference your dependencies like Prism and Xamarin.Forms.


问:
Scroll to the top of the page using JavaScript?
How do I scroll to the top of the page using JavaScript? The scrollbar instantly jumping to the top of the page is desirable too as I'm not looking to achieve smooth scrolling.</p>

答:
You can use javascript's built in function scrollTo:

function scroll() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><button onclick="scroll">Scroll</button></code>```

Body:
You can use javascript's built in function scrollTo:

function scroll() {
  window.scrollTo({
    top: 0,
    behavior: 'smooth'
  });
}

<button onclick="scroll">Scroll</button>


问:
How to reinitialize inside synchronized block in Java?
I have a s3client which uses password with 60 days rotation policy. For that, we have a single s3client object being used but when the password rotates, all threads start giving exceptions. I want to catch and make sure only 1 of the threads reinitialize Client and others do nothing inside synchronized block. Can't figure out a way to do so.</p>

```<code>private static AtomicBoolean initializingS3Client = new AtomicBoolean(false);

public static AmazonS3 reinitializeAndProvideS3Client() throws Exception {
    synchronized (initializingS3Client) {
        if (initializingS3Client.compareAndSet(false, true)) {
            s3Client.shutdown();
            s3Client = createAmazonS3Client();
            initializingS3Client.notifyAll();
        } else {
            initializingS3Client.wait();
        }
    }
    return s3Client;
}
</code>```

答:
You didn't share the code that does the actual error handling / trigger the re-initialize. I assume that you call the method on any occuring IOException. To avoid that e.g. temporal network problems lead to thousands or millions of unwnated re-initializations I would suggest to specify a minimal time between two re-initializations. This helps also to make the code simpler:

```<code>public YourClass {
  ...
  private static final long MIN_TIME_BETWEEN_TWO_REINITIALIZES = 60 * 1_000; // 1 min
  privat static long lastReinitialize = 0;

  public static AmazonS3 reinitializeAndProvideS3Client() throws Exception {
    synchronized (YourClass.class) {
      long now = System.currentTimeInMillis();
      if (now - lastReinitialize > MIN_TIME_BETWEEN_TWO_REINITIALIZES ) {
        s3Client.shutdown();
        s3Client = createAmazonS3Client();
        lastReinitialize = now;
      }
      return s3Client;
    }
  }
}
</code>```

I assume that the s3Client field is volatile and the s3Client implementation is thread-safe. If s3Client should not be volatile and access to it should already be synchronized by another object, then replace YourClass.class in the synchronized statement with that object.

Body:
I have a s3client which uses password with 60 days rotation policy. For that, we have a single s3client object being used but when the password rotates, all threads start giving exceptions. I want to catch and make sure only 1 of the threads reinitialize Client and others do nothing inside synchronized block. Can't figure out a way to do so.

private static AtomicBoolean initializingS3Client = new AtomicBoolean(false);

public static AmazonS3 reinitializeAndProvideS3Client() throws Exception {
    synchronized (initializingS3Client) {
        if (initializingS3Client.compareAndSet(false, true)) {
            s3Client.shutdown();
            s3Client = createAmazonS3Client();
            initializingS3Client.notifyAll();
        } else {
            initializingS3Client.wait();
        }
    }
    return s3Client;
}

Body:
You didn't share the code that does the actual error handling / trigger the re-initialize. I assume that you call the method on any occuring IOException. To avoid that e.g. temporal network problems lead to thousands or millions of unwnated re-initializations I would suggest to specify a minimal time between two re-initializations. This helps also to make the code simpler:

public YourClass {
  ...
  private static final long MIN_TIME_BETWEEN_TWO_REINITIALIZES = 60 * 1_000; // 1 min
  privat static long lastReinitialize = 0;

  public static AmazonS3 reinitializeAndProvideS3Client() throws Exception {
    synchronized (YourClass.class) {
      long now = System.currentTimeInMillis();
      if (now - lastReinitialize > MIN_TIME_BETWEEN_TWO_REINITIALIZES ) {
        s3Client.shutdown();
        s3Client = createAmazonS3Client();
        lastReinitialize = now;
      }
      return s3Client;
    }
  }
}

I assume that the s3Client field is volatile and the s3Client implementation is thread-safe. If s3Client should not be volatile and access to it should already be synchronized by another object, then replace YourClass.class in the synchronized statement with that object.


问:
sproutcore vs javascriptMVC for web app development
I want to use a javascript framework with MVC for a complex web application (which will be one of a set of related apps and pages) for an intranet in a digital archives. I have been looking at SproutCore and JavascriptMVC. I want to choose one framework and stick with it.

Does anybody know what the distinguishing features are when comparing these two?

I want something that is simple, straightforward that I can customize/hack easily, and that doesn't get in my way too much, but that at the same time gives me a basis for keeping my code nicely organized, and event-driven. I also plan on using jquery substantially.

I know sproutcore is backed by Apple, and looks like it is getting more popular by the day, and it has a nice green website :), whereas JavascriptMVC looks less professional, with less of a following and less momentum behind it.

I've done the tutorials for both and I was impressed by SproutCore more (in the JMVC tutorial you don't really do anything substantial) - but somewhere in the back of my mind I feel that JMVC might just be better because it doesn't try and do too much - it just gives you MVC functionality based on a couple of jquery plugins, and you can use jquery for everything else, so its flexible. Whereas SproutCore seems to have more of its own API etc... which is also nice in a way... but then you're kind of stuck within that.... hmmm I'm confused :).

Any thoughts would be much appreciated.

答:
Sproutcore-2.0 eliminates the ui-constraints and plays nice with completely custom app-uis.

http://blog.sproutcore.com/announcing-sproutcore-2-0/

http://blog.sproutcore.com/dispatches-from-the-edge-dropping-in-a-sproutcore-2-0-application/

ContentLicense: CC BY-SA 2.5


问:
Need to subset a dataset in SAS based on two variables
I have a complex dataset and need to pull unique individuals who might have multiple observations for different reasons. Here is an example of how to the data is organized:

```<code>id caseid employerid
1  1      1
1  1      2
1  2      1
1  2      2
2  1      1
3  1      1
3  2      1
</code>```

Basically individuals have a unique id but could be in multiple cases and could also have multiple employers. I want to remove duplicates by caseid but not by employerid for each individual and I am not sure how to do this. Thanks.

答:
Use COUNT DISTINCT to find the number of caseID and employerID per ID

Filter it based on a WHERE query

Isolate all records from your have table based on #2.

```<code>proc sql;
create table _filtered as
select id, count(distinct caseID) as n_caseID, count(distinct employerID) as n_employerID
from have;
order by 1, 2, 3;
quit;

proc sql;
create table want as
select *
from have where ID in
      (select ID from _filtered where n_caseID=1);
quit;
</code>```

Body:
I have a complex dataset and need to pull unique individuals who might have multiple observations for different reasons. Here is an example of how to the data is organized:

id caseid employerid
1  1      1
1  1      2
1  2      1
1  2      2
2  1      1
3  1      1
3  2      1

Basically individuals have a unique id but could be in multiple cases and could also have multiple employers. I want to remove duplicates by caseid but not by employerid for each individual and I am not sure how to do this. Thanks.

Body:
Use COUNT DISTINCT to find the number of caseID and employerID per ID

Filter it based on a WHERE query

Isolate all records from your have table based on #2.

proc sql;
create table _filtered as
select id, count(distinct caseID) as n_caseID, count(distinct employerID) as n_employerID
from have;
order by 1, 2, 3;
quit;

proc sql;
create table want as
select *
from have where ID in
      (select ID from _filtered where n_caseID=1);
quit;


问:
Azure Streaming URL validity
I'm currently looking into Azure Streaming service for client purposes and I am wondering if there is a way to create time limited URL for Adaptive Streaming (we need this for security purposes, when user wants to stream, we verify permissions then create time limited URL). I see that Streaming Locator can have the end date, but is it really the best practice to create new Streaming Locator each time when someone requests the stream? That means I would need to persist them, then clean them up after expiration. Is there any better way to create time limited URL for adaptive streaming in Azure Media Services?</p>

答: I would recommend looking at the token authentication capabilities available in Azure CDN from Verizon Premium SKU - https://learn.microsoft.com/en-us/azure/cdn/cdn-token-auth. This would be the simplest path to take. The Azure CDN from Verizon Premium SKU can be enabled directly from configuration on your streaming endpoint. The endpoint will need to be stopped in order to enable Azure CDN for it. You could also accomplish directly using content protection capabilities available in Media Services - https://learn.microsoft.com/en-us/azure/media-services/previous/media-services-content-protection-overview. This path is much more complex one to take and would require significantly more development work.</p>

Title: Azure Streaming URL validity


问:
i'm trying to change the value in one dictionary by comparing the key from another dictionary
```<code>var clariQuestion: [String: String] = ["0": "What are my last 10 transactions",
                                    "1": "What are my spending transactions",
                                    "2": "What are my largest trasactions",
                                    "3": "What are my pending tracnstions"]

var explanationActionParameters: [String: Any] = ["clariQuestion": 2]
</code>```

So i need to match the value of explanationActionParameters with the key of clariQuestion, and then when the keys match replace the number 2 in explanationActionParameters with "what are my largest transactions". What's causing me difficulty is that the value in explanationActionParameter is of type 2 and the key in clariQuestion is of type String. Not to sure how to go about this.

答:
You can either convert your int to string, using String(2) or convert your string to int, like Int("2")
My answer to you would be to transform your clariQuestion dictionary into an array, because the keys are integers, and an array can be seen as a dictionary where the keys are integers. So, you could do

```<code>var clariQuestion: [String] = ["What are my last 10 transactions",
                                "What are my spending transactions",
                                "What are my largest trasactions",
                                "What are my pending tracnstions"]
var explanationActionParameters: [String: Any] = ["clariQuestion": 2]

let questionIndex = explanationActionParameters["clariQuestion"]
let question = clariQuestion[questionIndex]
</code>```

If you insist on maintaining this dictionary structure, you can flatmap your dictionaries and transform all keys from string to int, like this

```<code>clariQuestion.flatMap { (key, value) in [Int(key) : value] }
</code>```

or transform all your values to a string, like this

```<code>explanationActionParameters.flatMap { (key, value) in [key : String(value)] }
</code>```

Either way, now you should be able to access elements across those dictionaries. I'm going to create a function demonstrating how

```<code>func replace(_ clariQuestion: [String : String], _ explanationActionParameters: [String: Any]) -> [String: String] {
    // The dictionary that will be returned containing the mapping from clariQuestion to explanationActionParameters
    var ret = [String : String]()
    let mappedClariQuestion = clariQuestion.flatMap { (key, value) in [Int(key) : value] }
    for (key, value) in clariQuestion {
        ret[key] = mappedClariQuestion[value]
    }

    return ret
}
</code>```

Then, just explanationActionParameters = replace(clariQuestion, explanationActionParameters)

Body:
var clariQuestion: [String: String] = ["0": "What are my last 10 transactions",
                                    "1": "What are my spending transactions",
                                    "2": "What are my largest trasactions",
                                    "3": "What are my pending tracnstions"]

var explanationActionParameters: [String: Any] = ["clariQuestion": 2]

So i need to match the value of explanationActionParameters with the key of clariQuestion, and then when the keys match replace the number 2 in explanationActionParameters with "what are my largest transactions". What's causing me difficulty is that the value in explanationActionParameter is of type 2 and the key in clariQuestion is of type String. Not to sure how to go about this.

Body:
You can either convert your int to string, using String(2) or convert your string to int, like Int("2")
My answer to you would be to transform your clariQuestion dictionary into an array, because the keys are integers, and an array can be seen as a dictionary where the keys are integers. So, you could do

var clariQuestion: [String] = ["What are my last 10 transactions",
                                "What are my spending transactions",
                                "What are my largest trasactions",
                                "What are my pending tracnstions"]
var explanationActionParameters: [String: Any] = ["clariQuestion": 2]

let questionIndex = explanationActionParameters["clariQuestion"]
let question = clariQuestion[questionIndex]

If you insist on maintaining this dictionary structure, you can flatmap your dictionaries and transform all keys from string to int, like this

clariQuestion.flatMap { (key, value) in [Int(key) : value] }

or transform all your values to a string, like this

explanationActionParameters.flatMap { (key, value) in [key : String(value)] }

Either way, now you should be able to access elements across those dictionaries. I'm going to create a function demonstrating how

func replace(_ clariQuestion: [String : String], _ explanationActionParameters: [String: Any]) -> [String: String] {
    // The dictionary that will be returned containing the mapping from clariQuestion to explanationActionParameters
    var ret = [String : String]()
    let mappedClariQuestion = clariQuestion.flatMap { (key, value) in [Int(key) : value] }
    for (key, value) in clariQuestion {
        ret[key] = mappedClariQuestion[value]
    }

    return ret
}

Then, just explanationActionParameters = replace(clariQuestion, explanationActionParameters)


问:
How to produce static executable on NixOS?
Today I met a really interesting problem with my NixOS distro. I just wanted to create a statically compiled OCaml progam and couldn`t do that. Then I tried to do that with an ANSI C canonical toy "hello world!" application:

```<code>$> cat mytest.c
#include <stdio.h>

int
main ()
{
  puts ("hello world!") ;
}
</code>```

My distro:

```<code>$> uname -a
Linux cat 4.19.36 #1-NixOS SMP Sat Apr 20 07:16:05 UTC 2019 x86_64 GNU/Linux
</code>```

Compiler:

```<code>$> gcc -v
Using built-in specs.
COLLECT_GCC=/nix/store/myq0x6mjbdzxr9fckqn6kgy89kz19nkp-gfortran-7.4.0/bin/gcc
COLLECT_LTO_WRAPPER=/nix/store/myq0x6mjbdzxr9fckqn6kgy89kz19nkp-gfortran-7.4.0/libexec/gcc/x86_64-unknown-linux-gnu/7.4.0/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with:
Thread model: posix
gcc version 7.4.0 (GCC)
</code>```

Cannot produce static exec :

```<code>$> gcc -static mytest.c -o hello
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
</code>```

Any ideas?

Usually a "dynamically linked" program hello is generated by gccwithout a problem.

No such issues on Lubuntu. I was advised to try a different distro and test that exec is running on NixOS. I did it - produced an exec with gcc on Lubuntu and started it on NixOS. Therefore I think that the problem is not with gcc but with NixOS.

How does NixOS treat this problem (i.e., generation of statically compiled exec files)?

And, of course, I'm also interested in the results concerning ocamlopt compiler rather then gcc but I think that the problem is common for all compilers (I tried Haskell ghc too by the way with the same results).

brgs

UPDATE: from a discussion on another thread:

```<code>  1 @Ston17 You may have the .so but not the .a – norok2
  2
  3 yes - i have .so what the difference? can the presence of .a improve the situation? – Ston17
  4
  5 Yes. You typically need .a library to have the static linking work correctly – norok2

$> find /nix/store/ -name *libc.a.*
$>
</code>```

can this be the reason?

UPDATE2: as concerning ocamlopt:

source file

```<code>$> cat mytest.ml
print_string "hello world!" ;;
print_newline () ;;
</code>```

as you can see no special calls to anything. let try to make static exec:

```<code>$> ocamlopt -ccopt -static mytest.ml -o ocaml_test
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lm
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -ldl
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status
</code>```

so ld just cannot link to static version of libc. and i cannot find libc.a in the hole system

any suggetions?

答:
here https://vaibhavsagar.com/blog/2018/01/03/static-haskell-nix/ is explained how you could obtain in NixOS statical versions of sys libraries

nix-shell config file:

```<code>let
  pkgs = import <nixpkgs> {} ;
in pkgs.buildFHSUserEnv {
  name = "fhs" ;
  targetPkgs = pkgs: with pkgs; [
    pkgs.glibc.static
    pkgs.zlib.static
    pkgs.libffi
    pkgs.libtool
    pkgs.musl
    pkgs.ghc
    pkgs.gcc
    pkgs.ocaml
  ] ;
}
</code>```

after that in nix-shell you start chroot FHS and copy needed sys libs into your folder and close chroot FHS

and after that compile your file staticaly

good with gcc:

```<code>$> gcc -static -L/home/.local/lib/ mytest.c -o ansiC_test
$> ldd ansiC_test
  not a dynamic executable
</code>```

not so good but maybe working with ocaml:

```<code>ocamlopt -ccopt -static -cclib -L/home/.local/lib mytest.ml -o ocaml_test

ocamlopt -ccopt -static -cclib -L/home/nomad/.local/lib mytest.ml -o ocaml_test
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: /nix/store/j1v6kkxq081q4m4fw7gazaf6rb3vy87p-ocaml-4.06.1/lib/ocaml/libasmrun.a(unix.o): in function `caml_dlopen':
/build/ocaml-4.06.1/asmrun/unix.c:273: warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking

$> ldd ocaml_test
  not a dynamic executable
</code>```

dont work with ghc though :

```<code>ghc -static -optl-static -L/home/.local/lib/ mytest.hs -o haskell_test
[1 of 1] Compiling Main             ( mytest.hs, mytest.o )
Linking haskell_test ...
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: /nix/store/wfgrz42bpcl1r635dasfk7r236hm83az-ghc-8.6.4/lib/ghc-8.6.4/rts/libHSrts.a(Linker.o): in function `internal_dlopen':
Linker.c:(.text.internal_dlopen+0x7): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lffi
collect2: error: ld returned 1 exit status
`cc' failed in phase `Linker'. (Exit code: 1)
make: *** [makefile:5: haskell] Error 1
</code>```

ok. ocaml works:

```<code>lubuntu@lubuntu:~/Documents$ ./ocaml_hello_nix
hello world!

lubuntu@lubuntu:~/Documents$ readelf -l ocaml_hello_nix

Elf file type is EXEC (Executable file)
Entry point 0x4017a0
There are 9 program headers, starting at offset 64

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x00000000000005d8 0x00000000000005d8  R      0x1000
  LOAD           0x0000000000001000 0x0000000000401000 0x0000000000401000
                 0x0000000000107275 0x0000000000107275  R E    0x1000
  LOAD           0x0000000000109000 0x0000000000509000 0x0000000000509000
                 0x00000000000db191 0x00000000000db191  R      0x1000
  LOAD           0x00000000001e5140 0x00000000005e6140 0x00000000005e6140
                 0x0000000000008a18 0x000000000001dfe0  RW     0x1000
  NOTE           0x0000000000000238 0x0000000000400238 0x0000000000400238
                 0x0000000000000020 0x0000000000000020  R      0x4
  NOTE           0x0000000000000258 0x0000000000400258 0x0000000000400258
                 0x0000000000000020 0x0000000000000020  R      0x8
  TLS            0x00000000001e5140 0x00000000005e6140 0x00000000005e6140
                 0x0000000000000020 0x0000000000000060  R      0x8
  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000

                     0x0000000000000000 0x0000000000000000  RW     0x10
      GNU_RELRO      0x00000000001e5140 0x00000000005e6140 0x00000000005e6140
                     0x0000000000002ec0 0x0000000000002ec0  R      0x1

     Section to Segment mapping:
      Segment Sections...
       00     .note.ABI-tag .note.gnu.property .rela.plt
       01     .init .plt .text __libc_freeres_fn __libc_thread_freeres_fn .fini
       02     .rodata .eh_frame .gcc_except_table
       03     .tdata .init_array .fini_array .data.rel.ro .got .got.plt .data __libc_subfreeres __libc_IO_vtables __libc_atexit __libc_thread_subfreeres .bss __libc_freeres_ptrs
       04     .note.ABI-tag
       05     .note.gnu.property
       06     .tdata .tbss
       07
       08     .tdata .init_array .fini_array .data.rel.ro .got
</code>```

haskell works. the reason was that binary NixOS packet was built without FFI support. i installed ghc from sources and all become fine:

```<code>lubuntu@lubuntu:~/Documents$ ./haskell_hello_nix
hello world!

lubuntu@lubuntu:~/Documents$ readelf -l haskell_hello_nix

Elf file type is EXEC (Executable file)
Entry point 0x405d40
There are 6 program headers, starting at offset 64

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x0000000000188ba4 0x0000000000188ba4  R E    0x1000
  LOAD           0x0000000000188ec0 0x0000000000589ec0 0x0000000000589ec0
                 0x00000000000104c0 0x000000000001ac98  RW     0x1000
  NOTE           0x0000000000000190 0x0000000000400190 0x0000000000400190
                 0x0000000000000020 0x0000000000000020  R      0x4
  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x0000000000000000 0x0000000000000000  RW     0x10
  TLS            0x0000000000188ec0 0x0000000000589ec0 0x0000000000589ec0
                 0x0000000000000070 0x00000000000000b8  R      0x8
  GNU_RELRO      0x0000000000188ec0 0x0000000000589ec0 0x0000000000589ec0
                 0x0000000000003140 0x0000000000003140  RW     0x20

 Section to Segment mapping:
  Segment Sections...
   00     .note.ABI-tag .rela.plt .init .plt .text __libc_thread_freeres_fn .fini .rodata .gcc_except_table .eh_frame
   01     .tdata .data.rel.ro.local .fini_array .init_array .data.rel.ro .preinit_array .got .got.plt .data .tm_clone_table __libc_IO_vtables __libc_atexit __libc_thread_subfreeres .bss __libc_freeres_ptrs
   02     .note.ABI-tag
   03
   04     .tdata .tbss
   05     .tdata .data.rel.ro.local .fini_array .init_array .data.rel.ro .preinit_array .got
</code>```

good. tnx to all who was concerned. you save my a$$

Body:
Today I met a really interesting problem with my NixOS distro. I just wanted to create a statically compiled OCaml progam and couldn`t do that. Then I tried to do that with an ANSI C canonical toy "hello world!" application:

$> cat mytest.c
#include <stdio.h>

int
main ()
{
  puts ("hello world!") ;
}

My distro:

$> uname -a
Linux cat 4.19.36 #1-NixOS SMP Sat Apr 20 07:16:05 UTC 2019 x86_64 GNU/Linux

Compiler:

$> gcc -v
Using built-in specs.
COLLECT_GCC=/nix/store/myq0x6mjbdzxr9fckqn6kgy89kz19nkp-gfortran-7.4.0/bin/gcc
COLLECT_LTO_WRAPPER=/nix/store/myq0x6mjbdzxr9fckqn6kgy89kz19nkp-gfortran-7.4.0/libexec/gcc/x86_64-unknown-linux-gnu/7.4.0/lto-wrapper
Target: x86_64-unknown-linux-gnu
Configured with:
Thread model: posix
gcc version 7.4.0 (GCC)

Cannot produce static exec :

$> gcc -static mytest.c -o hello
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status

Any ideas?

Usually a "dynamically linked" program hello is generated by gccwithout a problem.

No such issues on Lubuntu. I was advised to try a different distro and test that exec is running on NixOS. I did it - produced an exec with gcc on Lubuntu and started it on NixOS. Therefore I think that the problem is not with gcc but with NixOS.

How does NixOS treat this problem (i.e., generation of statically compiled exec files)?

And, of course, I'm also interested in the results concerning ocamlopt compiler rather then gcc but I think that the problem is common for all compilers (I tried Haskell ghc too by the way with the same results).

brgs

UPDATE: from a discussion on another thread:

  1 @Ston17 You may have the .so but not the .a – norok2
  2
  3 yes - i have .so what the difference? can the presence of .a improve the situation? – Ston17
  4
  5 Yes. You typically need .a library to have the static linking work correctly – norok2

$> find /nix/store/ -name *libc.a.*
$>

can this be the reason?

UPDATE2: as concerning ocamlopt:

source file

$> cat mytest.ml
print_string "hello world!" ;;
print_newline () ;;

as you can see no special calls to anything. let try to make static exec:

$> ocamlopt -ccopt -static mytest.ml -o ocaml_test
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lm
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -ldl
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lc
collect2: error: ld returned 1 exit status

so ld just cannot link to static version of libc. and i cannot find libc.a in the hole system

any suggetions?

Body:
here https://vaibhavsagar.com/blog/2018/01/03/static-haskell-nix/ is explained how you could obtain in NixOS statical versions of sys libraries

nix-shell config file:

let
  pkgs = import <nixpkgs> {} ;
in pkgs.buildFHSUserEnv {
  name = "fhs" ;
  targetPkgs = pkgs: with pkgs; [
    pkgs.glibc.static
    pkgs.zlib.static
    pkgs.libffi
    pkgs.libtool
    pkgs.musl
    pkgs.ghc
    pkgs.gcc
    pkgs.ocaml
  ] ;
}

after that in nix-shell you start chroot FHS and copy needed sys libs into your folder and close chroot FHS

and after that compile your file staticaly

good with gcc:

$> gcc -static -L/home/.local/lib/ mytest.c -o ansiC_test
$> ldd ansiC_test
  not a dynamic executable

not so good but maybe working with ocaml:

ocamlopt -ccopt -static -cclib -L/home/.local/lib mytest.ml -o ocaml_test

ocamlopt -ccopt -static -cclib -L/home/nomad/.local/lib mytest.ml -o ocaml_test
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: /nix/store/j1v6kkxq081q4m4fw7gazaf6rb3vy87p-ocaml-4.06.1/lib/ocaml/libasmrun.a(unix.o): in function `caml_dlopen':
/build/ocaml-4.06.1/asmrun/unix.c:273: warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking

$> ldd ocaml_test
  not a dynamic executable

dont work with ghc though :

ghc -static -optl-static -L/home/.local/lib/ mytest.hs -o haskell_test
[1 of 1] Compiling Main             ( mytest.hs, mytest.o )
Linking haskell_test ...
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: /nix/store/wfgrz42bpcl1r635dasfk7r236hm83az-ghc-8.6.4/lib/ghc-8.6.4/rts/libHSrts.a(Linker.o): in function `internal_dlopen':
Linker.c:(.text.internal_dlopen+0x7): warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/nix/store/0y7jmqnj48ikjh37n3dl9kqw9hnn68nq-binutils-2.31.1/bin/ld: cannot find -lffi
collect2: error: ld returned 1 exit status
`cc' failed in phase `Linker'. (Exit code: 1)
make: *** [makefile:5: haskell] Error 1

ok. ocaml works:

lubuntu@lubuntu:~/Documents$ ./ocaml_hello_nix
hello world!

lubuntu@lubuntu:~/Documents$ readelf -l ocaml_hello_nix

Elf file type is EXEC (Executable file)
Entry point 0x4017a0
There are 9 program headers, starting at offset 64

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x00000000000005d8 0x00000000000005d8  R      0x1000
  LOAD           0x0000000000001000 0x0000000000401000 0x0000000000401000
                 0x0000000000107275 0x0000000000107275  R E    0x1000
  LOAD           0x0000000000109000 0x0000000000509000 0x0000000000509000
                 0x00000000000db191 0x00000000000db191  R      0x1000
  LOAD           0x00000000001e5140 0x00000000005e6140 0x00000000005e6140
                 0x0000000000008a18 0x000000000001dfe0  RW     0x1000
  NOTE           0x0000000000000238 0x0000000000400238 0x0000000000400238
                 0x0000000000000020 0x0000000000000020  R      0x4
  NOTE           0x0000000000000258 0x0000000000400258 0x0000000000400258
                 0x0000000000000020 0x0000000000000020  R      0x8
  TLS            0x00000000001e5140 0x00000000005e6140 0x00000000005e6140
                 0x0000000000000020 0x0000000000000060  R      0x8
  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000

                     0x0000000000000000 0x0000000000000000  RW     0x10
      GNU_RELRO      0x00000000001e5140 0x00000000005e6140 0x00000000005e6140
                     0x0000000000002ec0 0x0000000000002ec0  R      0x1

     Section to Segment mapping:
      Segment Sections...
       00     .note.ABI-tag .note.gnu.property .rela.plt
       01     .init .plt .text __libc_freeres_fn __libc_thread_freeres_fn .fini
       02     .rodata .eh_frame .gcc_except_table
       03     .tdata .init_array .fini_array .data.rel.ro .got .got.plt .data __libc_subfreeres __libc_IO_vtables __libc_atexit __libc_thread_subfreeres .bss __libc_freeres_ptrs
       04     .note.ABI-tag
       05     .note.gnu.property
       06     .tdata .tbss
       07
       08     .tdata .init_array .fini_array .data.rel.ro .got

haskell works. the reason was that binary NixOS packet was built without FFI support. i installed ghc from sources and all become fine:

lubuntu@lubuntu:~/Documents$ ./haskell_hello_nix
hello world!

lubuntu@lubuntu:~/Documents$ readelf -l haskell_hello_nix

Elf file type is EXEC (Executable file)
Entry point 0x405d40
There are 6 program headers, starting at offset 64

Program Headers:
  Type           Offset             VirtAddr           PhysAddr
                 FileSiz            MemSiz              Flags  Align
  LOAD           0x0000000000000000 0x0000000000400000 0x0000000000400000
                 0x0000000000188ba4 0x0000000000188ba4  R E    0x1000
  LOAD           0x0000000000188ec0 0x0000000000589ec0 0x0000000000589ec0
                 0x00000000000104c0 0x000000000001ac98  RW     0x1000
  NOTE           0x0000000000000190 0x0000000000400190 0x0000000000400190
                 0x0000000000000020 0x0000000000000020  R      0x4
  GNU_STACK      0x0000000000000000 0x0000000000000000 0x0000000000000000
                 0x0000000000000000 0x0000000000000000  RW     0x10
  TLS            0x0000000000188ec0 0x0000000000589ec0 0x0000000000589ec0
                 0x0000000000000070 0x00000000000000b8  R      0x8
  GNU_RELRO      0x0000000000188ec0 0x0000000000589ec0 0x0000000000589ec0
                 0x0000000000003140 0x0000000000003140  RW     0x20

 Section to Segment mapping:
  Segment Sections...
   00     .note.ABI-tag .rela.plt .init .plt .text __libc_thread_freeres_fn .fini .rodata .gcc_except_table .eh_frame
   01     .tdata .data.rel.ro.local .fini_array .init_array .data.rel.ro .preinit_array .got .got.plt .data .tm_clone_table __libc_IO_vtables __libc_atexit __libc_thread_subfreeres .bss __libc_freeres_ptrs
   02     .note.ABI-tag
   03
   04     .tdata .tbss
   05     .tdata .data.rel.ro.local .fini_array .init_array .data.rel.ro .preinit_array .got

good. tnx to all who was concerned. you save my a$$


问:
Pine script error when applying colors to volume bars
I'm trying to highlight volume bars that are 200% or greater than the previous bar but keep receiving the following error Error: Undeclared identifier volColor , however, it is declared so I don't understand the error.

```<code>study("200% Volume Highlight", shorttitle="Vol_200%")

v = volume
v0=volume[0]
v1=volume[1]

pct = (v0-v1)/v1*100

volColor = iff(pct>200, #DC143C)
plot(series=volume, style=histogram, color=volColor)
</code>```

答:
You did not have a color assigned for the case where pct>200 is false. na is used now but you can replace it with the color of your choice, of course.

Pls include the //@version= compiler directive with your snippets so we know which version of Pine you are using.

```<code>//@version=3
study("200% Volume Highlight", shorttitle="Vol_200%")

v = volume
v0=volume[0]
v1=volume[1]

pct = (v0-v1)/v1*100

volColor = iff(pct>200, #DC143C, na)
plot(series=volume, style=histogram, color=volColor)
</code>```

Body:
I'm trying to highlight volume bars that are 200% or greater than the previous bar but keep receiving the following error Error: Undeclared identifier volColor , however, it is declared so I don't understand the error.

study("200% Volume Highlight", shorttitle="Vol_200%")

v = volume
v0=volume[0]
v1=volume[1]

pct = (v0-v1)/v1*100

volColor = iff(pct>200, #DC143C)
plot(series=volume, style=histogram, color=volColor)

Body:
You did not have a color assigned for the case where pct>200 is false. na is used now but you can replace it with the color of your choice, of course.

Pls include the //@version= compiler directive with your snippets so we know which version of Pine you are using.

//@version=3
study("200% Volume Highlight", shorttitle="Vol_200%")

v = volume
v0=volume[0]
v1=volume[1]

pct = (v0-v1)/v1*100

volColor = iff(pct>200, #DC143C, na)
plot(series=volume, style=histogram, color=volColor)


问:
MS Access Form to Query with Date Ranges (And Even Without)
I'm new to Access and I'm building a database here at work to log all production that was done. I was able to make a query form with criteria between a date range, condition, part number and work order. Using a code in the expression builder, these are what is placed in the criterion:

Date range: Between [Forms]![Form Query]![BeginDate] And [Forms]![Form Query]![EndDate]

Part number: Like (IIf(IsNull([Forms]![Form Query]![Part Number]),"*",[Forms]![Form Query]![Part Number]))

Condition: Like (IIf(IsNull([Forms]![Form Query]![Condition]),"*",[Forms]![Form Query]![Condition]))

This is where even when part numbers and condition is empty, the query will display all records. My problem is the date range if I leave it empty (say, I simply wanted to query all of the records), it will return with zero value. I wanted it to make it simple for the user that if I leave the date range empty, it will still show all of the records. I had to temporarily put the date range as required to always return results.

Query form

Query Criteria

All input is appreciated! Thank you so much!

答:
Provide alternate value if date is not input:

Between Nz([Forms]![Form Query]![BeginDate], #1/1/1900#) And Nz([Forms]![Form Query]![EndDate], #12/31/2200#)

For text fields, assuming value is unique and is never part of a longer string, LIKE criteria can just concatenate wildcard:

LIKE [Forms]![Form Query]![Part Number]) & "*"


问:
Trying to draw a line on a JPanel but only draws a dot
I'm trying to make a program that will be able to draw lines on a white background on a JPanel. I have other classes to make selections for colors and width sizes, but for now I'm just trying to figure out how to draw lines. This is my "DrawingPanel" class which contains the code for the JPanel I will be drawing on. Right now what happens is if I click down my mouse and drag it across the screen a dot follows the mouse, but I want a line to be drawn by the mouse. Please help.</p>

```<code>import javax.swing.*;
import java.awt.event.*;
import java.awt.event.MouseMotionListener;
import java.awt.*;
import java.awt.Graphics;

public class DrawingPanel extends JPanel
{
    private Graphics g;
    private int x, y, startx, starty;
    public DrawingPanel ()
    {
        setBackground(Color.WHITE);
        addMouseMotionListener(new MouseMotionSensor ());
    }

    public void paintComponent (Graphics g)
    {
        //super.paintComponent(g);
        g.setColor(Color.BLACK);
        System.out.println(x + " " + y);
        g.drawLine(startx,starty,x,y);
    }

    public class MouseMotionSensor implements MouseMotionListener, MouseListener
    {
        public void mouseDragged(MouseEvent e)
        {
            x = e.getX();
            y = e.getY();
            repaint();
            startx = x;
            starty = y;
        }
        public void mousePressed(MouseEvent e)
        {
            startx = e.getX();
            starty = e.getY();
        }
        public void mouseMoved(MouseEvent e) {}
        public void mouseClicked(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}

    }
}
</code>```

答: Your problem may be that in mouseDragged you're changing both startx and starty, and x and y while the mouse is being dragged. While the mouse is being dragged, you want the start location (startx and starty) to be the same, and you want the end location (x and y) to change, so remove the those two lines in mouseDragged, so as to only change x and y.</p>

Body:
I'm trying to make a program that will be able to draw lines on a white background on a JPanel. I have other classes to make selections for colors and width sizes, but for now I'm just trying to figure out how to draw lines. This is my "DrawingPanel" class which contains the code for the JPanel I will be drawing on. Right now what happens is if I click down my mouse and drag it across the screen a dot follows the mouse, but I want a line to be drawn by the mouse. Please help.

import javax.swing.*;
import java.awt.event.*;
import java.awt.event.MouseMotionListener;
import java.awt.*;
import java.awt.Graphics;

public class DrawingPanel extends JPanel
{
    private Graphics g;
    private int x, y, startx, starty;
    public DrawingPanel ()
    {
        setBackground(Color.WHITE);
        addMouseMotionListener(new MouseMotionSensor ());
    }

    public void paintComponent (Graphics g)
    {
        //super.paintComponent(g);
        g.setColor(Color.BLACK);
        System.out.println(x + " " + y);
        g.drawLine(startx,starty,x,y);
    }

    public class MouseMotionSensor implements MouseMotionListener, MouseListener
    {
        public void mouseDragged(MouseEvent e)
        {
            x = e.getX();
            y = e.getY();
            repaint();
            startx = x;
            starty = y;
        }
        public void mousePressed(MouseEvent e)
        {
            startx = e.getX();
            starty = e.getY();
        }
        public void mouseMoved(MouseEvent e) {}
        public void mouseClicked(MouseEvent e) {}
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) {}
        public void mouseExited(MouseEvent e) {}

    }
}


问:
Unable to push to Heroku due to a package version being 0
I've created my heroku repository that uses python-3.6.9. On an attempt to push to the master branch, the push fails due to pkg-resources being version 0 in my requirements file.

error:

```<code>       ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12)) (from versions: none)
       ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12))
 !     Push rejected, failed to compile Python app.
 !     Push failed
</code>```

requirements (pip freeze > requirements.txt):

```<code>asgiref==3.2.7
astroid==2.4.1
beautifulsoup4==4.9.1
dj-database-url==0.5.0
Django==3.0.6
django-bootstrap4==1.1.1
django-heroku==0.3.1
gunicorn==20.0.4
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
pkg-resources==0.0.0
psycopg2==2.7.7
pylint==2.5.2
pytz==2020.1
six==1.14.0
soupsieve==2.0.1
sqlparse==0.3.1
toml==0.10.1
typed-ast==1.4.1
whitenoise==5.1.0
wrapt==1.12.1
</code>```

答: You are trying to install pkg-resources==0.0.0, change the version to a correct value. There is no 0.0.0 version

Body:
I've created my heroku repository that uses python-3.6.9. On an attempt to push to the master branch, the push fails due to pkg-resources being version 0 in my requirements file.

error:

       ERROR: Could not find a version that satisfies the requirement pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12)) (from versions: none)
       ERROR: No matching distribution found for pkg-resources==0.0.0 (from -r /tmp/build_X/requirements.txt (line 12))
 !     Push rejected, failed to compile Python app.
 !     Push failed

requirements (pip freeze > requirements.txt):

asgiref==3.2.7
astroid==2.4.1
beautifulsoup4==4.9.1
dj-database-url==0.5.0
Django==3.0.6
django-bootstrap4==1.1.1
django-heroku==0.3.1
gunicorn==20.0.4
isort==4.3.21
lazy-object-proxy==1.4.3
mccabe==0.6.1
pkg-resources==0.0.0
psycopg2==2.7.7
pylint==2.5.2
pytz==2020.1
six==1.14.0
soupsieve==2.0.1
sqlparse==0.3.1
toml==0.10.1
typed-ast==1.4.1
whitenoise==5.1.0
wrapt==1.12.1


问:
Where is Response.json() in Angular 8?
I use to do this in Angular 4/5:

import { Http, Headers } from "@angular/http"

public listTemplates(): Observable<EmailTemplate[]> {
    let url = `${this.apiUrl}/templates`
    this.http.get(url).map(
        response => this.parseTemplates(response.body)),
        error => new ErrorObservable(error)
    )
}

```

<p>Now, with Angular 8, I'm trying to use the <code>HttpClient</code> class:  </p>

<pre class="lang-ts prettyprint-override"><code>import { HttpClient, HttpResponse } from "@angular/common/http"
import { Observable } from "rxjs"
import { ErrorObservable } from "rxjs/observable/ErrorObservable";

public listTemplates(): Observable<EmailTemplate[]> {
    let url = `${this.apiUrl}/templates`
    return this.http.get(url)
        .pipe( // ??
        map(  //??
            response => this.parseTemplates(response.body)),  // ?? HttpResponse
            error => new ErrorObservable(error)
        )
    )
}
</code>```

map does not exist anymore

pipe, how to use it?

HttpResponse does not have a json method anymore

I think I should be able to use .get to obtain an any object that will be my JSON object (as .get documentation says), but how?

How can I use pipe or map (or both) to manage JSON object returned by the .get with a custom parsing and return a collection or an Observable of a collection?

[Solution]

import { HttpClient, HttpResponse } from "@angular/common/http"
import { Observable } from "rxjs"
import { ErrorObservable } from "rxjs/observable/ErrorObservable"
import { map } from 'rxjs/operators'

    public listTemplates(): Observable<EmailTemplate[]> {
        let url = `${this.apiUrl}/templates`

        return this.http.get(url).pipe(
            map(
                data => this.parseTemplates(data),
                error => new ErrorObservable(error)
            )
        )
    }
```

I still do not know how to get the HttpResponse for the cases where I need to check the HTTP status or some HTTP header. I understand that what get is returning is driven by the type returned by the function (because of the pipe call).

I tried to use get<HttpResponse<any>> but didn't worked.

答:
So , there is no response.json in Angular 9 i guess as i searched a lot for it.
But instead we can directly convert the response object to the desired type and use it, like in the example below using response object as an array to fetch the data in my array.</p>

```<code>   export class PostsComponent{
    posts : any[];
      constructor(http : HttpClient){
          http.get('https://jsonplaceholder.typicode.com/posts')
                  .subscribe((response:any[]) => {
                      this.posts=response;
                  });
      }
    }
</code>```

Title: Where is Response.json() in Angular 8?

Body:
I use to do this in Angular 4/5:

import { Http, Headers } from "@angular/http"

public listTemplates(): Observable<EmailTemplate[]> {
    let url = `${this.apiUrl}/templates`
    this.http.get(url).map(
        response => this.parseTemplates(response.body)),
        error => new ErrorObservable(error)
    )
}

Now, with Angular 8, I'm trying to use the HttpClient class:

import { HttpClient, HttpResponse } from "@angular/common/http"
import { Observable } from "rxjs"
import { ErrorObservable } from "rxjs/observable/ErrorObservable";

public listTemplates(): Observable<EmailTemplate[]> {
    let url = `${this.apiUrl}/templates`
    return this.http.get(url)
        .pipe( // ??
        map(  //??
            response => this.parseTemplates(response.body)),  // ?? HttpResponse
            error => new ErrorObservable(error)
        )
    )
}

map does not exist anymore

pipe, how to use it?

HttpResponse does not have a json method anymore

I think I should be able to use .get to obtain an any object that will be my JSON object (as .get documentation says), but how?

How can I use pipe or map (or both) to manage JSON object returned by the .get with a custom parsing and return a collection or an Observable of a collection?

[Solution]

import { HttpClient, HttpResponse } from "@angular/common/http"
import { Observable } from "rxjs"
import { ErrorObservable } from "rxjs/observable/ErrorObservable"
import { map } from 'rxjs/operators'

    public listTemplates(): Observable<EmailTemplate[]> {
        let url = `${this.apiUrl}/templates`

        return this.http.get(url).pipe(
            map(
                data => this.parseTemplates(data),
                error => new ErrorObservable(error)
            )
        )
    }

I still do not know how to get the HttpResponse for the cases where I need to check the HTTP status or some HTTP header. I understand that what get is returning is driven by the type returned by the function (because of the pipe call).

I tried to use get<HttpResponse<any>> but didn't worked.

Body:
So , there is no response.json in Angular 9 i guess as i searched a lot for it.
But instead we can directly convert the response object to the desired type and use it, like in the example below using response object as an array to fetch the data in my array.

   export class PostsComponent{
    posts : any[];
      constructor(http : HttpClient){
          http.get('https://jsonplaceholder.typicode.com/posts')
                  .subscribe((response:any[]) => {
                      this.posts=response;
                  });
      }
    }


问:
Obtain email address from GmailService using C# client API
Gmail API to get profile info

Base on this link, it is possible to get the email address from the authenticated profile.
Unfortunately I wasn't able to find how to get this in C# API client.

I have tried this: GmailService.Users.GetProfile("me"), but this does not contain the email address.

I hope someone know how to do this with C# API client.

Thank you.

答:
You could use a simple WebRequest and parse the JSON to get the emailAddress field.

You could build a Response model that would look something like:

```<code>public class APIResponse
{
    public string emailAddress {get; set;}
    public int messagesTotal {get; set;}
    public int threadsTotal {get; set;}
    public int id {get; set;}
}
</code>```

Then you will want to make a GET Request to the GoogleAPI url and deserialize the JSON response from your API Response class.

```<code>WebRequest request = WebRequest.Create("https://www.googleapis.com/gmail/v1/users/me/profile");
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            request.Timeout = 50000;
            //Get response from server
            using (StreamReader stream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
            {
                sResponse = stream.ReadToEnd();
                resp = new JavaScriptSerializer().Deserialize<APIResponse>(sResponse);
            }
</code>```

Then you could get your emailAddress back by simply calling resp.emailAddress.
I have not tested this code for the GoogleAPI but this should get you going in the right direction.

Body:
You could use a simple WebRequest and parse the JSON to get the emailAddress field.

You could build a Response model that would look something like:

public class APIResponse
{
    public string emailAddress {get; set;}
    public int messagesTotal {get; set;}
    public int threadsTotal {get; set;}
    public int id {get; set;}
}

Then you will want to make a GET Request to the GoogleAPI url and deserialize the JSON response from your API Response class.

WebRequest request = WebRequest.Create("https://www.googleapis.com/gmail/v1/users/me/profile");
            request.Method = "GET";
            request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
            request.Timeout = 50000;
            //Get response from server
            using (StreamReader stream = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.UTF8))
            {
                sResponse = stream.ReadToEnd();
                resp = new JavaScriptSerializer().Deserialize<APIResponse>(sResponse);
            }

Then you could get your emailAddress back by simply calling resp.emailAddress.
I have not tested this code for the GoogleAPI but this should get you going in the right direction.


问:
What is an easy way to put an element in the middle of a PHP array?
Say you have a 10 element indexed array and you want to place an element somewhere in the middle (say index 3). Then I want to have the rest of the array shift and thus be 11 elements long. Is there an easy way to do this?

I am surprised there is no put() function or something.

I know it would be easy enough to do this with a combination of array_splice and array_merge but I was just wondering if there an easier way.

答:
array_splice() does this</p>

```<code>$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green", "blue", "purple", "yellow");
</code>```

OwnerDisplayName: Andrew

LastEditorDisplayName: Andrew

Body:
array_splice() does this

$input = array("red", "green", "blue", "yellow");
array_splice($input, 3, 0, "purple");
// $input is now array("red", "green", "blue", "purple", "yellow");

OwnerDisplayName: Scott Evernden

LastEditorDisplayName: Scott Evernden


问:
How to get document id and document data?
So i have a list of some documents is my app and when i click on avatar it will open modal page. At this modal page it will shown information by doc that i clicked. so how can i do this? I use Cloud Firestore.

How i get list from collection and display it on the screen:

```<code>useEffect(() => {
    const fetchRequest = async () => {
      const requestCollection = await db.collection("request").get();
      setRequest(
        requestCollection.docs.map((doc) => {
          return doc.data();
        })
      );
    };
    fetchRequest();
  }, []);

  return (
    <Panel id={id}>
      <PanelHeader left={<PanelHeaderBack onClick={go} data-to="home" />}>
        Обычные скины
      </PanelHeader>
      <Group header={<Header mode="secondary">Новые скины</Header>}></Group>
      {request.map((playerID) => {
        return (
          <Cell
          onClick={(e) => {openModal}
          key={playerID.player_id}
            style={{ marginBottom: 10 }}
            expandable
            indicator={
              <Counter size="s" mode="prominent">
                Новый скин
              </Counter>
            }
            before={<Avatar size={64} src={playerID.image} />}
          >Автор: {playerID.nickname}</Cell>
        );
      })}
    </Panel>
  );
</code>```

Modal Page:

```<code> const modal = (
      <ModalRoot onClose={() => { setActiveModal(null)
      }}
       activeModal={activeModal}>
        <ModalPage id="skin_info"
        header={
          <ModalPageHeader
            right={<PanelHeaderButton onClick = {() => { setActiveModal(null)
            }} ><Icon24DoneOutline/></PanelHeaderButton>}
          >
            Карточка скина
          </ModalPageHeader>
        }>
           <Group title="MainInfo" header={<Header mode="secondary">Основная информация</Header>}>
           <Banner
           before={<Avatar size={48} />}
           header="Никнейм игрока:"
           subheader="ID Аккаунта:"
         />
          <SimpleCell>
          <InfoRow header="Комментарий игрока">
            Здесь расположен комментарий игрока.
          </InfoRow>
          </SimpleCell>
          <SimpleCell>
          <InfoRow header="Комментарий администратора">
            Здесь расположен комментарий администратора.
          </InfoRow>
          </SimpleCell>
          </Group>
          <Group title="Gallery" header={<Header mode="secondary">Галерея</Header>}>
          <Gallery
                slideWidth="90%"
                style={{ height: 150 }}
                bullets="dark"
              >
                <div style={{ backgroundColor: 'var(--destructive)' }} />
                <div style={{ backgroundColor: 'var(--button_commerce_background)' }} />
                <div style={{ backgroundColor: 'var(--accent)' }} />
              </Gallery>
              <Separator/>
          </Group>
        </ModalPage>
      </ModalRoot>
      )
</code>```

It just open modal page. By this I need to get id and all doc data that i clicked

答:
```<code>const Row = ({setActiveItem, playerID}) => (
    <Cell onClick={e => setActiveItem(playerID)}>
        Автор: {playerID.nickname}
    </Cell>
);
const List = () => {
    const [activeItem, setActiveItem] = useState(null);
    {request.map((playerID) => (
        <Row
            key={playerID.player_id}
            setActiveItem={setActiveItem}
            playerID={playerID}
        />
    )}
    <Modal activeItem={activeItem} />
}
</code>```

Body:
So i have a list of some documents is my app and when i click on avatar it will open modal page. At this modal page it will shown information by doc that i clicked. so how can i do this? I use Cloud Firestore.

How i get list from collection and display it on the screen:

useEffect(() => {
    const fetchRequest = async () => {
      const requestCollection = await db.collection("request").get();
      setRequest(
        requestCollection.docs.map((doc) => {
          return doc.data();
        })
      );
    };
    fetchRequest();
  }, []);

  return (
    <Panel id={id}>
      <PanelHeader left={<PanelHeaderBack onClick={go} data-to="home" />}>
        Обычные скины
      </PanelHeader>
      <Group header={Новые скины}></Group>
      {request.map((playerID) => {
        return (
          <Cell
          onClick={(e) => {openModal}
          key={playerID.player_id}
            style={{ marginBottom: 10 }}
            expandable
            indicator={
              <Counter size="s" mode="prominent">
                Новый скин
              </Counter>
            }
            before={<Avatar size={64} src={playerID.image} />}
          >Автор: {playerID.nickname}</Cell>
        );
      })}
    </Panel>
  );

Modal Page:

 const modal = (
      <ModalRoot onClose={() => { setActiveModal(null)
      }}
       activeModal={activeModal}>
        <ModalPage id="skin_info"
        header={
          <ModalPageHeader
            right={<PanelHeaderButton onClick = {() => { setActiveModal(null)
            }} ><Icon24DoneOutline/></PanelHeaderButton>}
          >
            Карточка скина
          </ModalPageHeader>
        }>
           <Group title="MainInfo" header={Основная информация}>
           <Banner
           before={<Avatar size={48} />}
           header="Никнейм игрока:"
           subheader="ID Аккаунта:"
         />
          <SimpleCell>
          <InfoRow header="Комментарий игрока">
            Здесь расположен комментарий игрока.
          </InfoRow>
          </SimpleCell>
          <SimpleCell>
          <InfoRow header="Комментарий администратора">
            Здесь расположен комментарий администратора.
          </InfoRow>
          </SimpleCell>
          </Group>
          <Group title="Gallery" header={Галерея}>
          <Gallery
                slideWidth="90%"
                style={{ height: 150 }}
                bullets="dark"
              >

              </Gallery>
              <Separator/>
          </Group>
        </ModalPage>
      </ModalRoot>
      )

It just open modal page. By this I need to get id and all doc data that i clicked


问:
How to define a type alias using a variable name
I need to deﬁne a type alias, and I know that a variable is of the type I need an alias for. The explicit name for the type is not available. What can I do?</p>

答:
You cannot have two distinct types with the same name.

You can have types of the same name in different namespaces though.


问:
Alter or delete user data using Asyncstorage when Uninstall React Native App
How to alter or delete specific application data using Asyncstorage when uninstall or update app

答: App locally saved data might be backed up on Google Drive on the latest versions of Android. You can disable it either by setting <android:allowBackup="false"> (true is the default behavior) or by disabling auto backup in your phone's settings.


问:
How to make vue js website printer accessible?
I have a website build with vue js and I used a lot of scooped styling for different components.

In many websites separate css files are provides with media="print" to facilitate print version.

How do I achieve this in my vue is app/website?

答:
You could add a link tag inside your HTML which links to the print stylesheet, you can then let your browser know through the media attribute that it serves for printing only:

<link rel="stylesheet" href="print.css" media="print">

https://www.w3schools.com/tags/att_link_media.asp


问:
jQuery - disable select options
I need some help with jquery condition. I've been searching and testing for hours, any help would be great !!!

$(document).ready(function() {
  if ($(".select_red option:selected").attr('disabled', 'disabled').hasClass("red")) {
    $(".select_red").addClass("redtext");
  }
})

$(document).on("change", ".select_red", function() {
  if ($(this).find("option:selected").hasClass("red")) {
    $(this).addClass("redtext");
  } else {
    $(this).removeClass("redtext");
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.redtext,
.select_red .red {
  color: red
}</code>```

Choose a option:
<select class="select_red" disabled>
  <option>--Select--</option>
  <option class="red">one</option>
  <option>two</option>
  <option class="red" selected>three</option>
  <option>four</option>
</select>```

I'm a beginner in jquery, and I don't know is this code is written correctly. I have added few things
The problem is:
Based on condition the enabled select field will be disabled after selecting the option which has class "red". But after the select field is disabled the color is not changing to red. Thanks for reading

答:
You must use your full Jquery code inside document ready function</p>

```<code>$(function(){
   if($(".select_red option:selected").attr('disabled','disabled').hasClass("red")){
    $(".select_red").addClass("redtext");
      }
      $(document).on("change", ".select_red", function() {
      if($(this).find("option:selected").hasClass("red")){
       $(this).addClass("redtext");
        }else {
        $(this).removeClass("redtext");
       }
       })
})
</code>```

Title: jQuery - disable select options

Body:
I need some help with jquery condition. I've been searching and testing for hours, any help would be great !!!

$(document).ready(function() {
  if ($(".select_red option:selected").attr('disabled', 'disabled').hasClass("red")) {
    $(".select_red").addClass("redtext");
  }
})

$(document).on("change", ".select_red", function() {
  if ($(this).find("option:selected").hasClass("red")) {
    $(this).addClass("redtext");
  } else {
    $(this).removeClass("redtext");
  }
})

.redtext,
.select_red .red {
  color: red
}

Choose a option:
<select class="select_red" disabled>
  <option>--Select--</option>
  <option class="red">one</option>
  <option>two</option>
  <option class="red" selected>three</option>
  <option>four</option>
</select>

I'm a beginner in jquery, and I don't know is this code is written correctly. I have added few things
The problem is:
Based on condition the enabled select field will be disabled after selecting the option which has class "red". But after the select field is disabled the color is not changing to red. Thanks for reading

Body:
You must use your full Jquery code inside document ready function

$(function(){
   if($(".select_red option:selected").attr('disabled','disabled').hasClass("red")){
    $(".select_red").addClass("redtext");
      }
      $(document).on("change", ".select_red", function() {
      if($(this).find("option:selected").hasClass("red")){
       $(this).addClass("redtext");
        }else {
        $(this).removeClass("redtext");
       }
       })
})


问:
How to add a 3rd party local maven repository to android project
I have been provided an SDK to work on, which contains a maven-local-metadata file, an .aar file, .pom file and .jar file. How do I add this to my project. I tried pasting it to the local .m2 file but it didn't work (is there any specific way)and also adding as a new .aar/.jar module in the file option didn't work.
any help would be greatly appreciated.

答:
Just add the files in the local .m2 repository in the correct structure and youre good. no need to add in the libs folder.

Note - If working with .aar files just as a modules


问:
Why does linking against static runtime libraries in Visual C++ 2008 still requires MSVCR71.dll at runtime?
I'm building a dll statically linked against the c runtime libraries. Why then does it require MSVCR71.dll at runtime?

答:
You may be linking against the LIB import library for the DLL - check you are using linker option /MT and not /MD

http://msdn.microsoft.com/en-us/library/abx4dbyh(v=VS.90).aspx

MSVCR71.dll doesn't look like the correct version of the runtime for VS2008. Are you linking against any other third party libraries that require the older runtime?


问:
I want to make part of our website content in virtual reality
I want to make part of our website content in virtual reality.
For example, small games
I can't figure it out yet. It's better to do it as an application for different headsets stores.
But it's much easier to add the VR button to the site itself.
How will this industry develop? Are there developers of WebVR sites? Will all devices open VR versions of sites?

Thank you .

答:
h1{
 font-family: Arial;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
<h1>Hello World</h1>
<a-scene>
  <a-assets>
    <img id="groundTexture" src="https://cdn.aframe.io/a-painter/images/floor.jpg">
  </a-assets>

  <a-cylinder id="ground" src="#groundTexture" radius="32" height="0.1"></a-cylinder>
</a-scene></code>```

Body:
h1{
 font-family: Arial;
}

<script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
<h1>Hello World</h1>
<a-scene>
  <a-assets>
    <img id="groundTexture" src="https://cdn.aframe.io/a-painter/images/floor.jpg">
  </a-assets>

  <a-cylinder id="ground" src="#groundTexture" radius="32" height="0.1"></a-cylinder>
</a-scene>


问:
String manipulation within a column (pandas): split, replace, join
I'd like to create a new column based on the following conditions:

if the row contains dogs/dog/chien/chiens, then add -00

if the row contains cats/cat/chat/chats, then add 00-

A sample of data is as follows:

```<code>Animal

22 dogs
1 dog
1 cat
3 dogs
32 chats
</code>```

and so far.

I'd like as output a column with only numbers (numerical):

```<code>Animal        New column

22 dogs       22-00
1 dog         1-00
1 cat         00-1
3 dogs        3-00
32 chats      00-32
</code>```

I think I should use an if condition to check the words, then .split and .join . It's about string manipulation but I'm having trouble breaking down this problem.

答:
You could do this, first extract the number, then use np.where to conditionally add characters to the string:

```<code>df['New Col'] = df['Animal'].str.extract(r'([0-9]*)')
df['New Col'] = np.where(df['Animal'].str.contains('dogs|dog|chiens|chien'), df['New Col']+'-00', df['New Col'])
df['New Col'] = np.where(df['Animal'].str.contains('cats|cat|chat|chats'), '00-'+df['New Col'], df['New Col'])
print(df)

     Animal New Col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32
</code>```

Body:
I'd like to create a new column based on the following conditions:

if the row contains dogs/dog/chien/chiens, then add -00

if the row contains cats/cat/chat/chats, then add 00-

A sample of data is as follows:

Animal

22 dogs
1 dog
1 cat
3 dogs
32 chats

and so far.

I'd like as output a column with only numbers (numerical):

Animal        New column

22 dogs       22-00
1 dog         1-00
1 cat         00-1
3 dogs        3-00
32 chats      00-32

I think I should use an if condition to check the words, then .split and .join . It's about string manipulation but I'm having trouble breaking down this problem.

Body:
You could do this, first extract the number, then use np.where to conditionally add characters to the string:

df['New Col'] = df['Animal'].str.extract(r'([0-9]*)')
df['New Col'] = np.where(df['Animal'].str.contains('dogs|dog|chiens|chien'), df['New Col']+'-00', df['New Col'])
df['New Col'] = np.where(df['Animal'].str.contains('cats|cat|chat|chats'), '00-'+df['New Col'], df['New Col'])
print(df)

     Animal New Col
0   22 dogs   22-00
1     1 dog    1-00
2     1 cat    00-1
3    3 dogs    3-00
4  32 chats   00-32


答:
```<code>PRES = set(("cats", "cat", "chat", "chats"))
POSTS = set(("dogs", "dog", "chien", "chiens"))

def fun(words):
    # words will come as e.g. "22 dogs"
    num, ani = words.split()
    if ani in PRES:
        return "00-" + num
    elif ani in POSTS:
        return num + "-00"
    else:
        # you might want to handle this..
        return "unexpected"

df["New Column"] = df["Animal"].apply(fun)
</code>```

where df is your dataframe. For a fast lookup, we turn the condition lists into sets. Then we apply a function to values of the Animal column of df and act accordingly.

Title: String manipulation within a column (pandas): split, replace, join

Body:
PRES = set(("cats", "cat", "chat", "chats"))
POSTS = set(("dogs", "dog", "chien", "chiens"))

def fun(words):
    # words will come as e.g. "22 dogs"
    num, ani = words.split()
    if ani in PRES:
        return "00-" + num
    elif ani in POSTS:
        return num + "-00"
    else:
        # you might want to handle this..
        return "unexpected"

df["New Column"] = df["Animal"].apply(fun)

where df is your dataframe. For a fast lookup, we turn the condition lists into sets. Then we apply a function to values of the Animal column of df and act accordingly.