Q:

base64 to hex inconsistent results

Yesterday, I wrote a unit test in java. The routine I was testing needed to convert a base64 in hex and back.
In my test, I used the string myEvent= for the base64. In hex, it becomes 9B212F7A7B, but when I convert the hex back to base64, I get myEvens=.
Why is this happening? I tried different libs and tools and it always give me this result.
import java.util.*;
import java.lang.*;

import javax.xml.bind.DatatypeConverter;

class Rextester
{
    public static void main(String args[])
    {
        String data1 = "myEvent=";
        String hex1 = convertBase64StringToBase16(data1); // 9B212F7A7B
        String data2 = convertBase16StringtoBase64(hex1); // myEvens=
        String hex2 = convertBase64StringToBase16(data2); // 9B212F7A7B
        System.out.println("data1=" + data1);
        System.out.println("data2=" + data2);
        System.out.println("hex1=" + hex1);
        System.out.println("hex2=" + hex2);
    }

    private static String convertBase16StringtoBase64(String base16) {
        return Base64.getUrlEncoder().encodeToString(DatatypeConverter.parseHexBinary(base16));
    }

    public static String convertBase64StringToBase16(String base64) {
        return DatatypeConverter.printHexBinary(Base64.getUrlDecoder().decode(base64));
    }
}

Live demo: http://rextester.com/JFDYO56442

A:

The base64 algorithm says:

When the number of bytes to encode is not divisible by three (that is, if there are only one or two bytes of input for the last 24-bit block), then the following action is performed:
Add extra bytes with value zero so there are three bytes, and perform the conversion to base64. If there was only one significant input byte, only the first two base64 digits are picked (12 bits), and if there were two significant input bytes, the first three base64 digits are picked (18 bits). '=' characters might be added to make the last block contain four base64 characters.

So, since your last block (ent=) contains a single =, that means that the original byte array ended with a block of 2 bytes, or 16 bits.

The first 6 bits were the number 30, leading to the character e.
The next 6 bits were the number 39, leading to the character n.
That leaves 4 significant bits followed by two 0 bits due to the padding, which should thus lead to an even number. And yet your third character is t, which represents the number 45. And 45 is odd. So that means that ent= is not a valid base64 block. A correct base64 encoder would never encode any byte sequence to ent=.

The number 45 is, in binary 101101. But since only the first 4 bits are significant, A correct encoder should have taken them and padded them with two 0 bits, leading to 101100, which is the number 44, leading to the letter s.
So, to recap, you would never have such a "bug" if the base64 value you're decoding was a correct base64 value.


Q:

Radio Button Text over Button

I'm trying to create a view in android that looks like:
Text

Radio Button 1
...
...

I thought it was simple enough but at least in the layout preview and emulator I'm seeing the text for the RadioButton appear on top of the actual radio button (the circle), see the attached screen shot. I'm guessing this is something very trivial but I'm messed around with gravity and every other setting I can think of and nothing. Android 3.1 if that matters.
Here's my layout:
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:orientation="vertical"
  android:background="@color/white"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<TextView android:id="@+id/question_text"
    android:textColor="@color/primary_gray"
    android:layout_width="match_parent"
    android:text="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
        android:layout_height="wrap_content"/>

<RadioGroup android:id="@+id/multiple_choice_one_answer_group"
    android:background="@color/white"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

   <RadioButton
      android:background="@color/primary_gray"
      android:textColor="@color/black"
      android:textSize="10sp"
      android:text="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" />
</RadioGroup>

</LinearLayout>

Screenshot:

A:

The problem is setting the background. If you remove the background from the RadioButton and keep it on the RadioGroup, it has the effect you're looking for. In general, setting the background of a Button to everything removes the button look; try it on a regular Button and you'll see. This is because the background for a Button is already set to something, and you're replacing it with a flat color.
Try this instead:
<RadioGroup android:id="@+id/multiple_choice_one_answer_group"
    android:background="@color/primary_gray"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    <RadioButton
        android:textColor="@color/black"
        android:textSize="10sp"
        android:text="XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" />
</RadioGroup>


Q:

How to re-use multiple .xib as a template to another .xib?

I want to re-use some .xib files as templates to the major views of my iOS app.
Can someone tell me if it's possible, in iOS, to achieve a "template-like" system such as: Header, Logo, Footer, and load them as separate .xib views to fill some placeholders inside another .xib?
And how can I do that?
Like this:

In the same app, I have a Header.xib, Footer.xib, and I want to include them in my MainMenu.xib

A:

You can reuse one xib files for multiple views just by using it in the initWithNibNamecall.
Then even if you have minor differences you can do them programmatically. I would recommend that you define one common setupMyScreen method which takes as a parameter the screenType you have and in a switch statement takes care of all the little modifications.
This way it is quite easy to maintain.
ps you might want to work on your acceptance level - otherwise one might not realy be inclined to provide answers to your questions...


Q:

Stress-energy-momentum tensor

In Wald's General Relativity, he writes on pg 61

For an observer with 4-velocity $v^a$, the component $T_{ab}v^a v^b$ is interpreted as the energy density, i.e. the mass-energy per unit volume, as measured by the observer.

However, if we use this with the stress tensor for dust $$T_{ab}=\rho_0 u_a u_b,$$
we get
$$T_{ab}v^a v^b= \rho_0 u_a u_b v^a v^b = (\rho_0 u_a v^a) (\rho_0 u_b v^b)/\rho_0 = U^2/ \rho_0$$
where I assumed $U=- \rho_0 u_b v^b$ is the energy density (since $E= - m_0 u_a v^a $).
What am I missing here?

A:

I henceforth assume $c=1$. Consider a 3-volume $\Delta \Sigma_0$ at rest with the dust. For the rest observer (this is its definition) $u^\mu$ has only (unit) temporal component.
The energy (i.e the mass) associated with that portion of system is  $\Delta \Sigma_0 \rho_0$.  The 4-momentum of that portion is therefore $\Delta p^\mu := \Delta \Sigma_0 \rho_0 u^\mu$.
Now consider another observer with four velocity $v^\mu$. The energy of that portion of system is the temporal component of $\Delta p^\mu$ computed in his/her reference frame. In other words it is:
$$\Delta p^\mu v_\mu = \rho_0 \Delta \Sigma_0 u^\mu v_\mu$$
However we are interested in the density of energy computed in that reference frame. It is defined as:
$$\frac{\Delta p^\mu v_\mu}{\Delta \Sigma} =  \rho_0\frac{\Delta \Sigma_0}{\Delta \Sigma} u^\mu v_\mu\:.$$
$\Delta \Sigma$ is the volume, as measured in the considered reference frame, of the portion of dust defined by $\Delta \Sigma_0$ at rest with the dust.
As is well known if a solid body has a volume $\Delta \Sigma_0$ in its rest frame, it has volume $$\Delta \Sigma = \Delta \Sigma_0\sqrt{1-v^2} $$
in a reference frame where it is seen to have a speed $v$. The above relation can be re-written
$$\Delta \Sigma_0 = \Delta \Sigma u^\nu v_\nu $$
where $u^\nu$ is the $4$-velocity of the body and now  $v^\nu$ the $4$-velocity of the other reference frame. Coming back to our dust system with field of $4$-velocity $u^\nu$, we can conclude that the energy density for a generic observer with $4$-velocity $v^\nu$ is, as correctly stated in Wald's book:
$$\frac{\Delta p^\mu v_\mu}{\Delta \Sigma} =  \rho_0 \frac{\Delta \Sigma_0}{\Delta \Sigma} u^\mu v_\mu = \rho_0 u^\nu v_\nu u^\mu v_\mu = T^{\mu\nu} v_\mu v_\nu\:.$$


Q:

Error in Sqlite 3 Python

This is my code:
import sqlite3
CreateDB = sqlite3.connect('Login.db')
querycurs = CreateDB.cursor()

def createTable():
    querycurs.execute('''CREATE TABLE Database (id INTEGER PRIMARY KEY, user TEXT, passw TEXT)''')
    print "Done"

def NewElement(new_user,new_pass):
    querycurs.execute('''INSERT into Database (user,passw) values (?,?)''',(new_user,new_pass))

def SelectElement(new_user):
    Pass = querycurs.execute('''SELECT passw FROM Database WHERE user = (?) ''',[new_user])
    print Pass

createTable()
NewElement("Abhishek","Mitra")

SelectElement("Abhishek")

The Pass value prints as;
<sqlite3.Cursor object at 0x0000000002A9FE30>

I followed the exact script given in my tutorial.

A:

Do this:
print Pass.fetchone()[0]

In addition, I recommend to follow the naming conventions of PEP 8. Name the result result, not Pass. Don't start function names with capital letters, use newElement, not NewElement.
Edit: See PEP 249 for the methods of a cursor.


Q:

What sound symbolism related to masturbation exist ?

Ideophones are words that stand for instance for physical sensation,psychological states or even abstract ideas.
For instance:

niko niko    smile
patan   the sensation of slamming a door
honobono   the state of peacefullness
kacha    sensation of sth. opening

Are there any sound symbolisms that can be used for sensations, events, psychological states related to masturbation ?
for instance:

the onset of  ejaculation
the pulling and pushing of the foreskin
imagining of some absent person while performing
the feeling of frustration  not being able to perform in a satisfying manner
the state of alertness one could be caught
pushing of sth. too big into the vagina

A:

シコシコ is the usual sound of masturbation.


Q:

How to plot a 2D region when there are 3 free parameters?

How could I obtain the region of payments, with the parameters a, b, c, d between 0 and 1 and the sum of all equal to 1?
After the comment/recommendation of belisarius, I edited the original question, and ask you a question in the last line of code.
P = {{a, b}, {c, d}}

A = {{2, -1}, {0, 1}}
B = {{-1, 1}, {2, -1}}

A[[1]].P[[1]] + A[[2]].P[[2]]

f1[a_, b_, c_, d_] = A[[1]].P[[1]] + A[[2]].P[[2]]
f2[a_, b_, c_, d_] = B[[1]].P[[1]] + B[[2]].P[[2]]

ParametricPlot[{f1[a, b, c, d], f2[a, b, c, d]}, {  a, 0, 1}, {b, 0,
  1}, {c, 0, 1}, {d, 0, 1} ]

In the last line, how can I code to consider only a, b, c, d in $[0,1]$ with $a+b+c+d=1$?
It´s similar to obatining all the convex combinations of the points $(a(i,j),b(i,j))$

A:

