text:
Q: This "weird group trick" makes MacBook Pro login, apps, and systems run slow slow slow ... but why? Edit  In response to Tetsujin's comment, further details now are provided for reproducing the slowdown, and for reverting back to normal speed.
The usual caveat  Experimenting with system-level bugs is inherently risky.  You are advised not to do so, unless you have a working understanding of users, groups, and permissions and you possess reliable system backups.

Here's a "weird trick" that instantly makes my MacBook Pro / Yosemite system run slow slow slow ... create a circular group inclusion in the Users & Groups pane of System Preferences.
Answers Sought Why does this slowdown happen?  Are other users affected?  Is there a tool that automatically diagnoses and fixes it?  How can it be avoided in the future?
Remark After creating this slowdown inadvertently, it took me two weeks to figure out, reproduce, and repair the cause of it.  The search for a fix was slow and frustrating because none of the usual fixes of "slow Mac syndrome" were effective, and none of the usual diagnostics were revealing.
Reproducing the slowdown
In the System Preferences pane "Users & Groups"

*

*create new groups "a" and "b"

Close System Preferences.
Now open the Finder's "Get Info" pane for the directory at the base of a large directory tree ... for me /usr/local is large enough to elicit a severe slowdown.  Then

*

*under "Sharing & Permissions", give "a", but not "b", read/write privileges to all files in the tree, via the menu-selected option "apply to enclosed items".

Now reopen the System Preferences pane "Users & Groups"

*

*include group "a" in group "b"

*include group "b" in group "a"

Voila!  Now everything on my MacBook runs slow ... slow ... slow.  Logins require up to one minute, and even simple typing sporadically elicits the "spinning pizza."  Fortunately, eliminating the circular group inclusion instantly restores the system to its former speed.
Returning to normal speed
To revert the changes, reverse the above steps

*

*first undo the group "a" and group "b" circular inclusions

*then remove the group "a" read/write permissions

*then delete groups "a" and "b"

Hypothesis Yosemite's bash shell performs poorly in resolving circular group references when searching large directory trees in "$PATH" variables.
Evidence Even simple command-lines like "ls" run slowly ... it appears that when circular group inclusions are present, bash is slow in searching $PATH to locate the "ls" file.

System Software Overview:
System Version: OS X 10.10.2 (14C109)
Kernel Version: Darwin 14.1.0
Boot Volume: Macintosh HD
Boot Mode: Normal
Computer Name: [redacted]
User Name: [redacted] (Administration)
Secure Virtual Memory: Enabled

Hardware Overview:
Model Name: MacBook Pro
Model Identifier: MacBookPro11,3
Processor Name: Intel Core i7
Processor Speed: 2.5 GHz
Number of Processors: 1
Total Number of Cores: 4
L2 Cache (per Core): 256 KB
L3 Cache: 6 MB
Memory: 16 GB
Boot ROM Version: MBP112.0138.B14

Note also that /usr/local tree is fairly large (as is typical of developers and LaTeX users) ...
$ find /usr/local -type f | wc -l
204713


text:
Q: Assembly x86 outputting incremented value I'm terribly new to Assembly, and I've been stuck at what I initially considered an easy thing to do.
I need to input two values, one smaller than the other, and output all the numbers in between.
For example, 1 and 4, output:
1
2
3
4
Now I've managed to input the numbers, and I've managed to output first two digits, but only manually. I can't understand how to use a loop and what conditions to look at.
I'm sure I have to compare the two values, and increment the first until it's equal to the second, but I'm uncertain of how it's done.
This is my code:
lequal:
# output first number
movl valore, %eax
addl $-48,%eax
call itoa

inc %eax #increment value of valore?
loop lequal
jmp end

I am guessing perhaps:
movl valore, %eax
addl $-48,%eax
movl valore2,%ebx
addl $-48,%ebx
cmp %eax, %ebx

comparing both values is needed in order to know when to stop incrementing the value of first integer?
I only get the first integer outputted, endlessly, because I used a loop, and the incrementation is simply overlooked, for some reason.
Anyway, I'd appreciate any help provided. Thanks in advance.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Create C++ background Win32 application from scratch I want to create a very simple background application.
I start with the empty c++ project, and I create a source.cpp file with the code below:
#include "Windows.h"

int WINAPI _tWinMain(HINSTANCE  hInstance,
    HINSTANCE   hPrevInstance,
    LPTSTR      lpCmdLine,
    int     nCmdShow)
{
    MSG Msg;

    while (GetMessage(&Msg, NULL, 0, 0))
    {

    }

    return 0;
}

then I set the settings of the project as follow:
Properties -> Configuration Properties -> Linker -> System: Set SubSystem is: Windows (/SUBSYSTEM:WINDOWS)
Properties -> Configuration Properties -> Linker -> Advanced ->Set Entry Point is: _tWinMain
Am I doing it right? Also I want to add the MFC library into this project so I can use the MFC's function, how can I do it?
Thanks for reading :)
Edit:
Weird, I just need to include "tchar.h" and the error [ LNK1561: entry point must be defined ] disappear. I don't need to configure the project settings anymore. All I need is the code below:
#include "Windows.h"
#include "tchar.h"

int WINAPI _tWinMain(HINSTANCE  hInstance,
    HINSTANCE   hPrevInstance,
    LPTSTR      lpCmdLine,
    int     nCmdShow)
{
    //MessageBox(0, _T("test"), _T("Test"), 0);

    return 0;
}

A: Create a SDI application without using Documents and Views. Check only the options you need. In most cases you need a window even for a background application to get window messages.
Leave the main window that is created and don't show it, set m_nCmdShow to SW_HIDE. Destroying this main window will end the message loop and stop the program.
Later you may remove other unused things like the toolbar from the mainframe.
Another way, is to create a dialog based application with the wizard. Without creating any dialog and using your own message pump. with something like this:
while (OuterCondition())
{
  while( ::PeekMessage( &message, NULL , WM_MIN, WM_MAX, PM_NOREMOVE ) )
  {
    ::AfxPumpMessage();
  }
}

Also MsgWaitForMultipleObjects may be useful.
You usually need a CWinApp object to init MFC correctly.


text:
Q: regular expression validating string I tried using this pattern
^[A-z]*[A-z,-, ]*[A-z]*

To match against a string that starts with multiple alpha characters (a-z) followed by multiple hyphens or spaces and ends with alpha characters, eg:
Azasdas- - sa-as

But it does not work.

A: You don't want the commas, in a character range you also need to specify [A-Za-z\- ] because the ASCII for A-Z and a-z aren't contiguous. You're missing some allowable spaces, and your last expression needs to account for the hypen.
You need something closer to this:
^([A-Za-z]*)-\s*([A-Za-z][A-Za-z -]*)([A-Za-z-]*)$

Depending on how you actually want to break things up. Without knowing the context behind the "chunks", it may or may not just be easier to split it apart on hyphens.
Edit
Actually, it's more like:
^([A-Za-z]*)([- ]*)([A-Za-z-]*)$

This is a word, followed by arbitrary spaces and hyphens, followed by a word that may contain a hyphen.

A: Don't use ',' (comma)
^[A-z]*[A-z- ]*[A-z]*

A: Try ^[A-Za-z][A-Za-z -]*[A-Za-z]$
^ indicates that the word should start with alphabets (A-Z or a-z) and then followed by any number of alphabets or hyphens. And then end with alphabets denoted by $ .
Also, you should not be using A-z because this will include unintended characters from ASCII range 91 to 96. See this table

A: The currently accepted answer (^[A-Za-z][A-Za-z-]*[A-Za-z]$) will only match strings that are at least two characters long--for example, it will match the string "AB", but not just "A" or "B".  Compare that to this regex:
^[A-Za-z]+([ -]+[A-Za-z]+)*$
By grouping the [ -]+ and the second [A-Za-z]+ together I'm saying, if there are any spaces and/or hyphens, they must be followed by more letters. The * quantifier on the group makes it optional, so "A" will match, while still meeting the requirement that the string start and end with a letter.


text:
Q: How to check all rules which can be applied to a mailItem in Outlook I am writing an application which has to get items that can be matched with rules.
//new messages goes here
void items_ItemAdd(object Item)
    {
        //all rules
        Rules rules = Application.Session.DefaultStore.GetRules();

        Outlook.MailItem mail = (Outlook.MailItem)Item;

        if (mail != null)
        {
            // I need to find out if mail matches with one of the rule. And handle in an appropriate way.
        }
    }

A: The only way to check which rules apply to which items is by enumerating the Rule Conditions (and excluding rule exceptions) manually for each MailItem. The rule engine works by executing each rule you have defined via Rule.Execute - it doesn't provide a mechanism to preview affected items.
Here is an (untested) example for reference on how to match a contains subject rule (olConditionSubject). You would also need to handle other Rule Conditions types.
if (mail != null)
{
    foreach (Outlook.Rule rule in rules)
    {
       foreach (Outlook.RuleCondition condition in rule.Conditions)
       {
         if (condition is TextRuleCondition)
         {
            Outlook.TextRuleCondition trc = condition as Outlook.TextRuleCondition;
            if (trc.ConditionType == Outlook.OlRuleConditionType.olConditionSubject)
            {
              // TODO: handle Rule.Exceptions conditions
              bool containsSubject = mail.Subject.Contains(trc.Text);
            }
         }
       }
    }
}


text:
Q: Area of a Polygon in a Polygon I'm dealing with a regular polygon with 7 corners. In this polygon is another polygon defined by connecting one point with the two opposite points of the same polygon.
I made a small sketch of the polygons

I need to calculate the ratio of the area of the big and of small polygon. I know how to calculate the area of the big polygon but I don't know how to get area of the small polygon.

