text:
Q: SPRING BOOT infinite recursion I have two entitys, Student and Subject. This two class have a many to many relationship. The thing is when i try to link a Subject with Student, not work give me a error. Looks like infinite recursion issue.
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy="students", fetch = FetchType.LAZY)
    @JsonIgnore
    private Set<Subject> subjects;

    @ManyToMany(mappedBy="students")
    @JsonIgnore
    private Set<Exam> exams;

    public boolean addSubject(Subject subject){
        return subjects.add(subject);
    }
}

@Entity
@Data
@NoArgsConstructor
public class Subject {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "Subjects_Students",
            joinColumns = @JoinColumn(name = "subject_id"),
            inverseJoinColumns = @JoinColumn(name = "student_id"))
    @JsonIgnore
    private Set<Student> students;

    @OneToMany(mappedBy="subject")
    @JsonIgnore
    private Set<Exam> exams;

    @ManyToOne()
    @JoinColumn(name="teacher_id")
    @JsonIgnore
    private Teacher teacher;

    public boolean addStudent(Student student) {
        return students.add(student);
    }
}

the methodo i use int the service is:
@PostMapping("/{studentId}/subject/{subjectId}")
public ResponseEntity<Student> addSubject(@PathVariable Long studentId, @PathVariable Long subjectId ){
    return studentService.addSubject(studentId,subjectId);
}

And the error:
Hibernate: select subjects0_.student_id as student_2_4_0_, subjects0_.subject_id as subject_1_4_0_, subject1_.id as id1_3_1_, subject1_.name as name2_3_1_, subject1_.teacher_id as teacher_3_3_1_, teacher2_.id as id1_5_2_, teacher2_.name as name2_5_2_ from subjects_students subjects0_ inner join subject subject1_ on subjects0_.subject_id=subject1_.id left outer join teacher teacher2_ on subject1_.teacher_id=teacher2_.id where subjects0_.student_id=?
Please help me, this is driving creazy

A: Try exclude hash code method auto generated by Lombok @Data annotation:
@EqualsAndHashCode(exclude = { "subjects" })
public class Student {

    @ManyToMany(mappedBy="students", fetch = FetchType.LAZY)
    @JsonIgnore
    private Set<Subject> subjects;
}

@EqualsAndHashCode(exclude = { "students" })
public class Subject {

    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "Subjects_Students",
            joinColumns = @JoinColumn(name = "subject_id"),
            inverseJoinColumns = @JoinColumn(name = "student_id"))
    @JsonIgnore
    private Set<Student> students;
}

A: You can use @JsonIgnoreProperties({<entity_class_name>}) to skip the recursive call.
On student class
@Data
@NoArgsConstructor
@AllArgsConstructor
@Entity
@JsonIgnoreProperties({"Subject"})
public class Student {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    private String name;

    @ManyToMany(mappedBy="students", fetch = FetchType.LAZY)
    @JsonIgnore
    private Set<Subject> subjects;

    @ManyToMany(mappedBy="students")
    @JsonIgnore
    private Set<Exam> exams;

    public boolean addSubject(Subject subject){
        return subjects.add(subject);
    }
}

and on subject class
@Entity
@Data
@NoArgsConstructor
@JsonIgnoreProperties({"Student"})
public class Subject {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    private String name;
    @ManyToMany(fetch = FetchType.LAZY)
    @JoinTable(
            name = "Subjects_Students",
            joinColumns = @JoinColumn(name = "subject_id"),
            inverseJoinColumns = @JoinColumn(name = "student_id"))
    @JsonIgnore
    private Set<Student> students;

    @OneToMany(mappedBy="subject")
    @JsonIgnore
    private Set<Exam> exams;

    @ManyToOne()
    @JoinColumn(name="teacher_id")
    @JsonIgnore
    private Teacher teacher;

    public boolean addStudent(Student student) {
        return students.add(student);
    }
}


text:
Q: mysql update user's password and activation key Instead of using the Default WP reset password form, I'm creating my own and I'm stumped on this prepared statement.
I'm trying to update the user's password by checking their user_login and user_activation_key.
When I run this query and echo the result, I'm getting a return of int(0). It seems like it's not returning any row of the user.
I also echo each POST variables to make sure it's the values are correct and it is so I'm not sure where the problem lies.
$newpassword = $_POST['newpass'];
$wp_hasher = new PasswordHash(16, FALSE);
$hashedPwd = wp_hash_password($newpassword);

$useremail = $_POST['useremail'];
$key = $_POST['key'];

$resetQuery = $wpdb -> query($wpdb -> prepare("UPDATE wp_users SET user_pass = %s, user_activation_key = '' WHERE user_login = %s AND user_activation_key = %s",
                                                $hashedPwd, $useremail, $key));

If anyone can please help me, that would be great!
Thanks.

A: You are using the user email as the user login. Your code, formatted for readability, looks like:
$resetQuery = $wpdb -> query(
  $wpdb -> prepare(
    "UPDATE wp_users
    SET user_pass = %s, user_activation_key = ''
    WHERE user_login = %s AND user_activation_key = %s",
    $hashedPwd,
    $useremail,
    $key
  )
);

The $useremail argument matches the user_login = %s placeholder.
Having the user_login match user_email is not normal. Unless you have altered your user registration so that the login always matches the email that isn't going to work, and I suspect that that is your problem. You need to rewrite the query, and/or supporting code, so that either the query matches user_login to user_login or user_email to user_email.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Accessing a Spreadsheet in Google Drive I have a Spreadsheet stored a few directories into my Google Drive that I'd like to access and read with the Google Spreadsheet API using Python. What is the best way to do this? It seems like all of the examples on the Google API website involve documents that are in Google Docs, not Google Drive, and it seems like none of the examples for the Google Drive API involve reading spreadsheets.

A: You can either use the Spreadsheets API or Apps Script to programmatically access spreadsheets stored on your Drive account.

A: link = https://docs.google.com/spreadsheets/d/...source = StringIO.StringIO(requests.get(link).content))
data = pd.read_csv(source)


text:
Q: For what values of x is $|x(1-x)| < 1$?
The series is:
  $$\sum_{n=1}^{\infty} \frac{x^n(1-x)^n}{n}$$

I used the ratio test to try and find the range of values of $x$ for which a series converges, and am stuck with
$$|x(1-x)| < 1.$$
The obvious values are $0$ and $1$.
What about the rest?
I tried:
$-1<x(1-x)<1 = -1<x-x^2<1,$ which isn't helpful.
Or $|x(1-x)| < 1$ if and only if $x^2(1-x)^2<1$, which just gives me a tricky quadratic polynomial to work with, so I feel I'm no better off.
Any ideas are welcome.
Thanks,

A: HINT: Draw the polynomial $y=x-x^2$, then draw the absolute value of it (this will simply flip the negative parts across the $x-$axis), then draw the line $y=1$. The values of $x$ where the former graph is below the line will be your answer.

A: $$\begin{align}
-1\lt x-x^2\lt1\\
\therefore x^2-x-1&\lt0\text{ or}&&x^2-x+1&&&>0\\
\therefore \left(x-\frac{1}{2}\right)^2-\frac{5}{4}&\lt0\text{ or}&&\left(x-\frac{1}{2}\right)^2+\frac{3}{4}&&&\gt0\\
\therefore \left(x-\frac{1}{2}\right)^2&\lt\frac{5}{4}\text{ or}&&\left(x-\frac{1}{2}\right)^2&&&\gt-\frac{3}{4}\\
\therefore -\frac{\sqrt{5}}{2}\lt x-\frac{1}{2}\lt\frac{\sqrt{5}}{2}\text{ or}&&-\frac{i\sqrt{3}}{2}\lt x-\frac{1}{2}\lt\frac{i\sqrt{3}}{2}\\
\end{align}$$
If $x$ is restricted to reals then we have:$$\frac{1-\sqrt{5}}{2}\lt x\lt\frac{1+\sqrt{5}}{2}$$

A: I'd start with finding the values where it is equal to 1.
$$|x(1-x)|=1$$
splitting cases:
$$
\begin{array}{rl|rl}
x-x^2&=-1 & x-x^2&=1\\
x^2-x-1&=0 & x^2-x+1&=0 \\
x_{1,2} &= \frac{1}{2}\pm\sqrt{\frac{1}{4}+1} & x_{3,4} &= \frac{1}{2}\pm
\sqrt{\frac{1}{4}-1}\\
x_{1,2} &\in\mathbb{R}& x_{3,4}&\in\mathbb{C}\\
\end{array}
$$
$x_{1,2}$ are of further interest. The polynomial is a parabola that is open to the bottom. It is shaped like a mountain, not a valley. If you go to either $\pm\infty$ the value will go towards $-\infty$. Hence the values outside the interval1 $(x_{1},x_2)$  cannot have an absolute value smaller than 1.