Being this the first answer at the site using the Region context, I think it deserves an entry on its own:
   AppendTo[$ContextPath, "Region`"]
   z = 0;
   RegionPlot[
         RegionProperty[
                  TransformedRegion[
                        ParametricRegion[{{p1, p2, p4},
                                          0 < p1 < 1 && 0 < p2 < 1 - p1 && 0 < p4 < 1 - p1 - p2}],
                         {2 #1 - #2 + #3, 2 - 3 #1 - #2 - 3 #3} &],
                   {x, y, z}, ImplicitDescription],
         {x, -3, 3}, {y, -3, 3}]

A:

To start with, I will work in 4 dimensions to accommodate a,b,c,d.
P = {a, b, c, d};
M = {{2, -1, 0, 1}, {-1, 1, 2, -1}};

The points of your 2D set are the linear transforms, of the form
M.P  (* {2 a - b + d, -a + b + 2 c - d} *)

where P lies in some 4D set which is defined by $a+b+c+d=1$ and all positive, that is some polytope in 4D. Since you get your 2D points by a linear transform on the 4D points (M.P), and since the linear transform of a polytope is the convex hull of the transform of the extreme points of the polytope, your set will be the convex hull of the points M.P for all P being an extreme point of the 4D polytope.
Not, this 4D polytope is a simple one, you can get its extreme points by all combinations {a,b,c,d} of 0's and 1's that have a sum <= 1. You can generate all the combinations and then Select the right ones :
Flatten[Table[{a, b, c, d},
  {a, 0, 1}, {b, 0, 1}, {c, 0, 1}, {d, 0, 1}], 3]
extremePoints4D = Select[%, Total[#] <= 1 &]

(* {{0, 0, 0, 0}, {0, 0, 0, 1}, {0, 0, 1, 0}, {0, 1, 0, 0}, {1, 0, 0, 0}} *)

(yes, you could have guessed that just fine!)
Now, transform these to their 2D transforms :
Points2D = M.# & /@ extremePoints4D

(* {{0, 0}, {1, -1}, {0, 2}, {-1, 1}, {2, -1}} *)

(not all of these will end up extreme points of the 2D region but that's OK, we will take the convex hull and interior points do not matter)
Now, plot the convex hull :
<< ComputationalGeometry`
Graphics[Polygon[Points2D[[ConvexHull[Points2D]]]], Frame -> True]

Note: This approach needs to generate all extreme points of a polytope; in higher dimensions (4D -> nD) and with constraints not so simple as $a+b+c+d=1$, getting those extreme points gets trickier.
About the bounding box
@Silvia got me thinking about the bounding box of the 2D region. With the above method it is quite obvious (min and max x and y over extreme points) but I thought I would suggest another way to do this that has the advantage of working in higher dimensions.
The idea is to get the min and max x and y over all possible (x,y). Linear programming will do just that :
(*
Min x (or -x, y, -y)
subject to linear constraints
a + b + c + d = 1
2a - b - d -x = 0
-a + b + 2c - d - y = 0
0 <= a, b, c, d <= 1
-infinity < x, y < infinity

with a 6D vector {a,b,c,d,x,y}.
*)

obj = {{0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, -1, 0}, {0, 0, 0, 0, 0, 1}, {0, 0, 0, 0, 0, -1}};
(* obj will be used to min/max y/y *)
M = {{1, 1, 1, 1, 0, 0}, {2, -1, 0, 1, -1, 0}, {-1, 1, 2, -1, 0, -1}};
(* M.{a,b,c,d,x,y}=0 generates all 3 constraints *)

bounds = {{0, 1}, {0, 1}, {0, 1}, {0, 1}, {-Infinity, Infinity}, {-Infinity, Infinity}}

(* Now get the 4 solutions to min/max x/y: *)
sol = LinearProgramming[#, M, {{1, 0}, {0, 0}, {0, 0}}, bounds] & /@ obj
(* and keep the {x,y}'s
sol[[1 ;; 4, 5 ;; 6]]

(* all downhill from here *)

xmin = Min[points[[1 ;; 4, 1]]]
xmax = Max[points[[1 ;; 4, 1]]]
ymin = Min[points[[1 ;; 4, 2]]]
ymax = Max[points[[1 ;; 4, 2]]]
ListPlot[points, AxesOrigin -> {xmin - 1, ymin - 1},
 Epilog -> {Orange, Line[{{xmin, ymin}, {xmax, ymin}, {xmax, ymax}, {xmin, ymax}, {xmin, ymin}}]}]

A:

You have 3 free parameters, since the imposed condition over their sum takes one away.
So, let's plot in 3D the region for those three free parms:
RegionPlot3D[(0 < p1 < 1 && 0 < p2 < 1 && 0 < p4 < 1 &&  p1 + p2 + p4 < 1),
             {p1, 0, 1}, {p2, 0, 1}, {p4, 0, 1}, PlotPoints -> 30]

Which is equivalent to:
Graphics3D[gc = GraphicsComplex[{{0, 0, 0}, {1, 0, 0}, {0, 1, 0}, {0, 0, 1}},
           Polygon@{{1, 2, 3}, {2, 3, 4}, {1, 2, 4}, {1, 3, 4}}],
           Axes -> True]

Now your functions f1 and f2 can bee written as:
f[p_, x_] := Total[p x, 2]
p = {{p1, p2}, {p3, p4}};
a = {{2, -1}, {0, 1}};
b = {{-1, 1}, {2, -1}};
{f[p, a], f[p, b]}
(*
  {2 p1 - p2 + p4, -p1 + p2 + 2 p3 - p4}
*)

Which is your target transform.
Now we find a transformation to map any {p1, p2, p3, p4} (minus one parm set by the sum restriction) into your target:
r = ToRules@
    Reduce[ForAll[{p1, p2, p4},
                  TransformationFunction[{{a1, a2, a3, a4}, {b1, b2, b3, b4},
                                          {c1, c2, c3, c4}, {d1, d2, d3, d4}}][{p1, p2, p4}] ==
                  {f[p, a], f[p, b], 0} /. p3 -> 1 - p1 - p2 - p4],
          {a1, a2, a3, a4, b1, b2, b3, b4, c1, c2, c3, c4, d1, d2, d3, d4}];

t = TransformationFunction[{{a1, a2, a3, a4}, {b1, b2, b3, b4},
                            {c1, c2, c3, c4}, {d1, d2, d3, d4}}] /. r /. a1 -> 1

And now we apply that transformation to our graphics complex:
Graphics3D[{FaceForm[Black], EdgeForm[None],
           GeometricTransformation[gc, t]}, Axes -> True]

And we can show it in 2D as:
Graphics[Normal@ GeometricTransformation[gc, t] /. {x_, y_, 0} :> {x, y} /.
         (VertexNormals -> x_) :> Sequence[], Frame -> True]


Q:

pre-DevOps deployment metrics challenge

TL;DR, how do you prove devops, specifically deployment automation, improves change failure rates?
We're all trying to capture metrics on 'deployment failures' using current (mostly manual) means. Unfortunately, a 'failure' rarely happens, right? Because when something goes wrong, the team comes together (typically with heroics) to fix the issue (typically permissions, missed configs, you know the drill). So... when we ask how the deployment went, the answer is "it worked."
But, intuitively we all know that's not good. The 2017 state of devops report says there's about a 31-45% "change failure rate." While that intuitively sounds about right, are they tracked as incidents? Nah. Because they get fixed pretty quickly, usually during validation. It's much more rare to actually roll back a deployment.
So, it takes discipline to report failure rates accurately. We're disincentivized to report like that because we want things to work and we do what it takes to make it happen.
So, how do you prove devops, specifically deployment automation, improves change failure rates?
(PS tried to tag this with "#devops-capability-model")

A:

A technique we've used in the past in similar situations is to get "management commitment" that imposes these rules to every team member:

Access to perform updates to the target deployment areas (i.e. production) is limited to selected automated systems, which have appropriate audit trails (= logging) of any kind of updates to the areas they manage.
Manual updates to the target deployment areas, for whatever reason, are no longer allowed by the typical team members (user ids) that used to be able (authorized) to perform these updates. Instead NEW (additional) user IDs will be created which will have all required permissions to (still) perform such manual updates, whenever needed. But to actually be able to use those new user IDs (= perform a logon with them), the team member who wants to perform a logon with such new user ID will have to perform "some" extra step to get access to the password for such new user Id. Ideally this extra step is automated also (use your own imagination how it should look like), but if anything else fails: just contact (= eMail, call, etc) the gate-keeper of the required password, including  "which issue they have to get fixed" (similar to your question).
Getting such gate-keeper in place is not an easy job. And the most resistance will come from ... the team members (for all sorts of reasons). Therefor a variation of those new user IDs (as in the previous step) is that each team member gets an extra user ID (with the password they decide themselves), but with an extra string attached to it: they are only allowed to perform a logon with that (extra) user ID if they actualy have a good reason to do so. And each time they perform such logon, they are required to file some type of report about "which issue they fixed" (similar to your question).

With these procedures in place, all that's left to do is to periodically review each of those reports / reasons why it was required to use such special user ID, and ask the question "Is there anything that can be done to further automate this, to further reduce the need for such special login?".
Update:
Quote from your extra comment below this answer:

I think adding artificial barriers to fixing a deployment issue is counter-productive.

True it adds an extra barrier, but I'm not conviced it is "artificial". Because this is, to my knowledge, the only way to become aware of things those team members otherwise won't ever tell you, for reasons such as:

job security.
bad things/practises they prefer to keep hidden.
power they do not want to loose.

A:

The 2017 state of devops report says there's about a 31-45% "change failure rate." While that intuitively sounds about right, are they tracked as incidents? Nah. Because they get fixed pretty quickly, usually during validation.

An issue that gets fixed quickly is still an issue.  If you're not reporting these as such, that's a problem.

So, it takes discipline to report failure rates accurately. We're disincentivized to report like that because we want things to work and we do what it takes to make it happen.

If your goal is actually to have things work, then you need to be honest about failures so you can prevent them in the future.  It sounds like the team here is lying (perhaps to themselves, certainly to management) about failures because their goal is to have things appear to be working.
These are different things.  For instance, take the old joke that QA produces bugs - "my code was fine until QA got ahold of it, and then they made all these bugs!".  The bugs were there all along, but the developer was ignorant of them.  An operations team's goal should be actual reliability, and they need to be incentivized as such by their management.  That means that if they put more monitoring in place that leads to discovering new issues, they should be rewarded, not penalized for the subsequent drop in reliability metrics.

TL;DR, how do you prove devops, specifically deployment automation, improves change failure rates?

If you're trying to motivate change in your organization, then you shouldn't be trying to prove anything, but provide evidence of what other organizations say about their own transitions.  If you're trying to measure the processes that you already have in place and justify their continued existence, then you should be tracking the standard reliability metrics, like mean time to repair (MTTR).
But devops principles are not merely about increasing reliability.  Even site reliability engineering is not merely about increasing reliability.  Rather, you want to get to an appropriate level of reliability - something that benefits the business but doesn't hinder development.  And that brings up the real motivator in devops, which is to empower change.  You want to allow the business to respond quicker to market stimuli, which happens by decreasing developer friction, increasing the rate of deploys, automating manual processes, etc. while staying within an acceptable bound of reliability.  This means you need to measure reliability, but you also need to measure velocity, because your goal is to increase the latter while keeping the former relatively static.


Q:

How to manipulate a particular IP address that is taken from route table in Bash Script

I'm trying to write a network scanner in Bash Script. where I'm taking an IP from the route table (IP of my router), but now I want to delete the last digit of that IP and put a letter so that I can able to put that IP address in a loop to generate a more sequential IP address.
this is the code I'm talking about:
first_ip=$(route -n | awk 'NR>2{print $2}' | head -1)

Now, what to do to delete the last character of that IP?

A:

You can remove the last part of the IP-addresses by using grep:
first_ip=$(route -n | awk 'NR >2 { print $2 }' | head -1 | grep -oE "\b([0-9]{1,3}\.){3}")
This gives you the first three numbers of the IP-address listed by route-n.
You can then add any numbers XXX that you wish like so:
first_ip=$(route -n | awk 'NR >2 { print $2 }' | head -1 | grep -oE "\b([0-9]{1,3}\.){3}")
first_ip = first_ip"XXX"

So if you have the IP-address 192.155.177.123 you get 192.155.177.
you can then add any number that you want to add...
I hope this helps!


Q:

command line batch file - define several customization

I am using batch file (*.bat) to run several programs.
Each line, (such as myexe.exe) may take long time, so I want

Add a spinner when the line executed (first character '/', second: '-', third: '\', forth: sixth: '|', seventh: '/', and so on). How can I do that?
ensure that the line execute, and if not - It won't hung the process, but the following line will continue (in some cases).
ensure that the line execute, and if not - It won't hung the process, but the following line will not continue (in some cases, I want to break the process).
Can I define time out for the line execute?

How can I do the above?
Need code sample, please.
Thanks :)

A:

This is what I've created:
@echo off

setlocal

set "executable=notepad.exe"
set "work_dir=."

for /f "skip=5 tokens=* delims=" %%# in ('wmic process call create "%executable%"^,"%work_dir%"') do (
    for /f "tokens=1,2 delims=;= " %%a in ("%%#") do (
       rem --In the part "%%a" equ "    ProcessID" the blank before the ProcessID is a single tab
       rem --Some (browser/online)editors could alert it to spaces!
       if not defined PID if "%%a" equ "    ProcessId" set "PID=%%b"
    )
)
if not defined PID echo Failed to start the process && exit /b 3

set s_time=%time%
set "_0=/"
set "_1=-"
set "_2=\"
set "_3=|"

set counter=0
set "line=."

:loop
echo executing %executable% [%s_time%]
set /a counter=counter+1
set /a mod=counter%%4
if %mod% equ 0 set line=%line%.

qprocess %PID% >nul 2>&1 && (

    setlocal ENABLEDELAYEDEXPANSION
    echo %line%!_%mod%!
    pathping 127.0.0.1 -n -q 1 -p 300 >nul
    cls
    endlocal
    goto :loop

) || (
    echo execution of %executable% finished [%time%]
)

endlocal

At the moment clearing the screen is mandatory , but may be will do the job for you? Also WMIC is not available for WinXP home edition.


Q:

Adding an accordion inside google maps infoBubble (from google maps utility library)

I am trying to add a jquery accordion (http://jqueryui.com/demos/accordion/) inside a google maps infoBubble
I first add a markup similar to

First header

First content

Second header

Second content

to the infoBubble. But i'm not able to attach any events to the above markup.
When I try to invoke $( "#accordion" ).accordion(); inside the domready event similar to
google.maps.event.addListener(infoBubble, 'domready', function() {
    $("#accordion").accordion();
});

It does not seem to attach the events.
I am not sure what is wrong with my code. Can someone please help me with this.

A:

Your code isn't working because it is running before the accordion in the infobubble exists.  You need to place that code so that it is called after the content of the infowindow has been set.  Not only does it need to be run after it's been opened, but it also needs to be run a few hundred milliseconds after it's been opened.  (You'd have to do testing in all browsers to find the right amount - I arbitrarily chose 500ms and it worked.)  After looking through the Infobubble code, I was disappointed to see that unless I missed something, there is no event that fires when the open is complete.
However, I was able to get it working by placing this code on line 122 (after the infobubble is opened) of the example that you linked to and also in the marker's click callback below that:
    setTimeout(function() {
        $("#accordion").accordion();
    }, 500);

This is not an optimal solution, but at least it demonstrates the problem and hopefully leads to the right solution.


Q:

How to decrypt data for an MVC View?

I am using ASP.NET MVC 4 Runtime, and writing encrypted data to my database using a function.
public string Encrypt(string encryptMe)
{
    return Helpers.Encryptor.Encrypt(encryptMe);
}

On return the data is displayed like so:
@foreach (var item in Model) {

        @Html.DisplayFor(modelItem => item.Phone)

        @Html.DisplayFor(modelItem => item.Name)

I want to decrypt the data before displaying it here using the following function:
public static string Decrypt(string decryptMe)
{
    return Helpers.Encryptor.Decrypt(decryptMe); ;
}

How can I decrypt my data?

A:

Add a Property in the model called for example "DecryptedPhone".
This will only have a Get and will call the decrypting function:
public string DecryptedPhone
{
      get
      {
      return Decrypt(Phone);
      }
}

private string Phone;

The phone will be private so that it cannot be accessed.


Q:

Bond character and bond angles

Somewhere along the line of researching why the $\ce{Cl-C-H}$ bond angle in methyl chloride is less than what is predicted ($\pu{109.5^\circ}$), I ran into a book which said that the electron withdrawing effects of the chlorine atom gave the $\ce{C-Cl}$ bond more "p-character".
What does this mean? Is he simply using this term to describe the elongated nature of the bond - i.e. s-orbitals are spherical and p-orbitals not spherical but rather elongated (at least as depicted by cartoon drawings in textbooks)?
Is the author saying that the electron-withdrawing effects of chlorine cause the electrons to spend more time further away from the nucleus; hence the "p-character"? I understand that in a spherical shell, electrons are basically equidistant from the nucleus. But in an elongated, "p-character" shell, electrons can go further away from the nucleus.

A:

S orbitals are lower in energy than P orbitals.  Electrons prefer to be in as low an energy orbital as possible.  Therefor, when we mix S and P orbitals to make hybrid orbitals, the more S character the orbital has the lower the energy of electrons occupying that orbital. Let me use chloroform, $\ce{CHCl3}$, as an example to make my point (I have data for it and the $\ce{C-Cl}$ bonds are analogous to those in methyl chloride).  The chlorine atom is electronegative, so electrons in the $\ce{C-Cl}$ bond will spend more of their time closer to chlorine - away from the carbon, then they would in say a $\ce{C-H}$ bond.  So if the electron density in the hybrid orbital contributed by carbon to the $\ce{C-Cl}$ bond is going to be reduced, why put as much S character in it?  Instead save that S character for other hybrid orbitals emanating from the carbon that have higher electron density in them.  It turns out in the case of chloroform, knowing the various bond angles and the $\ce{C_{3V}}$ symmetry of the molecule, that the carbon portion of the $\ce{C-Cl}$ has a hybridization of about $\ce{sp^4}$ (more P character and less S character just as we predicted since it has a lower electron density) and the $\ce{C-H}$ bonds are approximately $\ce{sp^{2.75}}$ (using that S character we saved from the $\ce{C-Cl}$ bond to stabilize the electrons in these 3 orbitals, just as we predicted).  The same effects play out in methyl chloride, just not as dramatically (e.g. the hybridization index of the $\ce{C-Cl}$ bond will be greater than 3 but less than 4).


Q:

Python: Alternative to binascii b-function for predefined string

I want to use the hashlib function which requires byte-representation of strings. In this example from the Python documentation they solve this by putting a 'b' in front of the string:
>>> import hashlib, binascii
>>> dk = hashlib.pbkdf2_hmac('sha256', b'password', b'salt', 100000)

This only seems to work when the string is defined in the function call. I would like to use predefined strings but I cannot seem to use the b-function. I would like to do something like:
>>> import hashlib, binascii
>>> mystr = 'password'
>>> dk = hashlib.pbkdf2_hmac('sha256', b(mystr), b'salt', 100000)

Or
>>> dk = hashlib.pbkdf2_hmac('sha256', b mystr, b'salt', 100000)

Obviously, non of these worked. I researched and found some more complex solutions, but I wonder if there is any solution for predefined strings that is as smooth as for strings defined directly in the function.
Thanks!

A:

You can use bytes(my_string) or bytes(my_string, encoding) to convert a string to bytes. No need for the binascii module.
Documentation can be found here: https://docs.python.org/3/library/functions.html#bytes


Q:

Algorithmic Analysis - Are there any algorithms having their best case complexity of the order of n^99?

Are there any algorithms having their best case complexity of the order of n^99? Is this NP complete? If not, how do we analyse such algorithms?

A:

One such problem is a k-clique problem.

Given a graph of size n, is there any clique with k vertices? (k is considered a constant).

An obvious brute-force algorithm checks all k-subsets of graph vertices and tests them for being a clique. Since there are (nk) k-subsets, and each can be checked in (k2) time, the total complexity becomes (nkk2) or just (nk) (because k is a constant).
The asymptotically best known algorithm for this problem (totally impractical though) runs in (n0.792k).
By varying k, one can deal in any desired complexity.


Q:

java add character into a string

i get a big string from a web page and its like this
"07:10Ο ΑΣΔΦΑΣΔΦ07:30ΑΣΔΦΑΣΔΦ10:15ΝΑΣΔΦΑΣΔΦ"

and i want every time i find time like this "17:50" or "07:30" to get a new line before the time! so i will have
07:10   ΑΣΔΦΑΣΔΦ
07:30   ΑΣΔΦΑΣΔΦ
10:15   ΝΑΣΔΦΑΣΔΦ

etc...
but here is my problem i tried to copmare the letters with this
StringBuilder builder = new StringBuilder(text);
for (int i = 0; i < text.length(); i++) {
     if(Character.isDigit(text.charAt(i))){
            builder.insert(i, "\n");
     }
}

but inside my text i have Greek letters so the isDigit returns 1 when it gets some Greek letters. Anyone has any idea how to solve this?

A:

To provide some initial help, the builder.insert() line isn't doing what you probably want:
StringBuilder builder = new StringBuilder(text);
for (int i = 0; i < text.length(); i++) {
     if(Character.isDigit(text.charAt(i))){
            builder.insert(i, "\n"); // questionable
     }
}

Do you really want `\n1\n2:\n4\n5" for the string "12:45"?
You might just want to match "\\d\\d[:.]\\d\\d" and prepend "\n" postpend " " on each match, but I can't be certain I understand your problem.
Specifically, I just tried:
String str = "07:10Ο Σκούμπι Ντου & ο κολλητός του07:30Πρωϊνή μελέτη10:15Νηστικοί πράκτορες11:15Σαρίτα, είσαι η ζωή μου12:50Οι ειδήσεις του Star13:45Made in Star15:45Μίλα17:45Ειδήσεις17:50Φώτης - Μαρία live19:45Οι ειδήσεις του Star21:00Ο Χαρί Πότερ και ο ημίαιμος πρίγκιψ00:15Σχολή για απατεώνες01:15Supernatural02:15Gypsy woman02:30Τα πλοκάμια του τρόμου03:45Ραπ πάρτι04:30The Dead zone";
return str.replaceAll("(\\d\\d[:.]\\d\\d)", "\n$1 ");

Does this work the way you want? My terminal doesn't seem to support these characters very well, so I may have a locale encoding issue.


Q:

In Memoriam: Leonard Nimoy

It is my sad duty to inform the community that Leonard Nimoy has beamed up for the last time. He will truly "Live long and prosper" in all our memories.
RIP

A:

We are assembled here today to pay final respects to our honored dead. And yet it should be noted, in the midst of our sorrow, this death takes place in the shadow of new life, the sunrise of a new world; a world that our beloved comrade gave his life to protect and nourish. He did not feel this sacrifice a vain or empty one, and we will not debate his profound wisdom at these proceedings. Of my friend, I can only say this: Of all the souls I have encountered in my travels, his was the most.... human.

A:

A:

RIP Spock.


Q:

Complexity analysis of logarithms

I have two functions, f(n)=log(base 2)n and g(n)=log(base 10)n. I am trying to decide whether f(n) is O(g(n)), or Ω(g(n)) or Θ(g(n)). I thinks i should take the limit f(n)/g(n) as n goes to infinity, and i think that limit is constant so f(n) must be Θ(g(n)). Am i right? Thanks in advance

A:

You can rely on a useful and often-forgotten result, that $(\log_a b)(\log_b c) = \log_a c$, so in your problem we'll have
$$
(\log_2 10)g(n) = (\log_2 10)(\log_{10} n) = \log_2 n = f(n)
$$
so $f(n)$ is just a constant multiple ($\log_2 10\approx 3.32$) of $g(n)$ and hence $f(n)=\Theta(g(n))$.


Q:

Why does this chicken recipe result in a glutinous mess?

Countless times I've tried to prepared a recipe that calls for dredging chicken tenders in flour, dipping them in beaten egg (or a mixture of egg and water), and then coating them with a bread crumb mixture.
It just doesn't work for me. In the process of dipping the chicken in egg, much of the flour gets wiped off and ends up in the egg; the flour that remains sticks to the chicken in gooey clumps, and those clumps tend to resist coating with bread crumbs. After the third or fourth chicken tender has been treated, the egg has become a mess because of all the flour that's been washed off.
I've finally given up on that method and I simply do the egg and bread crumb part of the recipe, which seems to work just fine.
So why would I put flour on first - what's the advantage? And what am I doing wrong that makes it work so badly?

A:

The reason for the flour being part of the breading process is to create a barrier between the meat and the breading, which will during the frying step allow for the formation of small steam pockets and a crisper crust. In a Wiener schnitzel this leads to the characteristic wrinkled surface. On the other hand, it’s the flour-egg mix that acts as „glue“ for the breadcrumbs or whatever you are using.
The amount of flour that is needed to achieve this is minimal. If you end up with flour in the egg, then I suspect you aren’t shaking off the excess flour.
The proper procedure starts with dry meat. This ensures that only little flour actually sticks to the meat when you then shake your meat to make sure all extra flour falls off. In this way you prevent the formation of what you describe as “glutinous mess”.
Then you proceed with the egg (again, let the extra drip off) and breadcrumbs.
Shallow-fry and serve immediately to ensure the crust is still crisp.


Q:

Using REGEXP_LIKE in old style join

I have PL/SQL query with old style joins (with using (+) ). And now I need to add left joined table with REGEXP_LIKE clause. How can I make this?
In ANSI-style the query look like this:
select
    *
from
    deals d
    left join
        auctions a on a.session_code = d.session_code
    left join
        auction_history ah on ah.auction_code = a.auction_code and
                                REGEXP_LIKE(ah.auction_code, '^[A-Z]+')
where
    trunc(d.operday) = trunc(sysdate)

And in old style I want to get something like this:
select
    *
from
    deals d,
    auctions a,
    auction_history ah,
where
    trunc(d.operday) = trunc(sysdate) and
    d.session_code = a.session_code (+) and
    (a.auction_code = ah.auction_code (+) and
        REGEXP_LIKE(ah.auction_code, '^[A-Z]+'))

But it doesn't return deals which session_code is null.
Thanks in advance!

A:

REGEXP_LIKE is treated as a regular function regarding legacy joins. Here's an example:
SQL> WITH main_table AS
  2  (SELECT 1 ID FROM dual UNION ALL
  3   SELECT 2 FROM dual),
  4  lookup_table AS
  5  (SELECT 1 ID, 'txt' txt FROM dual UNION ALL
  6   SELECT 2 ID, '999' txt FROM dual)
  7  SELECT m.id, l.txt
  8    FROM main_table m, lookup_table l
  9   WHERE m.id = l.id(+)
 10     AND REGEXP_LIKE(l.txt(+), '^[A-Z]+');

        ID TXT
---------- ---
         1 txt
         2

Still, I would advise against using old-style joins in recent editions.


Q:

How to configure the webpacker to work with stylus so I can use Vuetify?

I have webpacker working for basic a vue.js/rails app but I would like to configure it so stylus files compile to css so I can use Vuetify. Does anyone know how to do this?
My existing working stand alone vuetify/vue.js app has the following webpack config:
module: {
loaders: [
  {
    test: /\.vue$/,
    loader: 'vue'
  },
  {
      test: /\.s[a|c]ss$/,
      loader: 'style!css!sass'
  }
]
},
vue: {
  loaders: {
    scss: 'style!css!sass'
  }
}

The syntax for webpacker seems to be a bit different for webpacker. My rails app has /config/webpack/environment.js
const { environment } = require('@rails/webpacker')

environment.loaders.set('styl', {
test: /\.styl$/,
use: 'stylus-loader'
}),
environment.loaders.set('styl', {
test: /\.s[a|c]ss$/,
use: 'style!css!sass'
})
module.exports = environment

But I am getting this error:
Undefined variable: "$chip-label-color".in /rails_project_path/node_modules/vuetify/dist/vuetify.min.css (line 6, column 134917)
Does anyone have an example of how to configure Vuetify with Rails Webapcker?

A:

With webpacker 3 you can add loaders as explained in the loaders section of the docs.
Here is my configuration for stylus-loader in my webpack/environment.js
environment.loaders.append('stylus', {
  test: /\.styl$/,
  use: ['style-loader', 'css-loader', 'stylus-loader']
})

Also additional information can be found here on vuetify's website: setting up stylus loader with webpack and here
Also, I don't think environment.loaders.set works anymore. Use append.


Q:

Find the $x$ and $y$ values that satisfy the constrained optimisation problem.

I have the following constrained optimisation problem. We have the following multivariable function:
$$f(x,y) = 4x^2 +4y^2 +3xy -2x +4$$
This function is minimised on the line:
$$0 = \vec n \ (\vec x -\vec p)= \begin{bmatrix}-1\\1\end{bmatrix} \left(\begin{bmatrix}x\\y\end{bmatrix}-\begin{bmatrix}-2\\3\end{bmatrix} \right)$$
I have to use the Lagrange Multipliers to solve this problem and get the $x$ and $y$ values. I'm not sure how to go about doing this problem because normally I work with $g(x,y)$ as a linear equation which equals a constant (i.e. $x+y=12$). My initial idea was to write down the Lagrange Multipliers, since $f$ is subject to the constraint $g(x,y) = 0$ and simplify the line equation into a polynomial function. The function is as follows:
$$L(x, y, \lambda)=f(x,y)+\lambda (g(x,y)-c)$$
The line equation in its equivalent polynomial form:
$$-x+y-5 \equiv y-x = 5$$
Thus $c = 5$ and we have:
$$L(x,y, \lambda) = (4x^2+4y^2 +3xy -2x +4) - \lambda(-x+y-5)$$
From here I can find the gradient of $L$, which would be:
$$\nabla L= \begin{bmatrix}8x+3y-2+ \lambda\\8y +3x-\lambda\\x-y+5\end{bmatrix}$$
I then setup an augmented matrix and reduced it to RREF to solve for $x$ and $y$. The augmented matrix $A$ is as follows:
$$\left[\begin{array}{rrr|r}
8 & 3 & 1 & 2\\
3 & 8 & -1 & 0\\
1 & -1 & 0 & -5
\end{array}\right] \to  ... \to \left[\begin{array}{rrr|r}
1 & 0 & 0 & -\frac{55}{22}\\
0 & 1 & 0 & -\frac{57}{22}\\
0 & 0 & 1 & -\frac{27}{2}
\end{array}\right]$$
Therefore, $x = -2.50$ and $y=-2.59$. Hopefully this is correct but again, I'm not a 100% sure because of the line constraint.
Edit: There is a computation error in reducing the augmented matrix (RREF). As stated in the comments and answers, the correct answers are $x=-2.41$ and $y=2.59$.

A:

The minimization problem
$$
\min_{x,y}f(x,y)=4 x^2 + 4 y^2 + 3 x y - 2 x + 4,\ \ \text{s. t.}\ \ g(x,y) = y-x-5=0
$$
can be solved either by substitution of $y = x+5$ into $f(x,y)$ giving the unconstrained.
$$
\min_x f(x,x+5)=4 x^2+3 (x+5) x-2 x+4 (x+5)^2+4
$$
or using the Lagrange multipliers paradigm for the stationary points determination of
$$
L(x,y) = f(x,y)+\lambda g(x,y)
$$
In this case the stationary points are the solutions for
$$
\nabla f +\lambda\nabla g = 0
$$
which means that the functions $f, g$ should be tangent at the solution $\{x^*, y^*\}$ or
$$
\nabla f(x^*, y^*) +\lambda\nabla g(x^*, y^*) = 0
$$
Follows a plot showing first $x\times f(x,x+5)$

and the tangency at $\{x^*, y^*\}$ in the case of the Lagrangian approach. In black the level curves for $f(x,y)$ in blue $g(x,y)=0$ and in red the solution point $\{-\frac{53}{22},\frac{57}{22}\}$. Note that in both plots, the minimum coordinate $x^* = -\frac{53}{22}$ is the same.


Q:

Updating All Subscribers List with query, extract and import

I have followed instructions from this link :
How to Query a Data Extension and Update the Subscriber list at the Child Business Unit Level?
Our current configuration allows existing users to update their email address.
This page is hosted on a e commerce engine - Hybris
Issue is that when this is updated , it is not updated in SFMC, hence all they do not receive future communication.
Issue is that the final step, import activity keeps failing (csv import).  Here is a screen shot of the error log:

I will appreciate any help in solving this.
EDIT
I ran the first iteration and it worked. However we I tried to combine all five steps into a automation, it failed.

What I do know is that those are the values for my subscriber key, which I have manually mapped. I have checked the file on the FTP and it contains these values.

A:

Since you wanting to update the All Subscribers list (not a data extension), the correct field name is Email Address (note: the space).  You will need to rename the header in your file to match or choose to map fields manually in your import configuration.  If subscriber key is enabled in your account, you will also need to supply a column named subscriber key along with the corresponding subscriber key values for each emailaddress.
In order to update the status, your file must contain a column named Status.  The status values will need to be either "active" or "unsubscribe".  That part is tricky, since the subscriber status in the Platform appears as "Active" or "Unsubscribed".
Refer to the following link for more information on configuring import activities.
https://help.marketingcloud.com/en/documentation/exacttarget/interactions/activities/import_activity/
https://help.marketingcloud.com/en/documentation/exacttarget/subscribers/subscribers1/imports/


Q:

Different colour for axes and grids in D3

I want different colour for the axes(x and y) and grids for the graph. I tried changing the CSS but couldn't make it.

I have attached the  graph code and css with this. The css code is below
.axis path,
.axis line {
    fill: none;
    /*stroke: #000;*/
    stroke: #B2B2B2;
    shape-rendering: crispEdges;
    opacity: 0.5;
}

.area_characteristics_temperature {
    fill: steelblue;
    opacity:0.5;
    border: 0px;
    margin:0px;
    overflow: hidden;
}
.area_characteristics_temperature_3yr {
    fill: #7da7ca;
    opacity:0.5;
    border: 0px;
    margin:0px;
    overflow: hidden;
}
.area_characteristics_temperature_10yr {
    fill: #676767;
    opacity:0.5;
    border: 0px;
    margin:0px;
    overflow: hidden;
}
.area_characteristics_temperature_prev {
    fill: #eec7ea;
    opacity:0.5;
    border: 0px;
    margin:0px;
    overflow: hidden;
}

.line {
    fill: transparent;
    stroke:red;
    stroke-width:3px;
}
.line1 {
    fill: transparent;
    stroke:green;
    stroke-width:3px;
}

.line_characteristics_current_temperature_max{
    fill: transparent;
    /*stroke:red;*/
    stroke:#CC3300;
    stroke-width:3px;
}

.line_characteristics_current_temperature_min{
    fill: transparent;
    /*stroke:yellow;*/
    stroke:#0099CC;
    stroke-width:3px;
}

.line_characteristics_forecast_temperature_max{
    fill: transparent;
    /*stroke:green;*/
    stroke:#CC3300;
    stroke-width:3px;
    stroke-height:3px;
    /*stroke-dasharray:2.5px,6px;*/
    stroke-dasharray:2.5px,5.5px,2.5px,5.5px;
    stroke-soft:5px;
    stroke-linecap:round;
    stroke-height:3px;
    stroke-width:3.4px;
}

.line_characteristics_forecast_temperature_min{
    fill: transparent;
    stroke:#0088C3;
    stroke-width:3px;
    stroke-height:3px;
    /*stroke-dasharray:3px,6px,3px,6px;*/
    stroke-dasharray:2.5px,5.5px,2.5px,5.5px;
    stroke-soft:5px;
    stroke-linecap:round;
    stroke-height:3px;
    stroke-width:3.4px;
    strokeDashoffset:10px,5px;
}
#wgtmsr option{
    width:150px;
}

/*<DEMO>*/
#nav {
    height:200px;
    width:100px;
    float:left;
    padding:5px;
    padding-bottom:50px;
}
#section {
    width:350px;
    float:left;
    padding:10px;
}

/* Main style*/
.widget_sidebar{
    min-width: 200px;
    max-width:25%;
    overflow:hidden;
    float:left
}
.widget_graphArea{
    min-width: 200px;
    max-width:75%;
    overflow:hidden;
}

graph code: I am using D3 for graph coding
var self = this;
        this.divID = divID;
        this.forecastEnabled = true;
        this.currentEnabled = true;
        this.averagesEnabled = true;
        this.currentData = [];
        this.areaClass = "area_characteristics_temperature";

        this.averagesData = []

        this.forecastdata = new Array();
        this.merged_data = new Array();
        this.svg = null;

        this._currentDataTrail = {temperature_max: 0, temperature_min: 0, date: 0}
        this.parseDate = d3.time.format("%Y-%m-%d").parse;

        w = $("#" + this.divID).width();
        h = $("#" + this.divID).height();

        this.boxing = {top: 20, right: 30, bottom: 30, left: 50},
        this.width = w - this.boxing.left - this.boxing.right,
                this.height = h - this.boxing.top - this.boxing.bottom;

        this.x = d3.time.scale()
                .range([0, this.width]);

        this.y = d3.scale.linear()
                .range([this.height, 0]);

        this.xAxis = d3.svg.axis()
                .scale(this.x)
//                .ticks(d3.time.day, 1)
//                .tickFormat(d3.time.format('%b %d'))
                .orient("bottom");

        this.yAxis = d3.svg.axis()
                .scale(this.y)
                .orient("left")
                .ticks(5, 0)
                .tickPadding(10);

        this.svg = null;

        this.line_characteristics = d3.svg.line()
                .x(function (d) {
                    return self.x(d.date);
                })
                .y(function (d) {
                    return self.y(d.temperature);
                });

        this.line_characteristics_temperature_min = d3.svg.line()
                .x(function (d) {
                    return self.x(d.date);
                })
                .y(function (d) {
                    return self.y(d.temperature_min);
                });

        this.line_characteristics_temperature_max = d3.svg.line()
                .x(function (d) {
                    return self.x(d.date);
                })
                .y(function (d) {
                    return self.y(d.temperature_max);
                });

        this.area_characteristics_temperature = d3.svg.area()
                .x(function (d) {
                    return self.x(d.date);
                })
                .y0(function (d) {
                    return self.y(d.temperature_max);
                })
                .y1(function (d) {
                    return self.y(d.temperature_min);
                });

        self.updateCurrentData = function (newData, append)
        {
            var _currentMaxDate = new Date(0);
            newData.forEach(function (d) {
                d.date = self.parseDate(d.date);
                d.temperature_max = d.temperatures.max;
                d.temperature_min = d.temperatures.min;

                if (d.date > _currentMaxDate) {
                    _currentMaxDate = d.date;
                    self._currentDataTrail.temperature_max = d.temperature_max;
                    self._currentDataTrail.temperature_min = d.temperature_min;
                    self._currentDataTrail.date = d.date;
                }
            });
            if (append) {
                self.currentData = self.currentData.concat(newData);
            } else {
                self.currentData = newData;
            }
            self.forecastData = new Array();
            self.updateMerged();
        };

        self.setAreaClass = function (css_class) {
            self.areaClass = css_class;
        }

        self.updateForecastData = function (newData)
        {
            self.forecastData = new Array();
            newData.forEach(function (d) {
                d.date = self.parseDate(d.date);
                d.temperature_max = d.forecast[0].temperatures.max;
                d.temperature_min = d.forecast[0].temperatures.min;
            });

            if (self._currentDataTrail && self._currentDataTrail.date) {
                self.forecastData.push(self._currentDataTrail)
            }
            self.forecastData = self.forecastData.concat(newData)
            self.updateMerged();
        };

        self.updateAveragesData = function (newData, append)
        {

            var _temp = new Date();
            var current = new Date(_temp.getFullYear(), 0, 1);

            newData.forEach(function (d) {
                if (d.minTemp) {
                    current.setDate(current.getDate() + 1);
                    d.temperature_max = d.maxTemp.average.toFixed(4);
                    d.temperature_min = d.minTemp.average.toFixed(4);
                    var date = current.getFullYear() + "-" + d.day;
                    d.date = self.parseDate(date);
                } else {
                    d.date = self.parseDate(d.date);
                    d.date.setFullYear(d.date.getFullYear() + 1)
                    d.temperature_max = d.temperatures.max;
                    d.temperature_min = d.temperatures.min;
                }
            });
            if (append) {
                self.averagesData = self.averagesData.concat(newData);
            } else {
                self.averagesData = newData;
            }
            self.updateMerged();
        };

        self.updateMerged = function ()
        {
            self.merged_data = new Array();

            if (self.currentData != undefined && self.currentData instanceof Array && self.currentData.length > 0 && self.forecastData != undefined && self.forecastData instanceof Array && self.forecastData.length > 0) {
                self.merged_data = self.merged_data.concat(self.currentData)
                self.merged_data = self.merged_data.concat(self.forecastData)
            } else if (self.currentData != undefined && self.currentData instanceof Array && self.currentData.length > 0) {
                self.merged_data = self.merged_data.concat(self.currentData);
            } else if (self.forecastData != undefined && self.forecastData instanceof Array && self.forecastData.length > 0) {
                self.merged_data = self.merged_data.concat(self.forecastData);
            }
        };

        self.redraw = function () {
            w = $("#" + self.divID).width();
            h = $("#" + self.divID).height();
            self.width = w - self.boxing.left - self.boxing.right,
                    self.height = h - self.boxing.top - self.boxing.bottom;
            self.x = d3.time.scale()
                    .range([0, self.width]);
            self.y = d3.scale.linear()
                    .range([self.height, 0]);
            self.xAxis = d3.svg.axis()
                    .scale(self.x)
                    .ticks(d3.time.day, 1)
                    .tickFormat(d3.time.format('%b %d'))
                    .orient("bottom");
            self.yAxis = d3.svg.axis()
                    .scale(self.y)
                    .orient("left")
                    .tickSize(-self.width)
                    .ticks(5, 0)
                    .tickPadding(10);

            if (self.svg !== null) {
                self.svg.remove();
            }
            $("#" + self.divID).html("");
            self.svg = d3.select("#" + self.divID).append("svg")
                    .attr("width", self.width + self.boxing.left + self.boxing.right)
                    .attr("height", self.height + self.boxing.top + self.boxing.bottom)
                    .append("g")
                    .attr("transform", "translate(" + self.boxing.left + "," + self.boxing.top + ")");

            var minDate = new Date(2999, 01, 01);
            self.merged_data.forEach(function (d) {
                if (d.date < minDate) {
                    minDate = d.date;
                }
            });

            var maxDate = new Date(0);
            self.merged_data.forEach(function (d) {
                if (d.date > maxDate) {
                    maxDate = d.date;
                }
            });

            var totalDateDiff = maxDate - minDate;
            totalDateDiff = totalDateDiff / (1000 * 60 * 60 * 24);

            if (w < 500 && !isNaN(totalDateDiff)) {
                if (totalDateDiff < 30) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.days, 7)
                            .tickFormat(d3.time.format('%b %d'))
                            .orient("bottom");
                } else if (totalDateDiff > 30 && totalDateDiff < 150) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.months)
                            .tickFormat(d3.time.format('%b %y'))
                            .orient("bottom");
                } else if (totalDateDiff > 150 && totalDateDiff < 365) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.years)
                            .tickFormat(d3.time.format('%b %y'))
                            .orient("bottom");
                } else if (totalDateDiff > 365) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.years)
                            .tickFormat(d3.time.format('%Y'))
                            .orient("bottom");
                }
            } else if (w > 500 && !isNaN(totalDateDiff)) {
                if (totalDateDiff < 15) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.days, 1)
                            .tickFormat(d3.time.format('%b %d'))
                            .orient("bottom");

                } else if (totalDateDiff > 15 && totalDateDiff <= 30) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.days, 4)
                            .tickFormat(d3.time.format('%b %d'))
                            .orient("bottom");

                } else if (totalDateDiff > 30 && totalDateDiff < 100) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.months, 1)
                            .tickFormat(d3.time.format('%b %y'))
                            .orient("bottom");
                } else if (totalDateDiff > 100 && totalDateDiff < 365) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.months)
                            .tickFormat(d3.time.format('%b %y'))
                            .orient("bottom");
                } else if (totalDateDiff > 365) {
                    self.xAxis = d3.svg.axis()
                            .scale(self.x)
                            .ticks(d3.time.years)
                            .tickFormat(d3.time.format('%b %Y'))
                            .orient("bottom");
                }
            } else if (isNaN(w) || isNaN(totalDateDiff)) {
                self.xAxis = d3.svg.axis()
                        .scale(self.x)
                        .ticks(d3.time.years)
                        .tickFormat(d3.time.format('%Y'))
                        .orient("bottom");
            }

            self.x.domain(d3.extent(self.merged_data, function (d) {
                return d.date;
            }));

            self.y.domain([d3.min(self.merged_data, function (d) {
                    return d.temperature_min - 10;
                }), d3.max(self.merged_data, function (d) {
                    return d.temperature_max + 10;
                })]);

            self.svg.append("g")
                    .attr("class", "x axis")
                    .attr("transform", "translate(0," + self.height + ")")
                    .call(self.xAxis.orient("bottom"));

            self.svg.append("text")
                    .attr("x", 0)
                    .attr("y", self.height)
                    .style("text-anchor", "middle")
                    .text("");

            self.svg.append("g")
                    .attr("class", "y axis")
                    .call(self.yAxis)
                    .append("text")
                    .attr("transform", "rotate(-90)")
                    .attr("x", -85)
                    .attr("y", 6)
                    .attr("dy", ".71em")
                    .style("text-align", "middle")
                    .text("Temperature(°C)");

            self.svg.append("path")
                    .datum(self.averagesData)
                    .attr("class", self.areaClass)
                    .attr("d", self.area_characteristics_temperature);

            if (self.currentEnabled === true && self.currentData instanceof Array && self.currentData.length > 0) {
                self.svg.append("path")
                        .datum(self.currentData)
                        .attr("class", "line_characteristics_current_temperature_max")
                        .attr("d", self.line_characteristics_temperature_max);

                self.svg.append("path")
                        .datum(self.currentData)
                        .attr("class", "line_characteristics_current_temperature_min")
                        .attr("d", self.line_characteristics_temperature_min);
            }

            if (self.forecastEnabled === true && self.forecastData instanceof Array && self.forecastData.length > 0) {
                self.svg.append("path")
                        .datum(self.forecastData)
                        .attr("class", "line_characteristics_forecast_temperature_max")
                        .attr("d", self.line_characteristics_temperature_max)
                        .style("stroke-dasharray", "2.5,7");
                self.svg.append("path")
                        .datum(self.forecastData)
                        .attr("class", "line_characteristics_forecast_temperature_min")
                        .attr("d", self.line_characteristics_temperature_min)
                        .style("stroke-dasharray", "2.5,7");
            }
        }

        self.showCurrent = function (show)
        {
            self.currentEnabled = show;
        };

        self.showForecast = function (show)
        {
            self.forecastEnabled = show;
        };

        self.showAverages = function (show)
        {
            self.averagesEnabled = show;
        };
    }

