问:
What constitutes 'real time'
I am having trouble deciding on whether to classify my application as 'real time' or 'near real time', or perhaps even something else.

The software receives data immediately as it is generated from the source, then based on certain rules, raises an alert when certain conditions are met. It takes the approach of checking the last 30 seconds of data every 30 seconds to see whether the criteria for a rule has been met.

Is that real time? What are the thresholds for the definitions of real time vs. near real-time?

EDIT

I think this is a duplicate of Define realtime on the web for business.

Please decide if the above thread is insufficient to answer your question.

答: Definition of 'hard' real-time from my controls friends - Late information is wrong information.  If it needs to be there every 1s and it gets there in 1.1s, it's useless for calculations.  </p>

OwnerDisplayName: Steve M

Title: What constitutes 'real time'

LastEditorDisplayName: Jon Limjap

OwnerDisplayName: Stephen Friederichs


来源: stackexchange

问:
Which curve is SHA1withECDSA using?
I am using SHA1withECDSA to verify signed messages in my java application. Now I want to create a second application in another programming language (node/js) which creates those signed messages.

However I could not find any api which has "SHA1withECDSA". All of them only support ECDSA with a selected curve. So my question: Which ec curve is java using?

Keyfactory:
final KeyFactory keyFactory = KeyFactory.getInstance("EC");

Signature:
final Signature dsa = Signature.getInstance("SHA1withECDSA");

答:
The {hash}withECDSA algorithms in Java support any curve that can be expressed in an ECPrivateKey object passed to Signature.initSign(key) or (your case) an ECPublicKey object passed to Signature.initVerify(key) which for the standard SunEC provider are any curve expressed in X9.62 (Weierstrass) form. This is basically everything used nowadays except Bernstein et al's {Curve,X,Ed}{25519,448} (EdDSA is an elliptic-curve signature algorithm but not the algorithm named ECDSA).

The standard X9/NIST and TLS curves are predefined, although (edit) accessing them other than for key generation is a bit clumsy; see How does one convert a public EC code point and curve name into a PublicKey? .

Normally the keypair should be generated by the signer, and (only) the publickey distributed to the verifier(s) either in advance of or along with the signature(s) and signed data; often this is done in the form of a certificate, which avoids manual effort and manual mistakes that create vulnerabilities. Java directly supports X.509 certificates, and the publickey format used by them (SubjectPublicKeyInfo aka SPKI); see the javadoc for java.security.spec.X509EncodedKeySpec and java.security.Key. For EC, the SPKI includes the curve identification, but unfortunately the Java API provides no convenient way to get it back out.

If you have an X.509 certificate or just the X.509 SPKI for the publickey in a file, in either DER or PEM format, and have OpenSSL, it can decode and display this info:

```<code> openssl x509 -in certfile -inform {der|pem} -text
 openssl pkey -in spkifile -inform {der|pem} -pubin -text # 1.0.0 up
 openssl ec -in spkifile -inform {der|pem} -pubin -text # 0.9.x
 # look at the line labelled ASN1 OID:
</code>```

ContentLicense: CC BY-SA 4.0

Title: Which curve is SHA1withECDSA using?

Body:
The {hash}withECDSA algorithms in Java support any curve that can be expressed in an ECPrivateKey object passed to Signature.initSign(key) or (your case) an ECPublicKey object passed to Signature.initVerify(key) which for the standard SunEC provider are any curve expressed in X9.62 (Weierstrass) form. This is basically everything used nowadays except Bernstein et al's {Curve,X,Ed}{25519,448} (EdDSA is an elliptic-curve signature algorithm but not the algorithm named ECDSA).

The standard X9/NIST and TLS curves are predefined, although (edit) accessing them other than for key generation is a bit clumsy; see How does one convert a public EC code point and curve name into a PublicKey? .

Normally the keypair should be generated by the signer, and (only) the publickey distributed to the verifier(s) either in advance of or along with the signature(s) and signed data; often this is done in the form of a certificate, which avoids manual effort and manual mistakes that create vulnerabilities. Java directly supports X.509 certificates, and the publickey format used by them (SubjectPublicKeyInfo aka SPKI); see the javadoc for java.security.spec.X509EncodedKeySpec and java.security.Key. For EC, the SPKI includes the curve identification, but unfortunately the Java API provides no convenient way to get it back out.

If you have an X.509 certificate or just the X.509 SPKI for the publickey in a file, in either DER or PEM format, and have OpenSSL, it can decode and display this info:

 openssl x509 -in certfile -inform {der|pem} -text
 openssl pkey -in spkifile -inform {der|pem} -pubin -text # 1.0.0 up
 openssl ec -in spkifile -inform {der|pem} -pubin -text # 0.9.x
 # look at the line labelled ASN1 OID:


问:
How to display content under ttk treeview sun tree
I have these few lines of code where i want my gender content to display under treeview sub tree on the same row as the name there but it displays
on new rows after the subtree.

Want it to display as the example below:

FRED                        MALE

MAVIS                       FEMALE

FRED                        OTHER

on same row under the subtree but not able to achive that.

Your suggestions are welcome to achieve that.

```<code>from tkinter import ttk
import tkinter as tk

root = tk.Tk()
root.geometry("1200x680+50+20")

tree = ttk.Treeview(root)
    ############
tree.config(columns=("col1","col2","col3"))

#SUb treeview
style = ttk.Style(root)
style.configure("Treeview", rowheight=30)
tree.configure(style="Treeview")

tree.heading("#1", text="DOB")
tree.heading("#2", text="SCHOOL")
tree.heading("#3", text="GENDER")

tree.insert("", "0", "item1", text="Names",)
tree.insert("", "1", "item2", text="Names")

tree.set("item1", "#1", ["2019-05-25"])
tree.set("item1", "#2", ["HARVARD"])

#sub tree using item attribute to achieve that
tree.insert("item1", "1", text="FRED")
tree.insert("item1", "1", text="MAVIS")
tree.insert("item1", "1", text="BRIGHT")

tree.insert("", tk.END, values=("", "", "MALE"))
tree.insert("", tk.END, values=("", "", "OTHER"))
tree.insert("", tk.END, values=("", "", "FEMALE"))

tree.pack(fill=tk.BOTH, expand=True)

root.mainloop()
</code>```

答:
To achieve what you want, you can replace this:

```<code>tree.set("item1", "#1", ["2019-05-25"])
tree.set("item1", "#2", ["HARVARD"])

#sub tree using item attribute to achieve that
tree.insert("item1", "1", text="FRED")
tree.insert("item1", "1", text="MAVIS")
tree.insert("item1", "1", text="BRIGHT")

tree.insert("", tk.END, values=("", "", "MALE"))
tree.insert("", tk.END, values=("", "", "OTHER"))
tree.insert("", tk.END, values=("", "", "FEMALE"))
</code>```

with this:

```<code>tree.insert("item1", "end", text="FRED", values=("2019-05-25", "HARVARD", "MALE"))
tree.insert("item1", "end", text="MAVIS", values=("2019-05-25", "HARVARD", "OTHER"))
tree.insert("item1", "end", text="BRIGHT", values=("2019-05-25", "HARVARD", "FEMALE"))
</code>```

Body:
I have these few lines of code where i want my gender content to display under treeview sub tree on the same row as the name there but it displays
on new rows after the subtree.

Want it to display as the example below:

FRED                        MALE

MAVIS                       FEMALE

FRED                        OTHER

on same row under the subtree but not able to achive that.

Your suggestions are welcome to achieve that.

from tkinter import ttk
import tkinter as tk

root = tk.Tk()
root.geometry("1200x680+50+20")

tree = ttk.Treeview(root)
    ############
tree.config(columns=("col1","col2","col3"))

#SUb treeview
style = ttk.Style(root)
style.configure("Treeview", rowheight=30)
tree.configure(style="Treeview")

tree.heading("#1", text="DOB")
tree.heading("#2", text="SCHOOL")
tree.heading("#3", text="GENDER")

tree.insert("", "0", "item1", text="Names",)
tree.insert("", "1", "item2", text="Names")

tree.set("item1", "#1", ["2019-05-25"])
tree.set("item1", "#2", ["HARVARD"])

#sub tree using item attribute to achieve that
tree.insert("item1", "1", text="FRED")
tree.insert("item1", "1", text="MAVIS")
tree.insert("item1", "1", text="BRIGHT")

tree.insert("", tk.END, values=("", "", "MALE"))
tree.insert("", tk.END, values=("", "", "OTHER"))
tree.insert("", tk.END, values=("", "", "FEMALE"))

tree.pack(fill=tk.BOTH, expand=True)

root.mainloop()

Body:
To achieve what you want, you can replace this:

tree.set("item1", "#1", ["2019-05-25"])
tree.set("item1", "#2", ["HARVARD"])

#sub tree using item attribute to achieve that
tree.insert("item1", "1", text="FRED")
tree.insert("item1", "1", text="MAVIS")
tree.insert("item1", "1", text="BRIGHT")

tree.insert("", tk.END, values=("", "", "MALE"))
tree.insert("", tk.END, values=("", "", "OTHER"))
tree.insert("", tk.END, values=("", "", "FEMALE"))

with this:

tree.insert("item1", "end", text="FRED", values=("2019-05-25", "HARVARD", "MALE"))
tree.insert("item1", "end", text="MAVIS", values=("2019-05-25", "HARVARD", "OTHER"))
tree.insert("item1", "end", text="BRIGHT", values=("2019-05-25", "HARVARD", "FEMALE"))


问:
How to get rid from bad bind operator, the problems with if condition?
I need to prevent the captain and first officer if the if-condition is true

```<code>CREATE OR REPLACE TRIGGER noPilot
BEFORE INSERT OR UPDATE ON flight
FOR EACH ROW

DECLARE
    captainS varchar2(5);
    firstOfficerS varchar2(5);

BEGIN

Select F.captainStaffID
into captainS
from Flight.F
where F.StaffID = captainS;

select F.firstOfficerStaffID
into firstOfficerS
from Flight F
where F.StaffID = firstOfficerS;

If(UPPER(:old.pilotYesNo = 'N')) THEN
    RETURN 'No pilot to launch';

elsif(:old.qualification = 'ATPL') THEN
    RETURN 'No qualifications';

    ENDIF;
END nopilot;
/

17/10    PLS-00049: bad bind variable 'OLD.PILOTYESNO'
20/7     PLS-00049: bad bind variable 'OLD.QUALIFICATION'
24/5     PLS-00103: Encountered the symbol "NOPILOT" when expecting one of
     the following:
     if
</code>```

the tables for the above is as follows;

FLIGHT(flightID, estDepartureDateTime, actDepartDateTime, actArriveDateTime, avgSpeed,avgHeight, estDuration, estFuel, haulType, captainStaffID, firstOfficerStaffID, routeID, aircraftID)

STAFF(staffID, name, address, email, phone, passportNum, pilotYesNo, prevHrsPilotExp,attendantYesNo, memberID)

答:
It appears that there are no PILOTYESNO or QUALIFICATION fields on the FLIGHT table. You might want to edit your question and include the definitions of the FLIGHT table so that people can understand it better.

Further, triggers do not return values, so the RETURN statements are invalid in a trigger. Perhaps you should raise an exception here.