A: Let $O$ be the centre of the circumscribed circle of our heptagons, and the outer heptagon $P_1P_2P_3P_4P_5P_6P_7$ has circumradius $R$.
Then the distance from $O$ to side $P_1P_2$ is $R\cos(\pi/7)$ (as seen by drawing the isosceles triangle $OP_1P_2$.
Similarly, can you find the distance from $O$ to side $Q_1Q_2=P_3P_7$ and finish it from here?

A: Easy to see that $P_1Q_2P_3P_2$ and $P_1P_7Q_1P_2$ are parallelograms, which says that
$$P_1P_7=Q_1P_2=P_1P_2=P_1Q_2=P_2P_3.$$
Now, let $P_1P_4\cap P_6P_2=\{A\}$.
Thus, from $\Delta Q_1Q_2A$ we obtain:
$$Q_1Q_2=2AQ_2\sin\frac{\measuredangle Q_1AQ_2}{2}=2AQ_2\sin\frac{3\pi}{14}.$$
Also, from $\Delta P_1P_2A$ we obtain:
$$P_1P_2=2AP_1\sin\sin\frac{\measuredangle P_1AP_2}{2}=2AP_1\sin\frac{3\pi}{14}.$$
Since $$AQ_2+AP_1=P_1Q_2=P_2P_3=P_1P_2,$$ we obtain:
$$\frac{Q_1Q_2}{2\sin\frac{3\pi}{14}}+\frac{P_1P_2}{2\sin\frac{3\pi}{14}}=P_1P_2,$$ which gives
$$\frac{P_1P_2}{Q_1Q_2}=\frac{1}{2\sin\frac{3\pi}{14}-1},$$ which gives the answer:
$$\frac{1}{\left(2\sin\frac{3\pi}{14}-1\right)^2}.$$
Another way.
Let $R$ be a radius of the circumcircle of $P_1P_2...P_7.$
Thus, $$Q_1Q_2=P_7P_3-2P_1P_2=2R\sin\frac{3\pi}{7}-4R\sin\frac{\pi}{7}$$
and $$P_1P_2=2R\sin\frac{\pi}{7}.$$
Id est, $$\frac{P_1P_2}{Q_1Q_2}=\frac{\sin\frac{\pi}{7}}{\sin\frac{3\pi}{7}-2\sin\frac{\pi}{7}}=\frac{1}{3-4\sin^2\frac{\pi}{7}-2}=$$
$$=\frac{1}{1-2\left(1-\cos\frac{2\pi}{7}\right)}=\frac{1}{2\cos\frac{2\pi}{7}-1},$$ which gives a ratio of areas again.


text:
Q: Filter JBoss Access Logs By URL I am using JBoss 6.4 EAP access logs to debug when an item hits the server.
    <subsystem xmlns="urn:jboss:domain:web:2.2" default-virtual-server="default-host" native="false">
        <connector name="http" protocol="HTTP/1.1" scheme="http" socket-binding="http"/>
        <connector name="https" protocol="HTTP/1.1" scheme="https" socket-binding="https" secure="true">
        </connector>
        <virtual-server name="default-host" enable-welcome-root="true">
            <alias name="my.host.name"/>
            <access-log pattern="%t %a %A %b %h %m %p %q %U %r">
                <directory path="."/>
            </access-log>
        </virtual-server>
    </subsystem>

However, a monitoring tool constantly hits the server every couple of seconds to check it is up and so the access log is hard to read.
I can't turn off or change the monitoring and the code in the webserver is not mine so I can't change that either.
Is it possible to filter the access log so that it only logs when a specific url is hit?


text:
Q: Performance issue in Scala code - O(nlgn) faster than O(n) I am just getting started with scala. I am trying to learn it by solving easy problems on leetcode. Here's my first (successful) attempt at LC #977:
def sortedSquares(A: Array[Int]): Array[Int] = {
    A.map(math.abs).map(x => x * x).sorted
}

Because of the sorting, I expected this to run O(NlgN) time, N being the size of the input array. But I know that there is a two-pointers solution to this problem which has a run-time complexity of O(N). So I went ahead and implemented that in my noob Scala:
def sortedSquaresHelper(A: Array[Int], result: Vector[Int], left: Int, right: Int): Array[Int] = {
    if (left < 0 && right >= A.size) {
        result.toArray
    } else if (left < 0) {
        sortedSquaresHelper(A, result :+ A(right) * A(right), left, right + 1)
    } else if (right >= A.size) {
        sortedSquaresHelper(A, result :+ A(left) * A(left), left - 1, right)
    } else {
        if (math.abs(A(left)) < math.abs(A(right))) {
            sortedSquaresHelper(A, result :+ A(left) * A(left), left - 1, right)
        } else {
            sortedSquaresHelper(A, result :+ A(right) * A(right), left, right + 1)
        }
    }
}

def sortedSquares(A: Array[Int]): Array[Int] = {
    val min_idx = A.zipWithIndex.reduceLeft((x, y) => if (math.abs(x._1) < math.abs(y._1)) x else y)._2
    val result: Vector[Int] = Vector(A(min_idx) * A(min_idx))
    sortedSquaresHelper(A, result, min_idx - 1, min_idx + 1)
}

Turns out, the first version ran faster than the second one. Now I am quite confused about what I might have gotten wrong. Is there something about the recursion in second version that is causing high overhead?
I'd also like some suggestion about what is the idiomatic scala-way of writing the second solution? This is my first serious foray into functional programming, and I am struggling to write the function in a tail-recursive manner.

A: Vectors are significantly slower than Arrays overall. In particular

Vector item-by-item construction is 5-15x slower than List or mutable.Buffer construction, and even 40x slower than pre-allocating an Array in the cases where that's possible.

With map and sorted length of array is known, so they can be preallocated.
As that page mentions, Vector#:+ is really logarithmic, so you end up with O(n log n) in both cases. Even if you didn't, O(n log n) vs O(n) technically only says something about how performance changes when input grows indefinitely. It's mostly aligned with what's faster for small inputs as well, but only mostly.

I'd also like some suggestion about what is the idiomatic scala-way of writing the second solution?

One way is to construct a List in the reverse order, and then reverse it at the end. Or use an ArrayBuffer: even though it's mutable, you can effectively ignore that because you don't keep a reference to the older state anywhere.


text: Q: How to upload documents FROM sharepoint to an external content management server? How to upload documents "FROM" sharepoint to an external content management server? Is there a way to provide external CMS as source to sharepoint content server?


text:
Q: Download File with vbscript I have a problem downloading file, I have two URL´s the first URL content the user and pwd, the second URL content the path of the file that i require.
If only put the second URL appear a error message. I am begginer in VBScript.
only i want download file
this is my code, but i dont know if is correct.
Function Main
    Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
    IE.Visible = False
    IE.Navigate "url/sf_security_check?j_username=myuser&j_password=mypwd" '-- First URL
Call Extrae_Arc

End Function

Function Extrae_Arc
    Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
    IE.Visible = True
    IE.Navigate "url" '-- second URL
End Function

Thanks for help me

A: The IE object is redefined in Extrae_Arc function, hence overrides pointer assigned previously.
I'd use next scenario:
'...
Set IE = WScript.CreateObject("InternetExplorer.Application", "IE_")
Call Main
Call Extrae_Arc
'...

Function Main
  IE.Visible = False
  IE.Navigate "url/sf_security_check?j_username=myuser&j_password=mypwd" '-- First URL
End Function

Function Extrae_Arc
  IE.Visible = True
  IE.Navigate "url" '-- second URL
End Function


text:
Q: How to put Serial Number in dojox grid rows How can we insert the row number as serial number in each dojo grid rows??
this must not change as grid is filtered or sorted.. any Idea??

A: the solution i found is to use a 'get' in grid structure
add
function siFormatter(index){
return index + 1;
}

and add this to the structure of grid -
{field: "Si", name: "#", get : siFormatter, filterable: false}

disable sort for this column using canSort function in grid
donno if there is any other better solutions..


text:
Q: Probability conditional on entry of exchangeable random vector: does the index matter? I have a random varbiable $Y\in\{0,1\}$, which is dependent on a random vector $X \in \{0,1\}^n$. Therebey, the entries in $X$ are exchangeable. That is, $P(X_i=1)=P(X_j=1)$.
I want to compute/approximate $P(Y=1 | \exists j: X_j=1)$.
I know $P(Y=1 | X_1=1)$ and $P(Y=1)$. I have the intuition that $$|P(Y=1) - P(Y=1 | \exists j: X_j=1)| \leq |P(Y=1) - P(Y=1 | X_1=1)|,$$ because knowing the index of the known component of $X$ is more information than just knowing that $X_j=1$ for some index. Conditioning on more information, in turn, should change the probability more than conditioning on less information.
Is that correct? (Does it even hold with equality?) Why? How could I check that?

A: It is true that the event $B_1 = \{X_1 = 1\}$ is a subset of the event $B_2 = \{\exists j: X_j = 1\}$ so you do "know more information", but how does that affect the probability $P(Y=1)$?  You are essentially evaluating $P(Y=1 \mid B_k)$ for three events: $B_1, B_2$, and $B_3 = \Omega$ (i.e. the entire space, i.e. unconditioned).  While it is true that $B_1 \subset B_2 \subset B_3$, the prob $P(Y=1 \mid B_k) = {P(B_k \cap Y=1) \over P(B_k)}$ depends on how the event $\{Y=1\}$ intersects with each of them, and there is no reason to believe there will be a trend.  To be more explicit, as you go from $B_1$ to $B_2$ to $B_3$, both the numerator and denominator increase (or: do not decrease), so there is no telling what can happen to the ratio which is $P(Y=1 \mid B_k)$.
Here is a specific counter-example.  I found myself using this as a counter-example to many different MSE questions, BTW, so this seems to be a good one to test any conjecture about conditional probabilities. :)

*

*$X_1, X_2 =$ two different independent fair coin flips, where $X_i = 1$ means Heads

*$Y=$ the two flips show the same result

*$P(Y=1) = {HH,TT \over HH, HT, TH, TT} = \frac12$

*$P(Y=1\mid X_1= 1) = {HH \over HH, HT} = \frac12$

*$P(Y=1 \mid X_1 =1 \cup X_2 = 1) = {HH \over HH, HT, TH} = \frac13$


text:
Q: ATMega328: How to select alternate function on a pin This might be an easy question, but I couldn't find an answer to it in the Alternate Port Functions section of the ATMega328 datasheet (page 80)
Take pin PB3 as an example. As well as having a use as a GPIO pin, it is also wired to MOSI, OC2A, and PCINT3. How do you select which signal is wired to PB3?
Specifically, if I wanted to use PB3 as a GPIO pin, but I was using timer2 for some other function (which would have a side effect of setting and/or clearing OC2A), will the two signals interfere, and how would I avoid that?
Thanks

A: Specific to timer/counter control register A, register TCCR2A bits 7:6 COM2A1:0 control whether or not the internal OC2A signal overrides the normal PORTB3 pin behavior. See datasheet section 17.11.1 TCCR2A – Timer/Counter Control Register A - found by searching within the datasheet for OC2A.
The section you referenced 13.3 Alternate Port Functions gives a generic description of how all of the alternate port functions are worked out, but only goes as far as the override signal names. See table 13-5 for Overriding Signals for Alternate Functions in PB3..PB0. They give a bunch of Boolean expressions for each of the overrides -- PVOE is "Port Value Override Enable" and PVOV is "Port Value Override Value" as per the earlier diagram 13-5 Alternate Port Functions. To find out which actual bitfield in which register controls each alternate pin function, you have to search the signal name within the datasheet.


text:
Q: ¿Cómo puedo poner el Android Studio para trabajar offline? Mi Android Studio no me carga los layouts (uso la pantalla dividida, código y diseño), antes era después de un tiempo de haberlo abierto, ahora lo hace apenas lo abro.
Yo supongo que fue por conectar mi cuenta de google. Hace poco cerré la sesión, así que supuse que ese fue el problema.
Así que vi la siguiente solución y quise implementarla pero no encuentro el 'Offline work'.
https://stackoverflow.com/a/35859572/10783826
Mi ventana se ve así:

Esto no me deja trabajar.
Saludos y gracias de antemano.

A: En las últimas versiones de Android Studio el "modo offline" es controlado mediante el plugin de Gradle.

En Android Studio lo puedes encontrar del lado derecho donde se muestra la opción "Gradle", das clic para expander el panel y ahí puedes ver la opción para activar/desactivar el "modo offline".

Si activas el icono  trabajaras en "modo offline".

A: Ir a File -> Settings.
Y luego abrir 'Build,Execution,Deployment'. Luego abre
Build Tools -> Gradle
Luego check -> modo ofline a la derecha .
Presiona el botón ok.
Luego Reconstruye el proyecto .


text:
Q: How do I have a button and a label share the same width using SwiftUI? struct PasswordGenerator : View {
    var body: some View {
        NavigationView {
            VStack {
                Spacer()
                //123
                Text("Upon clicking the button the password\nwill also be copied so you\ncan simply paste")
                    .lineLimit(nil)
                Spacer()
                    //123
                    Button(action: generatePassword) {
                        HStack {
                            Image("GeneratorGlyph")
                            Text("Generate!").font(.title)
                            }
                            .accentColor(.white)
                                                .frame(minHeight: 56, maxHeight: 112)
                                                .frame(minWidth: 0, maxWidth: .infinity)
                        }
                        .background(LinearGradient(gradient: Gradient(colors: [Color.init(red: 48/255, green: 153/255, blue: 216/255), Color.init(red: 65/255, green: 165/255, blue: 237/255)]), startPoint: .topLeading, endPoint: .bottomTrailing), cornerRadius: 9)
                Spacer()
                }
                .navigationBarTitle(Text("Generator"), displayMode: .inline)
        }
    }
}

