text:
Q: I cannot sort the Linked List Alphabetically in C I am new to programming and StackOverflow. I cannot understand the other questions answers because i cannot read the code that good. So, can anyone help me with my code? I am trying to sort the given strings in the linked list in alpabetical order. They soon will be taken from the user. But i am trying to debug before coding that phase.
It doesnt give an output when i try to print the linked list as sorted.
There is no syntax error.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node
{
    char word[100];
    struct node *next;
}node;

node* addToLinkedList(node *head, char word[])
{
    node *temp = (node*)malloc(sizeof(node));
    strcpy(temp->word, word);

    if(head==NULL)
    {
        temp->next=NULL;
        head=temp;
        return head;
    }

    node *iter = head;
    while(iter->next!=NULL)
        iter=iter->next;

    iter->next=temp;
    temp->next=NULL;
    return head;
}

int listLenght(node *head)
{
    int len=0;
    node *iter = head;
    while(iter!=NULL)
    {
        len++;
        iter=iter->next;
    }

    return len;
}

void sortList(node *head)
{
    int len = listLenght(head);

    int i,j;
    for(i=0; i<len; i++)
    {
        node *tmp1 = head;
        node *tmp2 = tmp1->next;
        for(j=0; j<len; j++)
        {
            int idx = 0;
            while(tmp1->word[idx] == tmp2->word[idx])
                idx++;

            if(tmp1->word[idx] > tmp2->word[idx])
            {
                char wrd[100];
                strcpy(wrd, tmp1->word);
                strcpy(tmp1->word, tmp2->word);
                strcpy(tmp2->word, wrd);

            }
            tmp1=tmp1->next;
            tmp2 = tmp2->next;
        }
        tmp1 = head;
    }
}

void printfLinkedList(node *head)
{
    node *iter = head;
    while(iter!=NULL)
    {
         printf("%s ->", iter->word);
         iter=iter->next;
    }
}

int main()
{
    node *list = NULL;
    list=addToLinkedList(list,"one" );
    list=addToLinkedList(list,"two" );
    list=addToLinkedList(list, "three");
    list=addToLinkedList(list,"four" );
    list=addToLinkedList(list,"five" );
    sortList(list);
    printfLinkedList(list);

    return 0;
}

A: The program is terminated with a segmentation fault at this line
            while(tmp1->word[idx] == tmp2->word[idx])

because tmp2 is NULL and you try to dereference the pointer.
Since len is the number of elements in the list, in the last loop cycle here
        node *tmp1 = head;
        node *tmp2 = tmp1->next;
        for(j=0; j<len; j++)
        {
            /* ... */
            tmp1=tmp1->next;
            tmp2 = tmp2->next;
        }

tmp1 will point to the last list element and tmp2 will point to its non-existent successor, i.e. NULL.
To see this error you should run your program in a debugger and/or use a memory access checker like valgrind.
You can change this loop to one cycle less to make your program work as shown below. (I, additionally, modified your code to show the list before and after sorting.)
/* ... */
{
    int len = listLenght(head);

    int i,j;
    for(i=0; i<len; i++)
    {
        node *tmp1 = head;
        node *tmp2 = tmp1->next;
        for(j=0; j<len-1; j++)
        {
            int idx = 0;
            while(tmp1->word[idx] == tmp2->word[idx])
                idx++;

            if(tmp1->word[idx] > tmp2->word[idx])
            {
                char wrd[100];
                strcpy(wrd, tmp1->word);
                strcpy(tmp1->word, tmp2->word);
                strcpy(tmp2->word, wrd);

            }
            tmp1=tmp1->next;
            tmp2 = tmp2->next;
        }
        tmp1 = head;
    }
}

void printfLinkedList(node *head)
{
    node *iter = head;
    while(iter!=NULL)
    {
         printf("%s ->", iter->word);
         iter=iter->next;
    }
    printf("\n");
}

int main()
{
    node *list = NULL;
    list=addToLinkedList(list,"one" );
    list=addToLinkedList(list,"two" );
    list=addToLinkedList(list, "three");
    list=addToLinkedList(list,"four" );
    list=addToLinkedList(list,"five" );
    printfLinkedList(list);
    sortList(list);
    printfLinkedList(list);

    return 0;
}

Instead of counting the number of loop cycles, I suggest to check that tmp1 and tmp2are both not NULL.
void sortList(node *head)
{
    int len = listLenght(head);

    int i,j;

    for(i=0; i<len; i++)
    {
        node *tmp1 = head;
        node *tmp2 = (tmp1 != NULL) ? tmp1->next : NULL;
        while((tmp1 != NULL) && (tmp2 != NULL))
        {
            int idx = 0;
            while(tmp1->word[idx] == tmp2->word[idx])
                idx++;

            if(tmp1->word[idx] > tmp2->word[idx])
            {
                char wrd[100];
                strcpy(wrd, tmp1->word);
                strcpy(tmp1->word, tmp2->word);
                strcpy(tmp2->word, wrd);

            }
            tmp1=tmp1->next;
            tmp2 = tmp2->next;
        }
        tmp1 = head;
    }
}

The check for equal characters may access data after the end of the array if all characters are equal. This is undefined behavior and may result in a segmentation fault as well.
Make sure you stop reading at the end of the string.
            while((tmp1->word[idx] == tmp2->word[idx]) &&
                  (tmp1->word[idx] != '\0'))
                idx++;

Instead of implementing the string comparison yourself you could also use strcmp.
void sortList(node *head)
{
    int len = listLenght(head);

    int i,j;

    for(i=0; i<len; i++)
    {
        node *tmp1 = head;
        node *tmp2 = (tmp1 != NULL) ? tmp1->next : NULL;
        while((tmp1 != NULL) && (tmp2 != NULL))
        {
            int idx = 0;
            if(strcmp(tmp1->word, tmp2->word) > 0)
            {
                char wrd[100];
                strcpy(wrd, tmp1->word);
                strcpy(tmp1->word, tmp2->word);
                strcpy(tmp2->word, wrd);

            }
            tmp1=tmp1->next;
            tmp2 = tmp2->next;
        }
        tmp1 = head;
    }
}


text:
Q: Minimal degree affect on a tree subgraph. Show that each graph G with minimal degree m contains any tree with m+1 vertices as a subgraph.
I have no idea how to start here, would appreciate help. Thanks!

A: Hint:
Induct on $m$.
First, can you show the $m=1$ case is true?
Then, assume the claim for graphs of minimal degree $m$. We want to show the claim for a graph of minimal degree $m+1$.
Fix a graph $G$ with minimal degree at least $m+1$. Fix your favorite tree $T$ with $m+2$ vertices. Then remove a leaf $u$ from $T$ to get a tree $T'$ with $m+1$ vertices.

*

*Can you use the inductive hypothesis to show $G$ contains a copy of $T'$?

*Can you use the fact that $G$ has minimal degree $m+1$ to find a way to reattach $u$ to $T'$ in $G$? This will give you a copy of $T$ in $G$. As desired.

I hope this helps ^_^

redpajama_set_name: RedPajamaStackExchange


text:
Q: Uploading dSYM/.symbols file to appstore connect automatically using shell script Is there a way we can upload dSYM file when we upload .ipa file to TestFlight via shell script
xcrun altool --upload-app -f $ipa_path -u $appstore_connect_username -p $appstore_connect_password