Also, when this trigger executes you're probably going to get a MUTATING TABLE exception at run time because you're defining a BEFORE INSERT OR UPDATE ROW trigger in which you're selecting data in the body of the trigger from the same table (FLIGHT) that the trigger is defined on. This is not allowed in Oracle. Perhaps you should reference values in the :NEW pseudo-row.

A better solution would be to define a procedure (perhaps named INSERT_OR_UPDATE_FLIGHT) which performs all necessary checks, etc, prior to trying to do the appropriate INSERT or UPDATE. Putting business logic in triggers is s͟i̶m҉ply͞ Eͪ̂͛ͩ͂̽̈́V̩̼ͭ͊̐ͭ̀I̦͇̤͕̗̩̪͑Ĺ̨̩̱̘͇̰̲̀͌͆̄. :-)

Best of luck.

EDIT

As I noted earlier, according to the table definitions added to the question there are no PILOTYESNO or QUALIFICATION fields on the FLIGHT table. PILOTYESNO is a field on the STAFF table, not on FLIGHT. There is no QUALIFICATION field on either the FLIGHT or STAFF tables, so I don't know what to recommend there. Are there other tables in play here which haven't been mentioned yet?

Regardless, I think you can get closer to what you want with:

```<code>CREATE OR REPLACE TRIGGER FLIGHT_BIU
  BEFORE INSERT OR UPDATE ON FLIGHT
  FOR EACH ROW
DECLARE
  strMAX_PILOTYESNO  STAFF.PILOTYESNO%TYPE;
BEGIN
  SELECT MAX(UPPER(PILOTYESNO))
    INTO strMAX_PILOTYESNO
    FROM STAFF
    WHERE STAFFID IN (:NEW.CAPTAINSTAFFID, :NEW.FIRSTOFFICERSTAFFID);

  IF strMAX_PILOTYESNO  = 'N' THEN
    RAISE_APPLICATION_ERROR(-20000, 'No pilot assigned to the flight');
  END IF;

  -- Add code here to handle QUALIFICATION, wherever that may be found
END FLIGHT_BIU;
/
</code>```

Best of luck.

Body:
I need to prevent the captain and first officer if the if-condition is true

CREATE OR REPLACE TRIGGER noPilot
BEFORE INSERT OR UPDATE ON flight
FOR EACH ROW

DECLARE
    captainS varchar2(5);
    firstOfficerS varchar2(5);

BEGIN

Select F.captainStaffID
into captainS
from Flight.F
where F.StaffID = captainS;

select F.firstOfficerStaffID
into firstOfficerS
from Flight F
where F.StaffID = firstOfficerS;

If(UPPER(:old.pilotYesNo = 'N')) THEN
    RETURN 'No pilot to launch';

elsif(:old.qualification = 'ATPL') THEN
    RETURN 'No qualifications';

    ENDIF;
END nopilot;
/

17/10    PLS-00049: bad bind variable 'OLD.PILOTYESNO'
20/7     PLS-00049: bad bind variable 'OLD.QUALIFICATION'
24/5     PLS-00103: Encountered the symbol "NOPILOT" when expecting one of
     the following:
     if

the tables for the above is as follows;

FLIGHT(flightID, estDepartureDateTime, actDepartDateTime, actArriveDateTime, avgSpeed,avgHeight, estDuration, estFuel, haulType, captainStaffID, firstOfficerStaffID, routeID, aircraftID)

STAFF(staffID, name, address, email, phone, passportNum, pilotYesNo, prevHrsPilotExp,attendantYesNo, memberID)

Body:
It appears that there are no PILOTYESNO or QUALIFICATION fields on the FLIGHT table. You might want to edit your question and include the definitions of the FLIGHT table so that people can understand it better.

Further, triggers do not return values, so the RETURN statements are invalid in a trigger. Perhaps you should raise an exception here.

Also, when this trigger executes you're probably going to get a MUTATING TABLE exception at run time because you're defining a BEFORE INSERT OR UPDATE ROW trigger in which you're selecting data in the body of the trigger from the same table (FLIGHT) that the trigger is defined on. This is not allowed in Oracle. Perhaps you should reference values in the :NEW pseudo-row.

A better solution would be to define a procedure (perhaps named INSERT_OR_UPDATE_FLIGHT) which performs all necessary checks, etc, prior to trying to do the appropriate INSERT or UPDATE. Putting business logic in triggers is s͟i̶m҉ply͞ Eͪ̂͛ͩ͂̽̈́V̩̼ͭ͊̐ͭ̀I̦͇̤͕̗̩̪͑Ĺ̨̩̱̘͇̰̲̀͌͆̄. :-)

Best of luck.

EDIT

As I noted earlier, according to the table definitions added to the question there are no PILOTYESNO or QUALIFICATION fields on the FLIGHT table. PILOTYESNO is a field on the STAFF table, not on FLIGHT. There is no QUALIFICATION field on either the FLIGHT or STAFF tables, so I don't know what to recommend there. Are there other tables in play here which haven't been mentioned yet?

Regardless, I think you can get closer to what you want with:

CREATE OR REPLACE TRIGGER FLIGHT_BIU
  BEFORE INSERT OR UPDATE ON FLIGHT
  FOR EACH ROW
DECLARE
  strMAX_PILOTYESNO  STAFF.PILOTYESNO%TYPE;
BEGIN
  SELECT MAX(UPPER(PILOTYESNO))
    INTO strMAX_PILOTYESNO
    FROM STAFF
    WHERE STAFFID IN (:NEW.CAPTAINSTAFFID, :NEW.FIRSTOFFICERSTAFFID);

  IF strMAX_PILOTYESNO  = 'N' THEN
    RAISE_APPLICATION_ERROR(-20000, 'No pilot assigned to the flight');
  END IF;

  -- Add code here to handle QUALIFICATION, wherever that may be found
END FLIGHT_BIU;
/

Best of luck.


问:
How to redirect A's stdout to B's stdin and B's stdout to A's stdin?
Now I have programs A and B. I want to redirect A's stdout to B's stdin, and B's stdout to A's stdin using bash.

I saw someone doing this, but they didn't explain how they did it.

Any suggestions?

Upd: I found a script which can accomplish this task, but I don't understand why:

{ ./A < /dev/fd/3 | ./B 3>&-; } 3>&1 | :
```

答:
You can use the socat utility. It'll connect anything to anything else, including two processes to each other:

```<code>socat exec:'A' exec:'B'
</code>```

Body:
You can use the socat utility. It'll connect anything to anything else, including two processes to each other:

socat exec:'A' exec:'B'


问:
Django DateTimeField with auto_now_add asks for default
I have this field in my model created_at = models.DateTimeField( auto_now_add = True )

When I try to make migrations I get an error:

```<code>You are trying to add the field 'created_at' with 'auto_now_add=True' to user wi
thout a default; the database needs something to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py
</code>```

I tried to set the default value but it says default and auto_now_add are mutually exclusive. Of course I could just use default without auto_now_add but I want to know why this error pops up. Did I miss something?

答:
You have already some rows without created_at value.
But when you added following field and run migration

```<code>created_at = models.DateTimeField( auto_now_add = True)
</code>```

It expects the existing row has created_at value. So, It warns you at the time of migrations.

To solve this problem.
You can choose the 1st option which says Provide a one-off default now (will be set on all existing rows).
By choosing the 1st option you are asking for value. Here you can enter timezone.now(). It will populate existing rows with the current timestamp.

Body:
I have this field in my model created_at = models.DateTimeField( auto_now_add = True )

When I try to make migrations I get an error:

You are trying to add the field 'created_at' with 'auto_now_add=True' to user wi
thout a default; the database needs something to populate existing rows.

 1) Provide a one-off default now (will be set on all existing rows)
 2) Quit, and let me add a default in models.py

I tried to set the default value but it says default and auto_now_add are mutually exclusive. Of course I could just use default without auto_now_add but I want to know why this error pops up. Did I miss something?

Body:
You have already some rows without created_at value.
But when you added following field and run migration

created_at = models.DateTimeField( auto_now_add = True)

It expects the existing row has created_at value. So, It warns you at the time of migrations.

To solve this problem.
You can choose the 1st option which says Provide a one-off default now (will be set on all existing rows).
By choosing the 1st option you are asking for value. Here you can enter timezone.now(). It will populate existing rows with the current timestamp.


问:
Rainmeter Remove last space
From the example, the name of the processor is returned but with a space at the end, how can I make it return a value without a space in the end?

```<code>[MeasureRun]
Measure=Plugin
Plugin=RunCommand
Parameter=wmic cpu get Name
OutputType=ANSI
RegExpSubstitute=1
Substitute="Name.*#CRLF#":"","#CRLF#":""
ClipString=1
IfCondition=1
IfTrueAction=[!CommandMeasure MeasureRun "Run"]

[MeterResult]
Meter=String
MeasureName=MeasureRun
FontSize=14
FontColor=255,255,255,255
AntiAlias=1
Text=%1!
</code>```

I think this can be done through regular expression, but I'm not strong at it.

答:
Just add another Substitute in the substitution list to replace the occurence of one or more whitespaces from the end of the string (the pattern "\s+$") with an empty string like below:

```<code>Substitute="Name.*#CRLF#":"","#CRLF#":"","\s+$":""
</code>```

Title: Rainmeter Remove last space

Body:
From the example, the name of the processor is returned but with a space at the end, how can I make it return a value without a space in the end?

[MeasureRun]
Measure=Plugin
Plugin=RunCommand
Parameter=wmic cpu get Name
OutputType=ANSI
RegExpSubstitute=1
Substitute="Name.*#CRLF#":"","#CRLF#":""
ClipString=1
IfCondition=1
IfTrueAction=[!CommandMeasure MeasureRun "Run"]

[MeterResult]
Meter=String
MeasureName=MeasureRun
FontSize=14
FontColor=255,255,255,255
AntiAlias=1
Text=%1!

I think this can be done through regular expression, but I'm not strong at it.

Body:
Just add another Substitute in the substitution list to replace the occurence of one or more whitespaces from the end of the string (the pattern "\s+$") with an empty string like below:

Substitute="Name.*#CRLF#":"","#CRLF#":"","\s+$":""


问:
Calling a class having its name as a string
I have a string which specifies the name of the call.
How can i call the particular class by using this string.am trying this in java.
A function will return me a list of strings which are class names.now task is to make a call to a  class by using this string.</p>

答:
```<code>public class FooBar
{
    public static void main(String[] args) throws ClassNotFoundException {
        Class test = Class.forName("FooBar");
    }
}
</code>```

ContentLicense: CC BY-SA 3.0


问:
Trying to add elements of an array together
I am trying to get input into an array using a do while loop until the user enters a blank or 0 then am trying to add all the elements within that array together however it returns them in string form.

I have tried using parseInt() in multiple places however it usually makes the code not work at all.

```<code>document.getElementById('while').addEventListener('click', stats);
document.getElementById('while').addEventListener('click', reduction);

var input_array = [];
var value = 0;

function stats() {
  do {
    var number = prompt('Enter a Number');
    var array = input_array.push(number);

    document.getElementById('out2').innerHTML = "[" + input_array + "]";
  } while (value != number);
}

function array_sum(total, num) {
  return total + num;
}

function reduction(item) {
  document.getElementById('out3').innerHTML = input_array.reduce(array_sum);
}
</code>```

答:
If you simply parseInt before you push the value to the array you would get numbers in the array and all works as expected:

let input_array = [];
let value = 0

function stats() {
  do {
    var number = prompt('Enter a Number');
    var array = input_array.push(parseInt(number));  // <-- parse here
  } while (value != number);
}

stats()  // show the prompt etc

function array_sum(total, num) {
  return total + num
}

console.log(input_array.reduce(array_sum))```