A:

Apply CSS as shown below.
.axis path, .axis line{
    stroke: navy;
    fill: none;
}
.y.axis path{
    stroke: brown;
    fill: none;
}
.y.axis line{
    stroke: grey;
    opacity: 0.5;
}


Q:

How can I use "onchange" to get immediate response?

I'd like to make visible the event, event.target objects and  show immediately how event.target.value changes when I type in an input field.
My code works but it only shows the things when I click next to the input field.
Is it possible to show the value of event.target.value property as I am typing in?
(Here is the full version:
https://codepen.io/parragiWeb/pen/mdPREoB)
Here is part of it:
HTML: <input id="elem" type="text"></input>
JS:
elem.onchange = (event) => {
  for(let key in event) {
    output.innerHTML += "
" + key + ": " +  event[key] +"
";
  }

  for(let key in event.target) {
    output2.innerHTML += "
" + key + ": " +  event[key]  + "
";
  }

  output3.innerHTML += "
" + event.target.value + "
";
}

A:

The event should be onkeyup. This works fine now. Hope it helps!!.. Happy Coding!!

let output = document.getElementById("output");
output.innerHTML = "event object properties and values:";

let output2 = document.getElementById("output2");
output2.innerHTML = "event.target object properties and values:";

let output3 = document.getElementById("output3");
output3.innerHTML = "event.target.value:";

elem.onkeyup= (event) => {
  for(let key in event) {
    output.innerHTML += "
" + key + ": " +  event[key] +"
";
  }

  for(let key in event.target) {
    output2.innerHTML += "
" + key + ": " +  event[key]  + "
";
  }

  output3.innerHTML += "
" + event.target.value + "
";
}
.objs{
  width: 40%;
  float: left;
}
#output3{
  width: 20%;
  float: left;
}
.head {
  margin: 5px;
  padding: 10px;
  color: white;
  background: #333;
  border-radius: 5px;
}