If we do it manually using Xcode -> Window -> Organizer then it shows a checkbox (Upload your app's symbols to receive symbolicated reports from Apple) which is checked by default.

Since we have automated ipa uploading to testflight using above command, but dSYM is not uploading in that case. How can we upload dSYM to AppStoreConnect automatically?
Note: My iOS app project doesn't have bitcode enabled.

A: This can be achieved by setting uploadSymbols flag to true in ExportOptions.plist, while exporting .ipa file using the following command:
xcodebuild -exportArchive -archivePath build/myproject_results.xcarchive -exportPath ./build/ipa/ -exportOptionsPlist /path/to/ExportOptions.plist

So, when you upload your ipa using following command it will also upload symbols to app store connect.
xcrun altool --upload-app -f $ipa_path -u $appstore_connect_username -p $appstore_connect_password

You can verify existence of the symbols file in the exported .ipa using the following command:
unzip -lv $ipaPath | grep symbols

References:
Apple Developer Forum


text:
Q: xRy if and only if x is a descendant of y, on the set of all humans. Explain the relations xRy if and only if x is a descendant of y, on the set of all humans.
I have the solution to this. I just don't understand how transitivity follows.

A: If $x$ is a descendant of $y$ and $y$ is a descendant of $z$, then $x$ is a descendent of $z$. In other words: $xRy$ and $yRz$ implies $xRz$.

A: If your father (y) is a descendent of your grandfather (z) then yRz. If you (x) are a descendent of your father then xRy. You are also, by transitivity of the relation, a descendent of your grandfather, thus xRz.
Notice that the R relationship behaves similar to inequality in respect to transitivity and reflectivity.
Transitivity:
$$2 < 3 \hspace{1in} xRy$$
$$3 < 5 \hspace{1in} yRz$$
$$\Rightarrow 2 < 5 \hspace{.5in} \Rightarrow xRz$$
But $2 < 3 \not\Rightarrow 3 < 2$, likewise $xRy \not\Rightarrow yRx$.


text:
Q: Dynamic property defaults in CF9 ORM How do you set up dynamic property defaults on CF9 ORM objects?
For instance, I know I can set a property default like this:
property name="isActive" default="1";

But what if you want to have a dynamically generated default, such as a date or a UUID?
property name="uuid" default="#createUUID()#";

...throws an error - so what's the workaround for this?

A: When an Entity object is created the objects constructor is called. This is a great place for running "setup" code.
User.cfc
component persistent="true"
{
  property name="id" fieldtype="id" generator="native";
  property name="secretKey";

  public User function init() {
     if (isNull(variables.secretKey))
         setSecretKey(createdUUID());

     return this;
  }
}

A: Have you tried overloading the getter?
public string function getUUID() {if(variables.UUID EQ ""){ return createUUID(); } else { return variables.firstName; }; }

I can't test that from where I'm at, but I would try.


text:
Q: Spring security OAUTH 2.0 add new Client to the application I am trying to implement Spring OAuth 2.0 SSO, but i am unable to find a way to
ADD NEW CLIENT to the running app once it has started.
Adding new users is possible but i have been unable to find any way to add new CLIENTS to the app. please let me know if there is any way to do so.
I can only add Clients to the app a while it is booting up.


text:
Q: Word2Vec word embeddings on H2O Deep Water with GPU We followed the text categorization process with iterating the items below:

*

*Create a Word2Vec word embedding model with text documents.

*Do a Grid Search and tree depth parameters.

*Select the best performed Final GBM model.

As we iterate through the list CPU cores are working at %100 load. Are there any procedure or solution iterating the above process with H2O Deep Water GPU capabilities ?

A: No, no and maybe.
The maybe is that you could switch from GBM to xgboost, which does have a GPU option (I believe only single-node is supported, and only in Linux currently). xgboost is apparently slightly quicker on small data sets, h2o.gbm slightly quicker on large data sets. If you have a GPU going free, and are using the latest version of H2O, it should be easy to swap h2o.gbm with h2o.xgboost (H2OXGBoostEstimator if using Python API) and see for yourself.
I'd be interested to hear the relative timings!
(BTW, the 2nd "no" is for GPU use specifically for grids; but all the effort is in the models, not the grid itself, so the 2nd "no" could just as well be "N/A")


text:
Q: Observability matrix of a state-space representation Consider an uncontrolled linear dynamical system observed with an output $Y(t)$ in state space form: $$\left|\begin{array}{lll}\dot{X}=AX\\Y=CX\end{array}\right.$$
$X(t)$ is the state of the system in the state space (size $n\times1$), $Y(t)$ is the output vector (size $p\times 1$ for $p$ outputs), $A$ is the state matrix (size $n\times n)$, and $C$ is the output matrix (size $p\times n$).
We know that the unobservable subset of the state space is the null space of the observability matrix $$\mathfrak{O}=\begin{bmatrix}C\\CA\\\vdots\\CA^{n-1}\end{bmatrix}$$
And in particular, the system is fully observable iff $\text{rank}(\mathfrak{O})=n$.
Now, I'd like to derive this result in a simple way. I've seen a very simple derivation of the controlability matrix, and the author hinted that this approach can also work similarly to derive the observability matrix ; but I can't seem to work it out. Here it goes :
A state $X_0$ is unobservable iff the output $Y(t)$ is always $0$ when the system evolves freely from the said state $X_0$.
Now given an arbitrary initial state $X(0)=X_0$, by integrating the state equation $\dot{X}=AX$ we get that for $t\geq0$, $$X(t)=e^{At}X_0$$
And by the output equation $Y=CX$, the output is then $$Y=Ce^{At}X_0$$
Now, using the Cayley-Hamilton theorem, we can prove that the matrix $e^{At}$ can always be expressed as a finite polynomial of $A$ up to the power $n-1$, whose coefficient depends on $t$: $$e^{At}=\phi_0(t)I_n+\phi_1(t)A+\phi_2(t)A^2+..+\phi_{n-1}(t)A^{n-1}$$
I won't prove this result here because it's beyond my point, but it is not that complicated to show.
We can now use this expression of $e^{At}$ in the expression of $Y(t)$ above:
\begin{align}
Y(t)&=Ce^{At}X_0\nonumber\\
&=C\left(\phi_0(t)I_n+\phi_1(t)A+..+\phi_{n-1}(t)A^{n-1}\right)X_0\nonumber\\
&=C\cdot\phi_0(t)X_0+CA\cdot\phi_1(t)X_0+..+CA^{n-1}\cdot\phi_{n-1}(t)X_0\nonumber
\end{align}
This last equality can be expressed as a matrix product: $$Y(t)=\begin{bmatrix}C&CA&CA^2&..&CA^{n-1}\end{bmatrix}\begin{bmatrix}\phi_0(t)X_0\\\phi_1(t)X_0\\\vdots\\\phi_{n-1}(t)X_0\end{bmatrix}$$
And the state $X_0$ is in the unobservable space iff $Y(t)=0$ for all $t\geq0$ ; and I feel the last equality would enable us to conclude that the unobervable space of the system is the null space of the matrix $\begin{bmatrix}C&CA&CA^2&..&CA^{n-1}\end{bmatrix}$, which would mean that this is the observability matrix.
But it's not: it's constructed horizontaly from the blocs of $A$ and $C$'s, not verticaly. I can't seem to figure any way of expressing the last equations in terms of the observability matrix in it's official, vertical form. The thing is, the observability matrix i'm trying to get to is a $np\times n$ matrix, so there is no way we can obtain $Y(t)$ (which is a $p\times1$ matrix) by multiplicating the observability matrix by some other matrix.
And I am utterly lost there. I have no idea where the vertical construction of the observability matrix comes from, and I don't understand why the horizontal construction I got to wouldn't work. Plus, this approach i'm taking is supposed to lead me to the real observability matrix.
Any idea ?

A: You would want to factor out as much as possible, so also $X_0$, and use the fact that each $\phi_i(t)$ is scalar and thus commutes. Therefore, it is also possible to write your expression for $Y(t)$ as
$$
Y(t) =
\begin{bmatrix}
\phi_0(t)\,I & \phi_1(t)\,I & \cdots & \phi_{n-1}(t)\,I
\end{bmatrix}
\begin{bmatrix}
C \\ C\,A \\ \vdots \\ C\,A^{n-1}
\end{bmatrix} X_0,
$$
with $I$ the identity matrix of size $p \times p$.


text:
Q: update table based on a condition I need to update a column in table based on some condition.
here is the table -
DGTID |   SKAcc     |      Linkedaccount        |   DGTStatus
 1      8002180831     8102651144,8005370302          C
 2      8005370302           8002170111               I
 3      8002012348                                    I

So, for a particular DGT ID, if status = 'C' and if Linkedaccount is present in any other SKAcc, then DGTStatus for that SKAcc should also be C.
Lets say, DGTId = 1, it has DGTStatus as 'C' and it has a linkedaccount = '8005370302' which is the SKAcc for DGTID='2' . So, its DGTStatus should also be 'C'
Now, I believe the main part here is to extract linked account as there can be multiple comma seperated linked account.
This is what I wrote to extract linked account -
select  replace(''''+LinkedAccount+'''',',',''',''')  from IDCOPES..T_CDI_WHT_DGT where ISNULL(LinkedAccount,'')<>''

This gives me '8102651144','8005370302'.
and then, I wrote -
IF EXISTS (SELECT 1 from IDCOPES..T_CDI_WHT_DGT where DGTID=1 and DGTSTATUS='C')
    UPDATE IDCOPES..T_CDI_WHT_DGT
    SET DGTSTATUS='C'
    Where SKACC in (select  replace(''''+LinkedAccount+'''',',',''',''')  from IDCOPES..T_CDI_WHT_DGT where ISNULL(LinkedAccount,'')<>'' and DGTID=1)

But, this doesnt work.
However, when I write
IF EXISTS (SELECT 1 from IDCOPES..T_CDI_WHT_DGT where DGTID=1 and DGTSTATUS='C')
    UPDATE IDCOPES..T_CDI_WHT_DGT
    SET DGTSTATUS='C'
    Where SKACC in ('8102651144','8005370302')

It works. I can't understand why it won't work when both code are same.

A: IF EXISTS (SELECT 1 from IDCOPES..T_CDI_WHT_DGT where DGTID=1 and DGTSTATUS='C')
UPDATE IDCOPES..T_CDI_WHT_DGT
SET DGTSTATUS='C'
 Where SKACC in (
SELECT
LTRIM(RTRIM(m.n.value('.[1]','varchar(8000)'))) AS Certs
FROM
(
SELECT  *,CAST('<XMLRoot><RowData>' + REPLACE(LinkedAccount,',','</RowData>
<RowData>') + '</RowData></XMLRoot>' AS XML) AS x
FROM   IDCOPES..T_CDI_WHT_DGT
where LinkedAccount like '%,%'
)t
 CROSS APPLY x.nodes('/XMLRoot/RowData')m(n))

A: You can use the update logic as below-
DECLARE @TempTable TABLE(
    DGTID INT,
    SKAcc VARCHAR(MAX),
    Linkedaccount VARCHAR(MAX),
    DGTStatus VARCHAR(1)
)

INSERT INTO @TempTable (DGTID,SKAcc,Linkedaccount,DGTStatus)
VALUES( 1,'8002180831','8102651144,8005370302','C' ),
( 2,'8005370302','8002170111','I'),
( 3,'8002012348',NULL,'I' )

SELECT * FROM @TempTable

UPDATE A
SET A.DGTStatus = 'C'
FROM @TempTable A
INNER JOIN @TempTable B ON B.Linkedaccount LIKE '%'+CAST(A.SKAcc AS VARCHAR(MAX))+'%'
AND  B.DGTStatus = 'C'

SELECT * FROM @TempTable


text:
Q: Show that a,b, and c are a solution to a system of linear equations The curve $y = ax^2+bx + c$ passes through the points $(x_1, y_1), (x_2, y_2), and (x_3, y_3)$. Show that the coefficients a, b and c are a solution of the system of linear equations whose augmented matrix is:
$\left(\begin{array}{1} x_{1}^2 \quad x_{1} \quad 1 \quad y_{1}\\
x_{2}^2 \quad x_{2} \quad 1 \quad y_{2} \\
x_{3}^2 \quad x_{3} \quad 1 \quad y_{3}\end{array}\right)$
This is from Anton, Elementary Linear Algebra 9th Ed.
As seen here:
What does it mean to 'show that' coefficients are a solution of this system of linear equations?
I believe I have answered this question with my own answer below.
Thankyou.

A: Or do I just have to put this in the form:
$Xa=y$ where $a$ is vector with [a,b,c] in it?
If I put it in that form, is that simply demonstrating that we will get the respective linear equations? Maybe i'm thinking too hard and that's simply the response that is required because maybe the question is interrogating that you can identify that it's linear in a,b,c and to treat the x's as constants.


text:
Q: Farcry 3 randomly enters windowed mode For starters, whenever I face a tiger, game goes windowed mode. After that, whenever I press Z to use the camera (or to take it off) it also changes to windowed mode.
I've tried to set the camera key to the key next to 0, but when I press it, it still happens.
Is there a fix for that?

A: If I were to venture a guess, it sounds like your computer is communicating with another program, causing the other program to become the focus, forcing your game into windowed mode. You could try closing other programs, perhaps an overlay program such as Steam or Overwolf could cause this. There are any number of programs that actively listen for hotkeys, such as Skype or Teamspeak.

A: It was because I pressed once the windows key, and suddenly the game changed the mode to windowed (even if I set fullscreen with alt+enter, game still says it's in windowed mode).
I have to change it in the video settings.


text:
Q: Why Uncaught nc error appear at geocomplete bind function I have a google map with a input box to search location.  When I load the page I am getting the error at the console shown in image below. I checked and found out that the that error is coming from geocomplete().bind function. These are the codes I have tried. Can anybody help me why I am getting that error.
<div class="box-search">
    <input id="geocomplete" type="text" class="inputtxt-style -search" placeholder="Search Location">
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=1&libraries=places&callback=initialize" async defer></script>

<script src="https://maps.googleapis.com/maps/api/js?key=1&libraries=places&callback=initialize"
async defer></script>

<script type="text/javascript" src="assets/js/jquery.geocomplete.min.js"></script>
<script>
    function initialize()
    {
        //google map and marker code

        $("#geocomplete")
        .geocomplete()
        .bind("geocode:result", function(event, result){
        var searchLocation = result.geometry.location;
        var searchLatitude = searchLocation.lat();
        var searchLon = searchLocation.lng();
        var myLatlng = new google.maps.LatLng(parseFloat(searchLatitude),parseFloat(searchLon));
        mapSingle.panTo(myLatlng);
        });
    }
</script>


text:
Q: Visited nodes in Cypher I have a graph like this:
START root=node(0)
CREATE
(Dark { name:"dark" }),(Colors { name:"colors" }),(Blue { name:"blue" }),
(Indigo { name:"indigo" }),(Red { name:"red" }),(Orange { name:"orange" }),
(LightOrange { name:"lightorange" }),(Tangerine { name:"tangerine" }),
Dark-[:CHILD]->Colors,Blue-[:CHILD]->Colors,Indigo-[:CHILD]->Blue,
Red-[:CHILD]->Colors,Orange-[:CHILD]->Red,LightOrange-[:CHILD]->Orange,
Tangerine-[:CHILD]->Orange

It's essentially a tree, with some connections in between the branches.
Hence given an input of "dark","tangerine" and "indigo", I can get the most recent common ancestor, like so:
START a=node(*), b=node(*),c=node(*)
MATCH pa=a-[s:CHILD*]->x, pb=b-[s:CHILD*]->x,pc=c-[s:CHILD*]->x
WHERE a.name = 'dark' AND b.name = 'tangerine' AND c.name = 'indigo'
RETURN x
ORDER BY length(pa+pb+pc)
LIMIT 1

My question is, how do I get the nodes of the smallest set of tree branch(es), that can result in the ancestor? For example, the result for the above query can be "dark", "orange","red","colors","indigo".


text:
Q: Capacitive current leads, inductive lags, but how does this translate to voltage on an output? I'm really confused about the capacitive current leads the voltage, inductive current lags the voltage. The reason for this confusion is the graphs I've seen in different sources trying to explain this, the inconsistancy has really made me question everything I know about voltage and current.
One source used $$ V_R ; V_L ; V_C $$ to show that Vc leads i, VL lags i and VR will be in phase. Another source used V_S and showed the currents respectively leading/lagging the input voltage.
This probably sounds stupid, but it has confused me a lot now, is the voltage across the capacitor in phase with the voltage source, but the current through it is out of phase? Or is it something else?
In my scope readin, I have an RL circuit with the output voltage leading the input voltage, but in an RLC series circuit (below resonance when -X_C > X_L right?) I have a similar output with the output voltage leading the input.
When people say I_c leads V, is the V the voltage across the capacitor or the voltage source?
Edit
Firstly I really apprieciate the answers, all have been a lot of help and its helped me to understand the concept a lot more. I have still some doubts, particularly when it is applied to a real example. I made up an LCR circuit in series. I checked out the maths for frequencies at 4100Hz and 5500Hz (resonance was about 4.81kHz. At 4100Hz, the angle of impedance is \$-82^{\circ}\$, this is what I expected since the \$-X_C > X_L\$ giving \$\theta = \arctan(\frac{X_L - X_C}{R})\$ so \$\theta\$ is negative.I got the info from this site, the current/voltage plots are towards the bottom of the page
Similarly for 5500Hz, \$-X_C < X_L\$ and results in a postive angle of impedance ( \$75^{\circ}\$) as expected.
What I do not understand is how I have a negative angle of impedance, but the phase shift is positive and above resonance, a positive angle but negative impedance. Am I misunderstanding or should I indeed have a lag where it is leading and a lead where I have a lag in the readings below?

Or should I be taking this a step further and calculating the voltages across the components, as shown in the first example here? using this method, I get a positive angle of \$86^{\circ}\$, however I the capacitor voltage is greater than V across the inductor, which would surely result in a negative phase angle? Likewise, at 5530Hz, I calculate (using the same method) a phase angle of \$76^{\circ}\$, which \$V_L > V_C\$, which surely means a positive phase shift?

A: Imagine a capacitor with an existing, stable, unchanging voltage across it. It might be a DC power supply placed across the capacitor, for example, where it's been a long time and the capacitor has "charged up." In this case, there is no current because... well... there's no need for any. The circuit has reached equilibrium. It just sits there.
Now, you turn a knob and the DC power supply changes its voltage. The capacitor must also change, too. (You can't have a power supply with one voltage and a capacitor with a different voltage when they are tied together like this.) But it can't change instantly because the capacitor is a large reservoir of charge, in effect, and to change its voltage you must change that reservoir's "level of charge." To change that, you have to supply (or remove) some charge. But moving charge requires time and together, charge motion and time, you must have current to get there.
So, if you change the voltage then that must stimulate some charge to flow onto, or off of, the capacitor. If you change the voltage slowly, then the rate of change of charge in the capacitor's reservoir over time is less. If you change the voltage rapidly, then the rate of change of charge in the capacitor's reservoir must be more. To achieve a faster rate of change of voltage across the capacitor, you must supply a higher current in order to fill (or drain) the capacitor's storage of charge.
The voltage across a capacitor is: \$V=\frac{Q}{C}\$. So with the capacitance held fixed, to get a higher voltage \$V\$ you need more charge \$Q\$.
Now, when you look at the equation:
$$I = C\cdot \frac{\textrm{d}\:V}{\textrm{d}\:t}$$
You can see all that wonderful hand-waving tied up in a package with nice bow. The current has to be larger if the capacitor has a larger capacitance. Why? Because it is a bigger reservoir and it needs more charge to achieve the same voltage. The current has to be larger also if the rate of change of voltage is more. For reasons just discussed above. That equation puts it all in one place.
Now, what does this mean regarding lagging or leading currents and voltages? Well, take a look at a sine wave centered on \$y=0\$ with voltage on the \$y\$ axis. Then tell me at what value of \$y\$ is the rate of change of the sine wave at its most rapid. It will be when the voltage is itself at zero. In other words, the current into or out of the capacitor will have to be at its maximum value when the voltage across the capacitor is itself at zero (for the sine wave case, anyway.)
The only thing left to worry about is lagging vs leading, and which is which in the case of the capacitor. This is just a matter of sign. In the case of a capacitor, when the voltage is rapidly rising away from zero in the positive going direction, the conventional current into one side of the capacitor is also conventional current away from the other side. You want to look at this as a current "through" the capacitor, even though physical charges don't actually leap through the insulator of the capacitor. So the sign is taken as positive as the above equation suggests.
Now go back and look at those curves you mentioned. You will see that the shape of the current (which obeys all of the above discussion) through the capacitor will "look like" it is \$90^\circ\$ earlier than the voltage curve. You could also claim that it is \$270^\circ\$ later. But to keep things simple everything should be seen as \$-180^\circ \lt \theta \lt 180^\circ\$. (The special case of \$\theta = 180^\circ=-180^\circ\$ is reserved a special term: antiphase.)
So the current is said to "lead" voltage in a capacitor. Or else voltage is said to "lag" current in a capacitor. Either way means the same thing. That it happens to do so by exactly \$90^\circ\$ is only true when you aren't taking into account other "parasitics" such as Ohmic resistance in the wires. Resistors develop a voltage drop across them in strict accordance with the current through them. So when the voltage change attempts to cause a current to flow, the resistor immediately opposes this by developing a voltage drop across it hindering the voltage that is actually then applied to the capacitor. And this fact shifts the lead/lag calculation so that it is no longer \$90^\circ\$, anymore.
There's a lot of algebraic tools of the trade you learn to simplify the work you have to do, just like learning to perform long-hand multiplication is a trick that helps you multiply big numbers without having to perform lots and lots of additions, over and over. These tricks are based upon good theoretical ideas. But if you just learn them and apply them without really understanding where they come from, they will still work for you. Just like you don't need to understand why long-hand multiplication works in order to use it.

The capacitor is easier to describe because it works with attributes that are easier to imagine. We can count them. They are units of charge. An inductor works with equivalent units of charge, but as a matter of magnetism. These units are in Webers, instead of charge. And it's hard to "imagine" a Weber and count them (these are "volt-seconds," or \$\int V_t\:\textrm{d}t\$), for us normal folks. Some people have no problem. Others do. But these are a symmetrical unit for charge.
I'll do a short derivation to explain why, taken from an energy perspective (if there is a founding bedrock principle in physics it is the conservation of energy.) Let's follow here:
$$\begin{split}
W &= \frac{1}{2}\:C\: V^2\\\\
\textrm{d} W &= C\: V\:\textrm{d}V + \frac{1}{2}\: V^2\:\textrm{d}C\\\\
\frac{\textrm{d} W}{V} &= C\: \textrm{d}V + \frac{1}{2}\: V\:\textrm{d}C
\end{split}
\quad\leftrightarrow\quad
\begin{split}
W &= \frac{1}{2}\:L\: I^2\\\\
\textrm{d} W &= L\: I\:\textrm{d}I + \frac{1}{2}\: I^2\:\textrm{d}L\\\\
\frac{\textrm{d} W}{I} &= L\: \textrm{d}I + \frac{1}{2}\: I\:\textrm{d}L
\end{split}$$
noting,
$$\textrm{where } I=\frac{\textrm{d}Q}{\textrm{d}t}\textrm{ and } V=\frac{\textrm{d}W}{\textrm{d}Q}\textrm{ and d}L=0 \textrm{ and d}C=0$$
resulting in,
$$\begin{split}
\frac{\textrm{d} W}{\frac{\textrm{d}W}{\textrm{d}Q}} &= C\: \textrm{d}V \\\\
\frac{\textrm{d} W}{\textrm{d}W}\textrm{d}Q &= C\: \textrm{d}V \\\\
\textrm{d} Q &= C\: \textrm{d}V\\\\
\int\textrm{d} Q &= \int C\: \textrm{d}V\\\\
Q &= C\: V
\end{split}
\quad\leftrightarrow\quad
\begin{split}
\frac{\textrm{d} W}{\frac{\textrm{d}Q}{\textrm{d}t}}&= L\: \textrm{d}I\\\\
\frac{\textrm{d} W}{\textrm{d}Q}\textrm{d}t &= L\: \textrm{d}I\\\\
V\textrm{d}t &= L\: \textrm{d}I\\\\
\int V\textrm{d}t &= \int L\: \textrm{d}I\\\\
V\:t &= L\: I
\end{split}$$
And there you are. Countable things on the left. But weird units on the right. Volt-seconds (Webers) are to inductors as Coulombs of charge are to capacitors.
Another bit of slight of hand from the above can be had, as well:
$$\begin{split}
\textrm{d} Q &= C\: \textrm{d}V\\\\
\frac{\textrm{d} Q}{\textrm{d} t} &= C\: \frac{\textrm{d}V}{\textrm{d} t}\\\\
I &= C\: \frac{\textrm{d}V}{\textrm{d} t}
\end{split}
\quad\leftrightarrow\quad
\begin{split}
V\textrm{d}t &= L\: \textrm{d}I\\\\
\frac{V\textrm{d}t}{\textrm{d} t} &= L\: \frac{\textrm{d}I}{\textrm{d} t}\\\\
V &= L\: \frac{\textrm{d}I}{\textrm{d} t}
\end{split}$$
Sorry about the diversion. But I thought it may help some (and you?)

A: The "lag" and "lead" are relative to the currents and voltages at the terminals of the component.  Let us start with the plain basic differential equations for each:
$$i(t) = C{d v(t)\over dt}$$ and
$$v(t) = L{d i(t)\over dt}.$$
The first equation says that if  the voltage is proportional to \$\sin(\omega t)\$ the current is proportional to \${{d \sin(\omega t)}\over d t} \propto \cos(\omega t)\$ and the current leads the voltage.
The second equation says that if  the current is proportional to \$\sin(\omega t)\$ the voltage is proportional to \${{d \sin(\omega t)}\over d t} \propto \cos(\omega t)\$ and the voltage leads the current, or the current lags the voltage.
These differential equations are universal for any voltage and current at the component, also for distorted currents and voltages.
What happens in a circuit depends on the connections and any circuit can be analysed by following these two simple rules with normal circuit analysis.
For completeness for sinusoidal currents and voltages (and edited as per comment by @user287001) :
$$i(t) = I\cos(\omega t) ={C{{d V\sin(\omega t)}\over d t}} = \omega C\cdot V\cos(\omega t) $$ and
$$v(t) = V \cos(\omega t) = {L{{d I \sin(\omega t)}\over d t}} = \omega L \cdot I\cos(\omega t)$$ proving that \$ X_L = \omega L\$ and \$X_C = {1\over{\omega C}}\$.
(Oops?  Where does the \$\sqrt{-1}\$ fit in? :-)

A: When one says "the current in a resistor is in phase with the voltage" he thinks only a resistor that is connected to an AC voltage supply (ideal or not, no matter). He does not think a filter, amp or other circuit that has an input voltage and the resulted output voltage. The only thing that he tells is "the changes in the current follow the changes in the voltage without any timing difference, the minimum or the maximum are in both at the same time"
When one says that inductive current lags the voltage, he thinks an AC voltage source and an inductor, no inputs and no outputs. He tells that the current is somehow late when compared to the voltage. The voltage can already have passed its peak and is falling, but the current is still growing. If the voltage is sinusoidal, then the current is excactly 1/4 of the cycle duration behind the voltage or as we say "lagging 90 degrees "
In capacitor the scenario is opposite. The current seems somehow to rush before the voltage. If the voltage is sinusoidal, then the current is sinusoidal, too and its timing is exactly 1/4 cycle in front of the voltage.
These can be expressed exactly in math. We have differential equations for arbitary changing voltages and currents. The complex phasor and impedance notations are derived from those differential equations for sinusoidal voltages and currents.
In filtering circuits that have input and output voltages, one can compare the timing difference between the voltages. If the input is sinusoidal and the circuit makes no distortion, the output is also sinusoidal, but often its timing is in front (=leading) or behind (=lagging) the timing of the input voltage and the difference does not change as long as the frequency doesn't change. The lead or lag is usually expressed as degrees and called "phase shift".
How much a filtering circuit causes phase shift at a given frequency? That can be solved by the means of the "circuit analysis".
Your example RL filter where R is between the input and output, the phase shift is positive. It means thet the output voltage is in front of the input voltage. The filter cause leading. How much - that depends of the frequency and the component values.
ADDENDUM the phase shift calculation between resistor's and inductor's voltages in the RL series circuit
Let's assume voltage V1 to be sinusoidal => the current I is sinusoidal, the complex phasors can be used.

This calculation shows a basic fact that nearly all experienced electronics enthusiasts know without any calculations.
A little more useful would be to continue and find the phase shift and amplitude ratio between V1 and VL because VL can be considered as the output voltage of a RL filter.

A: Start by imagining a capacitor connected to a voltage source.  The voltage of the voltage source doesn't change no matter what load you present to it, including that load being a capacitor.  The only question is what the current will be.
The current thru a capacitor is always the derivative of the voltage across it.  That's what capacitors do.  There is one degree of freedom, which is how much current you get for any particular voltage slope.  That scale factor to go from Volts/second to Amps is the capacitance.  In fact, one Farad is defined:
  Farad = Amp / (Volt/second) = Amp second / Volt
Conversely, the current thru a capacitor (as we are trying to find above) is:
  Amps = Farad Volt / second
Therefore, if you have a 1 F capacitor in the setup described above, and the voltage is ramped up by 1 V/s, then the capacitor will draw 1 A.
So what does this have to do with leading and lagging voltage?  Using the terms "leading" and "lagging" implies a periodic waveform.  From Fourier analysis we know that those can be decomposed into a series of sines.  It is therefore useful to consider what happens when the voltage source in our example produces a sine voltage.
The derivative of a sine is a cosine.  The capacitor current will be a cosine while the voltage across it is a sine.  Since a cosine can also be thought of as a sine with -90° phase shift, we can say that in the case of a sine, the current thru a capacitor leads the voltage across it by 90°.
Unfortunately, especially for beginners, it is usually not pointed out that the signals are assumed to be sinusoids.  The current thru a cap doesn't "lead" the voltage for arbitrary signals.  This is a special case that applies only to sinusoids.
Think of the voltage being a triangle wave instead of a sine.  The current thru the cap will be two separate fixed values, one for each of the two fixed slopes of the triangle.  In other words, the current will be a square wave.
Now try putting a square wave across the cap.  The equations blow up since the derivative at the steps are infinite.  In theory, with a ideal voltage source and ideal capacitor, the current really would be infinite.  However, in real life the non-idealness will get in the way, and the voltage steps will be somewhat smushed out, and the current will be high blips at the edges.
Inductors work similarly, except that the voltage is the derivative of current, instead of the other way around.  If you do the math with a fixed sine voltage, you will see that the current is -cosine, or has a +90° phase shift from the voltage, or in other words lags the voltage by 90°.  Again, this only applies to sinusoids.


text:
Q: How to update price of all products in woocommerce? I have almost 1600 products in my store. I want to increase all the the product of my store double of the current price. And want to give all products a discount of 25% after doubling the price. Doing one by one is actually so lengthy. Is there any way of achieving this once at a time?

A: You'll need some way to activate this function:
function reduce_all_products_price() {
    $products = wc_get_products(['limit' => -1]);
    foreach($products as $product) {
        $new_full_price = floatval($product->get_regular_price('edit')) * 2;
        $product->set_price($new_full_price);
        $product->set_sale_price($new_full_price * 0.75);
    }
}

I'm using the 'sale price' to store the value with discount, because i think it makes more sense.
There are several ways to activate your function, but maybe the easiest would be to add a hook to admin_init and check for some parameter in URL.
add_action('admin_init', function () {
    if (isset($_GET['discount-everybody']) && $_GET['discount-everybody'] == 'true') {
        reduce_all_products_price();
    }
});

Then you have to be logged in to wp-admin and access yoursite.com/wp-admin/index.php?discount-everybody=true
Be careful not to do this twice.


text:
Q: Changing Visual States in a ContentDialog I am having trouble getting the VisualStateManager to switch states in a custom ContentDialog. I have included a self-contained example where the XAML page defines two rectangles with different colours and some visual states to adjust the visibility of the two rectangles. The idea is that when the button is pressed the rectangle that was previously invisible is now visible. However, what actually happens is that VisualStateManager::GoToState() returns false and no visual state change occurs.
Am I doing something obvious wrong here? I believe the <VisualStateManager.VisualStateGroups> element is in the correct place (being the child of the root element's child) but I'm still unable to get this scenario to work.
The XAML file:
<ContentDialog
    x:Class="Test.MyContentDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Test"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    MaxWidth="750"
    MaxHeight="550"
    Background="Black">

    <Grid Width="500" Height="210" Margin="0,25,0,0">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup>
                <VisualState x:Name="BlueVisibleState">
                    <VisualState.Setters>
                        <Setter Target="BlueRect.Visibility" Value="Visible" />
                        <Setter Target="RedRect.Visibility" Value="Collapsed" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="RedVisibleState">
                    <VisualState.Setters>
                        <Setter Target="BlueRect.Visibility" Value="Collapsed" />
                        <Setter Target="RedRect.Visibility" Value="Visible" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>

        <Rectangle x:Name="BlueRect" Width="50" Height="50" Fill="Blue" />
        <Rectangle x:Name="RedRect" Width="50" Height="50" Fill="Red" />

        <Button Content="Change Style" Width="500" Height="30" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="Button_Click"/>
    </Grid>
</ContentDialog>

And the code-behind:
namespace Test
{

MyContentDialog::MyContentDialog()
{
    InitializeComponent();
    VisualStateManager::GoToState(this, BlueVisibleState->Name, false);
}

void MyContentDialog::Button_Click( Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e )
{
    VisualStateManager::GoToState(this, RedVisibleState->Name, true);
}

} // namespace Test

A: I made a demo using your codes and reproduced the problem. It seems like the VisualStateManager.GoToState doesn't work with Content Dialog.
But it works well in a UserControl. So as a workaround, you can create a new user control and wrap it with your content dialog:
New user control xaml (RootDialogControl.xaml):
<UserControl
    x:Class="VisualStatesSampleCpp.RootDialogControl"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:VisualStatesSampleCpp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300"
    d:DesignWidth="400">

<Grid>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroup>
            <VisualState x:Name="BlueVisibleState">
                <VisualState.Setters>
                    <Setter Target="BlueRect.Visibility" Value="Visible" />
                    <Setter Target="RedRect.Visibility" Value="Collapsed" />
                </VisualState.Setters>
            </VisualState>
            <VisualState x:Name="RedVisibleState">
                <VisualState.Setters>
                    <Setter Target="BlueRect.Visibility" Value="Collapsed" />
                    <Setter Target="RedRect.Visibility" Value="Visible" />
                </VisualState.Setters>
            </VisualState>
        </VisualStateGroup>
    </VisualStateManager.VisualStateGroups>
    <StackPanel>
        <Rectangle x:Name="BlueRect" Width="50" Height="50" Fill="Blue" />
        <Rectangle x:Name="RedRect" Width="50" Height="50" Fill="Red" />
        <Button Content="Change Style" Width="500" Height="30" HorizontalAlignment="Center" VerticalAlignment="Bottom" Click="Button_Click"/>
    </StackPanel>
</Grid>

Code-behind (RootDialog.xaml.cpp):
RootDialogControl::RootDialogControl()
{
    InitializeComponent();
    VisualStateManager::GoToState(this, BlueVisibleState->Name, false);
}

void VisualStatesSampleCpp::RootDialogControl::Button_Click(Platform::Object^ sender, Windows::UI::Xaml::RoutedEventArgs^ e)
{
    VisualStateManager::GoToState(this, RedVisibleState->Name, false);
}

And wrap the user control in content dialog:
<ContentDialog
    x:Class="VisualStatesSampleCpp.RootDialog"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:VisualStatesSampleCpp"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    Title="TITLE"
    PrimaryButtonText="Button1"
    SecondaryButtonText="Button2"
    PrimaryButtonClick="ContentDialog_PrimaryButtonClick"
    SecondaryButtonClick="ContentDialog_SecondaryButtonClick">

<Grid Width="500" Height="210" Margin="0,25,0,0">
    <local:RootDialogControl/>
</Grid>


text:
Q: Record and upload audio and video files to the server in android In my app I need to record the audio or video in less size and need to save it to the media and send into the server. What is the best approach to do this?Without using any thirdparty libraries.Please guide me.Thanks in advance.

A: The best approach is to make API on server and just pass your parameters to that API. main functionality will be performed by API.

A: Sending the file to the server you will need an upload URL and the file name of the recording, here is the code
Explanation of the code,

*

*Open the URL connection and get the stream to which the data will be written.

*Specify a max buffer which will hold the stream information.
3.Read bytes from the file and write it to the output stream.
4.Get the response and do the necessary actions accordingly.
public boolean uploadFileNew(String sourceFileUri) {
        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        File upFile=null;

        try {
            final File root = new File((Environment.getExternalStorageDirectory() + File.separator + "DIR_NAME"));

            root.mkdirs();
            final String tmp[] = sourceFileUri.split(File.separator);
            final String fname = tmp[tmp.length-1];
            upFile = new File(root, fname);

                FileInputStream fileInputStream = new FileInputStream(upFile);

                URL url = new URL("YOUR_URL");
                connection = (HttpURLConnection) url.openConnection();

                // Allow Inputs & Outputs.
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setUseCaches(false);

                // Set HTTP method to POST.
                connection.setReadTimeout(10000);
                connection.setConnectTimeout(15000);
                connection.setRequestMethod("POST");

                connection.setRequestProperty("Connection", "Keep-Alive");

                connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);

                outputStream = new DataOutputStream(connection.getOutputStream());
                outputStream.writeBytes(twoHyphens + boundary + lineEnd);

                outputStream.writeBytes("Content-Disposition: form-data; typ=\""+1+"\"; name=\""+fname+"\";filename=\"" + fname + "\"" + lineEnd);
                outputStream.writeBytes(lineEnd);

                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // Read file
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {
                    outputStream.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);
                }

                outputStream.writeBytes(lineEnd);
                outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                int serverResponseCode = connection.getResponseCode();
                String serverResponseMessage = connection.getResponseMessage();
                InputStream in = connection.getInputStream();

                byte data[] = new byte[1024];
                int counter = -1;

                in.close();

                if (serverResponseCode == 200) {
                    Log.d("uploadFile", "File Upload Complete.");
                }

                fileInputStream.close();
                outputStream.flush();
                outputStream.close();

            }
        } catch (Exception ex) {
            Log.d("uploadFile", "File Upload Error:" + ex.toString());

            return false;

        }

        return true;
    }


text:
Q: Generating permutations using Bitmasking I was answering some programming problems in the internet and this problem interests me. The problem is defined as follows:

This code prints all the permutations of the string lexicographically. Something is wrong with it. Find and fix it by modifying or adding one line!

Input:
The input consists of a single line containing a string of lowercase characters with no spaces in between. Its length is at most 7 characters, and its characters are sorted lexicographically.
Output:
All permutations of the string printed one in each line, listed lexicographically.
def permutations():
global running
global characters
global bitmask
if len(running) == len(characters):
    print(''.join(running))
else:
    for i in xrange(len(characters)):
        if ((bitmask>>i)&1) == 0:
            bitmask |= 1<<i
            running.append(characters[i])
            permutations()
            running.pop()

raw = raw_input()
characters = list(raw)
running = []
bitmask = 0
permutations()

Can somebody answer it for me and explain how it works? I am not really familiar in the applications of bitmasking. Thank you.

A: You should make the bitmask bit 0 again by adding the line:
bitmask ^= 1<<i

Code:
def permutations():
    global running
    global characters
    global bitmask
    if len(running) == len(characters):
        print(''.join(running))
    else:
        for i in xrange(len(characters)):
            if ((bitmask>>i)&1) == 0:
                bitmask |= 1<<i
                running.append(characters[i])
                permutations()
                bitmask ^= 1<<i  #make the bit zero again.
                running.pop()

raw = raw_input()
characters = list(raw)
running = []
bitmask = 0
permutations()

Explanation:
Bitmask is an integer that is treated as a string of bits. In your case the length of this string is equal to the length of the input string.
Each position in this string signifies whether the corresponding character has already added in the partially built string or not.
The code works by building a new string starting from an empty string. Whenever any character is added, the bitmask records it. Then the string is sent deeper into recursion for further addition of characters. When the code returns from recursion, then the added character is to be removed and the bitmask value has to be made to its original value.
More information about masking can be found here.http://en.wikipedia.org/wiki/Mask_%28computing%29
EDIT:
Say the input string is "abcde" and the bitmask at any point in the execution of the code is "00100". This means that only the character 'c' has been added so far to the partially built string.
Hence we should not add the character 'c' again.
The "if" condition ((bitmask >> i) & 1) == 0 checks whether the i'th bit in bitmask has been set, ie., whether the i'th character has already been added in the string. If it is not added, only then the character gets appended, otherwise not.
If the bit operations are new to you then I suggest you look up on this topic on the internet.


text:
Q: Getting the height of a DIV with jQuery does not work properly So i tried to find a solution myself, but i couldn't find a topic with a solution that worked for me, because i have special prerequisites.
My Problem is the following:
I have a sticky DIV element on the left, put in another DIV Element with a
fixed height, because the sticky effect didn't work without fixed height.
On the right are many elements which are in a DIV Container as well. This
Container gets its height by the number of elements.
The optimal way would be, that the sticky element stops after the DIV Container with all his content elements is done. Yet because i have to set a fixed height for the Container of the sticky element, it keeps on taking its full height as white space before there can be any other content again.
I hope it wasn't explained to bad.

alert("The height is " + $("#ProductContainer").height());
#StickyContainer {
  float: left;
  height: 4000px;
  width: auto;
}

.sidebar {
  top: 0px;
  float: left;
  height: 400px;
  width: 200px;
  padding-left: 10px;
  padding-top: 20px;
  border: 2px solid black;
  margin: 20px 10px 0px 5px;
  position: -webkit-sticky;
  position: sticky;
}

.content {
  float: left;
  width: 200px;
  height: 300px;
  padding: 10px;
  margin-top: 20px;
  margin-left: 5px;
  border: 2px solid red;
}

#Test {
  margin-top: 20px;
  width: 100%;
  height: 100px;
  border: 2px solid blue;
}

    This is the sticky sidebar

    One of many boxes

    Here are 2, but in reality there are more than 10

 Here is the next content

Note: Run in fullscreen, otherwise the #ProductContainer will be under the sidebar anyway.
I took many approaches, one was to take the height of the #ProductContainer with jQuery, then set the result as the new height for the #StickyContainer.
Sadly it returns the height 0.
Didn't get much further because of the result. I tried much more of the stuff i found on StackOverflow, but nothing seemed to work. Not only with JavaScript, but also with HTML since the problem seems to be in the ProductContainer that is not embracing the content properly.
However, even if its just a simple stupid mistake of mine, i am thankful for any sort of help.

A: the content element hast a float and makes the ProductContainer feels nothing inside.
you have to use a clearfix class on parent.
.clearfix:after {
    content: " ";
    display: block;
    clear: both;
}

cross platform, compatible IE6 +, Chrome, Safari, Firefox, you name it!
.clearfix:after {
    content: ".";
    display: block;
    clear: both;
    visibility: hidden;
    line-height: 0;
    height: 0;
}

.clearfix {
    display: inline-block;
}

html[xmlns] .clearfix {
    display: block;
}

* html .clearfix {
    height: 1%;
}

and give the class to parent


text:
Q: jQuery Mobile: Style Header of Table using ThemeRoller Theme Is it possible to style the THEAD > TR in a standard HTML Table to the style described by the ThemeRoller Header??

A: OK so its not that difficult as it turns out..
Just need to apply the
ui-bar-x

class to the TR and its all shiny and jQM'd


text:
Q: I've been get error code:1064 sintaxys mysql workbench I'been watching this error but i don't find nothing
CODE:
SELECT sv.id, sv.service_state_id as sstId, sha.id, sha.address, sha.user_guide as guide, sha.users_id, sst.id
FROM deliver_db_v2.service as sv
inner join deliver_db_v2.service_has_address as sha
inner join deliver_db_v2.service_state as sst
on sv.id = sha.users_id
on sv.sstId = sst.id;

Error:

SELECT sv.id, sv.service_state_id as sstId, sha.id, sha.address, sha.user_guide as guide, sha.users_id, sst.id FROM deliver_db_v2.service as sv inner join deliver_db_v2.service_has_address as sha inner join deliver_db_v2.service_state as sst on sv.id = sha.users_id on sv.sstId = sst.id    Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'on sv.sstId = sst.id' at line 6    0.094 sec

A: You have misplaced the ON clause of the first inner join.
You can do:
SELECT
  sv.id, sv.service_state_id as sstId, sha.id, sha.address,
  sha.user_guide as guide, sha.users_id, sst.id
FROM deliver_db_v2.service as sv
inner join deliver_db_v2.service_has_address as sha on sv.id = sha.users_id
inner join deliver_db_v2.service_state as sst on sv.sstId = sst.id;

Each INNER JOIN must have its own ON clause.


text:
Q: Problema de ruta "src" para cargar imagen(archivo), wordpress, error 404, Estoy creando un tema para wordpress y tengo un problema con las imágenes que puse en el archivo footer.php. Como saben el header y footer de la pagina web se muestra en todas las paginas y entradas.
El problema es: esas imágenes de footer.php solo se muestran en la portada; ósea  cuando elijo como portada una de las paginas, solo en esa pagina se muestra dichas imágenes.
Todo el contenido del footer como textos, etc... se muestran normal; pero las imágenes son el problema.
Creo que es un problema de ruta en el "src" de la imagen; así que  mi pregunta es, ¿Que diferencia hay entre la portada y una pagina(no portada)?, si sabemos que las paginas y portada se construyen en el mismo archivo page.php.
La primera sospecha que tuve es que la función is_front_page() que sirve para mostrar el contenido solo en la portada; este siendo aplicado junto a las imágenes; pero no es el caso.
esta es la ruta de mi imagen src="wp-content/themes/temacreado/imagenes/icono.png" que esta dentro del archivo footer.php
seria absurdo poner un montón de código sin utilidad, porque creo que el problema es la ruta
¿Alguna idea?

A: Respuesta ampliada (gracias @JefferzonBol por tu aporte):

Como suele suceder, hay varias funciones y opciones que pueden dar una respuesta correcta a esta pregunta. Una solución posible es conseguir la ruta absoluta del Wordpress o bien del tema activo y luego corregir la ruta de las imagenes acorde a eso.
Funciones disponibles y sus parámetros:

*

*Función get_bloginfo($show): Muestra la información del parametro $show, que puede tener muchos valores predefinidos distintos, que encontrarás en su documentación. En esta respuesta nos centraremos solo en dos:

*

*'wpurl': Éste parámetro aplicado a esta función nos devuelve una URL con la ruta que está establecida dentro del admin de Wordpress, en el menú Opciones->General en el campo correspondiente a URL del Wordpress.

*'template_url': Éste parámetro nos devuelve una URL con la ruta del tema activo en Wordpress.

La forma de forzar la salida de esta función es usando echo. Por ejemplo si sólo queremos la ruta del Wordpress:
<php echo get_bloginfo('wprul'); ?>

o bien si queremos toda la ruta hasta el tema activo:
<php echo get_bloginfo('template_url'); ?>

Por otra parte, si queremos ahorrarnos el echo podemos usar directamente esta otra función:

*Función bloginfo($show): Hace casi lo mismo que get_bloginfo($show) pero haciendo un echo directamente de su resultado.

De hecho su código en wp-includes/general-template.php es el siguiente:
function bloginfo( $show = '' ) {
    echo get_bloginfo( $show, 'display' );
}

Es por ello que la forma de usarlo no necesita el echo, sino simplemente:
<?php bloginfo('wpurl'); ?>

Hay que tener en cuenta que esta función bloginfo() ejecuta el echo directamente, por lo tanto no sirve de nada asignarla a otra variable de trabajo en caso de necesidad, pues ejecutaria el echo y no seria asignada.
Por lo tanto, conociendo estas dos funciones y sus dos posibles parámetros relacionados con las rutas a las imagenes, tenemos hasta cuatro soluciones posibles según como sea el escenario para aplicarlas.
Aquí tan solo mostraré la solución expuesta en la respuesta inicial, dejando las otras opciones como alternativas para quien las quiera probar y usar por los motivos que crea convenientes.
Respuesta inicial:
Para solucionar tu problema una solución posible es agregar la ruta absoluta de tu Wordpress a la ruta absoluta de las imagenes.
Para descubrir la ruta absoluta de tu Wordpress con código PHP se usa esta función que pertenece a WP:
get_bloginfo('wpurl')

Esta función devuelve la ruta que está dentro del admin de Wordpress, en el menú Opciones->General en el campo correspondiente a URL del Wordpress.
Pasos:
Primero si el valor de get_bloginfo('wpurl') no termina en / deberas agregarlo a la ruta de la imagen para que también sea absoluta, es decir, debes cambiar esto:
src="wp-content/themes/temacreado/imagenes/icono.png"

por esto:
src="/wp-content/themes/temacreado/imagenes/icono.png"

Y segundo, agrega <?php echo get_bloginfo('wpurl'); ?> al principio del atributo  src= de la imagen. Para que al final quede así:
src="<?php echo get_bloginfo('wpurl'); ?>/wp-content/themes/temacreado/imagenes/icono.png"

Con esto deberia funcionarte en cualquier instalación de Wordpress que vaya a incluir tu tema sea cual sea la ruta que escojan en la URL del Wordpress dentro del menú Opciones->General del admin.


text:
Q: Giving maximum height and width equally to canvas in HTML/CSS I am trying to set a layout for my web app. I want to have 2 canvases to fill most of the window and 4 image buttons at the bottom. Here is what I am trying to achieve:

But I get it all screwed in the browser. The canvas are small! No matter what I put as height or width of the dives or the canvas itself in the CSS file. I want them to be be ideally 800x600 and resize with the same ratio if the window is being resized.

Here are my HTML and CSS:

body {
  margin: 0;
}

header {
  margin: 0;
  background-color: #DC0A2F;
  height: 50px;
}

header img.logo {
  width: 150px;
  height: auto;
  padding: 13px 13px 0px 13px;
}

header a {
  color: white;
  text-decoration: none;
  float: right;
  padding: 15px;
  font-family: Consolas;
  font-weight: revert;
}

header a:hover {
  padding-top: 16px;
}

html,
body {
  height: 100%;
}

main {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  height: 90vh;
}

main.index {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  color: #888888;
}

main img.menu {
  width: 250px;
  height: auto;
  padding: 50px;
}

table {
  font-size: 130%;
}

th {
  background-color: #888888;
  border-color: white;
}

td {
  background-color: white;
  border-bottom: solid 1px #888888;
  border-right: solid 1px #888888;
}

img.index {
  width: 400px;
  height: auto;
}

.ergebniss {
  margin: 50px;
}

svg.header {
  width: 125px;
  height: 30px;
  margin-top: 10px;
}

.vorschau {
  margin: 100px;
}

canvas{ border: 1px solid black; background-color: red;}

.footPreviewContainer {
  height: 800px;
  text-align: center;
}

#previewWrapper {
  display: table;
  table-layout: fixed;
  width: 100%;
  height: auto;
  background-color: antiquewhite;
}

#previewWrapper div {
  display: table-cell;
  height: auto;
}

#leftCanvas #rightCanvas {
  height: 800px;
  width: 600px;
  border: 1px solid #cccccc;
  background-color: #DC0A2F;
}

.previewButtons {
  text-align: center;
}

  <title>WebSocket Echo Client</title>
  <link rel="stylesheet" type="text/css" href="style.css">

    Herunterfahren
    Neustart

    <canvas id="leftCanvas"></canvas>
    <canvas id="rightCanvas"></canvas>

A: The easiest solution is to use display:flex; on the preview container and set the height using vh (view height) units. The defaults will cause the children canvases to stretch to fill the height, and you can then choose how to align them. They are set to justify-content: space-around; in the below snippet which evenly divides any free space on both sides of the children elements.
#previewWrapper {
  height: 85vh;
  display: flex;
  justify-content:space-around;
}

canvas {
  width: 46vw;
}

body {
  margin: 0;
}

header {
  margin: 0;
  background-color: #DC0A2F;
  height: 50px;
}

header img.logo {
  width: 150px;
  height: auto;
  padding: 13px 13px 0px 13px;
}

header a {
  color: white;
  text-decoration: none;
  float: right;
  padding: 15px;
  font-family: Consolas;
  font-weight: revert;
}

header a:hover {
  padding-top: 16px;
}

html,
body {
  height: 100%;
}

main {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  height: 90vh;
}

main.index {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  color: #888888;
}

main img.menu {
  width: 250px;
  height: auto;
  padding: 50px;
}

table {
  font-size: 130%;
}

th {
  background-color: #888888;
  border-color: white;
}

td {
  background-color: white;
  border-bottom: solid 1px #888888;
  border-right: solid 1px #888888;
}

img.index {
  width: 400px;
  height: auto;
}

.ergebniss {
  margin: 50px;
}

svg.header {
  width: 125px;
  height: 30px;
  margin-top: 10px;
}

.vorschau {
  margin: 100px;
}

canvas{ border: 1px solid black; background-color: red;}

.footPreviewContainer {
  height: 800px;
  text-align: center;
}

#previewWrapper {
  height: 85vh;
  display: flex;
  justify-content:space-around;
}

canvas {
  width: 46vw;
 }

  <title>WebSocket Echo Client</title>
  <link rel="stylesheet" type="text/css" href="style.css">

    Herunterfahren
    Neustart

    <canvas id="leftCanvas"></canvas>
    <canvas id="rightCanvas"></canvas>

A: You only have to add a bit css. I add it directly to style inline, like this you can fix it easily

    <canvas id="leftCanvas" style="height:100%;width:800px;"></canvas>
    <canvas id="rightCanvas" style="height:100%;width:800px;"></canvas>

The first thing is to fix the height of the previewWrapper. And then width in for the canvas.

body {
  margin: 0;
}

header {
  margin: 0;
  background-color: #DC0A2F;
  height: 50px;
}

header img.logo {
  width: 150px;
  height: auto;
  padding: 13px 13px 0px 13px;
}

header a {
  color: white;
  text-decoration: none;
  float: right;
  padding: 15px;
  font-family: Consolas;
  font-weight: revert;
}

header a:hover {
  padding-top: 16px;
}

html,
body {
  height: 100%;
}

main {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  height: 90vh;
}

main.index {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  color: #888888;
}

main img.menu {
  width: 250px;
  height: auto;
  padding: 50px;
}

table {
  font-size: 130%;
}

th {
  background-color: #888888;
  border-color: white;
}

td {
  background-color: white;
  border-bottom: solid 1px #888888;
  border-right: solid 1px #888888;
}

img.index {
  width: 400px;
  height: auto;
}

.ergebniss {
  margin: 50px;
}

svg.header {
  width: 125px;
  height: 30px;
  margin-top: 10px;
}

.vorschau {
  margin: 100px;
}

canvas{ border: 1px solid black; background-color: red;}

.footPreviewContainer {
  height: 800px;
  text-align: center;
}

#previewWrapper {
  display: table;
  table-layout: fixed;
  width: 100%;
  height: auto;
  background-color: antiquewhite;
}

#previewWrapper div {
  display: table-cell;
  height: auto;
}

#leftCanvas #rightCanvas {
  height: 800px;
  width: 600px;
  border: 1px solid #cccccc;
  background-color: #DC0A2F;
}

.previewButtons {
  text-align: center;
}

  <title>WebSocket Echo Client</title>
  <link rel="stylesheet" type="text/css" href="style.css">

    Herunterfahren
    Neustart

    <canvas id="leftCanvas" style="height:100%;width:800px;"></canvas>
    <canvas id="rightCanvas" style="height:100%;width:800px;"></canvas>


text:
Q: Redmine: extend controller action in plugin Need some help in plugin development.
I've created hook in user/edit form view, added ballance_amount to form and have "ballance_amount"=>"1".
How can I extend default update action in user controller?
In base.class_eval do I've added alias_method_chain :update, :ballance
In InstanceMethods:
def update_with_ballance
    ballance.amount = params[:user][:ballance_amount].to_f #I have ballance association
end

And get this:
NameError (undefined local variable or method `params' for #<User:0x007f972e9379d0>):
app/controllers/users_controller.rb:144:in `update'

How can I fetch params?

A: You should be able to make use of the mass-assignment code in the Redmine itself. Line 135 in the UsersController should handle provide you with a simple entry point for your extension, if balance_amount is considered a safe_attribute. To achieve that, add a patch like the following to the User model:
module RedmineBalancePlugin::UserPatch
  def self.included(base)
    base.class_eval do
      safe_attributes 'balance_amount'

      include InstanceMethods
    end
  end

  module InstanceMethods
    # This method is indirectly called when creating or updating a User
    def balance_amount=(amount)
      balance.amount = amount
    end

    # This could be useful in your view patch, but maybe not
    def balance_amount
      balance.amount
    end
  end
end

User.send(:include, RedmineBalancePlugin::UserPatch)

If this example does not help, it would be helpful, if you could provide more code fragments - e.g. the complete patch to the UsersController, to make it easier to reproduce and analyse the issue.


text:
Q: Pandas: create multiple aggregate columns and merge multiple data frames in an elegant way I am using the following code to create a few new aggregated columns based on the column version. Then merged the 4 new data frames.
new_df = df[['version','duration']].groupby('version').mean().rename(columns=lambda x: ('mean_' + x)).reset_index().fillna(0)

new_df1 = df[['version','duration']].groupby('version').std().rename(columns=lambda x: ('std_' + x)).reset_index().fillna(0)
new_df2 = df[['version','ts']].groupby('version').min().rename(columns=lambda x: ('min_' + x)).reset_index().fillna(0)
new_df3 = df[['version','ts']].groupby('version').max().rename(columns=lambda x: ('max_' + x)).reset_index().fillna(0)

new_df3

import pandas
df_a = pandas.merge(new_df,new_df1, on = 'version')
df_b = pandas.merge(df_a,new_df2, on = 'version')
df_c = pandas.merge(df_b,new_df3, on = 'version')
df_c

The output looks like below:
    version  mean_duration  std_duration    min_ts                max_ts
0   1400422  451                1               2018-02-28 09:42:15   2018-02-28 09:42:15
1   7626065  426                601             2018-01-25 11:01:58   2018-01-25 11:15:22
2   7689209  658                473             2018-01-30 11:09:31   2018-02-01 05:19:23
3   7702304  711                80              2018-01-30 17:49:18   2018-01-31 12:27:20

The code works fine, but I am wondering is there a more elegant/clean way to do this? Thank you!

A: Using functools reduce modify your result (merge)
import functools
l=[new_df1,new_df3,new_df3]
functools.reduce(lambda left,right: pd.merge(left,right,on=['version']), l)

Or let us using agg recreate what you need
s=df.groupby('version').agg({'duration':['mean','std'],'ts':['min','max']}).reset_index()

s.columns=s.columns.map('_'.join)


text:
Q: GCP Dataproc Runtime error in new version While I am using Dataproc "2.0 (Debian 10, Hadoop 3.2, Spark 3.1)" I am getting below error. But working fine in "1.4 (Debian 10, Hadoop 2.9, Spark 2.4)". Anyone have idea why this error is coming?
    Traceback (most recent call last):
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/worker.py", line 604, in main
    process()
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/worker.py", line 594, in process
    out_iter = func(split_index, iterator)
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2916, in pipeline_func
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 2916, in pipeline_func
  File "/usr/lib/spark/python/lib/pyspark.zip/pyspark/rdd.py", line 418, in func
  File "./comint_ml_scores-0.0.1-py3.8.egg/scores_eng/eng_nlp_helper.py", line 529, in enrichNLPRawJson_ForAmazonENG
    sentencesCount, totalsentences = getGrammarCount_ForAmazonENG(bulletFeatures, productDescription, richContentText, brandName, country)
  File "./comint_ml_scores-0.0.1-py3.8.egg/scores_eng/copy_quality_amazon_ENG.py", line 34, in getGrammarCount_ForAmazonENG
    tool = language_check.LanguageTool('en-US')
  File "/opt/conda/default/lib/python3.8/site-packages/language_check/__init__.py", line 196, in __init__
    self._start_server_on_free_port()
  File "/opt/conda/default/lib/python3.8/site-packages/language_check/__init__.py", line 333, in _start_server_on_free_port
    cls._start_local_server()
  File "/opt/conda/default/lib/python3.8/site-packages/language_check/__init__.py", line 345, in _start_local_server
    server_cmd = get_server_cmd(cls._port)
  File "/opt/conda/default/lib/python3.8/site-packages/language_check/__init__.py", line 596, in get_server_cmd
    java_path, jar_path = get_jar_info()
  File "/opt/conda/default/lib/python3.8/site-packages/language_check/__init__.py", line 607, in get_jar_info
    java_path = which('java')
  File "/opt/conda/default/lib/python3.8/site-packages/language_check/which.py", line 21, in which
    for path in get_path_list():
  File "/opt/conda/default/lib/python3.8/site-packages/language_check/which.py", line 33, in _get_path_list
    return os.environ['PATH'].split(os.pathsep)
  File "/opt/conda/default/lib/python3.8/os.py", line 675, in __getitem__
    raise KeyError(key) from None
KeyError: 'PATH'


text:
Q: Bluetherm SDK iOS - Apple rejected the APP I have used Bluetherm SDK (http://www.thermoworks.com/products/logger/bluetherm_bluetooth_probe.html) in my iOS APP. But the Application has been rejected by the Apple
Reasons
Not in MFI Program
----- MFi - Program Authorization -----
We are unable to post your app to the App Store at this time because your app has not been authorized by the accessory manufacturer to work with the MFi accessory. Please contact the accessory manufacturer to request your app be added to the MFi Product Plan form.
Once the accessory manufacturer confirms that your app has been added to the MFi Product Plan form, please reply to this message. When we receive your reply with this confirmation, we can proceed with the review; we do not require a new binary even though your application state in iTunes Connect state is Rejected.
If you have not yet provided the accessory's MFi Product Plan ID (PPID), please enter this information in the Notes section for your app in iTunes Connect. If you do not know the PPID, please request this information from the accessory manufacturer.
Please suggest to move ahead.
Thanks in advance.

A: The Apple message seems pretty clear - While the Bluetherm accessory is MFi certified, your app is not listed on the Bluetherm product plan as an approved app to work with that accessory.
From the ThermoWorks web page

The BlueTherm Probe can be integrated into custom mobile apps on the iOS, Android, and Windows platforms. If you are an app developer, your app can be BlueTherm compatible via a supplied SDK. Email Val McQuiston at val@thermoworks.com or call him at 801-756-7705 for more details.

So, my guess is you need to email or call this person and ask them to list your app on the Product Plan Form for the device.


text:
Q: Search string in JSON values without the key Is it possible to search through a JSON and find a single string?
I just want to know if this sting is in the JSON or not.
What I have tried before:
def parse_string(self, reg_string,  input_data):
        self.logger.info("parse string")
        for i in input_data:
            self.logger.info(input_data[i])
            if input_data[i] == reg_string:
                return (input_data[i])
            else:
                self.logger.info('regex: %s not found', reg_string)

but it prints lots of Nones.
My JSON:
{
  "id": 5931,
  "state": "opened",
  "created_at": "2020-09-24T15:04:05.728+02:00",
  "author": {
    "id": 130,
    "username": "veeti",
    "state": "active"
  }

How I call the method:
parser.parse_string("veeti", parser.data)

A: Something like the below
def find_item(obj, look_for):
    for k, v in obj.items():
        if isinstance(v,dict):
            return find_item(v, look_for)
        else:
            if v == look_for:
                return True
    return False

data = {
  "id": 5931,
  "iid": 4145,
  "project_id": 57,
  "title": "Change: SELAP-3333, SFCAP-3139",
  "state": "opened",
  "created_at": "2020-09-24T15:04:05.728+02:00",
  "updated_at": "2020-09-24T15:04:09.903+02:00",
  "author": {
    "id": 130,
    "username": "veeti",
    "state": "active"
  }
}

print(find_item(data,'veeti'))
print(find_item(data,'not_veeti'))

output
True
False

A: You could do str(json_value).find("veeti") > -1


text:
Q: Does this embedding holds? Could you please tell me whether the following continuous embedding holds?
$L^1(R^d)\hookrightarrow H^{-s}(R^d)$ $(s>\frac{d}{2})$

A: Because $u\in L^1$, then $\hat{u}\in L^\infty$. This implies that there exist a constant $C>0$, such that
\begin{eqnarray}
 \int_{\mathbb{R}^d}\frac{\hat{u}(\xi)^2}{(1+|\xi|^2)^s}d\xi &\leq& C \int_{\mathbb{R}^d}\frac{|\hat{u}(\xi)|}{(1+|\xi|^2)^s}d\xi    \nonumber \\
   &\leq& C_1\|u\|_1\int_{\mathbb{R}^d}\frac{1}{(1+|\xi|^2)^s}d\xi \nonumber
\end{eqnarray}
where $C_1>0$ is another constant. Because $s>\frac{d}{2}$, you can conclude that the last integral is finite and hance you have proved that $L^1$ is continuously embedded in $H^{-s}$.


text:
Q: Disable POSITIVE_BUTTON ("Continue") for 5 secs I have a alert pop-up which i show when my app launches. I want the user to read through it, so i want to grey out the continue button for 5 secs, then enable it so the user can continue.

 if (alertDialog == null) {
     alertDialog = new AlertDialog.Builder(this).setPositiveButton("Continue",
                    new AlertDialog.OnClickListener() {
                         public void onClick(DialogInterface dialog, int which) {
                             //continue with the app
                         }
                    }).create();
                    alertDialog.setTitle("My Title");
                    alertDialog.setView(myView);
                }
                if ((!alertDialog.isShowing())) {
                    alertDialog.show();
                    alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(false);
                }

After setting the button to false, i'm unable to set it back to true. I tried using Thread.sleep(5000l) and creating my own dialog. Niether of them worked. How can i go about achieving my objective?
Thanks,
AkasH

A: The UI elements are all rendered in one go after the callback from the user code has finished. This is why just adding a delay does not help.
You may want to start a thread or an AsyncTask where the doInBackground method is counting down (probably in a loop, so you can show a counter in the ok field) and then in onPostExecute enable the button
Pseudo-code:
MyAsyncTask extends AsyncTask {
   doInBackground() {
      for (int i = 5; i > 0 ; i ++) {
          publishProgress (i );
          Thread.sleep(1000);
      }
   }

   onProgressUpdate(int i ) {
        okButton.setText(i);
   }

   onPostExecute() {
       okButton.setText("Ok");
       okButton.enable();
   }
}


text:
Q: Expression Tree that can represent an object OR a list of that object? public returnType ReturnProperty<T>(Expression<Func<T, returnType>> property) where T : MyObject
{
  // Some code or something
}

Obviously this is not my actual function, but basically what I want is to be able to select either an object of MyObject or an object of List<MyObject>. What should I replace returnType with for this to be possible? Is it possible at all? Do I have alternatives besides making returnType be object?
Note: Also, I did not know what tags to put on this question, sorry.
Edit: Also, the reason I need to be able to do both is I wanted to have an array of them or something. Like Expression<Func<T, returnType>>[] properties. Maybe this gives me more or less options.

A: You can have the function return object.  object is anything, so it could be MyObject or List<MyObject>.  You can then do things like this:
object retval = ReturnProperty(...)
if (retval is MyObject)
{
}
else if (retval is IEnumerable<MyObject>)    // Works for List, array, etc.
{
}

A: The short answer is that if you can't write it as direct c# code, you can't write it as an expression tree.
Not that I think it's at all a good idea, but you could define a collection which has an implicit conversion from the contained type, which would allow you to use an expression which only takes a collection as a parameter, e.g.:
private static void ProcessItems(ItemCollection c) {}
ProcessItems(new Item());

// ...

class Item {}

class ItemCollection : List<Item>
{
    public static implicit operator ItemCollection(Item item)
    {
        return new ItemCollection {item};
    }
}


text:
Q: How to transform CSV rows with the same keys into hash I have parsed the .csv file and received the following headers:
"Date":"Start" "Date":"Due" "Amount":"Total" "Amount":"Left"

There are values for each. I need to map it to hash dynamically in the following way:
{date => {start: value, due: value}, amount => {total: value, left: value}}

Please, could you suggest a way. I've tried to use it as an array like:
[["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]

and then
.each_slice(2)

but after that I got stuck. Thanks in advance

A: you can try something like:
rows.map do |row|
  {
    date: { start: row[1], end: row[3] },
    amount: { total: row[4], left: row[6] }
  }
end

A: Given:
headers = [["Date", "Start"], ["Date", "Due"], ["Amount", "Total"], ["Amount", "Left"]]
values= [1, 2, 3, 4]

Hash[headers.zip(values)].each_with_object({}) do |(keys, value), memo|
  pk = keys.first.downcase.to_sym
  memo[pk] ||= {}
  memo[pk][keys.last.downcase.to_sym] = value
end

Output:
=> {:date=>{:start=>1, :due=>2}, :amount=>{:total=>3, :left=>4}}


text:
Q: Know how to choose appropriate distribution for AFT It is written in many web resources that the distribution of the accelerated failure time model must be specified correctly but I don't think I've seen anything about how to know this.
I see often that common distributions (exp, Weibull, lognormal, Gompertz, etc.) are selected and AIC is used to choose the best (here is a fairly well-cited example).
This seems non-thorough to me. Comparing the models by AIC seems logical, but implementations of AFT often allow for more complex distributions that (theoretically) could be a better fit.
My questions:

*

*How can one know which distribution might fit best?

*Are common distributions (e.g., those in survreg in R) often chosen over more complex ones purely for simplicity or do one of these tend to perform sufficiently often enough that more complex ones are not required?

*Is AIC indeed sufficient for comparing different AFT models?

*In my case I expect my survival to simply decrease in a fairly linear fashion, both in general and for my treatment effects. Which distribution might this represent? None of the common distributions seems particularly appropriate.


text:
Q: How do i reset Object loop "counter"? How i can reset the "city" object and start the "for" statement from the start again after the "if" statement is true?
private SortedSet<City> cityList;
for(City city:this.cityList)
        {
            if(city.getPopulation()==arr[i])
            {
                System.out.printf(city.getName() + "(" + city.getCountry() + ") population: " + city.getPopulation() + " area: " + city.getArea());
                i++;
            }
        }

A: Is this what you want to accomplish?
import java.util.Set;

public class City {

    public static void main(String[] args) {
        Integer[] arr = { 50_000, 100_000, 200_000 };
        Set<City> cityList = Set.of( //
                new City(100_000, "city1", "country1", "area1"), //
                new City(200_000, "city2", "country2", "area2"), //
                new City(350_000, "city3", "country3", "area3") //
        );

        outer: for (int i = 0; i < arr.length; i++) {
            for (City city : cityList) {
                if (city.getPopulation() == arr[i]) {
                    System.out.println(city.getName() + "(" + city.getCountry() + ") population: "
                            + city.getPopulation() + " area: " + city.getArea());
                    continue outer;
                }
            }
        }
    }

    private int population;
    private String name;
    private String country;
    private String area;

    public City(int population, String name, String country, String area) {
        this.population = population;
        this.name = name;
        this.country = country;
        this.area = area;
    }

    public int getPopulation() {
        return population;
    }

    public void setPopulation(int population) {
        this.population = population;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getArea() {
        return area;
    }

    public void setArea(String area) {
        this.area = area;
    }

}

When nesting loops you can add a label to them (https://www.tutorialspoint.com/break-continue-and-label-in-Java-loop)


text:
Q: Remove 'bouncy scrolling' on mobile devices I'm trying to find a way to get rid of the bouncy scrolling behaviour on mobile devices (e.g. when there is no content below to scroll yet you are still able to do it and scroll content to top and when released it bounces back)
My html structure looks like this

where all elements stretch to full height of the window. I tried overflow hidden on html and body, auto etc.. yet nothing seems to achieve a state where if you scroll than it doesn't scroll unless there is more content below.

A: It sounds like what you're looking for is to disable the scroll bounce for a UIWebView in iOS. If you're developing a native iOS app, you can disable the bounce by setting [WebViewObject].bounces = NO where [WebViewObject] is the UIWebView.
If you're just looking to prevent the bounce in the Safari mobile browser, I don't believe there's a way to do this.


text:
Q: how to create an associative array from database object and json_encode as object instead of array? I am a newbie in PHP and developing an app using Yii. I have a database object where all I got all the records of a table. I wanted to create an associative array from that object and later encode that array in json_encode. However, my desired output,which is objects instead of array, is not coming. can anyone help, plz?
My code:
$info = array();
$category = Category::find()->all();
foreach($category as $key => $value) {
    $info[]=  array(
         "name" =>$value->name,
         "value" =>$value->description
    ) ;
}
echo json_encode($info,JSON_FORCE_OBJECT);

Output:
{"0":{"name":"test","value":"A"},"1":{"name":"test 2","value":"B"}}

Desired Output:
{"category":[{"name":"test","value":"A"},{"name":"test 2","value":"B"}]}

A: Try to use this:
$info2['category']=$info;
echo json_encode($info2);

A: Use array_values() before json_encode
$info =  array_values($info);
echo json_encode($info,JSON_FORCE_OBJECT);


text:
Q: android IllegalStateException during onBackPressed I have a very weird expception happening on my app.
I overwrote the onBackPressed of some of my activities in order to show an intertitial ad. the code is very simple
public void onBackPressed() {
        if (showIntertitialAd())
            //pseudocodehere
           show ad
            ... on close -> super.onBackPressed();

        else
            super.onBackPressed();
    }

however, somehow im gettng IllegalStateException in some cases here is the stacktrace
Caused by java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
       at android.app.FragmentManagerImpl.checkStateLoss(FragmentManagerImpl.java:1413)
       at android.app.FragmentManagerImpl.popBackStackImmediate(FragmentManagerImpl.java:576)
       at android.app.Activity.onBackPressed(Activity.java:2507)
       at androidx.activity.ComponentActivity.access$001(ComponentActivity.java:53)
       at androidx.activity.ComponentActivity$1.run(ComponentActivity.java:77)
       at androidx.activity.OnBackPressedDispatcher.onBackPressed(OnBackPressedDispatcher.java:197)
       at androidx.activity.ComponentActivity.onBackPressed(ComponentActivity.java:314)
       at com.tomatedigital.adinjector.AdsAppCompatActivity.access$001(AdsAppCompatActivity.java:50)
       at com.tomatedigital.adinjector.AdsAppCompatActivity$OnBackPressededReward.onRewarded(AdsAppCompatActivity.java:542)
       at com.tomatedigital.adinjector.listener.InterstitialAdListener.onAdClosed(InterstitialAdListener.java:40)
       at com.google.android.gms.internal.ads.zzuf.onAdClosed(zzuf.java:4)
       at com.google.android.gms.internal.ads.zzvp.zza(zzvp.java:4)
       at com.google.android.gms.internal.ads.zzgk.onTransact(zzgk.java:13)
       at android.os.Binder.transact(Binder.java:387)
       at fj.b(fj.java:2)
       at com.google.android.gms.ads.internal.client.ag.a(ag.java:1)
       at com.google.android.gms.ads.internal.zzk.n(zzk.java:2)
       at com.google.android.gms.ads.internal.aq.n(aq.java)
       at com.google.android.gms.ads.internal.g.D(g.java)
       at com.google.android.gms.ads.internal.aq.D(aq.java:1)
       at com.google.android.gms.ads.internal.overlay.k.n(k.java:5)
       at com.google.android.gms.ads.internal.overlay.k.m(k.java:6)
       at com.google.android.gms.ads.internal.overlay.k.e(k.java:3)
       at com.google.android.gms.ads.internal.overlay.client.b.a(b.java:13)
       at fk.onTransact(fk.java:4)
       at android.os.Binder.transact(Binder.java:387)
       at com.google.android.gms.internal.ads.zzgi.zza(zzgi.java:21)
       at com.google.android.gms.internal.ads.zzapi.onPause(zzapi.java:17)
       at com.google.android.gms.ads.AdActivity.onPause(AdActivity.java:40)
       at android.app.Activity.performPause(Activity.java:6356)
       at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1334)
       at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3388)
       at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3361)
       at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3336)
       at android.app.ActivityThread.-wrap13(ActivityThread.java)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1372)
       at android.os.Handler.dispatchMessage(Handler.java:102)
       at android.os.Looper.loop(Looper.java:148)
       at android.app.ActivityThread.main(ActivityThread.java:5443)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)

how can i solve it?

A: It seems that your activity is sometimes paused when you call onBackPressed() because of the ad, even though you have the "on close" pseudo code. onBackPressed() can't be called when activity is on pause.
Have you tried using finish() in this case? If your intention is to close the current activity/fragment, that could work as well.

A: To Avoid crash on back press just modify the code.
As well as you can get the actual exception on the log and can modify your code.
However, It will not crash your application.
    public void onBackPressed() {

    try{
    if (showIntertitialAd())
                //pseudocodehere
               show ad
                ... on close -> super.onBackPressed();

            else
                super.onBackPressed();
    }catch(Exception ex){
    Log.e(ex.localizedmessage)
super.onBackPressed();
    }
        }


text:
Q: How define the img src path in MVC I have my index.cshtml with a image

< img id="u3430_img" src="Images/send.png">

And a folder Images inside myApp/Images folder
if i access

*

*http:/localhost/myApp  OR

*http:/localhost/myApp/home/

works Ok. But if i use

*

*http:/localhost/myApp/home/index

The page try to look for the image in

*

*http:/localhost/myApp/home/Images/send.png

So how I should define my src.
Aditional note:
Beside the index.cshtml I also have an js file where a hover effect is add it to the image. And have same problem neither of those option work
$('#u3430_img').hover(
        function () {
            $(this).attr("src", "~/Images/send_hover.png");
        },
        function () {
            $(this).attr("src", "Images/send.png");
        }
);

A: You can reference images in the top level of the project with the ~.
<img src="~/Images/send.png">

Older versions of ASP.NET MVC needed a @Url.Content() around the path, as described here
Edit: If you want to update the path from Javascript, you can either specify an absolute path, or wrap it in @Url.Content().
$('#image').attr('src', '/Images/send.jpg');

$('#image').attr('src', '@Url.Content("~/Images/send.png")');

A: in Cshtml page adding ~ is not necessary.Just add /Images/send.png  ...It will come to root and follow hierarchy.