I only posted the js part without the html just to give you an example that it works as expected.

Body:
I am trying to get input into an array using a do while loop until the user enters a blank or 0 then am trying to add all the elements within that array together however it returns them in string form.

I have tried using parseInt() in multiple places however it usually makes the code not work at all.

document.getElementById('while').addEventListener('click', stats);
document.getElementById('while').addEventListener('click', reduction);

var input_array = [];
var value = 0;

function stats() {
  do {
    var number = prompt('Enter a Number');
    var array = input_array.push(number);

    document.getElementById('out2').innerHTML = "[" + input_array + "]";
  } while (value != number);
}

function array_sum(total, num) {
  return total + num;
}

function reduction(item) {
  document.getElementById('out3').innerHTML = input_array.reduce(array_sum);
}

Body:
If you simply parseInt before you push the value to the array you would get numbers in the array and all works as expected:

let input_array = [];
let value = 0

function stats() {
  do {
    var number = prompt('Enter a Number');
    var array = input_array.push(parseInt(number));  // <-- parse here
  } while (value != number);
}

stats()  // show the prompt etc

function array_sum(total, num) {
  return total + num
}

console.log(input_array.reduce(array_sum))

I only posted the js part without the html just to give you an example that it works as expected.


问:
JsTree: Show more options
Is there any way to have a show more option/link in jsTree?
I want to show only part of the children and have a link to expand to show all elements.
I tried a few google searches but could not find a solution. Any help/hint would be useful.

Let's say parent-1 has 10 child nodes and the Main Root has 5 parent nodes.

```<code>Main Parent
    - Parent - 1
        - child-1
        - child-2
        - child-3
        show 7 more parent-1 elements //LINK
    - Parent - 2
        - child-1
        - child-2
    - Parent - 3
        - child-1
        - child-2
    show 2 more Main Parent elements //LINK
</code>```

I'm trying to achieve the following result

Is this possible? Are there any available plugins for this? Are there any alternatives for jsTree that support this?

答:
You could feasibly use classes/childElement count to work this. Depending on what you want to show, you could use ids/classes to leave the elements you want to stay visible or optionally show/hide. The same principle can be applied to both child elements (say list items in a list) and higher parent elements, so once you have the first function, it can easily be adapted.

I've included a list example here to give you the idea (it's in plain javascript and you could tweak it a bit..) Jquery would make the js shorter, but it's always good to know the vanilla i reckon..

var x = document.getElementById("show");
//var root = document.getElementsByTagName('body')[0];
var count = x.childElementCount;
var btn1 = document.getElementById("ulmore");
btn1.innerHTML = "+ Show all " + count + " li children";
document.getElementById("ulmore").addEventListener("click", showmore);