.clearfix {
  margin-bottom: 20px;
}

.clearfix::after {
  content: '';
  display: table;
  clear: both;
}

Type in the input field and then click next to it.

"When an event happens, the browser creates an event object, puts details into it and passes it as an argument to the handler."  (javascript.info)

Input field:
<input id="elem" type="text"></input>


Q:

Groovy compiler phase with variable resolution

I am creating a custom CompilationUnit with the intention to compile some Groovy script only up until a specific phase.
I want to have variables resolution inclusive so I am compiling up to the SEMANTIC_ANALYSIS phase.
CompilationUnit cu = new CompilationUnit(compilerConfiguration);
File file = new File("scripts/script12.esc");
cu.addSource(file);
cu.compile(Phases.SEMANTIC_ANAYLSIS);

My test script is really simple and has this content:
def a = b + "c";

The compilerConfiguration is nothing special except for the fact that I have the Type checking extension enabled.
And here comes the problem: as type checking is enabled, I would assume that Groovy will try to resolve the variables in the script. And this should happen during the SEMANTIC_ANALYSIS phase. But running this does not provide the expected errors.
If I let it compile up to the INSTRUCTION_SELECTION phase, then I get (as expected) [Static type checking] - The variable [b] is undeclared. But this happens a bit too late.

A:

