text:
Q: Convert JSON to an unordered HTML list (DFS?) I have a little problem with converting JSON to a list. I'm able to read all elements but currently it makes a bad list structurally.
Here is JSON:
{
  name: 'test,
  value: 'value',
  nodes: [
    {
      name: 'next test',
      value: 'next value',
      nodes: [...]
    },
    {
      name: 'third test',
      value: 'third value',
      nodes: [...]
    }
  ]
}

I'd like to create something like this:

test: value

next test: next value

third test: third value

I've created a loop in CoffeeScript but it makes something like this instead:

test: value

next test: next value

third test: third value

So everything is nested in each other.
Here is my code:
point = $('#jstree_demo_div');

        loopData = (node) ->
          if(node.name != undefined)
            name = node.name;
            value = node.value;
            ul = $('
');
            li = $('
');
            li.append(name + ' - ' + value + '');
            ul.append(li);
            point.append(ul);
            point = li;
            for chart in node.nodes
              loopData(chart);

        loopData(json);

Any idea what should I change here to make a proper structure list?
There is this condition:
if(node.name != undefined)

because it shouldn't go to the next deeper node when there is a name undefined.

A: Here's an answer with vanilla Javascript:
  var json = {
    name: 'test',
    value: 'value',
    nodes: [
      {
        name: 'next test',
        value: 'next value',
        nodes: [{}]
      },
      {
        name: 'third test',
        value: 'third value',
        nodes: [{}]
      }
    ]
  }

  function makeNewList(obj) {
    // if the object does not contain children, make a 'li' element only
    if (obj.nodes[0].name === undefined) {
      var res = document.createElement('li');
      res.innerHTML = obj.name + ": " + obj.value;
      return res;
    }
    // otherwise, first make a 'ul' element with main name and value, then
       // nest a new 'ul' with child nodes inside
    else {
      var res = document.createElement('ul');
      var nameLi = document.createElement('li');
      nameLi.innerHTML = obj.name + ": " + obj.value;
      res.appendChild(nameLi);
      var nestedNodes = document.createElement('ul');
      obj.nodes.forEach(function(node) {
        nestedNodes.appendChild(makeNewList(node));
      })
      res.appendChild(nestedNodes);
      return res
    }
  }


text:
Q: DiffUtil is not updating recyclerview when items are moved I implemented drag and drop in RecyclerView and is using DiffUtil to dispatch updates. But it appears items moves are somehow not dispatched by DiffUtil to the adapter. However, if I call notifyItemMoved() on the adapter, it works.
In the Adapter
fun updateItems(items: List<Item?>) {
        val diffResult = DiffUtil.calculateDiff(MyDiffCallback(this.items, items), true)
        diffResult.dispatchUpdatesTo(this)
        this.items = items
    }

Repository
fun swap(fromPosition: Int, toPosition: Int) {
        val list = liveItems.value
        Collections.swap(list, fromPosition, toPosition)
        liveItems.value = list
    }

Item
data class Item(val id: String, @StringRes val title: Int, @DrawableRes val icon: Int) {

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false

        other as Item

        if (id != other.id) return false
        if (title != other.title) return false
        if (icon != other.icon) return false

        return true
    }

    override fun hashCode(): Int {
        var result = id.hashCode()
        result = 31 * result + title
        result = 31 * result + icon
        return result
    }
}

MyDiffCallback
class MyDiffCallback(private val oldList: List<Item?>?, private val newList: List<Item?>) :
    DiffUtil.Callback() {

    override fun getOldListSize(): Int {
        return oldList?.size ?: 0
    }

    override fun getNewListSize(): Int {
        return newList.size
    }

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList!![oldItemPosition]!!.id == newList[newItemPosition]!!.id
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList!![oldItemPosition]!! == newList[newItemPosition]
    }

}