function showmore() {
  //var d = document.getElementsByClassName("tg1").length;
  //use d if you want to show "show d more children" instead of the full amount of children
  var el = document.getElementsByTagName("li");

  var i;
  for (i = 0; i < el.length; i++) {
    if (el[i].classList.contains("tg1")) {
      //el[i].style.display = "block"; works
      el[i].classList.toggle('more');
      if (el[i].classList.contains("more")) {
        btn1.innerText = "Hide children";
      } else {
        btn1.innerText = "+ Show all " + count + " li children";
      }
    }
  }
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>body {
  padding: 1em;
  font-size: 10pt;
}

ul {
  list-style: none;
  width: 10em;
  padding: 0px;
}

li {
  text-align: left;
  line-height: 1.5;
  background: lightblue;
  border: 1px solid #444;
  margin: 1px 0px;
  padding: 2px;
}

span {
  display: inline-block;
}

div {
  display: inline-block;
  width: 100%;
  float: left;
  margin: 1em 2em 1em 0em;
}

.tg1 {
  background: lightsteelblue;
  display: none;
}

.more {
  background: lightsteelblue;
  display: block;
}

/*.tog2 {
  display: none;
}

.grow {
  background: yellow;
  display: inline-block;
}*/</code>```

Demo List

One

Two

Three

Four

Five

Six

Seven

Eight

```

Here's a fiddle link (with body 'parent' elements) included in code.
(Note: even a
 tag [when used between divs] will be regarded as a top-level element .. I'd think that count by tagName (or className) would be most useful if you want to count different types of  'parent' elements (as opposed to counting children of body).  Examples of both (children of body and getElementsByTagName) are included in the fiddle)

Hope this helps

Title: JsTree: Show more options

Body:
Is there any way to have a show more option/link in jsTree?
I want to show only part of the children and have a link to expand to show all elements.
I tried a few google searches but could not find a solution. Any help/hint would be useful.

Let's say parent-1 has 10 child nodes and the Main Root has 5 parent nodes.

Main Parent
    - Parent - 1
        - child-1
        - child-2
        - child-3
        show 7 more parent-1 elements //LINK
    - Parent - 2
        - child-1
        - child-2
    - Parent - 3
        - child-1
        - child-2
    show 2 more Main Parent elements //LINK

I'm trying to achieve the following result

Is this possible? Are there any available plugins for this? Are there any alternatives for jsTree that support this?

Body:
You could feasibly use classes/childElement count to work this. Depending on what you want to show, you could use ids/classes to leave the elements you want to stay visible or optionally show/hide. The same principle can be applied to both child elements (say list items in a list) and higher parent elements, so once you have the first function, it can easily be adapted.

I've included a list example here to give you the idea (it's in plain javascript and you could tweak it a bit..) Jquery would make the js shorter, but it's always good to know the vanilla i reckon..

var x = document.getElementById("show");
//var root = document.getElementsByTagName('body')[0];
var count = x.childElementCount;
var btn1 = document.getElementById("ulmore");
btn1.innerHTML = "+ Show all " + count + " li children";
document.getElementById("ulmore").addEventListener("click", showmore);

function showmore() {
  //var d = document.getElementsByClassName("tg1").length;
  //use d if you want to show "show d more children" instead of the full amount of children
  var el = document.getElementsByTagName("li");

  var i;
  for (i = 0; i < el.length; i++) {
    if (el[i].classList.contains("tg1")) {
      //el[i].style.display = "block"; works
      el[i].classList.toggle('more');
      if (el[i].classList.contains("more")) {
        btn1.innerText = "Hide children";
      } else {
        btn1.innerText = "+ Show all " + count + " li children";
      }
    }
  }
}

body {
  padding: 1em;
  font-size: 10pt;
}

ul {
  list-style: none;
  width: 10em;
  padding: 0px;
}

li {
  text-align: left;
  line-height: 1.5;
  background: lightblue;
  border: 1px solid #444;
  margin: 1px 0px;
  padding: 2px;
}

span {
  display: inline-block;
}

div {
  display: inline-block;
  width: 100%;
  float: left;
  margin: 1em 2em 1em 0em;
}

.tg1 {
  background: lightsteelblue;
  display: none;
}

.more {
  background: lightsteelblue;
  display: block;
}

/*.tog2 {
  display: none;
}

.grow {
  background: yellow;
  display: inline-block;
}*/

<body>
  <div id="ulbit">
    <h4>Demo List</h4>
    <ul id="show">
      <li>One</li>
      <li>Two</li>
      <li class="tg1">Three</li>
      <li class="tg1">Four</li>
      <li class="tg1">Five</li>
      <li class="tg1">Six</li>
      <li class="tg1">Seven</li>
      <li class="tg1">Eight</li>
    </ul>
    <span id="ulmore"></span>
  </div>

<!--  <div class="tog2">
    Div 2 hello
  </div>
  <div class="tog2">
    Div 3
  </div>
  <span id="divmore"></span>-->
</body>

Here's a fiddle link (with body 'parent' elements) included in code.
(Note: even a <br> tag [when used between divs] will be regarded as a top-level element .. I'd think that count by tagName (or className) would be most useful if you want to count different types of  'parent' elements (as opposed to counting children of body).  Examples of both (children of body and getElementsByTagName) are included in the fiddle)

Hope this helps


问:
How to output DATEADD with a specific precision?
I have a procedure which is called from external application.
The procedure has a parameter time of bigint type. In the procedure I insert the time to my table to column of 'time' type. To convert bigint to time I use DATEADD:

```<code>DATEADD(S, @piHMSTime, '19700101')
</code>```

Everything works fine but I get time in my table like this 22:59:57.0000000.
How do I set a needed precision? I need only seconds or maybe 2 digits after point.

答:
The external application is sending you the number of seconds since 1970-01-01.  As long as that doesn't change you can't get more precision.

If you can get the external application to pass you milliseconds since 1970-01-01, you can use the function shown here.

Body:
I have a procedure which is called from external application.
The procedure has a parameter time of bigint type. In the procedure I insert the time to my table to column of 'time' type. To convert bigint to time I use DATEADD:

DATEADD(S, @piHMSTime, '19700101')

Everything works fine but I get time in my table like this 22:59:57.0000000.
How do I set a needed precision? I need only seconds or maybe 2 digits after point.


问:
Relative Paths From Partials Referencing Other Partials
I am using a (primary) partial:

```<code><%= render partial: 'shared/page/head' %>
</code>```

Which makes use of other (secondary) partials:

```<code><head>
  <%= render partial: 'shared/page/head/title' %>
  <%= render partial: 'shared/page/head/meta' %>
  ...
  <%= render partial: 'shared/page/head/fonts' %>
  ...
  <%= render partial: 'shared/page/head/google_analytics' %>
</head>
</code>```

As you can see I'm currently using paths relative to app/view for these secondary partials even though they are sitting in the same directory as the primary partial.

I've tried using relative paths:

```<code><%= render partial: 'title' %>
</code>```

Or

```<code><%= render partial: './title' %>
</code>```

But neither work.

Is there a way to have a partial resolve partials it uses using a relative path?

答:
I write a helper method to implement it. Sound like work perfectly.</p>

```<code>def render_relative_partial(relative_path, option={})
    caller_path = caller[0].split(".")[0].split("/")[0..-2].join("/")
  path = caller_path.gsub("#{Rails.root.to_s}/app/views/","") + "/#{relative_path}"

  option[:partial] = path
  render option
end
</code>```

Body:
I am using a (primary) partial:

<%= render partial: 'shared/page/head' %>

Which makes use of other (secondary) partials:

  <%= render partial: 'shared/page/head/title' %>
  <%= render partial: 'shared/page/head/meta' %>
  ...
  <%= render partial: 'shared/page/head/fonts' %>
  ...
  <%= render partial: 'shared/page/head/google_analytics' %>

As you can see I'm currently using paths relative to app/view for these secondary partials even though they are sitting in the same directory as the primary partial.

I've tried using relative paths:

<%= render partial: 'title' %>

Or

<%= render partial: './title' %>

But neither work.

Is there a way to have a partial resolve partials it uses using a relative path?

Body:
I write a helper method to implement it. Sound like work perfectly.

def render_relative_partial(relative_path, option={})
    caller_path = caller[0].split(".")[0].split("/")[0..-2].join("/")
  path = caller_path.gsub("#{Rails.root.to_s}/app/views/","") + "/#{relative_path}"

  option[:partial] = path
  render option
end


问:
problem with jquery dialog
I have a partial view with a dropdown (with Paid and unpaid as options) and a button.
I am loading this partial view using jquery load, when the user click Paid/Unpaid List link in the sub menu of a page.

When i select Paid in dropdown and click the button, it shows the list of paid customers in the jquery dialog and if i select Unpaid and click button, it shows unpaid customers in the jquery dialog.

I am writing the following code for the dialog:

```<code> $('#customers').dialog({
            bgiframe: true,
            autoOpen: false,
            open: function(event, ui) {
                //populate table
                var p_option = $('#d_PaidUnPaid option:selected').val();
                if (p_option  == 'PAID') {
                    $("#customercontent").html('');
                    //$("#customercontent").load("/Customer/Paid");
                }
                else if (p_option  == 'UNPAID') {
                    $("#customercontent").html('');
                    //$("#customercontent").load("/Customer/Unpaid");
                }
            },
            close: function(event, ui) {
                //do nothing
            },
            height: 500,
            width: 550,
            modal: true
        });
</code>```

For the first time, i am getting the list correctly in the jquery dialog, but when i click the Paid/Unpaid List link again and select Unpaid in the dropdown and click the button, it shows the previos loaded content in the jquery dialog.

What am i doing wrong here?

答:
I hope Im not too late to come up with correct answer. I had the same problem and I solved it with following ajax settings.</p>

```<code>open: function () {
      jQuery.ajaxSetup({
             cache: false
       });
       //populate table or do what you want...
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: problem with jquery dialog

Body:
I have a partial view with a dropdown (with Paid and unpaid as options) and a button.
I am loading this partial view using jquery load, when the user click Paid/Unpaid List link in the sub menu of a page.

When i select Paid in dropdown and click the button, it shows the list of paid customers in the jquery dialog and if i select Unpaid and click button, it shows unpaid customers in the jquery dialog.

I am writing the following code for the dialog:

 $('#customers').dialog({
            bgiframe: true,
            autoOpen: false,
            open: function(event, ui) {
                //populate table
                var p_option = $('#d_PaidUnPaid option:selected').val();
                if (p_option  == 'PAID') {
                    $("#customercontent").html('');
                    //$("#customercontent").load("/Customer/Paid");
                }
                else if (p_option  == 'UNPAID') {
                    $("#customercontent").html('');
                    //$("#customercontent").load("/Customer/Unpaid");
                }
            },
            close: function(event, ui) {
                //do nothing
            },
            height: 500,
            width: 550,
            modal: true
        });

For the first time, i am getting the list correctly in the jquery dialog, but when i click the Paid/Unpaid List link again and select Unpaid in the dropdown and click the button, it shows the previos loaded content in the jquery dialog.

What am i doing wrong here?

Body:
I hope Im not too late to come up with correct answer. I had the same problem and I solved it with following ajax settings.

open: function () {
      jQuery.ajaxSetup({
             cache: false
       });
       //populate table or do what you want...
}


问:
Rotate list
 of images placed on a circle on click of any child to a given position
I have arranged a list of images on a circle using css transforms. what i want is that when any child image of the list is clicked the circle rotates and the selected or the active child image reaches to a given position. say 3'o clock.
how can i achieve this with js. i dont know sass currently

this is what i got right now.

!https://ibb.co/zfPQvNn

when any child image is clicked i want the circle to rotate such that the active image always ends up at the same position. say 3'o clock

```

<pre class="lang-css prettyprint-override"><code>.team-list > ul > * {
  /* 4 */
  display: block;
  position: absolute;
  margin-top:55%;

}
.team-list > ul > :nth-of-type(1) {
  transform: rotate(0deg) translate(10em) rotate(0deg);
}
.team-list >ul > :nth-of-type(2) {
  transform: rotate(45deg) translate(10em) rotate(-45deg);
}
.team-list > ul > :nth-of-type(3) {
  transform: rotate(90deg) translate(10em) rotate(-90deg);
}
.team-list > ul > :nth-of-type(4) {
  transform: rotate(135deg) translate(10em) rotate(-135deg);
}
.team-list > ul > :nth-of-type(5) {
  transform: rotate(180deg) translate(10em) rotate(-180deg);
}
.team-list > ul > :nth-of-type(6) {
  transform: rotate(225deg) translate(10em) rotate(-225deg);
}
.team-list > ul > :nth-of-type(7) {
  transform: rotate(270deg) translate(10em) rotate(-270deg);
}
.team-list > ul > :nth-of-type(8) {
  transform: rotate(315deg) translate(10em) rotate(-315deg);
}

.team-list img {
  display: block;
  width: 100%;
}
</code>```

答:
Option 1

One of the ways it could be done is by "transferring" the transform property across the items every time a user clicks one, achieving an effect somewhat attractive but not quite a clean rotation. You would do this by using the getComputedStyle function, like this:

let allItems = document.getElementById('list').getElementsByTagName('li');
let allItemsAsArray = Array.from(allItems);

let fixedPositions = {}, transforms = {};
let auxPosition = 0;

allItemsAsArray.forEach((elem, index) => {
  transforms[auxPosition] = window.getComputedStyle(elem).transform;
  fixedPositions[index] = auxPosition++;

  elem.addEventListener('click', (event) => {
    let steps = 8 - fixedPositions[index];
    allItemsAsArray.forEach((elem2, index2) => {
          copyTransformProp(
              transforms[fixedPositions[(index2 + steps) % 8]]
            ,
          elem2);
    });
  });
});

function copyTransformProp(sourceProperty, targetNode) {
  targetNode.style.setProperty('transform', sourceProperty);
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.team-list > ul > li {
  /* 4 */
  display: block;
  position: absolute;
  top:55%;
  left: 40%;
  transition: ease all 1s;
}

#list img {
  width: 50px
}

.team-list > ul > :nth-of-type(1) {
  transform: rotate(0deg) translate(10em) rotate(0deg);
}

.team-list >ul > :nth-of-type(2) {
  transform: rotate(45deg) translate(10em) rotate(-45deg);
}

.team-list > ul > :nth-of-type(3) {
  transform: rotate(90deg) translate(10em) rotate(-90deg);
}

.team-list > ul > :nth-of-type(4) {
  transform: rotate(135deg) translate(10em) rotate(-135deg);
}
.team-list > ul > :nth-of-type(5) {
  transform: rotate(180deg) translate(10em) rotate(-180deg);
}
.team-list > ul > :nth-of-type(6) {
  transform: rotate(225deg) translate(10em) rotate(-225deg);
}
.team-list > ul > :nth-of-type(7) {
  transform: rotate(270deg) translate(10em) rotate(-270deg);
}
.team-list > ul > :nth-of-type(8) {
  transform: rotate(315deg) translate(10em) rotate(-315deg);
}

.team-list img {
  display: block;
  width: 20%;
}</code>```

```
</div>
</div>
</p>

<h2>Option 2</h2>

<p>Now, to achieve a really clean rotation, I would go with requestAnimationFrame
. This time you would not depend on the CSS property <em>transition</em> for smoothness, but directly in JavaScript, working with angles.</p>

<p>I thought it might be better to generate the items dynamically in JS, so you don't have to style each one manually in CSS. It also allows you to generate "as many items as you want", careful though, don't get too greedy on the amount.</p>

<p>Try this snippet full page. </p>

<p>HIH</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let ul = document.getElementById('list');
let anglePerItem = [];

generateItems(8, 0, 9);

let allItems = ul.getElementsByTagName('li');
let allItemsAsArray = Array.from(allItems);

function generateItems(itemNum, initAngle, radius) {
    let angleStep = Math.PI * 2 / itemNum;
    let angle = initAngle;

    for (let i = 0; i < itemNum; i++) {
        let li = document.createElement('li');
        if (i === 0)
            li.classList.add('wow', 'active', 'zoomIn');
        else
            li.classList.add('wow', 'zoomIn');

        let a = document.createElement('a');
        a.href = '#team-' + (i + 1);
        a.setAttribute('data-team', 'team-' + (i + 1));
        li.appendChild(a);

        let img = document.createElement('img');
        img.src = 'https://dummyimage.com/640x4:3/&text=' + (i + 1);
        img.alt = 'Team Member image ' + (i + 1);
        a.appendChild(img);

        let x = Math.cos(angle) * radius, y = Math.sin(angle) * radius;
        anglePerItem.push(angle);
        angle += angleStep;
        li.style.transform = 'translate(' + x + 'em, ' + y + 'em)';

        ul.appendChild(li);

        addClickEvent(li, i, radius);
    }
}

function addClickEvent(elem, clickedIndex, radius) {
    elem.addEventListener('click', () => {
        if (anglePerItem[clickedIndex] !== 0) {
            Array.from(ul.getElementsByTagName('li')).forEach((elem, index) => {
                let angle = anglePerItem[index] % (Math.PI * 2);
                let endAngle = Math.PI * 2 - anglePerItem[clickedIndex] + angle;
                if (angle > endAngle)
                    endAngle += Math.PI * 2;

                function step(timestamp) {
                    let x = Math.cos(angle) * radius, y = Math.sin(angle) * radius;
                    angle += .1;

                    elem.style.transform = 'translate(' + x + 'em, ' + y + 'em)';

                    if (angle < endAngle) {
                        setTimeout(function () {
                            window.requestAnimationFrame(step);
                        }, 10);
                    } else {
                        elem.style.transform = 'translate(' + Math.cos(endAngle) * radius + 'em, ' + Math.sin(endAngle) * radius + 'em)';
                        anglePerItem[index] = endAngle;
                    }
                }

                window.requestAnimationFrame(step);
            });
        }
    });
}</code>```

.team-list > ul > li {
    display: block;
    position: absolute;
    top:50%;
    left: 40%;
}

#list img {
    width: 50px
}

.team-list img {
    display: block;
    width: 20%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="team-list"><ul id='list'></ul></div></code>```

Title: Rotate list <li> of images placed on a circle on click of any child to a given position

Body:
I have arranged a list of images on a circle using css transforms. what i want is that when any child image of the list is clicked the circle rotates and the selected or the active child image reaches to a given position. say 3'o clock.
how can i achieve this with js. i dont know sass currently

this is what i got right now.

!https://ibb.co/zfPQvNn

when any child image is clicked i want the circle to rotate such that the active image always ends up at the same position. say 3'o clock

.team-list > ul > * {
  /* 4 */
  display: block;
  position: absolute;
  margin-top:55%;

}
.team-list > ul > :nth-of-type(1) {
  transform: rotate(0deg) translate(10em) rotate(0deg);
}
.team-list >ul > :nth-of-type(2) {
  transform: rotate(45deg) translate(10em) rotate(-45deg);
}
.team-list > ul > :nth-of-type(3) {
  transform: rotate(90deg) translate(10em) rotate(-90deg);
}
.team-list > ul > :nth-of-type(4) {
  transform: rotate(135deg) translate(10em) rotate(-135deg);
}
.team-list > ul > :nth-of-type(5) {
  transform: rotate(180deg) translate(10em) rotate(-180deg);
}
.team-list > ul > :nth-of-type(6) {
  transform: rotate(225deg) translate(10em) rotate(-225deg);
}
.team-list > ul > :nth-of-type(7) {
  transform: rotate(270deg) translate(10em) rotate(-270deg);
}
.team-list > ul > :nth-of-type(8) {
  transform: rotate(315deg) translate(10em) rotate(-315deg);
}

.team-list img {
  display: block;
  width: 100%;
}

Body:
Option 1

One of the ways it could be done is by "transferring" the transform property across the items every time a user clicks one, achieving an effect somewhat attractive but not quite a clean rotation. You would do this by using the getComputedStyle function, like this:

let allItems = document.getElementById('list').getElementsByTagName('li');
let allItemsAsArray = Array.from(allItems);

let fixedPositions = {}, transforms = {};
let auxPosition = 0;

allItemsAsArray.forEach((elem, index) => {
  transforms[auxPosition] = window.getComputedStyle(elem).transform;
  fixedPositions[index] = auxPosition++;

  elem.addEventListener('click', (event) => {
    let steps = 8 - fixedPositions[index];
    allItemsAsArray.forEach((elem2, index2) => {
          copyTransformProp(
              transforms[fixedPositions[(index2 + steps) % 8]]
            ,
          elem2);
    });
  });
});

function copyTransformProp(sourceProperty, targetNode) {
  targetNode.style.setProperty('transform', sourceProperty);
}

.team-list > ul > li {
  /* 4 */
  display: block;
  position: absolute;
  top:55%;
  left: 40%;
  transition: ease all 1s;
}

#list img {
  width: 50px
}

.team-list > ul > :nth-of-type(1) {
  transform: rotate(0deg) translate(10em) rotate(0deg);
}

.team-list >ul > :nth-of-type(2) {
  transform: rotate(45deg) translate(10em) rotate(-45deg);
}

.team-list > ul > :nth-of-type(3) {
  transform: rotate(90deg) translate(10em) rotate(-90deg);
}

.team-list > ul > :nth-of-type(4) {
  transform: rotate(135deg) translate(10em) rotate(-135deg);
}
.team-list > ul > :nth-of-type(5) {
  transform: rotate(180deg) translate(10em) rotate(-180deg);
}
.team-list > ul > :nth-of-type(6) {
  transform: rotate(225deg) translate(10em) rotate(-225deg);
}
.team-list > ul > :nth-of-type(7) {
  transform: rotate(270deg) translate(10em) rotate(-270deg);
}
.team-list > ul > :nth-of-type(8) {
  transform: rotate(315deg) translate(10em) rotate(-315deg);
}

.team-list img {
  display: block;
  width: 20%;
}

<div class="team-list">
    <ul id='list'>
       <li class="wow active zoomIn" data-wow-duration="1s" data-wow-delay=".1s" >
            <a href="#team-1" data-team="team-1">

                      <img src="https://dummyimage.com/640x4:3/&text=1" alt="Team Member image One">

            </a>
        </li>
        <li class="wow zoomIn" data-wow-duration="1s" data-wow-delay=".3s">
            <a href="#team-2" data-team="team-2">

                       <img src="https://dummyimage.com/640x4:3/&text=2" alt="Team Member image two">

            </a>
        </li>
        <li class="wow zoomIn" data-wow-duration="1s" data-wow-delay=".5s">
            <a href="#team-3" data-team="team-3">

                      <img src="https://dummyimage.com/640x4:3/&text=3" alt="Team Member image three">

            </a>
        </li>
        <li class="wow zoomIn" data-wow-duration="1s" data-wow-delay=".7s">
            <a href="#team-4" data-team="team-4">

                      <img src="https://dummyimage.com/640x4:3/&text=4" alt="Team Member image four">

            </a>
        </li>
        <li class="wow zoomIn" data-wow-duration="1s" data-wow-delay=".9s">
            <a href="#team-5" data-team="team-5">

                      <img src="https://dummyimage.com/640x4:3/&text=5" alt="Team Member image five">

            </a>
        </li>
        <li class="wow zoomIn" data-wow-duration="1s" data-wow-delay="1.1s">
            <a href="#team-6" data-team="team-6">

                      <img src="https://dummyimage.com/640x4:3/&text=6" alt="Team Member image six">

            </a>
        </li>
        <li class="wow zoomIn" data-wow-duration="1s" data-wow-delay="1.3s">
            <a href="#team-7" data-team="team-7">

                       <img src="https://dummyimage.com/640x4:3/&text=7" alt="Team Member image seven">

            </a>
        </li>
        <li class="wow zoomIn" data-wow-duration="1s" data-wow-delay="1.5s">
            <a href="#team-8" data-team="team-8">

                       <img src="https://dummyimage.com/640x4:3/&text=8" alt="Team Member image eight">

            </a>
        </li>
     </ul>
</div>

Option 2

Now, to achieve a really clean rotation, I would go with requestAnimationFrame
. This time you would not depend on the CSS property transition for smoothness, but directly in JavaScript, working with angles.

I thought it might be better to generate the items dynamically in JS, so you don't have to style each one manually in CSS. It also allows you to generate "as many items as you want", careful though, don't get too greedy on the amount.

Try this snippet full page.

HIH

let ul = document.getElementById('list');
let anglePerItem = [];

generateItems(8, 0, 9);

let allItems = ul.getElementsByTagName('li');
let allItemsAsArray = Array.from(allItems);

function generateItems(itemNum, initAngle, radius) {
    let angleStep = Math.PI * 2 / itemNum;
    let angle = initAngle;

    for (let i = 0; i < itemNum; i++) {
        let li = document.createElement('li');
        if (i === 0)
            li.classList.add('wow', 'active', 'zoomIn');
        else
            li.classList.add('wow', 'zoomIn');

        let a = document.createElement('a');
        a.href = '#team-' + (i + 1);
        a.setAttribute('data-team', 'team-' + (i + 1));
        li.appendChild(a);

        let img = document.createElement('img');
        img.src = 'https://dummyimage.com/640x4:3/&text=' + (i + 1);
        img.alt = 'Team Member image ' + (i + 1);
        a.appendChild(img);

        let x = Math.cos(angle) * radius, y = Math.sin(angle) * radius;
        anglePerItem.push(angle);
        angle += angleStep;
        li.style.transform = 'translate(' + x + 'em, ' + y + 'em)';

        ul.appendChild(li);

        addClickEvent(li, i, radius);
    }
}

function addClickEvent(elem, clickedIndex, radius) {
    elem.addEventListener('click', () => {
        if (anglePerItem[clickedIndex] !== 0) {
            Array.from(ul.getElementsByTagName('li')).forEach((elem, index) => {
                let angle = anglePerItem[index] % (Math.PI * 2);
                let endAngle = Math.PI * 2 - anglePerItem[clickedIndex] + angle;
                if (angle > endAngle)
                    endAngle += Math.PI * 2;

                function step(timestamp) {
                    let x = Math.cos(angle) * radius, y = Math.sin(angle) * radius;
                    angle += .1;

                    elem.style.transform = 'translate(' + x + 'em, ' + y + 'em)';

                    if (angle < endAngle) {
                        setTimeout(function () {
                            window.requestAnimationFrame(step);
                        }, 10);
                    } else {
                        elem.style.transform = 'translate(' + Math.cos(endAngle) * radius + 'em, ' + Math.sin(endAngle) * radius + 'em)';
                        anglePerItem[index] = endAngle;
                    }
                }

                window.requestAnimationFrame(step);
            });
        }
    });
}

.team-list > ul > li {
    display: block;
    position: absolute;
    top:50%;
    left: 40%;
}

#list img {
    width: 50px
}

.team-list img {
    display: block;
    width: 20%;
}

<div class="team-list"><ul id='list'></ul></div>


问:
cannot pass float array out of a function
I'm new to c++, and I want to pass a float array out of a function using a pointer. However, the returning array is always 0; I am running on an Arduino Uno.

This is my code. I want the readSensor() function to pass out a float array consisting of 3 floats. The float array should be pass to the pointer output*. But when I print out readings, it shows 0.00 instead of the values I passed out.

void setup() {
  Serial.begin(9600);
}

void loop() {
  float readings[3];
  readSensor(readings);
  for (int i = 0;i < 3;i++) {
    Serial.println(readings[i]);
  }
  delay(1000);
}

// pass out these 3 floats
float val1 = 3.14159;
float val2 = 2.741;
float val3 = 87;
void readSensor(float* output) {
  float container[3] = {val1, val2, val3};
  output = container;
}
```

答:
```<code>void readSensor(float* output)
{
    float container[3] = {val1, val2, val3};
    for (int i=0; i<3; i++)
    {
        output[i] = container[i];
    }
}
</code>```


问:
Update document is free or is it considered write operation?
firestore is charging for reading, write and delete operation but update case is not mentioned

firestore update document is free or is it considered write operation?
in pricing page, no details were given about update document case

答: A write is billed any time a document is created or changed, including use of the update method.</p>


问:
Class-based views in aiohttp
What is the right approach to use class-based handlers instead of functions in aiohttp library? I'm used to writing handlers as classes in Django so I am wondering how to do it correctly in aiohttp?

答:
You can use it like this:

from aiohttp import web
from datetime import datetime

class TokenView(web.View):

    async def get(self):
        token = datetime.now().strftime("%Y%m%d%H%M%S")
        room = self.request.match_info.get("room", None)
        return web.json_response({"room": room, "token": token, "result": "OK"})

    async def post(self):
        room = self.request.match_info.get("room", None)
        token = datetime.now().strftime("%Y%m%d%H%M%S")
        return web.json_response({"room": room, "token": token, "result": "OK"})

if __name__ == "__main__":

    app = web.Application()
    app.router.add_view("/token/{room}", TokenView)
    print(app.router.named_resources())
    web.run_app(app)
```

Title: Class-based views in aiohttp


问:
Extension of STL container through composition or free functions?
Say I need a new type in my application, that consists of a std::vector<int> extended by a single function. The straightforward way would be composition (due to limitations in inheritance of STL containers):

```<code>class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> vec_
}
</code>```

This requires the user to first construct a vector<int> and a copy in the constructor, which is bad when we are going to handle a sizeable number of large vectors. One could, of course, write a pass-through to push_back(), but this introduces mutable state, which I would like to avoid.

So it seems to me, that we can either avoid copies or keep A immutable, is this correct?

If so, the simplest (and efficiency-wise equivalent) way would be to use a typedef and free functions at namespace scope:

```<code>namespace N {
typedef std::vector<int> A;
int a_hash(const A & a);
}
</code>```

This just feels wrong somehow, since extensions in the future will "pollute" the namespace. Also, calling a_hash(...) on any vector<int> is possible, which might lead to unexpected results (assuming that we impose constraints on A the user has to follow or that would otherwise be enforced in the first example)

My two questions are:

how can one not sacrifice both immutability and efficiency when using the above class code?

when does it make sense to use free functions as opposed to encapsulation in classes/structs?

Thank you!

答:
One simple solution is to declare the private member variable as reference & initialize in constructor. This approach introduces some limitation, but it's a good alternative in most cases.

```<code>class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> &vec_; // 'vec_' now a reference, so will be same scoped as 'vec'
};
</code>```

Body:
Say I need a new type in my application, that consists of a std::vector<int> extended by a single function. The straightforward way would be composition (due to limitations in inheritance of STL containers):

class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> vec_
}

This requires the user to first construct a vector<int> and a copy in the constructor, which is bad when we are going to handle a sizeable number of large vectors. One could, of course, write a pass-through to push_back(), but this introduces mutable state, which I would like to avoid.

So it seems to me, that we can either avoid copies or keep A immutable, is this correct?

If so, the simplest (and efficiency-wise equivalent) way would be to use a typedef and free functions at namespace scope:

namespace N {
typedef std::vector<int> A;
int a_hash(const A & a);
}

This just feels wrong somehow, since extensions in the future will "pollute" the namespace. Also, calling a_hash(...) on any vector<int> is possible, which might lead to unexpected results (assuming that we impose constraints on A the user has to follow or that would otherwise be enforced in the first example)

My two questions are:

how can one not sacrifice both immutability and efficiency when using the above class code?

when does it make sense to use free functions as opposed to encapsulation in classes/structs?

Thank you!

Body:
One simple solution is to declare the private member variable as reference & initialize in constructor. This approach introduces some limitation, but it's a good alternative in most cases.

class A {
    public:
        A(std::vector<int> & vec) : vec_(vec) {}
        int hash();
    private:
        std::vector<int> &vec_; // 'vec_' now a reference, so will be same scoped as 'vec'
};


问:
Python turtle project producing error: object has no attribute
I am trying to complete a final project for my Python course. The requirements are as follows:

Use the concepts of object-based programming—classes, objects, and
methods

Draw two-dimensional shape

Develop recursive algorithms to draw recursive shapes

Write a nested loop to process a two-dimensional grid

I have written some code but I am having trouble getting it to produce a result in the turtle screen:

```<code>import turtle
from PIL import Image
kel = turtle.Turtle()

