text:
Q: How to calculate backplane throughput given an arbitrary list of network links? Given a device (router lets say) that can take an arbitrary number of network connections how much backplane throughput should be allocated to a given set of network connections.
(we assume all of these are symmetrical, and further to simplify the discussion we assume we're only counting each interface once, instead of once for TX and a second time for RX)
Also we assume traffic is always TRANSITING the router, never destined to it directly.  So any packets that come in one interface must leave another.  There is no "loopback" function here.
examples:
a single 1G link.  It can't send any traffic to anywhere so backplane allocation is ZERO.
two 1G links.  one can perfectly saturate the other, so total backplane allocation should be 1000mbps.
a single 1G link and a single 50M link.  total allocation is 50mbps since the most traffic the 1G link would ever be able to send is 50mbps.
My intuitive assumption is there must be a "simple" formula to get this, something easily suitable for an excel spreadsheet or the like, but I haven't been able to come up with anything.
The mental algorithm I use to come up with the "right" answer is  essentially picking the biggest link, stack the others against it until it's "saturated", then repeating with the next largest remaining link, etc.  any throughput left over from the last interface at the end is discarded.
Here's the test cases I've come up with, my official answer, and the various results I get from the various strategies I've tried.

case
My answer
sum
sum / 2
'sum the minimums of the sorted pairs'
sum - max

4x50m
100
200
100
100
150

1x100,3x50
100
250
125
100
150

2x125, 2x50
175
350
175
175
225

1x1000,2x200,1x50
450
1450
725
250
450

A:
Revision: Thanks to help from JvdV and
EDS in this connected
question,
I have added a way to accept the text inputs shown in the Cases from
your examples.

To get the correct backplane bandwidth, you need to find the right combination of connections that will total to half of the aggregate bandwidth. For example, if you had connections of 1,2, ... ,6, you are looking for any combination that adds to 21/2=10. e.g., 6,4 gets you there.
i.e., the correct answer will approach the half of the sum of all bandwidth. While sum/2 would provide a quick & dirty approximation, it can be wildly off if the number of connections is small and their make-up is asymmetrical. e.g. the case that you presented as 1x1000,2x200,1x50 has a backplane bandwidth of 450 - far from 725.
To get to the correct answer in all cases, requires some form of iteration, which is not supported in Excel functions. You can create real iteration through LAMBDA recursion (not yet released) or VBA. But there is also another way: iteration can be emulated through functions that contain iterations.
You can imagine this as a method of 'folding'.  What we are trying to do is to put the connections on either side of a piece of paper and fold the paper where the left and right side numbers cancel each other.  The sum of the numbers that get canceled are the backplane bandwidth. The residual is waste. For example: connections of speeds 1,2,3,4,5, and 6, would have 4 & 6 on the left side and 2, 3, & 5 on the right. The 1 has no match and becomes residual, like this:

There are obviously 2^6-2=62 possible arrangements on the paper and we have to find the one that best balances them.  I came up with two approaches which I will call:

*

*Brute-force Folding : create every possible fold and search for the one that gets half the summation on a single side.

*Adaptive Folding : sort the connections, make an initial fold and use it to determine the next fold, rinse, repeat.

Brute-force is achievable as a LET formula without iteration. Adaptive works, but requires iteration or possibly recursion, so it would only be possible with a LAMBDA or VBA UDF tmk.
Forming the Input
Connection Array
In all cases we need to normalize the input into an array of connection speeds. e.g.:

That's probably not the best user interface for the formula because it would be tedious and take up a lot of cells to write all those out. So there are two possible alternatives:
Connection Table

Connections
of Speed

1
1050

2
400

1
200

1
100

1
50

Comma Delimited Strings -as you showed in your example
1x1050,2x400,1x200,1x100,1x50
So, the front part of the formula will simply form the input into a Connection Array.
The rest focuses on the calculation mechanics.
Brute-Force Folding
Using a Connection Table as input, you can do:
=LET( connectionTable, A2:B6,
       connections, INDEX(connectionTable,,1), speeds, INDEX(connectionTable,,2),
       elements, SUM( connections ),  eSeq, SEQUENCE( elements,,0 ),
       bySeq, SEQUENCE( ROWS( connections ) ),
       byPos, MMULT( --(bySeq >= TRANSPOSE( bySeq )), connections ),
       conx, INDEX( speeds, IFERROR(MATCH( eSeq, byPos, 1 )+1,1)  ),
       bpBW, LET( array, conx,
                  r, ROWS( array ), c, 2^(r-1)-1, s, SUM(array),
                  cSeq, SEQUENCE(1,c,1),
                  idx, MOD(SEQUENCE(r,c,0),c)+1, e, 2^SEQUENCE(r,,r-1,-1), foldArray, MOD(INT(idx/e),2),
                  p, MMULT( SIGN( SEQUENCE( 1, ROWS( foldArray ) ) ), array*foldArray ), n, s - p,
                  c2z, MATCH( MIN( ABS( p-n ) ), ABS( p-n ), 0 ),
                  result, MIN( INDEX( CHOOSE( {1;2}, p, n ), , c2z ) ),
                   result  ),
       bpBW )

Where connectionTable is a table containing the number of connections of each speed as described above. Here is an illustration of 1x1050,2x400,1x100,1x50 which will yield a backplane bandwidth of 1100 with no residual. It effectively puts 1050 and 50 on one page and the rest on the other.

Notes
I nested the LETs and broke out their results of result and bpBW to make it easier to inspect each part. This can be consolidate further, but that would make it harder to optimize and understand.  The calculations can also be simplified a little bit by using s/2 instead of creating an n array, but that makes it harder to explain and to break out and examine, so I did left this formula in its most readable and understandable format even if it is quite long.
How it works
The first LET starts by reshaping the Connection Table input into a Connection Array which is an expanded list of connection speeds.

The second LET is the takes the array from the first LET and calculates the bpBW (backplane bandwidth) as result.
It does this by generating an array of binary representations of each possible fold called the foldArray. It then multiplies this times array to create a matrix of values and that matrix is summed column-wise to create a single-row array called p or the positive side of the fold. It also calculated n, the negative side of the fold by taking s (the sum of all connections) - p.  (This can be simplified and eliminated by using s/2 as a reference, but I kept n in place for inspection to understand how the approach actually works.)
Now that we have both sides of the fold, the residuals can be calculated as ABS( p - n ). We are looking for the column with lowest residual or "closest to zero" c2z. At that column, we need to take the smaller of the p and n values. That min is the backplane bandwidth.
Putting it All Together
This diagram shows how it works.  The blue sections are showing how the inputs can be shaped into a Connection Array and the green section shows how the computations are rendered.

Variations on Inputs
The version above accepts a Connection Table as input.  Here are different versions of the formula for each possible way that you might want to accept the input:
Connection Array
=LET( array, A2:A7,
         r, ROWS( array ), c, 2^(r-1)-1, s, SUM(array),
         cSeq, SEQUENCE(1,c,1),
         idx, MOD(SEQUENCE(r,c,0),c)+1, e, 2^SEQUENCE(r,,r-1,-1), foldArray, MOD(INT(idx/e),2),
         p, MMULT( SIGN( SEQUENCE( 1, ROWS( foldArray ) ) ), array*foldArray ),
         c2z, MATCH( MIN( ABS( s/2-p ) ), ABS( s/2-p ), 0 ),
         bpBW, MIN( INDEX( CHOOSE( {1;2}, p, s-p ), , c2z ) ),
       bpBW )

Comma Delimited e.g. "1x100,2x500,3x200"
=LET( case, A11,
       x, FILTERXML("<t><s>"&SUBSTITUTE(SUBSTITUTE(A11,",","x"),"x","</s><s>")&"</s></t>","//s"),
       connectionTable, INDEX(x,SEQUENCE(COUNT(x)/2,2)),
       connections, INDEX(connectionTable,,1), speeds, INDEX(connectionTable,,2),
       elements, SUM( connections ),  eSeq, SEQUENCE( elements,,0 ),
       bySeq, SEQUENCE( ROWS( connections ) ),
       byPos, MMULT( --(bySeq >= TRANSPOSE( bySeq )), connections ),
       conx, INDEX( speeds, IFERROR(MATCH( eSeq, byPos, 1 )+1,1)  ),
       bpBW, LET( array, conx,
                   r, ROWS( array ), c, 2^(r-1)-1, s, SUM(array),
                   cSeq, SEQUENCE(1,c,1),
                   idx, MOD(SEQUENCE(r,c,0),c)+1, e, 2^SEQUENCE(r,,r-1,-1), foldArray, MOD(INT(idx/e),2),
                   p, MMULT( SIGN( SEQUENCE( 1, ROWS( foldArray ) ) ), array*foldArray ),
                   c2z, MATCH( MIN( ABS( s/2-p ) ), ABS( s/2-p ), 0 ),
                   result, MIN( INDEX( CHOOSE( {1;2}, p, s-p ), , c2z ) ),
                    result  ),
       bpBW )

And here are the results applied to an extended version of your cases:

case
Brute-force

4x50
100

1x100,3x50
100

2x125, 2x50
175

1x1000,2x200,1x50
450

1x1050,2x400,1x200,1x100,1x50
1100

1x1050,2x400,1x150,1x100,1x50
1050

2x1000,2x200,1x50,1x100
1250

1x200,3x125,4x400,3x1000,2x2000
4575

1x130,1x270,1x410,1x390,1x300,1x120
810

1x170,2x270,1x210
440

1x130,1x270,1x180,1x220
400

Adaptive Folding
It would be a lot of work to fully describe adaptive folding or build it in VBA and I think the above answers your question already, so I will keep this brief.
The problem with the Brute Force approach is that it computes all possible arrangements.  A 16 port device would have a 524,272 cell array. 24 ports is 201 million, 32 is 68 billion, and 48 port would be 6.8 quadrillion. When you reach such levels SUM/2 is probably already a good enough approximation, but if you really had to have a correct answer, Brute-Forcing it would break your machine.
So an alternative is to search for the best-fit combination of connections that form SUM/2 of aggregate bandwidth without 'boiling the ocean'. The method is:

*

*Sort the Connection Array - descending.

*Start subtracting elements 2... to X from element 1 until the sum is <= 0. Then set a variable B to equal the sum of the bandwidth of elements 2... X - Residual (if there is any).

*Go to element X+1 and add the Residual and then repeat Step 2 above by adding the new B to the old B.
Keep repeating 2 and 3 until all connections have been reviewed. B is the answer.

This reduces a 48 port connection from a 6.8 quadrillion array to at-most a 48^2 array and 47 iterations. In all likelihood, the algorithm will end in less than 10 iterations on such a large device.


text:
Q: Extract Java Cluster Creation functionality for a Java Web App Our spring based webapp is deployed to Tomcat AppServer. We have Multiple Tomcat Nodes behind a Load Balancer. If we want to discover all the AppServer Nodes in the Cluster, which clustering library can be used ? Ignite has TcpIp Multicast based and other cluster discovery mechanisms and Hazelcast has similar discovery mechanisms.
If our cluster size is roughly at 10 nodes, it appears that TcpIp Multicast based discovery would be a right strategy. Is that assumption right ?
Did anyone extract just the Cluster discovery feature from ignite ? If not, how do I go about extracting just the Cluster creating code and peer to group/peer messaging feature from Ignite (or any similar library/framework) ?
Any ideas appreciated.

A: AFAIK JBoss clustering functions used to run on top of JGroups.
You already mentioned Hazelcast...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Switch pro controller disconnects and reconnects bluetooth. 19.04 Using the controller with steam and it constantly is disconnecting and reconnecting. Sometimes it takes a few minutes and sometimes its almost instant. Tried un-pairing and re-pairing it. I don't have any other bluetooth devices to see if it's just the controller.

A: Sorry for late reply, but just found out the answer.
You'll need to disable Ubuntu's Enhanced Re-Transmission Mode, which conflicts with how the controller works.
In order to do that, you'll need to add:
options bluetooth disable_ertm=1

to /etc/modprobe.d/bluetooth.conf and restart your PC.


text:
Q: How to write a regex OR statement within strapply in R I have been using strapplyc in R to select different portions of a string that match one particular set of criteria.  These have worked successfully until I found a portion of the string where the required portion could be defined one of two ways.
Here is an example of the string which is liberally sprinkled with \t:
\t\t\tsome words here\t\t\tDefect: some more words here Action: more words

I can write the strapply statement to capture the text between Defect: and the start of Action:
strapplyc(record[i], "Defect:(.*?)Action")

This works and selects the chosen text between Defect: and Action.  In some cases there is no action section to the string and I've used the following code to capture these cases.
strapplyc(record[i], "Defect:(.*?)$")

What I have been trying to do is capture the text that either ends with Action, or with the end of the string (using $).
This is the bit that keeps failing.  It returns nothing for either option.  Here is my failing code:
strapplyc(record[i], "Defect:(.*?)Action|$")

Any idea where I'm going wrong, or a better solution would be much appreciated.

A: If you are up for a more efficient solution, you could drop the .*? matching and unroll your pattern like:
Defect:((?:[^A]+|A(?!ction))*)

This matches Defect: followed by any amount of characters that are not an A or are an A and not followed by ction. This avoids the expanding that is needed for the lazy dot matching. It will work for both ways, as it does stop matching when it hits Action or the end of your string.
As suggested by Wiktor, you can also use
Defect:([^A]*(?:A(?!ction)[^A]*)*)

Which is a little bit faster when there are many As in the string.
You might want to consider to use A(?!ction:) or A(?!ction\s*:), to avoid false early matches.

A: The alternation operator | is the regex operator with the lowest precedence. That means the regex Defect:(.*?)Action|$ is actually a combination of Defect:(.*?)Action and $ - since an empty string is a valid match for $, your regex returns the empty string.
To solve that, you should combine the regexes Defect:(.*?)Action and Defect:(.*?)$ with an OR:
Defect:(.*?)Action|Defect:(.*?)$

Or you can enclose Action|$ in a group as Sebastian Proske said in the comments:
Defect:(.*?)(?:Action|$)


text:
Q: Pass data through Named Function using jQuery .on() Method This can be easily achieved with the use of an anonymous function but is there a better way to pass data through a named function using jQuery .on() method?
$('#browser .next').on( 'click', function() {

    APP.search.page('next');

});

But removing anonymous functions from the event is difficult.
When using a named function I can access the data by first passing the event and then accessing the data within the event (event.data.page) but that makes for some messy code within the function.
$('#browser .next').on( 'click', {  page: 'next'  } , APP.search.page );

Is there any better way to pass the data without having to access it through the event as can be achieved in the anonymous function?

A: You can use the bind method
$('#browser .next').on(
   'click',
    APP.search.page.bind(APP.search.page,
   'next')
);

or
You can pass as parameter any type of data
$('#browser .next').on(
   'click',
    APP.search.page.bind(APP.search.page,
   {some: 'value'})
);


text:
Q: Unity Desktop "freezes" but can be recovered with xkill I'm running 16.04 with Unity desktop enviro, and periodically my desktop environment looses responsiveness.  It often happens when I open Blender, Krita, Cura, and many other apps (just did it now when I opened the Calculator!)
The mouse still moves, but I can't click anything.  I've discovered that I can recover my opening a terminal with the keyboard, then using xkill.  I click anywhere on the screen and xkill causes the screen to flash, like it's killing some overlay that covered the entire screen blocking me from clicking anything.  Then everything works again.
xkill doesn't actually kill the app that seemed to trigger the "freeze", all apps are still running fine.
How do I fix this?
EDIT
Just occured again.  Here's the output of xprop:
$ xprop
_NET_WM_ICON_GEOMETRY(CARDINAL) = 5, 710, 54, 54
WM_STATE(WM_STATE):
        window state: Normal
        icon window: 0x0
_NET_WM_DESKTOP(CARDINAL) = 0
_NET_WM_ALLOWED_ACTIONS(ATOM) = _NET_WM_ACTION_ABOVE, _NET_WM_ACTION_BELOW
XdndAware(ATOM) = BITMAP
WM_PROTOCOLS(ATOM): protocols  WM_TAKE_FOCUS
WM_HINTS(WM_HINTS):
        Client accepts input or input focus: False
WM_NAME(STRING) = "Hud"
_NET_WM_PID(CARDINAL) = 7753
WM_CLIENT_MACHINE(STRING) = "mymachine"
_NET_WM_WINDOW_TYPE(ATOM) = _NET_WM_WINDOW_TYPE_DOCK
_NET_WM_STATE(ATOM) = _NET_WM_STATE_STICKY, _NET_WM_STATE_SKIP_TASKBAR, _NET_WM_STATE_SKIP_PAGER

$ xkill
Select the window whose client you wish to kill with button 1....
xkill:  killing creator of resource 0x320001c


text:
Q: Prove that every subsequence of a convergent real sequence converges to the same limit. Here's the statement I want to prove:
Let $\{a_n\}_{n=1}^{\infty}$ be a sequence of real numbers that converges to a real number $L$. Then, every subsequence $\{a_{n_k}\}_{k=1}^{\infty}$ converges to $L$.

Proof Attempt:
Let $\epsilon > 0$ be arbitrary but fixed. We are required to prove that:
$$\exists K \in \mathbb{N}: \forall k \geq K: |a_{n_k}-L| < \epsilon$$
We know that there exists an $N_0 \in \mathbb{N}$ such that:
$$\forall n \geq N_0: |a_n-L| < \epsilon$$
Since $\{n_k\}_{k=1}^{\infty}$ is a strictly increasing sequence of natural numbers, then:
$$\exists K \in \mathbb{N}: \forall k \geq K: n_k \geq N_0$$
$$\implies \exists K \in \mathbb{N}: \forall k \geq K: |a_{n_k}-L| < \epsilon$$
which is exactly the assertion that $\lim_{k \to \infty} (a_{n_k}) = L$. That proves the desired result.
Is the proof above correct? If it isn't, why? How can I fix it?

A: Your proof is correct. In fact, you could use your proof to derive a method to find an explicit suitable $K$ for each $\epsilon$, for the subsequence, given a method for the sequence itself.


text:
Q: Vue breaks DataTables and Pace JS Running Vue 2.5.16 with jQuery DataTables 1.10.15 and Pace JS 1.0.2.
When I add the

 wrapper to my root page layout, Vue components work but DataTables won't actually show the table data even tho the AJAX table data is valid.
Pace JS will sometimes overlay the entire screen in a grey overlay after some AJAX requests that load data that is big enough to push the render below the fold.
All I have to do is remove id="app" to fix either of these problems.
There are no errors in the console.
None of my DataTable instances integrate any Vue components. All Vue components are on entirely different pages than those of the DataTables.
All Pace JS pages have no Vue components.
My root Blade template code:

@if(Auth::check())
    @include('layouts.navigation')
@endif

    @if(Auth::check())
        @include('layouts.topnavbar')
    @endif

        @yield('content')

    @include('layouts.footer')

My DataTables initialization script:
@push('scripts')

@endpush

Example edit.blade.php page which holds a simple component:
@if(Auth::user()->can('edit-plans'))
    <edit-plans
            :plan="{{ json_encode($plan) }}"
    ></edit-plans>
@endif

My Vue initialization in app.js:
window.Vue = require('vue');

Vue.component('edit-plans', require('./components/plans/edit.vue'));

window.onload = function () {
    const app = new Vue({
        el: '#app'
    });
};

Currently integrating all of this in Laravel 5.4 if that makes any difference.
What could be causing this?

A: If you have left Laravel / Webpack in its default fresh install state, I believe you will find that the bootstrap.js file is already loading jQuery globally.  My guess is that since you are loading jQuery in your root page footer the fact that it is loading twice is causing your issue.  When you remove your Vue instance

 then you are only loading jQuery once and things work again.
So see if simply removing your CDN  fixes the issue for you.
If the included jQuery version is not new enough then updated it using npm.


text:
Q: how do you deal with a vague software proposal? We all get them. What do you do when you are supposed to write a functional spec from a woolly proposal? You can write a ton of questions about the proposal but answers are not always forthcoming. Sometimes for political reasons you cannot make someone firm them up. How do you deal with a vague software proposal, when experience and intuition only go so far?

A: I do as much as I can with what is not vague (which in some cases has been nothing, if you don't include setting up the workspace and naming the project), and then send an email to supervisors say "I need to get details regarding requirements X, Y, and Z or I cannot proceed". If the supervisor says "do it anyway!" I then push them to explain what I should do, and ask for a time allocation to undo and correct when my code inevitably does not meet the late-given requirements. Even if the supervisor/team lead doesn't like this, it makes sure they know that progress is being blocked by lack of requirements.
If I am dealing directly with a client, I tell them very clearly what I need. If they can't get back to me with it right away, I tell them that work will start only after we both agree on the requirements. Again, this is not always popular, but it has saved significant amounts of wasted effort with clients who in some casese never got requirements back to me.

A: You wouldn't expect someone to build an office building with vague requirements, why should someone expect you to build software with equally vague requirements.
Without concrete feature requirements, you are guaranteed to fail! Because you will never be able to meet what the customer has or doesn't have in their head as expectations.
Software development Agile Methodologies like SCRUM exist to force this very issue, you only work on what is the most important thing, if they can't tell you what is important from a business value stand point why should you know what to do?

A: In addition to

*

*Focus on the things that -are- concrete and build around those

*Engage the proposal author (customer?) as much as possible as soon as possible

*Plan on lots of iterations as part of the development plan (pick your favorite iterative methodology...)

*Build in acceptance/review gates into the project (that is, if all else fails, you may need to propose -a- solution, which the customer must accept, or provide comments on why it isn't acceptable)

*Make sure the Project Manager has factored in lots of buffer time & money :-)

Also consider

*

*Jump to an architectural spec (based on existing products/technologies/whatever) - proposing and discussing something concrete can be helpful in pulling the more abstract functions/behaviors out of the customer

*Try to understand the problem from the customer's perspective and look at the problems they are trying to solve and see how other solutions solve similar issues (e.g. a proposal that says "Add security" can generally be expanded reasonably well based on an understanding of the problem domain (banking vs marketing web form)

*Build a prototype - it will either solve your "experience only goes so far" problem, or provide a talking point for the customer, or make it clear what can be achieved in the budget and what is impossible.

*Write to the "Negative space" in the Functional Spec... list out what the product will -not- do so you have some scope control.  The pieces that you just can't do in the time/budget get listed as "out" and you then can negotiate/discuss/make a pass at the other areas that are easy to implement/change as the project progresses

I assumed that you are doing this as part of proposal writing and eventually the customer will be able to answer your questions, if not, seriously ask management if the risk is worth taking on the project/customer  (who knows, maybe the customer just doesn't care?)

A: Be creative, work by example. Fill in some blanks yourself and try to present it to them early. Listen and (re)work your functional description/code with their feedback.
Develop by example. Bill by the hour.


text:
Q: how to find the number of real root Prove $\;ax^3+bx+c=0\;$,  with $\;a,b>0\;$,  has at most one real root.
Should I use Rolle's theory for this? But I use it, what is the boundary of this function? I can only work out x must not be zero. Is the domain then turn into x is not equal to 0?

A: The derivative of the function $f(x)=ax^3+bx+c$ is
$$f'(x)=3ax^2+b$$
which is positive, so $f$ is strictly increasing and hence injective.

A: If you really want to use Rolle's theorem, suppose to the contrary that there exist real roots $p$ and $q$ with $p\lt q$. Our function is certainly continuous in the interval $[p,q]$ and differentiable in $(p,q)$. So there exists a $t$ between $p$ and $q$ such that $f'(t)=0$. But $f'(t)=at^2+b\gt 0$.


text:
Q: every time the button is pressed clear the view and start again - backbone.js Every time I press the button it adds my data and reloads the page and the list disappears. The preventdefault worked but then every time I click the button it keeps adding to the list.
How do I make it clear the list and start again every the button is clicked?
HTML

    <title></title>

            <button>Load</button>

JavaScript
model = new Backbone.Model({

    data: [

        { text: "site 1", href: "link1.htm" },
        { text: "site 2", href: "link2.htm" },
        { text: "site 3", href: "link3.htm" },
        { text: "site 4", href: "link4.htm" },
        { text: "site 4", href: "link4.htm" },
        { text: "site 4", href: "link4.htm" },
        { text: "site 4", href: "link4.htm" },

    ]
});

var View = Backbone.View.extend({

    initialize: function () {
        //console.log('initializing ' + this.options.blankOption);
        this.template = $('#list-template').children();
    },
    el: '#container',
    events: {
        'click button' : 'render'
    },
    //model:model,
    render: function(event){
        //event.preventDefault();
        var data = this.model.get('data');
        for (var i = 0; i < data.length; i++) {
            var li = this.template.clone().find('a').attr('href', data[i].href).text(data[i].text).end();
            this.$el.find('ul').append(li);
        }

    }
});

A: The reason is each time you clicked the button, the whole view is rendered again and appended to the existing content. this would fix your problem:
// empty the content inside the $el and re-rendering.
this.$el.empty();
this.$el.find('ul').append(li);

A: Another thing you should try is instead of creating a model with a data attribute full of objects you could create a Collection called something like "Links" and a model called "Link". To show the models you can pass the collection to the view and on the render call:
this.collection.each(function(model){$el.find('ul').append('
' + model.get('text') + '
')})

You can improve this by creating another view just to display the model with it's "tagName" attribute set to "li".
For example, here i'll create a model and a collection to hold the models. Then I'll create 2 views one to hold the collection and the other to display the model.
var Link = Backbone.Model.extend({})
var Links = Backbone.Collection.extend({
  model: Link
  url: '/links'

});
var ls = new Links()

When you call ls.fetch() a call will be made to your server that should answer with a JSON object with all your links. Backbone will take care to instantiate the Link models within itself. You can check if it worked by doing ls.length which should return a value bigger than zero.
Then you could create a View like this:
var MainView = Backbone.View.extend({
  template: JST['teams/index']

  render: function(){
      $(this.el).html(this.template())
      this.collection.each(this.appendLink())
      this},
  appendTeam: function(model){
    view = new LinkView({model: model})
    $('#links').append(view.render().el)
    this}})

The template function should have a list whith id = links where we can append our models. All we have to do now is create a the LinkView
var LinkView = Backbone.View.extend({
  template: JST['teams/team'],
  tagName: 'li',

  render: function(){
    $(this.el).html(this.template({model: this.model}));
    this}})

Hope this helps!


text:
Q: How can I use UIViewAnimationTransitionCurlUp for scene transitions in Cocos2d? For a storybook application being developed (with cocos2d-iphone), I am currently using the CCTransitionPageTurn class to handle the transitions between each page's scene. This is dandy and all but I would really like to use UIViewAnimationTransitionCurlUp transition from the iOS SDK library (much more crispy in my opinion). Here is an example of what I am currently doing:
PageThreeScene *pageThreeScene = [PageThreeScene node];
[[CCDirector sharedDirector] replaceScene:[CCTransitionPageTurn transitionWithDuration:1.0 scene:pageThreeScene ]];

Does anyone have any recommendations on how I might go implementing scene switches with iPhone SDKs own UIViewAnimationTransitionCurlUp for transitions between scenes? Would something like that be a big pain? Thanks ahead of time for any input.
Regards,
Chris

A: You can't apply UIViewAnimationTransitionCurlUp to a CCScene because it is not a UIView. And placing CCScene in a UIView wouldn't work because then the scene wouldn't be attached to CCDirector. Plus it wouldn't accept CCScene as a view anyway, because it is not a UIView.
You could (probably) apply the effect to the openGL view of your entire game, but that's not what you want, I know.


text:
Q: find replace text in file with Phing Does anyone know how to find and replace text inside a file with Phing?

A: I was looking for the same thing, and I found out that exists a filter named ExpandProperties which allows to replace properties in the copied file. For example I used it in a apache virtual host template:
<target name="apache-config" description="Generates apache configuration">
    <!-- Default value for Debian/Ubuntu -->
    <property name="apache.vhost.dir" value="/etc/apache2/sites-available" override="false"/>
    <copy file="${application.startdir}/docs/vhost.conf.tpl" todir="${apache.vhost.dir}" overwrite="true">
        <filterchain>
            <expandproperties/>
        </filterchain>
    </copy>
    <echo message="Apache virtual host configuration copied, reload apache to activate it"/>
</target>

And in the template file
<VirtualHost *:80>
   DocumentRoot "${application.startdir}/public"
   ServerName ${apache.default.host}

   <Directory "${application.startdir}/public">
       Options Indexes MultiViews FollowSymLinks
       AllowOverride All
       Order allow,deny
       Allow from all
   </Directory>

</VirtualHost>

In this way you don't need to explicitly list all the tokens you want replaced, pretty useful...

A: If you don't want to copy files and just replace a string in the current folder where your files reside, do a reflexive task:
<reflexive>
    <fileset dir=".">
        <include pattern="*.js" />
    </fileset>
    <filterchain>
        <replaceregexp>
            <regexp pattern="SEARCH" replace="REPLACEMENT"/>
        </replaceregexp>
    </filterchain>
</reflexive>

A: You can replace text inside files using filters. Filters are used inside other file operation tasks such as copy.
I believe the main idea behind filters is that you can have template files with tokens instead of real values and you then substitute the tokens as a part of the copy process.
Quick example: have a database configuration template file stored in a template directory. Then you copy it to the target configuration file using:
<copy file="templates/database.config.php.tpl" tofile="config/database.config.php" overwrite="true">
                <filterchain>
                    <replacetokens begintoken="%%" endtoken="%%">
                        <!-- MySQL TOKENS -->
                        <token key="dbname" value="${db.mysql.dbname}" />
                        <token key="dbhost" value="${db.mysql.host}" />
                        <token key="dbport" value="${db.mysql.port}" />
                        <token key="dbuser" value="${db.mysql.username}" />
                        <token key="dbpassword" value="${db.mysql.password}" />
                    </replacetokens>
                </filterchain>
            </copy>

There are plenty of other filters (e.g. regex search and replace) available.
See more about filters in the documentation: http://phing.info/docs/guide/stable/chapters/appendixes/AppendixD2-CoreFilters.html

A: I use this on my phing build.xml file
<exec command="find ./ -type f -name '*.php' | xargs sed -i 's|x--Jversion--x|${jversion}|g'" dir="${targetdir}/_package/${extname}.${package.version}" />

A: The simplest way to achieve this using 'traditional' tools would be sed:
sed -i 's/old/new/g'  myfile.txt

And if it is ant-based then this should help: http://ant.apache.org/manual/Tasks/replace.html
The simplest form would be <replace file="myfile.html" token="OLD" value="NEW"/>.
And if you really need it, you could run external tools with ant as documented at http://ant.apache.org/manual/Tasks/exec.html, which means that among other things you could, for example, call sed from ant with something like:
 <exec executable="sed">
   <arg value="s/old/new/g" />
   <arg value="$MY_FILE" />
 </exec>

A: The answer given by Acme, is the right one.
If you try to copy a file to itself in order to modify it, yells telling that yo cannot self-copy.
<reflexive file="./app/config/config.yml" tofile="./app/config/config.yml">
    <filterchain>
    <replacetokens begintoken="__" endtoken="__">
        <token key="BUILD_VERSION" value="Replace Value" />
    </replacetokens>
    </filterchain>
</reflexive>

This works well for me.


text:
Q: Automatic Update to SQL Server CE local database using sync framework I have deployed the sync framework for Oracle and SQL Server CE using the following link
http://code.msdn.microsoft.com/Database-Sync-Oracle-and-037fb083 successfully.
The SQL Server CE database updates after pressing synchronize button when I made any changes to the Oracle database.
But I need to update the SQL Server CE database (local cache database in my case) automatically once I made any change to the Oracle database, without pressing the synchronize button. Is this possible?

A: Yes, you can invoke the sync from code based on system events or a timer...


text:
Q: comparison of strings with a another string characters assume I have two strings a="a-b-c" and another one is b="a-b".
I want to check if string a contains every alphabet of string b.

A: An efficient solution will be to read the two strings into two sets of characters. After doing so, "every character in b in in a" if and only if b is a subset of a. It can be optimized to use only one set (for b) - see pseudo code.
The complexity of this approach is O(|a|+|b|) on average using hash table, or O(log(min{|a|,|b|})*(|a|+|b|)) worst case using tree based. It is much better comparing to a naive solution which will get you O(|a|*|b|) if you search each and every character.
Pseudo code:
setB <- empty set
for each element e in b:
  setB.add(e)
for each element e in a:
  setB.remove(e) //assuming doing nothing if doesn't exist
return setB.isEmpty()

The idea of the optimization is to load the elements (chars) of b into a set, and then iterate a while removing elements from the set if encountered.
Once you are done iterating a, if (and only if) there is a character in b that is not in a - it will remain in the set and the algorithm will return false

A: function func(a,b) {
    var alphabet = b.split("-");
    for (var i=0; i < alphabet.length; i++) {
      if (a.indexOf(alphabet[i]) == -1)
          return false;
    }
    return true;
}

func("a-b-c", "a-b");

A: you can use the following code:
var b = "a-b";
var a = "a-b-c";
var firstArray = b.split("-");
var secArray = a.split("-");
var length = firstArray.lenght;
for(var i =0; i<length; i++)
{
  if(secArray.indexOf(firstArray[i]) != -1)
    continue; //or do something
  else
    break; // or return false.
}

A: I am assuming that there are several ways and orders you could potentially get both Strings represented; that said, the most straight forward way would be to check for each char in String b if it is indeed contained in String a. For that purpose, you could easily call indexOf(currentCharFromStringB) on String a.
I hope the following example helps you to see my idea:
"Blue Whale".indexOf("Blue") != -1; // true
"Blue Whale".indexOf("Bloe") != -1; // false

Some pseudo code would be:
for each char in b
     for each char in a
        is a in b?

Now, it's up to you, dealing how you want to extract or represent each character of String B.
I hope this helps.


text:
Q: Thoughts on console.log/catch on webpage using socket.io/express.js Now trying to learn socket.io, and only able to find chat related tutorials around.
My approach is an app to log all "server" debug code (console.log, try/catch) remotely on a web page.
Its a very simple implementation (one way communication), a buffer could be implemented avoiding losing logs, a more robust way to show objects/arrays could be nice, and a few more changes...
Expert review required :) and suggestions always welcome.
// server.js
const app = require("express")();
const http = require("http").createServer(app);
app.io = require("socket.io").listen(http);
const logWeb = require("./logweb")(app)      // web log component

// testing
logWeb('testing');
logWeb({ txt: 'obj testing' });

app.set('view engine', 'ejs');
app.set('views', './views');
app.set('port', process.env.PORT || 5002);
app.get("/", (req, res) => res.send("working!") );
http.listen(app.get('port'), () => logWeb("live on: http://localhost:" + app.get('port')));

// logweb.js
"use strict";
module.exports = (app) => {
  const io = app.io.of("/logs");
  const getHandle = (req, res) => res.render("index");    // ejs template
  app.get("/logs", getHandle);

  const sendData = (msg) => {
    io.on("connection", (cli) => {
      const isObj = (x) => x instanceof Object && x.constructor === Object;
      const data = isObj(msg) ? JSON.stringify(msg, undefined, 2) : msg;
      const ts = new Date().toLocaleString("sv").replace(" ", "_");
      let out = { ts: ts, msg: data }
      cli.emit('log', out);
      console.log(out);
    });
  };
  return (msg) => sendData(msg);
};

// index.ejs

logServer started!


text:
Q: UWP MediaSource with authentication via HTTP I am trying to stream a video from a webserver via HTTP. To stream the video I currently create a MediaSource:
MediaSource.CreateFromUri(new Uri("https://example.com/video.mp4"));

And then I add that MediaSource to my MediaPlayerElement and the video plays.
This works as long as the server does not need authentication. But now I have a server which uses Basic auth so the video does not start.
My old requests looked similar to this
GET /video.mp4 HTTP/1.1
Range: bytes=0-
Accept: */*
User-Agent: NSPlayer/12.00.15063.0332 WMFSDK/12.00.15063.0332
GetContentFeatures.DLNA.ORG: 1
Accept-Encoding: gzip, deflate
Host: example.com
Connection: Keep-Alive enter code here
Now I need them to also have an Authentication Header, but I dont know how to achieve that (because I can't use my own HttpClient):
Authorization: Basic dXNlcjpwYXNzd29yZA==

I found this question UWP MediaElement source from http with authentication which is similar to my problem. The author solved his problem, but unfortunately did not exactly describe how he did it.
Can someone help here? How can I get the MediaSource or the MediaPlayerElement to use credentials/basic auth?

A: As you can see, MediaSource.CreateFromUri(Uri) method can only accept a Uri parameter, there is no way to set Authentication Header with this method.
To play a online video file that requires authentication, we can take advantage of HttpClient which can make HTTP requests with required credentials or headers manually.
And then we may also need a custom IRandomAccessStream class that builds on top of HttpClient, so we could use range headers to request just a sequence of bytes from the server and would not need to download the whole file in order to stream it.
For more info, you can refer to MediaPlayerElementWithHttpClient on GitHub, which implements a HttpRandomAccessStream class.

The HttpRandomAccessStream class is a wrapper on top of HttpClient that can stream content from the internet and can be consumed as an IRandomAcessStream or IRandomAccessStreamWithContentType.

And when using above solution, please note: The server must support HTTP Range headers.


text:
Q: Having trouble with getting Enterprise traps to be encrypted with net-snmp I am at a loss on this one.
I am using net-snmp version 5.7.3 and recently added support in the application to support SNMP v3.
SNMP GETS are working flawlessly with any combination of Auth and Priv protocol. I can see the encrypted PDU's when I capture with Wireshark and the MIB browser is able to decode and all works fine.
The problem I am having is with SNMP v3 traps. For the life of me I cannot get Enterprise traps to be encrypted. Wireshark capture shows them clearly going out in clear text.
Here is my relevant configuration:
In /etc/snmp/snmpd.conf I have:
master agentx
agentaddress udp:161
engineID 43f8513afdd8a1648e63a728be8625
rouser allenmcw priv
trapsess -v 3 -u allenmcw -a SHA -A <authPass>-x AES -X <privPass> <IP address>

In /usr/lib/snmp/snmpd.conf I have:
 usmUser 1 3 "43f8513afdd8a1648e63a728be8625" "allenmcw" "allenmcw" NULL .1.3.6.1.6.3.10.1.1.3 0x11c712fff7718594a12d2444a3356405a31b3c9c .1.3.6.1.6.3.10.1.2.4 0x11c712fff7718594a12d2444a3356405 0x
setserialno 746862596
##############################################################
#
# snmpNotifyFilterTable persistent data
#
##############################################################

    engineBoots 42
    oldEngineID "43f8513afdd8a1648e63a728be8625"

For trapsess I have tried the following variation as my understanding is that the passphrase, etc should be picked up with the usmUser entry.
trapsess -v 3 -u allenmcw -l authPriv
Note that this last option results in NO trap going out at all! The -l option should be valid based on all research I have done but it is not working for me.
It should be NOTED that the COLD start trap sent out by net-snmp itself IS getting encrypted, but NO enterprise level traps are.
I confess to being somewhat lost at this point as to what the problem could be.
Thanks for any guidance.
Allen

A: Have the solution. I suspect this occurred because in our environment we run a separate trap daemon to send all the enterprise traps.
Rather than have clear text passwords in the /etc/snmp/snmpd.conf the following will allow the trap daemon to use the HASHED version of the passwords which comes from /usr/lib/snmp/snmpd.conf
Here is the corrected trapsess line:
trapsess -v 3 -u allenmcw -3m 0x9d833d009db321cec1d2f1ed737bf11aff770fa1 -3M 0x9d833d009db321cec1d2f1ed737bf11a <IP address>

These hashed values were pulled from the other snmpd.conf referenced.


text:
Q: What is this software style called? It's a new app I want to build, but I would like some ideas, tips or information etc.
it's a web app with icefaces which people can generate their own dynamic page using drag-n-drop from components I created.
Example: there are 3 "components" an inputBox, OutputBox and FixedText. user can use them to generate a "script" doing something like following:
1- drag a the fixedText and put property "welcome, my name is: "
2- drag the outputBox and select from a list of variables, "myName"
3- drag the the inputBox and select from an list of where to store the variable "usrName"
then there will be a "script reader" and render the previous "script" into a page with following:
welcome, my name is John, [an_input_field_to_enter_user_name] and a "save" button, when pressed, the user_name will be saved in db.
it's like to create my own swing or my own tags for jsf but less powerful. or like those websites which assist you to create your own home page
any criticizes, help, tips, ideas are welcome.

A: It might be called WYSIWYG, or just a GUI for building UIs.


text:
Q: calculate student total marks and insert that total in another table with the id of that student together I'm developing a simple student information system, for now i have 300 students and six subjects, so when i want to add marks obtained by each student i use html form and php script to add those marks, for each student i add marks for six subjects that is one subject at a time, so i'm asking if there is the way where by php can allow me retrieve one student and add all the marks for the six subjects at once and then take another and so on. Also i want to calculate total marks for each student and store those total in another table with respective student id so that i can know who is the first student and who is the last by using that total marks of each student.
here is the way i'm doing right now
<?php error_reporting(E_ALL ^ E_NOTICE); ?>

<form action="connmarks.php" method="post">

Adding Student Results

    Student Code<?php echo $mstudentcode;?>
    <input name="student_code" type="text" size="30" value="<?php echo $studentcode;?>" />

    Subject Code<?php echo $msubjectcode;?>
    <input name="subject_code" type="text" size="30"  value="<?php echo $subject_code;?>"/>

    Marks<?php echo $mmark;?>
    <input name="mark" type="text" size="30" value="<?php echo $mark;?>"/>

     	<input type="submit" name="save" value="Add Marks" />

<?php echo $sms1.$sms.$sms2;?>

    </form>

Copyright <?php echo date("Y", time()); ?>

<?php error_reporting(E_ALL ^ E_NOTICE); ?>
<?php
session_start();
if(isset($_POST['save']))
{
//  validating student code
    if(empty($_POST['student_code']))
    {
        $mstudentcode='**';
    }
    else
    {
        $student_code=$_POST['student_code'];
    }
//  validation for kiswahili subject
    if(empty($_POST['subject_code']))
    {
        $msubjectcode='**';
    }
    else
    {
        $subject_code=$_POST['subject_code'];
    }
// validating english subject
    if(empty($_POST['mark']))
    {
        $mmark='**';
    }
    else
    {
        $mark=$_POST['mark'];
    }
// checking if there is any error message, if no error proceed, if there is error, display the error
//  Then exit the script and redirect at the same page
    if($mstudentcode||$msubjectcode||$mmark||$sms)
    {
        $sms1='Error found,please check **
';
        include 'addmarks.php';
        exit;
    }
// if there is no error include connection file
    if($student_code&&$subject_code&&$mark)
    {
//      include 'mysqli_connect.php';
      require_once ('../../mysqli_connect.php');
        $addmarks= "insert into result(student_code,subject_code,mark) values ('".$student_code."','".$subject_code."','".$mark."')";
        $k = mysqli_query($dbc, $addmarks);
        if ($k)
        {
       $sms1='Student Marks Submitted Successfully
';
            include 'addmarks.php';
                        exit;
        }
        else
        {
            $sms1='Failed To Add Student Marks
';
            include 'addmarks.php';
                        exit;
        }
    }
    }
?>

A: <!DOCTYPE html>

    <title></title>

    <form method="post">

        <select name="students">
            <option>Student 1</option>
            <option>Student 2</option>

            <?php
                //This code below is what you will need to use for yours to pull values out of the database(changing the values to suit yours obviously).

                // $query = "SELECT * FROM students ORDER BY student_name ASC";
                // $result = mysqli_query($conn,"$query");

                // while($row = mysqli_fetch_assoc($result)){
                //     echo "<option>" . $row['student_name'] . "
</option>";
                // }
            ?>

        </select>

        <input type="text" name="eng_grade" value="" placeholder="Enter English Grade">

        <input type="text" name="math_grade" value="" placeholder="Enter Maths Grade">

        <input type="text" name="science_grade" value="" placeholder="Enter Science Grade">

        <input type="submit" name="submit" value="Submit">
    </form>
    <?php

        //If submit is pressed
        if (isset($_POST['submit'])) {

            //this gets the value of the student name from the select box and stores it as $student
            $student = $_POST['students'];

            //These gets the values stored in the inputs above and store them in the 3 vairables
            $english = $_POST['eng_grade'];
            $maths = $_POST['math_grade'];
            $science = $_POST['science_grade'];

            //this is a mysql query that updates the data with whatever you put into the database(to add to existing tables you will have to dig abit deeper and create your
            //database with all the correct fields!
            $query = "UPDATE students SET maths_grade = '$maths', $english_grade = '$english', science_grade = '$science' WHERE student_name = '$student'";
            $update = mysqli_query($conn,  "$query"); //<-- this inserts the values into the database, changing the current #null value (null means nothing is in it)
        }

    ?>

A: Create 2 tables, one for student and other for marks.
In one table, just insert student name and id(unique), and in other table student all 6 subject marks i.e. 6 columns for 6 sub, 1 for student id, and other one as auto increment id column.
So using that student id you can retrieve all the subject marks of a particular student.

A: Edit: Just noticed this question is 3 years old w00t!?
Drafting tables would be something like
student table:
id   primarykey  integer
name notnullable nvarchar(255)

subject table
id   primarykey  integer
name notnullable nvarchar(255)

student_subject table
 id         primarykey integer
 student_id foreignkey notnullable unique integer
 subject_id foreignkey notnullable unique integer
 mark                  notnullable        double(2,2)

E.g. Select the marks of a subject
Select student.name, subject.name, subject_student.mark from subject_student
inner join student on student.id = subject_student.student_id
inner join subjecton subject.id = subject_student.subject_id
where student_id = X; // X is the id of the student you want

Any calculation should be based on query, you don't want to store results in the database. You want data in the database and since it's volatil data (can be changed anytime), it's easier and faster to calculate whenever required. Sum, GroupBy, there are a ton of basic sql keywords that can help you. student_subject table is the table where it combines that Many students in Many subjects with a certain mark. If you want to save a student's mark, you just Insert into this table the id's and the mark value.
Since it's a school project, this should be suffice for you to work it out.
In the future, take a look at prepared statements

http://php.net/manual/en/book.pdo.php


text:
Q: Can someone expalin me how facebook stores the start and end time of events? I got from various sources that Facebook stores The start and end time of events as PST. But there must be something I'm missing. Take this facebook event which I created. I live in Italy and in fact when I insert the event time it says UTC + 2. I insert 2012-05-18 10.30 PM as the event start time.  I Expect this to be saved as 1.30 PM Pacific time, because PST should be GMT -7 (because of daylight saving time). But if I do
$start = date("Y-m-d H:i:s", $facebook_event['start_time'] );

$start comes out 2012-05-19 05:30:00 which is 7 hours after the time I inserted! How is that possible? what am I missing?
EDIT - this is how I retrieve the event start_time
        $fql = "SELECT
                    eid,
                    name,
                    description,
                    start_time,
                    end_time,
                    venue,
                    location,
                    update_time
                FROM
                    event
                WHERE
                    eid IN (SELECT eid FROM event_member WHERE uid = $id)" ;
        $events = $facebook->api( array(
            'method' => 'fql.query',
            'query' => $fql,
        ) );

I don't use the /$id/events/ api call because I always get back an empty set when I get my friends events

A: let me explain the Facebook timezone rules,
Facebook always assumes start_time or end_time you are sending are in pacific timezone. so its our responsibility to send them in pacific timezone.
In above case,
You inserted 2012-05-18 10.30 PM in EST but Facebook assumes that you are sending it in pacific time. so it converts in to UTC as 2012-05-19 05:30:00. which you will recive throuh API.
simply fb_stored_time = epoch(UTC(assumed_Pacific_time))

A: Put this in your script before the date function.
date_default_timezone_set('America/Los_Angeles');


text:
Q: многократно очистить div от динамически создаваемого содержимого созданного jquery Добрый день, прошу помощи у сообщества, т.к. сам, что-то ни как не могу найти решения.
В редактор TinyMCE в конец поля редактирования вставляю при помощи jquery div c img.

var arrImgs = [];
$('#jsubmitbtn').on('mouseover', function(){
  $('#images img').each(function(){
    if($(this).hasClass('prev_img')){
      arrImgs.push($(this).clone());
    }
  });

  if(bodyTinyMCE.find('.slider').length == 0){
     bodyTinyMCE.append('

');
  }else{
    bodyTinyMCE.find('.slider').empty();
  }
$.each(arrImgs,function(){
    bodyTinyMCE.find('.slider').append($(this));
  });

Но получается, что очистка происходит только первый раз (при условии, что div уже был на странице), дальше картинки просто множатся, а требуется, чтоб содержимое див перезаписывалось каждый раз.
Пробовал удалять и создавать div - та же проблема.
Как я понимаю remove(), detach() , empty(), html("") позволяют работать только с DOM-элементами, а то что вставляется js`ом в дом не попадает (на данном этапе) или попадает раз отображается в структуре. В любом случае, ведь им явно можно как-то манипулировать. Вот только как?

A: Массив нужно создавать внутри, а не снаружи, как у меня

A: используйте классы для повторяющихся элементов, id - должен быть уникальным идентификатором: $('#images img').each...
ага, вы каждый раз добавляете новый элемент в массив arrImgs. стираете содержимое div.slider, и добавляете содержимое arrImgs, который естественно уже больше на один элемент.
pop и push -- отличный учебник по js
здесь, кстати, можно обойтись и без массива


text:
Q: BasicHTTPServer, SimpleHTTPServer and concurrency I'm writing a small web server for testing purposes using python, BasicHTTPServer and SimpleHTTPServer. It looks like it's processing one request at a time. Is there any way to make it a little faster without messing around too deeply?
Basicly my code looks as the following and I'd like to keep it this simple ;)
os.chdir(webroot)
httpd = BaseHTTPServer.HTTPServer(("", port), SimpleHTTPServer.SimpleHTTPRequestHandler)
print("Serving directory %s on port %i" %(webroot, port) )
try:
 httpd.serve_forever()
except KeyboardInterrupt:
 print("Server stopped.")

A: You can make your own threading or forking class with a mixin inheritance from SocketServer:
import SocketServer
import BaseHTTPServer

class ThreadingHTTPServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer):
    pass

This has its limits as it doesn't use a thread pool, is limited by the GIT, etc, but it could help a little (with relatively little effort).  Remember that requests will be served simultaneously by multiple threads, so be sure to put proper locking around accesses to global/shared data (unless such data's immutable after startup) done in the course of serving a request.
This SO question covers the same ground (not particularly at length).

A: You might also look at CherryPy -- it's pretty simple, too, and has multiple request threads with no additional effort.  Although your needs may be modest now, CP has a lot of nice capabilities that may benefit you in the future.

A: Depending on what your requirements are, another option might be to hook in Paste. Though, based on your example, it may be overkill.  Something to keep in the toolbox.


text:
Q: Getting java to display the correct amount of decrements I am making an app which is a guessing game between 1 and 100. The current version I am writing gives the player 7 tries to to find the correct guess. I have created a variable to display how many guesses the player has left, however once the player has guessed, the number of guesses decrements by more than one (usually two).
So basically the numberOfGuesses var. will decrement every time the checkGuess() method is run. I have tried placing the decrement in the event listener for when the player presses the button, but it's still decrementing by more than one. There is a setOnClick listener if the player clicks the mouse button too, and another for the enter button. When I use the button in the game, it decrements properly. When I use the ENTER button, it decrements by two. Is it running the button listener when I press ENTER?
I tried changing decrement from numberOfGuesses--; to --numberOfGuesses;
I tried assigning it as numberOfGuesses = numberOfGuesses - 1;
Here is the variables wiring to thew GUI, and the checkGuess() method
public class MainActivity extends AppCompatActivity {
    private EditText txtGuess;
    private Button btnGuess;
    private TextView lblOutput;
    private int theNumber;
    private int numberOfTries = 7;

    public void checkGuess() {
        String guessText = txtGuess.getText().toString();//
        String message = "";
        try {
            --numberOfTries;
            int guess = Integer.parseInt(guessText);
            if (guess > theNumber)
                message = guess + " is too high. You have " +numberOfTries + " " + " tries left! ";

            else if (guess < theNumber)
                message = guess + " is too low. You have " +numberOfTries + " " + " tries left! ";

            else{
                message = guess +
                        " is correct! You finished with " +numberOfTries + " tries left. Let's play again!";
                Toast.makeText(MainActivity.this, message,
                          Toast.LENGTH_LONG).show();
                newGame();

            }
        } catch (Exception e) {
            message = "Enter a whole number between 1 and 100.";
        } finally {
            lblOutput.setText(message);
            txtGuess.requestFocus();
            txtGuess.selectAll();

The newGame() method which generates a new random number
 public void newGame(){

        theNumber = (int)(Math.random() * 100 + 1);
        numberOfTries = 7;

    }

Here is the method which runs on execution of app
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtGuess = (EditText) findViewById(R.id.txtGuess);
        btnGuess = (Button) findViewById(R.id.btnGuess);
        lblOutput = (TextView) findViewById(R.id.lblOutput);
        newGame();
        btnGuess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                checkGuess();
            }
        });
        txtGuess.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
               checkGuess();
               return true;
            }
        });
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

       FloatingActionButton fab = findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });
    }

I am expecting the numberOfGuesses to decrement from 7 to 6, but the actual output is decrementing from 7 to 5, when I use enter, it works as I want for the button click (or at least displaying as 7 to 5),

A: Pressing enter while the text field is selected would trigger the OnEditorActionListener (and so would any other change, as far as I can tell).  Have you tried filtering that Listener by actionId to make sure it only goes off specifically for the enter key?


text:
Q: Are there any serious diseases in the Star Wars universe? Are there any serious diseases in the Star Wars universe, like cancer or other diseases which are incurable?

A: The Blue Shadow Virus was an artificially produced virus, created by the CIS on Naboo, during The Clone Wars tv show. I remember there being a three or four-part episode around it. It was deadly to most organisms. Does this count?

A: Hive viruses were a broad category of highly contagious viruses which would remain dormant in the host for some time before symptoms began to appear. A hive virus in its dormant stage is still contagious, and thus the virus could spread rapidly through a group before it became obvious that anyone was sick.
In the Legends continuity, a hive virus was responsible for the loss of the Katana fleet. By the time they realized that an epidemic was underway, the virus had spread throughout the crews of all of the 200 dreadnaughts in the fleet. The virus drove the crews insane and eventually killed them, leaving the fleet abandoned in an unknown location.

A: In the X-Wing series (part of Star Wars Legends), the Imperial Director of Intelligence engineers the Krytos virus, and the New Republic has to devise a cure while using vast amounts of bacta to keep the victims alive (if I recall correctly, bacta can stave off the symptoms, but not cure the virus). It's mostly mentioned in the third book of the X-Wing series, The Krytos Trap.

A: The rakghoul plague.

The rakghoul plague or rakghoul disease was a disease engineered by the ancient Sith Lord Karness Muur, it could turn most nearby sentient beings into a mindless rakghoul, a Sith-spawned mutant. The virus-like plague, carried by every rakghoul in existence at the time, could be spread to another being by a bite or a scratch from a rakghoul's claw. The victim would then suffer through an incubation period lasting approximately six to forty-eight hours before being transformed into a rakghoul, one fully capable of spreading the Sith-made disease on to further victims.
  -Wookieepedia

Like with many serious diseases in real world, there have been cases of it being cured in early stages of incubation, but once one turned into rakghoul, it was incurable.
This is in Legends.

A: The Legends novel Legacy of the Force: Betrayal features a man named Movac Arisster who is dying of incurable cancer.

I'm a nobody and I'm dying. In six months, incurable cancers of the lungs and other organs, probably caused by a radiation leak I experienced on a trip many years ago, will kill me.

A: Another example is Jedi Master Taria Damsin, who is dying from Borotavi syndrome.
It is basically described as cancer, including terminology like 'remission'.

"So," said Taria, once they were seated in a private booth with bowls
of steaming bean soup and fresh, crusty bread. The dining hall's air
was warm and scented with good food. Scattered, cheerful conversations
provided a backdrop of sound. "To make a long story short, Ahsoka,
it's called Borotavi syndrome. It's not contagious but it is terminal.
Eventually."
Ahsoka felt her mouth suck dry. Terminal? But—but—She's so young and
strong and amazing. So alive. "How did you get it?"
"I ate the wrong kind of shellfish on Pamina Prime." With a wry smile
Taria stirred a pinch of salt into her soup. "Turns out it's the
blue-shelled mollusk with the green stripe you need to watch out for.
Blue mollusks with black stripes you can eat till you burst." She sat
back. "Just a little tip to stand you in good stead, if ever you find
yourself on Pamina Prime."
Star Wars Clone Wars Gambit: Stealth


text:
Q: Fetch value from SharePoint JSON output I am getting below JSON object from a Sharepoint list. How can I get the value for Company in the Data operation ( select) for logic apps. I did item()['Company']?['Value'] and it is not working. Any suggestions?
"body": [
  {
    "Company": {
      "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
      "Id": 0,
      "Value": "Test1"
    },
    "Date From": "2022-03-30",
    "Date To": "2022-03-31",
    "Title": "Title 1"
  },
  {
    "Company": {
      "@odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference",
      "Id": 2,
      "Value": "Line2"
    },
    "Date From": "2022-03-21",
    "Date To": "2022-03-29",
    "Title": "Title 2"
  }
]
}

I am fetching share-point list and then using data operations (select) to get the JSON as output.
I need JSON in the below format so that I can pass this to stored procedure and insert into the Azure SQL DB. I have another 12 items in the list.
         [
          {
            "Company": "Test1",
            "Date From": "2022-03-30",
            "Date To": "2022-03-31",
            "Title": "Title 1"
          },
          {
            "Company": "Line2",
            "Date From": "2022-03-21",
            "Date To": "2022-03-29",
            "Title": "Title 2"
          }
        ]

A: Rather than select, you can set a variable.  We're all different but that makes far more sense to me.

Your expression is much the same, I used ...
item()['Company']['Value']

Just make sure you initialise the variable outside and prior to the For each ...

This is the result for the first item in the array ...

To compile a full JSON object and add it to an array, again, simply use a variable and specify the values as need be.
Firstly, initialize your array outside of the For each ...

... and then in the For each, add an object to the array variable on each loop (make sure you include the quotes around the expression where required) ...

You just have to compile the JSON.  The end result will look like this ...

This is the JSON in full ...
[
  {
    "Company": "Line2",
    "Date From": "2022-03-21",
    "Date To": "2022-03-29",
    "Title": "Title 2"
  },
  {
    "Company": "Test1",
    "Date From": "2022-03-30",
    "Date To": "2022-03-31",
    "Title": "Title 1"
  }
]

Also, you'll notice my list has come out in a different order, that's because the For each runs in parallel, if you need to avoid that, change the settings so it runs in a single thread ...

This is the JSON definition of the LogicApp, you can load it into your tenant and test with it ...
{
    "definition": {
        "$schema": "https://schema.management.azure.com/providers/Microsoft.Logic/schemas/2016-06-01/workflowdefinition.json#",
        "actions": {
            "For_each": {
                "actions": {
                    "Append_to_SQL_Array": {
                        "inputs": {
                            "name": "SQL Array",
                            "value": {
                                "Company": "@{item()['Company']['Value']}",
                                "Date From": "@{item()['Date From']}",
                                "Date To": "@{item()['Date To']}",
                                "Title": "@{item()['Title']}"
                            }
                        },
                        "runAfter": {},
                        "type": "AppendToArrayVariable"
                    }
                },
                "foreach": "@variables('SharePoint JSON')",
                "runAfter": {
                    "Initialize_SQL_Array": [
                        "Succeeded"
                    ]
                },
                "runtimeConfiguration": {
                    "concurrency": {
                        "repetitions": 1
                    }
                },
                "type": "Foreach"
            },
            "Initialize_SQL_Array": {
                "inputs": {
                    "variables": [
                        {
                            "name": "SQL Array",
                            "type": "array"
                        }
                    ]
                },
                "runAfter": {
                    "Initialize_SharePoint_JSON": [
                        "Succeeded"
                    ]
                },
                "type": "InitializeVariable"
            },
            "Initialize_SharePoint_JSON": {
                "inputs": {
                    "variables": [
                        {
                            "name": "SharePoint JSON",
                            "type": "array",
                            "value": [
                                {
                                    "Company": {
                                        "Id": 0,
                                        "Value": "Test1",
                                        "odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference"
                                    },
                                    "Date From": "2022-03-30",
                                    "Date To": "2022-03-31",
                                    "Title": "Title 1"
                                },
                                {
                                    "Company": {
                                        "Id": 2,
                                        "Value": "Line2",
                                        "odata.type": "#Microsoft.Azure.Connectors.SharePoint.SPListExpandedReference"
                                    },
                                    "Date From": "2022-03-21",
                                    "Date To": "2022-03-29",
                                    "Title": "Title 2"
                                }
                            ]
                        }
                    ]
                },
                "runAfter": {},
                "type": "InitializeVariable"
            },
            "Initialize_variable": {
                "inputs": {
                    "variables": [
                        {
                            "name": "Result",
                            "type": "array",
                            "value": "@variables('SQL Array')"
                        }
                    ]
                },
                "runAfter": {
                    "For_each": [
                        "Succeeded"
                    ]
                },
                "type": "InitializeVariable"
            }
        },
        "contentVersion": "1.0.0.0",
        "outputs": {},
        "parameters": {},
        "triggers": {
            "Recurrence": {
                "evaluatedRecurrence": {
                    "frequency": "Month",
                    "interval": 12
                },
                "recurrence": {
                    "frequency": "Month",
                    "interval": 12
                },
                "type": "Recurrence"
            }
        }
    },
    "parameters": {}
}


text:
Q: Display linux terminal colors in windows In Linux terminal, we can use colors, that's totally cool.
Now, I have some Linux script that produces colorful text. I would like to give the output to someone who uses Windows. How can I preserve the colors?
My understanding is that Windows terminal does not support the same kind of color encoding. Installing cygwin is probably too demanding. The output is too long so giving a screenshot is not an option.

A: Depending on the Linux terminal you are using, when copying the colored text from it, it should copy it with color too. For example, copying from Cygwin's MinTTY to Microsoft Word copies it colored.
Anyway, it's called ANSI escape codes, so you can search for editors or terminals for Windows that support ANSI escape codes.


text:
Q: How do I perform an iterative calculation using a value from another table selected based on a YYYY-MM date and write it back to the first table? Started learning PHP and MySQL yesterday and have managed to create two tables, insert rows and then display that data on a web page using various different groupings. Now I need to do a calculation based on data in the two tables and write the result back to one of the tables.
I'm trying to figure out how to perform an equation for a row with a date in table A using a range of values associated with a range of dates in table B. The two dates are in the format YYYY-MM-DD, but the days mostly do not match, so I need match on the month.
Here's the two tables I have:
Table A (user)
+----+----------+------------+-------------+
| id | username | start-date | bench-value |
+----+----------+------------+-------------+
|  1 | tim      | 2010-03-04 |             |
+----+----------+------------+-------------+
|  2 | jim      | 2010-05-30 |             |
+----+----------+------------+-------------+
|  3 | fred     | 2010-06-12 |             |
+----+----------+------------+-------------+
|  4 | sam      | 2010-08-16 |             |
+----+----------+------------+-------------+
|  5 | jane     | 2010-10-21 |             |
+----+----------+------------+-------------+
|  6 | ella     | 2010-10-21 |             |
+----+----------+------------+-------------+
|  7 | bob      | 2011-01-24 |             |
+----+----------+------------+-------------+

Table B (benchmark)
+----+------------+---------+
| id | start-date |  value  |
+----+------------+---------+
|  1 | 2010-01-31 | 1173.19 |
+----+------------+---------+
|  2 | 2010-02-28 | 1199.85 |
+----+------------+---------+
|  3 | 2010-03-31 | 1264.91 |
+----+------------+---------+
|  4 | 2010-04-30 | 1263.43 |
+----+------------+---------+
|  5 | 2010-05-31 | 1211.36 |
+----+------------+---------+
|  6 | 2010-06-30 | 1187.32 |
+----+------------+---------+
|  7 | 2010-07-31 | 1218.30 |
+----+------------+---------+
|  8 | 2010-08-31 | 1207.96 |
+----+------------+---------+
|  9 | 2010-09-30 | 1272.12 |
+----+------------+---------+
| 10 | 2010-10-31 | 1280.27 |
+----+------------+---------+
| 11 | 2010-11-30 | 1275.60 |
+----+------------+---------+
| 12 | 2010-12-31 | 1346.45 |
+----+------------+---------+
| 13 | 2011-01-31 | 1337.07 |
+----+------------+---------+
| 14 | 2011-02-28 | 1338.37 |
+----+------------+---------+
| 15 | 2011-03-31 | 1349.14 |
+----+------------+---------+

And here's an example of what I'm trying to achieve:
tim's current bench value today = the sum of: (first(benchmark.value)/latest(benchmark.value))for every month from the first to the latest month inclusive
First date  = 2010-03 which is id  3 = 1264.91
Latest date = 2011-03 which is id 15 = 1349.14 (this is always the last row as I am trying to calculate on "today" and nothing in the future)
1/(first/latest)   =1/(1264.91/1349.14) = 1.0666    [this is bench.id=3]
...now iterate...
1/(next/latest)    =1/(1263.43/1349.14) = 1.0678    [bench.id=4]
1/(next/latest)    =1/(1211.36/1349.14) = 1.1137    [bench.id=5]
1/(next/latest)    =1/(1187.32/1349.14) = 1.1363    [bench.id=6]
1/(next/latest)    =1/(1218.30/1349.14) = 1.1074    [bench.id=7]
1/(next/latest)    =1/(1207.96/1349.14) = 1.1169    [bench.id=8]
1/(next/latest)    =1/(1272.12/1349.14) = 1.0605    [bench.id=9]
1/(next/latest)    =1/(1280.27/1349.14) = 1.0538    [bench.id=10]
1/(next/latest)    =1/(1275.60/1349.14) = 1.0577    [bench.id=11]
1/(next/latest)    =1/(1346.45/1349.14) = 1.0020    [bench.id=12]
1/(next/latest)    =1/(1337.07/1349.14) = 1.0090    [bench.id=13]
1/(next/latest)    =1/(1338.37/1349.14) = 1.0080    [bench.id=14]
...and finish up...
1/(current/latest) =1/(1349.14/1349.14) = 1.0000    [bench.id=15]

Total = 13.7997 = 1.0666 + 1.0678 + 1.1137 + 1.1363 + 1.1074 + 1.1169 + 1.0605 + 1.0538 + 1.0577 + 1.002 + 1.009 + 1.008 + 1

So I would then want to write that result back to Table A, giving me:
Table A (user)
+----+----------+------------+-------------+
| id | username | start-date | bench-value |
+----+----------+------------+-------------+
|  1 | tim      | 2010-03-04 |     13.7997 |
+----+----------+------------+-------------+

As this is an iterative process it would be a much shorter calculation for a user like 'bob' who started in 2011-01.
I would also like to be able to do this every 4 months to produce termly stats so that someone like user tim would be calculated like this (the initial search to find the first date would need to take into account over a 4 month period):
1/(first/latest)   = 2010-03 = 1/(1264.91/1349.14) = 1.0666
1/(next/latest)    = 2010-07 = 1/(1218.30/1349.14) = 1.1074
1/(next/latest)    = 2010-11 = 1/(1275.60/1349.14) = 1.0577
1/(current/latest) = 2011-03 = 1/(1349.14/1349.14) = 1.0000

Total = 1.0666 + 1.1074 + 1.0577 + 1 = 4.2317

That major issues I'm having are two fold:
1. how to use the user.start-date value for each user to pick the first(benchmark.value) based ont he year and the month (day is unimportant).
2. how to iteratively calculate the formula up to and including the latest value in the bench table - at the end of april, a new row with id=16 would be added and if this were run then the April value would become the last value used in the calculation.
As I'm learning SQL And PHP right now I'm not sure which parts of this process should be done in SQL and which in PHP.
Any and all help would be greatly appreciated as I'm determined to figure this out.
That major issues I'm having are two fold:

*

*how to use the user.start-date value
for each user to pick the
first(benchmark.value) based on the
year and the month (day is
unimportant).

*how to iteratively calculate the
formula up to and including the
latest value in the bench table - at
the end of april, a new row with
id=16 would be added and if this
were run then the April value would
become the last value used in the
calculation.

As I'm learning SQL And PHP right now I'm not sure which parts of this process should be done in SQL and which in PHP.
Any and all help would be greatly appreciated as I'm determined to figure this out.
Just for reference, I've been reading:

*

*http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

*http://www.databasejournal.com/features/mssql/article.php/10894_2191631_3/Working-with-SQL-Server-DateTime-Variables.htm

*There were more but it won't let me post the other links yet...

There's almost too much info out there, so some guided advice would be realy appreciated. Thanks again.

A: I wouldn't include the column bench-value in table A. This value will be constantly changing, so it would be better to create a View that would calculate the latest User bench-value or create a stored procedure that takes a User as a parameter and then returns the bench-value
There also needs to be a link/key between the two tables, right now there is no way to tell which user is related to which benchmark

A: Wow, what a well asked question. Sadly my reply maybe a lot shorter.
What I think you're looking for is:

bob's current bench value today = the
  sum of:
  first(benchmark.value)/latest(benchmark.value)
  First date = 2011-01 which is id 13 =
  1337.07 Latest date = 2011-03 which is id 15 = 1349.14

select username, start_date, tmp.value/tmp2.value as new_mark from tablea
 join (select id,value from tableb having id=min(id) group by id) as tmp
 on tablea.id=tmp.id
join  (select id,value from tableb having id=max(id) group by id) as tmp2
on tablea.id=tmp2.id

That seems ugly but should work.


text:
Q: Lambda Localstack Cannot Access Mysql Container in Docker Compose I have a local deployment using AWS Lambda, MySQL, and Localstack using Docker compose. So the Lambda is a simple javascript code accessing MySQL.
var mysql = require('mysql');

var con = mysql.createConnection({
    host: "mariadb",
    user: "root",
    password: "password",
    database: "database"
});

exports.handler =  async function(event, context) {

    con.connect(function(err) {
        if (err) throw err;
        console.log("Connected!");
    });

    return {
        statusCode: 200,
        body: `Received: ${event.message}`
    };
}

The docker compose is like below.
version: '3.3'
services:
  localstack:
    image: localstack/localstack:latest
    environment:
     - DEFAULT_REGION=ap-southeast-3
     - SERVICES=s3,lambda
    ports:
     - '4566-4583:4566-4583'
  mariadb:
    image: mariadb:latest
    ports:
      - "3306:3306"
    environment:
      - MYSQL_ROOT_PASSWORD=password
      - MYSQL_DATABASE=database
    restart: always

I have a simple script to bundle the Lambda, creating and uploading the function to localstack, then invoking it.
The deploy script looks like below
#!/usr/bin/env bash
echo "Bundling Function"
cd lambda
zip -r ../lambda.zip *
cd ..

echo "Creating Function"
aws lambda create-function \
    --endpoint-url http://localhost:4566 \
    --function-name lambda \
    --runtime nodejs14.x \
    --role arn:aws:iam::000000000000:role/lambda \
    --handler index.handler \
    --zip-file fileb://lambda.zip

echo "Invoking Function"
aws lambda invoke \
    --endpoint-url http://localhost:4566 \
    --function-name lambda \
    --payload fileb://payload.json \
    output.json

I have successfully deploy the Lambda to localstack. However the script failed at invocation.
I tried adding the configuration LAMBDA_DOCKER_NETWORK to bridge, host, or <project>_default but it fails at the Lambda uploading. I couldn't find a simplest code everywhere to showcase Lambda accessing other container in Docker compose. In case you want to reproduce, I uploaded to code here https://github.com/petrabarus/lambda-localstack-database.
What did I miss?

A: It turns out that I have to mount the docker socket in the container. This works like charm.
version: '3.3'
services:
  localstack:
    container_name: "${LOCALSTACK_DOCKER_NAME-localstack_main}"
    image: localstack/localstack:latest
    environment:
     - DEFAULT_REGION=ap-southeast-3
     - SERVICES=s3,lambda
     - DEBUG=${DEBUG-}
     - PERSISTENCE=${PERSISTENCE-}
     - LAMBDA_EXECUTOR=${LAMBDA_EXECUTOR-}
    ports:
     - "127.0.0.1:4566:4566"
     - "127.0.0.1:4510-4559:4510-4559"
    volumes:
      - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack"
      - "/var/run/docker.sock:/var/run/docker.sock"
  postgres:
    image: postgres:alpine
    ports:
      - "5432:5432"
    volumes:
      - ./volume/postgres:/var/lib/postgresql/data
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=postgres
    restart: always

A: I had the same problem and the solution was adding:
environment:
       - DOCKER_HOST=unix:///var/run/docker.sock
volumes:
      - "/var/run/docker.sock:/var/run/docker.sock"

Docker daemon process was missing in first place.


text:
Q: Issues in new folder structure in a dojo tree How can I make the store observable for the ItemFileWriteStore function below?Am I using the correct syntax below? It isn't working in my code, please suggest.
 store = new dojo.store.Observable(dojo.data.ItemFileWriteStore{
target:'store'
url: "my url"

}

I have written a small function in my dojo tree code as below to add new child folder under the parent folder of the tree structure created but it is not getting saved finally in the store. It is opening till the prompt "Folder name", after that when I add the folder name and click on ok, it is not saving in the folder tree structure. can someone suggest where it is going wrong?
Here is my code to create new folder which isnt working:
function myFunction(item){
item.name = prompt("Folder name");
var childItem = {
              name: "New Folder",
              id: Math.random(),
              parent: item.id
            };
 store.put(childItem, {overwrite: true
                  });

           store.put(item);
         }

A: dojo.data.ItemFileWriteStore is old dojo data store which will be deprecated in the future. The recommended new dojo stores are in dojo.store module, like Memory store and JsonRest store.
dojo.store.Observable only works with new dojo.store . You can do:

*

*Either change your dojo.data.ItemFileWriteStore to dojo.store.Memory

*or wrap your dojo.data.ItemFileWriteStore with dojo.store.DataStore


text:
Q: Ускорение разбиения текста c++ Требуется разбить большой файл (1 600 000 строк) на строки и сохранить в коллекцию с уникальными значениями. Подгрузка файла происходит на javascript, полученный из файла текст отправляется в модуль на c++, где происходит разбивка файла по строкам. Созданная коллекция возвращается обратно в js. Код который мне удалось написать:
C++:
#include <node.h>
#include <v8.h>

#include <string>
#include <sstream>
#include <iterator>

using namespace v8;

// Split function --------------------------------------------------------------
template<typename Out>
void split(const std::string &s, char delim, Out result) {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        *(result++) = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}

// Dictionary parse ------------------------------------------------------------
void Parse(const FunctionCallbackInfo<Value>& args) {
    Isolate* isolate = args.GetIsolate();
    Local<Context> context = isolate->GetCurrentContext();

    // Set для записи слов
    Local<Set> Words = Set::New(isolate);

    // Проверка аргумента на тип
    if (!args[0]->IsString()) {
        isolate->ThrowException(
            Exception::TypeError(
                String::NewFromUtf8(isolate, "Wrong type of first argument")
            )
        );

        return;
    }

    // Конвертим аргумент в строку
    String::Utf8Value arg(args[0]->ToString());
    std::string dictInput = std::string(*arg);

    // Разбиение строки в вектор
    std::vector<std::string> v = split(dictInput, '\n');

    // Перебор вектора
    std::vector<std::string>::iterator it = v.begin();
    for (it; it != v.end(); ++it) {
        // Сохраняем слово в коллекцию
        Words->Add(context, String::NewFromUtf8(isolate, (*it).c_str()));
    }

    // Возвращаем получившийся Set
    args.GetReturnValue().Set(Words);
}

// Module exports --------------------------------------------------------------
void Init(Local<Object> exports, Local<Object> module) {
    NODE_SET_METHOD(module, "exports", Parse);
}

NODE_MODULE(addon, Init)

Javascript:
const fs = require('fs');
const readDict = require('./build/Release/read-dictionary')

let text = fs.readFileSync('./dictionary.txt', 'utf8')
let WORDS = readDict(text);

Проблема состоит в том, что код на C++ работает дольше 2200 мс, в то время как аналогичный код на js работает около 1550 мс, что тоже очень долго (и занимает всего десять строк, да):
const fs = require('fs');

let WORDS = new Set()

let file = fs.readFileSync('file.txt')
let list = text.split('\n')

for (let i = 0; i < list.length; i++) {
    // Быстрее, чем "WORDS = new Set(list)"
    WORDS.add(list[i++])
}

С целью ускорить обработку и была предпринята попытка написания на C++, но пока не очень удачная. ++ я не знаю совсем, сегодня первый день как пишу на нём. Есть какие-то способы ускорить всё это?
Спасибо


text:
Q: Is it OK to call authentication methods from the view in Codeigniter? I am using TankAuth with Codeigniter, and I was wondering if it is alright to call library specific methods from the view, as opposed to passing them from the controller? For example,
$this->tank_auth->is_logged_in()

Called from the view is so much more convenient for outputting dynamic HTML than passing the variables from the controller. However, is it safe? Is it an acceptable practice?

A: There is no reason why you cannot do that but its against the MVC concept. You could have these kind of things set in the constructor of an extended controller so you have variables like $is_logged_in available in all your controllers to make it easier.


text:
Q: JDBC Connection inside DAO layer Good day,
I try to create DAO layer, following mostly this guide.
Take a note, that I don't use any frameworks, just plain JDBC.
Take a look on creating a Connection instance:
Inside each CRUD method we obtain a connection the following way:
Connection connection = daoFactory.getConnection();

So we obtain a new connection each time we call method.
The only question I have is how to implement transactions here?
I see two solutions:

*

*Instead of DaoFactory field, I use Connection field, which I share among the methods. So as to have one Connection per DAO. But then, what layer should be responsible for transaction? Should I create something in between Service - DAO?

*I create fields for other DAO instances needed to create transaction. So as if, for example, I would have TransactionDao to implement banktransfer (take money from one user and add to another) and this TransactionDao will have also UserDao, because I should make one create and two update actions.

I want to know the right solution, maybe it's none of above mentioned.
Tell me please also are there any concurrency issues I should be worry about?
Thank you

A: The simplest solution is to always perform transaction within a single DAO method, grabbing the connection at the start of the method and passing it to the rest of the methods which run SQL that needs to be part of this transaction.
I wouldn't advice you to roll your own alternative to this simplistic approach.  Spring will allow you to do this with its behind the scenes magic, and I'm sure there are other frameworks for doing it, dozens of them, but if you want to keep it simple, keep it simple.
If some of these methods are also standalone kind, I would do something like this:
public void incBalance(int accountId, int val) {
  Connection conn = daoFactory.getConnection();
  incBalance(conn, accountId, val);
}

private void incBalance(Connection conn, int accountId, int val) {
  con.update(...);
}

public void transfer(...) {
  Connection conn = daoFactory.getConnection();
  conn.beginTransaction();
  ...
  incBalance(conn, acc1, val);
  incBalance(conn, acc2, -val);
  ...
  conn.commit();
}


text:
Q: how to get FCM message in a UIViewController in Swift3? I am using swift3. I want to show FCM message to tableview in a UIViewController when My app receive FCM message data.I have got my fcm data using bellow code in appDelegate..But I don't know how to get data in UIViewController.
func userNotificationCenter(_ center: UNUserNotificationCenter,  willPresent notification: UNNotification, withCompletionHandler   completionHandler: @escaping (_ options:   UNNotificationPresentationOptions) -> Void) {

    let message : UNNotificationPresentationOptions = .alert

    //GlobalVariables.notification_message = getAlert(notification: .alert)

    if UIApplication.shared.applicationState == .active { // In iOS 10 if app is in foreground do nothing.
        print("active****")

        print("\(notification.request.content.userInfo)")
        completionHandler([message, .sound])

    } else {
        print("Not active****")
        completionHandler([message, .badge, .sound])
    }
}

Please help me
Thanks advance

A: Set a variable on your AppDelegate, then use it from either:

*

*AppDelegate's didFinishLaunchingWithOptions on window?.rootViewController

*Your view controller by calling (UIApplication.shared.delegate as? AppDelegate)?.yourVariable
I recommend setting variable in AppDelegate to nil after using it, to prevent using same notification data twice.

A: In app delegate change your code like this
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
   // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.sandbox)
   // FIRInstanceID.instanceID().setAPNSToken(deviceToken, type: FIRInstanceIDAPNSTokenType.prod)

}
func applicationWillTerminate(_ application: UIApplication) {
    UserDefaults.standard.removeObject(forKey: "check")
    UserDefaults.standard.removeObject(forKey: "userid")
    UserDefaults.standard.removeObject(forKey: "patient_no")
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    let state: UIApplicationState = UIApplication.shared.applicationState

    if state == .active{
        UIApplication.shared.applicationIconBadgeNumber = 0

        if let notification = userInfo["aps"] as? [AnyHashable: Any],
            let alert = notification["alert"] as? String {
            print(alert)
            message = alert
            let localNotification = UILocalNotification()
            localNotification.alertBody = alert
            localNotification.soundName = UILocalNotificationDefaultSoundName
            UIApplication.shared.scheduleLocalNotification(localNotification)
            print("Active----")
        }
    }else if state == .inactive{

        if let notification = userInfo["aps"] as? [AnyHashable: Any],let alert = notification["alert"] as? String {
            print(alert)
            message = alert
            let localNotification = UILocalNotification()
            localNotification.alertBody = alert
            localNotification.soundName = UILocalNotificationDefaultSoundName
            UIApplication.shared.scheduleLocalNotification(localNotification)
            print("Inactive----")

        }
    }else if state == .background{

        if let notification = userInfo["aps"] as? [AnyHashable: Any],let alert = notification["alert"] as? String,let sound = notification["sound"] as? String{
            print(alert)
            message = alert
            var localNotification = UILocalNotification()
            localNotification.alertBody = alert
            localNotification.soundName = sound
            UIApplication.shared.applicationIconBadgeNumber = number!+1
            print(number!+1)
            UIApplication.shared.scheduleLocalNotification(localNotification)
            print("Background----")

        }
    }
}

then add this where you want the message back
    let delegate = UIApplication.shared.delegate as! AppDelegate
    let message = delegate.message

*

*This is a sample only you want to add some condition


text:
Q: Robots.txt Disallow Certain Folder Names I want to disallow robots from crawling any folder, at any position in the url with the name: this-folder.
Examples to disallow:
http://mysite.com/this-folder/
http://mysite.com/houses/this-folder/
http://mysite.com/some-other/this-folder/
http://mysite.com/no-robots/this-folder/

This is my attempt:
Disallow: /.*this-folder/

Will this work?

A: Officially globbing and regular expressions are not supported:
http://www.robotstxt.org/robotstxt.html
but apparently some search engines support this.


text:
Q: remove index.php from url codeigniter when put in sub folder i want to remove index.php from url . i put codeigniter file in  subfolder
http://192.168.2.8/mydomain_folder/subdomain_folder/index.php/admin_controls

want to get it as
   http://192.168.2.8/mydomain_folder/subdomain_folder/admin_controls

.htacess file
<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine on
RewriteCond $1 !^(index\.php|robots\.txt|favicon\.ico|public)
RewriteRule ^(.*)$ /app_staging/index.php/$1 [L]
</IfModule>

where to place the .htacess files
I put 1 at the root folder and another inside application folder.

A: Add this code in top of your .htaccess file
  RewriteEngine On
  RewriteCond %{REQUEST_FILENAME} !-f
   RewriteCond %{REQUEST_FILENAME} !-d
   RewriteCond $1 !^(index\.php|images|robots\.txt)
   RewriteRule ^(.*)$ index.php?/$1 [L]

Put it in root folder where index.php is available.
test on your server have mod_rewrite enabled?

A: Find $config['index_page'] = 'index.php'; and remove the variable 'index.php' form /root/codeigniter/config/config.php you rewrite looks good.


text:
Q: I need Difference between the VERY LAST values and the 2nd LAST values for each record I have two table_One and Table_Two for each client the very 1st Record goes into Table_One There after any more records for that client goes into Table_Two.
Now I want the Difference between the very last record and the 2nd last record added for that client. say X is the very last value added for the client and Y is the 2nd last value added for the client. I want the Value X - Y = value in my result set.   I have attached a screen shot of the tables and desired result set.

"Every Client will have a record in Table_One but may or may not have a record in Table_Two , Only the very 1st record goes into Table_One"
"If the very last two records are both in Table_Two then I need the Difference between them values."
my limitations are I cannot create a stored procedure as this query is being plugged into a 3rd party software and I can only execute ah-hoc sql there or UDFs but no stored procedures :(.

A: first put all records in one result (using a cte)
then construct query by joining this to original table1, twice
with combined (clientid, date, column3) as
(select clientid, date, column3 from table1
 union all
select clientid, date, column3 from table2)
select t1.clientid, t1.column1, t1.column2,
       l.column3-nl.column3
from table1 t1
  join combined l  -- the last record
     on l.clientid = t1.clientid
       and l.date = (select max(date)
                     from combined
                     where clientid = t1.clientid)
  join combined nl -- the next to last record
     on nl.clientid = t1.clientid
       and nl.date = (select max(date)
                     from combined
                     where clientid = t1.clientid
                        and date < l.date)


text:
Q: Where are Profiles stored in Wine 1.6? I am running several programs via Wine 1.6, and I need to get into the data that they would normally store under the users profile in Windows, i.e., the "AppData/Local" folder.
Everywhere I have looked says that this is in the "Profiles" folder in .wine/drive_c/windows.
But I do not have a "Profiles" folder there. I have looked and looked, but no where can I find the user profiles that are stored for Wine programs. Anybody help me out?

A: In Windows the AppData folder is located in C:\Users\yourname\AppData. That folder is hidden away.
In Wine the AppData folder is located at /home/$USER/.wine/drive_c/users/yourname/.  To find the folder open "Files" (which opens to /home/$USER for your user).
The .wine folder should be here but, it is hidden. To unhide it, press CTRL+H. Now you should see the .wine folder.
Next, open and goto drive_c and you should see the folders Windows, users, Program Files, and Program Files (x86). Open users and navigate into your folder.
You should now see Application Data.