So I have a button and a Text label (I put a comment that says 123 over both of them so it's easier for you to see) and I was wondering how I could have the button have the same width as the Text label.

A: Just add padding to your button:
.padding(.horizontal, 40)


text:
Q: Matlab/Simulink: Determine current system level In Matlab/Simulink, is there a convenient way to determine the depth of the current system, i.e. the numbers of system block borders one has to cross to reach the root level from there? I suppose you can get the pathname of the current system by gcb and count the number of slashes, but that doesn't seem to be a very natural way to do it.

A: You can ask for the parent in a loop, until the system doesn't have a parent,
depth = 1;
parent = get_param(system, 'Parent');

while ~isempty(parent)
  depth = depth + 1;
  parent = get_param(parent, 'Parent');
end

I didn't try this, but I think it should work.


text:
Q: Django ORM how to return a grouped random query set I need to return a set of random groups in one query set. For example I currently have the following data set returned:
ID  Identity  Name

 1     E       Foo

 4     S       Bar

 2     E       Ted

 3     S       Bob

 5     S       Jen

I need to group the Identity column so that 'E' and 'S' are returned together but in random order each time. IE:
Query 1:
ID  Identity  Name

 1     E       Foo

 2     E       Ted

 4     S       Bar

 3     S       Bob

 5     S       Jen

And if I were to run it again:
Query 2:
ID  Identity  Name

 2     E       Ted

 1     E       Foo

 4     S       Bar

 5     S       Jen

 3     S       Bob

I am not sure if this is possible using Django ORM functionality. Please advise. Thanks in advance as I am a little new to Django. Also, I am aware that I can send a Raw query in and get results. I would like to try to avoid this if possible. If not, I understand. Thanks in advance.

A: I belive you can't do this in a queryset, but you can use random module from python and sort by identity after:
import random
objects = list(queryset)
random.shuffle(objects)
objects.sort(key=lambda x: x.Identity)

In fact, like specified in the
docs, you can order by random.
try something like this:
queryset.order_by('Identity', '?')


text:
Q: Select FROM syntax multiple tables Oracle 11G Hi there I have multiple tables which I extract data. I have a question regarding the syntax for ORACLE 11 g  I have used SQL server before .
My Query looks like this
FROM
dw_bi.dw_detalle_altas
let join dw_bi.dm_producto_claro

is the first part before the period dw_bi the schema ? object? and the second part dw_detalle_altas and dm_producto_claro the table?

A: According to the Oracle docs, the term before the dot is the schema, and the term after the dot is the table.  So, in general, your query would look like:
SELECT *
FROM yourSchema.table1 t2
LEFT JOIN yourSchema.table2 t2
    ON -- some conditions

A: You can use Left outer join or inner join to fetch data from multiple tables.
Left Outer join:
SELECT *
FROM table1 AS T1
LEFT OUTER JOIN table2 AS T2
ON T1.column_name = T2.column_name;

Inner Join:
SELECT *
FROM table1 AS T1
INNER JOIN table2 AS T2
ON T1.column_name = T2.column_name;


text:
Q: Navbar search box in the dropdown menu crashes other navbar icons

        .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .open > a:focus, .navbar-default .navbar-nav > .open > a:hover {
            background-color: transparent !important;
        }
        .nav > li a.dropdown-toggle {
            text-align: right;
        }

        .dropdown-menu {
            min-width: 20px !important;
        }
        .nav>li{vertical-align:top}

        /* navbar-icon */
        .nav {
        //  display: flex;
            width: 100%;
        }

        .navbar-default .navbar-nav > li > a:focus, .navbar-default .navbar-nav > li > a:hover {
            background-color: transparent;
        }

        .nav > li {
            display: inline-block !important;
        }

        .nav_li_last_options {
            float: right;
        }
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

                        <form class="navbar-form" style="width: 100%; margin: auto">

                            <input class="form-control" placeholder="Search" id="searchbar" type="text">

                        </form>

JavaScript

options: bootstrap3(3.3.7) and jquery3
I made navbar that has search icon. When I click search icon, search box in the dropdown menu will be opened.
But, On browser's width < 768, when I click search Icon, navbar and other icons are crashed.
Is there any good way to fix it?
How can I fix it?

A: According to bootstrap official documentation.

Changing the collapsed mobile navbar breakpoint
The navbar collapses into its vertical mobile view when the viewport is narrower than @grid-float-breakpoint and expands into its horizontal non-mobile view when the viewport is at least @grid-float-breakpoint in width. Adjust this variable in the Less source to control when the navbar collapses/expands. The default value is 768px (the smallest "small" or "tablet" screen).

look Official documentation may help you


text:
Q: How do I enable adb tracing I am intrested in viewing the packets sent by between adb client and adbd through usb. I tried setting the environment variable ADB_TRACE to 1. But when I run "adb shell" though the shell comes up, I am not able to see any traces. Any help will be appreciated thanks

A: Try adb logcat.  That will show you the log.

A: Below patch should help you. More info is present at https://events.linuxfoundation.org/images/stories/pdf/lf_abs12_kobayashi.pdf
diff --git a/adb/adb.h b/adb/adb.h
index 622ca70..ecf9597 100644
--- a/adb/adb.h
+++ b/adb/adb.h
@@ -379,7 +379,7 @@ void adb_qemu_trace(const char* fmt, ...);
  extern unsigned char    adb_trace_output_count;
  void    adb_trace_init(void);

-#  define ADB_TRACING  ((adb_trace_mask & (1 << TRACE_TAG)) != 0)
+#  define ADB_TRACING  1//((adb_trace_mask & (1 << TRACE_TAG)) != 0)

   /* you must define TRACE_TAG before using this macro */
#  define  D(...)                                      \
@@ -415,7 +415,7 @@ void adb_qemu_trace(const char* fmt, ...);
#endif

-#if !DEBUG_PACKETS
+#if 1//!DEBUG_PACKETS
 #define print_packet(tag,p) do {} while (0)
#endif

A: You just need to type some commands in the terminal:
adb kill-server
export ADB_TRACE=all
adb start-server


text:
Q: Proving the inverse series is right. If we have the following series when $ x<0.5$ $$y=\sum_{n=1}^{\infty }(x)^n $$ How can I prove the inverse series is $$x=-\sum_{n=1}^{\infty }(-y)^n$$

A: First solve the first series:
$$
y = \sum_{n=1}^\infty x^n = \frac{x}{1-x} = -1 + \frac1{1-x}
$$
and solve for $x$:
$$
1-x = \frac1{y+1}\implies x = 1-\frac 1{y+1} = -\frac y{y+1}
$$
This has the form $u_0 \times \frac 1{1-r}$ with $r = y, u_0 = -y$.
Hence this is the sum of the geometric series with first term $u_0$ and ratio $r$, that is:
$$
x = \sum_{n=0}^\infty -y\times (-y)^n = -\sum_{n=1}^\infty (-y)^n
$$

A: $\sum_{n=1}^{\infty }(x)^n$ is a geometric series, so:
$$y=\sum_{n=1}^{\infty }(x)^n=\frac{x}{1-x}$$
It can be written as $y-xy=x$, next $y=x+xy=x(1+y)$, so:
$$x=-\frac{(-y)}{1-(-y)}$$
But $-\frac{(-y)}{1-(-y)}$ is also sum of geometric series:
$$-\frac{(-y)}{1-(-y)}=-\sum_{n=1}^{\infty}(-y)^n.$$
Next check that new series converges (it should be $|y|<1$). But $|x|<0.5$, so:
$$|y|=\frac{|x|}{|1-x|}<\frac{0.5}{|1-x|}\leq\frac{0.5}{1-|x|}<\frac{0.5}{0.5}=1$$


text:
Q: Partially replace video stream while preserving audio stream Consider a video file with one video and one audio stream. I want to replace the video stream partially while preserving the original audio stream.
With partially I mean to replace certain seconds within the original video stream with another video stream of the corresponding length (either specifying the time or frame span)
Additionally I want to replace multiple parts of the original video stream.
Would it be possible with an ffmpeg one-liner? Otherwise what would be the best procedure to follow? Extract audio, cut down everything in small video chunks, concatenate them together and add the original audio stream?
Exact timing is not relevant at first hand.


text:
Q: How to auto fill my form just like we get value by serialize()? Just like with jquery function serialize() we can get all the values of form how can I set all value to form ?

function getAllValue(){
    document.write($("#test").serialize());
}

function setAllValue(){
    var all_values = [{name:"input1",value:"test1"},{name:"input2",value:"test2"},{name:"input3",value:"test3"}];
    $.map(all_values,function(input) {
        $("input[name='"+input.name+"']").val(input.value);
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="test">
  <input type="text" name="input1">
  <input type="text" name="input2">
  <input type="text" name="input3">
  <input type="button" onClick="getAllValue();" value="Get All Value">
  <input type="button" onClick="setAllValue();" value="Set All Value">
</form>

Or this is also a good solution which I am doing right now. Please suggest.

A: If you want something more generic, something that you can use even if you don't know what inputs the form will have, you can use this:
var inputsNamesArray = $("#test").serialize().replace(/\=[^\=\&]*/g,"").split("&");
$.each(inputsNamesArray, function(key,val){
    $("#test input[name="+val+"]").val("placeholder");
});


text:
Q: How to insert elements in a vector at regular intervals in Matlab I have a vector of 13 entities in Matlab.
a=[3 4 6 8 1 5 8  9  3 7 3 6 2]

I want to append values [1 2 3 4 5] at regular intervals at position 1 5 9 13  & 17.
The final value of a looks like this.
a=[1 3 4 6 2 8 1 5  3 8  9  3  4 7 3 6 5 2].
The values with italics show the appended values.
How can I do it?

A: Since you are looking for regular intervals, you can take advantage of the reshape and cat function:
a = [3 4 6 8 1 5 8 9 3 7 3 6 2];
v = [1 2 3 4 5];
l = [1 5 9 13 17];

interval = l(2)-l(1)-1; %computes the interval between inserts
amax = ceil(size(a,2)/interval) * interval; %calculating maximum size for zero padding
a(amax) = 0; %zero padding to allow `reshape`
b = reshape (a,[interval,size(v,2)]); %reshape into matrix
result = reshape(vertcat (v,b), [1,(size(b,1)+1)*size(b,2)]); %insert the values into the right position and convert back into vector

%remove padded zeros
final = result(result ~= 0) %remove the zero padding.

>>final =

Columns 1 through 16
 1     3     4     6     2     8     1     5     3     8     9     3     4     7     3     6

Columns 17 through 18
 5     2

A: Here's an approach using boolean-indexing -
% Inputs
a = [3 4 6 8 1 5 8 9 3 7 3 6 2]
append_vals = [1 2 3 4 5]
append_interval = 4 % Starting at 1st index

% Find out indices of regular intervals where new elements are to be inserted.
% This should create that array [1,5,9,13,17]
N_total = numel(a) + numel(append_vals)
append_idx = find(rem(0:N_total-1,append_interval)==0)

% Get boolean array with 1s at inserting indices, 0s elsewhere
append_mask = ismember(1:N_total,append_idx)

% Setup output array and insert new and old elements
out = zeros(1,N_total)
out(~append_mask) = a
out(append_mask) = append_vals

Alternatively, we can also use linear-indexing and avoid creating append_mask, like so -
% Setup output array and insert new and old elements
out = zeros(1,N_total)
out(append_idx) = append_vals
out(setdiff(1:numel(out),append_idx)) = a

A: a=[3 4 6 8 1 5 8 9 3 7 3 6 2]; % // Your original values
pos = [1 5 9 13 17]; % // The position of the values you want to insert
b=[1 2 3 4 5]; % // The values you want to insert

% // Pre-allocate a vector with the total size to hold the resulting values
r = zeros(size(a,2)+size(pos,2),1);

r(pos) = b % // Insert the appended values into the resulting vector first
r3 = r.' <1 % // Find the indices of the original values. These will be zero in the variable r but 1 in r3
ans =

   0   1   1   1   0   1   1   1   0   1   1   1   0   1   1   1   0   1

ind= find(r3==1) % // Find the indices of the original values

ind =

    2    3    4    6    7    8   10   11   12   14   15   16   18

r(ind) = a; % // Insert those into the resulting vector.

r.'
ans =

   1   3   4   6   2   8   1   5   3   8   9   3   4   7   3   6   5   2

A: You can use this function to append a bunch of values to an existing vector, given their positions in the new vector:
function r=append_interval(a,v,p)

% a - vector with initial values
% v - vector containing values to be inserted
% p - positions for values in v

lv=numel(v); % number of elements in v vector
la=numel(a); % number of elements in a vector

column_a=iscolumn(a); % check if a is a column- or row- wise vector

tot_elements=la+lv;

% size of r is tha max between the total number of elements in the two vectors and the higher positin in vector p (in this case missing positions in a are filled with zeros)
lr=max([max(p) tot_elements]);

% initialize r as nan vector
r=zeros(column_a*(lr-1)+1,~column_a*(lr-1)+1)/0;

% set elements in p position to the corresponding values in v
r(p)=v;

% copy values in a in the remaining positions and fill with zeros missing entries (if any)
tot_missing_values=lr-tot_elements;
if(tot_missing_values)
    remaining_values=cat(2-iscolumn(a),a,zeros(column_a*(tot_missing_values-1)+1,~column_a*(tot_missing_values-1)+1));
else
    remaining_values=a;
end

% insert values
r(isnan(r))=remaining_values;

You can use row-wise or column-wise vectors; the orientation of r will be the same of that of a.
Input:
a =

     3     4     6     8     1     5     8     9     3     7     3     6     2

v =

     1     2     3     4     5

p =

     1     5     9    13    17

Output:
>> append_interval(a,v,p)

ans =

     1     3     4     6     2     8     1     5     3     8     9     3     4     7     3     6     5     2

Every sequence of positive positions is allowed and the function will pad for you with zeros the final vector, in case you indicate a position exceding the sum of the original vector and added items.
For example, if:
v3 =

     1     2     3     4     5     6    90

p3 =

     1     5     9    13    17    30    33

you get:
append_interval(a,v3,p3)

ans =

  Columns 1 through 19

     1     3     4     6     2     8     1     5     3     8     9     3     4     7     3     6     5     2     0

  Columns 20 through 33

     0     0     0     0     0     0     0     0     0     0     6     0     0    90

Hope this will help.


text:
Q: DevExpress DisplayFormat in RowCellStyle Switching application to use DevExpress XtraGrid and implemented customized color and format for row/cells.
For most part formats are being applied correctly. However when applied to a decimal 1000 following format "#,###;(#,###);0" ends up 1000.0000 instead of 1,000.
gridView.RowCellStyle += CellFormatting;
private void CellFormatting(object sender, RowCellStyleEventArgs e)
 {
        if (gridView.IsRowSelected(e.RowHandle))
        {
            e.Appearance.BackColor = SystemColors.Highlight;
            e.Appearance.ForeColor = SystemColors.HighlightText;
            return;
        }

        // get cell by its index
        var gridRow = gridView.GetRow(e.RowHandle);
        TLColumn columnEnum = ((BindableTextBoxColumn)e.Column).ColumnEnum;
        // get new format values
        T row = (T)gridRow;

        e.Column.DisplayFormat.FormatString = row.GetCellFormat(columnEnum);
        e.Appearance.BackColor = row.GetCellBackColor(columnEnum);
        e.Appearance.ForeColor = row.GetCellColor(columnEnum);

 }

A: For bound columns that do not use CustomColumnDisplayText need to set FormatType before setting DisplayFormatString.
e.Column.ColumnType

can show type of the bound property
 private void CellFormatting(object sender, RowCellStyleEventArgs e)
 {
       // get cell by its index
        var gridRow = gridView.GetRow(e.RowHandle);
        var column = (BindableTextBoxColumn)e.Column;
        TLColumn columnEnum = column.ColumnEnum;
        // get new format values
        T row = (T)gridRow;

        e.Column.DisplayFormat.FormatType = (column.IsNumeric) ? FormatType.Numeric : column.DisplayFormat.FormatType;
        e.Column.DisplayFormat.FormatString = row.GetCellFormat(columnEnum);
        if (gridView.IsRowSelected(e.RowHandle))
        {
            e.Appearance.BackColor = SystemColors.Highlight;
            e.Appearance.ForeColor = SystemColors.HighlightText;
            return;
        }
        e.Appearance.BackColor = row.GetCellBackColor(columnEnum);
        e.Appearance.ForeColor = row.GetCellColor(columnEnum);
}


text:
Q: OpenSubKey() returns null for a registry key that I can see in regedit.exe I'm trying to get all the display names of the sub keys within this key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

With this code:
     RegistryKey newKey;
     string val;

     string KeyPath64Bit = @"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall";
     RegistryKey mainKey = Registry.LocalMachine.OpenSubKey(KeyPath64Bit);

     string[] RegKeys64Bits = Registry.LocalMachine.OpenSubKey(KeyPath64Bit).GetSubKeyNames();

     foreach (string s in RegKeys64Bits)
     {
        newKey = mainKey.OpenSubKey(s);
        val = newKey.GetValue("DisplayName", -1, RegistryValueOptions.None).ToString();
        if (val != "-1")
           file64.WriteLine(val);
     }

After running the code I can't find one of the keys I need:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}

And it should have the display name: Microsoft Visual C++ 2010  x64 Redistributable - 10.0.30319, but instead the GetSubKeyNames() method gives me the sub key : {DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}.KB2151757 which doesn't have any display name.
Why can't I get the exact sub key I need ({DA5E371C-6333-3D8A-93A4-6FD5B20BCC6E}) and how can I get it?

A: In Visual Studio 2017 go to
Project > Properties > Build > Uncheck **Prefer 32-bit** and Platform target as **Any CPU**.

A: A 32-bit application on a 64-bit OS will be looking at the HKLM\Software\Wow6432Node node by default. To read the 64-bit version of the key, you'll need to specify the RegistryView:
using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (var key = hklm.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall"))
{
   // key now points to the 64-bit key
}

The API to do this was added in .NET 4.0; if you're still using 3.5, you'll need to use P/Invoke to access the 64-bit keys:
http://www.rhyous.com/2011/01/24/how-read-the-64-bit-registry-from-a-32-bit-application-or-vice-versa/


text:
Q: Running Docker command in java I'm trying to run this command in docker trough java, but i don't know why it only works when i execute the command in the host machine and not trough java (when execute on java it doesn't add or say nothing). i'm 99% sure problem are the ">>" of the echo but i don't know how to fix it.
    private void doCommand(){

    String command = "docker exec -i -t vsftpd bash -c 'echo -e \"myuser5\\nmypass\" >> /etc/vsftpd/virtual_users.txt'";

    try {
        ProcessBuilder pb = new ProcessBuilder(command);

        Process process = pb.start();

        InputStream inputStream = process.getInputStream();

        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        String line = null;

        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    }catch (Exception e){
        e.printStackTrace();
    }

}

A: Error has been resolved, fixed by using https://github.com/docker-java/docker-java


text:
Q: How can I change the string object inside a string object? I'm trying to create a mutable string object by just subclassing str (Unlike the answer to this other question).
Here's my code so far:
class mstr(str):

    def __new__(self, s):

        self.s = list(s)
        return str.__new__(self, s)

    def __getitem__(self, index):
        return self.s[index]

    def __setitem__(self, index, value):
        self.s[index] = value

    def __eq__(self, other):
        return ''.join(self.s) == other

    def __ne__(self, other):
        return ''.join(self.s) != other

    def __lt__(self, other):
        return len(self.s) < len(other)

    def __gt__(self, other):
        return len(self.s) > len(other)

    def __le__(self, other):
        return len(self.s) <= len(other)

    def __ge__(self, other):
        return len(self.s) >= len(other)

    def __add__(self, other):
        return ''.join(self.s) + other

    def __mul__(self, other):
        return ''.join(self.s) * other

    def __hash__(self):
        return hash(''.join(self.s))

    def __str__(self):
        return ''.join(self.s)

def main():

    s = mstr("Hello ")
    s[5] = " World!"
    print(s)

if __name__ == '__main__':

    main()

By just outputting this example, it's easy to be fooled by the __ str __ return value:
Hello World!

It's also easy to be fooled by the return value of __ add __ :
print(s + " Bloody madness!")

Output:
Hello World! Bloody madness!

But the immutable truth is revealed once we pass the mstr itself by the other argument of __ add __, as an example:
print(s + s)

Output:
Hello World!Hello

Removing all the extra methods:
class mstr(str):

    def __new__(self, s):

        self.s = list(s)
        return str.__new__(self, s)

    def __setitem__(self, index, value):
        self.s[index] = value
        self = ''.join(self.s) # Foolish attepmt.

Output of print(s) is just "Hello ".
So, how can I change the string object inside the string object? I mean, WHERE is the string actual and physical content stored in str or object or whatever? Wherever that is, I want to assign there.

A: It's in here:
typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1]; // This part. (Not actually one char.)

    /* ... */
} PyStringObject;

Unless you want to screw with the memory directly with ctypes or something, you can't get at it. If you do screw with it, weird things will break, because the assumption that that data is immutable isn't waived for string subclasses.


text:
Q: Is there any XPath processor for SAX model? I'm looking for an XPath evaluator that doesn't rebuild the whole DOM document to look for the nodes of a document: actually the object is to manage a large amount of XML data (ideally over 2Gb) with SAX model, which is very good for memory management, and give the possibility to search for nodes.
Thank you all for the support!
For all those who say it's not possible: I recently, after asked the question, found a project named "saxpath" (http://www.saxpath.org/), but I can't find any implementing project.

A: XPath DOES work with SAX, and most XSLT processors (especially Saxon and Apache Xalan) do support executing XPath expressions inside XSLTs on a SAX stream without building the entire dom.
They manage to do this, very roughly, as follows :

*

*Examining the XPath expressions they need to match

*Receiving SAX events and testing if that node is needed or will be needed by one of the XPath expressions.

*Ignoring the SAX event if it is of no use for the XPath expressions.

*Buffering it if it's needed

How they buffer it is also very interesting, cause while some simply create DOM fragments here and there, others use very optimized tables for quick lookup and reduced memory consumption.
How much they manage to optimize largely depends on the kind of XPath queries they find. As the already posted Saxon documentation clearly explain, queries that move "up" and then traverse "horizontally" (sibling by sibling) the document obviously requires the entire document to be there, but most of them require just a few nodes to be kept into RAM at any moment.
I'm pretty sure of this because when I was still making every day webapp using Cocoon, we had the XSLT memory footprint problem each time we used a "//something" expression inside an XSLT, and quite often we had to rework XPath expressions to allow a better SAX optimization.

A: SAX is forward-only, while XPath queries can navigate the document in any direction (consider parent::, ancestor::, preceding:: and preceding-sibling:: axis). I don't see how this would be possible in general. The best approximation would be some sort of lazy-loading DOM, but depending on your queries this may or may not give you any benefit - there is always a worst-case query such as //*[. != preceding::*].

A: Sorry, a slightly late answer here - it seems that this is possible for a subset of XPath - in general it's very difficult due to the fact that XPath can match both forwards and backwards from the "current" point. I'm aware of two projects that solve it to some degree using state machines: http://spex.sourceforge.net & http://www.cs.umd.edu/projects/xsq. I haven't looked at them in detail but they seem to use a similar approach.

A: I'll toss in a plug for a new project of mine, called AXS. It's at https://code.google.com/p/annotation-xpath-sax/ and the idea is that you annotate methods with (forward-axis-only) XPath
statements and they get called when the SAX parser is at a node that matches it. So with a document
<doc>
<nodes>
  <node name="a">text of node 1</node>
  <node name="b">text of node 2</node>
  <node otherattr="I have attributes!">text of node 3</node>
</nodes>
</doc>

you can do things like
@XPath("/nodes/node")
void onNode(String nodeText)
{
  // will be called with "text of node [123]"
}

or
@XPathStart("//node[@name='']")
void onNode3(Attrs node3Attrs) { ... }

or
@XPathEnd("/nodes/node[2]")
void iDontCareAboutNode3() throws SAXExpression
{
  throw new StopParsingExpression();
}

Of course, the library is so new that I haven't even made a release of it yet, but it's MIT licensed, so feel free to give it a try and see if it matches your need. (I wrote it to
do HTML screen-scraping with low enough memory requirements that I can run it on
old Android devices...) If you find bugs, please let me know by filing them on the
googlecode site!

A: There are SAX/StAX based XPath implementations, but they only support a small subset of XPath expressions/axis largely due to SAX/StAX's forward only nature.. the best alternative I am aware of is extended VTD-XML, it supports full xpath, partial document loading via mem-map.. and a max document size of 256GB, but you will need 64-bit JVM to use it to its full potential

A: My current list (compiled from web search results and the other answers) is:

*

*http://code.google.com/p/xpath4sax/

*http://spex.sourceforge.net/

*https://github.com/santhosh-tekuri/jlibs/wiki/XMLDog (also contains a performance chart)

*http://www.cs.umd.edu/projects/xsq/ (uniersity project, dead since 10 years, GPL)

*MIT-Licensed approach http://softwareengineeringcorner.blogspot.com/2012/01/conveniently-processing-large-xml-files.html

*Other parsers/memory models supporting fast XPath:

*

*http://vtd-xml.sourceforge.net/ ("The world's fastest XPath 1.0 implementation.")

*http://jaxen.codehaus.org/ (contains http://www.saxpath.org/)

*http://www.saxonica.com/documentation/sourcedocs/streaming/streamable-xpath.html
The next step is to use the examples of XMLDog and compare the performance of all these approaches. Then, the test cases should be extended to the supported XPath expressions.

A: We regularly parse 1GB+ complex XML files by using a SAX parser which extracts partial DOM trees that can be conveniently queried using XPath. I blogged about it here: http://softwareengineeringcorner.blogspot.com/2012/01/conveniently-processing-large-xml-files.html - Sources are available on github - MIT License.

A: What you could do is hook an XSL transformer to a SAX input source. Your processing will be sequential and the XSL preprocessor will make an attempt to catch the input as it comes to fiddle it into whatever result you specified. You can use this to pull a path's value out of the stream. This would come in especially handy if you wanted to produce a bunch of different XPATH results in one pass.
You'll get (typically) an XML document as a result, but you could pull your expected output out of, say, a StreamResult with not too much hassle.

A: Have a look at the streaming mode of the Saxon-SA XSLT-processor.
http://www.saxonica.com/documentation/sourcedocs/serial.html
"The rules that determine whether a path expression can be streamed are:

*

*The expression to be streamed starts with a call on the document() or doc() function.

*The path expression introduced by the call on doc() or document must conform to a subset of XPath defined as follows:

*any XPath expression is acceptable if it conforms to the rules for path expressions appearing in identity constraints in XML Schema. These rules allow no predicates; the first step (but only the first) can be introduced with "//"; the last step can optionally use the attribute axis; all other steps must be simple Axis Steps using the child axis.

*In addition, Saxon allows the expression to contain a union, for example doc()/(*/ABC | /XYZ). Unions can also be expressed in abbreviated form, for example the above can be written as doc()//(ABC|XYZ).

*The expression must either select elements only, or attributes only, or a mixture of elements and attributes.

*Simple filters (one or more) are also supported. Each filter may apply to the last step or to the expression as a whole, and it must only use downward selection from the context node (the self, child, attribute, descendant, descendant-or-self, or namespace axes). It must not be positional (that is, it must not reference position() or last(), and must not be numeric: in fact, it must be such that Saxon can determine at compile time that it will not be numeric). Filters cannot be applied to unions or to branches of unions. Any violation of these conditions causes the expression to be evaluated without the streaming optimization.

*These rules apply after other optimization rewrites have been applied to the expression. For example, some FLWOR expressions may be rewritten to a path expression that satisfies these rules.

*The optimization is enabled only if explicitly requested, either by using the saxon:stream() extension function, or the saxon:read-once attribute on anXSLT xsl:copy-of instruction, or the XQuery pragma saxon:stream. It is available only if the stylesheet or query is processed using Saxon-SA."
Note:  It is most likely in the commercial version this facility is available.  I've used Saxon extensively earlier, and it is a nice piece of work.

A: Mmh I don't know if I really understand you. As far as I know, the SAX model is event oriented. That means, you do something if a certain node is encountered during the parsing. Yeah, it is better for memory but I don't see how you would like to get XPath into it. As SAX does not build a model, I don't think that this is possible.

A: I don't think xpath works with SAX, but you might take a look at StAX which is an extended streaming XML API for Java.
http://en.wikipedia.org/wiki/StAX

A: The standard javax xpath API technically already works with streams; javax.xml.xpath.XPathExpression can be evaluated against an InputSource, which in turn can be constructed with a Reader. I don't think it constructs a DOM under the covers.

A: Did you have tried also QuiXPath https://code.google.com/p/quixpath/ ?


text:
Q: Control variables in experiments Assume you are trying to test the effect of condition X. You sample people randomly and put them in a manipulation group (condition X) and a control group (condition Y). Simultaneously you want to control for another variable, say gender, so you measure gender, and then when you compare the manipulation group to the control group you control for the gender variable (e.g. through including it in an ANCOVA or a regression).
Is it correct to control for gender in this way, or is it unnecessary, since the sample is random?

A: With random allocation to treatment and control groups, and as your sample size increases, it should become increasingly unnecessary to control for any covariates. However, if chance results in an unusually disproportionate number of females in one of your groups, it's certainly not wrong to control for gender in your analysis. But you will likely need to make it clear why you did control for it and others, or it and not others, by describing the characteristics of each group clearly.

A: It is unnecessary but a good idea since including gender or any other covariate can reduce error and increase power. I don't know what your variables are but gender interacts with many things so I would probably start by looking at the Gender x Condition interaction. Keep in mind that the purpose of randomization is not to equalize the uncontrolled variables but rather to allow their combined effects to be estimated so as to asses the plausiblity that they together with measurement error account for the effect.


text:
Q: gpg keyserver address not available It's a good practice nowadays to verify a hash sum of downloaded tarballs via gnupg with the help of key servers. One of the most used keyserver in my experience is ha.pool.sks-keyservers.net (reports 5M added keys). Very often I get the following error with this key server gpg: keyserver receive failed: Address not available.
It's super annoying. Is this a problem of just sks-keyservers.net? If so, why people keep using it?

A: Seems to be a common error, the solution is to use multiple key servers. There's a simple script how you can do it gpg_verify:
#!/usr/bin/env bash

set -e

if [[ -n "${DEBUG}" ]]; then
    set -x
fi

signature="${1}"
file="${2}"
found="";

declare -a keyservers=(
    "ha.pool.sks-keyservers.net"
    "hkp://keyserver.ubuntu.com:80"
    "hkp://p80.pool.sks-keyservers.net:80"
    "pgp.mit.edu"
)

export GNUPGHOME="$(mktemp -d)"

IFS=';' read -ra keys <<< "${GPG_KEYS}"

for key in "${keys[@]}"; do
    for server in "${keyservers[@]}"; do
        echo "Fetching GPG key ${key} from ${server}"
        gpg --keyserver "$server" --keyserver-options timeout=10 --recv-keys "${key}" && found="yes" && break 2
    done
done

if [[ -z "${found}" ]]; then
    echo >&2 "error: failed to fetch GPG key ${GPG_KEYS}"
    exit 1
fi

gpg --batch --verify "${signature}" "${file}"
rm -rf "${GNUPGHOME}" "${signature}"

Usage:
export GPG_KEYS=[YOUR GPG KEY]
gpg_verify archive.tar.gz.asc archive.tar.gz


text:
Q: ping command doesn't return when pinging a remote server that is down I have a function in a python script that basically checks whether a remote server is up or not using ping. If it is not up then it should wait till it is up and only then return. But the script doesn't return if the remote server is down, if the remote server is up then the script returns.
I have tried both subprocess and os.system, I also tried with various parameters in ping command like -c, -w and -W but nothing seems to help. Any ideas on what I might be doing wrong?
Here is the code:
def waitTillUp():
    command = "ping -c 1 -W 2 " + remoteServer
    response = os.system(command)

    if response == 0:
        print "UP\n"
    else:
        print "Down\n"
    '''
    args = shlex.split(command)
    p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = p.communicate()
    logging.debug("Waiting for the Remote Server to be up")
    while "4 packets transmitted, 4 received" not in output:
        logging.debug("Waiting for the remoteServer to be up")
        p = subprocess.Popen(args, stdout=subprocess.PIPE)
        output, err = p.communicate()
    '''

Ideally it should loop till it is up but just for the sake of checking whether it is returning or not I have just put an if else condition. When the remote server does actually come up, the script is still stuck and not stopping. Once I hit an enter in the window, it returns. Any suggestions are welcome.
Update# 2
Right now I am just trying to do this, not checking for any response or anything. I just hope to let the program fall through to main and then end of program but it is not even doing that.
def waitTillUp():
    command = "ping -c 1 " + Params.storageArray
    response = os.system(command)

I am using lot of subprocess.Popen calls one after the other, so is it possible that some buffer is not getting cleared or something of similar sort? Can this be the reason for the weird behavior?
Update# 3
The problem is probably in the reboot call of the remote server before the code that I have pasted. I changed few things and realized that at the function where I am trying to do a reboot, at that point the function is not returning.
This is the complete code. With logging statements I am able to determine that the call for reboot, below marked as the "CULPRIT CALL" is the point where the execution is getting stuck and doesn't proceed till it gets a ENTER key from the user.
def waitTillUp():
    command = "ping -c 1 " + remoteServer
    response = os.system(command)

def execCmd(op, command):
    logging.info("Executing %s operation(command: %s)" %(op, command))
    args = shlex.split(command)
    sys.stdout.flush()
    p = subprocess.Popen(args, stdout=subprocess.PIPE)
    output, err = p.communicate()
    logging.debug("Output of %s operation: %s" %(op, output))

def install():
    execCmd("chmod", "ssh root@" + remoteServer + " chmod +x ~/OS*.bin")
    execCmd("reboot", "ssh root@" + remoteServer  + " reboot -nf") ### CULPRIT CALL
    waitTillUp()

def main():
    install()


text:
Q: xmlrpc search in odoo database Im using xmlrpc to search data in my postgres odoo database.
When searching in table such res_partner everything is fine.
Now I want to search in res_partner_title, but it doesn't return the ID.
My database content:
myDatabase=# select * from res_partner_title;

id | create_uid |        create_date         |   name    | shortcut | write_uid |         write_date
----+------------+----------------------------+-----------+----------+-----------+----------------------------
 1 |          1 | 2017-12-29 09:26:11.139936 | Madam     | Mrs.     |         1 | 2017-12-29 09:26:11.139936
 2 |          1 | 2017-12-29 09:26:11.139936 | Miss      | Miss     |         1 | 2017-12-29 09:26:11.139936
 3 |          1 | 2017-12-29 09:26:11.139936 | Sir       | Sr.      |         1 | 2017-12-29 09:26:11.139936
 4 |          1 | 2017-12-29 09:26:11.139936 | Mister    | Mr.      |         1 | 2017-12-29 09:26:11.139936
 5 |          1 | 2017-12-29 09:26:11.139936 | Doctor    | Dr.      |         1 | 2017-12-29 09:26:11.139936
 6 |          1 | 2017-12-29 09:26:11.139936 | Professor | Prof.    |         1 | 2017-12-29 09:26:11.139936
(6 rows)

my code:
 myData = myObject.search('res.partner.title', [('shortcut','=','Mr.')])

class MyClass:
def __init__(self, host, port, username, pwd, dbname, context, dbsuperpwd=None,
             dbuser=None, dbpasswd=None):

    self.sock_common = xmlrpclib.ServerProxy ("http://" + host + ":" + str(port) + "/xmlrpc/common")
    self.uid = self.sock_common.login(dbname, username, pwd)
    self.sock = xmlrpclib.ServerProxy("http://" + host + ":" + str(port) + "/xmlrpc/object")
    self.dbname = dbname
    self.pwd = pwd
    self.dbsuperpwd = dbsuperpwd
    self.context = context

def search(self, modelname, query, offset=0, limit=0, order=False,
           context=None):
    context = context or self.context

    for i in range(MAX_RETRIES):
        try:
            return self.sock.execute(self.dbname, self.uid, self.pwd,
                                     modelname, 'search', query, offset,
                                     limit, order, context)
        except socket.error:
            pass

It returns always 1, no matter the filter is.
How can I get 3 (in my example)?
EDIT (adding comment asked data)
context = {'lang': 'es_ES'}
it returns 1 or 0
I've just discovered, it works in odoo9 and fails in odoo10

A: I guess the problem could be the language. You're sending in context es_ES and looking for the shorcut in English, so now try for example to replace your current search domain with [('shortcut','ilike','%Sr.%')].
Take a look at ir_translation table:
  id  | lang  |  src   |            name            | type  | module |   state    | comments | value | res_id
------+-------+--------+----------------------------+-------+--------+------------+----------+-------+--------
 6483 | es_ES | Mister | res.partner.title,name     | model | base   | translated |          | Señor |      3
 6559 | es_ES | Mr.    | res.partner.title,shortcut | model | base   | translated |          | Sr.   |      3


text:
Q: Storing user progress despite database changes for a VLE I'm planning to build a VLE system in Laravel 5 and have previously worked with Moodle and built a small VLE in CakePHP. I'm able to build the logic for assigning users to courses, giving courses lessons and questions to lessons as well as storing user progress through a specific course. However my only issue which was out of scope from my original CakePHP VLE is how to handle a user who is part way through a course when the course is updated.
The easiest way I could see for the system to work would be to invalidate previous lesson completions if the lesson is updated and require the user to retake the lesson. Unless the course has been completed then the lesson would stay completed. However then I have the problem if the user having completed questions that might no longer exist.
Is there any standard way of handling data with potentially changing relationships? Or any advise for handing situations like this? The only way I can picture avoiding any issues is to store all the users questions answers and completed lessons as JSON then use that data to output to the user on the front end.


text:
Q: Why is $T^* -\bar{\lambda}I$ not one-to-one? From Friedberg's Linear Algebra

Let $T$ be a linear operator on a finite-dimensional inner product space $V$. If $T$ has an eigenvector, then so doess $T$*.
Proof. Suppose that $v$ is an eigenvector of $T$ with corresponding eigenvalue $\lambda$. Then for any $x \in V$,
$0 = \langle 0,x \rangle = \langle(T - \lambda\ I)(v),x \rangle = \langle v,(T-\lambda\ I)^*(x)\rangle = \langle v, (T^*-\bar{\lambda} I)(x)\rangle$,
and hence $v$ is orthogonal to the range of $T^* -\bar{\lambda}I$. So $T^* -\bar{\lambda}I$ is not onto and hence is not one-to-one. Thus $T^* -\bar{\lambda}I$ has a nonzero null space, and any nonzero vector in this null space is an eigenvector of $T*$ with correspoinding eigenvalue $\bar{\lambda}.$

I'm unable to see why  $T^* -\bar{\lambda}I$ is not one-to-one, and why $T^* -\bar{\lambda}I$ has a nonzero null space.

A: Not onto: Assume it's onto, then exists $x'\in V$ s.t. $0=\langle v,(T^*-\bar\lambda I)(x')\rangle=\langle v,v\rangle,$ so $v=0,$ which contradicts $v\not=0.$
Not one-one: Since $T^*:V\to V, I_V:V\to V,$ clearly $(T^*-\bar\lambda I):V\to V,$ so $$\dim(V)=Nullity(T^*-\bar\lambda I)+Rank(T^*-\bar\lambda I),$$
but $Rank(T^*-\bar\lambda I)\lt\dim(V)$ since we just observed, so $Nullity(T^*-\bar\lambda I)\gt0$.

A: Lauds to our colleague Vizag for his elegant demonstration that
$\lambda \; \text{an eigenvalue of} \; T \Longrightarrow \bar \lambda \; \text{an eigenvalue of} \; T^\dagger; \tag 1$
however, his work on this subject leaves unaddressed the title question, that is,
$\text{"Why is} \; T^\dagger - \bar \lambda I \; \text{not one-to-one?"} \tag 2$
I wish to take up this specific topic here, and provide a sort of "classic" answer; specifically, I wish to demonstrate the essential and well-known result,
"A linear map $S:V \to V$ from a finite dimensional vector space to itself is one-to-one if and only if it is onto."
Note: in what follows we allow $V$ to be a vector space over any base field $\Bbb F$.
Proof:  The argument is based upon elementary notions of basis and linear independence.
We first assume $S:V \to V$ is onto.  Then we let $w_1, w_2, \dots w_n$ be a basis for $V$ over the field $\Bbb F$, and we see, since $S$ is surjective, that there must be a set of vectors $v_i$, $1 \le i \le n$, with
$Sv_i = w_i, \; 1 \le i \le n; \tag 3$
I claim the set $\{ v_i \mid 1 \le i \le n \}$ is linearly independent over $\Bbb F$; for if not, there would exist $\alpha_i \in \Bbb F$, not all zero, with
$\displaystyle \sum_1^n \alpha_i v_i = 0; \tag 4$
then
$\displaystyle \sum_1^n \alpha_i w_i = \sum_1^n \alpha_i Sv_i = S \left (\sum_1^n \alpha_i v_i \right ) = S(0) = 0; \tag 5$
but this contradicts the linear independence of the $w_i$ unless
$\alpha_i = 0, \; 1 \le i \le n; \tag 6$
but condition (6) is precluded by our assumption that not all the $\alpha_i = 0$; therefore the $v_i$ are linearly independent over $\Bbb F$ and hence form a basis for $V$; then any $x \in V$ may be written
$x = \displaystyle \sum_1^n x_i v_i, \; x_i \in \Bbb F; \tag 7$
now suppose $S$ were not injective.  Then we could find $x_1, x_2 \in V$ with
$Sx_1 = Sx_2; \tag 8$
if, in accord with (7) we set
$x_1 = \displaystyle \sum_1^n \alpha_i v_i, \tag 9$
$x_2 = \displaystyle \sum_1^n \beta_i v_i, \tag{10}$
then from (8)-(10),
$\displaystyle \sum_1^n \alpha_i w_i = \sum_1^n \alpha_i Sv_i = S \left (\sum_1^n
\alpha_i v_i \right ) = S \left (\sum_1^n \beta_i v_i \right) = \sum_1^n \beta_i Sv_i = \sum_1^n \beta_i w_i, \tag{11}$
whence
$\displaystyle \sum_1^n (\alpha_i - \beta_i) w_i = 0; \tag{12}$
now the linear independence of the $w_i$ forces
$\alpha_i = \beta_i, \; 1 \le i \le n, \tag{13}$
whence again via (9)-(10)
$x_1 = x_2, \tag{14}$
and we see that $S$ is injective.
Going the other way, we now suppose $S$ is injective; and let the set
$\{v_i \mid 1 \le i \le n \}$ form a basis for $V$.  I claim that the vectors $Sv_1, Sv_2, \ldots, Sv_n$ also form a basis; for if not, they must be linearly dependent and we may find $\alpha_i \in \Bbb F$ such that
$\displaystyle S \left ( \sum_1^n \alpha_i v_i \right ) = \sum_1^n \alpha_i Sv_i = 0; \tag{15}$
now with $S$ injective this forces
$\displaystyle \sum_1^n \alpha_i v_i = 0, \tag{16}$
impossible by the assumed linear independence of the $v_i$; thus the $Sv_i$ do form a basis and hence any $y \in V$ may be written
$y = \displaystyle \sum_1^n \beta_i Sv_i = S \left ( \sum_1^n \beta_i v_i \right ); \tag{17}$
thus every $y \in V$ lies in the image of $S$ which at last seen to be onto.
End:  Proof.
If we apply this result to $T^\dagger - \bar \lambda I$ as in the body of the question, we see that, having shown that $T^\dagger - \bar \lambda I$ is not onto, we may conclude it is also not injective by the preceding basic demonstration; but not injective implies the null space is not $\{ 0 \}$, since if $x_1 \ne x_2$ but $Sx_1 = Sx_2$, we have $x_1 - x_2 \ne 0$ but
$S(x_1 - x_2) = Sx_1 - Sx_2 = 0, \tag{18}$
whence $0 \ne x_1 - x_2 \in \ker S \ne \{ 0 \}$.


text:
Q: Mybatis statement with Map parameterType, how to refer to Map directly? I am passing a Map of parameters into a Mybatis select template:
 <select id="summary" parameterType="java.util.Map" resultMap='baseMap'>
...

The Map values have different types (String, Integer, Boolean) and I can refer to them in my query by key (String), e.g.:
where user_id = ${user_id}

So, in order to achieve this it would seem that the Mybatis framework/OGNL calls the Map's get() method, eg: get("user_id")
Is it possible to refer to the Map itself in order to call a different method on the Map itself as part of an OGNL clause? I can't figure out how to refer to the parameter map itself at all.
NOTE: I know that parameterMap is deprecated, but I am not averse to using it if it's the only way

A: There is an (alas undocumented) _parameter key in MyBatis' mapping context that gives you access to the input parameter of your statement. This should allow you access to the Map itself.
You can find more information in this MyBatis issue or in this post.


text:
Q: python requests library errors that i cannot resolve I have been looking for any answer to this for the past 12-hours and I'm finding nothing.
import requests

class TypeSpeed:
    def __init__(self):
        url = "https://www.mit.edu/~ecprice/wordlist.10000"
        r = requests.get(url)
        s = r.content.splitlines()

        print(s)
        input("type here:   ")
        # wpm calc

TypeSpeed()

This is my code. At first, I was consistently getting the error:
ImportError: cannot import name 'Union' from 'typing'

With the traceback:
  File "/home/sam/workspace/personal/proj/type-speed/typing.py", line 2, in <module>
    import requests
  File "/usr/lib/python3.10/site-packages/requests/__init__.py", line 134, in <module>
    from . import packages
  File "/usr/lib/python3.10/site-packages/requests/packages.py", line 15, in <module>
    locals()[package] = __import__(package)
  File "/usr/lib/python3.10/site-packages/idna/__init__.py", line 2, in <module>
    from .core import (
  File "/usr/lib/python3.10/site-packages/idna/core.py", line 5, in <module>
    from typing import Union, Optional

Changed some stuff around but ultimately changed it all back to the way it was. Now, I am getting a different error that I don't understand!
  AttributeError: partially initialized module 'requests' has no attribute 'get' (most likely due to a circular import)

  File "/home/sam/workspace/personal/proj/type-speed/typing.py", line 1, in <module>
    import requests
  File "/usr/lib/python3.10/site-packages/requests/__init__.py", line 134, in <module>
    from . import packages
  File "/usr/lib/python3.10/site-packages/requests/packages.py", line 15, in <module>
    locals()[package] = __import__(package)
  File "/usr/lib/python3.10/site-packages/idna/__init__.py", line 2, in <module>
    from .core import (
  File "/usr/lib/python3.10/site-packages/idna/core.py", line 5, in <module>
    from typing import Union, Optional
  File "/home/sam/workspace/personal/proj/type-speed/typing.py", line 13, in <module>
    TypeSpeed()
  File "/home/sam/workspace/personal/proj/type-speed/typing.py", line 6, in __init__
    r = requests.get(url)

Any assistance in where I'm going wrong would be appreciated, I have literally written this exact code like 30 times in the past and I have no clue why it would throw this error. Thanks in advance!


text:
Q: Why doesn't VS2015 debugger show the function address correctly in the watch window? C++ code in Visual Studio 2015 debugger. Platform: Window 10
The watch window says:
Name:functionPointer Value:0x012812d0  Type:void(*)(float)
Name:printStuff Value:0x01282440   Type:void(float)
Name:&printStuff Value:0x01282440  Type:void(*)(float)
However, the output windows says:
functionPointer = 012812D0 printStuff = 0x012812D0 &printStuff = 0x012812D0
This is the print stuff function
#include<iostream>
using namespace std;
void printStuff(float)
{
    cout << "This is the print stuff function." << endl;
}

const float PI = 3.1415926f;

int main()
{
    void(*functionPointer)(float); // *functionPointer is a pointer
    functionPointer = printStuff;  // *functionPointer point to function printstuff
    cout << "functionPointer = " << functionPointer << "  " << "printStuff = " << printStuff << "  " << "&printStuff = " << &printStuff << endl;
    functionPointer(PI);

    return 0;
}

Output

A: This behavior seems to be because of incremental linking. When it is enabled, the function is assembled in one memory address and another address contains a jump table entry with one jump instruction to the 'real' address. The function is always called by calling the jump table. If you disable incremental linking, the 'detour' via the jump table goes away and also your example case shows just one address.
Everything else seems to show the address to the jump table, but the 'printStuff' and '&printStuff' watch expressions show the actual address where the function code is located.
See also:
jump stubs in PE files


text:
Q: using a constructor in an Activity class and trying to get information out from that constructor to display on the associated screen My activity class contains a constructor that computes some data:
    public IPrintPanelActivity(String title, Object data, byte logoChar,
        String keyName, boolean printNCopies, boolean showPrintButton) {
    /*
     * Configure the panel
     */
    super();
    panelTitle = title;
    this.logoChar = logoChar;

    if (data != null) {
        setTextArea((String) data);
    }
    //put the display print panel here
    SignOnActivity.startMyActivity(context,(String) data,"CORRECT?");

    finish();
}

Then I need this data Object (which is actually a string) to display it in a TextView of the associated layout file. The problem is that I don't know how to get data "out of the constructor" to write something like
myTextView.setText(data);

I found an answer to a question that was asked more than 2 years ago and it seems to be what I need. The problem is that I get a NullPointerException for the context variable.
Here's the definition of the static function startMyActivity:
    public static void startMyActivity(Context context, String paramA, String paramB) {
    // Build extras with passed in parameters
    Bundle extras = new Bundle();
    extras.putString("PARAM_A", paramA);
    extras.putString("PARAM_B", paramB);

    // Create and start intent for this activity
    Intent intent = new Intent(context,IPrintPanelActivity.class);
    intent.putExtras(extras);
    context.startActivity(intent);
}

Do I give you enough information? Please let me know and please help me fix the NullPointerException.

A: Do not create constructors for your Activity classes. The Android OS is responsible for instantiating Activities and will only try to do so with the default constructor. Keep in mind that an Activity may be destroyed and recreated by the system at various times, usually during configuration changes, such as when the device is rotated between portrait and landscape orientations.
Any "arguments" you pass to an Activity should be done using a Bundle in the Intent that starts the Activity. In one of the lifecycle callback methods (e.g. onCreate()) you can call getIntent() and check its extras for data, then do as you wish.
The link you posted where the user Chase create d static method for starting an activity still follows these guidelines. All his method does is compose the Intent and its extras using the arguments of the static method, then calls startActivity using this Intent. He did not create a constructor for the Activity, nor did he ever call new to instantiate an Activity. He just simplified the process of creating the Intent and its extras to start the Activity with the proper data.

A: You don't have constructors explicitly for Activties. You don't instantiate a Activity class. You only declare the Activity in manifest file.
Please read the answer by Raghav Sood
And i quote Raghav

By treating an Activity as a normal Java class, you end up with a null
  context. As most methods in an Activity are called on its Context, you
  will get a null pointer exception, which is why your app crashes.

Can i Create the object of a activity in other class?


text:
Q: removing file from commit (Due to file size on the github) I am beginner with git and i use github that has file size limit. So I had few commits and I wanted to push them to remote repo but I could not because of the file size. I removed the file and made a new commit but it still does not allow me (because of the previous commits)
Is there a way to resolve this problem by reseting or erasing previous commits and making brand new or any other way? Thanks!

A: You can remove that big file from the history of your repo with the BFG repo cleaner tool
$ java -jar bfg.jar --strip-biggest-blobs 500 some-big-repo.git

$ cd some-big-repo.git
$ git reflog expire --expire=now --all
$ git gc --prune=now --aggressive

$ git push

A: The key to moving backwards in commit history in git is
git reset <commit>

Let's say your git graph looks like this:
* commit 3  (HEAD, branch-1)
| Adding a large file
|
|
* commit 2 (branch-2)
| Some changes
|
|
* commit 1

If you have branch-1 checked out in the above example, and do a git reset branch-2, branch-1 will move to commit 2 and the large file will become an "untracked file". All changes to tracked files will be under "Changes not staged for commit". Once you perform the reset, you can then create a new commit by "adding" or "checking out" files as you see fit. This new commit will no longer have the large file in its history and you should be able to push to your remote repository.
You can find more information about git reset here.
While resetting, previous commits will no longer be visible if they don't have a branch pointing to them. If you feel like you might want those old commits back you can, in our example, create a temporary branch pointing to commit 3. Alternatively, you can use git fsck to find your old commits again.


text:
Q: HttpStatus and DownloadData I'm trying to download a file (an image) with RestSharp using the DownloadData method
var client = new RestClient(baseUrl);

var request = new RestRequest("GetImage", Method.GET);

var response = client.DownloadData(request);

This works fine, but if the requests returns an error I cannot see the HttpStatus code.
I could make a Request and check the status:
var client = new RestClient(baseUrl);

var request = new RestRequest("GetImage", Method.GET);

var response = client.Execute(request);

var status = response.StatusCode;

But then I cannot get the image from the Content property.
I'm I missing something obvious?

A: The image data would be in RestResponse.RawBytes


text:
Q: Img dynamic scale into box-height I need to build a website with the same features as seen on http://www.babingtonhouse.co.uk/house The boxes have to be always same height and the images should proportualy scale within the box-height. How can i do that? Unfortunaltey i cannot find the js-code to lear how they did it.
I've tried it with css (img-class: width:100%) but on some sizes the ing will be height than the text-box.
Thanks for any help.
best regards
thomas

A: maybe something like this
http://jsfiddle.net/2jrn208p/1/
HTML:

CSS
#wrap {
    height:90vh
}
.image {

    height:50%;
    background-repeat: no-repeat;
    background-position: center center;
}
#img1 {
    background-image: url('http://i56.tinypic.com/2hr0twi.jpg');
}
#img2 {
    background-image: url('http://media.desura.com/images/members/1/420/419240/SERB_VILLAGE.jpg');
}


text:
Q: Indicate in page title if I have changes to my Recent Activity I often have many tabs open in my browser while I work away, and like many others, I routinely go to my SOFU pages and hit refresh to see if there have been any answers to my questions or comments to my posts or other positive or negative feedback.
I would like to propose a feature request that would provide an addition to the page title that appears on the browser tab/title bar, which would indicate that there has been some recent activity.  This would be triggered at the same time that the Recent Activity mail icon is colored, and preferably also if there has been some modification in my rep.  The indication could look something like the '(1)' that you see on your GMail page title to indicate a new mail in your inbox.  Alternatively, it could be as simple as an asterisk.
It would also be nice if this could be polled via AJAX so that it isn't dependent on a manual or custom-scripted page refresh request.  (Note that I am not requesting an auto update to the full page,  as in this question, but simply an update to the page title).

A: This would be great for those of us who have our browsers minimized while we work on other stuff.
Glancing down at the title is easier than stopping what we're doing, opening up the browser, refreshing the page, minimizing, and getting back into the swing of things regarding our work.


text:
Q: What does the [something] syntax in Swift mean when working with closures? Normally when capturing reference to a property in a closure I would do something like this -
foo { [weak self] in
    self?.bar()
}

But I have also seen this written as -
foo { [bar] in
    bar()
}

What is meant by [bar] and how is this different from capturing a weak self?

A: That [bar] part is a capture list.
It instructs the closures as how values should be captured. When you enter variables in the bracket right before the keyword in, the closure is no longer referencing the original variables, instead the closure creates its own copy within the closure block.

A: That's a capture list, which can be used to resolve strong reference cycles.
If a closure captures variables by reference (which it does for all reference types), the closure could create a strong reference cycle by being the last object to hold a reference to the captured variable.
A weak reference means that it doesn't increase the reference count of the object, so if the last reference to an object is a weak one, its reference count is 0 and hence ARC will deallocate it. This is especially useful for escaping closures, whose lifetime might be longer than the lifetime of the referenced/captured objects and hence the closure could end up holding the last reference to the object and hence wouldn't allow ARC to deallocate it.


text:
Q: How to access Microsoft Graph Api using Jenkins for automation I have recently migrated my test automation project from using smtp protocols to Microsoft Graph Api to automate sending emails and reading the replies. We are getting the access token using ClientSecretCredentialBuilder and we are able to send the emails and read the replies when run locally, however when the same tests are run through jenkins we are facing 404 : Not Found error when trying to send emails.
The Azure app is having all the required permissions to send and read the emails, am I missing anything in the permissions or do I have to install any Jenkins plugin to read the data from Microsoft Graph API services?
Below is the error that I am facing:
com.microsoft.graph.http.GraphServiceException: Error code: ResourceNotFound
Error message: Resource could not be discovered.
POST https://graph.microsoft.com/v1.0/users/1/microsoft.graph.sendMail
SdkVersion : graph-java/v3.2.0
[...]
404 : Not Found
[...]
Thanks in advance for your help

A: Since the code is working locally, I guess the problem lies on the Id of the user you are using.
Is https://graph.microsoft.com/v1.0/users/1/microsoft.graph.sendMail copy and pasted or did you changed the Id before posting it here for security reasons? If you didn't change the url, this should be the issue because you will not have a user with Id: 1. Most of the time, the Id will be a GUID, read more here.
Another possibility would be that you are saving the Id of the user you need for testing in an environment variable and you forgot to add this variable in Jenkins.


text:
Q: Android ViewPager: Show particular page no matter in which direction user swipes I have really worked A LOT trying to get this running, without any results.
I want my ViewPager to go to the next page, no matter if I swipe to the right, left, top, down. The pages should be like a stack of cards and the top one is always swiped away.
I have tried to extend the class ViewPager, with an overridden
public boolean onInterceptTouchEvent(MotionEvent ev) { ... }
method, but this seemed to me to be a little too much effort for this task.
The other idea was to create a gesture listener and set it to the ViewPager via
setOnTouchListener();
but as soon as I did manage to get what I wanted, the transition of pages stopped working.
Lastly, I found a method in ViewPager called
determineTargetPage(...)
which sounds like it could be what I need, but it is private :-(
I am really out of ideas and it seems to me this should not be such a hard task to worry about it so much. Do you have any recommendations on how to proceed? I'd greatly appreciate any help!


text:
Q: Is it possible to add vertical lines to tables produced with R knitr::kable in pdf? I want to produce a table with knitr::kable with vertical lines on the borders and between certain columns. Is there a way to do it?
My output document is pdf.
Thanks!

A: Answer using huxtable:
library(huxtable)
library(dplyr)

as_hux(mtcars[1:5, 1:6], add_colnames = TRUE) %>%
      set_right_border(2:5, everywhere, 0.4) %>%
      set_bottom_border(1, everywhere, 0.4)

You can then save it to PDF with quick_pdf(), or print it within a rmarkdown document.

A: Not too much clear, but maybe this could help:
library(knitr)
library(kableExtra)
library(dplyr)

dt <- mtcars[1:5, 1:6]
dt %>%
kable() %>%
# here you can add the vertical line, in my example, for all the columns
column_spec (1:7,border_left = T, border_right = T) %>%
kable_styling()

And if you need to save it as .pdf:
save_kable(k, "k.pdf")

With k as the result of the code above.


text:
Q: MySql where clause, variable with <> and without comparison When i referring a where clause i saw a code
where status='locked'
and =person_uuid.p_uuid
and users.p_uuid <> 1
order by full_name,users.p_uuid

I confused with unfamiliar syntax of the code.

*

*In where clause there is a variable called person_uuid.p_uuid without any comparison.

*users.p_uuid <> 1

I referred some books and websites. but no solution.
is this valid. if so, what's the meaning of that.

A: Here,
=person_uuid.p_uuid

// there should be value to that column, otherwise it will give error
users.p_uuid <> 1

// implies users.p_uuid not equal to 1

A: Is this the full query,
Some RDBMS have a structure where, the select query selected vales will be directly match,
like in your case
=person_uuid.p_uuid
If the select query is created to select person_id from a table person, it will match the condition as
Select person_id from person where status='locked' and person.person_id = person_uuid.p_uuid and users.p_uuid <> 1 order by full_name,users.p_uuid


text:
Q: How to get the stock price of ^NSEI I want to get the price of nifty index from yahoo finance.  I am using thise code:
import urllib
import re

url= 'https://in.finance.yahoo.com/q?s=^nsei'
htmlfile=urllib.urlopen(url)
htmltext =htmlfile.read()
regex ='(.+?)'
pattern = re.compile(regex)
price =re.findall(pattern,htmltext)
print price

But the output is an empty list.  What is wrong with my code?

A: You need to escape ^ in regex. It should be:
regex ='(.+?)'


text:
Q: How to call custom function from postgresql use objection js knex js I build api use hapi js and postgresql with ORM objection js (knexjs). I create own function in postgresql with two argument. When I try to call my function use objection .raw it's doesn't work. This one of the codes that I have tried and it doesn't work:
let _data = await Model.knex().raw('select * from fn_user_profiling('+ Model.knex().raw('??', ['840018']).toString() +', ' + Model.knex().raw('??', ['human capital']).toString() + ')');

This the error when I run the code:
select * from fn_user_profiling("840018", "human capital") - column "840018" does not exist

I try to follow this thred in this link, but not work for me.
I hope advance can help to give the answer or clue to solve this problems.
Thank you very much.

A: I found the answer. I use objection js to call knex raw.
let _data = await Model.knex().raw('select * from function_name(?, ?)', [arg_1, arg_2]);

I hope this can help someone.


text:
Q: Is there a better way to access variables from one React component to another than just passing it through as parameters? Let's say I have a React component somewhat like this:
function App() {
  const [step, setStep] = useState(0);
  const [someValue, setSomeValue] = useState("xyz");
  const var1 = "abc";
  const var2 = "def";

  function StepZero() {
    return

{someValue}

       <input type="text" id="fname" name="fname" />

{var1} {var2}

       <Button onClick={() => setSomeValue("123")}>Click</Button>

;
  }

  function StepOne() {
    return

{someValue}

      <Button onClick={() => setSomeValue("456")}>Click</Button>

{var1}

{var2}

;
  }

  return (

        {step === 0 ? (
          <StepZero />
        ) : (
          <StepOne />
        )}

  );
}

What happens here is, once someValue gets set, the whole StepZero gets re-rendered and the input lost. Really any user interaction gets reset, e.g. an accordion that got opened.
What resolves this is putting StepZero and StepOne directly into the return function, or putting them outside the App component and then passing all the variables in the params like:
{ var1, var2, someValue, setSomeValue }

Is there a better way to do this that I can separate the two steps into components while still being able to access the states and variables/constants, without state changes re-rendering the components every time, or without having to pass all the required variables as parameters?
Note this example app isn't meant to do anything functionally useful

A: Based on react architecture passing states and variables through props is the best solution.
Now, based on what you requested I have multiple suggestion:

*

*if the constants are resetting, have you tried to save the constants in a ref? (for ex: const var1 = useRef("abc");)

*if you don't want to pass data as props but you want them to share the same variables, you can either add Redux (React-redux) or use React Context (How to use React Context)

*But if you're project isn't big, i'd suggest you pass them as props, similar to the following:
In the parent App component:
 const [step, setStep] = useState(0);
  const [someValue, setSomeValue] = useState("xyz");
  const var1 = useRef("abc");
  const var2 = useRef("def");

And in a separate component
      function StepZero({someValue,var1,var2,setSomeValue}) {
    return

{someValue}

       <input type="text" id="fname" name="fname" />

{var1.current} {var2.current}

       <Button onClick={() => setSomeValue("123")}>Click</Button>

;
  }

A: I think you need to know more about how reactjs its work, and base on that you can go...the main idea you need start think about that react is Component-Based, and thats mean "Build encapsulated components that manage their own state"
so, from this point you can know that we have component which its has a control to manage their state, so this will move to next step..
At first level, we have props, state and context, which all of these concepts will help you to pass/share data
1- Props will used to pass data from higher component to nested component, and its immutable
2- State will track your value change and you can updated it to update needed functions...
3- Context which its used to share data between multiple component without passing a props from higher one to lowest one...
After we know about these details, we need to go to step two, which we need to understand Re-render...
The render spitted to initial render which happens when a component first appears on the screen and re-render happens when React needs to update the app with some new data, and usually its happen base on action or interactive action...
Note: react handle the re-render and know which spesfic part is render and handling to re-render it, its virtual dom and can be controlled very well...
Now lets go to your code:
1- You can pass your details as props, and you can split App component to small component:
function StepZero(props) {
        return

{props.someValue}

           <input type="text" id="fname" name="fname" />

{var1} {var2}

           <Button onClick={() => props.setSomeValue("123")}>Click</Button>

;
      }

      function StepOne(props) {
        return

{props.someValue}

          <Button onClick={() => props.setSomeValue("456")}>Click</Button>

{var1}

{var2}

;
      }

function App() {
      const [step, setStep] = useState(0);
      const [someValue, setSomeValue] = useState("xyz");
      const var1 = "abc";
      const var2 = "def";

      return (

            {step === 0 ? (
              <StepZero {youProps}/>
            ) : (
              <StepOne {youProps}/>
            )}

      );
    }

The second solution is use content React Context
For re-render you need to handling update dependency correctly and if its in loop or list you need to add key
Also, you must know that var1 and var2 will keep re-render since its set direct without state, ref and its put directly in component not a static / const out side the component, so each time you re-render the component its will has a new memory address which its mean a new re-render for any place has lisen to it...

A: First all your child components have to be outside your App function, in order of having their own state.
Secondly you will pass the somevalue state to all your child in a props and lift the state up to your parent with a callback function.
https://reactjs.org/docs/lifting-state-up.html
Something like this (I simplified your code for the example)
function StepZero({val,var1,var2,callback}) {
    return

{val}

       <input type="text" id="fname" name="fname" />

{var1} {var2}

       <Button onClick={() => callback("123")}>Click</Button>

;
  }

function App() {
  const [step, setStep] = useState(0);
  const [someValue, setSomeValue] = useState("xyz");
  const var1 = "abc";
  const var2 = "def";
  return (

       <StepZero val={someValue} var1={var1} var2={var2} callback={setSomeValue} />

  );
}


text:
Q: array_pluck with model result Laravel I have the index function on my app, that shows a table with all users:
public function index(Request $request)
{
    $this->authorize('inet.user.view');
    $users = User::with(['roles', 'groups'])->paginate(10);

    return view('security.users.index', compact('users'));
}

But when I try do make the list of groups and roles, i have many errors. This is table:

            @lang('table.generic.name')

            @lang('table.users.role') & @lang('table.users.group')

        @foreach($users as $user)

                {!! $user->fullname !!}

                {!! ---HERE NEED TO SHOW LIST OF ROLES--- !!}

       @endforeach

Im trying to join with implode(', ', theMethod) and get the names with array_pluck($user, 'roles.name') but doesn't work and $user->pluck('roles.name') neither.
How can i get the list of roles and groups without doing a for in the view?

A: Just iterate over nested collections loaded with the with() method:
@foreach($user->roles as $role)
    {{ $role->name }}
@endforeach

@foreach($user->groups as $group)
    {{ $group->name }}
@endforeach

If you want to use implode(), use pluck() to get names:
implode(', ', $user->roles->pluck('name')->toArray())


text:
Q: Unable to sign in with my Apple ID after updating my iPhone I got a notification to update the software on my iPhone 4S (A1387), so I updated it. After updating completed, it asked to sign in with your Apple ID.
I tried to sign in with my Apple ID, then it asked me to agree to some terms and conditions.
After I agreed to those, it is now showing notification Could Not Sign In several times. So having updated, I am now unable to sign in with my Apple ID.