class Draw_pattern(object):
    def __init__(self,posx,posy,size):
        self.posx = posx
        self.posy = posy
        self.size = size

    def draw_grid(self,initx, inity):
        # Drawing grid
        kel.penup()
        kel.color("black")
        for i in range(7):
            kel.goto(self.posx, self.posy)
            kel.pendown()
            kel.forward(self.size*6)
            self.posy = self.posy+self.size;
            self.posx = initx;
            kel.penup()

        self.posx = initx;
        self.posy = inity;
        kel.left(90)
        for i in range(7):
            kel.goto(self.posx, self.posy)
            kel.pendown()
            kel.forward(self.size*6)
            self.posx = self.posx+self.size;
            self.posy = inity;
            kel.penup()

def draw_shape(self,initx, inity):
    self.posx = initx;
    self.posy = inity;
# Drawing yellow portion
    kel.penup()
    kel.goto(self.posx, self.posy)
    kel.pendown()
    kel.fillcolor("yellow")
    kel.begin_fill()
    kel.goto(self.posx, self.posy+self.size*6)
    kel.goto(self.posx+self.size*6, self.posy+self.size*6)
    kel.goto(self.posx+self.size*6, self.posy)
    kel.goto(self.posx, self.posy)
    kel.end_fill()

# Drawing red portion
    kel.penup()
    kel.goto(self.posx, self.posy+self.size*2)
    kel.pendown()
    kel.fillcolor("red")
    kel.begin_fill()
    kel.goto(self.posx+self.size, self.posy+self.size*3)
    kel.goto(self.posx, self.posy+self.size*4)
    kel.goto(self.posx+self.size*2, self.posy+self.size*4)
    kel.goto(self.posx+self.size*2, self.posy+self.size*6)
    kel.goto(self.posx+self.size*3, self.posy+self.size*5)
    kel.goto(self.posx+self.size*4, self.posy+self.size*6)
    kel.goto(self.posx+self.size*4, self.posy+self.size*4)
    kel.goto(self.posx+self.size*6, self.posy+self.size*4)
    kel.goto(self.posx+self.size*5, self.posy+self.size*3)
    kel.goto(self.posx+self.size*6, self.posy+self.size*2)
    kel.goto(self.posx+self.size*4, self.posy+self.size*2)
    kel.goto(self.posx+self.size*4, self.posy)
    kel.goto(self.posx+self.size*3, self.posy+self.size)
    kel.goto(self.posx+self.size*2, self.posy)
    kel.goto(self.posx+self.size*2, self.posy+self.size*2)
    kel.goto(self.posx, self.posy+self.size*2)
    kel.end_fill()

 # recursive function to draw repeating shape