Answering my own question:
The @TypeChecked annotation actually is a kind of AST tranformation which runs during the INSTRUCTION_SELECTION phase - so no wonder that it did not run during SEMANTIC_ANALYSIS.


Q:

convert a 2d list to RDD[vector] or JavaRDD[vector] scala

I have a 2d list of integers and I would like to convert it to either RDD[vector] or JavaRDD[vector] in order to use the predict method of the SVM model in spark MLlib.
I have tried the following, in order to convert it to rdd. But it seems that this is not what I need.
 val tuppleSlides = encoded.iterator.sliding(10).toList
 val rdd = sc.parallelize(tuppleSlides)

Any ideas what is the command to convert it to the right type?
Thank you in advance.

A:

If you want to use MLlib you will need an RDD[LabeledPoint]. Given your 2D list of data and some list of labels, you can create your RDD[LabeledPoint] like so:
scala> val labels = List(1.0, -1.0)
labels: List[Double] = List(1.0, -1.0)

scala> val myData = List(List(1d,2d), List(3d,4d))
myData: List[List[Double]] = List(List(1.0, 2.0), List(3.0, 4.0))

scala> import org.apache.spark.ml.linalg.Vectors
import org.apache.spark.ml.linalg.Vectors

scala> import org.apache.spark.ml.feature.LabeledPoint
import org.apache.spark.ml.feature.LabeledPoint