1 I think some use this notation $]x_{1},x_2[$ to denote that the interval of valid does not contain the boundaries $x_1$ and $x_2$ ,


text:
Q: Displaying two values on the same row in a listview I'd like to be able to display the name and price of the product on the same line. Right now, it's displayed as:
Product name
Product price
I've tried adding a linearlayout with the orientation horizontal, tried using weightsum / weight and can't figure out how to make it show properly, like in a normal menu, with the name at the left and the price at the right. I also tried setting their gravity, but it always displays them on two rows. I'd like to display them as such:
Product name...........................Product Price
The layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:orientation="vertical"
 android:layout_height="fill_parent"
 android:layout_width="fill_parent"
 android:background="#ffffff">

  <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

  <TextView
        android:id="@+id/Price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"

        />
  <LinearLayout
      android:id="@+id/LinearLayout01"
      android:layout_width="wrap_content"
      android:layout_height="fill_parent"
      android:orientation="horizontal" >

      <Button
          android:id="@+id/Remove"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_gravity="bottom|center"
          android:text="Remove product(s)" />

      </LinearLayout>

</LinearLayout>

How I'm adding the items:
oslist = new ArrayList<HashMap<String, String>>();

  HashMap<String, String> map = new HashMap<String, String>();
  map.put(PROD_NAME, name);
  map.put(PROD_PRICE, price);
  oslist.add(map);

   adapter = new SimpleAdapter(shopping_cart.this, oslist,
            R.layout.shoppingcart,
            new String[] {PROD_NAME, PROD_PRICE}, new int[] {R.id.name, R.id.Price});
    setListAdapter(adapter);

A: It's often easier to create a layout like this using a RelativeLayout as it gives you more control over the placement of views. You would give the name element layout_alignParentLeft="true" and the price element layout_alignParentRight="true" (and probably layout_gravity="right" to right align the text).
EDIT
Here's what your XML might look like. You won't actually need the layout_gravity attribute if you are using layout_width="wrap_parent", and I've omitted the remove button because I'm not sure where you want it to be.
This layout allows the name and price to overlap if they are too long - probably the best option to fix that is to put the name element after the price element in the XML and add layout_toLeftOf="@id/Price" to it. That forces it to wrap the name instead of overlap the price.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_height="fill_parent"
 android:layout_width="fill_parent"
 android:background="#ffffff">

  <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        />

  <TextView
        android:id="@+id/Price"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        />

</RelativeLayout>


text:
Q: React Router V4 Implement NavLink inside a ListItem using Material UI I am new to React and I created a simple application with Login and Dashboard page. I have successfully configured my Public Routes and Private Routes with Redirect functionalities. However when I want to implement material-ui/core Things are still quite working well but I can't achieve the UI that I want.
Here is my old implementation of my NavBar below:
const Navigation = () => {
    return (

            <NavLink exact to="/" activeStyle={{ color: 'red' }}>Home</NavLink>
            <NavLink to="/about" activeStyle={{ color: 'red' }}>About</NavLink>
            <NavLink to="/contact" activeStyle={{ color: 'red' }}>Contact</NavLink>

    )
}

export default Navigation

As simple as that with no styling or classes
But since I want to add some styles I used material/ui core and ended up doing the new one below:
export const MainNavigation = (

    <ListItem button>
      <ListItemIcon>
        <DashboardIcon />
      </ListItemIcon>
      <ListItemText primary="Dashboard" />
    </ListItem>
    <ListItem button>
      <ListItemIcon>
        <ShoppingCartIcon />
      </ListItemIcon>
      <ListItemText primary="Orders" />
    </ListItem>
    <ListItem button>
      <ListItemIcon>
        <PeopleIcon />
      </ListItemIcon>
      <ListItemText primary="Customers" />
    </ListItem>
    <ListItem button>
      <ListItemIcon>
        <BarChartIcon />
      </ListItemIcon>
      <ListItemText primary="Reports" />
    </ListItem>
    <ListItem button>
      <ListItemIcon>
        <LayersIcon />
      </ListItemIcon>
      <ListItemText primary="Integrations" />
    </ListItem>

);

Now the first ListItem looks like this below:

But when I add this line of code below:
<ListItemText primary={<NavLink exact to="/">Dashboard</NavLink>} />

This is the result:

But I don't want this to happen.
I want to keep the first UI I dont wan't it to make it look like an anchor tag with a under line below
How can I also handle the active state of the ListItem in material/ui integrated with react router NavLink or Link? So that I can put some style or uses the active class of material.
Appreciate if someone could help.
Thanks in advance.

A: You can do it by setting the NavLink as the component of the list item. Here is an example that has worked for me!
<ListItem
  button
  key="Dashboard"
  component={NavLink} to="/dashboard"
>
    <ListItemIcon>
        <Dashboard />
    </ListItemIcon>
    <ListItemText primary="Dashboard" />
</ListItem>

Hope it helps!

A: Use the component prop of ListItem. To get active route styling, set activeClassName of NavLink to Mui-selected.
<ListItem button component={NavLink} to="/" activeClassName="Mui-selected" exact>
  ...
</ListItem>


text:
Q: AppKit thread-safe or not? Can you explain me is AppKit thread-safe or not? Where can I read about it? (Except Threaded Programming Guide because this documentation creates more question instead answers). For example can I validateVisibleItems of NSToolbar in separated thread? Or can I increment value of NSProgressIndicator in second thread?

A: No, it is not in general.  You should not send messages to any UI objects except from the main thread.
In the specific example you give, you can use performSelectorOnMainThread:withObject:waitUntilDone: to get around the restriction:
[myToolbar performSelectorOnMainThread: @selector(validateVisibleItems)
                            withObject: nil
                         waitUntilDone: whatever];


text:
Q: Algorithm complexity I got this problem "Implement this method to return the sum of the two largest numbers in a given array."
I resolved it in this way:
 public static int sumOfTwoLargestElements(int[] a) {

     int firstLargest = largest(a, 0, a.length-1);

     int firstLarge =  a[firstLargest];
     a[firstLargest] = -1;

     int secondLargest = largest(a, 0, a.length-1);

     return firstLarge + a[secondLargest];
}

private static int largest(int s[], int start , int end){

    if (end - start == 0){

        return end;
    }

   int a = largest(s, start, start + (end-start)/2) ;
   int b = largest(s, start + (end-start)/2+1 , end);
    if(s[a] > s[b]) {

       return a;
    }else {

      return b;
    }

}

Explanation: I implemented a method 'largeset'. This method is responsible to get the largest number in a given array.
I call the method tow times in the same array. The first call will get the first largest number.I put it aside into variable and i replace it by '-1' number into the array. Then, i call the largest medhod second time.
Some one can tell me what is the complexity of this algo? please

A: The complexity of the algorithm would be measured as O(n).
But the real answer is that your algorithm is WAY more complex, and more expensive in terms of machine resources than it needs to be. And it's WAY more expensive in terms of someone reading your code and figuring out what it's doing.
The complexity of your algorithm should really be on the order of:
public static int sumOfTwoLargestElements(int[] a) {

    //TODO handle case when argument is null,
    //TODO handle case when array has less than two non-null elements, etc.

    int firstLargest = Integer.MIN_VALUE;
    int secondLargest = Integer.MIN_VALUE;
    for (int v : a) {
        if ( v > firstLargest ) {
            secondLargest = firstLargest;
            firstLargest = v;
        } else if ( v > secondLargest ) secondLargest = v;
    }
    //TODO handle case when sum exceeds Integer.MAX_VALUE;
    return firstLargest + secondLargest;
}

A: The time complexity of the algorithm is O(n).
Each recursive call's complexity is actually:
f(n) = 2*f(n/2) + CONST

It is easy to see (by induction1) that f(n) <= CONST'*n - and thus it is O(n).
The space complexity is O(logN) - because this is the maximal depth of the recursion - so you allocate O(logN) memory on the call stack.

(1)
If you use f(n) = 2*n*CONST - CONST you get:
f(n) = 2*f(n/2) + CONST = (h.i.) 2*(2*CONST*n/2 - CONST) + CONST =
=  2*n*CONST - 2CONST + CONST = 2*n*CONST - CONST

(Checking the base is is left as exercise for the reader)

A: The reccurence for 'Largest' method is:
        _
f(n) = !
       !  1        n = 1
       !  2f(n/2)  n >=2
       !_

If we experiment some few cases, we notice that

f(n) = 2^log(n)   When n is power of 2       Rq:Log base 2

Proof:

By induction,

f(1) = 2^log(1) = 2^log(2^0) = 1

We suppose that f(n) = 2^log(n)=n

We show f(2n) = 2^log(2n)= 2n^log(2)=2n

f(2n) = 2*f(2n/2) = 2*f(n)
                  = 2*2^log(n)
                  = 2^log(n) + 1
                  = 2^log(n) + log(2^0)
                  = 2^log(2n)
                  = 2n^log(2)  by log properties
                  = 2n
Then f(n) = 2^log(n)=n  When n is power of2-smooth function f(2n) < c f(n). it follows smooth function properties that **f(n) = theta of n**


text:
Q: running two ionic 3 apps on the same device The issue can be replicated with the tutorial templates. I installed the blank and sidemenu templates using the CLI: ionic start First blank and ionic start Second sidemenu. If you build and put them on a device the following problem occurs.
The problem occurs only on iOS. If you start one of them, when you minimize it (by pushing the phone button), if you immediately start the 2nd app (in the first 5 seconds after you minimized the 1st app - i think it's because of the iOS app lifecycle that sends the app to background after 5s) then the 2nd app starts the first app. But if you wait 5 seconds after minimizing the first app and then start the second app then it works, the second app actually starts.
I tested this on ionic 3.9.2
a) Ionic CLI 3.20.0, Cordova CLI 8.0.0, Node 8.11.1, npm 5.6.0, windows 10
b) Ionic CLI 3.20.0, Cordova CLI 8.1.1, Node 8.11.2, npm 6.4.1, macOS Sierra
Is there a solution for this? Can I have two Ionic 3 apps installed on the same iOS device and when I minimize the first one if I immediately start the second one it will actually start the second one and not the first? What can I do? What options do I have?
Thank you.


text:
Q: Vertical margins within a nested divs aren't working as expected Why is the margin on the content div pushing down the intro div as well? I feel like I made a really silly mistake when nesting the divs, but I really have no idea.

body {
  margin: 0px;
}
div.content {
  text-align: center;
  margin-top: 35px;
  border-style: solid;
}
h1 {
  display: inline-block;
  margin: auto;
  font-family: Lane;
  color: white;
  font-size: 80px;
}
div#intro {
  background: blue;
  height: 100%;
  width: 100%;
}

Text

A: This is occurring because the vertical margins are collapsing.

Box Model 8.3.1 Collapsing margins
In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.
When two or more margins collapse, the resulting margin width is the maximum of the collapsing margins' widths. In the case of negative margins, the maximum of the absolute values of the negative adjoining margins is deducted from the maximum of the positive adjoining margins. If there are no positive margins, the maximum of the absolute values of the adjoining margins is deducted from zero.

Take a look at the relevant spec to see the rules that apply for all the possible workarounds.
For instance, one rule is:

Margins of elements that establish new block formatting contexts (such as floats and elements with overflow other than visible) do not collapse with their in-flow children.

Therefore, in your case, you can simply change the overflow property on the #intro element to something other than the default value of visible. Values such as auto/hidden would work:

body {
  margin: 0px;
}
div#intro {
  background: blue;
  height: 100%;
  width: 100%;
  overflow: auto;
}
div.content {
  text-align: center;
  margin-top: 35px;
  border-style: solid;
}
h1 {
  display: inline-block;
  margin: auto;
  font-family: Lane;
  color: white;
  font-size: 80px;
}

Text

A: With the "Text" inside both divs, they might as well be one single div.  Also, that "body" style means nothing if you don't use the  and  tags.  More complete HTML might help us give you a solution.


text:
Q: Update all instances of key inside nested JSON array I'm trying to update a complex JSON document stored in a table in CockroachDB.
The CockroachDB query language is mostly Postgres compatible except for the lack of procedural code, so a Postgres answer without user functions or explicit loops will most likely work. The below sample code is also Postgres-compatible.
Among other things that make the document complex are that it contains nested arrays and some redundant structures.
The table and document are similar to the following:
  table_name |                      create_statement
-------------+--------------------------------------------------------------
  foo        | CREATE TABLE public.foo (
                 id INT8 NOT NULL,
                  data JSONB NOT NULL
              );