def repeat_shape(self,intx, inty):
    if intx>=3 | inty>=3:
        return
    else:
        self.draw_shape(intx*180, inty*180)
        kel.right(90)
        self.repeat_shape(intx+1,inty)
        self.repeat_shape(intx,inty+1)

class image_play(object):
    def __init__(self,im_name):
        self.im_name = im_name

def rgb_to_gray_image(self):
    im = Image.open(self.im_name)
    im = im.convert('LA')

     # editing pixels of image to white
def loop_over_image(self):
    im = Image.open(self.im_name)
    width, height = im.size
    # nested loop over all pixels of image
    for i in range(width):
        for j in range(height):
            im[i][j] = 255;

kel.speed("fastest")

# object of class Draw_pattern
obj = Draw_pattern(0,0,30)
obj.draw_grid(0,0)
obj.repeat_shape(0,0)

AttributeErrorTraceback (most recent call last)
<ipython-input-14-8b7bbac27093> in <module>
    103 obj = Draw_pattern(0,0,30)
    104 obj.draw_grid(0,0)
--> 105 obj.repeat_shape(0,0)

AttributeError: 'Draw_pattern' object has no attribute 'repeat_shape'
</code>```

答:
I agree with the answer by @VasuDeo.S (+1) regarding your immediate problem.  However, I see some more subtle issues with your code:

When it comes to your grid, your instructions say, "write a nested
loop" but your two loops are sequential not nested.

When working with turtle, goto() is used for large jumps (and to get out of jams).  For smaller movements, we tend to use forward(), backward(), left() and right() otherwise there's no difference between using turtle and a conventional line drawing graphics package.

Your self.posx and self.posy instance variables serve no purpose beyond being convenient local variables.  They save no state that carries from one method to the other.  We can eliminate them as instance variables.

It seems odd to have your object's instance methods rely on the global turtle named 'kel' -- it would make more sense to pass a turtle to its constructor or have it create one of its own.

You can take more advantage of symmetry in your designs to reduce the amount of code you need to draw them.

I've addressed the above issues in my rework of your/Vasu's code below.  (I've left out your image code as that isn't currently active.)

```<code>from turtle import Screen, Turtle

class DrawPattern():
    def __init__(self, size):
        self.size = size

        self.turtle = Turtle()
        self.turtle.speed("fastest")

    def draw_grid(self, init_x, init_y):

        ''' Draw a grid '''

        self.turtle.penup()
        self.turtle.goto(init_x, init_y)

        for _ in range(2):
            for _ in range(7):

                self.turtle.pendown()
                self.turtle.forward(self.size * 6)
                self.turtle.backward(self.size * 6)
                self.turtle.left(90)
                self.turtle.penup()
                self.turtle.forward(self.size)
                self.turtle.right(90)

            self.turtle.right(90)
            self.turtle.forward(self.size)

    def repeat_shape(self, iter_x, iter_y):
        if iter_x < 3 > iter_y:
            self.draw_shape(iter_x * 180, iter_y * 180)
            self.turtle.right(90)
            self.repeat_shape(iter_x + 1, iter_y)
            self.repeat_shape(iter_x, iter_y + 1)

    def draw_shape(self, init_x, init_y):

        ''' Recursive method to draw repeating shape '''

        # Draw yellow portion
        self.turtle.penup()
        self.turtle.goto(init_x, init_y)
        self.turtle.setheading(90)
        self.turtle.pendown()

        self.turtle.fillcolor("yellow")
        self.turtle.begin_fill()

        for _ in range(4):
            self.turtle.forward(self.size * 6)
            self.turtle.right(90)

        self.turtle.end_fill()

        # Draw red portion
        self.turtle.penup()
        self.turtle.goto(init_x, init_y + self.size * 2)
        self.turtle.setheading(0)
        self.turtle.pendown()

        self.turtle.fillcolor("red")
        self.turtle.begin_fill()

        for _ in range(4):
            self.turtle.left(45)
            self.turtle.forward(42)
            self.turtle.left(90)
            self.turtle.forward(42)
            self.turtle.right(135)
            self.turtle.forward(self.size * 2)
            self.turtle.left(90)
            self.turtle.forward(self.size * 2)
            self.turtle.left(180)

        self.turtle.end_fill()

# object instance of class DrawPattern
obj = DrawPattern(30)
obj.draw_grid(-200, -200)
obj.repeat_shape(0, 0)