Please note the id variableis specific to eachItem`.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Idiomatically creating hot observables with BehaviorSubject in RxKotlin / RxJava Currently I'm building a project in Kotlin using RxKotlin. My background with Rx is primarily grounded in RxJS.
A pattern I would regularly use for creating hot observables in Typescript would look something along the lines of this:
  private dataStore: IFoo;
  private dataStoreSubject: BehaviorSubject<IFoo> = new BehaviorSubject(this.dataStore);
  public dataStoreObservable: Observable<IFoo> = Observable.from(this.dataStoreSubject);

  public getNetworkData(): Observable<IFoo[]> {
      return this.http.get()
         .map((response: IResponse) => {
             this.dataStore = <IFoo[]>response;
             this.dataStoreSubject.next(this.dataStore);
             return this.dataStore;
          });
   }

This would allow me to expose an Observable, without exposing the Subject and subsequently the subject.next(); method.
My question is: What would be the most idiomatic way to establish similar logic in RxKotlin or RxJava?

A: You need to use compose and transform. You can add "link" between your subject and observable into the transform.


text:
Q: How to divert All incoming calls to voicemail through coding in Android How to divert All incoming calls to voicemail through coding in Android? I am aware that you can set a flag for a contact which determines whether the call should be diverted to voicemail or not. ContactsContract.RawContacts has got a flag to indicate that call should be forwarded to voice mail
SEND_TO_VOICEMAIL read/write An indicator of whether calls from this raw contact should be forwarded directly to voice mail ('1') or not ('0').
However I need to send all incoming call to voice mail.
Thanks,


text:
Q: Jenkins Perforce Plugin - multiple changelists in a single poll I'm using the Jenkins Perforce plugin, and polling a workspace for changes, then a build is running on the caught changelist.
The problem: In case there are multiple changelists caught in the same poll, the build is running ONLY on the last changelist (and not on all of the changelists)
P4_CHANGELIST contains the last changelist.
How can I run the build on each of the caught changelists?

A: As for running a build for each changelist, that is a feature request that hasn't yet been acted upon (first answered in This Question).
The specific changelist information is in the metadata for the job.   I'm not sure you can get to it during the build phase, but you can definitely see it afterwards.   The Summary of Changes section shows just the changelists since the last build.
In the builds directory for each job, there is a changelog.xml file that contains entries for each individual "changelog entry", which in the case of Perforce is a changelist.   The changenumber element of each entry indicates the changelist number from perforce.
Finally, if you want to scrape the information for an automated process external to the Jenkins server, you can retrieve XML data on the last build by retrieving:
http://{sereveraddress}/job/{jobname}/lastSuccessfulBuild/api/xml

Which will return an XML structure containing the changeSet list of items which each have the changeNumber in them (along with the msg and each affectedPath).   This data is also available in json.

A: The more correct way of implementing this would be to parameterize your job to run at a specific changeset, then write a post-commit trigger in your perforce server that starts the Jenkins job remotely, either using the CLI or through something as simple as curl. This has the added advantage of building every changeset as they are committed, rather than in batches whenever the polling interval occurs.
As has been mentioned, this functionality doesn't exist in Jenkins core yet. Fortunately, there is a ticket open for adding this functionality directly to the Perforce Plugin. This would essentially cause it to only build the next change whenever it is run, and should be fairly simple to implement, but will have the disadvantage of only running one build per polling period.
https://issues.jenkins-ci.org/browse/JENKINS-17889

A: Solution was found!
The problem was with the polling that didn't provided the multiple changelists info.
Instead of polling the branch with Jenkins\Perforce plugin, I used a Perforce query to find all queries that were submitted since last build.
Here is what I did in order to solve the problem:

*

*I've created a standalone job to build a changelist by it's a number.

*I've created a job the finds all changelists that were submitted since the last changelist build (param LATEST_CHANGELIST_NUMBER that is saved in a file or registry).
In order to do that I used the Perforce query:
p4 changes "//projects/BRANCH_NAME/...@>LATEST_CHANGELIST_NUMBER"

Then I build each of the found changelists and update the LATEST_CHANGELIST_NUMBER (in a file for example).
It works fine!
Thanks for the ideas!

A:
Checked the builds will occur with 1 change per build, unchecked you gat all changes since the quiet period started.


text:
Q: Multiple data stored into a field for better management? I have a MySQL table as follow:
id, user, culprit, reason, status, ts_register, ts_update

I was thinking of using the reason as an int field and store just the id of the reason that could be selected by the user and the reason itself could be increased by the admin.
What I meant by increased is that the admin could register new reason, for example currently we have:
Flood, Racism, Hacks, Other

But the admin could add a new reason for instance:
Refund

Now my problem is that I would like to allow my users to select multiple reasons, for example:
The report 01 have the reasons Flood and Hack.
How should I store the reason field so that I could select multiple reasons while maintaining a good table format?
Should I just go ahead and store it as a string and cast it as an INT when I am searching thru it or there are better forms to store it?
UPDATE Based on Jonathan's reply:
SELECT mt.*, group_concat(r.reason separator ', ') AS reason
  FROM MainTable AS mt
  JOIN MainReason AS mr ON mt.id = mr.maintable_ID
  JOIN Reasons AS r ON mr.reason = r.reason_id
  GROUP BY mt.id

A: The normalized solution is to have a second table containing one row for each reason:
CREATE TABLE MainReasons
(
    MainTable_ID INTEGER NOT NULL REFERENCES MainTable(ID),
    Reason       INTEGER NOT NULL REFERENCES Reasons(ID),
    PRIMARY KEY(MainTable_ID, Reason)
);

(Assuming your main table is called MainTable and you have a table defining valid reason codes called Reasons.)

From a comment:

[W]ould you be [so] kind [as] to show me an example of selecting something to retrieve a report's reason? I mean if I simple select it SELECT * FROM MainTABLE I would never get any reasons since MainTable doesnt know it right? Because it is only linked to the MainReasons and Reasons table so I would need to do something like SELECT * FROM MainTable LEFT JOIN MainReasons USING (MainTable_ID) or something alike but how would I go about getting all the reasons if multiples?

SELECT mt.*, r.reason
  FROM MainTable AS mt
  JOIN MainReason AS mr ON mt.id = mr.maintable_ID
  JOIN Reasons AS r ON mr.reason = r.reason_id

This will return one row per reason - so it would return multiple rows for a single report (recorded in what I called MainTable).  I omitted the reason ID number from the results - you can include it if you wish.
You can add criteria to the query, adding terms to a WHERE clause.  If you want to see the reports where a specific reason is specified:
SELECT mt.*
  FROM MainTable AS mt
  JOIN MainReason AS mr ON mt.id = mr.maintable_ID
  JOIN Reasons AS r ON mr.reason = r.reason_id
 WHERE r.reason = 'Flood'

(You don't need the reason in the results - you know what it is.)

If you want to see the reports where 'Floods' and 'Hacks' were the reasons given, then you can write:
SELECT mt.*
  FROM MainTable AS mt
  JOIN (SELECT f.MainTable_ID
          FROM (SELECT MainTable_ID
                  FROM MainReason AS mr1
                  JOIN Reasons    AS r1  ON mr1.reason = r1.reason_ID
                 WHERE r1.reason = 'Floods'
               ) AS f ON f.MainTable_ID = mt.MainTable_ID
  JOIN (SELECT f.MainTable_ID
          FROM (SELECT MainTable_ID
                  FROM MainReason AS mr2
                  JOIN Reasons    AS r2  ON mr2.reason = r2.reason_ID
                 WHERE r1.reason = 'Hacks'
               ) AS h ON h.MainTable_ID = mt.MainTable_ID

A: To do a one-to-many relationship, I would spin reason off into it's own table, like so:
id, parent_id, reason

parent_id would refer back into your current table's id.
You could store it as an INT, but it would be a continual pain to have to parse it every time you wanted to read the data.  This way would just take one more join.


text:
Q: How can I resolve thenReturn() may be missing exception in junit Can someone please help what to do to resolve below mentioned exception
When stubbing below mentioned line
Mockito.doNothing().when(customerRepository.save(customerProduct))

Suggest me correct execution here
E.g. thenReturn() may be missing.

Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();

Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3. you are stubbing the behaviour of another mock inside before 'thenReturn' instruction is completed

A: The mockito docs tell doNothing() method should be used like this:
doNothing().when(mock).method()

So in your case you may want to try this:
Mockito.doNothing().when(customerRepository)
    .save(customerProduct)


text:
Q: PrintWriter create empty file I have StringBuilder sb and I want that string save as *.txt file. Problem is that I get "filename.txt" but it is completely empty, also there is no errors in console.
Here is my code:
System.out.print(sb.toString());
PrintWriter out;
try{
    out = new PrintWriter("filename.txt");
    out.println(sb.toString());
}catch (Exception e) {
    e.printStackTrace();
}

Console output:
[19/3/2014]

Ime in priimek: Matjaz Mav
Naslov: Ppot 6, 1000 Ljubljana
Telefon: 040 111 222

Registerska št.: LJ 1234
Znamka: Citroen
Model: C4
Letnik: 2005
Opombe: Popravi

Thanks!

A: You should use out.close() statement in this program.

A: out.close ();   is missing.
You have to put it in to close the session.

A: Either create your PrintWriter with this constructor, changing the first argument to an OutputStream:
out = new PrintWriter(new FileOutputStream("filename.txt"), true);

to turn on auto flushing, or, just close the writer once you're done writing to it with out.close().

A:    PrintWriter out;
   try{
       out = new PrintWriter("filename.txt");
       out.println(sb.toString());
       //add the below lines
       out.flush();
       out.close();
   }catch (Exception e) {
       e.printStackTrace();
   }

Another way is to have a PrintWriter with autoFlush on. That can be achieved by
  out = new PrintWriter(new FileOutputStream("filename.txt"), true);

If you do only out.close() that would also solve the problem at hand as that would internally flush the content written in its internal buffer.
Hope this helps.


text:
Q: MapView to background - Corona SDK I need some help with the MapView in Corona SDK. I want to put the map as background (but with all functions) and, in this case, a button to the front. Here is my code:
function scene:createScene( event )
    local group = self.view

    if ( system.getInfo( "environment" ) == "simulator" ) then
        local simulatorMessage = "Maps not supported in Corona Simulator.\nYou must build for iOS or Android to test native.newMapView() support."
        local label = display.newText( simulatorMessage, 36, 40, 270, 0, native.systemFont, 12 )
        label.anchorX = 0
        label.anchorY = 0
    end

    myMap = native.newMapView( 20, 20, display.contentWidth, display.contentHeight )

    if ( myMap ) then
        myMap.mapType = "normal"
        myMap.x = display.contentCenterX
        myMap.y = display.contentCenterY
        myMap:setCenter( currentLatitude, currentLongitude )
        myMap:addEventListener("mapLocation", mapLocationListener)
    end

    backBtn = widget.newButton
    {
        id="backButton",
        label="Back",
        fontSize="30",
        labelColor={ default={1, 1, 1}, over={0, 0, 0, 0.5} },
        defaultFile="images/button.png",
        width = dispWidth * 0.25, height = dispHeight * 0.1,
        onRelease = onBackBtnRelease
    }
    backBtn.anchorX = 0.5
    backBtn.anchorY = 0.5
    backBtn.x = display.contentWidth * 0.8
    backBtn.y = dispHeight * 0.8
    backBtn:toFront()

    group:insert( backBtn )
    group:toFront() --second try to put that button to front
end

Since the MapView is a native object I can't add it to any group and 'mapView:toBack()' doesn't work as well ('attempt to index upvalue 'myMap' (a nil value)'). In Corona SDK the button appears without the map, as expected. On device I get the map without my button, not as expected.
Is it any possible to put a native object to the back, or to force something to be in the front?

A: What you are trying to do with the map and the button is not currently possible with CoronaSDK.
Indeed the MapView is a native object. According to Corona's documentation, you cannot place other objects on top of a MapView.
The documentation says:

Map objects, like other native display objects, cannot be inserted into groups and are always displayed on top of regular Display Objects (groups, vector, images, and text).

See documentation here
Good luck coding.

A: First Check the Following :
If button doesn't appear on device most common problem will be , you might misspell the Image names(Check for Caps) or check the path of the file is proper or not.
To know in detail about the mapView : http://docs.coronalabs.com/api/library/native/newMapView.html
I know you might have visited already, its better you look again.
Thanks,


text:
Q: application defined or object defined error - Excel VBA .range(cells I have a line of code that is displaying the application defined or object defined error, I have no idea why.
filenm17 = "DSR Consolidated"
findstring16 = "21"

filenm17 and findstring16 are both defined as strings. I tried removing findstring16 and replacing it with the formula to get findstring16 (it's a cell reference .value) but that still didn't work.
Workbooks(filenm17).Sheets("5").Range(Cells(67, findstring16 + 2), _
                               Cells(440, findstring16 + 2)) = firstarray

Please help!

A: Without a qualifying worksheet, your Cells() will refer to the Activesheet: if that isn't "5" then they don't match the Range() and that will trigger the error you're getting.
Try:
With Workbooks(filenm17).Sheets("5")
    .Range(.Cells(67, CLng(findstring16) + 2), _
           .Cells(440, CLng(findstring16) + 2)).Value = firstarray
End With


text:
Q: `-': no implicit conversion of Fixnum into Array A user inputs coins in a comma-separated list, and then they put a colon before the amount of change they want. We have coins: £1 (100p), 50p, 20p, 10p, 5p, 2p, and 1p, and we wish to give the customer 57p. The data input would be like this: 100,50,20,10,5,2,1:57. Change is given to the user in the simplest way.
This is my code:
user_input = gets
i = 0
change_needed = 67
coins = [50,5,20,1,5]
check_input = user_input.length
coins = user_input.split(',')
change_needed = user_input.split(':')
coins_length = coins.length
coins.map!(&:to_i)
coins = coins.sort {|a,b| b <=> a}
if check_input < 100 then
  while change_needed != 0 do
    if change_needed - coins[i] then
      change_needed -= coins[i]
    else
      i += 1
      puts "#{i} is the number in the coin array"
    end
  end