scala> val vectors = myData.map(x => Vectors.dense(x.toArray))
vectors: List[org.apache.spark.ml.linalg.Vector] = List([1.0,2.0], [3.0,4.0])

scala> val labPts = labels.zip(vectors).map{case (l, fV) => LabeledPoint(l, fV)}
labPts: List[org.apache.spark.ml.feature.LabeledPoint] = List((1.0,[1.0,2.0]), (-1.0,[3.0,4.0]))

scala> val myRDD = sc.parallelize(labPts)
myRDD: org.apache.spark.rdd.RDD[org.apache.spark.ml.feature.LabeledPoint] = ParallelCollectionRDD[0] at parallelize at <console>:34


Q:

How do I know what data type to use in Python?

I'm working through some tutorials on Python and am at a position where I am trying to decide what data type/structure to use in a certain situation.
I'm not clear on the differences between arrays, lists, dictionaries and tuples.
How do you decide which one is appropriate - my current understanding doesn't let me distinguish between them at all - they seem to be the same thing.
What are the benefits/typical use cases for each one?

A:

How do you decide which data type to use? Easy:
You look at which are available and choose the one that does what you want. And if there isn't one, you make one.
In this case a dict is a pretty obvious solution.

A:

Best type for counting elements like this is usually defaultdict
from collections import defaultdict

s = 'asdhbaklfbdkabhvsdybvailybvdaklybdfklabhdvhba'
d = defaultdict(int)

for c in s:
   d[c] += 1

print d['a']   # prints 7

A:

Tuples first. These are list-like things that cannot be modified. Because the contents of a tuple cannot change, you can use a tuple as a key in a dictionary. That's the most useful place for them in my opinion. For instance if you have a list like item = ["Ford pickup", 1993, 9995] and you want to make a little in-memory database with the prices you might try something like:
ikey = tuple(item[0], item[1])
idata = item[2]
db[ikey] = idata

Lists, seem to be like arrays or vectors in other programming languages and are usually used for the same types of things in Python. However, they are more flexible in that you can put different types of things into the same list. Generally, they are the most flexible data structure since you can put a whole list into a single list element of another list, but for real data crunching they may not be efficient enough.
a = [1,"fred",7.3]
b = []
b.append(1)
b[0] = "fred"
b.append(a) # now the second element of b is the whole list a

Dictionaries are often used a lot like lists, but now you can use any immutable thing as the index to the dictionary. However, unlike lists, dictionaries don't have a natural order and can't be sorted in place. Of course you can create your own class that incorporates a sorted list and a dictionary in order to make a dict behave like an Ordered Dictionary. There are examples on the Python Cookbook site.
c = {}
d = ("ford pickup",1993)
c[d] = 9995

Arrays are getting closer to the bit level for when you are doing heavy duty data crunching and you don't want the frills of lists or dictionaries. They are not often used outside of scientific applications. Leave these until you know for sure that you need them.
Lists and Dicts are the real workhorses of Python data storage.


Q:

MPI large data processing

My application of MPI will read a series images to build a 3-D data. It is very large data( about 4 GB). I don't want the data distributed to every worker. I don't know how to do with this. Shared memory may be one solution. But how to use shared memory by using MPI. I have searched a lot about this, nothing good was found. Could someone give me suggestions or examples for large data processing by using MPI (BTW. I am using Open MPI implementation).
Thank you very much for your great help.

A:

What you are looking for are one-sided communications that were added to MPI-2. It is available in OpenMPI. For an introduction, you could have a look at http://www.linux-mag.com/id/1793/ .
The principle is that you create a window (an area of shared memory), then you can get or put data from that window. MPI should optimize it to use RMA when available. There are also mechanisms like fences to ensure synchronization across processes.


Q:

Apache Velocity Template Language - Ignore invalid references

Suppose I want to parse a map like this in VTL.
map - { "person" = "xyz", age="99" }

Using VTL, I would call $map.person and $map.age to insert the appropriate values in the template.
Now suppose the map does not hold any valid value for the key "person"
map - { age="99" }

If I call $map.person , VTL simply will return $map.person. I want to ignore such a reference from being parsed at all. How can I achieve this?

A:

silent notation.  yep, it's in the manual.
$!map.person


Q:

Adding a permanent number line to VIM OSX Terminal

I have come across a command for vim in osx terminal that allows you to view each line in a predetermined .c document, which is :set number.  I want to set this parameter to be on default each time a document is created or opened.
After doing a search I came across this: you can append :set number to vi ~/.vimrc
First, what is this file?  How do you access it, and how do I append such a command to it?
I've tried searching the vim docs for .vimrc, but it doesn't make much sense as it talks about there being "4 places for initialisations, etc..."

A:

Note: If you are on windows the .vimrc is called _vimrc
Your .vimrc file should be created inside your home directory (~). This is a script that is run everytime you start vim and should contain customizations to the editor such as the set number command. It allows you to customize and "program" vim. If you want :set number to be called every time you start vim, you should place it inside your vimrc to be run everytime vim starts.
Create a .vimrc (text) file with vim (or with any other text editor) in your home directory
$ cd ~
$ vim .vimrc

Then add this line:
set number

Notice there is no :. That is because this is not a command line command anymore and instead is executed as vimscript code.
The .vimrc file is useful for remapping keys to other commands, creating your own commands, turning on options like set number (there are many more) enabling plugins etc... For this reason, everyone has a different .vimrc file, which has been crafted as they use vim. I am often coding in vim, and decide it would be nice to have a command that you let me do something more efficiently, so I open up my .vimrc and add in something that would help me code faster.
As you use vim more and more, you will discover good optimizations to put in your .vimrc and the file will start to grow. You can google example vimrcs to see very cool settings that will help you code faster or better.
While in vim, use :h vimrc to see more information about it.
See here for a website about how to make a good vimrc.


Q:

Why are two different forms for 1st order transfer functions often presented?

In my notes from a controls course, we derived the transfer function for a first order system, and it was given as $$\frac{1}{1+sT}$$
However, the notes also state that
$$\frac{K}{1+sT}$$
Is the general transfer function for 1st order systems. I am very confused on how they can both represent the same system. I initially thought I had misunderstood the first equation and that it was a transfer function for a particular solution, but this http://ece.gmu.edu/~gbeale/ece_421/xmpl-421-1st-order-01.pdf set of notes and What is the significance of the standard form of 1st and 2nd order transfer functions? this question suggest that it fact a general transfer function.
The question in the second link actually asks why sometimes one is given instead of the other, but I would like to know how it is possible for two transfer functions to be equivalent when they differ by a factor of K.  Where am I going wrong? Thanks in advance.

A:

The former is a special case of the latter when the scalar gain is equal to one. It can be simpler to understand a system if you use 1/(1+sT) and K as separate blocks; the following block diagrams are equivalent.

simulate this circuit – Schematic created using CircuitLab