screen = Screen()
screen.exitonclick()
</code>```

Body:
I am trying to complete a final project for my Python course. The requirements are as follows:

Use the concepts of object-based programming—classes, objects, and
methods

Draw two-dimensional shape

Develop recursive algorithms to draw recursive shapes

Write a nested loop to process a two-dimensional grid

I have written some code but I am having trouble getting it to produce a result in the turtle screen:

import turtle
from PIL import Image
kel = turtle.Turtle()

class Draw_pattern(object):
    def __init__(self,posx,posy,size):
        self.posx = posx
        self.posy = posy
        self.size = size

    def draw_grid(self,initx, inity):
        # Drawing grid
        kel.penup()
        kel.color("black")
        for i in range(7):
            kel.goto(self.posx, self.posy)
            kel.pendown()
            kel.forward(self.size*6)
            self.posy = self.posy+self.size;
            self.posx = initx;
            kel.penup()

        self.posx = initx;
        self.posy = inity;
        kel.left(90)
        for i in range(7):
            kel.goto(self.posx, self.posy)
            kel.pendown()
            kel.forward(self.size*6)
            self.posx = self.posx+self.size;
            self.posy = inity;
            kel.penup()

def draw_shape(self,initx, inity):
    self.posx = initx;
    self.posy = inity;
# Drawing yellow portion
    kel.penup()
    kel.goto(self.posx, self.posy)
    kel.pendown()
    kel.fillcolor("yellow")
    kel.begin_fill()
    kel.goto(self.posx, self.posy+self.size*6)
    kel.goto(self.posx+self.size*6, self.posy+self.size*6)
    kel.goto(self.posx+self.size*6, self.posy)
    kel.goto(self.posx, self.posy)
    kel.end_fill()

# Drawing red portion
    kel.penup()
    kel.goto(self.posx, self.posy+self.size*2)
    kel.pendown()
    kel.fillcolor("red")
    kel.begin_fill()
    kel.goto(self.posx+self.size, self.posy+self.size*3)
    kel.goto(self.posx, self.posy+self.size*4)
    kel.goto(self.posx+self.size*2, self.posy+self.size*4)
    kel.goto(self.posx+self.size*2, self.posy+self.size*6)
    kel.goto(self.posx+self.size*3, self.posy+self.size*5)
    kel.goto(self.posx+self.size*4, self.posy+self.size*6)
    kel.goto(self.posx+self.size*4, self.posy+self.size*4)
    kel.goto(self.posx+self.size*6, self.posy+self.size*4)
    kel.goto(self.posx+self.size*5, self.posy+self.size*3)
    kel.goto(self.posx+self.size*6, self.posy+self.size*2)
    kel.goto(self.posx+self.size*4, self.posy+self.size*2)
    kel.goto(self.posx+self.size*4, self.posy)
    kel.goto(self.posx+self.size*3, self.posy+self.size)
    kel.goto(self.posx+self.size*2, self.posy)
    kel.goto(self.posx+self.size*2, self.posy+self.size*2)
    kel.goto(self.posx, self.posy+self.size*2)
    kel.end_fill()

 # recursive function to draw repeating shape
def repeat_shape(self,intx, inty):
    if intx>=3 | inty>=3:
        return
    else:
        self.draw_shape(intx*180, inty*180)
        kel.right(90)
        self.repeat_shape(intx+1,inty)
        self.repeat_shape(intx,inty+1)

class image_play(object):
    def __init__(self,im_name):
        self.im_name = im_name

def rgb_to_gray_image(self):
    im = Image.open(self.im_name)
    im = im.convert('LA')

     # editing pixels of image to white
def loop_over_image(self):
    im = Image.open(self.im_name)
    width, height = im.size
    # nested loop over all pixels of image
    for i in range(width):
        for j in range(height):
            im[i][j] = 255;

kel.speed("fastest")

# object of class Draw_pattern
obj = Draw_pattern(0,0,30)
obj.draw_grid(0,0)
obj.repeat_shape(0,0)

AttributeErrorTraceback (most recent call last)
<ipython-input-14-8b7bbac27093> in <module>
    103 obj = Draw_pattern(0,0,30)
    104 obj.draw_grid(0,0)
--> 105 obj.repeat_shape(0,0)

AttributeError: 'Draw_pattern' object has no attribute 'repeat_shape'

Body:
I agree with the answer by @VasuDeo.S (+1) regarding your immediate problem.  However, I see some more subtle issues with your code:

When it comes to your grid, your instructions say, "write a nested
loop" but your two loops are sequential not nested.

When working with turtle, goto() is used for large jumps (and to get out of jams).  For smaller movements, we tend to use forward(), backward(), left() and right() otherwise there's no difference between using turtle and a conventional line drawing graphics package.

Your self.posx and self.posy instance variables serve no purpose beyond being convenient local variables.  They save no state that carries from one method to the other.  We can eliminate them as instance variables.

It seems odd to have your object's instance methods rely on the global turtle named 'kel' -- it would make more sense to pass a turtle to its constructor or have it create one of its own.

You can take more advantage of symmetry in your designs to reduce the amount of code you need to draw them.

I've addressed the above issues in my rework of your/Vasu's code below.  (I've left out your image code as that isn't currently active.)

from turtle import Screen, Turtle

class DrawPattern():
    def __init__(self, size):
        self.size = size

        self.turtle = Turtle()
        self.turtle.speed("fastest")

    def draw_grid(self, init_x, init_y):

        ''' Draw a grid '''

        self.turtle.penup()
        self.turtle.goto(init_x, init_y)

        for _ in range(2):
            for _ in range(7):

                self.turtle.pendown()
                self.turtle.forward(self.size * 6)
                self.turtle.backward(self.size * 6)
                self.turtle.left(90)
                self.turtle.penup()
                self.turtle.forward(self.size)
                self.turtle.right(90)

            self.turtle.right(90)
            self.turtle.forward(self.size)

    def repeat_shape(self, iter_x, iter_y):
        if iter_x < 3 > iter_y:
            self.draw_shape(iter_x * 180, iter_y * 180)
            self.turtle.right(90)
            self.repeat_shape(iter_x + 1, iter_y)
            self.repeat_shape(iter_x, iter_y + 1)

    def draw_shape(self, init_x, init_y):

        ''' Recursive method to draw repeating shape '''

        # Draw yellow portion
        self.turtle.penup()
        self.turtle.goto(init_x, init_y)
        self.turtle.setheading(90)
        self.turtle.pendown()

        self.turtle.fillcolor("yellow")
        self.turtle.begin_fill()

        for _ in range(4):
            self.turtle.forward(self.size * 6)
            self.turtle.right(90)

        self.turtle.end_fill()

        # Draw red portion
        self.turtle.penup()
        self.turtle.goto(init_x, init_y + self.size * 2)
        self.turtle.setheading(0)
        self.turtle.pendown()

        self.turtle.fillcolor("red")
        self.turtle.begin_fill()

        for _ in range(4):
            self.turtle.left(45)
            self.turtle.forward(42)
            self.turtle.left(90)
            self.turtle.forward(42)
            self.turtle.right(135)
            self.turtle.forward(self.size * 2)
            self.turtle.left(90)
            self.turtle.forward(self.size * 2)
            self.turtle.left(180)

        self.turtle.end_fill()

# object instance of class DrawPattern
obj = DrawPattern(30)
obj.draw_grid(-200, -200)
obj.repeat_shape(0, 0)

screen = Screen()
screen.exitonclick()


问:
How do you test an HTTP server running on a Compute Engine instance without exposing it to the public?
I am using a Compute Engine as my main development machine, I would like to start testing my application, however, if I assign it an external IP address then it will be open to the public web which is a privacy concern of mine.

Assuming that I will not be accessing this instance from the same IP address  every time, how can I go about being able to test HTTP requests for the development that I am doing?

答:
Your issue is that your IP address is not fixed.

The first method is to configure the Google VPC firewall to your current IP address. Then as you IP address changes, update the VPC firewall rule. This is the simplest method and only takes a minute or two but you must do this every time your address changes.

If your public IP address changes but is within a range then you can configure the firewall rule with a CIDR block instead of a single IP address.

The preferred method is to not assign the instance a public IP address. Install a VPN gateway in your VPC and the VPN client on your desktop. Your web browser and tools will then use the VPN to connect to the private IP address. Google Marketplace has free VPN software, such as OpenVPN which I use. You just pay for the instance time, which you can shut down when you don't need a VPN.

There are more sophisticated methods, such as token authorization, but this is overkill for web server testing.


答:
```<code>void readSensor(float* output) {
  float container[3] = {val1, val2, val3};
  output = container;
}
</code>```

Here you are creating an array container on the stack and initializing it, and assigning the address of its first element to output. You then destroy container when you reach the end of the function, and by the time the function returns, the array that output used to point to no longer exists.

j.doe's answer is one solution to this, but you have to be careful to ensure output already points to an array of sufficient size before assigning values to it. You could also consider looking into std::array or std::vector.

Title: cannot pass float array out of a function

Body:
I'm new to c++, and I want to pass a float array out of a function using a pointer. However, the returning array is always 0; I am running on an Arduino Uno.

This is my code. I want the readSensor() function to pass out a float array consisting of 3 floats. The float array should be pass to the pointer output*. But when I print out readings, it shows 0.00 instead of the values I passed out.

void setup() {
  Serial.begin(9600);
}

void loop() {
  float readings[3];
  readSensor(readings);
  for (int i = 0;i < 3;i++) {
    Serial.println(readings[i]);
  }
  delay(1000);
}

// pass out these 3 floats
float val1 = 3.14159;
float val2 = 2.741;
float val3 = 87;
void readSensor(float* output) {
  float container[3] = {val1, val2, val3};
  output = container;
}

Body:
void readSensor(float* output) {
  float container[3] = {val1, val2, val3};
  output = container;
}

Here you are creating an array container on the stack and initializing it, and assigning the address of its first element to output. You then destroy container when you reach the end of the function, and by the time the function returns, the array that output used to point to no longer exists.

j.doe's answer is one solution to this, but you have to be careful to ensure output already points to an array of sufficient size before assigning values to it. You could also consider looking into std::array or std::vector.


问:
GeoFirestore GeoFire dependency not allowing me to update Firebase
I am using Firebase and GeoFirestore. I want to update my Firebase pod, so I updated the GeoFirestore podspec dependency to 'Firebase', '~> 6.1.0'. However, Geofirestore has a Geofire dependancy which has a Firebase/Database (~>5.0) dependency. How can I get the latest Firebase with the 5.0 Geofire dependency?</p>

```<code>[!] CocoaPods could not find compatible versions for pod "Firebase/Database":
  In Podfile:
    Geofirestore (from `https://collinesmon@github.com/CollinEsmon/GeoFirestore-iOS.git`) was resolved to 1.0.0, which depends on
      GeoFire (~> 3.0) was resolved to 3.0.0, which depends on
        Firebase/Database (~> 5.0)

Specs satisfying the `Firebase/Database (~> 5.0)` dependency were found, but they required a higher minimum deployment target.
</code>```

答: I ended up just adding GeoFirestore and Geofire to my app manually instead of using cocoapods. That seemed to be the only solution for now.</p>

Body:
I am using Firebase and GeoFirestore. I want to update my Firebase pod, so I updated the GeoFirestore podspec dependency to 'Firebase', '~> 6.1.0'. However, Geofirestore has a Geofire dependancy which has a Firebase/Database (~>5.0) dependency. How can I get the latest Firebase with the 5.0 Geofire dependency?

[!] CocoaPods could not find compatible versions for pod "Firebase/Database":
  In Podfile:
    Geofirestore (from `https://collinesmon@github.com/CollinEsmon/GeoFirestore-iOS.git`) was resolved to 1.0.0, which depends on
      GeoFire (~> 3.0) was resolved to 3.0.0, which depends on
        Firebase/Database (~> 5.0)

Specs satisfying the `Firebase/Database (~> 5.0)` dependency were found, but they required a higher minimum deployment target.


问:
How do I fix "domainnsposixerrordomain code13 permission denied" runtime error in AWSCognito code?
I am getting a runtime error that says:

[NetworkInfo] Signal strength query returned error: Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied", descriptor:

in my code where the variable "task" is declared. I marked the line that generates the error with a comment.

```<code>let serviceConfiguration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)

//create a pool
let configuration: AWSCognitoIdentityUserPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "6n3mb6nu0ls9ttfapkl69uuvd3", clientSecret: "7vlgp2ip3ihov4on7n0v4sti88sj6tfsobqlop6qu5t3db07bo6", poolId: "us-east-1_d0Y5gS66r")

AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: configuration, forKey: "AlarmMusic")
pool = AWSCognitoIdentityUserPool(forKey: "AlarmMusic")

let alertMessage = "Please register in order to be able to use this app:"

let alertController = UIAlertController(title: "Register", message: alertMessage, preferredStyle: .alert)

alertController.addTextField(configurationHandler: nil)
alertController.addTextField(configurationHandler: nil)
alertController.addTextField(configurationHandler: nil)

let actionOK = UIAlertAction(title: "OK", style: .cancel) {
    action in

    var attributes = [AWSCognitoIdentityUserAttributeType]()

    let email: AWSCognitoIdentityUserAttributeType = AWSCognitoIdentityUserAttributeType(name: "email", value: alertController.textFields?[2].text ?? "olea.gnolaum@gmail.com")

    attributes.append(email)

    let task: AWSTask<AWSCognitoIdentityUserPoolSignUpResponse> = self.pool.signUp(alertController.textFields?[0].text ?? "dbrower", password: alertController.textFields?[1].text ?? "Password@1989", userAttributes: attributes, validationData: nil).continueOnSuccessWith( block: {_ in return nil }) as! AWSTask<AWSCognitoIdentityUserPoolSignUpResponse> // ERROR OCCURS HERE!

    print("task=", task)

    let signUpResponse: AWSCognitoIdentityUserPoolSignUpResponse? = task.result

    print("signUpResponse=", signUpResponse as Any)

    let user: AWSCognitoIdentityUser? = signUpResponse?.user

    print("user=", user as Any)

}

alertController.addAction(actionOK)

self.present(alertController, animated: true, completion: nil)
</code>```

Here are the results in the debug window of the print statements:

task=

signUpResponse= nil

user= nil

I checked my user pool in AWS Cognito Console. It all checks out. I provided all the required information the user pool requires.

Here's a screenshot of the pool:

What is the cause of this error, and what do I need to look into in order to fix it?

答:
Here's a small example of how to get the user from Cognito.</p>