> insert into foo (id, data)
values(1, '{
    "foo": {
        "bar": {
            "bar": [
                {
                    "fields": [
                        {
                            "things": [],
                            "key": "something",
                            "value": ""
                        },
                        {
                            "things": [],
                            "key": "somethingelse",
                            "value": "1"
                        },
                        {
                            "things": [],
                            "key": "color",
                            "value": "pink"
                        }
                    ]
                },
                {
                    "id": "ALL",
                    "fields": [
                          {
                            "things": [],
                            "key": "something",
                            "value": ""
                        },
                        {
                            "things": [],
                            "key": "somethingelse",
                            "value": "1"
                        },
                        {
                            "things": [],
                            "key": "color",
                            "value": "white"
                        }
                    ]
                },
                {
                    "id": "1",
                    "fields": [
                          {
                            "things": [],
                            "key": "something",
                            "value": ""
                        },
                        {
                            "things": [],
                            "key": "somethingelse",
                            "value": "1"
                        },
                        {
                            "things": [],
                            "key": "color",
                            "value": "green"
                        }
                    ]
                },
                {
                    "id": "ALL",
                    "fields": [
                                            {
                            "things": [],
                            "key": "something",
                            "value": ""
                        },
                        {
                            "things": [],
                            "key": "somethingelse",
                            "value": "1"
                        },
                        {
                            "things": [],
                            "key": "color",
                            "value": "red"
                        }
                    ]
                }
            ]
        }
    }
}');

> select jsonb_pretty(data) from foo;
                     jsonb_pretty
-------------------------------------------------------
  {
      "foo": {
          "bar": {
              "bar": [
                  {
                      "fields": [
                          {
                              "key": "something",
                              "things": [],
                              "value": ""
                          },
                          {
                              "key": "somethingelse",
                              "things": [],
                              "value": "1"
                          },
                          {
                              "key": "color",
                              "things": [],
                              "value": "pink"
                          }
                      ]
                  },
                  {
                      "fields": [
                          {
                              "key": "something",
                              "things": [],
                              "value": ""
                          },
                          {
                              "key": "somethingelse",
                              "things": [],
                              "value": "1"
                          },
                          {
                              "key": "color",
                              "things": [],
                              "value": "white"
                          }
                      ],
                      "id": "ALL"
                  },
                  {
                      "fields": [
                          {
                              "key": "something",
                              "things": [],
                              "value": ""
                          },
                          {
                              "key": "somethingelse",
                              "things": [],
                              "value": "1"
                          },
                          {
                              "key": "color",
                              "things": [],
                              "value": "green"
                          }
                      ],
                      "id": "1"
                  },
                  {
                      "fields": [
                          {
                              "key": "something",
                              "things": [],
                              "value": ""
                          },
                          {
                              "key": "somethingelse",
                              "things": [],
                              "value": "1"
                          },
                          {
                              "key": "color",
                              "things": [],
                              "value": "red"
                          }
                      ],
                      "id": "ALL"
                  }
              ]
          }
      }
  }

How do I set the value for all instances of the key named color to an empty string ("")? The syntax for handling this on nested arrays eludes me.

A: This former question should be of help as well as the official CockroachDB doc for handling JSON. Here's an example of changing key values for an array of JSON objects, though nested arrays may require a bit more work.
SELECT jsonb_agg(updated_jsonb)
    FROM jsonb_array_elements('[{"key": 1}, {"key": 2}]'::JSON) individual_object,
    LATERAL jsonb_set(individual_object, '{key}', '"foo"') updated_jsonb;

             jsonb_agg
------------------------------------
  [{"key": "foo"}, {"key": "foo"}]


text:
Q: Defining the correct include path I am facing a include path error.
In a file config.php  I am including include ("./inc/logged_in.php" ); which (logged_in.php) further includes include ("./include/connect.php" ); but I get a error saying:

failed to open stream: No such file or directory in C:\xampp\htdocs\demo\fileman\filemanager\config\config.php

Now this error may be because config.php and logged_in.php are in different subfolders and my inclusion path is incorrect.
I tried using
include ("../../inc/logged_in.php" ); now no error for logged_in.php but error for connect.php:

include(./inc/connect.php): failed to open stream: No such file or directory in C:\xampp\htdocs\demo\inc\logged_in.php

My structure for config.php is:
// root
//   |- demo
//   |    |-  fileman
//   |    |    |- filemanager
//   |    |    |   |- config
//   |    |    |   |    |- config.php
My structure for connect.php and logged_in.php is:
// root
//   |- demo
//   |    |-  inc
//   |    |    |- connect.php
//   |    |    |- logged_in.php

A: Check it:
/demo/fileman/filemanager/config/config.php
include('../../../inc/logged_in.php');

/demo/inc/logged_in.php
include('connect.php');


text:
Q: "file not sent" from Android to Macbook, whereas they're paired I'm trying to send a file from Android to Macbook via bluetooth. I pair them successfully and when I'm sending a file from Android, it just ends up saying "file not sent". In the Macbook does happen nothing at that time, no pop up window or something.
That's it.

A: After updating to macOS Monterey v 12.1 I also had this problem.
For me, I needed to turn OFF Bluetooth Sharing, turn down System Preferences and then turn ON Bluetooth Sharing again and it did work.

A: In System Preferences > Sharing > Bluetooth Sharing, ensure that Folder for accepted items is set to something. If it isn't set, incoming file transfers are rejected automatically.


text:
Q: Google Map won't appear on page load I am trying to load a google map with some markers on it.
the html is the following The div where the map is supposed to be is at the bottom in bold:
<!DOCTYPE html>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">

DSA Homework Assignment

Veteran's Administration Data Presentation

Vets by State Chart

Count of VA Facilities by State

Vets by State Map

VETSTATS with VF Ratio

<select id = "choice" style = "font-size: 15px">
  <option value="safety">Safety</option>
  <option value="effectiveness">Effectiveness</option>
  <option value="efficiency">Efficiency</option>
</select>
<input type = "button" class = "btn"
name = "Switch Category" value = "View Different Performance Measure" id ='btn1'/>

State Scores for Safety All Years

Category
2010
2011
2012
2013
2014

Average Improvement All Measure All Years

Performance Change FY10 - FY14

<select id = "choice2" style = "font-size: 15px">
  <option value="safety">Safety</option>
  <option value="effectiveness">Effectiveness</option>
  <option value="efficiency">Efficiency</option>
</select>
<input type = "button" class = "btn"
name = "Switch Category" value = "View Different Performance Measure" id ='btn2'/>

Improvement in Safety

 **

**

The javascript that generates the markers is the following the file in called VA_map.js:
function initMap() {
  //var state_filter = $('#state_select').val()
  var map = new google.maps.Map(document.getElementById('map'), {
    zoom: 2,
    center: new google.maps.LatLng(39.8524, -93.80046)
  });

 var state_filter = 'New York';

$.ajax({
    type: 'GET',
    url: 'https://opendata.socrata.com/resource/29sw-6mq4.json?state_name='+ state_filter,
    success: function(data) {$.each(data, function(i, item) {
         var marker = new google.maps.Marker({
                            position: new google.maps.LatLng(item.location_1.latitude, item.location_1.longitude),
                            map: map
  });
        });
    console.log(data);
    }
});
}

However the map won't appear on the page.  Oddly when I was developing this on a sample page that had only the map and nothing else, the map appears.  But the second I moved the code over, it won't load.  No idea why. The console shows no errors in any of the sources, but the map won't show.

A: Set height of map div with some absolute unit (e.g. px). Then works fine


text:
Q: Display custom list of tags in post/page editor with hooks I used the information posted on this blog post to display specific tags when editing a post.  The editors on my site wanted the ability to display pre-specified tags instead of the most popular ones.  We have a lot of tags and sometimes the ones they want to use are not being used because they are not seen and they don't remember what to search for.
So in the wp-admin/includes/ajax-actions.php file I changed the line 651 to
$tags = get_terms( $taxonomy, array(
    'number' => 45,
    'orderby' => 'name',
    'order' => 'DESC',
    'include' => array('21', '12')
) );

where the include array is the selection of tags I want to display.
and line 665 to
$return = wp_generate_tag_cloud( $tags, array(
    'largest' => 10,
    'smallest' => 10,
    'filter' => 0,
    'format' => 'flat',
    'separator' => "  "
) );

