text:
Q: How to use this class in my code I saw this natural sorting class that Ian Griffiths created (http://www.interact-sw.co.uk/iangblog/2007/12/13/natural-sorting) in C#.
I wanted to use it to sort a List of objects in my own code by the name of the object (also, how would I do it by a field in an object), how would I do so?
I tried, that came up with errors...
    System.Func<MyObjectClass, string> ConvertMyObject = str =>
    {
        return str.ToString();
    };
    listObjects = listObjects.OrderBy(str => Regex.Split(str, "([0-9]+)").Select(ConvertMyObject), new EnumerableComparer<MyObjectClass>());

Thanks!
/// <summary>
/// Compares two sequences.
/// </summary>
/// <typeparam name="T">Type of item in the sequences.</typeparam>
/// <remarks>
/// Compares elements from the two input sequences in turn. If we
/// run out of list before finding unequal elements, then the shorter
/// list is deemed to be the lesser list.
/// </remarks>
public class EnumerableComparer<T> : IComparer<IEnumerable<T>>
{
/// <summary>
/// Create a sequence comparer using the default comparer for T.
/// </summary>
public EnumerableComparer()
{
    comp = Comparer<T>.Default;
}

/// <summary>
/// Create a sequence comparer, using the specified item comparer
/// for T.
/// </summary>
/// <param name="comparer">Comparer for comparing each pair of
/// items from the sequences.</param>
public EnumerableComparer(IComparer<T> comparer)
{
    comp = comparer;
}

/// <summary>
/// Object used for comparing each element.
/// </summary>
private IComparer<T> comp;

/// <summary>
/// Compare two sequences of T.
/// </summary>
/// <param name="x">First sequence.</param>
/// <param name="y">Second sequence.</param>
public int Compare(IEnumerable<T> x, IEnumerable<T> y)
{
    using (IEnumerator<T> leftIt = x.GetEnumerator())
    using (IEnumerator<T> rightIt = y.GetEnumerator())
    {
        while (true)
        {
            bool left = leftIt.MoveNext();
            bool right = rightIt.MoveNext();

            if (!(left || right)) return 0;

            if (!left) return -1;
            if (!right) return 1;

            int itemResult = comp.Compare(leftIt.Current, rightIt.Current);
            if (itemResult != 0) return itemResult;
        }
    }
}
}

A: The natural sorting method he provides is really useful when the 'normal' sort doesn't comply with with what you need. For instance, the 'normal' way to sort strings is alphabetical, so we need a workaround.
However, in your example you're trying to sort a custom object--which means that you get to  supply your own sort rules!
To define those rules, implement IComparable with your own comparison based on whatever field you choose from the object.
You could have the sort first check 'Name' field you described, and if they're a match, then compare the numerical field.
However, if you truly need natural sorting on a given field, then you can still adapt the blog's handy EnumerableComparer with this easier to understand technique. (simply comparing the left's  Regex.Split(str.Replace(" ", ""), "([0-9]+)").Select() to the right's)
Finally, if it's the LINQ expression that's giving you a hard time, check out this LINQ-less approach.


text:
Q: SQL Server 2008 Timeout expired rebuild and reorganize index solve the issue I have a large database with a file stream located on a different disk the server that hosts this database has a large number of another none related databases but the specifications of this server are great, my database throws a timeout exception for some queries from time to time,
every time I rebuild and reorganize the indexes the queries back to work normally, I have created a maintenance plan that do Rebuild, Reorganize and update statistics every 3 hours to avoid such issues, the fill factor for the indexes is 90%,
What are the reasons for this? and how I can avoid this issue without the maintenance plan as it adds an extra overhead on the CPU and the RAM.

A: You have a performance issue at your hands. Investigate it appropriately, using a performance investigation methodology like Waits and Queues. USE is also a great performance troubleshooting framework.
Stop doing random changes in hope something improves. Measure, identify, then act appropriately. Establish baselines. Read the entire Monitor and Tune for Performance chapter on MSDN.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I create a rating slider where the handle, or knob, animates/morphs as it is dragged? Looking to see if something is technically possible before embarking on its development. The ideal scenario would be a rating slider, not dissimilar to this: http://flowplayer.org/tools/rangeinput/, but as I drag the slider across the form of the knob animates.
I've uploaded an image to show what I mean:
http://imageshack.us/photo/my-images/818/examplesliders.jpg
I want to create a rating system that has four metrics, two that morph and two that extend (the bird/egg and balloon that you see here are just example placeholders). Ideally it would be as platform-neutral as possible.
The slider would record a value on that range that we can then process.
Is this possible? If so ideas how much appreciated. Thanks guys.

A: Yes off course it's possible. For example using plugin you have post (jqueryRangeinput) you can monitoring this event:
$(":range").change(function(event, value) {
    //Here you can check how value is change and fadeIn(with FadeIn function) or
    //fadeOut(with FadeOut function) the right image you wants to show.
    //You can replace slider image editing css background .handle class!
});

Hope this could be usefull!


text:
Q: Textbox like gmail login page I want a textbox functionality like a gmail login page textbox. Right now I have code like this:
<script>
        function inputFocus(i){
                if(i.value===i.defaultValue){ i.value=""; i.style.color="#000"; }
        }
        function inputBlur(i){
                if(i.value===""){ i.value=i.defaultValue; i.style.color="#888"; }
        }
</script>
<body>
   <input type="text" name="firstname" title="First Name" style="color:#888;"
          value="First Name" onfocus="inputFocus(this)" onblur="inputBlur(this)" />
   ...
</body>

The problem with this code is when I select the tetbox, type "First Name" and if I reselect the textbox the text is clearing. And also gmail login page textbox functionality looks great, until I type a letter it shows the transperent text. But I don't know how to implement it.

A: For the "transparent text" you need to use the placeholder attribute:
<input type="text" name="firstname" ... placeholder="Email">

A: are you looking for a placeholder ??
If so... you can do like this..
<input type="text" name="somename" id="someid" value="" placeholder="Email">

Placeholder is used to display the text in the text box and will disappear as soon as you start typing..

A: If you want to delete the "transparent text" once start typing, you can use placeholder attribute of input element
This attribute is introduced in HTML5 to handle this scenario without writing any peice of javascript code
Your html code should look like this
<input type="text" name="firstname" placeholder="First Name"/>

This will also work as desired when you delete your text, as it will reset the transparent text back again.
Also, here is a working example on jsfiddle
I also, encourage you to review new elements and attributes introduced in HTML5, it will save a your time writing a lot of javascript to handle already built in functionalities


text:
Q: Asp.net Mvc Routing. "*" meaning in route In ASP.NET MVC routing I have seen "*" in routes:
{Controller}/{Action},{*parameters}

What does this mean?

A: It's a catchall parameter. It must always be the last, if you want to use one, and it will ignore any slashes /. An example:

Home/Index/Foo/Bar/Baz

Controller will be Home, Action will be Index and parameters will be Foo/Bar/Baz.
If you were using {Controller}/{Action}/{parameters} instead, parameters would be Foo while the rest of the URL would be lost.


text:
Q: How to change a commutator of SUSY super-charges into an anti-commutator? I would like to understand an apparently rather simple calculation which checks the closure of the Supersymmetry algebra via the commutator of 2 supersymmetric variations of the type:
$$\delta \phi = i(\epsilon^\alpha Q_\alpha + \overline{Q}_\dot{\alpha} \overline{\epsilon}^\dot{\alpha})\phi$$
where $Q_\alpha$ and $Q_\dot{\alpha}$ are the supercharges and $\phi$ is a complex scalar field.
In the following the commutator $[\delta_1,\delta_2]\phi$ is evaluated:
$$[\delta_1,\delta_2]\phi =-[\epsilon^\alpha_1 Q_\alpha + \overline{Q}_\dot{\alpha} \overline{\epsilon}_1^\dot{\alpha},\epsilon_2^\beta Q_\beta + \overline{Q}_\dot{\beta} \overline{\epsilon}^\dot{\beta}_2]\phi =$$
$$-\left( [\epsilon^\alpha_1 Q_\alpha, \epsilon^\beta_2 Q_\beta] +[\epsilon^\alpha_1 Q_\alpha, \overline{Q}_\dot{\beta} \overline{\epsilon}^\dot{\beta}_2] + [\overline{Q}_\dot{\alpha} \overline{\epsilon}^\dot{\alpha}_1, \epsilon_2^\beta Q_\beta ] +
[\overline{Q}_\dot{\alpha} \overline{\epsilon}^\dot{\alpha}_1,\overline{Q}_\dot{\beta} \overline{\epsilon}^\dot{\beta}_2]\right)\phi$$
Now I assume that the commutators  $[\epsilon^\alpha_1 Q_\alpha, \epsilon^\beta_2 Q_\beta]$ and $[\overline{Q}_\dot{\alpha} \overline{\epsilon}^\dot{\alpha}_1,\overline{Q}_\dot{\beta} \overline{\epsilon}^\dot{\beta}_2]$ are zero.
In the paper (I regret I no longer have the reference) I've seen the calculation, however, the 2 remaining commutators turn into anti-commutators :
$$[\delta_1,\delta_2]\phi =-\left(\epsilon_1^\alpha \left\{Q_\alpha, \overline{Q}_\dot{\beta}\right\}\overline{\epsilon}_2^\dot{\beta}-\epsilon_2^\beta \left\{Q_\beta, \overline{Q}_\dot{\alpha}\right\}\overline{\epsilon}_1^\dot{\alpha}\right)\phi$$
and with simplified notation  the following is obtained($P_\mu$ is the momentum 4-vector):
$$[\delta_1,\delta_2]\phi =-2\left(\epsilon_1 \sigma^\mu\overline{\epsilon}_2 P_\mu- \epsilon_2 \sigma^\mu\overline{\epsilon}_1 P_\mu\right)\phi =
2i\left( \epsilon_1 \sigma^\mu\overline{\epsilon}_2 - \epsilon_2 \sigma^\mu\overline{\epsilon}_1\right)\partial_\mu\phi$$
So in this calculation it is shown that the supersymmetric algebra is closed, however I have no clue at all how the commutator $[\epsilon^\alpha_1 Q_\alpha, \overline{Q}_\dot{\beta} \overline{\epsilon}^\dot{\beta}_2]$  respectively $[\overline{Q}_\dot{\alpha} \overline{\epsilon}^\dot{\alpha}_1,\epsilon^\beta_2 Q_\beta ]$ is changed to $\epsilon_1^\alpha \left\{Q_\alpha, \overline{Q}_\dot{\beta}\right\}\epsilon_2^\dot{\beta}$ respectively $-\epsilon_2^\beta \left\{Q_\beta, \overline{Q}_\dot{\alpha}\right\}\overline{\epsilon}_1^\dot{\alpha}$.
Actually it is only an algebraic problem(however, SUSY algebra is really complicated), however, for me it is particularly curious how a commutator can become an anticommutator.

A: Actually in SUSY, there is only one commutator and it is called graded commutator or super-commutator, which is denoted and defined as follows:
$$
\{ A, B ] = AB - (-1)^{ab} BA
$$
where $a$ and $b$ are the degrees of $A$ and $B$, respectively, which is $1$ if the operator is fermionic and $0$ if it is bosonic. Some textbooks or papers use only [,] notation for graded commutators.
So, if even one of $A$ or $B$ is bosonic, then graded commutator reduces to the usual commutator, otherwise it becomes anti-commutator. This means that the algebra is closed under graded commutation relations of the generators.
Note that $\delta_i$ are bosonic since terms like $\epsilon_i^\alpha Q_\alpha$ are not fermionic as a whole. However, graded commutators satisfy the commutation axioms regardless their arguments. So for the distribution property of a graded commutator over multiplication, the result will be again in terms of graded commutators, even if the arguments were bosonic operators. One may switch graded ones into usual in the end of the calculation, of course.

A: Oktay Dogangun's answer is exactly right:

*

*The only relevant (graded) Lie-bracket is the supercommutator
$$[A,B]_{SC}~:=~AB-(-1)^{|A||B|}BA ,\tag{1}$$
where $|A|$ and $|B|$ denote the Grassmann parities of $A$ and $B$, respectively.

*It is easy to check that the supercommutator satisfies a graded skew/antisymmetry
$$ [A,B]_{SC}~=~-(-1)^{|A||B|}[B,A]_{SC}, \tag{2}$$
a graded Jacobi identity,
$$ \sum_{A,B,C~{\rm cycl.}} (-1)^{|A||C|}[[A,B]_{SC},C]_{SC}~=~0, \tag{3}$$
and a graded Leibniz rule
$$[A,BC]_{SC}~=~[A,B]_{SC}C+ (-1)^{|A||B|}B[A,C]_{SC}, $$
$$[AB,C]_{SC}~=~A[B,C]_{SC}+ [A,C]_{SC}B(-1)^{|B||C|}. \tag{4}$$

*Example: When we reduce a supercommutator $[A_1\ldots A_n,B_1 \ldots B_m]_{SC}$ with the help of the graded Leibniz rule (4) we again get $nm$ terms involving supercommutators $[A_i,B_j]_{SC}$. This explains OP's observation.


text:
Q: Find two solutions of $299x+247y=13$ Applying Euclidean algorithm I got
$299=247+52$
$247=4\cdot 52+39$
$52=39+13$
$39=3\cdot 13+0$
Applying this in reverse order I got
$52-39=13$
$52-(247-4\cdot 52)=13$
$5(299-247)-247=13$
$5\cdot 299-6\cdot 247=13$
$x=5, y=-6$, this is one solution, what is the other solution?

A: You know
$$5\cdot 299-6\cdot 247=13.$$
So, you can have
$$299x+247y=13=5\cdot 299-6\cdot 247,$$
i.e.
$$299(x-5)=247(-6-y)$$
Dividing the both sides by $13$ gives
$$23(x-5)=19(-6-y)$$
Since $23$ and $19$ are coprime, we have
$$x-5=19k,\quad -6-y=23k,$$
i.e.
$$x=19k+5,\quad y=-23k-6$$
where $k\in\mathbb Z$.

A: As $13|(299,247)=13$
from this, we shall have $13$ in-congruent solutions $\pmod{13}$
$299x+247y=13\iff23x+19y=1=23\cdot5-19\cdot6$
$\iff23(x-5)=-19(y+6)$
As $\dfrac{19(y+6)}{23}=5-x$ which is an integer,
$\implies23\mid(y+6)$ as $(19,23)=1$
$\iff y\equiv-6\pmod{23}$
and similarly, $x\equiv5\pmod{19}$

A: Consider an integral solution $(x_0,y_0)$ to the diophantine equation
$$c=ax+by$$
So we have
$$c=ax_0+by_0$$
To generate (infinitely many) more solutions we can just apply an algebraic trick
$$c=ax_0+by_0+abd-abd=a(x_0+bd)+b(y_0-ad)$$
Choosing any $d\in\Bbb{Z}$ gives the solution pair $(x_0+bd,y_0-ad)$ and choosing $d=0$ gives the original solution.


text:
Q: android internal storage I want to make an application to be able to save files on sdcard and on device (files saved on device must be available to gallery and other applications). Where should I save these files on device, so files should be public? Application must support Android 2.1. Thanks

A: http://developer.android.com/guide/topics/data/data-storage.html#filesExternal

Every Android-compatible device supports a shared "external storage" that you can use to save files. This can be a removable storage media (such as an SD card) or an internal (non-removable) storage. Files saved to the external storage are world-readable and can be modified by the user when they enable USB mass storage to transfer files on a computer.

A: Personally think you should try to keep the number of files on the internal storage to a minimum. Normally on mobiles, the internal memory is quite limited so I'd recommend to try not to safe files locally

A: i had your same problem and i solved this way:
when external memory is not available (that's my first choice) ,i use internal memory using getCacheDir as starting path, this way only your application can access those files.
next, when i need to see that files on gallery, i use a contentprovider to obtain access to the file, look at this answer i wrote that solved my problem:
https://stackoverflow.com/a/13935210/1716620


text:
Q: With v12.2, how to call gpg (or gpg4win) and tell it to generate RSA key pair and to return private and public key blocks and fingerprint? Using Mathematica v12.2, is it possible to call gpg (or gpg4win) and then tell it to generate an RSA key pair and to return

*

*private and public PGP key blocks in standand format

*and the 40 hex-character PGP fingerprint,

with all three then processable as Mathematica variables?
(So for example if the fingerprint did not have characters 9-12 spelling "ABC1" you could loop back and keep generating asymmetric key pairs until you found one that did have a fingerprint that met the criterion, and when you did you would have both its public key block and its private key block, as well as the "nice" fingerprint itself.)


text:
Q: Sharing dependencies between maven modules I have the following structure:
main/
  --pom.xml
  --common/
      --pom.xml
  --core/
      --pom.xml

Both common and core are modules of the main projects, so main/pom.xml is like this:
<project>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>main</artifactId>
  <packaging>pom</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>Main APP</name>
  <url>http://maven.apache.org</url>
  <modules>
      <module>common</module>
      <module>core</module>
  </modules>
</project>

Besides that, common/pom.xml is supposed to hold some common dependencies between all future modules. This is how common/pom.xml looks like for now:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>common</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>mod1</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>com.mycompany.app</groupId>
        <artifactId>main</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>common-dependency</groupId>
                <artifactId>common</artifactId>
                <version>3.8.1</version>
            </dependency>
        </dependencies>
    </dependencyManagement>
</project>

Finally, the module core should use dependencies defined in the common module, so this is what I done in core/pom.xml:
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>core</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Core</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>com.mycompany.app</groupId>
        <artifactId>main</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>com.mycompany.app</groupId>
                <artifactId>common</artifactId>
                <version>1.0-SNAPSHOT</version>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

What I wanted is that when I run mvn dependency:copy-dependencies inside core module, maven should copy all the dependencies from common module, also (that common-dependency:common, for example). But actually what happens is that it do not copy any dependency, so it's like if core module didn't had any dependency at all.
What am I missing here?

A: Scope 'import' is for dependencyManagement, that only gives you the versions and default scopes of modules, when you actually use them.
If you want to get the dependencies, you don't need to wrap them in dependencyManagement, and just use transitive dependency mechanism.
So common/pom.xml should be
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>common</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>mod1</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>com.mycompany.app</groupId>
        <artifactId>main</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

        <dependencies>
            <dependency>
                <groupId>common-dependency</groupId>
                <artifactId>common</artifactId>
                <version>3.8.1</version>
            </dependency>
        </dependencies>
</project>

And core/pom.xml should be
<project>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.mycompany.app</groupId>
    <artifactId>core</artifactId>
    <packaging>jar</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>Core</name>
    <url>http://maven.apache.org</url>

    <parent>
        <groupId>com.mycompany.app</groupId>
        <artifactId>main</artifactId>
        <version>1.0-SNAPSHOT</version>
    </parent>

        <dependencies>
            <dependency>
                <groupId>com.mycompany.app</groupId>
                <artifactId>common</artifactId>
                <version>1.0-SNAPSHOT</version>
            </dependency>
        </dependencies>

</project>


text:
Q: How to launch Windows Explorer with the privileges of a different domain user? My Windows 7 computer is connected to a Windows network at the workplace. There are two domains in use on this network, EMPLOYEES and TESTERS. I have logins on both domains, for example EMPLOYEES\Joe and TESTERS\TestJoe.
If I am logged into a computer as EMPLOYEES\Joe, how do I launch a Windows Explorer instance with the privileges of TESTERS\TestJoe? Note that I can switch user and login as TESTERS\TestJoe on this computer without any problem.
I have tried the suggestions given in this post, and they do not work.

A: This works for Windows 7, 8.0, 8.1 and 10

*

*Start the Registry Editor as an Administrative User.

*Navigate to, take ownership of, and grant yourself Full Control permission to the key HKEY_CLASSES_ROOT\AppID\{CDCBCFCA-3CDC-436f-A4E2-0E02075250C2}

*Rename the value RunAs to _RunAs.

*Close Regedit.

*Create a shortcut on the Desktop to C:\Windows\Explorer.exe

*Right-click the shortcut and choose Run as administrator. This will open Explorer in the security context of the Administrator.

A: You don't need to run explorer.exe as a different user just to connect to a network share with different credentials.
In an explorer window you can click on "Map network drive", fill in the path and and make sure to check "Connect using different credentials". When you click the finish button you will get prompted for the credentials you want to use to connect the current share.
You can also accomplish this with the net command on the command line.
net use x: \\server\share /user:testuser@example.com password

A: It seems that Windows actively resists the ability to launch Explorer as a different user. I resolved this issue on my Windows 7 system by doing the following:

*

*take ownership of reg key HK_CLASSES_ROOT\AppID\{CDCBCFCA-3CDC-436f-A4E2-0E02075250C2}, and grant yourself Full Control. This key controls how Explorer is allowed to launch

*rename the subkey from runas to _runas. If you receive an error doing this, then you probably didn't complete step one correctly

Once this is changed, you can launch Explorer with a different set of credentials via the runas command or with the freeware tool CPAU from Joeware.
From command prompt, you can then launch Explorer:

*

*with runas

*

*runas /user:domain\username "c:\windows\explorer.exe /separate"

*followed by completing the password prompt.

*with cpau

*

*cpau.exe  /u domain\username  /p password  /ex "E:\Windows\explorer.exe /separate"
Note:

*

*You have to use the Explorer option /separate to force Explorer to launch as a    separate process. see also

*The advantage of using cpau over runas is that with cpau, you can specify username and password in the command prompt.

*Other than using cpau for my own use, I am not affiliated with Joeware.

A: *

*Go to the Start button;

*Type in Explorer;

*Shift Right-Click "Windows Explorer";

*Run as different user.

That user will also need privileges to access the file system on the local machine, and perform any futher operations you'd like to execute.

A: Open Task Manager and End Task on explorer.exe
From File use 'Run New Task'
In the Run window type: runas /user:domain\username explorer.exe
When you press enter a CMD window should open prompting for the password of the elevated user.
Once entered you can confirm what user is running the Explorer.exe in Task Manager

A: Here is command line batch script if somebody needs one click solution. You'll need to put SubInACL.exe in the folder with script (get it here from Microsoft).
@echo off
Setlocal EnableDelayedExpansion
:check_admin
NET FILE 1>NUL 2>NUL
IF ERRORLEVEL 1 (
    cls
    echo Starting as admin ...
    powershell "saps -filepath %0 -verb runas" >nul 2>&1
    exit
)
cls

:set_privileges
rem Enable explorer to run privileged, src: https://superuser.com/a/591082/145585

echo Setting permissions ...
rem change owner to Administrators
rem should report: Done:        1, Modified        1, Failed        0, Syntax errors        0
%~dp0subinacl.exe /noverbose /statistic /subkeyreg "HKEY_CLASSES_ROOT\AppID\{CDCBCFCA-3CDC-436f-A4E2-0E02075250C2}" /setowner=administrators >nul 2>nul

rem give Administrators full permission
rem should report: Done:        1, Modified        1, Failed        0, Syntax errors        0
%~dp0subinacl.exe /noverbose /statistic /subkeyreg "HKEY_CLASSES_ROOT\AppID\{CDCBCFCA-3CDC-436f-A4E2-0E02075250C2}" /grant=administrators=f >nul 2>nul

echo Rename registry entry ...
powershell -ExecutionPolicy Bypass -Command "Rename-ItemProperty -Path 'Registry::HKEY_CLASSES_ROOT\AppID\{CDCBCFCA-3CDC-436f-A4E2-0E02075250C2}' -Name 'RunAs' -NewName '_Runas' -ErrorAction SilentlyContinue"

:run_explorer
echo Starting explorer ...
start "" /MAX "c:\windows\explorer.exe" "%~dp0"

A: shift and right click the .exe to see the option in question
or from CLI runas /user:"domain\username" "whatever"


text:
Q: Strange popup behavior I have a modal popup controller that I dynamically render on the page defined as follows
<MatDialog @bind-IsOpen="@Open">
    <MatDialogTitle>@Title</MatDialogTitle>
    <MatDialogContent>
        @Content
    </MatDialogContent>
    <MatDialogActions>
        <MatButton OnClick="@Yes">Yes</MatButton>
        <MatButton OnClick="@(e => { Open = false; })">No</MatButton>
    </MatDialogActions>
</MatDialog>

@code {
    [Parameter] public bool Open { get; set; }
    [Parameter] public string Title { get; set; }
    [Parameter] public string Content { get; set; }
    [Parameter] public EventCallback<string> YesCallback { get; set; }

    void Yes()
    {
        Open = false;
        YesCallback.InvokeAsync("deleted");
    }

}

It just meant to close the popup and call the passed in callback function. Issue is if YesCallback.InvokeAsync("deleted"); is called dialog never closes. The callback gets executed but the dialog stays open. If YesCallback.InvokeAsync("deleted"); is removed the dialog closes fine, but, obviously no callback is called.
There are no errors.


text:
Q: Scala IDE (sbt project): Error instead of info I am using Scala IDE for working with a sbt project. I use it to work with Spark and MLlib.
I just run a simple example from the documentation. Everything seems right but the sbt output instead of reporting the log file with "debug" or "info" word in the start of each line, it uses "error" word in the start of each line:
this:
backgroung log: error: 15/04/2013 11:44:19 INFO Executor: Finished task 2.0 in stage 114.0 <TID 219> in 8 ms on localhost <1/4>

instead of this:
backgroung log: info: 15/04/2013 11:44:19 INFO Executor: Finished task 2.0 in stage 114.0 <TID 219> in 8 ms on localhost <1/4>

It's weird! I think it shouldn't use "error" because there is no error and it's just an information. What is your opinion?


text:
Q: conditions for the two functions have the same maximizer I have two quadratic functions $$W(x_1,x_2,\ldots,x_n)=\sum_{i}^{n} a_{ii} x_i^2+ \sum_{i\neq j}^{n} a_{ij}x_ix_j+\sum_{i}^{n} b_{i} x_i, $$  and $$V(x_1,x_2,\ldots,x_n)=\sum_{i}^{n} c_{ii} x_i^2+ \sum_{i\neq j}^{n} c_{ij}x_ix_j+\sum_{i}^{n} d_{i} x_i,$$with $x_i\in[0,1)$. Both functions are subject to constraint $\sum_{i}x_i \leq M$ where $M<n$. All parameters $a_{ii}, a_{ij}$, $b_{ii}$, $b_{ij}$ and $d_i$, $b_{i}$ to be non-negative. Note I split the second order terms, they can be written into one term like $\sum_{i}^{n}\sum_{j}^{n} a_{ij}x_ix_j$.
My question is, when will the two functions have the same maximizer? A sufficient condition is when the parameters are all same: $a_{ij}=c_{ij}$, $b_i=d_i$, for all $i,j$. Or parameters of $V$ is proportional to parameters of $W$. See Why coefficients have to be proportional for two quadratic functions to have the same roots. But is this necessary? Other than special cases where they are multiples of each other, can I have a simple necessary and sufficient condition?
Thanks in advance.


text:
Q: GridView RowCommand copy to clipboard the e.CommandArgument Value Protected Sub GridView_Paga_AT_0_RowCommand(sender As Object, e As GridViewCommandEventArgs)

    If e.CommandName = "C_Nif" Then

        Dim row As GridViewRow = DirectCast(DirectCast(e.CommandSource, Control).NamingContainer, GridViewRow)
        Dim Botao_Nif As ImageButton = TryCast(row.FindControl("ImageButton_C_Nif"), ImageButton)
        Dim Nif As String = e.CommandArgument
        Botao_Nif.Attributes.Add("onclick", "function copyClipboard(){window.clipboardData.setData('Text'," + Nif + ");CopiedTxt.execCommand('Copy');}")

    End If

End Sub

A: After some searching the best solution for me is:
    If e.CommandName = "C_Nif" Then

        Dim row As GridViewRow = DirectCast(DirectCast(e.CommandSource, Control).NamingContainer, GridViewRow)
        Dim Botao_Nif As ImageButton = TryCast(row.FindControl("ImageButton_C_Nif"), ImageButton)

        Dim Nif As String = e.CommandArgument
        Botao_Nif.Attributes.Add("onclick", "window.prompt(""To copy use Ctrl+C. Close with Enter.""," + Nif + ");")

    End If


text:
Q: R: installing package to a different location from R base I am accessing R-3.4 from a location on a shared drive. IT have configured it such that, when I install a package, it will default to installing it on my local drive. In many cases, it succeeds with a warning, but a few packages are failing, saying they can't access other libraries/packages.
The location on the shared drive is available in .libpaths(), and when I specifically install to this location using install.packages("package_name", lib = .libpaths()[2]), these packages install successfully.
Unfortunately, IT have told me I'm not allowed to install to the shared drive. So: is there a way that I can install a package to my local drive, but tell install.packages() to refer to the shared drive for any dependencies?
(This problem has so far arisen with installing arules, RGoogleAnalytics, and googleAnalyticsR, but I suspect they won't be the only ones.)


text:
Q: Adding vertical lines on line graph distorting scale I have a line graph with datetime in the X axis that I modify the format to show HH:MM:SS
fig.update_xaxes(title_font=dict(size=12), tickformat='%X')

Before vertical lines are added, the scale is perfect:

Example 1: vline adding the value: 1970-01-01T00:00:00.000000000:

Example 2 vline adding the value: 1970-01-01T00:01:34.000000000

My vertical line code is:
for loop...
if time in df['ColA'].values:
fig.add_vline(x=df[df['ColA'] == time)]['ColB'].values[0])

ColA and variable time (iterator in the loop) is of type string and has values as such. Values are coming from selected rows indices from a callback
0:00:00
0:01:34

ColB is a datetime64[ns] type:
1970-01-01 00:00:00
1970-01-01 00:01:34

And my graph is a px.line graph with facetted rows and im using ColB on the X axis.
Why is the scale completely changing if the vline value x is of the same type and within the same range?

A: *

*it all comes down to type coercing

*df["ColA"].values returns an array of datetime64[ns]

*inspect fig.data[0].x and it returns an array of datetime.datetime

*make them consistent with pd.Timestamp(time).to_pydatetime()

*have simulated some data, no faceting as you have not included any details of this in your question

ROWS = 20
df = pd.DataFrame({"ColA":pd.date_range("1-jan-1970", freq="4H", periods=ROWS), "ColB":np.random.uniform(1,30, ROWS)})

fig = px.line(df, x="ColA", y="ColB")
fig.update_xaxes(title_font=dict(size=12), tickformat='%X')

for time in df["ColA"].values:
    if time in df['ColA'].values:
        fig.add_vline(x=pd.Timestamp(time).to_pydatetime())

fig


text:
Q: How to skip while or for loops in chrome devtools? I'm working with the code of one application. I use breakpoints in chrome devtools in order to find problems in the code if they are there. But the problem is, that there are many cases with for or while loops.
And in such situations I should press the button "step over next function call" hourly. How can I skip loops?
I only want to skip the loop that I see on the way, but then I also want to see further what happens in the code step by step.
Is it possible to skip loops?
Or maybe You know another way about detailed code control?
Thank You!


text: Q: when is it better to use One Vs All and when to use One Vs One in Statistics and Machine Learning? I would love to further understand the uses and the application because while I understand the difference I still don't know which one is better for which type of problem.


text:
Q: Why my APK running with different performance on same Android version? I build a simple game (APK) with Construct 2 + CLI Cordova + Android Studio (target SDK 27, min SDK 21), then test it on two devices :

*

*Samsung i9082 (Lolipop - cust rom) : Slow performance

*Asus (Lolipop) : Good performance

*Same results when i build it with Phonegapp build.
Its mean old devices no longer supported to run APK with this configuration ? Or there any other explanation / solutions?


text:
Q: ¿Cómo conocer en dónde se ubican los querys en mi aplicación web? Tengo una aplicación web desarrollada bajo maven con el framework Spring y el servidor de aplicaciones en el que se desplega es weblogic que realiza consultas a una base de datos en un servidor. Viendo el código en el index, no logro descubrir cómo manda y qué query manda para realizar las consultas a la base de datos.
En el siguiente código se encuentra el metodo que se supone realiza la búsqueda, al darle clic al botón buscar:

Buscar
Limpiar
<input type="hidden" name="IpCC" id="IpCC" value="" class=""/>

Buscando producto,

 por favor espere...

Y acá está el código de ese método
function informacionProducto() {
    $("#loading").show();
    var formulario = $('#formularioBusqueda');

    if (document.formularioBusqueda.radio2.checked) {
        var x = 0;
        $.post(
            'ConsultasRms/tabla_consultaProductoPromocion.html',
            formulario.serialize(),
            function (data) {
                $("#loading").hide();
                if (data.rows[0].length == 0 && data.rows[1].length == 0) {
                    $("#dialog-NoDataPromocion").dialog("open");
                }
                else {
                    //borramos el contenido de los option del select
                    //$("#comboboxSucursales").html("");
                    //recorremos todas las filas del resultado del proceso que obtenemos en Json
                    comboSucursales = document.getElementById('comboboxSucursales');
                    sucursalConsulta = comboSucursales.options[comboSucursales.selectedIndex].text;
                    var listaProductoActivo = data.rows[0];
                    for (x = 0; x < listaProductoActivo.length; x++) {
                        var datarow = {
                            sucursal: sucursalConsulta,
                            numeroSucursal:comboSucursales.options[comboSucursales.selectedIndex].value,
                            ip: ipControlador,
                            sistema: tipoSucursal,
                            codigoPrincipal: listaProductoActivo[x].codigoPrincipal,
                            descripcionCorta: listaProductoActivo[x].descripcionCorta,
                            precio: listaProductoActivo[x].precio,
                            precioPromocion: listaProductoActivo[x].precioPromocion,
                            pvJusto: listaProductoActivo[x].pvJusto,
                            statusProducto: listaProductoActivo[x].statusProducto
                        };
                        datarowRmsDetalle[cont] = {
                            descripcionLarga: listaProductoActivo[x].descripcionLarga,
                            iva: listaProductoActivo[x].iva,
                            estado: listaProductoActivo[x].estado,
                            departamento: listaProductoActivo[x].departamento,
                            codigoComponente: listaProductoActivo[x].codigoComponente,
                            codigoPromocion: listaProductoActivo[x].codigoPromocion,
                            fechaInicioPromocion: listaProductoActivo[x].fechaInicioPromocion,
                            fechaFinPromocion: listaProductoActivo[x].fechaFinPromocion
                        };

                        var su = jQuery("#tablaProductoRms")
                                        .jqGrid('addRowData', cont,
                                        datarow);

                        cont++;
                    }

                    var inactivo = "";
                    var listaProductoInactivo = data.rows[1];
                    if (listaProductoInactivo.length > 0) {
                        for (x = 0; x < listaProductoInactivo.length; x++) {

                            inactivo = inactivo + "
" + listaProductoInactivo[x].codigoPrincipal + "
"
                        }
                        $("#etiquetaMensajeInactivo").html(inactivo);
                        $("#dialog-DataProductoInactivo").dialog("open");
                    }
                }
            }, "json");

No veo en dónde está el query ni ningún archivo al que haga referencia.

del lado de backend encontre este codigo
@RequestMapping("/tabla_consultaProductoPromocion")
public ModelAndView consultaProductoPromocion(HttpServletRequest request, HttpServletResponse response,
                                                  @RequestParam("buscarProductoInput") String codigoPromocion,
                                                  @RequestParam("comboboxSucursales") String sucursal,
                                                  @RequestParam("IpCC") String ipControlador
    ) throws Exception {
        logger.info("Antes de la ejecutar consultaProductoPromocion" + codigoPromocion + ", " + sucursal + ", "
                + ipControlador);
        codigoPromocion = codigoPromocion.replace(" ", "");
        IConsultaProductosRms consultaRms = new ConsultaProductosRms();
        List<String> listaBarra = consultaRms.consultaProductosPromocion(em, codigoPromocion, sucursal);

        List<List<Producto>> listaP = new ArrayList<List<Producto>>();

        listaP.add(0, crearListaProducto(sucursal, consultaRms, listaBarra, "2"));

        listaBarra = consultaRms.consultarProductosPromocionInactivos(em, codigoPromocion, sucursal);

        listaP.add(1, crearListaProducto(sucursal, consultaRms, listaBarra, "1"));

        logger.info("Despu\u00E9s de la ejecutar consultaProductoPromocion retorna: "+ listaP);
        return new ModelAndView("tabla_consultaProductoPromocion", "lista", listaP);
    }
}

por lo que veo realiza las consultas, pero no del estilo sql, alguien podria explicarme como podria modificar esas consultas?
en crearLista reposa el siguiente codigo...
private List<Producto> crearListaProducto(String sucursal, IConsultaProductosRms consultaRms, List<String>
        listaBarra, String estatusProducto) {
    Producto producto = new Producto();
    List<Producto> productos = new ArrayList<Producto>();
    logger.info("Antes de la ejecutar crearListaProducto" + estatusProducto + ", " + sucursal + ", "
            + listaBarra);
    for (String codigoBarra : listaBarra) {

        producto = consultaRms.consultaProducto(em, codigoBarra, sucursal);
        producto.setStatusProducto(estatusProducto);

        productos.add(producto);
    }
    logger.info("Despu\u00E9s de la ejecutar consultaProductoPromocion retorna: "+ productos);
    return productos;
}

realmente lo que puedo ver es que crea la lista con los parametros que recibe y no se mucho, pero luego veo que envia el codigo de barra y hace uso de EM que tengo entendido es el EntityManager, pero a la final no logro ver el query como tal, que en la documentacion de la aplicacion es asi
SELECT DISTINCT temp.codigoPrincipal,temp.item
FROM (SELECT  tmp_barra_primaria.codigoPrincipal,
tmp_barra_primaria.item
FROM item_master       im, vat_item          vi, store             s,
      uda_item_lov      uil, rpm_future_retail rfr2, (
      SELECT decode(im.item_number_type, 'ITEM', im.item, im.item_parent)
      codigoPrincipal,im.item, im.item_desc descripcionLarga, im.short_desc
      descripcionCorta
      FROM item_master im
WHERE im.item_parent = ?1  ) tmp_barra_primaria
LEFT OUTER JOIN(item_loc il) ON (tmp_barra_primaria.codigoPrincipal = il.item
      AND il.loc = ?2) LEFT OUTER JOIN(rpm_future_retail rfr)
ON (tmp_barra_primaria.codigoPrincipal = rfr.item AND rfr.location = ?2 AND
TO_DATE(sysdate, 'DD/MM/YYYY') <=
TO_DATE(rfr.action_date, 'DD/MM/YYYY') AND (to_date(sysdate) - to_date(rfr.
      action_date)) >= 0) LEFT OUTER JOIN(rpm_promo_item_loc_expl rpile) ON (
      tmp_barra_primaria.codigoPrincipal = rpile.item
      AND rpile.location = ?2
      AND TO_DATE(sysdate, 'DD/MM/YYYY') between TO_DATE(rpile.
      detail_start_date, 'DD/MM/YYYY')
      AND to_date(rpile.detail_end_date, 'DD/MM/YYYY'))
      WHERE im.item = tmp_barra_primaria.codigoPrincipal
      AND vi.item = im.item
      AND s.store = ?2
      AND s.vat_region = vi.vat_region
      AND uil.item = im.item
      AND uil.uda_id = 3
      AND rfr2.item = tmp_barra_primaria.codigoPrincipal
      AND rfr2.location = ?2
      AND (to_date(SYSDATE) - to_date(rfr2.action_date)) >= 0
ORDER BY (RFR2.ACTION_DATE) DESC ) TEMP

Ese es el que necesito modificar y no logro conseguir de esa forma.

A: Se está ejecutando una petición AJAX al servidor. Exactamente, esta es la URL del servicio: ConsultasRms/tabla_consultaProductoPromocion.html. Esto se denota en la siguiente llamada de jquery:
$.post(
    'ConsultasRms/tabla_consultaProductoPromocion.html',
    //resto de parámetros...

Revisa en tu proyecto, en la parte de backend, algún controlador que atienda las peticiones POST para esta URL. Siguiendo esa traza encontrarás los queries, tablas y demás elementos asociados.
Basado en tu edición, se puede saber que tu aplicación está desarrollada usando el patrón de arquitectura de capas. Es decir, tu aplicación debe estar dividida en capas, una dedicada para atender el request, otra para manejar los queries, otra para aplicar las reglas de negocio, etc. Esto significa que no esperes que los queries estén en el mismo método o clase donde se encuentra el código para atender el request. De momento, tienes lo siguiente en tu controlador:
listaP.add(0, crearListaProducto(sucursal, consultaRms, listaBarra, "2"));

La línea invoca a un método crearListaProducto, el cual en su interior es el que debe encargarse de tener la lógica para poder crear la lista de productos con los parámetros que recibe. Te recomiendo que revises las fuentes de ese método, es probable que dentro de ello se encuentren más llamadas a otros métodos, posiblemente de otras clases. Al final, podrás dar cuenta del método que ejecuta el query para insertar en la base de datos. No lo has explicado, pero es probable que tu aplicación utilice algún framework para operar contra la base de datos como JPA/Hibernate o MyBatis, por lo cual la sentencia INSERT no esté escrita explícitamente en el código.


text:
Q: PHP methods outputting HTML with incorrect structure? I have a strange situation that I've never encountered where the returned HTML from my class methods doesn't output in the correct structure. For some unknown reason, everything is nested inside the HTML within the first loop, second loop, etc.
index.php

some html...

<?= $generate->output('short_name',id,'hostname'); ?>

some html...

<?= $generate->output('short_name',id,'hostname'); ?>

some html...

class.generate.php
function __construct() {
    $this->getCopy = new getCopyData();
    $this->getDrive = new getDriveData();
    $this->helper = new helper();

}

function output ($short_name,$id,$hostname) {

    $portCount = $this->getCopy->portCount($hostname, 'total');

    for ($port = 0; $port < $portCount; ++$port) {
        if ($this->getCopy->probePort($hostname,$port)) {
            $default = $this->usbPortDefault($short_name,$id,$hostname,$port);

            return $default;
        } else {
            $details = $this->usbPortDetails($short_name,$id,$hostname,$port);

            return $details;
        }
    }
}

function usbPortDefault($short_name,$id,$hostname,$port) {

    $port_details =  '

----

----

';

    return $port_details;
}

function outputRecords($hostname,$port) {

    //get records data from database
    $records = $this->getCopy->records($hostname,$port);

    //create empty variable for HTML
    $records_html = "";

    foreach ($records as $key => $value) {
        if ($value) {
            $records_html .= '
' .$key. '' .$value. '
';
        } else {
            return '
Unable to get any group or instance
';
        }
    }

    return $records_html;
}

function usbPortDetails($short_name,$id,$hostname,$port) {

  $port_info = '';
  $port_info .= 'bunch of HTML';
  $port_info .= $this->outputRecords($hostname,$port);
  $port_info .= 'bunch of HTML';

  return $port_info;

}

My best guess as to the problem, is that there is an issue with the way I am returning the HTML or something with output buffering. I actually don't know if I need it within my class, but I've taken it out and issue is the same. I've also tried adding output buffering to index.html.
Here is a snippet of the source HTML. The first discrepancy I notice is that the

 highlighted in blue doesn't belong there, it should be inside

 and adjacent to the prior

. After port-data-left should be port-data-right but it's nowhere to be found. I'm almost convinced at this point that there's a missing closing tag somewhere but I can't find it. It's been several years since I seriously did any development :D

EDIT: After further investigation, it appears that the final $port_info is not outputting and may be causing this problem. Is there an issue with $port_info .= $this->outputRecords($hostname,$port); being there?

A: Since you reuse you object instance using $generate, the constructor and destructor methods are only called once in this script.
The constructor starts a new output buffer using ob_start(), which means everything outputted by the output method will be buffered until you flush it.
The issue is, the flush only happens in the destructor, with ob_end_flush(), which is only executed once, after the last output call.
Because you echo the result of the method and start a buffer at the same time, the output must indeed be weird and some nesting / repetition occurs because the next output still adds to the buffer.
As pointed out in the comment, the easiest solution is to turn off the output buffering in the class.
You also need to clear $port_info at the beginning of the method to make this work, although it should be fine, unless $port_info is a global var?
This was probably not cleared in the initial Class in order to make it work when called several times, to concatenate the results (and buffer them, before outputting them all at once)
A good usage of buffers in the middle of a page is to redirect the output of a function to a variable.
For example, you could have a function that echoes code but you don't want it echoed.
You could then do something like:
Some HTML
<?php
ob_start();
call_to_some_function_that_normally_outputs_code();
$myvar = ob_get_clean();
?>
Rest of the HTML


text:
Q: What will store a Key-Value list in Java or an alternate of C# IDictionary in Java? I am new to java development, I am from C# .net, developing android application.
I am looking for Key-Value list to use in Java same as IDictionary in C#.
Thanks

A: Use the Map<K, V> interface, and the HashMap<K, V> class for example. Or see the "All Known Subinterfaces" section in the Map<K, V> interface description for more implementations.
http://download.oracle.com/javase/6/docs/api/java/util/Map.html

A: Java has Hashtable and HashMap
See Differences between HashMap and Hashtable?

A: The interface you are looking for is Map<K, V>.
For an implementation similar to C#'s Dictionary try HashMap<K, V>

A: I've usually preferred java.util.TreeMap to a HashMap.  It's not quite as fast, but you don't have to worry about hashing algorithms or setting the size.  More important, it's memory-friendly because it uses small chunks of memory rather than allocating vast arrays.  If you have close control over your Maps' creation and disposal, know in advance how much data they will hold, and know the number of entries will not vary dramatically as your program runs, use a Hashmap.  Otherwise use a Treemap.
The other really cool Map, which I have yet to encounter the likes of in .NET, is java.util.concurrent.ConcurrentSkipListMap.  This is excellent for multithreaded situations.  It is completely thread safe and it is non-blocking.
(I found this question while looking at one closed for being a duplicate.  I thought both questions could use an answer that mentioned something other than HashMaps, good as HashMaps are for most uses and similar as they are to the C# Dictionary.)

A: You are looking for an alternative to the generic IDictionary in C# which takes (key,value) pairs.
In Java, there is a Dictionary class that is the parent class of any class, which accepts (key,value) pairs.
A HashTable (which extends Dictionary) will suit your need. It performs operations like copy, remove, add, check if an item exists etcetera. However, while IDictionary supports foreach loop in C#, to loop over a HashTable in Java, you will need an Iterator.
An added advantage with HashTables is that it is synchronized, so you would not have to worry about concurrency.
IF however, you are looking for an asynchronous implementation, you should use the HashMap. A HashMap too requires an Iterator to traverse through it.
Undoubtedly, you also need to look at how an Iterator works in Java.

HashTables: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Hashtable.html
HashMaps: http://download.oracle.com/javase/1.4.2/docs/api/java/util/HashMap.html
Iterator: http://download.oracle.com/javase/1.4.2/docs/api/java/util/Iterator.html


text:
Q: Difference in length of lines computed with GeoPandas or in QGIS So, first of all, here is a test file: https://we.tl/t-xqo5KyRlqD
The column length was added using QGIS (v 3.10 A Coruña), field calculator and adding parameter $length.
If the file is opened with geopandas (v 0.6.1), the property length outputs this:
a.length
Out[8]:
0    1581.729679
1     899.177689
2      38.054220
3      47.333848
4     189.591771
5     275.946388
dtype: float64
the values obtained by qgis are:
a['length']
Out[9]:
0    1580.830737
1     898.686067
2      38.033291
3      47.307854
4     189.489982
5     275.796306
Name: length, dtype: float64
As you can see there is a difference of a few centimeters.
Has anyone else experienced this?

A: Yes both are correct. The difference is because one it taking into account the curvature of the earth while the other is not.
See following images:
and


text:
Q: Reading data from a specific line and counting words from nth line to print nth word on that line I have this program that reads a text file. I need to get some data out of it.
The text files look like this:
No.     Ret.Time    Peak Name   Height  Area    Rel.Area    Amount  Type
    min     µS  µS*min  %   mG/L
1   2.98        Fluoride    0.161   0.028   0.72        15.370  BMB
2   3.77        Chloride    28.678  3.784   99.28       2348.830    BMB
Total:          28.839  3.812   100.00      2364.201

I need to start reading from line #29 and from there get the Peak Name and the Amount of each element like Fluoride, Chloride and so on. The example only shows those two elements, but other text files will have more. I know I will need some sort of loop to iterate through those lines starting on line #29 which is where the "1" starts then the "2" which will be the 30th line and so on.
I have tried to make this work, but I am missing something I think and I`m not sure what. Here is my Code.
int lines = 0;
BufferedReader br = new BufferedReader(new FileReader(selectFile.getSelectedFile()));
Scanner sc = new Scanner(new FileReader(selectFile.getSelectedFile()));
String word = null;

while((word =br.readLine()) != null){
    lines++;
    /*if(lines == 29)
    System.out.println(word);*/

    if ((lines == 29) && sc.hasNext())
    count++;
    String value = sc.next();
    if (count == 2)
    System.out.println(value + ",");
}

A: Here's some code for you:
int linesToSkip = 28;

try (BufferedReader br = new BufferedReader(new FileReader(file))) {

    String line;
    while ( (line = br.readLine()) != null) {
        if (linesToSkip-- > 0) {
            continue;
        }

        String[] values = line.split(" +");

        int index = 0;
        for (String value : values) {
            System.out.println("values[" + index + "] = " + value);
            index++;
        }
    }
}

Note that I've surrounded it in a try(expr) {} block to ensure that the reader is closed at the end, otherwise you'll consume resources and possibly lock the file from other processes.
I've also renamed the variable you called word as line to make it clearer what it contains (i.e. a string representing a line in the file).
The line.split(" +") uses a regular expression to split a String into its constituent values. In this case your values have spaces between, so we're using " +" which means 'one or more spaces'. I've just looped through the values and printed them out; obviously, you will need to do whatever it is you need to do with them.
I replaced the line count with a linesToSkip variable that decrements. It's less code and explains better what you're trying to achieve. However, if you need the line number for some reason then use that instead, as follows:
if (++lineCount <= 28) {
    continue;
}

A: If I'm reading it correctly, you are mixing two different readers with the BufferedReader and the Scanner, so you are not going to get the results right changing from one to the other (one is not pointing to the same position than the other). You already have the line in word and you can parse it, no need of using the Scanner. Just skip until line 29 (lines > 29) and then parse the values you want, line by line.

A: You are reading the file twice... try something like this
    int lines = 0;
    BufferedReader br = new BufferedReader(new FileReader(selectFile.getSelectedFile()));
    String line = null;

    while ((line = br.readLine()) != null) {

        if (++lines < 29)
            continue; //this ignores the line

        for(String word : line.split("separator here")) {
            // this will iterate over every word on that line
            // I think you can take it from here
            System.out.println(word);
        }
    }


text:
Q: Remote WMI not working when hosted as Windows Service I am working on Remote WMI. I have done all DCOM settings, CIMV2 and WMI settings for particular User. When I run the application as console app, it works fine and fetches me the data. But when I host the same as Windows service, it is throwing exception as
Message:  Error Message: Access is denied.
(Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
Inner Exception Message:  Stack Trace:
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at System.Management.ManagementScope.InitializeGuts(Object o)
at System.Management.ManagementScope.Initialize()
at RemoteWMIRule.BackupServerRule..ctor()

A: Got Solved by adding Network and Network Service in DCOM Configurations. But still the problem persists in Windows Server 2008 R2 OS. Anything OS specific to be done???!!


text:
Q: Set eventual consistency (late commit) in MySQL Consider the following situation: You want to update the number of page views of each profile in your system. This action is very frequent, as almost all visits to your website result in a page view incremental.
The basic way is update Users set page_views=page_views+1. But this is totally not optimal because we don't really need instant update (1 hour late is ok). Is there any other way in MySQL to postpone a sequence of updates, and make cumulative updates at a later time?
I myself tried another method: storing a counter (# of increments) for each profile. But this also results in handling a few thousands of small files, and I think that the disk IO  cost (even if a deep tree-structure for files is applied) would probably exceed the database.
What is your suggestion for this problem (other than MySQL)?

A: To improve performance you could store your page view data in a MEMORY table - this is super fast but temporary, the table only persists while the server is running - on restart it will be empty...
You could then create an EVENT to update a table that will persist the data on a timed basis. This would help improve performance a little with the risk that, should the server go down, only the number of visits since the last run of the event would be lost.

A: The link posted by James via the comment to your question, wherein lies an accepted answer with another comment about memcached was my first thought also. Just store the profileIds in memcached then you could set up a cron to run every 15 minutes and grab all the entries then issue the updates to MySQL in a batch, but there are a few things to consider.

*

*When you run the batch script to grab the ids out of memcached, you will have to ensure you remove all entries which have been parsed, otherwise you run the risk of counting the same profile views multiple times.

*Being that memcache doesn't support wildcard searching via keys, and that you will have to purge existing keys for the reason stated in #1, you will probably have to setup a separate memcache server pool dedicated for the sole purpose of tracking profile ids, so you don't end up purging cached values which have no relation to profile view tracking. However, you could avoid this by storing the profileId and a timestamp within the value payload, then have your batch script step through each entry and check the timestamp, if it's within the time range you specified, add it to queue to be updated, and once you hit the upper limit of your time range, the script stops.
Another option may be to parse your access logs. If user profiles are in a known location like /myapp/profile/1234, you could parse for this pattern and add profile views this way. I ended up having to go this route for advertiser tracking, as it ended up being the only repeatable way to generate billing numbers. If they had any billing disputes we would offer to send them the access logs and parse for themselves.


text:
Q: Name error with f-strings in python3 I am using the following f-strings in a web application. When I run it locally (before trying on the web) I am getting a name error:
NameError: name 'path' is not defined
But path prints properly and seems to be defined to my mind. What am I doing wrong?
path = f'{PROJECT_PATH["raw_data"]}/cashValues'
print("PATH", path)
filenames = [f'{path}/{i}' for i in filenames]

Thanks
Full traceback:
Traceback (most recent call last):
  File "scripts/TableTransform.py", line 8, in <module>
    class TableTransform(object):
  File "scripts/TableTransform.py", line 14, in TableTransform
    Filenames = [f'{path}/{i}' for i in filenames]
  File "scripts/TableTransform.py", line 14, in <listcomp>
    Filenames = [f'{path}/{i}' for i in filenames]
NameError: name 'path' is not defined

A: It seems that list comprehension in python 3.6.5 has its own scope and is not aware of variables outside of that scope. This is why it was failing.


text:
Q: keep elements in box regardles of amount of text in the first one I have sayings and authors.
if a saying has enough amount of text - everything is ok - first example
if a saying is short - the design is ugly - second example.
how to keep  everything in box and on center - regardles of amount of text in story ?

.wrap{
  height:140px;
  display:flex;
  flex-direction:column;
  justify-content:center;
  padding:0 25px;
  background:gold;
}

.story{
  display:inline-block;
  text-align:justify;
  margin:5px 0;
}

.auth{
  display:inline-block;
  text-align:right;
  margin:5px 0;
}

lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet

author

lorem ipsum dolor sit amet

author

A: as discussed with you in comment you can do it like this, if needed something else please let me know

.wrap{
  display:flex;
  align-items: center;
  justify-content:space-between;
  padding:0 25px;
  background:gold;
margin-bottom: 20px;
flex-direction: column;
}

.story{
  text-align:justify;
  margin:5px 0;
}

.auth{
  margin:5px 0 5px 20px;
  align-self: flex-end;
}

lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet

author

lorem ipsum dolor sit amet

author

lorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit ametlorem ipsum dolor sit amet

author

A: You can try like below:

.wrap{
  height:140px;
  display:flex;
  align-items:center;
  align-content:center;
  flex-wrap:wrap;
  padding:0 25px;
  margin:5px;
  background:gold;
}

.story{
  text-align:justify;
  margin:5px 0;
}

.auth{
  margin:5px 0 5px auto;
}

lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet

author

lorem ipsum dolor sit amet

author

A: Are you asking for your .story text to be horizontally centered if it doesn't fill the full space? There are 2 options.
First, the reason you're not seeing the result you want is because the width of your .story div will be 100%, and there's no easy way to adjust that to fit the content of your text. By the flex property, your div IS centered horizontally; however, it takes up the full width, so you don't notice.
One solution would be to set your text-align to center, but that doesn't seem to be the result you want, since you already have it set to justify.
So the solution I suggest is to reset your horizontal margin from 0 to auto. This will fill the horizontal margin based on the available space equally on each side.
Is this what you're asking for?
Also, as @neaumusic already said, you should remove the duplicate CSS entries.

.wrap{
  height:140px;
  display:flex;
  flex-direction:column;
  justify-content:center;
  padding:0 25px;
  background:gold;
}

.story{
  display:inline-block;
  text-align:justify;
  margin:5px 0;
}

.auth{
  display:inline-block;
  text-align:right;
  margin:5px auto;
}

lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet lorem ipsum dolor sit amet

author

lorem ipsum dolor sit amet

author


text:
Q: Avoiding invalidated pointers while using WinAPI (Windows Core Audio) We are using an instantiation of IMMNotificationClient to notify us of changes that happen with a specific audio device (the Foo sound blaster), but when a Foo blaster that has not yet been installed on the computer yet is plugged in, the program seg-faults (throws an Access Violation) inside of the IMMNotificationClient::OnDeviceStateChanged function
Here's what's causing this to happen as far as I can tell:

*

*plug in the new Foo blaster

*Windows fires off a device state change notification to the IMMNotificationClient

*Before the IMMNotificationClient::OnDeviceStateChanged function can finish execution, Windows invalidates the COM object.

This invalidation happens at seemingly random points in the IMMNotificationClient::OnDeviceStateChanged function.
Here's some sample code:
#include <mmdeviceapi.h>
#include <functiondiscoverykeys_devpkey.h>
#include <string>

class FooSoundBlasterNotifier: public IMMNotificationClient {
    //private member variables
    const char * FOO_BLASTER_NAME = "Foo Blaster";

public:
    HRESULT STDMETHODCALLTYPE OnDeviceStateChanged(LPCWSTR pDeviceId, DWORD newState)
    {
        IMMDeviceEnumerator *pDeviceEnumerator;
        IMMDevice *pDevice;
        IPropertyStore *pStore;
        HRESULT hr = CoInitialize(NULL);
        hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void**)&pDeviceEnumerator);

        if(SUCCEEDED(hr))
        {
            hr = pDeviceEnumerator->GetDevice(pDeviceId, &pDevice);

            if(SUCCEEDED(hr))
            {
                hr = pDevice->OpenPropertyStore(STGM_READ, &pStore);

                if (SUCCEEDED(hr))
                {
                    PROPVARIANT variant;
                    PropVariantInit(&variant);

                    hr = pStore->GetValue(PKEY_Device_FriendlyName, &variant);

                    if (SUCCEEDED(hr))
                    {
                        //Code usually crashes about right here
                        std::wstring friendlyNameW(variant.pwszVal);
                        std::string friendlyName(friendlyNameW.begin(), friendlyNameW.end());
                        if(friendlyName.find(FOO_BLASTER_NAME) != std::string::npos)
                        {
                            //Log the information about state change
                        }
                        //release
                    }
                    //all
                }
                //COM
            }
            //Objects
        }

        return S_OK;
    }

    //Declare other needed functions
};

How can I avoid using an invalidated Windows COM object? Baring that, how do I successfully recover from an access violation without having to close down the whole program?
EDIT
Here's a call trace of where the code is failing:
common_strnlen_simd<1,1,unsigned short>(const unsigned short * const string, const unsigned __int64 maximum_count) Line 152
    at minkernel\crts\ucrt\src\appcrt\string\strnlen.cpp(152)
common_strnlen<1,unsigned short>(const unsigned short * const string, const unsigned __int64 maximum_count) Line 185
    at minkernel\crts\ucrt\src\appcrt\string\strnlen.cpp(185)
wcslen(const wchar_t * string) Line 219
    at minkernel\crts\ucrt\src\appcrt\string\strnlen.cpp(219)
[External Code]
FooSoundBlaster::OnDeviceStateChanged(const wchar_t * pwstrDeviceId, unsigned long dwNewState)
[External Code]

A: The real problem isn't an invalidation of the IMMDevice object, but rather variant.pwszVal being null. A simple check like this:
if(variant.pwszVal /* != NULL, there you go Paul! :) */)
{
    friendlyNameW = variant.pwszVal;
}

should solve the problem in the above code.


text:
Q: Database design for entities with many options I am looking for the best approach to solve the following requirements. "Best" here means that performance beats "beautiful" design, I am not afraid of ugly, but performant designs.
Here are the constraints:

*

*I want to have several Player in my database. I expect to have 20k Players in there, at most.

*There is a bunch of Games there, too - it's a list of about 500 Games. A game won't change once it's in there, but occasionally, a game will have to be added.

*The relationship between Player and Game is as follows: The player either plays a game or he doesn't, and he has a skill (Value from 1 to 5) for every game.

Now here's the part that really gives me headaches: I want to be able to search for multiple Player by specifying multiple Games, a min skill and a max skill. So potentially, I have those 500 games, all compounded by OR, which makes a very long query which isn't very fast. My approach is that I should somehow get rid of the ORs and replace them by ANDs, but if someone is not looking for a specific Game, it means that he is looking for Players who play or don't play that particular Game (Because the user is interested in other Games).
I really hope I am missing something obvious or some trick that prevents me from having hundreds of OR-Clauses in every search request...
I tried it with Parse (hence the tag) and got an error: {"code":154,"message":"too many $or clauses"}

A: The relationship between Player and Game will be another table e.g. Player_Game with columns something like this:

*

*player_id (foreign key to Player)

*game_id (foreign key to Game)

*plays (yes or no)

*skill (integer 1-5)

So if you wanted to be able to search for multiple Players by specifying a single Game, a min skill and a max skill" the SQL query would be:
select player_id
from   player_game
where  game_id = {GAME_ID}
and    skill >= {MIN_SKILL}
and    skill <= {MAX_SKILL};

However, if the user can select multiple games it is harder.  Rather than construct a query with multiple ORs or a big IN list I would probably save the selected games to some kind of temporary table and then query:
select player_id
from   player_game
where  game_id in (select game_id from temp_games_list)
and    skill >= {MIN_SKILL}
and    skill <= {MAX_SKILL};


text:
Q: Strange behavior of drawing image in java I am making an animation by drawing different images dozens of milliseconds after the former one. something like this:
 drawimage(image1,0,0,null);

 try {

   Thread.sleep(100);

 }catch(Exception e){//To do something

 }

 drawimage(image2,0,0,null);

But the first image doesn't show until the second one appear. That means they appear at the same time.
My question is why does this happen?

A: The program, in its current state, draws two images at the same time because there are two draw methods in the loop (if you are indeed using a loop).
In order to solve this issue, you should use only a single draw method and leave the delay in the same place. However, in order to cycle through all of the different image variables (if you have them named as numbers 1,2,3,4...etc in an array) you can use a for loop to draw them:
for (int i = 0; i<  *however many images you have*; i++){
     drawimage(image[i],0,0,null);

     try {

       Thread.sleep(100);

     }catch(Exception e){//To do something

     }
}

Edit
You do not use delays inside the paintComponent. Since you are, that is what is likely causing the issues. Move the delay into the main method of your program.

A:
Me: Where exactly is this code? Is it in a paint/paintComponent method?
OP: it is in paintComponent. I use it to make animation, but I am not sure it is a good way.

You're right it isn't a good way. Don't ever call Thread.sleep in the paintComponent method. I would avoid the Thread.sleep all together and use a javax.swing.Timer.  See more How to Use Swing Timers
See examples here and here and here and here.
You could...
Use a list of Images and every iteration firing of the Timer event, add another Image to the List<Image> and call repaint()
You could...
Have an MyImage object class that has an Image field and a boolean draw field. In the Timer, loop through the MyImage objects and do something like
    for (MyImage image: images) {
        if (!image.isDraw()) {
            image.setDraw(true);
            break;
        }
    }
    repaint();

For the MyImage List just loop through them in the paintComponent method and call it drawImage method, that you create.

Run this exmaple, showing the first option

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.Timer;

public class AnimateImages extends JPanel {
    private static final int IMAGE_ROWS = 10;
    private static final int IMAGE_COLS = 10;
    private static final int IMAGE_SIZE = 50;
    private static final int DIM_WIDTH = IMAGE_COLS * IMAGE_SIZE;

    private final List<MyImage> images;
    private Image image;
    private int currX = -IMAGE_SIZE;
    private int currY;

    public AnimateImages() {
        try {
            image = ImageIO.read(new URL("http://swoo.co.uk/content/images/icons/stackoverflow.png"));
        } catch (IOException ex) {
            Logger.getLogger(AnimateImages.class.getName()).log(Level.SEVERE, null, ex);
        }
        images = createImages();

        Timer timer = new Timer(100, new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                for (MyImage image : images) {
                    if (!image.isDraw()) {
                        image.setDraw(true);
                        break;
                    }
                    repaint();
                }
            }
        });
        timer.start();
    }

    private List<MyImage> createImages() {
        List<MyImage> list = new ArrayList<>();
        for (int i = 0; i < IMAGE_ROWS * IMAGE_COLS; i++) {
            if (currX >= DIM_WIDTH) {
                currX = 0;
                currY += IMAGE_SIZE;
            } else {
                currX += IMAGE_SIZE;
            }
            list.add(new MyImage(image, currX, currY));

        }
        return list;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        for (MyImage img : images) {
            img.draw(g);
        }
    }

    @Override
    public Dimension getPreferredSize() {
        return new Dimension(IMAGE_SIZE * IMAGE_COLS, IMAGE_SIZE * IMAGE_ROWS);
    }

    public class MyImage {

        Image image;
        int x, y;
        boolean draw = false;

        public MyImage(Image image, int x, int y) {
            this.image = image;
            this.x = x;
            this.y = y;
        }

        public void setDraw(boolean draw) {
            this.draw = draw;
        }

        public boolean isDraw() {
            return draw;
        }

        public void draw(Graphics g) {
            if (draw) {
                g.drawImage(image, x, y, IMAGE_SIZE, IMAGE_SIZE, AnimateImages.this);
            }
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new AnimateImages());
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

A: Your answer
You're getting this result because it is printing image1, waiting .1 seconds and then printing image2. Then it doesn't wait at all, the game is immediately updated and then prints image1. Your display time for image2 is microscopic and you're likely only seeing image1 as a result.
Furthermore, the images are never deleted or replaced and so you are constantly drawing images on top of each other which is causing a memory leak, and is likely the cause of you seeing both images.
Considerations
This is a handy little animation class that I got, and still use, from this tutorial. This class is pretty handy and you can add the animated sprites necessary for each animation.
With this class, when you do a drawImage() you can use object.getImage() to extract the current frame of the animation.
Just make sure that you're calling the animation's update() method in your game's main loop so that the animations are constantly being updated.
import java.awt.Image;
import java.util.ArrayList;

public class Animation {

    private ArrayList frames;
    private int currentFrame;
    private long animTime;
    private long totalDuration;

    public Animation() {
        frames = new ArrayList();
        totalDuration = 0;

        synchronized (this) {
            animTime = 0;
            currentFrame = 0;
        }
    }

    public synchronized void addFrame(Image image, long duration) {
        totalDuration += duration;
        frames.add(new AnimFrame(image, totalDuration));
    }

    public synchronized void update(long elapsedTime) {
        if (frames.size() > 1) {
            animTime += elapsedTime;
            if (animTime >= totalDuration) {
                animTime = animTime % totalDuration;
                currentFrame = 0;
            }
            while (animTime > getFrame(currentFrame).endTime) {
                currentFrame++;
            }
        }
    }

    public synchronized Image getImage() {
        if (frames.size() == 0) {
            return null;
        } else {
            return getFrame(currentFrame).image;
        }
    }

    private AnimFrame getFrame(int i) {
        return (AnimFrame) frames.get(i);
    }

    private class AnimFrame {

        Image image;
        long endTime;

        public AnimFrame(Image image, long endTime) {
            this.image = image;
            this.endTime = endTime;
        }
    }

}


text:
Q: Unknown provider: $rootElementProvider <- $rootElement <- $location error in karma run hi i am getting the error while running karma run
controller :
myApp.controller('LookupCtrl', function($scope, $rootScope, LCService, $q, $http,$location) {....}

Here the above controller users LCService
LCService :
myApp.service("AccountService", function($rootScope, $http, $location) {...}

in karma.conf.js file
files: [
            //angular files
            'app/js/vendor/angular/angular.js',
            'app/js/vendor/angular/angular-route.js',
            ...

        ]

i have the 'angular-route.js' in my application as well., but when i run this it shows the following error
Error: [$injector:unpr] Unknown provider: $rootElementProvider<-$rootElement<-$location

how to fix this ?


text:
Q: How to enable Rhino (or any JavaScript Engine) in CQ 5.6? I have some custom logic where I need to evaluate a simple boolean expression. In my IDE I have some unit tests that run fine, but when I'm trying to use it on my CQ 5.6.1 instance, the ScriptEngineManager can't find a JavaScript engine. Though this should be part of a standard java installation on any environment.
ScriptEngineManager sef = new ScriptEngineManager();
ScriptEngine se = sef.getEngineByName("JavaScript");

In the pom I have the following which usually helps:
<Import-Package>*;resolution:=optional</Import-Package>

Usually some system libraries aren't exposed in OSGi when you don't put it into the bootdelegation in the sling.properties, but this didn't work either:
org.osgi.framework.bootdelegation=org.w3c.*,com.sun.script.*,com.yourkit.*, ${org.apache.sling.launcher.bootdelegation}

What else could I try?
EDIT:
Also regarding my comment to Christians answer. I found out that there should be a service in the OSGi:
http://svn.apache.org/repos/asf/sling/trunk/bundles/scripting/javascript/src/main/java/org/apache/sling/scripting/javascript/internal/RhinoJavaScriptEngineFactory.java
But when I try to reference it with the following code, my servlet isn't active anymore:
@Reference
private transient ScriptEngineFactory sef = null;

So it seems it can't inject the factory for some reason. I've seen there could be more than one service implementing this interface, how would I target the correct one (linked above)?
EDIT2:
I now even tried to reference the Rhino factory directly:
@Reference(target = "(component.name=org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngineFactory)")
private transient ScriptEngineFactory sef = null;

With this my servlet tells me it is satisfied:
["Satisfied","Service Name: javax.script.ScriptEngineFactory","Target Filter: (component.name=org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngineFactory)","Multiple: single","Optional: mandatory","Policy: static","Bound Service ID 2004 (org.apache.sling.scripting.javascript.internal.RhinoJavaScriptEngineFactory)"]

But if I access my servlet it doesn't get triggered and the SlingDefaultServlet takes over. Without the above @Reference it is accessible, so it has to do something with it.

A: You need an OSGi capable ScriptEngineManager. See https://devnotesblog.wordpress.com/2011/09/07/scripting-using-jsr-223-in-an-osgi-environment/

A: After almost a whole day of trial and error I found 2 major problems:
First: My compiler plugin was set to use 1.8; I had to revert that to 1.6 so my maven-scr-plugin would create proper manifests again and injection of OSGi services actually works:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
        <source>1.6</source>
        <target>1.6</target>
        <encoding>UTF-8</encoding>
    </configuration>
</plugin>

I have to investigate later how it would be possible to increase that to at least 1.7 (I tried but didn't work either).
Second and the actual answer for my question is simple:
@Reference
private transient ScriptEngineManager sem = null;

Also I had to use javascript instead of JavaScript for the getEngineByName method from the manager. To see what is registered for the engine, you can check out the following path in your OSGi console:
/system/console/status-slingscripting

There all available ScriptEngine are listed with their registered names, extensions and MIME Types.


text:
Q: VB app to web service I know very little about web service but I assumed it would be the solution I was looking for. Basically I made an application in VB that I want to be ubiquitous for a lack of a better word. I need it to receive requests from multiple users and respond all at once. I was told "technically if you write a webservice you can provide as many results back to users as are connected."
Maybe there is another solution for me that will give me the results I want.
Here is an example of what I'm trying to do.
Lets say I make an application in VB that does math.
I now make a website. My website allows for a person to input 1 + 1
they click submit and my website then connects to my VB application running on my server
listening for a request. It accepts the request from my website, and then it solves the math problem and returns the answer back to the website "1 + 1 = 2"
That is only an example of the type of thing I need. My problem is that I can't have multiple people visiting my website all connecting to that same application running on my server so somehow I need the application to be where it can be accessed by multiple users. I was told a web service would be the answer but if there is another solution I'd like to know.
If the only solution is a web service, then how can I manage to either convert the VB app to a web service? Can I have to convert the app to asp.net or some other language? Is there an easier option?

A: Without knowing more about what you're actually doing, I might suggest that building an ASP.NET project around your existing VB code might be a good approach. It's going to be awkward to build any kind of "web service" around an existing (presumably GUI) application, so rebuilding your code inside ASP.NET would be the way to go.

A: How about doing it the push notification way.
http://channel9.msdn.com/posts/Windows-Phone-7-Push-Notification-QuickApp--Web-Service-With-Azure-Publishing-Instructions
You can inform users of your application via a push notification


text:
Q: Cannot insert data in the database using option(textarea) I got this code but it is not inserting the content of the option (textarea) into the database.
connection.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "";
$db = "copy";
$conn = mysqli_connect($dbhost,$dbuser,$dbpass,$db);
?>

submit.php
<?php
include 'connection.php';

$foodA = $_POST['foodA'];
$foodB = $_POST['foodB'];
$foodC = $_POST['foodC'];
$foodD = $_POST['foodD'];
$foodE = $_POST['foodE'];

if(!$_POST['submit']) {
    echo "please fill out the form";
    header('Location: select.html');
}
else {
    $sql = "INSERT INTO remove(foodA, foodB, foodC, foodD, foodE) VALUES (?,?,?,?,?);";
    $stmt = mysqli_prepare($conn, $sql);
    mysqli_stmt_bind_param($stmt,"sssss",$foodA,$foodB,$foodC,$foodD,$foodE);
    mysqli_stmt_execute($stmt);
    echo "User has been added!";
    header('Location: select.html');
}

select.html
<html lang="en">
<title>Catering Service</title>
<meta charset="utf-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="js/js.1.js" type="text/javascript"></script>
</head>
<body>
<form action="submit.php" method="post">

<select multiple="multiple" class="options" id="textarea" >
   <option value="foodA">foodA</option>
   <option value="foodB">foodB</option>
   <option value="foodC">foodC</option>
   <option value="foodD">foodD</option>
   <option value="foodE">foodE</option>
</select>

  <button type="button" id="copy" onclick="yourFunction()">Copy</button>
  <button type="button" id="remove" onclick="yourFunction()">Remove</button>

  <select id="textarea2" multiple class="remove" >

<input type="submit" name="submit" />
</form>
        </select>
        </html>

A: You need to name the <select> so you can use the data.
name="food[]"

Like this
<select multiple="multiple" name="food[]" class="options" id="text area" >
   <option value="foodA">foodA</option>
   <option value="foodB">foodB</option>
   <option value="foodC">foodC</option>
   <option value="foodD">foodD</option>
   <option value="foodE">foodE</option>
</select>

Then if you want the value to be 0 or 1, depending on selected or not, you can use the following to replace this:
$foodA = $_POST['foodA'];
$foodB = $_POST['foodB'];
$foodC = $_POST['foodC'];
$foodD = $_POST['foodD'];
$foodE = $_POST['foodE'];

to
$foodA = 0;
$foodB = 0;
$foodC = 0;
$foodD = 0;
$foodE = 0;

foreach ($_POST['food'] as $value) {
    if($value == 'foodA')
        $foodA = 1;
    if($value == 'foodB')
        $foodB = 1;
    if($value == 'foodC')
        $foodC = 1;
    if($value == 'foodD')
        $foodD = 1;
    if($value == 'foodE')
        $foodE = 1;
}

A: You need to name your select with name=food or something so it will be in $_POST['food']. Each option in the select does not show up in $_POST, only what is selected will be in the name of the select. Each option is not it's own thing.
<select multiple="multiple" name="food" class="options" id="textarea" >
   <option value="foodA">foodA</option>
   <option value="foodB">foodB</option>
   <option value="foodC">foodC</option>
   <option value="foodD">foodD</option>
   <option value="foodE">foodE</option>
</select>

When you save the data it will have:
$_POST['food'] with the value of 'foodA' if multiples, it will be 'foodA, foodB'


text:
Q: @Html.EditorFor doesn't return specific types to the controller Let's assume the following, simplified, class structure:
public class Parent
{
    public int ID { get; set; }
}

public class ChildA : Parent
{
    public string Name { get; set; }
}

public class ChildB : Parent
{
    public DateTime Date { get; set; }
}

public class ChildC : Parent
{
    public int NumericData { get; set; }
}

public class ViewModel
{
    public List<Parent> ChildElements { get; set; }
}

As you can see, in my view model I have a list of objects, but these objects can be of different types.
Now, I've found that editor templates work well in this scenario - @Html.EditorFor() selects the right editor as needed depending on the type of the element in the list.
I am, however, having trouble getting meaningful data back from the user to the controller. Upon submitting the form, the view-model contains a list of Parent elements (not the specific sub-types). Worse - the properties specific to each of the Child classes is lost!
What can I do to get all the information for the subtypes back to the controller?

A: When data is posted by to the controller, the MVC framework handles the binding of the request data to your model. Have a look at this link
When it is trying to instantiate your ViewModel, it is probably using the default parameterless constructor for your Parent class, and whatever the actual data being sent back, it cannot assign it to the properties as they don't exist within the Parent class.
You can create your own custom model binder which might solve your problem. Or you could potentially create all the properties in the Parent class, and have different named EditorTemplates.
@Html.EditorFor(x => Model.Parent, "ChildATemplate")

@Html.EditorFor(x => Model.Parent, "ChildBTemplate")

As a general rule it is a good idea to stick to the rule, "One View, One ViewModel", even if it feels like duplication at first. It makes it clear exactly what data is being sent out from the server and exactly what data is being returned.
If 'Parent' represents a complex object, perhaps one that that is persisted into a database and is interacted with from several views, then you can always have an intermediate tier which handles converting data from the view model to your complex class.
EDIT - in response to comment regarding survey questions
Rather than using inheritance, why not accept that you need to duplicate a little of the shared values, and create a class for each question type?
public class QuestionTypeA
{
    public int ID { get; set;}
    public string Name { get; set; }
}

public class QuestionTypeB
{
    public int ID { get; set;}
    public DateTime Date { get; set; }
}

public class QuestionTypeC
{
    public int ID { get; set;}
    public int NumericData { get; set; }
}

public class ViewModel
{
    public List<QuestionTypeA> QuestionAs { get; set; }
    public List<QuestionTypeB> QuestionBs { get; set; }
    public List<QuestionTypeC> QuestionCs { get; set; }
}


text: Q: WebChromeClient open app in chrome browser.I want to open it in WebView.What's the solution for that WebChromeClient open app in chrome browser.I want to open it in WebView.I used WebChromeClient for KitKat devices and for other WebViewClient used. What's the solution for that?


text:
Q: Using Asset_path tag I'm trying to using asset_path in a javascript file but I'm getting a error say the file was not found.
The file is under app/assets/images/Elidium/items/.
new Item(' <%= asset_path '/Elidiun/items/ancienp_hair_olive.png' %>'),

A: <%= asset_path '/Elidiun/items/ancienp_hair_olive.png' %>

should be
<%= asset_path 'Elidiun/items/ancienp_hair_olive.png' %>

I believe the former will mess with the relative URL required to map to /assets/...


text:
Q: Exit For in vb.net will not exit I have these for loops:
For x = search_phone.Length To 0 Step -1
                    For m = 1 To number_call_costs
                        If search_phone.Substring(0, x) = call_costs_data(m, 2) Then
                            match = True

                            customer_cost = callcost_lookup("sequence", call_costs_data(m, 1), customer_sequence, "cost")
                            customer_connection = callcost_lookup("sequence", call_costs_data(m, 1), customer_sequence, "connection")
                            description = call_costs_data(m, 3)
                            MsgBox(call_costs_data(m, 3))
                            Exit For
                            Exit For
                        End If
                    Next
                Next

the data i am testing with is:
search_phone = '101'
call_costs_data(m, 2) = one row is '1' and another row is '101'

its matching search_phone to 101 in the loop but its not exiting, because its matching again to 1

A: That second exit won't be reach, so try it like this:
For x As Integer = search_phone.Length To 0 Step -1
  match = False
  For m As Integer = 1 To number_call_costs
    If search_phone.Substring(0, x) = call_costs_data(m, 2) Then
      match = True
      '// code...
      Exit For
    End If
  Next
  If match Then
    Exit For
  End If
Next


text:
Q: Example of Eigenvalue and Eigenvector in $\mathbb{R^2}$. Let $l$ be a straight line through the origin and let $P_l$ be the transformation
which projects each vector $X$ to $l$.

*

*a) Show that $0$ and $1$ are eigenvalues of $P_l$.

*b)  Find all the eigenvectors which correspond to each of these eigenvalues.

*c) Show that $P_l$ has no eigenvalues except for $0$ and $1$.

I don't know what should I do for $a)$. Can you help for $a)$?


text:
Q: jsPDF css style does not working I'm trying to convert my div to pdf using jsPDF , this is my div :

     <headerp>

</headerp>
     <navp>

</navp>
     <articlep>

Description

    </articlep>
     <footerp style="text-align: center;">Copyright © Emoovio</footerp>

and this is my jquery code :
$('#cmd').click(function () {
var x =  $(".entry-title").text();

        doc.fromHTML($('#pdffile').html(), 15, 15, {
            'width': 170,
            'elementHandlers': specialElementHandlers
        });
        //doc.autoPrint();
        doc.save('emoovio-'+x+'.pdf');

});

and when I excute this code , i have my pdf , but no center , no color , nothing styling !!!

A: To Retain all the styles, try html2pdf.js. It will first convert your HTML page into Image and then as a pdf. You can refer to their documentation for further details.


text:
Q: Error Projecting Raster (.hdf) Using ArcPy I want to project HDF files (MODIS images) to another coordinate system using ArcPy. The following is the code I wrote:
input_ras="N:\\mod16a2\\MOD16A2.A2001001.h24v05.006.2017068142418.hdf"

out_ras= "\test.tif"

# the coordinate system which is required
out_co="G:\\Rathore\\vic_auto7\\shape_proj.prj"

arcpy.ProjectRaster_management(in_raster=input_raster,out_raster=out_ras,out_coor_system=out_co)

This script produces the following error:
ExecuteError                              Traceback (most recent call last)
<ipython-input-95-0d17576ef2fe> in <module>()
 arcpy.ProjectRaster_management(in_raster=input_ras,out_raster="out_ras,out_coor_system=out_co)

C:\Program Files (x86)\ArcGIS\Desktop10.5\ArcPy\arcpy\management.py in ProjectRaster(in_raster, out_raster, out_coor_system, resampling_type, cell_size, geographic_transform, Registration_Point, in_coor_system)
   9700         return retval
   9701     except Exception as e:
-> 9702         raise e
   9703
   9704 @gptooldoc('RegisterRaster_management', None)

ExecuteError: Failed to execute. Parameters are not valid.
Undefined coordinate system for input dataset.
Failed to execute (ProjectRaster).

I checked the projection of input file and it is:
"PROJCS['Unknown_datum_based_upon_the_custom_spheroid_Sinusoidal',GEOGCS['GCS_Unknown_datum_based_upon_the_custom_spheroid',DATUM['D_Not_specified_based_on_custom_spheroid',SPHEROID['Custom_spheroid',6371007.181,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Sinusoidal'],PARAMETER['false_easting',0.0],PARAMETER['false_northing',0.0],PARAMETER['central_meridian',0.0],UNIT['Meter',1.0]]")

A: The way to resolve this is to put in the full projection of the coordinate system for input dataset as an argument to ProjectRaster_management:
arcpy.ProjectRaster_management (ifpn, ofpn, "4326", "NEAREST", "#", "#", "#", "PROJCS['Unknown_datum_based_upon_the_custom_spheroid_Sinusoidal',GEOGCS['GCS_Unknown_datum_based_upon_the_custom_spheroid',DATUM['D_Not_specified_based_on_custom_spheroid',SPHEROID['Custom_spheroid',6371007.181,0.0]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]],PROJECTION['Sinusoidal'],PARAMETER['false_easting',0.0],PARAMETER['false_northing',0.0],PARAMETER['central_meridian',0.0],UNIT['Meter',1.0]]")

ifpn and ofpn are my input and output rasters respectively. If these are already assigned your variables (as you did with input_ras and out_ras), you don't need to reassign them within the function.


text:
Q: time series: find PACF given causal ARMA process $Xt$, find PACF:
$X(t) - cX(t-1) - c^2X(t-2) = Z(t)$
$1 - cz - c^2z^2 = 0, $
$ z= \frac{-1 + \sqrt{5}}{2a}$
and
$z= \frac{-1 - \sqrt{5}}{2a}$
My book (Introduction to Time Series, Brockwell & Davis) defines every alpha as an AR coefficient as seen below. So would that just follow that $α(1)=c$ and $α(2)=c^{2}$ ?

However, the solutions I found online are not consistent with this:

Edit: I did calculate everything through and my book is correct, - the alphas are just AR(p) coefficients. I would be curious to know why it was not the case for the other problem above.


text:
Q: Запуск js-скрипта Всем привет! Каким образом можно "запустить" js-скрипт (содержащий canvas) при определенном событии (например, клик на кнопку)? И так же его завершить.
Я пытался все это дело реализовать с помощью insertAdjacentHTML, который бы добавлял в корневом файле index.html - соответствующий html код, подключающий этот самый канвас, но это добавляет много проблем.

A: Вот пример кнопки с canvas

var button = document.getElementsByClassName('mybutton')[0]; //Получить узел кнопки
var canvas = document.getElementsByClassName('mycanvas')[0]; //Получить узел кнопки
var ctx = canvas.getContext('2d');

function click() {
  ctx.fillRect(0, 0, 30, 30);
  ctx.fillRect(30, 30, 30, 30);
  ctx.fillRect(60, 60, 30, 30);
  ctx.fillRect(90, 90, 30, 30);
}

addEventListener('click', click); //Добавить обработчик событий
*{
  padding: 0px;
  margin: 0px;
}

.mycanvas{
  position: absolute;
  left: 0px;
  top: 0px;
}
.mybutton{
  position: absolute;
  right: 0px;
  top: 0px;
}
<button class='mybutton'>Click me!</button>
<canvas class='mycanvas'></canvas>

<button class='mybutton'>Click me</button>