```<code>private func registerNewUser() {
  let userPool = ...
  let email = ...
  let password = ...
  let emailAttribute = AWSCognitoIdentityUserAttributeType(name: "email", value: email)
  let attributes:[AWSCognitoIdentityUserAttributeType] = [emailAttribute]

  userPool.signUp(email, password: password, userAttributes: attributes, validationData: nil).continueWith { (response) -> Any? in
    if response.error != nil {
      DispatchQueue.main.async {
        let alert = UIAlertController(title: "Error", message: (response.error! as NSError).userInfo["message"] as? String, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler:nil))
        self.present(alert, animated: true, completion: nil)
      }
    } else {
      self.user = response.result!.user
    }
    return nil
  }
}
</code>```

Body:
I am getting a runtime error that says:

[NetworkInfo] Signal strength query returned error: Error Domain=NSPOSIXErrorDomain Code=13 "Permission denied", descriptor:

in my code where the variable "task" is declared. I marked the line that generates the error with a comment.

let serviceConfiguration: AWSServiceConfiguration = AWSServiceConfiguration(region: .USEast1, credentialsProvider: nil)

//create a pool
let configuration: AWSCognitoIdentityUserPoolConfiguration = AWSCognitoIdentityUserPoolConfiguration(clientId: "6n3mb6nu0ls9ttfapkl69uuvd3", clientSecret: "7vlgp2ip3ihov4on7n0v4sti88sj6tfsobqlop6qu5t3db07bo6", poolId: "us-east-1_d0Y5gS66r")

AWSCognitoIdentityUserPool.register(with: serviceConfiguration, userPoolConfiguration: configuration, forKey: "AlarmMusic")
pool = AWSCognitoIdentityUserPool(forKey: "AlarmMusic")

let alertMessage = "Please register in order to be able to use this app:"

let alertController = UIAlertController(title: "Register", message: alertMessage, preferredStyle: .alert)

alertController.addTextField(configurationHandler: nil)
alertController.addTextField(configurationHandler: nil)
alertController.addTextField(configurationHandler: nil)

let actionOK = UIAlertAction(title: "OK", style: .cancel) {
    action in

    var attributes = [AWSCognitoIdentityUserAttributeType]()

    let email: AWSCognitoIdentityUserAttributeType = AWSCognitoIdentityUserAttributeType(name: "email", value: alertController.textFields?[2].text ?? "olea.gnolaum@gmail.com")

    attributes.append(email)

    let task: AWSTask<AWSCognitoIdentityUserPoolSignUpResponse> = self.pool.signUp(alertController.textFields?[0].text ?? "dbrower", password: alertController.textFields?[1].text ?? "Password@1989", userAttributes: attributes, validationData: nil).continueOnSuccessWith( block: {_ in return nil }) as! AWSTask<AWSCognitoIdentityUserPoolSignUpResponse> // ERROR OCCURS HERE!

    print("task=", task)

    let signUpResponse: AWSCognitoIdentityUserPoolSignUpResponse? = task.result

    print("signUpResponse=", signUpResponse as Any)

    let user: AWSCognitoIdentityUser? = signUpResponse?.user

    print("user=", user as Any)

}

alertController.addAction(actionOK)

self.present(alertController, animated: true, completion: nil)

Here are the results in the debug window of the print statements:

task=

signUpResponse= nil

user= nil

I checked my user pool in AWS Cognito Console. It all checks out. I provided all the required information the user pool requires.

Here's a screenshot of the pool:

What is the cause of this error, and what do I need to look into in order to fix it?

Body:
Here's a small example of how to get the user from Cognito.

private func registerNewUser() {
  let userPool = ...
  let email = ...
  let password = ...
  let emailAttribute = AWSCognitoIdentityUserAttributeType(name: "email", value: email)
  let attributes:[AWSCognitoIdentityUserAttributeType] = [emailAttribute]

  userPool.signUp(email, password: password, userAttributes: attributes, validationData: nil).continueWith { (response) -> Any? in
    if response.error != nil {
      DispatchQueue.main.async {
        let alert = UIAlertController(title: "Error", message: (response.error! as NSError).userInfo["message"] as? String, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "OK", style: .default, handler:nil))
        self.present(alert, animated: true, completion: nil)
      }
    } else {
      self.user = response.result!.user
    }
    return nil
  }
}


问:
Comparing two columns in a pandas DataFrame and filling in missing values for one of them
I have a Frame with 2 columns with missing values:

```<code>   name   code
0   A      12
1   B      39
2   C      23
3   A      12
4   NaN    12
5   NaN    39
6   C      23
7   NaN    39
</code>```

I need to fill the missing value as follows:

```<code>   name   code
0   A      12
1   B      39
2   C      23
3   A      12
4   A      12
5   B      39
6   C      23
7   B      39
</code>```

答:
Generate a reverse mapping of codes to non-null names, then use that to map missing values back:

```<code>mapping = dict(df.dropna()[['code', 'name']].values)
# mapping = df.set_index('code')['name'].dropna().to_dict()

df['name'] = df['name'].fillna(df['code'].map(mapping))
df

  name  code
0    A    12
1    B    39
2    C    23
3    A    12
4    A    12
5    B    39
6    C    23
7    B    39
</code>```

You can perform an in-place update as well.

```<code>df['name'].update(df['code'].map(mapping))
df

  name  code
0    A    12
1    B    39
2    C    23
3    A    12
4    A    12
5    B    39
6    C    23
7    B    39
</code>```

Body:
I have a Frame with 2 columns with missing values:

   name   code
0   A      12
1   B      39
2   C      23
3   A      12
4   NaN    12
5   NaN    39
6   C      23
7   NaN    39

I need to fill the missing value as follows:

   name   code
0   A      12
1   B      39
2   C      23
3   A      12
4   A      12
5   B      39
6   C      23
7   B      39

Body:
Generate a reverse mapping of codes to non-null names, then use that to map missing values back:

mapping = dict(df.dropna()[['code', 'name']].values)
# mapping = df.set_index('code')['name'].dropna().to_dict()

df['name'] = df['name'].fillna(df['code'].map(mapping))
df

  name  code
0    A    12
1    B    39
2    C    23
3    A    12
4    A    12
5    B    39
6    C    23
7    B    39

You can perform an in-place update as well.

df['name'].update(df['code'].map(mapping))
df

  name  code
0    A    12
1    B    39
2    C    23
3    A    12
4    A    12
5    B    39
6    C    23
7    B    39


问:
How can a local std::bernoulli_distribution create accurately distributed data?
Here, I have a class Generator that has a random number engine and a method genTrial() that's supposed to return a bool representing the "success" or "failure" outcome of an independent trial. Using the std::bernoulli_distribution, I can assign the probability of getting a "success"; notice that this variable is local to genTrial().

In the main code, I am generating 30,000 trials by repeatedly calling genTrial() with a success parameter of 25% in the loop. When the code runs, the distribution is correct.

My question is: Since the std::bernoulli_distribution variable is local, how does it know/remember the state of the distribution in order to still generate a correct data set? If a new variable is created/destroyed every iteration, there's no persistence of state and no way to know what's been done in the past, so how does it determine where to put the fed in number? Shouldn't it put the numbers in the same set?

generator.h

#ifndef GENERATOR_H
#define GENERATOR_H

#include <random>

class Generator
{
    private:
        static std::mt19937 randEngine;

    public:
        bool genTrial(double success);
};

#endif
```

<p><strong>generator.cpp</strong></p>

<pre class="lang-cpp prettyprint-override"><code>#include "generator.h"
#include <cstdlib>
#include <random>

std::mt19937 Generator::randEngine(0);

bool Generator::genTrial(double success)
{
    std::bernoulli_distribution distrib(success);
    return distrib(randEngine);
}
</code>```

main.cpp

#include "generator.h"
#include <iostream>

int main()
{
    const int NUM_SAMPLES = 30000;
    const int NUM_OF_BINARY_VALUES = 2;
    const double SUCCESS_RATE = 0.25;

    Generator gen;
    int binaryRecord[NUM_OF_BINARY_VALUES] = {0};

    // "roll the dice"
    for(int x = 0; x < NUM_SAMPLES; x++)
    {
        bool thisRoll = gen.genTrial(SUCCESS_RATE);
        if(thisRoll == true) binaryRecord[1]++;
        else binaryRecord[0]++;
    }

    // draw the results
    for(int y = 0; y < NUM_OF_BINARY_VALUES; y++)
    {
        if(y == 0) std::cout << "[F]: ";
        else std::cout << "[T]: ";

        int numActualTallies = binaryRecord[y];
        int numDisplayedTallies = numActualTallies / 1000;
        for(int i = 0; i < numDisplayedTallies; i++)
        {
            std::cout << "*";
        }
        std::cout << "\n";
    }
    return 0;
}
```

答:
The only state that std::bernoulli_distribution holds is the p distribution parameter that was used during construction. It doesn't need to remember previously output values to output the next value with the correct distribution. For example, it can generate a random double from the given random engine and return true if the value is less than p.

Your function constructs a new distribution each time it's called and passes the same p parameter value SUCCESS_RATE. You could rewrite your code to only construct distrib once. That might be more efficient than constructing it each time but the result would be the same, a stream of bool values with true appearing 25% of the time.

Body:
Here, I have a class Generator that has a random number engine and a method genTrial() that's supposed to return a bool representing the "success" or "failure" outcome of an independent trial. Using the std::bernoulli_distribution, I can assign the probability of getting a "success"; notice that this variable is local to genTrial().

In the main code, I am generating 30,000 trials by repeatedly calling genTrial() with a success parameter of 25% in the loop. When the code runs, the distribution is correct.

My question is: Since the std::bernoulli_distribution variable is local, how does it know/remember the state of the distribution in order to still generate a correct data set? If a new variable is created/destroyed every iteration, there's no persistence of state and no way to know what's been done in the past, so how does it determine where to put the fed in number? Shouldn't it put the numbers in the same set?

generator.h

#ifndef GENERATOR_H
#define GENERATOR_H

#include <random>

class Generator
{
    private:
        static std::mt19937 randEngine;

    public:
        bool genTrial(double success);
};

#endif

generator.cpp

#include "generator.h"
#include <cstdlib>
#include <random>

std::mt19937 Generator::randEngine(0);

bool Generator::genTrial(double success)
{
    std::bernoulli_distribution distrib(success);
    return distrib(randEngine);
}

main.cpp

#include "generator.h"
#include <iostream>

int main()
{
    const int NUM_SAMPLES = 30000;
    const int NUM_OF_BINARY_VALUES = 2;
    const double SUCCESS_RATE = 0.25;

    Generator gen;
    int binaryRecord[NUM_OF_BINARY_VALUES] = {0};

    // "roll the dice"
    for(int x = 0; x < NUM_SAMPLES; x++)
    {
        bool thisRoll = gen.genTrial(SUCCESS_RATE);
        if(thisRoll == true) binaryRecord[1]++;
        else binaryRecord[0]++;
    }

    // draw the results
    for(int y = 0; y < NUM_OF_BINARY_VALUES; y++)
    {
        if(y == 0) std::cout << "[F]: ";
        else std::cout << "[T]: ";

        int numActualTallies = binaryRecord[y];
        int numDisplayedTallies = numActualTallies / 1000;
        for(int i = 0; i < numDisplayedTallies; i++)
        {
            std::cout << "*";
        }
        std::cout << "\n";
    }
    return 0;
}