This works fine for displaying a sequential list (I didn't want a tag cloud) of specific tags but these changes are to the wordpress core and on the next update I'll have to go in and re-do these.  Is there any way to accomplish this with hooks so that I don't mess with the core?
Thanks

A: We can override the Ajax call to wp_ajax_get_tagcloud() and do a clean hack.
<?php
/* Plugin Name: Custom Admin Tag Cloud */

add_action( 'wp_ajax_get-tagcloud', 'ajax_tag_cloud_wpse_99497', 1 );

function ajax_tag_cloud_wpse_99497()
{
    // PASTE ALL THE MODIFIED FUNCTION HERE
    // http://core.trac.wordpress.org/browser/tags/3.5.1/wp-admin/includes/ajax-actions.php#L639
}

Restore your core files to its original state, copy the modified function inside the above container and create a plugin for it. And ready to go.


text:
Q: Align 2 pictures in the same line Bootstrap I am trying to recreate this website: Fister.
But my pictures won't align.

    <meta charset="utf-8">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="icon" href="124010.png">
    <title>FacebookMusic</title>

In this picture you can see my result:

I need the picture with the girl on the right,
Can someone help me? I am a beginner.

A: Just Use Below css
img {
    max-width: 100%;
}

img{
  max-width:100%;
}

    <meta charset="utf-8">

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="icon" href="124010.png">
    <title>FacebookMusic</title>

A: Apply the img-fluid class to your images to make them respect the grid. You may have been following docs for Bootstrap 3, which had the class you used.
https://getbootstrap.com/docs/4.5/content/images/#responsive-images

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">


text:
Q: Sending string from C# to C++ dll file I have a function in socket.dll library as below:
 __declspec(dllexport) string GetPib(const wchar_t* pib_key_chars)
 {
    wstring ws(pib_key_chars);
    std::string pib_key(ws.begin(), ws.end());
        cout << "In GetPib" << "  and pib_key in string=" << pib_key << endl;
    Pib pb;

    return std::to_string(pb.Get(phyFskTxPacket, 0));

 }

When i use "dumpbin /exports socket.dll" to check the GetPib function of socket.dll signature it returns
1    0 00011370 ?GetPib@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?
$allocator@D@2@@std@@V12@@Z = @ILT+875(?GetPib@@YA?AV?$basic_string@DU?
$char_traits@D@std@@V?$allocator@D@2@@std@@V12@@Z)

I am using the same signature in the C# project(WindowsFormsApp1) to call/invoke GetPib function.
Below is the C# source code to invoke GetPib function:
 namespace WindowsFormsApp1
 {
     public partial class Form1 : Form
     {
         [DllImport("socket.dll", EntryPoint = "?GetPib@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PB_W@Z", CallingConvention = CallingConvention.Cdecl)]
         public static extern string GetPib([MarshalAs(UnmanagedType.LPStr)] string pib_key);

         public Form1()
         {
             InitializeComponent();
         }

         private void GetPib_button_Click(object sender, EventArgs e)
         {
             String str = pib_id_tbox.Text;

             pib_uvalue_tbox.Text = GetPib(str);

         }
 }

When I invoke GetPib function like GetPib(0x1004xxx4), it invokes the socket.dll's GetPib function but the value is different with special characters
str=0x10040004  tr=268697604-----> in C# file
In GetPib  and pib_key in string=h䤰"------> in C++ .dll file

How to fix this issue.

A: First of all, wrap the unmanaged function declaration in extern "C" to eliminate the mangling and rewrite the unmanaged function to something more sensible for interop with managed code.
extern "C" {

  __declspec(dllexport) int GetPib(const char* pib_key_chars, char *result, int len) {
    cout << "In GetPib" << "  and pib_key in string=" << pib_key_chars << endl;
    Pib pb;
    string packet = std:to_string(pb.Get(phyFskTxPacket, 0);
    int n = (int)packet.length;
    if (n < len) {
      packet.copy(result, n, 0);
      result[n] = '\0';
    }
    return n + 1;
  }

}

In this rewrite, we are passing the managed string, an allocated buffer to hold the result, and the length of that buffer. This version handles char* strings. If you need to use wchar_t* wide strings, it should be trivial to convert it. The main thing to note is that we are not using any C++ types as parameters to the function, since the interop marshaller has no way of knowing how to deal with those types. We are only using language primitives.
The managed P/Invoke signature would look like this:
[DllImport("socket.dll", EntryPoint="GetPib")]
public static extern int GetPib(([MarshalAs(UnmanagedType.LPStr)] string keyChars, IntPtr buffer, int len);

To call it:
private void GetPib_button_Click(object sender, EventArgs e)
{
  int needed = GetPib(pib_id_tbox.Text, IntPtr.Zero, 0);
  IntPtr p = Marshal.AllocHGlobal(needed);
  GetPib(pib_id_tbox.Text, p, needed);
  pib_uvalue_tbox.Text = Marshal.PtrToStringAuto(p);
  Marshal.FreeHGlobal(p);
}

Here we are allocating unmanaged memory so that the GC won't move it around while we are interoperating with unmanaged code. The unmanaged function will fill the buffer with the resulting char*, which we convert back into a managed string with PtrToStringAuto(). Then we free the unmanaged memory.

A: I followed this link
https://answers.unity.com/questions/142150/passing-strings-to-and-from-a-c-dll.html
I modified GetPib api in C++
 __declspec(dllexport) string GetPib(const wchar_t* pib_key_chars)

to
 extern  BSTR __declspec(dllexport)  GetPib(BSTR pib_key_chars)

Modified C# file from
[DllImport("socket.dll", EntryPoint = "?GetPib@@YA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@PB_W@Z", CallingConvention = CallingConvention.Cdecl)]
     public static extern string GetPib([MarshalAs(UnmanagedType.LPStr)] string pib_key);

to
 [DllImport("socket.dll", EntryPoint = "?GetPib@@YAPA_WPA_W@Z", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
    [return: MarshalAs(UnmanagedType.BStr)]
    public static extern string GetPib(string str);

and it solved my problem!!!!!!


text:
Q: Absence of leading or trailing space in regex invalidates search I am trying to search different types of dates in my strings using regex.
import re

txt1 = "The date is 3-Dec "
txt2 = "The date is3-Dec "
txt3 = "The date is 3-Dec"
txt4 = "The date is Dec-20"
txt5 = "The date isDec-20"

regx = r"(?:\d{2}|\d{1}|\d{0})(?:[,| ,|, |-|/|\\|\s|\d{0}])(?:%s)(?:[,| ,|, |-|/|\\|\s|\d{0}])(?:\d{4}|\d{2}|\d{0})" % '|'.join(['Nov', 'Dec'])

x1 = re.findall(regx, txt1)
print(x1)
x2 = re.findall(regx, txt2)
print(x2)
x3 = re.findall(regx, txt3)
print(x3) # empty
x4 = re.findall(regx, txt4)
print(x4)
x5 = re.findall(regx, txt5)
print(x5) # empty

Could someone help why txt3 and txt5 are not working? Basically following portion of regex is not working when there is no leading or trailing space for date (?:[,| ,|, |-|/|\\|\s|\d{0}])

A: You can use
months = ['Nov', 'Dec']
date_rx = r'(?:[1-9]|[12]\d|3[01])'
month_rx = r'(?:{})'.format('|'.join(months))
sep_rx = r'[\s,/\\-]'
regx = r"(?<!\d){0}{2}{1}|{1}{2}{0}(?!\d)".format(date_rx, month_rx, sep_rx)

See the online Python demo. The regex is
(?<!\d)(?:[1-9]|[12]\d|3[01])[\s,/\\-](?:Nov|Dec)|(?:Nov|Dec)[\s,/\\-](?:[1-9]|[12]\d|3[01])(?!\d)

See the regex demo.
Regex part details:

*

*(?:[1-9]|[12]\d|3[01]) (date_rx) - a non-zero digit, 10 to 29 or 30 or 31

*(?:Nov|Dec) (month_rx) - Nov or Dec

*[\s,/\\-] (sep_rx) - whitespace, comma, slash, backslash or a hyphen.

The negative lookbehind (?<!\d) makes sure there is no digit immediately to the left of the current location and the negative lookahead (?!\d) makes sure there is no digit immediately to the right of the current location.


text:
Q: Knockout popover bindings for checklist I would like to bind the values from database to popover checkbox list using knockout Js.Please help.Thanks in Advance!

A: var viewModel = function() {
    var self = this;
    self.valuesForCheckBoxList = ko.observableArray([]);
    self.init = function () {
        $.get("... url for get data from database ...", function (data) {
            self.valuesForCheckBoxList(data);
        });
    };
    self.init();
}

var vm = new viewModel();
ko.applyBindings(vm);

And if returned data will be looked like this: [{Id: 1, Name: "n1"}, {Id: 2, Name: "n2"}], you could write folowing html:

        <input type="checkbox" data-bind="checked: $root.valuesForCheckBoxList, value: Id" />

For configure you request more specifically you could read this https://api.jquery.com/jQuery.get/ page.
ko.observableArray: http://knockoutjs.com/documentation/observableArrays.html
checkbox bindings: http://knockoutjs.com/documentation/checked-binding.html


text:
Q: How does Java run() method work? Multi-threading in Java is done by defining run() and invoking start().
Start delegates to a native method that launches a thread through operating system routines and run() is invoked from within this newly spawned thread.
When a standalone application is started a main thread is automatically created to execute the main().
Now consider this code -
public class Test extends Thread {
    public static void main(String[] args) throws Exception {
        new Thread(new Test()).start();
        throw new RuntimeException("Exception from main thread");
    }
    public void run() {
        throw new RuntimeException("Exception from child thread");
    }
}

This is the output -
java.lang.RuntimeException: Exception from child thread
    at com.Test.run(Test.java:11)
    at java.lang.Thread.run(Thread.java:662)
java.lang.RuntimeException: Exception from main thread
    at com.Test.main(Test.java:8)

If main() method is launched via a thread why doesn't run() show up at the top of invocation hierarchy?
How could the main thread get spawned without implementing Runnable?

A:
If main() method is launched via a thread why doesn't run() show up at the top of invocation hierarchy?

As others have mentioned, this is because the "main" thread is special.  It is not launched through the standard Thread class mechanisms but instead through Java bootstrap code.  The public static void main(String[] args) is always run by the main thread from native code.
Another explanation is that there actually maybe a run() method but the way they build the stackframe is hiding it on purpose for the sake of not confusing the user.  For example, since you are doing a new Thread(new Test()) then your Test class is actually the target field inside of the Thread.  When the background Thread is started then it actually calls Thread.run() which has the code:
public void run() {
    if (target != null) {
        target.run();
    }
}

But we never see the Thread.run() method in the stackframe although it seems like it should be there.  The run() method would be in the stackframe if the user overrode it in a Thread superclass.  It could be removed by the JDK to improve stackframe output.

Multi-threading in Java is done by defining run() and invoking start().

This is correct but for posterity I thought it was important to realize that your code has a problem.  Your Test class should not be extending Thread but instead should be implementing Runnable.  It works because Thread implements Runnable.
Either you should implement Runnable and change your code to something like this:
public class Test implements Runnable {
    public static void main(String[] args) throws Exception {
        new Thread(new Test()).start();
        throw new RuntimeException("Exception from main thread");
    }
    public void run() {
        throw new RuntimeException("Exception from child thread");
    }
}

Or you still extend Thread and change the way you start your thread to something like the following.  The above Runnable pattern is recommended since it allows your Test thread to extend another class if necessary.
public class Test extends Thread {
    public static void main(String[] args) throws Exception {
        new Test().start();
        throw new RuntimeException("Exception from main thread");
    }
    @Override
    public void run() {
        throw new RuntimeException("Exception from child thread");
    }
}

Why is this important?  You current code is actually instantiates 2 Thread objects but only one of them is start()ed and is running as a background Thread.  You could have something like the following bug:
public class Test extends Thread {
    public static void main(String[] args) throws Exception {
        Test test = new Test();
        new Thread(test).start();
        // this is not interrupting the background thread
        test.interrupt();

A: main method is started in a separate thread by JVM, it is the parent thread of child thread, thats why you dont see child thread at the top of invocation hierarchy.
So in your case JVM created a thread started your program, which also extends Thread.
Then in your main method you created a new instance of your class, called start on it, this will start a new thread which is child of thread started by JVM to launch your program.
Since main method is a starting point for a standalone java program, it is the responsiblity of JVM to launch it in a separate thread, you dont write code for it.
While launching a program by calling main method JVM doesn't need it to be a Thread or implement Runnable, it is a standard procedure.
Description from Inside Java Virtual Machine

The main() method of an application's initial class serves as the
  starting point for that application's initial thread. The initial
  thread can in turn fire off other threads.
Inside the Java virtual machine, threads come in two flavors: daemon
  and non- daemon. A daemon thread is ordinarily a thread used by the
  virtual machine itself, such as a thread that performs garbage
  collection. The application, however, can mark any threads it creates
  as daemon threads. The initial thread of an application--the one that
  begins at main()--is a non- daemon thread.
A Java application continues to execute (the virtual machine instance
  continues to live) as long as any non-daemon threads are still
  running. When all non-daemon threads of a Java application terminate,
  the virtual machine instance will exit. If permitted by the security
  manager, the application can also cause its own demise by invoking the
  exit() method of class Runtime or System.

The call hierarchy is not governed by you it is governed by the underlying thread scheduler.
So for example If I run the same code on my machine this is the output
Exception in thread "main" java.lang.RuntimeException: Exception from main thread
    at TestThread.main(TestThread.java:6)
Exception in thread "Thread-1" java.lang.RuntimeException: Exception from child thread
    at TestThread.run(TestThread.java:9)
    at java.lang.Thread.run(Thread.java:662)

so when you ran your example, scheduler choose to let go child thread first before main.
Adding to @JB Nizet, how a program will be invoked, or how a thread lifecycle will be implemented depends from underlying OS and hardware, which will and does vary.
No single implementation details would provide a complete answer, each implementation will vary.

A: I haven't looked at the internals of the JVM, but I would guess that the JVM instantiates the main thread to run the main method, but runs this main thread by invoking native code directly, without going through the classical Java classes and methods to start the thread.

A: Maybe it is a semantic argument, but a Thread and a Process are not synonymous.
A process is launched by the operating system, and has it's own private code pages (compiled set of code).  A Thread is launched from the program internals, and initially shares its parent's code pages (compiled set of code).
That the JVM internally uses a Thread to run the main method is an implementation detail of the environment, but not a representation of the Java language.  If a Thread was to report in the main stack frames, the architecture of referring back to the source code position would be impossible, because that main-serving thread would have no compilation unit (it is internal to the JVM).


text:
Q: Relativistic charged particle in a constant uniform electric field I'm doing some special relativity exercises. I have to find $x(t)$ and $v(t)$ of a charged particle left at rest in $t=0$ in an external constant uniform electric field $\vec{E}=E_{0} \hat{i}$, then with that velocity I should find the Liénard–Wiechert radiated power.
I will show you what I did but I feel that it is wrong.
We should solve the equation of motion given by
$$
\tag{1}\frac{dp^{\mu}}{d\tau} = \frac{q}{c} F^{\mu \nu}u_{\nu}
$$
The four-velocity is given by
$$
u^{\mu} = (u^{0},u^{1},u^{2},u^{3}) = \gamma (c,v^{1},v^{2},v^{3})
$$
where $v^{\alpha}$ are the components of the three-velocity. The four-momentum is
$$
p^{\mu} = mu^{\mu}
$$
This will give us four equtions where two of them will give a constant velocities and the other two are
$$
\tag{2}\frac{d\gamma}{d\tau} = -\frac{qE_{0}}{mc^{2}}\gamma v_{1}
$$
$$
\tag{3}\frac{d\gamma}{d\tau} v_{1} + \gamma \frac{dv_{1}}{d\tau} = \frac{qE_{0}}{m} \gamma
$$
Replacing $(2)$ in $(3)$ gives
$$
\tag{4}\frac{dv_{1}}{d\tau} = -\frac{qE_{0}}{mc^{2}} (v_{1})^{2} + \frac{qE_{0}}{m}
$$
The solution of the ODE $(4)$ gives something like
$$
\tag{5}v_{1}(\tau) = A\tanh{(B\tau)}
$$
This component of the three-velocity is in terms of the proper time $\tau$ and the problem ask me to find the velocity in terms of the time $t$. So my attempt was to solve
$$
\tag{6}\frac{dt}{d\tau} = \gamma (\tau) = \frac{1}{\sqrt{1 - \frac{(v_{1}(\tau))^{2}}{c^{2}}}}
$$
and then replacing this solution for  $\tau$ in $(5)$. But the solution of $(6)$ is this. Which doesn't make any sense to me.
I think that I'm misunderstanding something or missing something that will give me a easier solution to this problem. I thought it because in the Liénard–Wiechert radiated power I sould do $dv_{1}/dt$ which is almost impossible to do it without WolframAlpha.

A: You need to match the initial conditions,
\begin{align*}
  a_{0} &= \frac{qE_{0}}{m} \\
  v &= c\tanh \frac{a_{0} \tau}{c} \\
  \gamma &= \cosh \frac{a_{0} \tau}{c} \\
  &= \frac{dt}{d\tau} \\
  t &= \int_{0}^{\tau} \cosh \frac{a_{0} \tau}{c} \,  d\tau \\
  &= \frac{c}{a_{0}} \sinh \frac{a_{0} \tau}{c} \\
  \frac{a_{0} t}{c} &= \sinh \frac{a_{0} \tau}{c} \\
  v &= \frac{a_{0} t}{\sqrt{1+\left( \dfrac{a_{0}t}{c} \right)^{2}}} \\
\end{align*}


text:
Q: handling dtype in for loop from an Excel file I'm trying to extract columns from an excel file onto a website by using pandas for loop.
However, not all data from a specific column have the same data type, so sometimes it can't output due to "datatype" issue and there are even null value in the column.
Is it possible to extract any value regardless of its data type? What does numpy.ndarray actually mean?

A: You could use try/except conditionals to catch the various data types.


text:
Q: How to split cell content and extract information into a new column in an SQL select statement? I have a table where one of the columns are storing key/value pairs separated by semicolons, like this:
KEY1:VALUE1;KEY2:VALUE2;KEY3:VALUE3

I would like to construct a view where I have additional columns where the value will be extracted from the field above. My question is how to extract VALUE1, VALUE2 and VALUE3 in a SELECT query.
There will not be more than three key-value pairs in this field.

A: I've already answered an incredibly similar question today, so look at the answer:
SQL comma delimted column => to rows then sum totals?
but try this:
I prefer the number table approach to split a string in TSQL
For this method to work, you need to do this one time table setup:
SELECT TOP 10000 IDENTITY(int,1,1) AS Number
    INTO Numbers
    FROM sys.objects s1
    CROSS JOIN sys.objects s2
ALTER TABLE Numbers ADD CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number)

Once the Numbers table is set up, create this split function:
CREATE FUNCTION [dbo].[FN_ListToTable]
(
     @SplitOn  char(1)      --REQUIRED, the character to split the @List string on
    ,@List     varchar(8000)--REQUIRED, the list to split apart
)
RETURNS TABLE
AS
RETURN
(

    ----------------
    --SINGLE QUERY-- --this will not return empty rows
    ----------------
    SELECT
        ListValue
        FROM (SELECT
                  LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
                  FROM (
                           SELECT @SplitOn + @List + @SplitOn AS List2
                       ) AS dt
                      INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
                  WHERE SUBSTRING(List2, number, 1) = @SplitOn
             ) dt2
        WHERE ListValue IS NOT NULL AND ListValue!=''

);
GO

You can now easily split a CSV string into a table and join on it:
select * from dbo.FN_ListToTable(',','1,2,3,,,4,5,6777,,,')

OUTPUT:
ListValue
-----------------------
1
2
3
4
5
6777

(6 row(s) affected)

Your can now use a CROSS APPLY to split every row in your table like:
DECLARE @YourTable table (RowID int, RowValue varchar(200))
INSERT INTO @YourTable VALUES (1,'KEY11:VALUE11;KEY12:VALUE12;KEY13:VALUE13')
INSERT INTO @YourTable VALUES (2,'KEY21:VALUE21;KEY22:VALUE22;KEY23:VALUE23')
INSERT INTO @YourTable VALUES (3,'KEY31:VALUE31;KEY32:VALUE32;KEY33:VALUE33')

SELECT
    o.RowID,RIGHT(st.ListValue,LEN(st.ListValue)-CHARINDEX(':',st.ListValue)) AS RowValue
    FROM @YourTable  o
        CROSS APPLY  dbo.FN_ListToTable(';',o.RowValue) AS st

OUTPUT:
RowID
----------- -------
1           VALUE11
1           VALUE12
1           VALUE13
2           VALUE21
2           VALUE22
2           VALUE23
3           VALUE31
3           VALUE32
3           VALUE33

(9 row(s) affected)

A: Writing a scalar function, which receives the string containing the key/value pairs, and the index of the value to get (or the key of the value to get) as its arguments, and returns the appropriate value, would make your problem easily solvable.
You could also write this scalar function in .Net, which would perform a lot better than writing it in TSQL, as you wouldn't have to access any tables or database objects from that function.


text:
Q: Why the errors? # include <stdio.h>
# include <stdlib.h>
#define MAX 1000
struct stack {
    int st[MAX];
    int *top ;
};

int main() {
  struct stack *s = malloc(sizeof(struct stack));
  s->(*top) = -1;
  return 0;
}

I am writing a piece of code for stack implementation in C. This is a practice assignment. Why do I get the following compilation errors?
error: expected identifier
  s->(*top) = -1;
error: use of undeclared identifier 'top'
  s->(*top) = -1;

A: If you want to assign -1 to the pointer: s->top = -1; (should  give a warning but will probably compile).
If you want to assign -1 to the int top is pointing at *(s->top) = -1; will compile but probably crash since top is not pointing anywhere valid yet.
int anInteger;
struct stack *s = malloc(sizeof(struct stack));
s->top = &anInteger;
*(s->top) = -1;
/* anInteger should now have the value -1 */
/* beware scope - if you did this somewhere other than main
   anInteger may go out of scope */
return 0;

A: I know you already accepted an answer for this, but based on the names of your variables, I think what you really want to do is this:
s->top = s->st;

This will mean that "top" is pointing to position 0 of the stack, you can insert at the top and then increment like so:
*(s->top) = INSERT_VALUE;
s->top++;

To pop:
REMOVE_VALUE = *(s->top);
s->top--;

Neither has any bound checks.  Given that you've declared top as a pointer, this is what I think you want to do.  You don't usually store empty pointers as -1, you store them as 0 (or NULL).  That being said, using an empty pointer in this case just doesn't make any sense.


text:
Q: Elements of $\mathbb{Z}/(n)$ Let $(n) = \{ \lambda n | \lambda \in \mathbb{Z} \}$. In my book it has shown that every element in  $\mathbb{Z}/(n)$ can be expressed uniquely in the form $r + (n)$ where $0 \leq r \leq n-1$ now I look at a practical application of this, say:
$\mathbb{Z}/6 = \{ 0,1,2,3,4,5 \}$ and when computing elements in this set we just do it in modulo $6$, so everytime I see a $6$ I write $0$, so for $\mathbb{Z}/(n)$ everytime I see $n$ I write $0$. However, I don't see how this leads on from the theorem I stated above, i.e. if we know that every element in  $\mathbb{Z}/(n)$ can be represented in the form $r + (n)$ with $ 0 \leq r \leq n-1$ why does that mean, when I see $n$ I write $0$? I'm just not comfortable with $r + (n)$ I mean, what is the $(n)$ doing there?

A: Remember that $r + (n)$ in this context is a coset, it itself is not a single number but an infinite collection of integers (namely those elements $k \in \mathbb{Z}$ such that $r-k$ is a multiple of $n$.  You should think of the coset $r+(n)$ as the set of elements that are $n$-translates of $r$.  In your example above you had $\mathbb{Z}/(6)$ so the coset corresponding to $r=5$ is
$$
5 + (6) \; \; = \;\; \{\ldots, -7, -1, 5, 11, 17, 23, \ldots \}.
$$
So the $6$-translates of $6$ would be the coset
$$
6 + (6) \;\; =\;\; \{\ldots, -18, -12, -6, 0, 6, 12, 18, \ldots\}
$$
We see that $0 \in [6 + (6)]$ so if we want to represent the coset uniquely in terms of nonnegative integers less than $6$ we can use $0$ to represent the coset containing $6$.

A: Notice that $r$ is the remainder of the division of any integer number by $n$. And as $0 \leq r < n$ then you may choose a class representant to the residue class $[r]$ then
$$[r] = r + (n) = \{r + x ; x \in (n)\}$$
You may also notice that
$$a \equiv b\mod (n) \iff b-a \in (n)$$

A: The problem is that $\mathbb Z/(6)$ is not the set $\{0,1,2,3,4,5\}$. Instead, $\mathbb Z/(6)$ is the set of equivalence classes of $\mathbb Z$ under the equivalence relation $x\sim y:\Leftrightarrow x-y\in(6)$. These equivalece classes are not single numbres, but are sets of numbers, for example
$$\{\ldots,-24,-18,-12,-6,0,6,12,18,24,\ldots\} $$
and
$$\{\ldots,-23,-17,-11,-5,1,7,13,19,25,\ldots\} $$
are two of these equivalence classes.
The first is just $(6)$ (cf. the definition of $(n)$). Since $0$ "does nothing" we can also write it as $0+(6)$. The second equivalence class is the set $(6)$ with $1$ added to each element, which is suggestively written as $1+(6)$. There is nothing special about the $1$ for we might with the same justification cwrite this set as $-5+(6)$ or $6667+(6)$ or many other ways of the form $r+(6)$. But the theorem you quote says that we can pick $r$ such that $0\le r\le 5$ (which we actually did in our first attempt, with $r=1$).
So more precisely
$$\mathbb Z/(6)=\{(6),1+(6),2+(6),3+(6),4+(6),5+(6)\} $$
Remark: You may sometimes find the notation $6\mathbb Z$ instead of $(6)$, so with that convention $\mathbb Z/6\mathbb Z=\{6\mathbb Z,1+6\mathbb Z,2+6\mathbb Z,3+6\mathbb Z,4+6\mathbb Z,5+6\mathbb Z\}$


text:
Q: Where can I find the Windows version in a CIM instance? On the Windows Settings > System > About page, the "Windows specifications" section presents the following information.
Edition Windows 10 Enterprise
Version     20H2
OS build    19042.1288

Using the following reports the Version member as 19042.1288.
(Get-CimInstance -ClassName 'Win32_OperatingSystem').Version

Where can 20H2 be found in a CIM instance? I cannot find it in any of the following CIM instances.
CIM_OperatingSystem
Win32_OperatingSystem
Win32_SystemOperatingSystem

A: Indeed, the so-called display version - such as "20H2" - doesn't seem to be a part of the Win32_OperatingSystem (CIM_OperatingSystem appears to be just an alias) and Win32_SystemOperatingSystem  CIM (WMI) classes (as of Windows 10 20H2), but you can obtain it from the registry:
Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' DisplayVersion

Similarly, the release ID - such as "2009" - is seemingly also only found in the registry:
Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion' ReleaseId


text:
Q: jquery dynamic content and date output var jsonObj = jQuery.parseJSON(passData);
thisId = jsonObj.id;
thisPage = jsonObj.page;
thisPageItem = jsonObj.item;
if (jsonObj.json != undefined) {
    $.each(jsonObj.json, function (key, tempJson) {
        if (tempJson.position != undefined) {
            var tempId = tempJson.id;
            var tempStyle = tempJson.position;
            objJsonArr[tempId] = tempStyle;
        }
    });
}
for (var i = 1; i < 9; i++) {
    var tempList = window.objJsonArr;
    var tempDom = '#dropAbleArea #area.' + i;
    $(tempDom).css('top', dropObjectPositionArr[i].top);
    $(tempDom).css('left', dropObjectPositionArr[i].left);
    console.log("Out " + objJsonArr[i]);
    $(tempDom).load('images/pageThree/' + i + '.svg', null, function (e) {
        console.log("In " + objJsonArr[i]);
    });
}

$.each(objJsonArr, function (key, value) {
    if (value != undefined) {
        $('#dropAbleArea div#area').on('', function (e) {
            $('#dropAbleArea div#area.' + key + ' g#ball path#bk').attr('style', value);
        });
    };
});

the return is
[Log] Out fill:rgb(244, 133, 142) (3.html, line 130)
[Log] Out fill:rgb(130, 202, 156) (3.html, line 130)
[Log] Out fill:rgb(207, 229, 174) (3.html, line 130)
[Log] Out fill:rgb(130, 202, 156) (3.html, line 130)
[Log] Out undefined (3.html, line 130, x4)
[Log] In undefined (3.html, line 132, x8)

Q1: I can't get the javascript array data in the console.log("In " + objJsonArr[i]);
Q2: How can i get the dynamic content in the
$('#dropAbleArea div#area').on('',function(e){
    $('#dropAbleArea div#area.' + key +' g#ball path#bk').attr('style',value);
});

A: The complete function given to jQuery .load captures the variables objJsonArr and i. But when the function is executed, the loop has already finished and i has the value 9 and objJsonArr[9] seems to be undefined.
You can see the same effect with a delayed function
var a = [ 1, 2, 3 ];

for (var i = 0; i < a.length; ++i) {
    setTimeout(function() {
        console.log('a[' + i + ']=' + a[i]);
    }, 500);
}

which gives the output
a[3]=undefined

JSFiddle
You can "fix" this with creating an additional scope by wrapping the anonymous function, where you capture the loop variable's value in a another variable k
var a = [ 1, 2, 3 ];

for (var i = 0; i < a.length; ++i) {
    setTimeout((function(k, v) {
        return function() {
            console.log('a[' + k + ']=' + v);
        };
    })(i, a[i]), 500);
}

JSFiddle
In your case, this would be something like
$(tempDom).load('images/pageThree/' + i + '.svg', null, (function(v) {
    return function (e) {
        console.log("In " + v);
    };
})(objJsonArr[i]));

Update:
I just learned about jQuery.proxy() and it seems to be the solution to your problem. Taking my first example and applying jQuery.proxy to it will give
var a = [ 1, 2, 3 ];

for (var i = 0; i < a.length; ++i) {
    setTimeout($.proxy(function(k, v) {
        console.log('a[' + k + ']=' + v);
    }, null, i, a[i]), 500);
}

JSFiddle
This is equivalent to the closure in my second example, where the two values are captured. Equally, using $.proxy in your program will be
$(tempDom).load('images/pageThree/' + i + '.svg', null, $.proxy(function (v, e) {
    console.log("In " + v);
}, null, objJsonArr[i]));


text:
Q: Quaternion to Euler angles conversion I have written the following MATLAB code for transforming Quaternion to Euler angles based on the mathematical formula from wikipedia:
function [phi theta psii]=quat(q0,q1,q2,q3)

q_length=sqrt(q0*q0+q1*q1+q2*q2+q3*q3);

q0=q0/q_length;
q1=q1/q_length;
q2=q2/q_length;
q3=q3/q_length;

phi=atan2(2*(q0*q1+q2*q3),1-2*(q1*q1+q2*q2));
theta=asin(2*(q0*q2-q3*q1));
psii=atan2(2*(q0*q3+q1*q2),1-2*(q2*q2+q3*q3));

end

I tested the code:
[phi theta psi]=quat(0.99619,0,0,0.08716)
psi*180/pi
ans =

   -115.0435

The result is different compared to this website which suggests:
$\theta=0,~~~\phi=0,~~~\psi=-90$

A: Be careful when you convert between quaternions and euler angles. One of the main source of confusions are the conventions adopted to represent angles. The same quaternion can represent a rotation or it's inverse based on the adopted convention.
Your equations seems to be correct at first glance. As a comparison write some code to compute the conversion to the rotation vector. I do not know what the website does and I believe that when it comes to quaternions it is safe not to use software from different sources because you do not know the conventions that are adopted.
By the way, quaternions are provided by matlab in the aerosym toolbox (included in the complete version), but they follow the JPL convention and not the Hamiltonian.


text:
Q: javascript: how to check a property is undefined I have codes below.
elem.onkeypress=function(e){
 if( (e.which===undefined?e.keyCode:e.which)==13 ){
   //dosomething
  }
}

at IE8, it occus erros:  'which' is null or not an object
how to fix this problem.

A: The problem is that e is undefined in IE because no event object is passed as a parameter to the event handler. You need the window.event property:
elem.onkeypress=function(e) {
  e = e || window.event;
  var charCode = e.which || e.keyCode;
  if (charCode == 13) {
    //dosomething
  }
};

A: One option is to go with (e.hasOwnProperty('which') ? ...

A: use typeof:
if (typeof e.which == 'undefined' ? e.keyCode : e.which) == 13)


text:
Q: How to dedicate a single CPU for a specified child process? I'm using posix_spawn function in 1 parent process to call other executable files child processes. I want to dedicate some of those child processes exclusively to a cpu for each (I know I cannot dedicate 4 of them as the kernel and other processes are critical and they should run, but let's assume now for at least 1 or 2 processes).
I ran htop command and I saw that all the 4 cores are being used, but I want to be able to have more control in case I got hundreds of processes so I decide which can run fully.

A: You can use sched_setaffinity() system call to assign CPU core for a process. see manpage


text:
Q: What speed is my ethernet port? My network card appears to have two Ethernet ports. I'm trying to work out the theoretical maximum speed of those Ethernet ports - specifically if they are Gigabit (1000Mbit/s) ports or plain old 100Mbit/s.
I've tried a couple of different things:

*

*Device Manager shows me having Realtek PCI GBE Family Controller drivers. Does the GBE stand for Gigabit?

*The controller properties shows both ports are 1.0 Gbps capable.

*I've used WMIC to get the speed in bits. Which is 100000000 bits, so 100 Mb.

*Finally I've checked the Ethernet status. Which is where my confusion lies as this says 100Mbps. Is this because I only have a Cat5 Ethernet cable plugged in, or is this the real speed.

How can I determine the speed of my Ethernet ports?

A: You have gigabit ports connected to a 100 megabit switch (or equivalent device). GBE = Gigabit Ethernet.   The 100 megabit will be coming from the speed negotiated with the switch or equipment on the other end of the link.
The cat5 cabling is probably not relevant - most cat5 cables will negotiate a gigabit connection (but you might not get the full gigabit throughput).   That said, if your cabling is only using 2 of the 4 pairs, then it would negotiate 100 megabit.


text:
Q: How to create/Initialize ArrayList of ArrayList using java Lambda How to convert the following code to lambda in java8???
    List<List<String>> my2dList = new ArrayList<List<String>>();
    int counter = 0;
    for (int i = 0; i < 5; i++) {
        my2dList.add(new ArrayList<String>());
        for (int j = 0; j < 10; j++) {
            System.out.println("Counter: " +counter);
            my2dList.get(i).add(new String(""+counter));
            counter++;
        }
    }

expected result:
[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], [10, 11, 12, 13, 14, 15, 16, 17, 18, 19], [20, 21, 22, 23, 24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35, 36, 37, 38, 39], [40, 41, 42, 43, 44, 45, 46, 47, 48, 49]]

A: You can use IntStream.range(int startInclusive, int endExclusive) to generate a stream of integers.
You can then use mapToObj(IntFunction<? extends U> mapper) to process those integers.
Finally, you can use collect(Collector<? super T,A,R> collector) to collect the values, e.g. to a List by using Collectors.toList().
List<List<String>> my2dList =
        IntStream.range(0, 5)
                 .mapToObj(i -> IntStream.range(0, 10)
                                         .mapToObj(j -> Integer.toString(i * 10 + j))
                                         .collect(Collectors.toList()))
                 .collect(Collectors.toList());

UPDATE
If you want to print the values as they are streamed, use peek(Consumer<? super T> action).
If the peek() method should see the value as an int, you can split the expression in the mapToObj so you can peek at the intermediate value, before it is converted to String.
The conversion to String can then be done with a method reference, instead of a lambda.
                 .mapToObj(i -> IntStream.range(0, 10)
                                         .map(j -> i * 10 + j)
                                         .peek(val -> System.out.println("Counter: " + val))
                                         .mapToObj(Integer::toString)
                                         .collect(Collectors.toList()))


text:
Q: Data Analysis for Spoofed DNS A remote nameserver, that I do not have privileges on, is intermittently responding with spoofed addresses. I want to monitor this server and collect data on the spoofed responses for analysis. How should I go about doing this?
I essentially want to query for a known domain, compare it to the known IP address, and log the data. I intend to visualize the amount of time the server is responding with spoofed vs. legitimate - as well as patterns in this behavior.
Im hoping there are tools readily avaiable to do this, but I could do some python/sql if needed. Please advise.
Example:
An A record query for google.com will return 195.22.26.248.
Obviously not a google address

A: I'm going to assume that you know what you're talking about when you say that it's a single DNS server. I'm skeptical because you have not shared your methodology for determining this, but my answer will take it as a given that this information is accurate.
Normally you would perform a query, look at the observed TTL, and query again once that TTL expires. You would continue this until your predetermined sampling period is reached and compare good answers against bad answers.
Unfortunately, the operative word here is "normally". You're looking for a deterministic answer, but these are hard to come by once a server is compromised and in most cases you have to throw logic out the window until you know the specifics of the exploit methodology.

*

*Given your other question on security.SE, it's more likely that the server software itself has been compromised than this being the result of being bombed with forged answers.

*Bombing of spoofed packets would always cycle out on a TTL, but other methods
might change the reply unpredictably before the TTL window has
expired. In the latter case, it's hard to tell whether the change is
due to a refresh or not unless you're 100% certain that you're
dealing with a single server and not a farm behind a VIP. TTL will vary pretty consistently in the latter case.

Long story short, you're putting in a lot of work for a problem that isn't yours to own, and since you don't own it you have very few ways of making sure that your gathered information provides a useful conclusion. (aside from an academic exercise in ratio of raw good:bad replies over time, which would turn this Q&A into one of those "gimme the codez" questions that we frown on on this SE site)

A: You can use dig www.example.com in bash on most Linux systems to perform a DNS lookup, the output can be customized based on the amount of detail you would like.  You can save known good output to a file then compare results using diff.  Logging can be performed by extracting the desired info from dig output, then it you can save it in whatever format you want using a log file or database.  Using date +%s you can get a unix timestamp to add to the log, which make selecting a time range in the logs a matter of integer comparison on a single value.


text:
Q: Why do these days of the week line up? I go to the gym every Mon/Wed/Fri while a friend of mine goes every 3 days regardless of the day. A typical two weeks could look like:
     Su | M | T | W | R | F | Sa | Su | M | T | W | R | F | Sa
 ME:      X       X       X             X       X       X
HIM:          X           X             X           X

To my surprise, I've observed that I see him exactly once a week. I decided to look at it from a math perspective.
It's clear the number of times a week I see him has an upper bound of 1. If I see him Mon, he'll come in Thurs and I won't see him Wed/Fri. The same logic can be used for if I see him Wed/Fri.
However, I'm not sure why the lower bound here is 1. My intuition tells me it has something to do with modulus 7, since the days he comes to the gym are cyclical (this would also make some kind of sense since I'm coming to the gym every two days 3 times while he comes every 3 days and his cycle repeats every 3 weeks) but I can't make the mathematical leap.
I also tried to generalize. What if I come in for 3 days that are each 1 apart? Then it's obvious I'll see him exactly once. But what if I come in 3 days that are each 4 days apart?
I can bruteforce this to find that I'm right, but intuitively, why are our days lining up exactly once a week?

A: Let's think of numbers $0, 1, \ldots, 6, \ldots$ as the days starting from some Sunday.
Then every Monday, Wednesday, and Friday, means $\{7n + 1, 7n + 3, 7n + 5\}$.
"Every three days" is all days of the form $3n + k$, where $k \in \{0, 1, 2\}$. Equivalently, these are all days that are $\equiv k \pmod 3$.
Taking $\{\rm M, W, F\}$ modulo $3$, we get $\{n+1, n, n+2\}$, which is the same as $\{0,1,2\}$, thus one of Monday, Wednesday, Friday is $k \pmod{3}$. Thus for any $k$, there is a day that matches both sets.

A: Your pattern would repeat every 2 days if you didn't include Sunday. Looking at the six days from Monday to Saturday, your pattern is:
X-X-X- (1, 3, 5)

which is all the odd numbers, if Monday is day 1.
Your friend goes every 3 days and his pattern shifts compared to yours:
X--X-- (1, 4)
-X--X- (2, 5)
--X--X (3, 6)

Only one of his days will be odd, the other will be even for the six overlapping days. That's why it will always be one day per week you will be at the gym on the same day.

A: He comes in every three days, so on any given week he comes in on all day whith numbers congruent to x modulo 3, just the x changes from week to week, but it can be assumed to be 0, 1, or 2.
You on the other hand come in on days 0, 2, 4. Modulo 3, that is 0, 2, 1. So he will be there on exactly one of your days.
What makes this particular setup work: He comes in every $n$ days, you come in on exactly $n$ days, and the days on which you come in are $m$ apart, where $m$ is relatively prime to $n$ (so that $0$, $m$, $2m$, ..., $(n-1)m$ are all different modulo $n$).

A: Take any three numbers of the form $n,n+2,n+4$ for some $n\in\Bbb N$. Then one of them, and exactly one, is a multiple of $3$.
This is because $2$ is a generator of the cyclic group of order $3$,  $\Bbb Z/3\Bbb Z$.

A:
It's clear the number of times a week I see him has an upper bound of 1. If I see him Mon, he'll come in Thurs and I won't see him Wed/Fri. The same logic can be used for if I see him Wed/Fri.

Similar logic works the other way around. Since he comes every three days, he'll have to be there on Monday, Tuesday or Wednesday:

*

*If he comes in on Monday, you'll see him on Monday.

*If he comes in on Tuesday, he'll also come on Friday, and you'll see him on Friday.

*If he comes in on Wednesday, you'll see him on Wednesday.

So there's also a lower bound of 1.
If you go on three days that are four days apart, they can be numbered as $n$, $n+4$, and $n+8$. Modulo 3, these are $n$, $n+1$ and $n+2$. All remainders modulo 3 are covered, so exactly one of these days coincides with the every-three-days cycle of the other person.
On the other hand, if you went on days that are three apart (or any multiple of three), then your partial cycle would be locked with the other person's cycle, and you'd see him either every time, or never.

A: One way of analyzing this is to take your period (7 days), his period (3 days), and take the lcm (21 days). Every 21 days, your combined pattern will be the same. Once you see what happens each week three weeks in a row, you know what the general pattern is. This can be generalized to other cases.

Then it's obvious I'll see him exactly once. But what if I come in 3 days that are each 4 days apart?

Then your period will be 12 days, and his will be 3, so your combined period will be lcm(12,3) = 12. If you line up the first time, the next time you will be one day late. The third time, you will be two days late. The fourth time, you will be three days late, but since he comes every three days, you will line up again. So you will see him every three visits, he will see you every four of his visits, and you will see each other every 12 days.


text:
Q: rails relationship one-to-many; can't build child objects? class Photo < ActiveRecord::Base
    has_many :boosts, class_name: BoostedPhoto
    ...
end

class BoostedPhoto < ActiveRecord::Base
    belongs_to :photo
end

This is how I have it set up so far, but when i try to do this in the console:
photo = Photo.first
photo.boosts.create(title: 'testing')

I get the following results
(0.3ms)  begin transaction
(0.1ms)  rollback transaction
ActiveRecord::UnknownAttributeError: unknown attribute: photo_id

Been looking up how to do relationships for a few hours, and I think I might be overlooking something really simple...sorry for the newb question, but I'm starting to pull my hair out from frustration!

A: There should be a foreign key column in the boosted_photos table. General rule is the we put belongs_to association in the table model which have the foreign key, here it is BoostedPhoto
After that following should work,
photo = Photo.first
photo.boosts.create(title: 'testing')


text:
Q: Why Wont My HTML5/JS App Work On My iPhone? How's it going guys?
Recently, with the help given from this site, I've learned how to draw a rectangle on an HTML5 canvas at the click of the button... that's not the problem:) The is problem this... unfortunately, it didn't work at all when I tried to use it on my iPhone... why:(?

Here's my code:

JAVASCRIPT:
// "Rectangle" Button
function rect()
{
var canvas = document.getElementById('canvasSignature'),
    ctx = canvas.getContext('2d'),
    rect = {},
    drag = false;

    function init() {
  canvas.addEventListener('mousedown', mouseDown, false);
  canvas.addEventListener('mouseup', mouseUp, false);
  canvas.addEventListener('mousemove', mouseMove, false);
}

function mouseDown(e) {
  rect.startX = e.pageX - this.offsetLeft;
  rect.startY = e.pageY - this.offsetTop;
  drag = true;
}

function mouseUp() {
  drag = false;
}

function mouseMove(e) {
  if (drag) {
    rect.w = (e.pageX - this.offsetLeft) - rect.startX;
    rect.h = (e.pageY - this.offsetTop) - rect.startY ;
    draw();
  }
}

function draw() {
  ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}

init();
}

HTML5:

    <canvas id="canvasSignature" width="580px" height="788px" style="border:2px solid #000; background: #FFF;"></canvas>

<button onclick="rect();">Rectangle</button>

Any help at all would be greatly appreciated:)

A: for first you got a mistake in you code
you star with this
rect() {

and close it only at the end of script
and on touch devices you need to use touch* events i think
something like this
var canvas = document.getElementById('canvasSignature'), ctx = canvas.getContext('2d'), rect = {}, drag = false;

function init() {
  canvas.addEventListener("touchstart", touchHandler, false);
  canvas.addEventListener("touchmove", touchHandler, false);
  canvas.addEventListener("touchend", touchHandler, false);
}

function touchHandler(event) {
  if (event.targetTouches.length == 1) { //one finger touche
    var touch = event.targetTouches[0];

    if (event.type == "touchstart") {
      rect.startX = touch.pageX;
      rect.startY = touch.pageY;
      drag = true;
    } else if (event.type == "touchmove") {
      if (drag) {
        rect.w = touch.pageX - rect.startX;
        rect.h = touch.pageY - rect.startY ;
        draw();
      }
    } else if (event.type == "touchend" || event.type == "touchcancel") {
      drag = false;
    }
  }
}

function draw() {
  ctx.fillRect(rect.startX, rect.startY, rect.w, rect.h);
}

init();


text:
Q: Bulma cards changing width when resizing window Cards when window is zoomed out

Cards when zoomed in

Is there any way to make the cards not change width when resizing the window with bulma?

A: You can add a fixed width on the card with CSS, but then you are kinda going against what Bulma wants you to do (keep everything responsive) and it may break your columns.
I think your best bet would be to include some responsive column classes, so that you can specify the width according to the screen size. Untested, but just as an example:

More on Bulma responsive columns


text:
Q: Getting System.ObjectDisposedException when redirecting pages Update: The problem was that the OnGet methods was async. Thank you everyone for the help and input!
In my first page (Home) i'm getting a list of Users:
HomePageModel:
public async void OnGetAsync()
    {
            var everything = await _context.Users.ToListAsync();
            GetUsers = everything;
    }

Then i'm creating a list of the users on the page and a link that redirects to a page that has another list of the users bets:
The HomePage:

@foreach (var user in Model.GetUsers)
{

    //Irrelevant stuff
    View Bets

}

That redirects to UserBets, here's the UserBetsModel:
public async void OnGetAsync(string Id)
    {
        if (Id != null)
        {   //Debugging
            Message += Id;
            using (var db = _context)
            {
                var everything = await _db.Bet.Where(a => a.UserId == Id).Select(s => s.MatchId).SingleAsync();
                GetBets = everything;
            }
        }
    }

When it gets there i'm getting a message that says:

System.ObjectDisposedException: 'Cannot access a disposed object. A common cause of this error is disposing a context that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling Dispose() on the context, or wrapping the context in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances.
  Object name: 'AsyncDisposer'.'

I've tried withouth having using scopes, having it on both pagemodels.
The thing is that i don't really understand the problem here, so i'm sorry if i'm not giving you enough context or code but ask if you need more.
What i want to do is print out a list of the users bets.
Thanks in advance!

A: using (var db = _context)
{
    var everything = await _context.Bet.Where(a => a.UserId == Id).Select(s => s.MatchId).SingleAsync();
    GetBets = everything;
}

Your using will dispose of _context immediately after the GetBets = everything; line. The problem is that _context doesn't belong to your method, so any other code that uses _context will find it disposed. I imagine you have similar code elsewhere that is disposing of it too, which is probably why the issue is presenting here.
Don't dispose of shared objects until they aren't going to be used anymore (usually when the containing class is destroyed - you should add your own IDisposable implementation on the parent class).


text:
Q: Is it possible to change the min-height of Google+ comment on Blogger? I just created a new Blogger blog and successfully incorporated the Google+ comment using the Blogger built-in feature. But I noticed that a div id="widget_bounds" is consuming too much of empty spaces with the min-height=600px CSS property. I suspect that the code was generated on the fly and I couldn't find the div in my Blogger template code. I wonder if it is possible to change its min-height to something like 250px and let it auto-expands as the comment grows?
You can refer my website with this URL:
http://blog.malaysiatraining.net/2013/08/official-blog-announcement.html
Any advice would be appreciated. Thank you.

A: No, it's not possible to change.

A: You can't to change the min-height of google+ comments.

A: I have this problem.
You can set style for frame's parent element:
.parent {
   position: relative;
   height: 240px;
   overflow: hidden;
}


text:
Q: Wordpress:"Your PHP installation appears to be missing the MySQL extension which is required by WordPress." A few hours ago I installed wordpress on my localhost, but when I connect to it with my browser an Error is displayed

Your PHP installation appears to be missing the MySQL extension which is required by WordPress."

My PHP version is 7.0 and I know that I have installed MySQLi.
The DataBase for Wordpress is set. I create the user and the password.
A few minutes ago I installed a plugin which is supposed to solve the problem, but when I refresh the page it goes in blank


text:
Q: how to disable the back button after logout in angular 7 I have one login page as part of my application . I want to disable my back button after logout successfully so that the user can not go back.

A: You can add a guard to watch and decide if user can access the page or not rather than disabling the browser's events. CanActivate is the saviour

CanActivate (Interface)
Interface that a class can implement to be a guard deciding if a route
  can be activated. If all guards return true, navigation will continue.
  If any guard returns false, navigation will be cancelled. From official documentation of Angular

Here I am adding some code that I am currently using. Hope it helps to understand how to implement one.
import { CanActivate, ActivatedRouteSnapshot, Router, RouterStateSnapshot } from '@angular/router';

import { IdentityService } from './identity.service';

@Injectable()
export class LoginGuard implements CanActivate {

    constructor(private identityService: IdentityService, private router: Router) { }

    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
        if (this.identityService.isLoggedIn()) { // determine if the uder is logged in from this method.
            return true;
        }
        this.router.navigate(['/login']);
        return false;
    }
}

add this LoginGuard class into provider in you app.module.ts
providers: [{ provide: LoginGuard, useClass: LoginGuard }]

then add canActive in the route to guard it.
{
    path: 'dashboard',
    component: DashboadComponent,
    canActivate: [LoginGuard]
}

A: You cannot disable it, you can only prevent it. Just check the login status and redirect it to a specific page if they're redirected to a page that needed to be logged in

A: yes Auth gurad is been useful here .
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth-service.service';

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(private authService: AuthService) {

  }

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    return this.authService.getisLoggedIn();
  }
}

Add the auth guard in app.module.ts
{ path: 'home', component: HomeComponent, canActivate: [AuthGuard] }
{ path: 'logout', component: LogoutComponent , canActivate:[AuthGuard]}

So that after logout we can disable the back button
Add the auth guard as part of app.module.ts
providers: [AuthGuard]

A: You can try below, It worked for me.
https://www.npmjs.com/package/angular-disable-browser-back-button
import { NgModule } from '@angular/core';
import { BackButtonDisableModule } from 'angular-disable-browser-back-button';

@NgModule({
  ...
  imports: [
    ...
    BackButtonDisableModule.forRoot()
  ],
  ...
})
export class AppModule {}


text:
Q: Swift Strings appear to mishandle carriage returns and newlines together For context, the app I'm developing is using a Bluetooth UART connection, and that's how I discovered this apparent issue.
When ending my messages with "/r/n" Swift ignores the newline when considering the length of the string. I can actually add a SECOND newline, but that introduces UART bugs.
Here's some code that outlines my issue:
var str = "Hey Apple"
print(str.count) //9
str += "\r" //"Hey Apple\r"
print(str.count) //10
str += "\n" //"Hey Apple\r\n"
print(str.count) //10
str += "\n" //"Hey Apple\r\n\n"
print(str.count) //11

var str2 = "Uh, hello?"
print(str2.count) //10
str2 += "\n" //"Uh, hello?\n"
print(str2.count) //11
str2 += "\n" //"Uh, hello?\n\n"
print(str2.count) //12
str2 += "\r" //"Uh, hello?\n\n\r"
print(str2.count) //13

There's something fishy here, and I don't know why.
Ideas?

A: Both "\r" and "\r\n" count as a single "extended Unicode grapheme
cluster", and that is what str.count counts (compare
"Strings and Characters" in the Swift
reference and Strings in Swift 2 in the Swift blog).
If you convert the string to UTF-8 data for sending it via Bluetooth
and determine the actual length of the data
let data = Data(str.utf8)
let count = data.count // == str.utf8.count

then everything works as expected:
var str = "Hey Apple"
print(Data(str.utf8) as NSData) // <48657920 4170706c 65>
print(Data(str.utf8).count) // 9

str += "\r" //"Hey Apple\r"
print(Data(str.utf8) as NSData) // <48657920 4170706c 650d>
print(Data(str.utf8).count) // 10

str += "\n" //"Hey Apple\r\n"
print(Data(str.utf8) as NSData) // <48657920 4170706c 650d0a>
print(Data(str.utf8).count) // 11

str += "\n" //"Hey Apple\r\n\n"
print(Data(str.utf8) as NSData) // <48657920 4170706c 650d0a0a>
print(Data(str.utf8).count) // 12


text:
Q: Issues updating data after insert trigger I am currently creating my first trigger the way it works is as follows.
When someone inserts data on an extension table, I have the trigger fire an insert statement. The insert statement places the data that was inserted into a table. Once this is done, I have a proc that fires off that inserts the data into another table and then truncates the tables that the data was temporarily stored in.
This works great but I am now getting a duplicate key error every time I try to update, which I assume would re-insert and overwrite the previous data? I believe I have to create an update trigger as well but I can't seem to figure out the logic on how to do so. What would be the best approach to dealing with updating the data?