Q:

Looking for a simple JavaScript "confirm action" dialog

I have a Visualforce page with a custom link that calls a function in the page's controller extension. Before that function gets called, I'd like to use JavaScript to pop up an confirmation dialog box along the lines of "You have chosen to mark this item as resolved. Your name will be added to the comments. OK/Cancel". If OK is clicked, we proceed to the Apex function call.  If Cancel is clicked, nothing happens.
I've found this example:
Custom JS confirm button for IF
But it looks to me like it will always call the Apex function. My understanding of what's happening is likely incomplete.
I'm not using any JavaScript packages at present. I'd like to keep things that way if possible.
Here's the code I started with. It's a trimmed down version of what I linked to and gets accessed by adding the following to the link onclick="return showConfirmation();"
<apex:outputPanel id="sendScript">
    <script type="text/javascript">
        function showConfirmation() {
            return confirm('All selected items will be marked resolved. Your name will be added to the comments.');
        }
    </script>
</apex:outputPanel>

A:

The answer that you found is OK. You could try this:
<apex:commandLink onclick="return confirm('You have chosen to mark this item as resolved. Your name will be added to the comments. OK/Cancel');" action="{!yourMethod}" value="Call your method"/>

If you return a false onclick the method will not be called.
The confirm function returns true or false (OK or Cancel).


Q:

Can't find marketplace client for Eclipse oxygen version milestone 6

I'm unable to find the Eclipse Marketplace in the Help Menu for Eclipse Oxygen version milestone 6. I've seen it last in Mars version in my old system. As I moved to a new system I installed a new version of eclipse which is Oxygen version. But this version doesn't seem to have marketplace client installed with it. How can I find it or install the plugin from external sources?

A:

This is the problem with latest eclipse to prevent bloating. So go to Eclipse-> Help--> Install New software and --> type Oxygen in the "Work with" space (or copy paste this "Oxygen - http://download.eclipse.org/releases/oxygen".)
Now search "Market place client" in the second search box .
You will get as below: General purpose tools-->Market place client. Check that box and you are good to go.


Q:

Preload/predisplay tiles in a CATiledLayer?

On the iPhone (though I imagine it's an equally valid question in Cocoa) I have a UIScrollView around a UIView backed by a CATiledLayer. The way it works by default is to load any uncached/unfetched tiles when my viewport scrolls over a blank section of the CATiledLayer.
What I would like to know is if there's a way to trigger CATiledLayer to load a tile that's not actively being displayed? I would like to, for example, preload all tiles contiguous to the currently displayed tile while they are still offscreen, thus avoiding flashing a blank screen that fades in to the image once it's loaded asynchronously.
Any ideas?

A:

I don't think CATiledLayer will do what you want.  There are a couple of other options though.  First you can disable the tile fade-in and have it display immediately with something like this:
@interface NoFadeTiledLayer : CATiledLayer {
}
@end

@implementation NoFadeTiledLayer
+ (CFTimeInterval)fadeDuration {
    return 0.0;
}
@end

@implementation MyViewWithTiledLayer
+ (Class)layerClass {
    return [NoFadeTiledLayer class];
}
...
@end

Second, you can do your own pre-fetch and caching of the adjacent tiles so they're ready to go when CATileLayer calls drawLayer:inContext.  I'd implement scrollViewDidScroll: and scrollViewDidZoom: to determine the adjacent tiles and levelOfDetail.  Then do a cache lookup and add any not present to a pre-fetch/render queue.  A background thread could service the queue and subsequent scrolls or zooms would clear and rebuild the queue.  Then have drawLayer:inContext check the cache first and only fetch/render if necessary.

A:

CATileLayer is one of those frustrating classes where it does one thing great, but has no flexibility to it.
At this point all that's left to us is creativity:
1) Make your scroll view huge.  I tried 5x the size of the screen before I stopped seeing "blank" tiles.  Be wary of memory use!  You are drawing to a huge area even though the user only sees 2% of it.
2) Have two version of your image, one high res and one low res.  you should be able to blit the low res very quickly and basically you get "blurry" instead of "blank" tiles.  Apple's sample code ZoomingPDFViewer shows you how to do this.
http://developer.apple.com/library/ios/#samplecode/ZoomingPDFViewer/Introduction/Intro.html
Of course, some combination of the two might work if you want to invest the time.


Q:

circuit analysis of DC-source, inductance and modulated resistance

Here's an interesting problem. Consider a DC voltage source (for bias), an inductor (supply wires, for instance) and a resistor, which changes its resistance as a function of time: \$ R(t) = R_{offset}+R_{mod}\cos(\omega t)\$, where \$R_{offset} > R_{mod}\$. The bias voltage across the photoresistor would cause an AC-current \$i(t)\$ to flow.

simulate this circuit – Schematic created using CircuitLab
Now, to find the unknown AC-current \$i(t)\$, I would solve the following ODE:
$$
V=L\frac{di}{dt}+i(t)R(t)
$$
which can be rearranged to:
$$
\frac{di}{dt}+i(t)\frac{R(t)}{L}=\frac{V}{L}
$$
which enables us to solve the DE using the integration factor method.
$$
i(t)=\frac{\int e^{\int p(t)dt}g(t)dt+c}{e^{\int p(t)dt}}
$$
where \$g(t)=\frac{V}{L}\$ and \$p(t)=\frac{R_{offset}}{L}+\frac{R_{mod}}{L}\cos(\omega t)\$. We get:
$$
i(t)=\frac{\frac{V}{L}\int e^{\big(\frac{R_{offset}}{L}t+\frac{R_{mod}}{\omega L}\sin(\omega t)\big)}dt + c}{e^{\big(\frac{R_{offset}}{L}t+\frac{R_{mod}}{\omega L}\sin(\omega t)\big)}}
$$
which becomes:
$$
\require{cancel}
i(t)=\frac{V}{\cancel{L}}\frac{\cancel{L}}{R_{offset}t + \frac{R_{mod}}{\omega}\sin(\omega t)} + \frac{c}{e^{\big(\frac{R_{offset}}{L}t+\frac{R_{mod}}{\omega L}\sin(\omega t)\big)}}\\
=\frac{V}{R_{offset}t + \frac{R_{mod}}{\omega}\sin(\omega t)} + \frac{c}{e^{\big(\frac{R_{offset}}{L}t+\frac{R_{mod}}{\omega L}\sin(\omega t)\big)}}\\
$$
The first term goes to 0 after briefly going to \$\infty \$ when \$R_{offset}t\$ and \$\frac{R_{mod}}{\omega L}\sin(\omega t)\$ are equal (big L-'hard-start'?). The other term goes to 0 with \$e^{-t}\$ which looks kind of strange, as I would expect some sort of steady-state solution.
Am I asking the wrong kind of question, here? i.e., is the problem badly stated, or am I missing something else?
EDIT: After doing the write-up, I have a suspicion, that:
$$
\int e^{\big( \frac{R_{offset}}{L}t+\frac{R_{mod}}{\omega L}\sin(\omega t)\big)}dt \neq \frac{L}{R_{offset}t + \frac{R_{mod}}{\omega}\sin(\omega t)}e^{\big(\frac{R_{offset}}{L}t+\frac{R_{mod}}{\omega L}\sin(\omega t)\big)}
$$
I will have another look, and correct if needed.

A:

You won't (easily) get a closed form for \$\int e^{p(t)}dt\$.
The solution to the differential equation that you wrote is:
$$i(t)=\left(\frac{V}{L}\right)e^{\frac{-R_{mod}\sin(\omega t)}{L\omega}-\frac{R_{offset}t}{L}}\left(\int_0^t e^{\frac{R_{mod}\sin(\omega \tau)}{L\omega}+\frac{R_{offset}\tau}{L}} d\tau\right)+ Ce^{\frac{-R_{mod}\sin(\omega t)}{L\omega}-\frac{R_{offset}t}{L}}$$
where \$C\$ is an unknown determined by the initial condition.  Obviously the term involving integration is the troublesome bit so lets focus on that piece.
The power series for \$e^{x}\$ converges uniformly on bounded sets so we can exchange the power series with the integral giving
$$\int_0^t e^{\frac{R_{mod}\sin(\omega \tau)}{L\omega}+\frac{R_{offset}\tau}{L}} d\tau = \sum_{n=0}^{\infty}\frac{1}{n!}\int_0^t\left(\frac{R_{mod}\sin(\omega \tau)}{L \omega}+\frac{R_{offset} \tau}{L} \right)^n d\tau.$$
Integrating the inner terms involves integrating terms of the form \$\tau^k\sin(\omega \tau)^{n-k}\$ which have closed form solutions.
The real upshot is that if we only want approximate solutions we can bound the tail of this series by bounding the integrands and using that $$\sum_{n=N+1}^{\infty}\frac{1}{n!}x^n = e^x-\frac{e^x \Gamma(N+1,x)}{N!}.$$
Then we will have a closed formed approximate solution \$\tilde{i}_N(t)\$ which approximates \$i(t)\$ and we will know a bound for the error \$|\tilde{i}_N(t) - i(t)|\$.


Q:

Beginner Trying to Understand Existing Project

I have a project that requires me to control movement of SCARA robot using VC. I am a beginner in programming so I thought of using existing program as my reference. The SCARA robot that I am using is regarded as a valuable property of the department and must be operated with extra care. I cannot simply make a program out of nowhere to ensure no damage on the robot.
I find it difficult to understand the existing program and am overwhelmed with the long lines of coding. Unfortunately, the last person involved with the program already left and no one in my department has any experience with the program. Currently I am not getting the help that i really need.Hopefully someone can give me guidance on this project.

A:

Can you run the program on the robot and step through it?  That could be a good way to get an understanding of the overall program flow, assuming that pausing the program in the middle won't cause a crash.  If the position/velocity control loop is implemented in VC, then you really shouldn't step through it, or you risk sending a constant output to some actuator, which will just cause it to accelerate into a hard stop.  On the other hand, if the robot has a built-in separate motion controller, and the VC program is just telling the motion controller what step to take next, then you're safe to step through it.
Whether or not you can step through it, you're going to have to get familiar with the code.  I suggest printing it out so you can make annotation in the margin, etc.  Start with the high level program flow, and try to understand it.  Then dive into each piece.  You pretty much need to familiarize yourself with each line of code.
Yeah, it's a lot of work.  Reading code is hard.

A:

In this situation, you have your work cut out for you, but it is not impossible.  You will need to organize things a bit for your own sake.  The actions you will need are:

Collect the specifications, manufacturer manuals, etc. you can.  You'll need to familiarize yourself with how the SCARA robot is controlled and what acceptable parameters are.  Don't assume someone else has done their due diligence for you.
Discover how the files are organized.  It might look like a mess to start with, but eventually you'll learn which file(s) to look in.  If the current organization of the application doesn't seem to make sense, spend some time adding some order.  Some people still like to put everything in one file, esp. if it's a small app.  You might consider breaking files up that have multiple classes so that there is one class per file.  That makes it easier to find the file you need.
Attempt to recognize patterns that are being used.  The GoF book "Design Patterns" provides some blueprints for common approaches to solving some problems.  The code you see in the wild may not conform exactly to the way they are described in the book, but you can at least get an idea of what the code is supposed to be doing.
Comment the critical sections.  The hard part is finding out what the critical sections of code are.  That's what the previous steps were doing.  Now that you've got an idea of what they are, it's time to really analyze what is happening.  You'll have your manuals and specifications open for reference, but you will have to trace the application line by line to come up with the intent behind the code.