else
end

I get the following error message on the line if change_needed - coins[i] then:

rb:17:in `-': no implicit conversion of Fixnum into Array (TypeError)

I don't understand this error message. It seems to be a simple fix, but I can't grasp what I need to do with my code to fix it.

A: In change_needed = user_input.split(':') you are setting change_needed to an array, not to an int.
Try replacing:
coins = user_input.split(',')
change_needed = user_input.split(':')

with
coins_part, change_needed_part = user_input.split(':')
coins = coins_part.split(',')
change_needed = change_needed_part.to_i


text:
Q: Add conditional filter before applying limitTo Can I use limitTo along with a conditional? The documentation of it shows only simple usage.
Say I want to display 2 results of items named car:
$scope.items = [
    {"name":"laptop","color":"green"},
    {"name":"shoe","color":"blue"},
    {"name":"Car","color":"gold"},
    {"name":"Car","color":"gold"},
    {"name":"Car","color":"gold"}
];

Plunker

A: You can prepend an additional filter to your limitTo filter. This is known as filter chaining:

{{item.name}}

If you'd like for filter to apply to only your items array's name property, you can use an object literal to narrow it down:

{{item.name}} - {{item.color}}

This can also use a dynamic value based on user input:
<input type="text" ng-model="search.name" />

{{item.name}} - {{item.color}}

Read more about filter chaining in the Angular docs.


text:
Q: Skip code fragments when cargo check runs I have a proc-macro that makes some compile-time job, generating some SQL queries.
That queries should be executed when processed, that is, when the macro full expands, there's another one that takes the results and launches them against the selected database.
Everything is fine, but the analyzers. These are running cargo check for reporting the status of your code, so every time that my code is analized, those queries are executed. I want to avoid that process, and only enable it if it's triggered with a cargo build or cargo run.

*

*Is this possible?

I am looking for something similar like this
#[ignore_cargo_check]
pub async fn launch_queries() {
    /* some database stuff */
}

Or even better, at call site:
#[ignore_cargo_check]
my_module::launch_queries().await;


text:
Q: Filtering out of required JSON object from a JSON Array column in postgresql with the input as single parameter I have a select query return and it shows the result like below:
select * from table gives the result like below

I have parameter called Apple If I pass the parameter somewhere in query I should get the result like below

How to get this in postgresql. If anyone knows please share the answer below.

A: I would do this with a helper function for clarity. And it might be reusable.
create or replace function filter_jsonb_array(arr jsonb, fruit text)
returns jsonb language sql immutable as
$$
select coalesce
(
 (select jsonb_agg(j) from jsonb_array_elements(arr) j where j ->> 'fruit' = fruit),
 '[]'::jsonb
);
$$;

and then
select "Column_A", "Column_B", filter_jsonb_array("Column_JSONARRAY", 'Apple') from table_;

If you do not want a function then the function body can be placed directly into the select query.
select
  "Column_A",
  "Column_B",
  coalesce
  (
   (select jsonb_agg(j) from jsonb_array_elements("Column_JSONARRAY") j where j ->> 'fruit' = 'Apple'),
   '[]'::jsonb
  ) "Column_JSONARRAY"
 from table_;

A: Considering your datatype of column Column_JSONARRAY is JSONB, try This:
with cte as (
   SELECT column_a, column_b,  (column_jsonarray ->> ( index_-1 )::int)::jsonb  AS "column_jsonarray"
     FROM table_
    CROSS JOIN jsonb_array_elements(column_jsonarray)
     WITH ORDINALITY arr(array_,index_)
    WHERE array_->>'fruit' in ('Apple')
)

select t1.column_a, t1.column_b, jsonb_agg(t2.column_jsonarray)
from table_ t1
left join cte t2 on t1.column_a =t2.column_a and t1.column_b =t2.column_b

group by t1.column_a, t1.column_b


text:
Q: How to use poisson to estimate arrival time (generate random integers)? In my assignment, I'm supposed to use a distribution curve to describe how many minutes will the employee come to work in advanced or later than the planed start time.
I decided to use Poisson distribution to solve my case. However, I don't know how should I assign the parameter to the Poisson function. I want my x-axis is from 0 to 60 minute (integer). The peak of the curve should be show up when x is 15. Should I just assign the lambda as 15?
I don't know if it's correct to use Poisson distribution to estimate the arrival time, and also don't know, if Poisson is correct, then should I just let the lambda be 15 and that's it, how can I set up a specific range (0, 60)?

A: A geometric distribution may be better suited to the problem you describe. A poisson distribution is basically a binomial distribution in the limit, and is a good approximation when the number of trials $n$ is large and the probability $p$ of the Bernoulli process is small. Thus $\lambda \approx np$, where $\lambda$ is the mean expected value. And, if you want the average value to be 15, you should use the distribution $Poi(\lambda = 15)$.
To calculate the probability k events, use the following formula:
$$P(K = k) = \frac{\lambda^k}{k!}e^{-\lambda}$$


text:
Q: codeigniter select and get security I have a question about this query, does codeigniter prevent SQL injection when we use this query:
$this->db->like();
$query = $this->db->get();

A: Despite lolipaps bad attitude may as well offer an answer that actually responds to this code.
First off, this will never work so the question of whether it prevents SQL injection is moot. In order to actually get anything back from this you would need to define both the like conditions and the table from which to perform the get. eg
$this->db->like('field','string');
$this->db->get('table');

Additionally it can never be vulnerable to SQL injection as in the example code (the code we are supposed to help support) there are no arguments passed. If the code was even close to being a viable real world example it might look like this
$some_input=$this->input->post('something_from_the_outside_world');

$this->db->like('field',$some_input); //maybe the question is whether this is sanitized??
$this->db->get('table');

If the question is whether this input is sanitized for SQL injection then the answer is yes of course it is or what's the point of the Active Record class.
If you want to further clean this for cross site scripting you either need to define this in the config.php file. eg
$config['global_xss_filtering'] = TRUE;

Or use the form validation library and run the rule xss_clean


text:
Q: Found the radius of a 3D spiral (corkscrew type) I am trying to find the radius of a 3D spiral with the following constraint:

*

*Center of spheres of 3mm radius are on the spiral

*Each sphere is tangent to other

Basically, it's a spiral of 6mm sphere, and I want to know the radius of the spiral as a function of the number of spheres per tour.
With picture :
(16 sphere per tour)

(11 sphere per tour)

I know the parametric equation for a spiral is
\begin{align}
x &= r * \cos(a)\\
y &= r * \sin(a)\\
z &= r * a * \tan (b)
\end{align}
with
$r$ = radius
$a$ = angle (degre)
$b$ = constant
But there begin my problem, because I don't know what to do now.
If I put a sphere $S_1$ of center 'A' at the beginning of the spiral ($a = 0$), I have
\begin{align}
Ax &= r \\
Ay &= 0 \\
Az &= 0
\end{align}
But I don't know how to calculate the intersection of the spiral and the sphere $S_1$.
Anybody can give me a hint ?
(ps : this is a personal project, not school homework).
Thank for reading me.

A: This isn't an exact answer, but a close approximation when the radius is reasonably large (as in the two models pictured).
Suppose the individual spheres have radius $r$, and that a string of $n$ spheres make "one full turn" on a cylinder of radius $R$ in the sense of the diagram:

If the centers of all the spheres lie on a cylinder of radius $R$, each sphere cuts the cylinder (very nearly) in a disk of radius $r$. The diagram comes from cutting this cylinder open and rolling it flat. The shaded disk represents the initial ball in the chain.
The straight-line distance between the centers of the shaded disks is $2\pi R$, the circumference of the cylinder.
If the left-hand center lies at the origin, then the right-hand center has coordinates $\bigl((2n - 1)r, -\sqrt{3}r\bigr)$, so the Pythagorean theorem gives
$$
2\pi R \approx r\sqrt{(2n-1)^{2} + 3} = 2r\sqrt{n^{2} - n + 1},
$$
of $R \approx \frac{1}{\pi} r\sqrt{n^{2} - n + 1}$. For instance:

*

*If $n = 11$, then $R \approx 3.354r$, or just over $10$mm for beads of diameter $6$mm;

*If $n = 16$, then $R \approx 4.94r$, or about $14.8$mm for beads of diameter $6$mm.
This calculation is approximate because spheres (as opposed to disks) occupy space, and so will intersect slightly (inside the cylinder) when the flat diagram is rolled into a cylinder.

A: Here's an exact (but non-explicit) treatment, which I'm posting separately since the original approximation may also be of interest to posterity.
Let $r$ denote the radius of the "beads", $R$ the radius of the cylinder on which the centers lie, and $n$ the number of beads in "one turn". The centers of the beads lie along a helix of the form
$$
(x, y, z) = (R\cos t, R\sin t, Rmt).
\tag{1}
$$

If $\theta$ denotes the angular separation (measured around the axis of the cylinder) between the centers of successive beads, then without loss of generality, an "initial" bead has position $(R, 0, 0)$, while the $j$th bead has center
$$
\bigl(R\cos(j\theta), R\sin(j\theta), Rmj\theta\bigr).
\tag{2}
$$
The three unknowns $\theta$, $m$, and $R$ satisfy three constraints (shown in blue):

*

*The centers $p_{0}$ and $p_{1}$ of adjacent beads have a straight-line separation of $2r$:
\begin{align*}
  4r^{2}
  &= R^{2}\bigl[(1 - \cos\theta)^{2} + \sin^{2}\theta + (m\theta)^{2}\bigr] \\
  &= R^{2}\bigl[2[1 - \cos\theta] + (m\theta)^{2}\bigr].
\tag{3a}
\end{align*}

*The centers $p_{0}$ and $p_{n}$ of the initial bead and the $n$th bead have a straight-line separation of $2r$. From (2) with $j = n$:
$$
4r^{2} = R^{2}\bigl[2[1 - \cos(n\theta)] + (m\theta)^{2} n^{2}\bigr].
\tag{3b}
$$

*The centers $p_{0}$ and $p_{n+1}$ of the initial bead and the $(n + 1)$th bead have a straight-line separation of $2r$:
$$
4r^{2} = R^{2}\bigl[2[1 - \cos((n + 1)\theta)] + (m\theta)^{2}(n + 1)^{2}\bigr].
\tag{3c}
$$
Subtracting (3c) from (3b), simplifying, and using the cosine addition formula for $\cos((n + 1)\theta) = \cos(n\theta + \theta)$ gives
\begin{align*}
0 &= 2\cos((n + 1)\theta) - 2\cos(n\theta) - (m\theta)^{2}(2n + 1) \\
&= 2\cos(n\theta)(\cos\theta - 1) - 2\sin(n\theta)\sin\theta - (m\theta)^{2}(2n + 1),
\end{align*}
or
$$
m^{2} \theta^{2} = \frac{2}{2n + 1} \bigl[\cos(n\theta)(\cos\theta - 1) - \sin(n\theta)\sin\theta\bigr].
\tag{4a}
$$
Subtracting (3b) from (3a) and rearranging gives, similarly,
$$
m^{2} \theta^{2} = \frac{2}{n^{2} - 1}\bigl[\cos(n\theta) - \cos\theta\bigr].
\tag{4b}
$$
Subtracting (4a) from (4b) and cancelling the factor of $2$ gives
$$
0 = \frac{1}{n^{2} - 1}\bigl[\cos(n\theta) - \cos\theta\bigr] - \frac{1}{2n + 1} \bigl[\cos(n\theta)(\cos\theta - 1) - \sin(n\theta)\sin\theta\bigr],
\tag{5}
$$
an equation for $\theta$ alone. If $\theta_{n}$ denotes the smallest positive solution of (5), which is a bit larger than $4\pi/(2n + 1)$, substitution in (4b) gives $m$, and then substitution in (3a) gives $R$.


text:
Q: How to refresh the page after routing to that page on click of a button from previous page I have 2 pages, one home and page2. when I click a button on home page it is routing to page2. Now after clicking the button on home,when I comes to page2 it should be refresh,since there is some cache issue in my project. I added the window.location.reload() on ngoninit,but here my page is continuously refreshing.
Here is the code below.
home.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-home',
  template: '<button (click)="gonextPage()">Go to next page</button>',
  styleUrls: ['./home.component.css']
})

export class HomeComponent implements OnInit {
imageSource :any;
statusdata1: any;
moreThanTen:boolean = false;
showit:boolean = false;
groupList:any = [];

constructor(private router: Router) { }
gonextPage(){
this.router.navigateByUrl('/page2');
}
  ngOnInit() {
     // window.location.reload();
    /* First data */
    let response =
    {"vehicle_number":1,"vehicle_name":"car","status":"yellow"}
    let response1 = {"vehicle_number":0,"vehicle_name":"car","status":"yellow"}
    let response2 = {"vehicle_number":2,"vehicle_name":"car","status":"yellow"}
    this.groupList.push(response,response1,response2);
    console.log(this.groupList);

  }

}

page2.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
@Component({
  selector: 'app-page2',
  template: '',
  styleUrls: ['./page2.component.css']
})

export class page2Component implements OnInit {
imageSource :any;
statusdata1: any;
moreThanTen:boolean = false;
showit:boolean = false;
groupList:any = [];

constructor(private router: Router) { }

  ngOnInit() {
     window.location.reload();
    /* First data */
    let response =
    {"vehicle_number":1,"vehicle_name":"car","status":"yellow"}
    let response1 = {"vehicle_number":0,"vehicle_name":"car","status":"yellow"}
    let response2 = {"vehicle_number":2,"vehicle_name":"car","status":"yellow"}
    this.groupList.push(response,response1,response2);
    console.log(this.groupList);

  }

}

A: You dont need to manually reload. If you route to a specific component always you will get a new component. If you can explain more about ur problem I can help you.

A: I remove the previous edited answer because it is bullied.
The only way is to use an information that persists even when reloading the js (on window.location.reload();), because all the rest of the information would be lost. You can use the localStorage (with localStorage.setItem('firstReload', 'true'); ).
  ngOnInit() {
    if (!localStorage.getItem('firstReload') || localStorage.getItem('firstReload') == 'true') {
      localStorage.setItem('firstReload', 'false');
      window.location.reload();
    } else {
      localStorage.setItem('firstReload', 'true');
    }
  }

Here a working modified example: https://stackblitz.com/edit/angular-correct-routing?file=src%2Fapp%2Fpage.component.ts


text:
Q: Where are string constants stored in memory? In a C++ program, where is constant data stored, especially string constants ?
I am asking because in the following question:
Why can creating a static const std::string cause an exception?
The answer by Damon, has the following at the end:

A string_view will, contrary to a string, not allocate non-constant
  memory, copy constant data into that, and then pretend it's constant.
  Instead, it will manage a pointer directly to the constant data, and
  that's all.
That way, your constants are truly (not just formally) constant, there
  are no allocations, no possibility of exceptions, and no double memory
  usage. And for the most part, it still looks and smells like a string.
  The only notable differences being that a string_view doesn't
  guarantee nul-termination (but the character constant it points to
  does, so this is irrelevant), and the fact that it's really constant,
  not modifiable... which is exactly what you want.

Dont even the constants need to be stored in memory some where ? And if they are stored in memory (since memory is finite), isn't it possible an exception can be thrown because there is no more memory ?

A: The problem is that a std::string is an object, not just plain data.
This means that when you declare
static const std::string foobar = "foobar";

the static data that is reserved in the binary is the one for the literal "foobar" (intended as a const char*) and the space required to store a std::string object, which is NOT the space required to store its contents.
Imagine a std::string as something like, let's say
class string {
private:
  size_t length;
  char* data;

public:
  string(const char* data) : length(strlen(data), data(new char[length+1]) {
    strcpy(this->data, data);
  }
  ~string() { delete data; }
};

This is a trivial unsafe piece of code but it's just to give you the idea. When you have your static std::string the only space required is sizeof(char*)+sizeof(size_t) bytes, since the data itself is dynamically allocated on heap.
That's why using a static const std::string wastes twice the space: for the literal itself, which is passed to the constructor of the string, and for the std::string.
Now this object is not "pre-constructed" at compile time. It's constructed at runtime and the standard doesn't guarantee you when this happens exactly (indeed if it happens before calling main you are not able to catch any exception that the constructor may throw).
The cited string_view is a wrapper around a const char* which doens't waste memory as it stores only a pointer to the contents, which is not the case for a normal std::string which is designed to be mutable.

A: Static constants are stored in the 'data' segment of the executable. Exactly where they are stored may vary from system to system, but in the case of Linux for example they are loaded as part of the executable and appear immediately above the 'text segment' in the process memory map.
They are loaded into the process memory map by the operating system before the program starts executing; therefore if there is not enough memory for them, the program cannot even load, much less throw an exception!
If you are interested in the memory layout of processes, I found this blog post to be most helpful.


text:
Q: Reverse Proxy not running on HTTPS Apache Server Created a Hello_World NodeJS App.
The app is accessible at http://<DOMAIN_NAME>/app & http://<DOMAIN_NAME>:3000
but when accessed via https://<DOMAIN_NAME>/app it returns an error.
http://<SERVER_IP>:3000 also works & https:<SERVER_IP>:3000 returns an error
sudo apachectl -S
OUTPUT :
AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
VirtualHost configuration:
*:80                   okoyama.in (/etc/apache2/sites-enabled/okoyama.in.conf:1)
*:443                  okoyama.in (/etc/apache2/sites-enabled/okoyama.in.conf:45)
ServerRoot: "/etc/apache2"
Main DocumentRoot: "/var/www/html"
Main ErrorLog: "/var/log/apache2/error.log"
Mutex default: dir="/var/run/apache2/" mechanism=default
Mutex mpm-accept: using_defaults
Mutex watchdog-callback: using_defaults
Mutex proxy-balancer-shm: using_defaults
Mutex rewrite-map: using_defaults
Mutex ssl-stapling-refresh: using_defaults
Mutex ssl-stapling: using_defaults
Mutex proxy: using_defaults
Mutex ssl-cache: using_defaults
PidFile: "/var/run/apache2/apache2.pid"
Define: DUMP_VHOSTS
Define: DUMP_RUN_CFG
User: name="www-data" id=33
Group: name="www-data" id=33
<VirtualHost *:80>

    ServerAdmin admin@okoyama.in
        ServerName okoyama.in
        ServerAlias www.okoyama.in
    DocumentRoot /var/www/okoyama.in/public_html

    ProxyPreserveHost On
    ProxyPass /app http://localhost:3000/
    ProxyPassReverse /app http://localhost:3000/

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

<IfModule mod_ssl.c>
<VirtualHost *:443>
    DocumentRoot /var/www/okoyama.in/public_html
    ServerName okoyama.in
        SSLEngine on
        SSLCertificateFile /etc/ssl_install/certificate.crt
        SSLCertificateKeyFile /etc/ssl_install/private.key
        SSLCertificateChainFile /etc/ssl_install/ca_bundle.crt

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>
</IfModule>

The above code has Reverse Proxy enabled for HTTP. HTTPS works normally. I have removed the Reverse Proxy section from 443 Port for now to make the working code cleaner.
Multiple variations of solutions suggested on various platforms have been tried in Port 443 section but none worked until now.
The included turning on SSLProxyEngine & a similar Proxy method as mentioned in the HTTP section.
Suggest possible solution. I will retry & post for clarity.


text:
Q: "Be mother" - Etymology and usage I recently came across the idiom "Be mother" in a crossword. It is supposed to mean 'to pour tea'. I was surprised by the meaning, and want to ask if there is any etymology or history behind this curious idiom. Is it informal/facetious/slang?

A: It is also a saying that stems from the superstition that a female guest should never pour the tea in another woman's household - for then she would fall pregnant.
So should a woman offer to pour the tea in another woman's household ("I'll be mother"), she desires to become a mother. Or it may also be used as tongue-in-cheek by those who are not in the least superstitious.
From author and folk historian Dr. Alec Gill:

Tea-drinking and fertility were intermingled. Indeed, the tea-pouring clich' "I'll be Mother" stems directly from primitive superstition. The consequences of two people pouring from the same pot could be dire.
During the 1930s, if a man and woman took turns in pouring, a child would be born to them. A female visitor must not pour tea in another woman's house - otherwise, she would fall pregnant. This evolved to having twins and - even worse at the superstitious level - ginger-headed twins.
Thus, an early form of birth-control was to let only one person do all the pouring in company!

A: It's normally heard as Shall I be mother? meaning 'Shall I pour the tea?' It's used because pouring the tea has traditionally been seen as a mother's role. I suspect it's now heard less than it once was for various social rather than linguistic reasons. It's not slang and it's not facetious, but because of the nature of tea-drinking it's likely to be heard in informal situations.

A: Traditionally the mother in a family pours the tea. So "being mother" means "pouring tea".
It's as simple as that.

A: I don't think it's just that mothers pour the tea.  Mothers have historically been seen, obviously, as caregivers, and nothing spells nurturance to a Brit like tea.  So, more idiomatically, I think it refers to, more generally, "let me take care of you."

A: I don't think the phrase "be mother" specifically means to pour tea. It's used, in my experience, when one adult is serving something to another adult and that person could easily serve themselves. Because a child isn't usually allowed to serve him or herself at the table, their mother does it for them. So if someone is serving something to another person, they are "being mother".
It's not just about tea.


text:
Q: JAXB mixed content list contains newline characters I was hoping that you might be able to help me with a problem that I'm facing regarding JAXB.
I have the following XML file:
<root>
    <prop>
        <field1>
            <value1>v1</value1>
            <value2>v2</value2>
        </field1>
        <field2>
            <value1>v1</value1>
            <value2>v2</value2>
        </field2>
    </prop>
    <prop>
        text
        <field1>
            <value1>v1</value1>
            <value2>v2</value2>
        </field1>
    </prop>
    <prop>
        text
    </prop>
</root>

The XML can have under prop other elements (field1, field2), text or both.
And the following classes:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "root")
public class Root {

    protected List<Root.Element> prop;

    @XmlAccessorType(XmlAccessType.FIELD)
    public static class Element {
        @XmlMixed
        protected List<String> content;
        @XmlElement
        public Field1 field1;
        @XmlElement
        public Field2 field2;

        @XmlAccessorType(XmlAccessType.FIELD)
        public static class Field1 {
            @XmlElement
            protected String value1;
            @XmlElement
            protected String value2;
        }

        @XmlAccessorType(XmlAccessType.FIELD)
        public static class Field2 {
            @XmlElement
            protected String value1;
            @XmlElement
            protected String value2;

        }

    }

}

I want to unmarshal the XML in to the above classes.
The issue that I'm having is that in the content list I get, besides the text, other characters like newline and tab. To be more specific, based on the above XML, when I try to unmarshal I get:

*

*first prop with content like ["\n\t\t", "\n\t\t", "\n\t"] - it should
be an empty list

*second prop with content like ["\n\t\ttext\n\t\t",
"\n\t"] - it should be a list with one string

*third prop with content
like ["\n\t\ttext\n\t"] - it should be an empty list

I have already tried to create and a XMLAdapter but it is applied for every element in the list, so if I remove the \n and \t and return null if it is an empty string I still get a list with some strings and some null values.

A: Why It's Happening
White space content in an element that has mixed context is treated as significant.
How to Fix It
You could use JAXB with StAX to support this use case.  With StAX you can create a filtered XMLStreamReader so that any character strings that only contain white space are not reported as events.  Below is an example of how you could implement it.
import javax.xml.bind.*;
import javax.xml.stream.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Root.class);

        XMLInputFactory xif = XMLInputFactory.newFactory();
        XMLStreamReader xsr = xif.createXMLStreamReader(new StreamSource("src/forum22284324/input.xml"));
        xsr = xif.createFilteredReader(xsr, new StreamFilter() {

            @Override
            public boolean accept(XMLStreamReader reader) {
                if(reader.getEventType() == XMLStreamReader.CHARACTERS) {
                    return reader.getText().trim().length() > 0;
                }
                return true;
            }

        });

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        Root root = (Root) unmarshaller.unmarshal(xsr);
    }

}


text:
Q: Webpage that displays the result of a function run every x seconds I want a small web page, that once every x seconds, runs a function.(It will display the result of that function)
import datetime
from bottle import Bottle, run

app = Bottle()

@app.route('/')
def hello():
    return datetime.datetime.now()

run(app, host='localhost', port=8080, reloader=True, interval=5)

Right now I've got this. I'm using pythonanywhere for hosting and this won't even run. Error logs state:
FileNotFoundError: [Errno 2] No such file or directory: '/usr/local/bin/uwsgi'

I'm kind lost on this one...

A: not sure exactly what you are doing, but i think you might have more luck if you do this on the browser side instead of the server side.
for example, look at this


text:
Q: Angular Azure AD B2C Password reset policy after password changed logs into app and then shows login page I am using Azure AD B2C with my Angular 11 application.
I am trying to use forgot password policy and it is working fine except after password is changed, it logs me into application and displays me my landing page and a fraction of second redirects to login page. Not sure what i am doing wrong.
Can anyone please help me how to resolve this?
this.msalBroadcastService.msalSubject$
        .pipe(
            filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_FAILURE || msg.eventType === EventType.ACQUIRE_TOKEN_FAILURE),
            takeUntil(this._destroying$)
        )
        .subscribe((result: EventMessage) => {
            // Checking for the forgot password error. Learn more about B2C error codes at
            // https://learn.microsoft.com/azure/active-directory-b2c/error-codes
            if (result.error && result.error.message.indexOf('AADB2C90118') > -1) {
                let resetPasswordFlowRequest: RedirectRequest | PopupRequest = {
                    authority: b2cPolicies.authorities.resetPassword.authority,
                    scopes: [],
                };

                this.login(resetPasswordFlowRequest);
            };
        });

login(userFlowRequest?: RedirectRequest | PopupRequest) {
        if (this.msalGuardConfig.interactionType === InteractionType.Popup) {
            if (this.msalGuardConfig.authRequest) {
                this.authService.loginPopup({ ...this.msalGuardConfig.authRequest, ...userFlowRequest } as PopupRequest)
                    .subscribe((response: AuthenticationResult) => {
                        this.authService.instance.setActiveAccount(response.account);
                    });
            } else {
                this.authService.loginPopup(userFlowRequest)
                    .subscribe((response: AuthenticationResult) => {
                        this.authService.instance.setActiveAccount(response.account);
                    });
            }
        } else {
            if (this.msalGuardConfig.authRequest) {
                this.authService.loginRedirect({ ...this.msalGuardConfig.authRequest, ...userFlowRequest } as RedirectRequest);
            } else {
                this.authService.loginRedirect(userFlowRequest);
            }
        }
    }

A: I was trying to do the same thing the other day using user flows, not custom policy as per business requirement, However, I found out that after the password reset is finished, it redirects back to the app, but it can not sign in back using returned information through the URL. Not sure, if it is a bug or what, but it still tries to do that and timeout.
I would suggest after the password reset is successful, try to force logout e.g. remove MSAL stored information, and redirect to the login or landing page.
If I find a better solution, I will post it for you.

A: I have done a bit of research on this. I found out, once the password has been reset, the user is supposed to log in again. If you want to get the user logged in after the password has been reset, you need to authenticate the user in the API and return back the token. Here is the code for that:
public async Task<OAuthResult> AuthenticateCredentialsAsync(string username, string password)
{
    var oauthEndpoint = new Uri(new Uri($"{_b2cSettings.Authority}{_b2cSettings.SignInROPC}/"), "oauth2/v2.0/token");

    using (var client = new HttpClient())
    {
        var result = await client.PostAsync(oauthEndpoint, new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("client_id", _b2cSettings.ClientId),
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("client_info", "1"),
            new KeyValuePair<string, string>("username", username),
            new KeyValuePair<string, string>("password", password),
            new KeyValuePair<string, string>("scope", $"openid {_b2cSettings.ClientId} offline_access "),
            new KeyValuePair<string, string>("client_secret", _b2cSettings.ClientSecret),
            new KeyValuePair<string, string>("response_type", "token id_token")
        }));

        if (result.StatusCode != HttpStatusCode.OK)
            throw new AuthenticationFailedException(await result.Content.ReadAsStringAsync());

        var content = await result.Content.ReadAsStringAsync();
        var authResult = JsonConvert.DeserializeObject<OAuthResult>(content);
        return authResult;
    }
}

    public class OAuthResult
{
    public string Token_Type { get; set; }
    public string Scope { get; set; }
    public int Expires_In { get; set; }
    public string Access_Token { get; set; }
    public string Id_Token { get; set; }
    public string Refresh_Token { get; set; }
    public string Client_Info { get; set; }
}

NOTE: You need to create an ROPC policy in the Azure AD B2C.
Another option is to logout user after the password reset and redirection happens back to the App:
this.loggedInSuccess$ = new ReplaySubject<boolean>();

this.msalBroadcastService.msalSubject$
  .pipe(
    filter((msg: EventMessage) => msg.eventType === EventType.LOGIN_SUCCESS || msg.eventType === EventType.ACQUIRE_TOKEN_SUCCESS)
  )
  .subscribe((result) => {

    const payload: IdTokenClaims = <AuthenticationResult>result.payload;

    if (payload.idTokenClaims?.tfp === b2cPolicies.names.forgotPassword) {

      return this.msalService.logout();

    } else if (payload.idTokenClaims?.tfp === b2cPolicies.names.signIn) {

      this.loggedInSuccess$.next(true);
      this.msalService.instance.setActiveAccount(payload.account);

    }
    return result;
  });

If you have any issues, let me know, and I can post the full code.
Furthermore, you can handle more things as per your app requirements using the MSAL events:
https://github.com/AzureAD/microsoft-authentication-library-for-js/blob/dev/lib/msal-angular/docs/v2-docs/events.md


text:
Q: How to find "good" sequences to use in the comparison test (in general) My question isn't about a specific mathematical problem. It's about the comparison method in general. I've been studying some real analysis and I specially struggle with the convergence test problems, and have realised that most of them can be solved easily with comparison test. I totally understand the method and how it works, but I have this questions:

*

*Is there any "typical form" of series $\sum a_n$ that I can recognize and say: "This one is about comparison test" ? (For example, for the series $\sum (a_n)^n$ I intuitively go for the root test, so I want to find a pattern like that but for comparison test).

*Is there any "rule" or method I can follow to easily find the right sequences to compare with? (I've seen answers in my textbook that use comparison test with sequences that seem totally impossible to guess, unless I'm missing something about how to find that "good" sequences).

I'm not pretty sure if this will make any sense, but I struggle with this method of convergence testing and maybe there's something I'm ignoring that makes it easier. Any help will be very appreciated.

A: If your series is of the form$$\sum_{n=1}^\infty\frac{a_n}{b_n},\tag1$$and each $a_n$ and each $b_n$ is the sum of several things, try to see which of those things grow faster; then compare $(1)$ and the series $\sum_{n_1}^\infty\frac{\alpha_n}{\beta_n}$, where $\alpha_n$ and $\beta_n$ are those things that grow faster.
For instance, consider the series$$\sum_{n=1}^\infty\frac{n^3+3n^2+\sqrt n}{2n^5+10n^3+\log(n)}.\tag2$$The part of the numerator which grows faster is $n^3$, and the part of the denominator which grows faster is $2n^5$. So, compare the series $(2)$ with the series $\sum_{n=1}^\infty\frac1{2n^2}\left(\text{i.e.},\sum_{n=1}^\infty\frac{n^3}{2n^5}\right)$, which converges. Since you have$$\lim_{n\to\infty}\frac{\frac{n^3+3n^2+\sqrt n}{2n^5+10n^3+\log(n)}}{\frac1{2n^2}}=\lim_{n\to\infty}\frac{n^5+3n^4+\sqrt n\,n^2}{2n^5+10n^3+\log(n)}=1,$$your series converges too.

A: There is no secret recipe; however some guidelines that I use include these:
1.If you see $n!$ it is a safe bet to use the ratio test ($\lim_{n\to\infty}\frac{a_{n+1}}{a_n}$)
2.Use a healthy suspicion regarding the series $a_n$. Does it even converge to zero? Usually very easy to check.
3.Using the integral or sum test with a simple function, like $\sum{1/n^{2}}$
4.Some series are just "pre-cooked" to be convergent via a theorem such as Dirichlet.
Those are from the top of my head; however, it just takes time and patience to learn to recognize what works and what doesn't. Sorry if it isn't very helpful, but I don't think there's any better insight than practice.


text:
Q: How to subscribe to observable in observableArray I'm using KnockoutJS and trying to subscribe to an observable that is in an observableArray that is in an observableArray. So my viewModel looks like this...
function viewModel() {
    // private properties
    var self = this;

    // public properties
    self.movies = ko.mapping.fromJS([]);

    // subscriptions
    self.movies.UserMovies.Rating.subscribe(function(newValue) {
        console.log(newValue);
    });
}

The movies observableArray would look like this once populated from the mapping plugin...
[{
    Id: 1,
    Title: 'Movie1',
    Year: 2010,
    UserMovies: [{ Id: 11, Rating: 3.5, IsWatched: true }]
},{
    Id: 2,
    Title: 'Movie2',
    Year: 2010,
    UserMovies: [{ Id: 4, Rating: 4, IsWatched: true }]
}]

I'm trying to set up a subscription to UserMovies.Rating but, from my above viewModel getting the error message

TypeError: self.movies.UserMovies is undefined

How would I got about setting up a subscription to UserMovies.Rating when it is populated from the mapping plugin?

A: Knockout does not provide the granularity for knowing which items changed in an array, just that something changed. You will need to loop trough the array each time an item is added or removed.
The foreach binding (via ko.utils.compareArrays) actually calculates the minimum number of operations to transform one array into another one, so that DOM-elements does not need to be recreated.
Using ko.utils.compareArrays, I was able to create a method that subscribes to array changes at an item level. Leveraging this, I could write a select method that manages the subscriptions.
http://jsfiddle.net/MizardX/s9M4z/
With the new select method, you could do this pretty concisely:
// Subscribe to items added to the array. The returned 'subscription' will be
// disposed of, when the item is later removed.
viewModel.movies.select(function (movie) {

    // Return the subscription. Same as above.
    return movie.UserMovies.select(function (userMovie) {

        // Subscribe to a non-array. The callback will receive the updated value,
        // instead of the an added item.
        return userMovie.Rating.select(function (rating) {

            // Executed each time a rating is updated.
            console.log(movie.Id(), userMovie.Id(), rating);
        });
    });
});

It handles additions, updates, and deletions as expected.

A: I think you'll have to loop through your movies and subscribe to each one's rating property:
$.each(self.movies(), function(i, movie) {
     movie.Rating.subscribe(function(newRatingValue){  /* ... */ })
});

Of course the donwside here is that you'll also have to subscribe to the array itself, for situations in which you add new movies to the array, and then manually subscribe to changes in their rating value as well.

A: You can kind of subscribe to your properties in this fashion:
   var UserMovies = function (data) {
        this.Id = ko.observable();
        this.Rating = ko.observable();
        this.IsWatched = ko.observable();
        this.update(data);
    }

    ko.utils.extend(UserMovies.prototype, {
        update: function (data) {
            this.Id(data.Id || "");
            this.Rating(data.Rating || "");
            this.Rating.subscribe(function (newValue) {
                console.log(newValue);
            });
            this.IsWatched(data.IsWatched || "");
        }
    });

I'm not sure what you might be able to do or not do from subscribing to things inside of your object, but this does work. I'm also not sure if each subscription will be unique, or if one Rating change will set off all UserMovies ratings subscriptions. I have not tested that. I've only used this in single objects and not arrays of objects.


text:
Q: simultaneous inverse fast fourier transform of two real functions I'm trying to calculate the inverse Fourier Transform of two real functions with a single IFFT. The best and most straightforward explanation I've found so far is here, where it says:

Use the fact that the FFT is linear and form the sum of the first transform plus i times the second.
  You have two vectors, x1 and x2, with
  discrete Fourier Transforms X1 and X2
  respectively. Then
x1 = Re[ IDFT[ X1 + i X2 ] ]
and
x2 = Im[ IDFT[ X1 + i X2 ] ].

The problem is that I don't get where the 'i' parameter comes from.
Any hint on this would be much appreciated.
Thanks in advance.
EDIT:
After doing some experiments I finally made it work, but now I'm more confused than before as it didn't work as I expected and had to use some imagination to figure out the correct formulas.
I just made up a new complex array where:
Re[n] = X1Re[n] - X2Im[n]
Im[n] = X2Re[n] + X1Im[n]

After doing an IFFT on it x1 = Re and x2 = Im, so wouldn't it be correct to express it like this?
x1 = Re[ IDFT[ X1 - i X2 ] ]
x2 = Im[ IDFT[ X2 + i X1 ] ].

A: Are you wondering what the 'i' represents?  In this case, I believe 'i' is referring to sqrt(-1), the imaginary unit vector.
Then:
Re[ IDFT[ X1 + i X2 ] ]

will be the 'real' part of that transform (anything without an 'i') and
Im[ IDFT[ X1 + i X2 ] ]

will be the 'imaginary' part of that transform (anything multiplied by an 'i').
It is possible I've misunderstood your question and this answer is much too simplistic; if it is, no insult was intended to your intelligence, I just misunderstood you.

A: If you want to ignore the mathematics of complex variables, multiplying by i is just notation for how you swap and scale a pair of vectors to produce another pair of vectors.  And the complex vectors X1 and X2 can each be considered to be just pairs of real-valued vectors (with a "complex" relationship under the transforms of interest).  The swap and scale makes the two component vectors more easily separable, after some arithmetic and transforms, into the real valued vector of interest.


text:
Q: How can I make gulp-watch generate CSS file when SASS changes? Here is my code:
gulp.task('sass', function () {
    gulp.src('./public/stylesheets/*.scss')
        .pipe(sass())
        .pipe(gulp.dest('./public/stylesheets/'));
});

gulp.task('watch-saas', function () {
    watch('./public/stylesheets/*.scss', function () {
        gulp.start('sass');
    });
});

Output:
[19:15:46] Using gulpfile ~/WebstormProjects/mySite/gulpFile.js
[19:15:46] Starting 'watch-saas'...
[19:15:46] Finished 'watch-saas' after 38 ms

Im afraid no CSS. Any ideas how to make this work?
I think my code looks very much like the example code here. And the 'sass' task runs fine on its own.

A: I'm not that experienced in Gulp, but I usually use:
gulp.task('watch-saas', function () {
    return gulp.watch(['./public/stylesheets/*.scss'], ['sass']);
});

I assume that you have to return the result in your task, because it's an asynchronous task.

A:
We should first pipe it and ask gulp to watch it in changes in our scss or file we alerted

var gulp = require('gulp')
var watch = require('gulp-watch');

gulp.task('styles', function(){
    return  gulp.src(''./public/stylesheets/.scss'').pipe(gulp.dest('./sass'));
});

watch('./public/stylesheets/.scss', function(){
    gulp.start('styles');
 });

styles is the task name which I assigned here


text:
Q: How to parse nested shortcodes? The nested shortcodes won't parse correctly:
[row]
    [col size="6"]...[/col]
    [col size="6"]
        [row]
            [col size="6"]...[/col]
            [col size="6"]...[/col]
        [/row]
    [/col]
[/row]

From the WordPress documentation, I understand that it is a WordPress shortcodes limitation. Is it still possible to get it work?
Edit:
Here's my shortcodes code, it works fine if its not nested (ie., row shortcode is not used inside the col shortcode).
add_shortcode( 'row', 'row_cb' );
function row_cb( $atts, $content = null ) {
        $output = '';
        $output .= '
';
        $output .= do_shortcode( $content );
        $output .= '
';

        return $output;
}

add_shortcode( 'col', 'col_cb' );
function col_cb( $atts, $content = null ) {
    extract( shortcode_atts( array(
            'size'  => '',
        ), $atts ) );

    $output = '';
    $output .= '
';
    $output .= do_shortcode( $content );
    $output .= '
';

    return $output;
}

A: There's a solution for that, actually. The shortcode you are using has the variable $content, whithout the filter do_shortcode, like this:
do_shortcode($content)

Open the file where there are the shortcodes and change $content for do_shortcode($content). It will work.

A: I created a solution for my nested shortcodes, maybe you could use something from it.
I used a recursive regex (notice |(?R)), so it might be not that fast as the official do_shortcode, but it allows nesting shortcodes with the same name.
My request for it was to not have a fixed list of shortcodes (so all existing in the content shortcodes  must be parsed), to allow any level of nesting, and also to use a structure of $atts, which contain some parameters, existing at the time of filling this exact content.
For $atts I wrote my own function, too, as I wanted $atts to include both everything coming from the content (and not only those, whose default value is defined), and the default values for those fields, existing in the default array and not coming from the shortcode values.
Here's my atts function:
function complete_atts_with_defaults( $pairs, $atts = array() ) {
  $out = $atts;
  foreach ($pairs as $name => $default) {
    if ( array_key_exists($name, $atts)  && !empty( $atts[$name] ) ) { continue; }
    //else
    $out[$name] = $default;
  }
  return $out;
}

And here's the other code:
define( 'OUR_SHORTCODE_FULL_REGEX', '@\[([a-z0-9_]+)([^\]]*)\]((?:[^[]|(?R))+)\[\/\1\]@' );
define( 'OUR_SHORTCODE_HALF_REGEX', '@\[([a-z0-9_]+)([^\]]*)\/\]@' );

function fill_all_post_placeholders( $text, $atts = array() ) {
  //...
  $text = str_replace( '%5B', '[', $text );
  $text = str_replace( '%5D', ']', $text );

  $atts = complete_atts_with_defaults(
        array(
            'value1' => 'Hi :)',
            'value2' => '',
            'value3' => '',
        ), $atts );

  //...

  $text = preg_replace_callback( OUR_SHORTCODE_HALF_REGEX, function( $match ) use ( $atts ) { return replace_half_shortcode_placeholder( $match[1], $match[2], $atts ); }, $text );
  $text = preg_replace_callback( OUR_SHORTCODE_FULL_REGEX, function( $match ) use ( $atts ) { return replace_shortcode_placeholder( $match[1], $match[2], $match[3], $atts ); }, $text );

  return $text;
}

function replace_shortcode_placeholder( $name, $params, $content, $atts ) {
  $content = preg_replace_callback( OUR_SHORTCODE_FULL_REGEX, function( $match ) use ( $atts ) { return replace_shortcode_placeholder( $match[1], $match[2], $match[3], $atts ); }, $content );
  //   $function_to_call = '_rp_' . $name;
  //   if ( function_exists( $function_to_call ) ) { return $function_to_call( $name, $params, $atts ); }
  //   //else
  //   $value = $atts[ $name ];
  //   if ( empty( $value ) ) { return ''; }
  //   //else
  //   return $value;

  return '
name: '  . $name . '
params: ' . $params . '
content: (' . $content . ')

';
}

function replace_half_shortcode_placeholder( $name, $params, $atts ) {
  //   $function_to_call = '_rp_' . $name;
  //   if ( function_exists( $function_to_call ) ) { return $function_to_call( $name, $params, $atts ); }
  //   //else
  //   $value = $atts[ $name ];
  //   if ( empty( $value ) ) { return ''; }
  //   //else
  //   return $value;

  return '
name half: '  . $name . '
params half: ' . $params . '

';
}

I left for you the commented area intact, so that you could see how those functions could be used.
These "shortcodes" of mine are not registered, as you can see in the commented code, they work differently, dynamically.
Also, the necessary rule for these shortcodes to work would be, to always add '/' to the self-closing tags, like one would do in XML. (In the code they are called "half-shortcodes".)
Example to the content parsed by this code (sorry for the gibberish):
[show_text_if campaign="2899"]subscribing to this newsletter [show_text_if campaign="2901" field_value="'a href='http://ajshdash.com/asdhal/asdasdasd'" field_value2="айксчд асй даксчй д"]subscribing to this new newsletter[/show_text_if] [red value1="dfsdfs" value2="sdfkls dfh skjha skd"/][/show_text_if]

[color value3="askdfjajls" value4="lskdfhjsldhfs df"/]

[show_text_if_not campaign="2899"]asdklja slkd alkd alskdj alsjd alsj als jdalsk jals dalskj asjd Experiment once more hooray! [green value4="askljjlaskd"/] Я сегодня это Я и я! :)[/show_text_if_not]

[show_text_if field_name="campaign" field_value="2899"]slkjd alsjkd aljsd ajs d new[/show_text_if]

And I understand, that this code is not a direct solution to what you asked for, but maybe you could use some of it, to work out the solution yourself.

A: Your shortcode callback should appears something like:
add_shortcode('col', 'col_cb');

add_shortcode('row', 'row_cb');

function col_cb( $atts, $content ) {
  $content = do_shortcode($content);
  // ...
}

function row_cb( $atts, $content ) {
  $content = do_shortcode($content);
  // ...
}