In this last step, you are going to want to take frequent breaks and keep asking yourself why is the application doing X or Y.  Basically you are trying to figure out if you are in a forest or a jungle by looking at the leaves around you.  But that's all you have at the moment.  As you go through pass by pass, you will start to get a mental model for how the code is actually working.  As you start to recognize the patterns and how things are working, change your comments because you need those to "get it".  As you look at the new comments and code, you might be able to get to another level of abstraction away.  You can add those comments, or change the comments you have as it makes sense.
Remember, you are trying to build some familiarity with the code.  In the absence of the developer who wrote it, this is all you can do.  This is also how I learned assembly programming way back in the day.  The higher level concepts are there, but it takes time to zoom out as it were.


Q:

Using lists from another Site

On our company sharepoint we have a seperate Site per 'Department'.  I've been implementing a Contactperson list on our site, which has a link to one or more Hospitals (a seperate list on our site). However, it would be useful if I could use a 'global' list of Hospitals instead of each department having to define his own (identical) list of Hospitals to reference.
So, the question: how can I reference a List defined on another site in a list on my Site?

A:

You could use the the BCS (Business Connectivity Services in SP2010) is an out of box feature enabling external business data to be shared between site collections without writing any code.
Here a link from microsoft
http://msdn.microsoft.com/en-us/magazine/ee819133.aspx
and here an answer from Stackexchange:
Sharing data between multiple site collections


Q:

Python,Tkinter, making a username/password interface

Beginner to python. Can't seem to figure out how to set a password to these
entries.Looked into a bunch of sites already. Any examples or feedback is much appreciated.Thanks...............................................
from tkinter import*
from PIL import Image,ImageTk
import glob,os
root=Tk()

w1=Label(root,text="1")
w2=Label(root,text="2")
w3=Label(root,text="3")

e1=Entry(text="five")
e2=Entry(text="six")
e3=Entry(text="seven")

text=(e1)

def show_entry_fields():
    print("1:%s\n2:%s\n3:%s" %(e1.get(),e2.get(),e3.get()))
e1.delete(0,END)
e2.delete(0,END)
e3.delete(0,END)

b1=Button(root,text="Submit",command=show_entry_fields).grid(row=3,column=3)

e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
e3.grid(row=2,column=1)

w1.grid(row=0)
w2.grid(row=1)
w3.grid(row=2)

image=Image.open("beer.png")
photo=ImageTk.PhotoImage(image)

label=Label(image=photo)
label.image=photo#keep a reference
label.grid(column=4)

mainloop()

A:

Can't seem to figure out how to set a password to these entries.

Going from your comment:

rather set a password to each entry.

This might be more along the lines of what you are attempting to do.
The below code will check if each entry field has the correct password.
if so it prints success and if not it prints try again.
from tkinter import *

root=Tk()

Label(root, text="1").grid(row=0)
Label(root, text="2").grid(row=1)
Label(root, text="3").grid(row=2)

e1=Entry(root)
e2=Entry(root)
e3=Entry(root)
e1.grid(row=0,column=1)
e2.grid(row=1,column=1)
e3.grid(row=2,column=1)

def test_entry_fields():
    if e1.get() == "five" and e2.get() == "six" and e3.get() == "seven":
        print("You have entered the correct passwords!")
    else:
        print("Please try again.")
    e1.delete(0,END)
    e2.delete(0,END)
    e3.delete(0,END)

b1=Button(root,text="Submit",command=test_entry_fields).grid(row=3,column=3)

mainloop()


Q:

Change std::thread execution flow with signals in c++

I have a program starting an std::thread doing the following: sleep X, execute a function, terminate.
create std::thread(Xms, &func)
  wait Xms
  then do func()
  end

I was wondering if I could for example send a signal to my std::thread in order to instantly break the sleep and do func, then quit.
Do I need to send the signal to std::thread::id in order to perform this?
my thread is launched this way, with a lambda function:
template<typename T, typename U>
void                          execAfter(T func, U params, const int ms)
{
  std::thread                 thread([=](){
      std::this_thread::sleep_for(std::chrono::milliseconds(ms));
      func(params);
    });
  thread.detach();
}

A:

Using wait_for of std::condition_variable would be the way to go, if the thread model can't be changed. In the code snippet below, the use of the condition_variable is wrapped into a class of which objects have to be shared across the threads.
#include <iostream>
#include <atomic>
#include <condition_variable>
#include <thread>
#include <chrono>

class BlockCondition
{
    private:
        mutable std::mutex m;
        std::atomic<bool> done;
        mutable std::condition_variable cv;
    public:
        BlockCondition()
        :
           m(),
           done(false),
           cv()
        {
        }
        void wait_for(int duration_ms)
        {
            std::unique_lock<std::mutex> l(m);
            int ms_waited(0);
            while ( !done.load() && ms_waited < duration_ms )
            {
               auto t_0(std::chrono::high_resolution_clock::now());
               cv.wait_for(l, std::chrono::milliseconds(duration_ms - ms_waited));
               auto t_1(std::chrono::high_resolution_clock::now());
               ms_waited += std::chrono::duration_cast<std::chrono::milliseconds>(t_1 - t_0).count();
            }
        }
        void release()
        {
            std::lock_guard<std::mutex> l(m);
            done.store(true);
            cv.notify_one();
        }
};

void delayed_func(BlockCondition* block)
{
    block->wait_for(1000);
    std::cout << "Hello actual work\n";
}

void abortSleepyFunction(BlockCondition* block)
{
    block->release();
}

void test_aborted()
{
    BlockCondition b();
    std::thread delayed_thread(delayed_func, &b);
    abortSleepyFunction(&b);
    delayed_thread.join();
}

void test_unaborted()
{
    BlockCondition b();
    std::thread delayed_thread(delayed_func, &b);
    delayed_thread.join();
}

int main()
{
    test_aborted();
    test_unaborted();
}

Note that there might be spurious wakeups that abort the wait call prematurely. To account for that, we count the milliseconds actually waited and continue waiting until the done flag is set.


Q:

Stack Exchange Data Explorer query to find upvoted questions with only downvoted answers

I have written a SQL query against the Stack Exchange Data Explorer that identifies answered questions with a positive score for which all the answers have a negative score (this was an answer to this Meta Stack Exchange post, though the code in that post is different from what I've posted below).
It's a fairly straightforward query; you can see it and run it on the Data Explorer (where you can also examine the schemata of the tables), and I have reproduced it below for your convenience.
SELECT
  q.Id AS [Post Link], -- this alias makes the Data Explorer do magic link rendering
  MAX(q.Score) AS [Score],
  COUNT(a.Id) AS [AnswerCount],
  AVG(CAST(a.Score AS float)) AS [AvgAnswerScore]
FROM
  Posts AS q
  -- INNER JOIN => At least one answer
  INNER JOIN Posts AS a
    ON q.Id = a.ParentId
WHERE
  -- Question has a positive score
  q.Score >= 1
GROUP BY
  q.Id
HAVING
  -- Zero answers with a non-negative score
  SUM((CASE WHEN a.Score >= 0 THEN 1 ELSE 0 END)) = 0
ORDER BY
  [Score] DESC,
  [AnswerCount] DESC

While I of course would love to hear anything you have to say about this code, I am particularly interested in the following:

Stylistic tips - coming from the perspective of a PEP8-adhering Python guy, the huge inhomogeneity in SQL coding styles makes me queasy.
MAX(q.Score) looks really stupid and is semantically wrong, since there's obviously only one q.Score for each q.Id since they come from the same table, and q.Id is the primary key of that table. But putting q.Score into the GROUP BY also seems weird to me, since that's not semantically what I'm doing either. Is there a better way to approach this?
How do the performance characteristics of the HAVING clause here differ from instead using a WHERE clause of the form below?
q.Score >= 1
AND NOT EXISTS (
  SELECT 1
  FROM Posts AS a2
  WHERE a2.ParentId = q.Id AND a2.Score >= 0
)

My sense is that HAVING SUM(...) = 0 is probably better, since, uh... there doesn't need to be a new subquery for each row of the outer query? But I don't know if that is true or even makes sense.

A:

Answering your questions in reverse order…
Your HAVING clause is clearer than than an anti-join condition in the WHERE clause.  It is also more efficient — tick the "Include execution plan" checkbox to see how much more complicated the anti-join is.  You could do better, though:  MAX(a.Score) < 0 also means that all answers have a net negative score.
Given the choice between selecting MAX(q.Score) and grouping by q.Score, I'd prefer the latter.  Both are annoying, but the SQL standard requires that you do one or the other, so that all columns are either mentioned in GROUP BY or are aggregated.
I can provide some style tips, but keep in mind that these are my personal recommendations.  I don't believe that there is a standard SQL style guide — and certainly nothing as formalized as PEP 8.

Fill in the description to your Data Explorer query.  Otherwise, there is a huge gap between the information contained in the title and the SQL.  Detail exactly what the query does.  Mention your motivation for writing the query.  State what the sort order is.
Indent more.  The FROM, WHERE, GROUP BY, HAVING, and ORDER BY clauses are all subsidiary to the SELECT, and therefore should be at the next indentation level.
Finishing the query with a semicolon is a good habit.
Move comments to the right to be less obtrusive.
I like to put commas before the selected columns.  That convention makes it easier to add and remove columns.
Prefer comparing with 0 instead of comparing with any other constant.

SELECT q.Id AS [Post Link] -- Alias makes Data Explorer do magic link rendering
     , q.Score AS [Score]
     , COUNT(a.Id) AS [AnswerCount]
     , AVG(CAST(a.Score AS float)) AS [AvgAnswerScore]
    FROM Posts AS q
        INNER JOIN Posts AS a
            ON q.Id = a.ParentId
    WHERE
        q.Score > 0        -- Question has a positive score
    GROUP BY
        q.Id, q.Score
    HAVING
        MAX(a.Score) < 0   -- Best answer has a negative score
    ORDER BY
        [Score] DESC,
        [AnswerCount] DESC;

I'd like to point out: good job remembering to CAST(a.Score AS float) before taking the average.  SQL Server is tricky, in that AVG() of ints is an int.


Q:

What is the meaning of "melaza" in the song "Caras Lindas"?

This is the song. The word is translated by online lyrics, RAE and wordreference.com as molasses. But it doesn't make sense to me in the context.

Somos la melaza que ríe
  Somos la melaza que llora
  Somos la melaza que ama

Suggested tag: metaphor.

A:

Melaza is a byproduct of the production of sugar and panela (a.k.a piloncillo) and it's dark brown and very sweet. The song you mention is really called "Las caras lindas" and it's interpreted by the great Ismael Rivera (himself an afro-descendant).
The song talks about how beautiful black people are, how loving, etc. I think using melaza as a metaphor of black people makes a lot of sense. Melaza is the same color as afro-descendant people and it's also well known that Africans were brought to America to work on sugar cane plantations, in Cuba, Colombia and I am sure other countries, it's still a job usually performed by Afro-descendants.
In conclusion, "la melaza" is referring to black people.


Q:

JQuery Carousel images mis-aligned

I am trying to install a JQuery Carousel into a clients website, I have tried a couple of different ones and they both give the same issue, the images appear aligned far over to the right and up a little bit. I was wondering if anyone could take a quick look for me? The site is being built here: www.samskirrow.com/client-hope
Thanks,
Sam

A:

The issue is that your menu and your tagline block are floated left.
A quick fix would be to add clear: both to your mask class.
I would recommend reading about clearfix solution for a better solution. This would entail adding the following CSS to your stylesheet and applying the class to floated elements.
.clearfix:before, .clearfix:after { content: ""; display: table; }
.clearfix:after { clear: both; }
.clearfix { zoom: 1; }