text:
Q: How do I find out what program 'owns' a hotkey? I'm running XFCE 4.12 on top of Gentoo with a 4.2.0 kernel.  My PlayPause button on my keyboard used to work as a global hotkey for VLC. Now VLC won't even recognize the key.  It does see "Alt + Media Play Pause" but not the key alone.
Is there a way to see if and what program might be capturing that key?
When I run xdotool key "XF86LogGrabInfo" the tail /var/log/Xorg.0.log file reads
[ 10138.690] (II) Printing all currently active device grabs:
[ 10138.690] (II) End list of active device grabs

A: To find out which app/program grabbed your key use the debug keysym XF86LogGrabInfo. Use xdotool to press keys + XF86LogGrabInfo at the same time e.g. in a terminal run
KEY=XF86AudioPlay
xdotool keydown ${KEY}; xdotool key XF86LogGrabInfo; xdotool keyup ${KEY}

Then check for output with tail /var/log/Xorg.0.log
Note that with gnome 3/gdm and systemd this is no longer logged to Xorg.0.log (it's instead logged to the journal). In that case you could
run
journalctl -f

and then in another terminal run the xdotool commands. Switch to the first terminal and you'll see something like
/usr/lib/gdm/gdm-x-session[629]: Active grab 0x40c0a58e (xi2) on device 'Virtual core keyboard' (3):
/usr/lib/gdm/gdm-x-session[629]: client pid 708 /usr/bin/gnome-shell
/usr/lib/gdm/gdm-x-session[629]: at 32595124 (from passive grab) (device frozen, state 6)
/usr/lib/gdm/gdm-x-session[629]: xi2 event mask for device 3: 0xc000
/usr/lib/gdm/gdm-x-session[629]: passive grab type 2, detail 0xac, activating key 172

In the above example the program (the client) that grabbed the key is gnome-shell.
How do I figure out what the keys are called?
Check out the manpage of xdotool using man xdotool or an online version, as it lists a number of the special keys. For instance, "alt+r", "Control_L+J", "ctrl+alt+n", "BackSpace". The LinuxQuestions wiki also has a list of X Keysyms one could use. To make things a bit easier, xdotool also has aliases for some of these, such that  pressing Shift-Alt-Tab would for instance just be shift+alt+Tab. To verify that this does indeed click that key combination, you could send the input to xev, which is a program that will print whatever key or mouse events it gets to the console. Just do sleep 2; xdotool keydown ${KEY} and switch to the xev window before two seconds has passed to see the keys being clicked on that window. It should then output a series of events, such as these:
PropertyNotify event, serial 168, synthetic NO, window 0x1e00001,
    atom 0x13e (_GTK_EDGE_CONSTRAINTS), time 4390512, state PropertyNewValue

MappingNotify event, serial 168, synthetic NO, window 0x0,
    request MappingKeyboard, first_keycode 8, count 248

KeyPress event, serial 168, synthetic NO, window 0x1e00001,
    root 0x163, subw 0x0, time 4390719, (882,657), root:(1000,771),
    state 0x0, keycode 64 (keysym 0xffe9, Alt_L), same_screen YES,
    XLookupString gives 0 bytes:
    XmbLookupString gives 0 bytes:
    XFilterEvent returns: False

KeyPress event, serial 169, synthetic NO, window 0x1e00001,
    root 0x163, subw 0x0, time 4390738, (882,657), root:(1000,771),
    state 0x8, keycode 23 (keysym 0xff09, Tab), same_screen YES,
    XLookupString gives 1 bytes: (09) " "
    XmbLookupString gives 1 bytes: (09) "   "
    XFilterEvent returns: False

A: the following commands helped me to identify all programs grabbing keyboard shortcuts:
$ lsof -c Xorg | grep ".log" # find out the path for the Xorg log file
Xorg    16025   sr    4w      REG              254,1    225839 3933229 /home/sr/.local/share/xorg/Xorg.0.log
$ xdotool key XF86LogGrabInfo # prints all Xorg registered grabs
$ cat /home/sr/.local/share/xorg/Xorg.0.log | grep grabs
[ 39303.019] (II) Printing all currently active device grabs:
[ 39303.019] (II) End list of active device grabs
[ 39303.019] Printing all currently registered grabs
[ 39303.019]   Printing all registered grabs of client pid 16024 xinit /home/sr/.xinitrc -- /etc/X11/xinit/xserverrc :0 vt1 -keeptty -auth /tmp/serverauth.6AO52I3zhe
[ 39303.019]   Printing all registered grabs of client pid 16045 unclutter
[ 39303.019]   Printing all registered grabs of client pid 16047 xscreensaver
[ 39303.019]   Printing all registered grabs of client pid 16109 /usr/lib/firefox/firefox
[ 39303.019]   Printing all registered grabs of client pid 16055 xscreensaver-systemd
[ 39303.019]   Printing all registered grabs of client pid 16057 xbindkeys
[ 39303.027]   Printing all registered grabs of client pid 16039 /usr/bin/openbox --startup /usr/lib/openbox/openbox-autostart OPENBOX
[ 39303.039]   Printing all registered grabs of client pid 16048 copyq
[ 39303.039]   Printing all registered grabs of client pid 16049 konsole
[ 39303.039]   Printing all registered grabs of client pid 16095 /usr/bin/copyq --clipboard-access monitorClipboard
[ 39303.039]   Printing all registered grabs of client pid 16109 /usr/lib/firefox/firefox
[ 39303.039]   Printing all registered grabs of client pid 16456 subl --detached
[ 39303.039]   Printing all registered grabs of client pid 16465 /usr/lib/at-spi2-registryd --use-gnome-session
[ 39303.039]   Printing all registered grabs of client pid 17178 xdotool key XF86LogGrabInfo
[ 39303.039] End list of registered passive grabs

so in my case the following apps were grabbing key bindings: xinit, unclutter, xscreensaver, firefox, xbindkeys, openbox, copyq, konsole, subl, at-spi2-registryd


text:
Q: page external links count in python I need such functions in python:
-check external links count on site pages.
-check if some link is present on given page or not.
Does anybody know good solutions/libs for this task?
I think i should use BeautifulSoup here.., may be something more lib can help?

A: You should be able to use urllib2 module to fetch the page, use beautifulsoup to parse the page and extract the links, store it up in list and match them to check for some existing link. There are number of questions on BeautifulSoup on SO itself.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Showing multiple headers in one column with DataGrid I would like to have more than one property in a column like the following:

Now, it's easy to create a cell template to show more than one property, but how would one go about creating a header template that shows more than one property that still lets you sort by clicking on them? So you should be able to sort by first name just by clicking on First Name header, and same goes for all the other properties.

A: You can use two TextBlock. In Tag property you should transfer name of the property from your data class. This string from Tag property you will use to set SortMemberPath. In the event MouseLeftButtonDown you can get from Tag property name of the actual sort property and assign it to SortMemberPath.
<DataGrid Name="dataGrid1" ItemsSource="{Binding}" AutoGenerateColumns="False" Margin="0,0,0,52">
    <DataGrid.Columns>
        <DataGridTemplateColumn>
            <DataGridTemplateColumn.HeaderTemplate >
                <DataTemplate>
                    <Grid ShowGridLines="True">
                        <Grid.RowDefinitions>
                            <RowDefinition />
                            <RowDefinition />
                        </Grid.RowDefinitions>
                        <TextBlock Text="First Name" Tag="FirstName" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" />
                        <TextBlock Text="Last Name" Grid.Row="1" Tag="LastName" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" />
                    </Grid>
                </DataTemplate>
            </DataGridTemplateColumn.HeaderTemplate>
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition />
                            <RowDefinition />
                        </Grid.RowDefinitions>
                        <TextBox Text="{Binding FirstName}"/>
                        <TextBox Text="{Binding LastName}" Grid.Row="1" />
                    </Grid>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTextColumn Header="Age" Binding="{Binding Age}" />
    </DataGrid.Columns>
</DataGrid>

Code-behind:
private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    TextBlock s = sender as TextBlock;
    string sortPath = s.Tag as string;
    dataGrid1.Columns[0].SortMemberPath = sortPath;
}

You can also add TextBlock style if you want to show which property is currently sorting property and bold it font.
<DataGridTemplateColumn.HeaderTemplate >
    <DataTemplate>
        <Grid ShowGridLines="True">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
            <TextBlock Text="First Name" Tag="FirstName" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown">
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="FontWeight" Value="Normal" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Columns[0].SortMemberPath, ElementName=dataGrid1}">
                                <DataTrigger.Value>
                                    <sys:String>FirstName</sys:String>
                                </DataTrigger.Value>
                                <Setter Property="FontWeight" Value="Bold" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
            <TextBlock Text="Last Name" Grid.Row="1" Tag="LastName" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown" >
                <TextBlock.Style>
                    <Style TargetType="TextBlock">
                        <Setter Property="FontWeight" Value="Normal" />
                        <Style.Triggers>
                            <DataTrigger Binding="{Binding Path=Columns[0].SortMemberPath, ElementName=dataGrid1}">
                                <DataTrigger.Value>
                                    <sys:String>LastName</sys:String>
                                </DataTrigger.Value>
                                <Setter Property="FontWeight" Value="Bold" />
                            </DataTrigger>
                        </Style.Triggers>
                    </Style>
                </TextBlock.Style>
            </TextBlock>
        </Grid>
    </DataTemplate>
</DataGridTemplateColumn.HeaderTemplate>

Where sys is following namespace:
xmlns:sys="clr-namespace:System;assembly=mscorlib"

A: Take a look at this example of StringFormat:
And change the header of your DataGrid column like the example below :
 <DataGrid>
      <DataGrid.Columns>
        <DataGridTemplateColumn>
          <DataGridTemplateColumn.Header>
            <TextBlock  HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
               <TextBlock.Text>
                    <MultiBinding StringFormat="{}{1}{0}{2}">
                        <Binding Source="{x:Static sys:Environment.NewLine}"/>
                        <Binding Path="FirstName" />
                        <Binding Path="LastName"/>
                    </MultiBinding>
            </TextBlock>
          </DataGridTemplateColumn.Header>
      </DataGrid.Columns>
      </DataGrid>

with xmlns:sys="clr-namespace:System;assembly=mscorlib"


text:
Q: make -j4 error opencv on kali linux When I execute the command "make -j4", then it doesn't work.
Below is the output that I am getting. How can I fix this problem?
/usr/include/c++/6/cstdlib:75:25: fatal error: stdlib.h: No such file or directory
 #include_next <stdlib.h>
                         ^
compilation terminated.
modules/viz/CMakeFiles/pch_Generate_opencv_viz.dir/build.make:62: recipe for target 'modules/viz/precomp.hpp.gch/opencv_viz_Release.gch' failed
make[2]: *** [modules/viz/precomp.hpp.gch/opencv_viz_Release.gch] Error 1
CMakeFiles/Makefile2:3227: recipe for target 'modules/viz/CMakeFiles/pch_Generate_opencv_viz.dir/all' failed
make[1]: *** [modules/viz/CMakeFiles/pch_Generate_opencv_viz.dir/all] Error 2
make[1]: *** Waiting for unfinished jobs....
[ 16%] Built target pch_Generate_opencv_test_video
[ 16%] Built target pch_Generate_opencv_video
[ 16%] Built target pch_Generate_opencv_perf_video
Makefile:160: recipe for target 'all' failed
make: *** [all] Error 2


text:
Q: represent $\log_{35}(28)$ by $\log_{14}(7)$ and $\log_{14}(5)$ I'm trying to figure out how to express $\log_{35}(28)$ with $a:=\log_{14}(7)$ and $b:=\log_{14}(5)$
(the hint convert the base to 14 was given).
So, $\log_{35}(28) = \dfrac{\log_{14}(28)}{\log_{14}(35)}$.
I already figured out the denominator is $a+b = \log_{14}(7)+\log_{14}(5) = \log_{14}(5\cdot 7) = \log_{14}(35) \Longrightarrow \log_{35}(28) = \dfrac{\log_{14}(28)}{a+b}$.
But I can't figure out the numerator. My guess is that $7\cdot 5 -\textbf{7}=28$ but there's no rule by which I can perform a subtraction in the argument of the log.
My other guess would be to find something like $x\log_{14}(7)+y\log_{14}(5) =\log_{14}(7^x\cdot 5^y)$ or $x\log_{14}(7)-y\log_{14}(5) =\log_{14}\left(\dfrac{7^x}{5^y}\right)$ so that $7^x\cdot 5^y=28$ or $\dfrac{7^x}{5^y}=28$.
However, I believe that there must be an easier way.

A: You are correct that $\log_{14}28$ cannot be simplified
by expanding $\log_{14}(7\cdot5-7)\ne\log_{14}(7\cdot5)-\log_{14}5$.
Instead, I would suggest using $\log_{14}28=2-\log_{14}7$.
To see that, note that $\log_{14}(28\cdot7)=\log_{14}(14\cdot14)=2$.

A: $$a(\log5+\log7)=2\log2+\log7=2\log2+a\log5+(1-a)\log7=0$$
$$b(\log2+\log7)=\log5\iff b\log2-\log5+b\log7=0$$
Let $c=\log_{14}5,$ $$\implies c\log2-\log5+c\log7=0$$
$$\implies\det\begin{pmatrix} 2  & a & 1-a \\ b  & -1 & b \\ c & -1 &c\end{pmatrix}=0$$


text:
Q: Google Docs Viewer Page, not opening csv files Google Docs Viewer working for all other required file formate like doc,xls, pdf and so on but not opening csv file, it through an error "There was a problem displaying this image."
I want to view csv without any file conversion.


text:
Q: Difference between methods with and without generics Can someone help me understand advantages and disadvantages (if any) between the following methods which do the same function of storing away the entity to azure (in my case)?
public bool Save<T>(string tableName, T entity) where T : TableEntityBase, new()
{
    throw new NotImplementedException();
}

vs
public bool Save(string tableName, TableEntityBase entity)
{
    throw new NotImplementedException();
}

A: With generic method you can pass a parameter T only if

*

*it is a subclass of TableEntityBase and

*have a public parameter-less constructor

Now you can be sure that new T(); won't throw an exception..

but in case of non-generic method
new TableEntityBase();

could throw an exception incase it doesn't have a parameterless constructor


text:
Q: Web Api 2 based service doesn't work on IIS 8.5 where another similar service works properly I have two .NET 4.5.2 Web Api services hosted in IIS 8.5 on Windows Server 2012 R2. One is called CtpVin and the other is called WixTrial.

For all practical purposes, they have the same config files, global.asax files and Wix based installers. The WixTrial service works and downloads a json while CtpVin service gives a 404.
Both have this in the config file:
<system.web>
    <compilation debug="true" targetFramework="4.5.2" />
    <httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
    <handlers>
        <remove name="ExtensionlessUrlHandler-Integrated-4.0" />
        <remove name="OPTIONSVerbHandler" />
        <remove name="TRACEVerbHandler" />
        <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
    </handlers>
</system.webServer>

Here is the 404 error I get:

What am I doing wrong in CtpVin?

A: I was able to figure this out. The issue was with the routes specified in the WebApiConfig.cs file.


text:
Q: Custom IdentifierGenerator returns null So, I want to customize the ID for a "FriendID" with IdentifierGenerator, and I want to make it as simple as possible first just to make sure it works. Been watching tutorials and looked at code examples, but I can't get it to work even though it seems really simple... Might it be something else I'm missing out?
It doesn't seem to reach the GenFriendID-class in the strategy-parameter, because the generator class name is grey and says "Class 'GenFriendID' is never used". The path should be right, and been trying moving them to same package and so on.
Also been trying to drop the DB and rerun the creation of the DB based on the changes (It was GenerationType.AUTO before)
Entity class,
package com.WineOutBE.entity;

import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.io.Serializable;

@Entity
@Table(name = "FriendID")
public class FriendID implements Serializable {

    @Id
    @GenericGenerator(name = "friend_id", strategy = "com.WineOutBE.generator.GenFriendID")
    @GeneratedValue(generator = "friend_id")
    @Column(name = "FriendID", unique = true, length = 6)
    private Long friendid;

    public Long getId() {
        return friendid;
    }

    public void setId(Long FID) {
        this.friendid = FID;
    }
}

Generator class that implements IdentifierGenerator,
package com.WineOutBE.generator;

import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SharedSessionContractImplementor;
import org.hibernate.id.IdentifierGenerator;

import java.io.Serializable;

public class GenFriendID implements IdentifierGenerator {

    @Override
    public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
            return 1234L;
    }
}

Testing method which returns NULL and not 1234,
package com.WineOutBE;

import com.WineOutBE.entity.FriendID;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;

class Testing {

    FriendID friendID;

    @Test
    void checkCorrectIdValue(){
        friendID = new FriendID();

        assertEquals(1234L, friendID.getId());
    }
}

Let me know if there's any other code you need to see and I'll update the post!
Thank you in advance!

A: Id generation will work if you write entity to db
if you execute simple
friendID = new FriendID();
it wont work
save friendID to database using for example EntityManager.merge od spring and than saved object should have id generated


text:
Q: Soft memory limit for AWS ECS task defined by docker-compose.yaml Amazon provides ecs-cli compose command which can set up task definition from docker-compose.yaml
But I am not able to declare memory limits (especially soft one) for such task. Deploy option is not supported.
Skipping unsupported YAML option for service...  option name=deploy

Is there way how to achieve this with compose? Or is using compose bad idea and it's better to use native task definitions.
update
My compose file was requested, here is it
version: '3'

services:
  worker:
    image: 880289074637.dkr.ecr.us-east-1.amazonaws.com/negative-keywords:latest
    env_file: .env
    command: ["celery", "-A", "negmatch", "worker", "-l", "info"]
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 256M
        reservations:
          cpus: '0.25'
          memory: 128M
  web:
    image: 880289074637.dkr.ecr.us-east-1.amazonaws.com/negative-keywords:latest
    env_file: .env
    ports:
      - "80:8000"
    depends_on:
      - "worker"
    deploy:
      resources:
        limits:
          cpus: '0.50'
          memory: 256M
        reservations:
          cpus: '0.25'
          memory: 128M

A: You will need to use v2 of docker compose to set the values.
As of today, according docker docs, deploy is meant for swarm mode deployment only.

Looking for options to set resources on non swarm mode containers?
The options described here are specific to the deploy key and swarm
  mode. If you want to set resource constraints on non swarm
  deployments, use Compose file format version 2 CPU, memory, and other
  resource options. If you have further questions, refer to the
  discussion on the GitHub issue docker/compose/4513.

More info on using v2 vs v3.
https://github.com/docker/compose/issues/4513#issuecomment-377311337
Here is sample docker-compose(v2) which sets the soft and hard memory limits on container definition of task. mem_limit is hard limit and mem_reservation is soft limit.
Command -
ecs-cli compose --project-name nginx --file docker-compose.yaml create

Compose File -
version: '2'
services:
  nginx:
    image: "nginx:latest"
    mem_limit: 512m
    mem_reservation: 128m
    cpu_shares: 0
    ports:
      - 80


text:
Q: Using N prefix in sql server parameters In my where clause if I write AND acts.displayname = N'Onaylanmış Rapor'  I get the results that I want. But for parameterizing the query I found out that NVARCHAR(MAX) parameters are still returning VARCHAR results without special characters and all.
A sample for my problem is like this;
    DECLARE @displayname NVARCHAR(MAX)
    SET @displayname = 'Onaylanmış Rapor'

    select @displayname as param, CONVERT(NVARCHAR(MAX),@displayname) as nvarconvert, CAST(@displayname as NVARCHAR(MAX)) as nvarcharcast

+------------------+------------------+------------------+
|      param       |   nvarconvert    |   nvarcharcast   |
+------------------+------------------+------------------+
| Onaylanmis Rapor | Onaylanmis Rapor | Onaylanmis Rapor |
+------------------+------------------+------------------+

I still need the parameter as 'Onaylanmış Rapor' though.
I tried casting and converting the parameter value into nvarchar(max) but it doesn't work either.
Is there any other way?

A: SET @displayname = 'Onaylanmış Rapor' by having a string in apostrophe it is being implicitly converted to non unicode.  You need the unicode identifier in your hard coded string.
DECLARE @displayname NVARCHAR(MAX)
SET @displayname = N'Onaylanmış Rapor'

select @displayname as param, CONVERT(NVARCHAR(MAX),@displayname) as nvarconvert, CAST(@displayname as NVARCHAR(MAX)) as nvarcharcast


text:
Q: Proving equality of mean between ANOVA with 2 levels and t-test I want to prove that there is an equality of the ANOVA with 2 levels and t-test. So:
From the t-test we know that:
$$t=\frac{\overline{x}_1-\overline{x}_2}{\sqrt{\frac{S_1^2}{n_1}-\frac{S_1^2}{n_1}}} \sim t(n_1+n_2-2)$$
And we know for a fact that if a statistic is t-distributed => $\mu=0$.
Now for ANOVA with 2 levels we should have a null hypothesis:
$$H_0:\mu_0=\mu_1$$
And I guess from this hypothesis we should get something out but I have no idea.
Can someone please show me a prove that this statement is true ?

A: I'm guessing that you have never looked carefully at the formulas for
a pooled two-sample t test or for a one-way ANOVA. (And that one purpose
of assigning this problem is to get you to do that.) Below both procedures
are computed in Minitab statistical software. The data are ten
normal observations in group A and ten in group B. I suggest you look at the formulas
and use them to compute what Minitab has computed. Then I'm guessing
you will understand what you need to do.
Data. Fake data were simulated as follows: A ~ NORM(100, 10), B ~ NORM(105, 10).
So $\mu_1  \ne \mu_2$ and $H_0$ is false. However, with population SD $\sigma = 10$ there is not enough information with only $n = 10$ replications in each group to detect that $H_0$ is false.
A
    99   103    92   105   103    97    98   113    90   112

B
   109    91   110   103   106   100   101   112   114   110

Pooled (equal pop variances) two-sided two-sample t test. You should
compute pooled SD $S_p$ and T-value.
Two-Sample T-Test and CI: A, B

Two-sample T for A vs B

    N    Mean  StDev  SE Mean
A  10  101.20   7.60      2.4
B  10  105.60   6.95      2.2

Difference = μ (A) - μ (B)
Estimate for difference:  -4.40
T-Test of difference = 0 (vs ≠):
    T-Value = -1.35  P-Value = 0.193  DF = 18
Both use Pooled StDev = 7.2801

One-factor ANOVA, two levels of factor. You should compute
MS(Factor) and MS(Error). In the ANOVA table below these values are
slightly rounded. Note the relationships of MS(Factor) to
the numerator of the T statistic (above) and MS(Error) to the
denominator of the T statistic. The F statistic is the ratio of
MS(Factor) to MS(Error). Verify that the pooled SD is the square root of
MS(Error). Notice that the P-value is exactly the same here as for the
t test above.
One-way ANOVA: A, B

Method

Null hypothesis         All means are equal
Alternative hypothesis  At least one mean is different

Equal variances were assumed for the analysis.

Factor Information

Factor  Levels  Values
Factor       2  A, B

Analysis of Variance

Source  DF       SS      MS  F-Value  P-Value
Factor   1    96.80   96.80     1.83    0.193
Error   18   954.00   53.00
Total   19  1050.80

Pooled StDev = 7.28011


text:
Q: Show that $f(x) = x^3 + 3\sin x + 2\cos x$ is one-to-one. How would I show that $f(x) = x^3 + 3\sin x + 2\cos x$ is one to one?
Showing that the function is strictly increasing seemed to be the way to go, but then I need to show that $f'(x) = 3x^2 + 3\cos x - 2\sin x > 0$. I graphed the derivative function and it is indeed strictly positive. Thoughts?

A: To show that $f(x) = x^3 + 3 \sin x + 2 \cos x $ is one-to-one, it is enough to show that $ f'(x) = 3 x^2 + 3 \cos x - 2 \sin x > 0 $ for all $ x $. Notice that $ (3 \cos x - 2 \sin x) \ge -2 $ for all $ x $. So, whenever $ 3 x^2 > 2 $, $ f'(x) $ must be positive. Note that for $ x \le -\pi/2 $ or $ x \ge \pi/2 $, $ 3 x^2 \ge 3 (\pi/2)^2 > 3 (3/2)^2 > 2 $. Hence, $ f'(x) > 0 $ for $ x \le -\pi/2 $ or $ x \ge \pi/2 $. Next, for $ -\pi/2 < x < 0 $, all three terms in the expression of $f'(x)$ are positive, and so $f'(x)$ is also positive.
Finally, consider the case $ 0 \le x \le \pi/2 $. Two ways of establishing $f'(x) > 0$ is described below: one requires a calculator, the other does not.
Using calculator: Note that within $ 0 \le x \le \pi/2 $, $(3 \cos x - 2 \sin x) \le 0$ for $ \tan^{-1} (3/2) \le x \le \pi/2 $. Using a calculator (or your favorite application or programming language), verify that $3 (\tan^{-1} (3/2))^2 > 2$. Since $3 x^2 \ge 3 (\tan^{-1} (3/2))^2 > 2 $ for $ \tan^{-1} (3/2) \le x \le \pi/2 $, we have $ f'(x) > 0 $ for $ 0 \le x \le \pi/2 $.
Without using calculator: This method would not require any calculator, but only knowledge of the values of $\sin x$ and $\cos x$ for $x = (\pi/4), (\pi/3)$, which follows from basic geometry. Like before, it is sufficient to show that $ f'(x) > 0 $ for $ \tan^{-1} (3/2) \le x \le \pi/2 $. Since $\tan^{-1} x$ is a strictly increasing function in $ 0 \le x \le \pi/2 $, it follows that $ \pi/4 = \tan^{-1} 1 < \tan^{-1} (3/2) < \tan^{-1} \sqrt{3} = \pi/3 $. Note that $ 3 x^2 \ge 3 (\pi/3)^2 > 3 $ for $\pi/3 \le x \le \pi/2$, and hence $f'(x) > 0$ for $\pi/3 \le x \le \pi/2$. So, it is sufficient to show that $f'(x) > 0$ for $\pi/4 \le x \le \pi/3$ to complete the proof. Note that for $\pi/4 \le x \le \pi/3$, $3x^2$ is an increasing function, while $(3 \cos x - 2 \sin x)$ is a decreasing function. Therefore, for $\pi/4 \le x \le \pi/3$, $f'(x) \ge$ $ 3 (\pi/4)^2 + (3 \cos (\pi/3) - 2 \sin (\pi/3))$ $> 3 (3/4)^2 + ((3/2) - \sqrt{3}) = (51/16) - \sqrt{3} > 3 - \sqrt{3} > 0$.


text:
Q: Android App crashing due to classcastexception when using sliding menu library I am getting this error when my app crashes due to Sliding Menu Library
12-31 14:02:54.319: E/AndroidRuntime(4121): java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.ListView.setupChild(ListView.java:1826)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.ListView.makeAndAddView(ListView.java:1793)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at  android.widget.ListView.fillSpecific(ListView.java:1337)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.ListView.layoutChildren(ListView.java:1620)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.AbsListView.onLayout(AbsListView.java:2087)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at  android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at com.jeremyfeinstein.slidingmenu.lib.CustomViewAbove.onLayout(CustomViewAbove.java:476)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.RelativeLayout.onLayout(RelativeLayout.java:1055)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.View.layout(View.java:14817)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewGroup.layout(ViewGroup.java:4631)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1983)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1740)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:996)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5600)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.Choreographer.doCallbacks(Choreographer.java:574)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.Choreographer.doFrame(Choreographer.java:544)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.os.Handler.handleCallback(Handler.java:733)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.os.Handler.dispatchMessage(Handler.java:95)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.os.Looper.loop(Looper.java:136)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at android.app.ActivityThread.main(ActivityThread.java:5001)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at java.lang.reflect.Method.invokeNative(Native Method)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at java.lang.reflect.Method.invoke(Method.java:515)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
12-31 14:02:54.319: E/AndroidRuntime(4121):     at dalvik.system.NativeStart.main(Native Method)

can anyone help me in this issue. i tried to download fresh copy of library and use, but even then it is not solved. im compiling all my project dependent projects and app with android 5.0

A: Check/Organise your imports(ctrl + shift + o, in Eclipse) in CustomViewAbove.java and ensure that if LayoutParams have been used anywhere, they are from the package of android.widget.AbsListView.
Basically that is what your error is telling you:
12-31 14:02:54.319: E/AndroidRuntime(4121): java.lang.ClassCastException:
android.view.ViewGroup$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams

If LayoutParams are being used at multiple places(other than line no. 476), then need to import both packages accordingly.


text:
Q: ArangoDB AQL Upsert how to push a value into list Trying to use the UPSERT in AQL and successful intill I need to push a value into an list array (and I also need ot check if it exists although I think I have that)
Code
const t_list_ = db._query(aql`
        UPSERT { token_name: ${token_i}, type: ${type}}
        INSERT { token_name: ${token_i},
                 type: ${type},
                 frequency: ${tokens[i].frequency},
                 user_list: [${req.pathParams.user_id}] }
        UPDATE { frequency: OLD.frequency + ${tokens[i].frequency},
                 user_list: OLD.user_list.push(${req.pathParams.user_id})}
             IN token_category
        RETURN { doc: NEW, type: OLD ? 'update' : 'insert' }`).toArray()

Error is : ArangoError: syntax error, unexpected (, expecting } near '(@value3)} IN token_category

A: The language used here is Javascript.
Simplifying the query as used here:
let foo="bar";
db._query(aql`RETURN ${foo}`).toArray()

is actually using a specialized AQL-Template string to generate bind values. To dismantle what is actualy handed into db._query() we may use JSON.stringify():
print(JSON.stringify(aql`RETURN ${foo}`))
{"query":"RETURN @value0","bindVars":{"value0":"bar"}}

here you see where that string came actually from that was there in the error message: @value3 actually is a bind variable for one of the expressions you've inserted into the template.
So the actual line in question of the syntax error is this one:
        UPDATE { frequency: OLD.frequency + ${tokens[i].frequency},
                 user_list: OLD.user_list.push(${req.pathParams.user_id})}

and here you're mixing AQL syntax with Javascript-Syntax, which is not supported.


text:
Q: Working with SplClassLoader.php and namespaces <?php
    //The basic Code.
    require_once("SplClassLoader.php");
     $loader = new SplClassLoader('test', 'lib');
        $loader->register();

    use test\database\Connector;
    ?>

    <?php
    namespace test\database;
    class Database {

    }
    ?>

    <?php
    namespace test\database\Connector;
    class Connector extends text\database\Database {

    }
    ?>

my file structure looks like this
\
-index.php
-splclassloader.php
\test
\test\database
\test\database\Database.php
\test\database\Connector.php
Its not loading the connector class.
What is it that I don't understand here.

A: If you are trying to autoload classes that are mapping folders to namespaces (I'm assuming that is the case) make sure that your namespaces only include the folder names and omit class names.  The use statement, on the other hand, would not omit the class name.
Using the namespace of test\database\Connector and then defining a class Connector means that you would instantiate the object using:
$connecter = new \test\database\Connector\Connector();

I'm guessing you have an additional subnamespace Connector that isn't needed.  Namespace test\database\Connector should be test\database.


text:
Q: Check points in svn I'm using svn with my code. I want to ask, if there is any way to make checkpoints with svn?
I have checkout of code on local drive. After making first part of changes I see that everything is OK. After second part of changes code is broken. I want to get back to point after first part of changes and before changes done after. So now I make patch file (with svn diff) and revert all code then patch it. I'm wondering is there svn command to make checkpoint after first part of changes and then simply back to this checkpoint with single svn command. I don't want to commit my changes after first part of changes.

A: I believe that the right terminology is svn save points. There is this ongoing feature design, but as far as I know it has not shipped yet.
Anyway, I was also looking for that functionality, as my company uses svn, and I solved it by configuring git over svn. Using this architecture, you have a local git repository, that "talks" to the remote svn repo, and thus you can benefit from the advantages of git (cheap branching, stash, etc), while still using svn in practice.
This "checkpoint" you want to implement can be accomplished via git's stash, or via creating a new branch (very easy and common practice in git) and use commits as your checkpoints (of course these commits will not be seen in svn - which is what you want if I get it right)

A: The traditional way to do this with SVN would be:

*

*Create a new SVN branch that you will use as your own sandbox (using 'svn copy').

*Switch your local checkout over to the SVN branch you just created (using 'svn switch' followed by the URL of the newly created branch)

*Start making changes.  Whenever you want to create a 'checkpoint', to a 'svn commit'.  This commit will commit the changes to your private branch only, so nobody else will see them (unless they deliberately go looking for your branch, of course).

*If, after making some changes, you decide they are all wrong and you want to revert back to your most-recently-committed checkpoint, a "svn --recursive revert ." at the top level of your SVN checkout folder will revert your SVN checkout back to the state of your most recent commit.

*If you want to go further and revert committed changes, you can do that via "svn merge -rXXXX:YYYY" where XXXX and YYYY are the SVN revision number of the change you want to revert, and YYYY is the number one less than that number.

*When you're done making changes and happy with the results, and you've committed all of your local changes to the branch, you'll probably want to merge all of your branch's changes back into the trunk so that other people can see/use them.
After that you can continue working in the trunk if you like, or you can create another private branch if you prefer and repeat the process again.


text:
Q: Choose databits from combobox I have a simple GUI for serial communication with an Arduino UNO. First I list all databit in an OrderedDict, then I put them in a combobox:
self.databits = OrderedDict([
            ('5', QtSerialPort.QSerialPort.Data5),
            ('6', QtSerialPort.QSerialPort.Data6),
            ('7', QtSerialPort.QSerialPort.Data7),
            ('8', QtSerialPort.QSerialPort.Data8)
        ])
        self.databit_comboBox.addItems(list(self.databits))

Then I run the code, I select an option from databits combobox (this is how I get data from combobox)
self.serial.setDataBits(self.databit_comboBox.currentData())

and when I press connect button, I get this error:
TypeError: setDataBits(self, QSerialPort.DataBits): argument 1 has unexpected type 'NoneType'

A: When you add data with addItems() method you only add text, so you will discard the second part. The solution is to iterate and separate each part:
databits = [
        ('5', QtSerialPort.QSerialPort.Data5),
        ('6', QtSerialPort.QSerialPort.Data6),
        ('7', QtSerialPort.QSerialPort.Data7),
        ('8', QtSerialPort.QSerialPort.Data8)
]
for text, databit in databits:
    self.databit_comboBox.addItem(text, databit)

# ...

self.serial.setDataBits(self.databit_comboBox.currentData())


text:
Q: How to get input from xml laravel I am newbie in laravel. now, I make a API which get input from a xml.
I confused, how can I get the input which be given?
I try using Input::all(), but I get an Array with index \nMY XML
so, I want the input can be format to array or json without string processing, but automatic convert, maybe using library.

A: thanks, at least I use php://input to get xml

A: If you're trying to get converted xml from your incoming request in the same way you would with a json or form reqest, this package makes it possible:
https://github.com/mtownsend5512/request-xml


text:
Q: Redux: Import new reducers and feed them new state on route change The goal
I want to change reducers (and feed them new state) when the route changes.
Current Attempt
I have a route set up with a slug (/components/:slug) that is handled by my ComponentPage reducer. This reducer notices that the route changed (via Redux-saga) and has an opportunity to fetch state that's relevant to the current :slug.
When the router first updates to go to a /components page, the state looks something like this:
route: {...}
language: {...}
theme: {...}
componentPage: {
  content: {[default / empty]}
}

After ComponentPage fetches data related to the :slug, it looks something like this:
route: {...}
language: {...}
theme: {...}
componentPage: {
  content: {...}
  liveExample: {...}
  tabCollection: {...}
}

In the above state tree, items like liveExample and tabCollection represent new domains that are managed by their own reducers (and have their initial state set by componentPageReducer).
My intention is that items like these will be set dynamically by ComponentPage based on the page's :slug so that they can be swapped out for other components without littering the state tree with every possible component that could go on every possible instance of a component page.
The issue
I currently have configuration files set up to import the specific reducers each page needs so that they can feed them to ComponentPage based on the :slug. Unfortunately, my current method of implementation only suffices to care for the initial render—after that pass-through, the imported reducers are replaced by the objects they return.
An example of an object I'm currently handing to ComponentPage
pageConfiguration = {
  content: {...},
  liveExample: (state, action) => liveExampleReducer(state || liveExampleConfiguration, action),
  tabCollection: (state, action) => tabCollectionReducer(state || tabCollectionConfiguration, action),
}

A note on how I came to this:
Redux's combineReducers would return something of this structure:
liveExample: liveExampleReducer(liveExampleConfiguration, action),
tabCollection: tabCollectionReducer(tabCollectionConfiguration, action),

That would be ideal (if I just knew how to get these listed as proper reducers). Instead, I had to make the function callable so that I could pass in the action (when componentPageReducer doesn't match an action.type, it still tries to call these dynamically loaded reducers manually, as you'll see below). (They also accept state || configuration so that when these get called subsequent times, they don't keep reinitializing with configuration/initial data).
ComponentPage/reducer.js
export default function componentPageReducer(state = initialState, action) {
  switch (action.type) {
    case FETCH_SLUG:
      // gets the `pageConfiguration` object from above,
      // and generates the state by manually mapping through
      // its functions and calling them
      if (pages.has(action.payload.slug)) {
        return pages.get(action.payload.slug).map((x) => {
          if (typeof x === 'function') {
            return x(undefined, action)
          }
          return x
        })
      }
      return state
    default:
      // an attempt at calling the now-nonexistent
      // imported reducer functions
      return state.map((x) => {
        if (typeof x === 'function') {
          return x(state, action)
        }
        return x
      })
  }
}

Possible solutions
So, from what I can tell, this might work if I store the reducer functions themselves in the state and map their return value onto a different key so they don't replace themselves, but... it seems like I'm going down a weird road here.
I think that I am currently hacking together something that probably shouldn't be considered proper Reducer Composition. I don't know if there is a more elegant way to handle this sort of scenario.

A: The standard approach to dynamic reducer slices is to keep around an object of all the existing slice reducers, and when you need to add a new one at runtime, update that object and re-run `combineReducers.  To give you the basic idea:
let sliceReducers = {
    first : firstReducer,
    second : secondReducer
};

const initialRootReducer = combineReducers(sliceReducers);
const store = createStore(initialRootReducer);

// sometime later

sliceReducers = {
    ...sliceReducers,
    third : thirdReducer
}

const newRootReducer = combineReducers(sliceReducers);
store.replaceReducer(newRootReducer);

I have a couple articles on the topic in the Redux Techniques#Reducers section of my React/Redux links list.  You may also want to look at the injectAsyncReducer utility from the React-Boilerplate toolkit.


text:
Q: .NET Parallel file creation I'm creating a program that fetches file data from the database. The requirement is that the files get numbered on existence 'IMAGE_00001.JPG', 'IMAGE_00002.JPG', ...
Because of performance issues i'm loading the data parallel but I'm getting an issue with creating the files.
For i As Long = 1 To maxSeqNr
    DIDir = New DirectoryInfo(currDir)
    If DIDir.GetFiles(currFilePrefix & Microsoft.VisualBasic.Right(maxSeqNrLeadingZeros & CStr(i), Len(maxSeqNr.ToString)) & ".*", SearchOption.TopDirectoryOnly).Length = 0 Then
        sRetValue = currFilePrefix & Microsoft.VisualBasic.Right(maxSeqNrLeadingZeros & CStr(i), Len(maxSeqNr.ToString)) & currFileExtention

        Dim oSW As StreamWriter
        oSW = New StreamWriter(currDir & sRetValue)
        oSW.WriteLine("")
        oSW.Close()
        oSW.Dispose()
        oSW = Nothing

        Exit For
    End If
Next

The issue is that sometimes 2 threads are running the same line of code.
I added logging and I found this:
Check for 'IMAGE_00001.JPG' ; Directory: ''
Check for 'IMAGE_00001.JPG' ; Directory: ''
Check for 'IMAGE_00002.JPG' ; Directory: 'IMAGE_00001.JPG'
Check for 'IMAGE_00003.JPG' ; Directory: 'IMAGE_00001.JPG,IMAGE_00002.JPG'

Is there a possibility to "lock" the working directory before I execute the Exists statement. And "release" after I created the file?
The other threads should wait until they can "lock" the directory.

A: You should generate the name that you want to use and then attempt to create a FileStream object using that name. Use a suitable constructor that accepts a FileMode parameter (e.g. this one) and specify CreateNew.
Catch an IOException if one is thrown and generate a new name.
Otherwise, you're dealing with a classic form of race. It's up to you whether you choose to combine your original strategy (check for existence, then try to open the file) or just attempt to create the file and expect exceptions.
Once you've successfully opened your FileStream, you can pass it to a StreamWriter constructor that accepts a Stream parameter, and proceed from there.

A: I would use a syn / lock strategy:
Lock when your threads wants to write a file and halt all other threads until that is done, then release the lock.
http://msdn.microsoft.com/de-de/library/vstudio/ms173179.aspx
Alternatively, use a non-blocking integer as a counter, so it will be guaranteed a unique file, but it MAY mess up your "numbering" requirement.
http://msdn.microsoft.com/en-us/library/system.threading.interlocked.aspx

A: If all you need to do is generate blank files IMG_00000.jpg thru IMG_XXXXX.jpg, you could use a Parallel.For loop to create the files if they do not exist. This will ensure two numbers are not checked by two different threads, instead the numbers will be carved out between threads.
Although I do not know that this will actually be any faster, especially if you must search the directory for a file with any extension matching the name of the image:
Dim width = Len(maxSeqNr.ToString)
Dim DIDir = New DirectoryInfo(currDir)
Parallel.For(1L, maxSeqNr, Sub(i)
    Dim pattern = currFilePrefix & Microsoft.VisualBasic.Right(maxSeqNrLeadingZeros & CStr(i), Len(maxSeqNr.ToString)) & ".*"
    If Not DDir.EnumerateFiles(pattern, SearchOption.TopDirectoryOnly).Any Then
        Dim fn = currFilePrefix & Microsoft.VisualBasic.Right(maxSeqNrLeadingZeros & CStr(i), width) & currFileExtention
        File.Create(fn).Close
    End If
End Sub)

If the folder you're searching in is small-ish, this may be better (assuming you actually care about any file name which matches the pattern):
' My VB.Net is horrible
Dim width = Len(maxSeqNr.ToString)
Dim files = Directory.GetFiles(currDir)
Parallel.For(1L, maxSeqNr, Sub(i)
    Dim pattern = currFilePrefix & Microsoft.VisualBasic.Right(maxSeqNrLeadingZeros & CStr(i), Len(maxSeqNr.ToString))
    ' consider case-insenstive matching
    If Not files.Any(Function(fn) Path.GetFileNameWithoutExtension(fn) = pattern) Then
        Dim fn = currFilePrefix & Microsoft.VisualBasic.Right(maxSeqNrLeadingZeros & CStr(i), width) & currFileExtention
        File.Create(fn).Close
    End If
End Sub)

Or, if all you really need is to only create a file if it does not exist, you just go ahead and touch them all:
Parallel.For(1L, maxSeqNr, Sub(i)
    Dim fn = currFilePrefix & Microsoft.VisualBasic.Right(maxSeqNrLeadingZeros & CStr(i), width) & currFileExtention
    File.Open(fn, FileMode.OpenOrCreate).Close
End Sub)


text:
Q: Mittag-Leffler Proof. Rudin notation question and some basic real analysis/topology

Proof is below

*

*What is meant by $\sum_{\alpha \in A_n}$? I thought $P_\alpha$ is a sum already.

*What is this open set he is talking about? Because $A_n$ isn't open. Oh he means the complement of $A_n$? That is $A^c \cup  K_{m - 1} - K_m$? I thought $A$ is open though?

*So I think my question 1 is correct. I guess $Q_1(z) = \sum_{\alpha} P_\alpha(z) = P_\alpha(z)$, and the same is for $Q_n(z) = \sum_{\alpha} P_\alpha(z) = P_\alpha(z)$
EDIT: editing right now, I forgot to put the last part of the proof…

A: *

*Each $P_\alpha$ is a sum, but then you sum these over the index set $\alpha \in A_n$. (Think partial fractions decomposition; Mittag-Leffler's theorem can be seen as a generalization of partial fractions to the infinite case.)

*The function $Q$ is rational, and there are no poles in the compact set $K_{n-1}$. Hence $Q$ is in fact holomorphic on some open neighbourhood of $K_{n-1}$. (Since $Q$ is rational, it only has finitely many poles, so there must be a positive distance between $K_{n-1}$ and the closest pole.)

*I don't understand the question here, $Q_n$ is defined in equation (1).


text:
Q: Implementing pixel-perfect background images in different orientations I'm developing a game in Swift (not Spritekit) and I'm having some difficulty creating a background image that works in every device orientation.
I see an XCode feature called asset catalog for defining the launch screen images, and I wonder if we can do something similar to define the device's background images?
Just like I said, I want to create a group of images to every device and orientation and create a image set or asset catalog, but i don't know how to do that. Has anyone here already done something like this?
*I know the concept of @2x and @3x images, but how can i implement images like that to other orientations?
Update 1: i posted one picture to help
[

A: When you edit storyboard, you will see wAny hAny at the bottom. There you could choose orientation and device type. After choosing you do anything you want, and it would be only in that orientation and that device type.

A: You can add a new image to your Asset catalogue:
Activate iPhone and iPad and choose the size classes you need:


text:
Q: Eclipse/Mylyn: use JIRA and Bitbucket? It is possible to connect a Bitbucket account to JIRA: http://blog.bitbucket.org/2012/04/30/linking-bitbucket-and-jira/
But is it possible to connect them using Eclipse/Mylyn?

A: Atlassian have a connector for Eclipse and JIRA which you can check out here: http://www.atlassian.com/software/ide-connectors/overview. It manages builds, source control, issues, etc, etc. Well worth a look.


text:
Q: Modal dialog on Active Explorer Window only I have a modal dialog in my form region. I am providing the form region as the owner of the dialog but it blocks access to Outlook main window as well as always appears on top of it.
Is it possible to have modal dialog on my active explorer window that is showing my form region and not on other Outlook windows?

A: No, this is not possible by design. A modal dialog will always be modal to the entire process, i.e. all windows belonging to the Outlook process will be blocked by your modal dialog.
As a workaround, you can make your dialog non-modal and bring it to the front whenever the explorer is activated (check for the Explorer.Activate event).


text:
Q: Netbeans platform. Non-ascii characters in path to app I'm create my app by using netbeans platfrom(7.4). I use nbm-maven plugin 3.13. In windows(8 in virtual box), i setup app to folder with cyrilic characters. Next, I launch exe file and have message box("Non-ascii ...").
I find bug report https://netbeans.org/bugzilla/show_bug.cgi?id=222850, but status is "RESOLVED FIXED". What should i do for resolve this problem?

A: I solved this by upgrading to Netbeans 8.0.


text:
Q: bash add value to array with embedded variable and single quotes I'm sure it's completely clear from the subject :)  Joking aside, I think part of the problem I'm having finding an answer is writing the search terms.
I have had good luck when issuing commands in a bash script by using an array for the arguments.
For example, I'm calling rsync and created an array like (spolier alert - superfluous variables will be referenced later):
#!/usr/bin/env bash
set -euo pipefail
rf=.rsync-filter
srcff="/home/roger/home$rf"

hm=/home/roger
syncto=/tmp/to-remote/home

rsarg=(-avv --prune-empty-dirs --stats)
rsarg+=(--dry-run)

rsync "${rsarg[@]}" "$hm" "$syncto/"  #works

exit

Where I'm having problems is in adding the $srcff variable to a filter rule and adding that to the rsarg array.
rsarg+=("--filter='merge $srcff'") # no dice
# or this
rsarg+=("--filter='merge ${srcff}'") # sad trombone

Upon running I get:
$ ./home-sync-simple
Unknown filter rule: `'merge /home/roger/home.rsync-filter''
rsync error: syntax or usage error (code 1) at exclude.c(904) [client=3.1.1]

I can get it to work by adding the merge rule to the rsync line, outside of the array and minus embedded variable:
rsync "${rsarg[@]}" --filter='merge /home/roger/home.rsync-filter' "$hm" "$syncto/"

Replacing the above filter with the variable outside the array, fails in the same manner:
rsync "${rsarg[@]}" "--filter='merge $srcff'" "$hm" "$syncto/"

I have tried many other variations, I'm assuming all possible excepting the one that actually works.  Sometimes it results in "unexpected end of filter rule: merge" and other things.  I've excluded those for brevity and because I think the versions above are closer to correct (he said, nervously).  I am guessing I end up passing too few/many arguments.
Thanks in advance!

A: If this works:
rsync "${rsarg[@]}" --filter='merge /home/roger/home.rsync-filter' ...

Then I suppose you do not want to give the single-quotes to rsync. Here, the shell eats them before rsync sees them. Your other examples have quotes within quotes, so the inner ones stay and are passed for rsync to see.
So skip the single-quotes when building the array:
rsarg+=("--filter=merge $srcff")

Note that from the shell's point of view, the equal sign is nothing special, and there's no need to treat the part that comes after any differently than the part before. --foo=bar is the same as --foo="bar" or "--foo=bar", or even --fo"o=ba"r.


text:
Q: Mapping Json to POJO without Jackson and only JDK classes Recently at a test, I came across a problem to do some processing after querying the response data from a restful service. I had to write a web service consumer and do some processing using Java.
While I was able to consume the service using Http classes from jdk, I didn't knew of any way to map the response json in their respective pojo's, without using Jackson's or other external  mapper libraries.
Now I have been trying to do that. Until now I have tried to change the incoming Json to byte array and deserialize and map into the pojo, but that didn't worked. I remember with JAX-B unmarshalling was possible but it has been carved out of jdk after java 8, and I have been working with higher version JDK 11.
I also tried getting the response as streams but then data processing does not remains equally straightforward, as it would have been in case of working with model classes. I am in split, any way out of it would be very appreciable ..
HttpRequest req = HttpRequest
                .newBuilder(new URI("https://jsonmock.hackerrank.com/api/transactions/search?userId=4"))
                .GET().build();

//HttpResponse<byte[]> response = HttpClient.newHttpClient().send(r, BodyHandlers.ofByteArray());

HttpResponse<Stream<String>> response = HttpClient.newHttpClient().send(req, BodyHandlers.ofLines());
Stream<String> responseStream = response.body();

A: Natively you can do it using Regex and plenty complex custom logic assuming you handling the JSON as string changing the response Line as below.
HttpResponse response = HttpClient.newHttpClient().send(req, HttpResponse.BodyHandlers.ofString());
I assume that the models you could use are below
Location Model
`
public class Location {
private int id;
private String address;
private String city;
private int zipCode;

public Location(int id, String address, String city, int zipCode) {
    this.id = id;
    this.address = address;
    this.city = city;
    this.zipCode = zipCode;
}

public Location() {
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public String getAddress() {
    return address;
}

public void setAddress(String address) {
    this.address = address;
}

public String getCity() {
    return city;
}

public void setCity(String city) {
    this.city = city;
}

public int getZipCode() {
    return zipCode;
}

public void setZipCode(int zipCode) {
    this.zipCode = zipCode;
}

}
`
User Model
`
public class User {
private int id;
private int userId;
private String userName;
private double timestamp;
private String txnType;
private String amount;
private Location location;
private String ip;

public User(int id, int userId, String userName, double timestamp, String txnType, String amount, Location location, String ip) {
    this.id = id;
    this.userId = userId;
    this.userName = userName;
    this.timestamp = timestamp;
    this.txnType = txnType;
    this.amount = amount;
    this.location = location;
    this.ip = ip;
}

public int getId() {
    return id;
}

public void setId(int id) {
    this.id = id;
}

public int getUserId() {
    return userId;
}

public void setUserId(int userId) {
    this.userId = userId;
}

public String getUserName() {
    return userName;
}

public void setUserName(String userName) {
    this.userName = userName;
}

public double getTimestamp() {
    return timestamp;
}

public void setTimestamp(double timestamp) {
    this.timestamp = timestamp;
}

public String getTxnType() {
    return txnType;
}

public void setTxnType(String txnType) {
    this.txnType = txnType;
}

public String getAmount() {
    return amount;
}

public void setAmount(String amount) {
    this.amount = amount;
}

public Location getLocation() {
    return location;
}

public void setLocation(Location location) {
    this.location = location;
}

public String getIp() {
    return ip;
}

public void setIp(String ip) {
    this.ip = ip;
}

}
`
Generally Java has not any build in parser. You may find this below
Java Built-in data parser for JSON or XML or else
The most simple library you might find is described here
https://www.oracle.com/technical-resources/articles/java/json.html
and you might find it as maven dependency below
https://mvnrepository.com/artifact/org.json/json

A: To do that you would have to write your own Json parser that would do the same as Jackson, Gson Simple Json or any other external Json library. In other words you would be re-inventing the wheel. While it might be very interesting it would be pretty useless. That is why those libraries have been written in the first place.


text:
Q: In "One More Day," did Spider-Man really have to make a deal with Mephisto? I'm writing this question on shaky ground, as I've not read the comics in question (still looking for an opportune moment to step in and I don't want to be too spoiled), but I've reccently(ish) heard Spiderman made a deal with the devil to save his Aunt May, and sacrificed his child. I heard no one in the marvel universe could help Aunt May, which sounds bizarre.
The question I'd like to ask then is this; Did he really have to make a deal with the devil to save his Aunt?
EDIT: The story in question is "One More Day" by J. Michael Straczynski and Joe Quesada, published by Marvel Comics from November 2007 to January 2008. The Wikipedia entry summarizes the events, saying:

After his Aunt May has been shot, Spider-Man seeks help to save her life. He encounters the demon Mephisto, who offers to save her life if Spider-Man gives him his marriage. Spider-Man and his wife Mary Jane Watson agree, and this part of their history is erased so that, effectively, they have never been married. Additionally, the demon erases the world's collective memory of Spider-Man's secret identity, which had been exposed in Civil War #2. The storyline set the stage for a restructuring of the Spider-Man titles, resulting in the cancellation of Friendly Neighborhood Spider-Man and The Sensational Spider-Man, with Amazing Spider-Man revamped as a thrice-monthly publication.

The reality shift only affected the marriage between Peter Parker and Mary Jane. In the new reality, they lived together and were in a serious, committed relationship, but were never actually married. The events of "One More Day" were expanded upon in the 2010 storyline "One Moment In Time," published in Amazing Spider-Man, written by Joe Quesada with art by Paolo Rivera. This storyline showed what happened in the new timeline instead of the  wedding, originally depicted in Amazing Spider-Man Annual #21 (1987). Essentially, Peter Parker missed the wedding due to superheroics, proving that they should stop the wedding due to their unstable lives.

A: There are many people in the Marvel universe with healing abilities.  The fact that Peter was not able to find someone who could heal Aunt May from a gunshot wound is laughable.  There are probably (at least) 3 mutants in the X-Men universe who have healing abilities.
Also, in Mephisto's changed history Aunt May was still shot.  But how did Quesada have her life saved?  Peter uses "the power of love" by giving her chest compressions.  Yes, according to the head of Marvel, chest compressions can cure gunshot wounds.

A: The way the story was written there was no-one in the Marvel Universe who could help Peter.
Initially he asked Dr. Strange but he could do nothing to help Aunt May who was dying of a gunshot wound. Dr. Strange does help Peter though in contacting other people who may be able to help including Dr. Doom, Reed Richards, the High Evolutionary, and even Doctor Octopus.  None of them can help.
Peter attempts to use a spell to travel back in time without Dr. Strange's assistance and is injured.  Strange heals his wounds and sends him on his way to spend time with Aunt May before she dies.
Peter then meets Mephisto who offers to save Aunt May provided that he be allowed to change history so Peter and Mary Jane were never married.  The couple agrees provided that Mephisto also erase the world's knowledge that Peter Parker is Spider-Man.  The deal is done, the plan goes off, Aunt May is saved, Peter and MJ were never married, no one remembers that Peter is Spider-Man. That is the in-universe explanation.
The real world explanation is that Marvel Editor-in-Chief Joe Quesada wanted to return Spider-Man to his roots and to that end he wanted Peter to be single.  Quesada also felt that a single Peter Parker was more relatable for fans.  Fan reaction was primarily outrage and derision.


text:
Q: Create a Inner Join to create proper output I am trying to get my data to look like the output below. I have a SQL with a Inner Join to
 connect two tables so they will output the data so it looks like the below. I am not sure how to do this could somebody give me a example
This is what the output looks like now
First American
2014-03-17 Blackwell Vancouver 115
First American
2014-04-21 Kurth Vancouver 85
Title Source
2014-01-04 Kurth Vancouver 85
Title Source
2014-03-11 Kurth Vancouver 85
Title Source
2014-03-17 Kurth Vancouver 85

This is what I would like it to look like
First American

2014-03-17 Blackwell Vancouver 115
2014-04-21 Kurth Vancouver 85

Title Source

2014-01-04 Kurth Vancouver 85
2014-03-11 Kurth Vancouver 85
2014-03-17 Kurth Vancouver 85

$result = $db->query("SELECT customers.name,signings.pid,signings.done,signings.signstart,
signings.lname,signings.ordern,  signings.city,signings.samount,signings.prtamount,
signings.faxamount FROM customers Inner Join signings On signings.custid = customers.custid
WHERE signings.pid = 6 AND signings.done = 1 GROUP BY customers.name, signings.pid,
signings.done,signings.signstart");
foreach($result as $key => $income) {

  echo $income['name'];

  echo '
';
  $total = $income['samount'] + $income['prtamount'] + $income['faxamount'];
  echo $income['signstart'] . ' ' .$income['lname']. ' ' .$income['city'] . ' ' .$total;

  echo '
';
}

A: You can modify your PHP like this:
$current=null;
foreach($result as $key => $income) {
if($current!=$income['name']){
    echo $income['name'];
    $current = $income['name'];
}

//other stuff
}

Hope this solves it!


text:
Q: Finding f'(x) , Differentiation problem $(a)$ Use the formal definition of the derivative to compute $ f'(2) $ when $ f(x)=\frac{1-x}{2x} $
$(b)$ Do the same to find $f'(x)$

A: Hint. One may write, as $x \to 2$,
$$
\frac{f(x)-f(2)}{x-2}=\frac{\frac{1-x}{2x}-\frac{(-1)}{4}}{x-2}=\frac{\frac{-(x-2)}{4x}}{x-2}=-\frac1{4x} \to -\frac1{8}
$$ Similarly, to get $f'(x)$, one may consider, as $h \to 0$,
$$\frac{f(x+h)-f(x)}{h}.
$$


text:
Q: CloudKit Cursor Error and Failing to Return all Rows - Encountered an error fetching records I am trying to retrieve all records from a CloudKit database table in order to compare with an array.  When I make the query from CloudKit, I am getting a general error.  I usually get some records back, but not the full set.  The table only has about 6500 records.  Using a predicate of true, i.e., no predicate, I get the same error.  The number of rows returned is different each time before the error occurs.
Full error:
<CKQuery: 0x618000423e40; recordType=ActionFigureSale, predicate=saleEndTime > CAST(422923500.000000, "NSDate")> errored for <CKError 0x60000085b6c0: "Internal Error" (1/1000); "Encountered an error fetching records">

I have tried setting the resultLimit to 1000, but get the same error multiple times as it queues multiple times.
        let publicDatabase = SharedData.sharedInstance.publicDatabase

        // let predicate = NSPredicate(value: true)
        let predicate = NSPredicate(format: "\(kSaleEndTime) > %@", saleEndTime)
        let query = CKQuery(recordType: kActionFigureSaleRecord, predicate: predicate)
        query.sortDescriptors = [NSSortDescriptor(key: kSaleSourceUniqueId, ascending: true)]

        var queryOperation = CKQueryOperation(query: query)
        queryOperation.queuePriority = .veryHigh
        queryOperation.resultsLimit = 10000

        var actionFigureItemSaleCloudRecordArray = Array<CKRecord>()
        var actionFigureItemSaleCloudArray = Array<ItemSale>()

        queryOperation.recordFetchedBlock = { (record) -> Void in
            actionFigureItemSaleCloudRecordArray.append(record)

            let actionFigureReference = record.object(forKey: kActionFigureReference) as! CKReference

            ...

            actionFigureItemSaleCloudArray.append(itemSaleItemCloud)
        }

        queryOperation.queryCompletionBlock = { (cursor, error) -> Void in

            if error != nil {
                DispatchQueue.main.async {
                    #if DEBUG
                        print("WARNING:  Action Figure Sale iCloud query \(query) errored for \(error!)")
                    #endif

                    completion(nil, error)
                    return
                }
            }

            if cursor != nil {
                let newQueryOperation = CKQueryOperation(cursor: cursor!)
                newQueryOperation.cursor = cursor
                newQueryOperation.resultsLimit = queryOperation.resultsLimit
                newQueryOperation.queryCompletionBlock = queryOperation.queryCompletionBlock

                queryOperation = newQueryOperation

                publicDatabase!.add(queryOperation)
                return

            }
            else {
                completion(actionFigureItemSaleCloudArray, nil)
                return
            }
        }

        publicDatabase!.add(queryOperation)
    }

A: I have had the same error and I was able to solve this by looking at the userInfo nested in CKError. The code below is part of my completionHandler in queryCompletionBlock:
if error is CKError {
    let ckerror = error as! CKError
    let info = ckerror.userInfo
    for inf in info {
        NSLog("User-Info:\(inf.key):\(inf.value)")
    }
    NSLog(error!.localizedDescription)
}

It came out, that my initial size of queryOperation.resultsLimit was too high. I decreased it to 400 and the error was gone.


text:
Q: Rebuild fails after adding reference in Unit Test App Nunit Lite Xamarin to Xamarin Service I have android xamarin app project that I want test. (Xamarin application, bound service)
I have created Unit Test App project.(nunit lite) I have added reference to project I want test via visual studio in Unit Test App project. When I rebuild solution I get this error. It is caused by adding this reference.
Severity    Code    Description Project File    Line    Suppression State
Error       The "LinkAssemblies" task failed unexpectedly.
Java.Interop.Tools.Diagnostics.XamarinAndroidException: error XA2006:
Could not resolve reference to 'System.Void
System.ServiceModel.ServiceBehaviorAttribute::.ctor()' (defined in
assembly 'AndroidClientApi, Version=0.12.0.0, Culture=neutral,
PublicKeyToken=c45bde296bb8c671') with scope 'System.ServiceModel,
Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.
When the scope is different from the defining assembly, it usually
means that the type is forwarded. ---> Mono.Cecil.ResolutionException:
Failed to resolve System.Void
System.ServiceModel.ServiceBehaviorAttribute::.ctor()
at Mono.Linker.Steps.MarkStep.HandleUnresolvedMethod(MethodReference
reference)
at Mono.Linker.Steps.MarkStep.MarkMethod(MethodReference reference)
at Mono.Linker.Steps.MarkStep.MarkCustomAttribute(CustomAttribute ca)
at

Mono.Linker.Steps.MarkStep.MarkCustomAttributes(ICustomAttributeProvider
provider)
at Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference)
at MonoDroid.Tuner.MonoDroidMarkStep.MarkType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.MarkType(TypeReference reference)
at MonoDroid.Tuner.MonoDroidMarkStep.MarkType(TypeReference reference)
at Mono.Linker.Steps.MarkStep.InitializeType(TypeDefinition type)
at Mono.Linker.Steps.MarkStep.InitializeType(TypeDefinition type)
at Mono.Linker.Steps.MarkStep.InitializeAssembly(AssemblyDefinition
assembly)
at Mono.Linker.Steps.MarkStep.Initialize()
at Mono.Linker.Steps.MarkStep.Process(LinkContext context)
at Mono.Linker.Pipeline.Process(LinkContext context)
at MonoDroid.Tuner.Linker.Process(LinkerOptions options, ILogger logger, LinkContext& context)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
--- End of inner exception stack trace ---
at Java.Interop.Tools.Diagnostics.Diagnostic.Error(Int32 code, Exception innerException, String message, Object[] args)
at Xamarin.Android.Tasks.LinkAssemblies.Execute(DirectoryAssemblyResolver res)
at Xamarin.Android.Tasks.LinkAssemblies.Execute()
at Microsoft.Build.BackEnd.TaskExecutionHost.Microsoft.Build.BackEnd.ITaskExecutionHost.Execute()
at Microsoft.Build.BackEnd.TaskBuilder.<ExecuteInstantiatedTask>d__26.MoveNext()    Test

Any ideas how to solve it ?

A: For me the solution was:
NameOfTheProject -> Properties -> AndroidOptions -> Linking: None


text:
Q: Avoiding type checking when interface method parameters are abstract My interface looks like this:
public interface UserHandler
{
    CheckUsernameResponse CheckUsername(CheckUsernameRequest request);
}

The request and response types in the signature are abstract classes, giving a usage of something like:
var fooHandler = new FooUserHandler();

var fooResponse = fooHandler.CheckUsername( new FooRequest { id = 1, FooProperty = "abc" });

or
var barHandler = new BarUserHandler();

var barResponse = barHandler.CheckUserName( new BarRequest { id = 2, BarProperty = true });

What I'm ultimately trying to do is have the ability to have multiple UserHandler implementations, each with their own versions of the request/response types with different properties but having a common base type. I'm doing this to avoid having to make changes to a consuming WCF service in the event that the external user provider changes and a new provider needs different properties in the method call.
Bearing in mind it's possible to pass any type that inherits from the abstract class, i.e. I can pass a BarRequest into a FooHandler, how can I ensure that only the correct/expected types are passed as parameters in the  without resorting to:
public CheckUsernameResponse CheckUsername(CheckUsernameRequest request)

    if (request.GetType() != typeOf(FooRequest))
        throw new ArgumentException("Wrong type!");

    var fooRequest = request as FooRequest;

This feels wrong so I'd appreciate any feedback into the specific question and the approach in general.
What I really want is a method signature of:
public FooResponse CheckUsername(FooRequest request)

but if I do that I'm not implementing the interface.

A: In my opinion, the interface should use generics, so you can rely on the implementation of the interface.
I would suggest something like this:
public interface UserHandler<TRequest, TResponse> where TRequest : CheckUsernameRequest
                                                  where TResponse : CheckUsernameResponse
{ }

Then FooHandler would become:
public class FooHandler : UserHandler<FooRequest, FooResponse>
{ }

And now you are all set, you don't have to check types any more. You are compiler safe.


text:
Q: iptables - Redirect local and transient outbound traffic destined for port 80 to port 8080 I'm having an issue with iptables due to my very small amounts of involvement with it.
I have a TOR exit relay setup and I'm trying to redirect all local and TOR traffic so that it exits my box on port 8080.
Currently I have it set as:
-A PREROUTING -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080
But this only seems to redirect transient traffic when I'm acting as a router rather than traffic originating from the box.

A: Not commenting on TOR as I don't have much knowledge.
But for the iptables goal, here it is. PREROUTING involves routing. When initiating a connection from the local system, you're not routing. You just have to use OUTPUT instead/in addition of PREROUTING.
Scope of REDIRECT:

REDIRECT
  This target is only valid in the nat table, in the
  PREROUTING and OUTPUT chains, and user-defined chains which are only
  called from those chains. It redirects the packet to the machine
  itself by changing the destination IP to the primary address of the
  incoming interface (locally-generated packets are mapped to the
  localhost address, 127.0.0.1 for IPv4 and ::1 for IPv6).

So:
iptables -t nat -A OUTPUT -p tcp -m tcp --dport 80 -j REDIRECT --to-ports 8080

EDIT:
To avoid a specific user or group to be redirected (eg to avoid an infinite loop with the service on port 8080), you can do like this (example for a service running with effective group tor) instead of above:
iptables -t nat -N OUTPUT intercept
iptables -t nat -A OUTPUT -p tcp -m tcp --dport 80 -j intercept
iptables -t nat -A intercept -m owner --gid-owner tor -j RETURN
iptables -t nat -A intercept -j REDIRECT --to-ports 8080


text:
Q: Python XML Parser not Returning XML Elemements I am trying to find a way to use Python to parse data from several .xml files that contain part numbers and descriptions for a system my team is working on. Here's what the files look like:
Note: Actual data sanitized for confidentiality reasons.
<DOCUMENT>
<config>
<lruname>NFS</lruname>
<swpn>123-A-456-7890</swpn>
<swname>00 NFS ABC DEFGHI XYZ JKL</swname>
<swver>Appid: abc-defghi-xyz  PN: 123-A-456-7890</swver>
</config>
</DOCUMENT>

I'd like to pull the  and  datatypes from several of these files into .csv format. My initial thought was to try to parse these data types out into a dictionary using the built in xml.etree library, but for some reason it's not finding the elements:
import xml.etree.ElementTree as ET

data = '''
<DOCUMENT>
<config>
<lruname>NFS</lruname>
<swpn>123-A-456-7890</swpn>
<swname>00 NFS ABC DEFGHI XYZ JKL</swname>
<swver>Appid: abc-defghi-xyz  PN: 123-A-456-7890</swver>
</config>
</DOCUMENT>
'''

tree = ET.fromstring(data)
PartNo = tree.find('swpn')
Desc = tree.find('swname')

print(PartNo)

The above code returns 'None' for some reason, but I would expect it to return the xml element I'm calling.

A: I think you're missing the config level in your XML hierarchy, you could do:
part_number = tree.find('config').find('swpn').text
part_desc = tree.find('config').find('swname').text

Alternately you can loop through all the elements if you don't want to have to know the structure and use conditionals to find the elements you care about with tree.iter.
for e in tree.iter():
    if e.tag == 'sqpn':
        part_number = e.text
    if e.tag == 'swname':
        part_desc = e.text

A: ElementTree and etree's find functionality searchers for direct children.
You can still use it by specifying the entire branch:
tree.find('config').find('swpn')
tree.find('config/swpn')

If you always want to look for swpn, but disregard the structure (e.g. you don't know if it's going to be a child of config), you might find it easier to use the xpath functionality in etree (and not in ElementTree):
tree = etree.fromstring(data)
tree.xpath('//swpn')

In this case, the // basically mean that you are looking for elements in tree, no matter where they are
If the xml files are small, and you don't care about performance, you can use minidom which IMHO is more convenient compared to lxml. In this case, your code could be something like this:
from xml.dom.minidom import parseString
xml = parseString(data)
PartNo = xml.getElementsByTagName('swpn')[0]
Desc = xml.getElementsByTagName('swname')[0]
print(PartNo.firstChild.nodeValue)


text:
Q: Weird screen when Windows 10 wakes up from sleep I think this happened after my Windows 10 installation was updated to the Creators Update. Whenever I put my laptop to sleep, I get this screen on wake-up:

My laptop is an MSI PE60-6QE with a GTX960 GPU (it also has Intel's onboard graphics). I have not messed with any settings yet.
To get past it I have to hold the power button to turn the whole thing off and then turn it on again. How can I stop this?

A: Please download and install the latest graphic card driver:
http://www.nvidia.com/download/driverResults.aspx/84889/en


text:
Q: Pass function to jQuery .ready() function I am currently making use of Simon Willson's addLoadEvent function to add functions that I want to run after the load event.  I ran into a problem wherein the the function I passed to the addLoadEvent function referenced a div that had not yet been loaded by the DOM and so my action (showing the div) did not do anything.  When I changed to using the jQuery $(document).ready function, the div has been loaded by the DOM and I can execute actions with it (make it show up).
So, a couple questions.  Why is my function being executed before the DOM has completed loaded using the above function?  Is there a way to delay it?  The other alternative that I can think of is passing in a function to a jquery equivalent:
function jqueryAddReadyEvent(myFunc)
{
    $(document).ready(function()
    {
        //execute already existing functions
        //add a new function to the ready event
        myFunc();
    }
}

When I try the above code, I get a javascript error "myFunc is not a function".  Is there a way to generically pass in a function to the jquery ready function and have it execute? Equivalent to the following:
$(document).ready(function()
{
    funcA();
}
$(document).ready(function()
{
    funcB();
}
...//more of the same

Replaced with the following:
jQueryAddReadyEvent(funcA);
jQueryAddReadyEvent(funcB);

A: You can just do:
$(document).ready(myFunc);

to attach functions to the DOM ready event. Here's the fiddle: http://jsfiddle.net/padtE/

A: If you will require many functions to be added then I suggest you do the following:
Create an array that will old all the functions you want to call.
Add functions to that array as you please.
In the .ready(function() { ... }) call every function in that array.

You're set.

A: function jqueryAddReadyEvent(myFunc) {
    $(myFunc);
}

jqueryAddReadyEvent(function() {
    alert('hello world');
});

Demo: http://jsfiddle.net/AlienWebguy/UzMLE/

A: It looks correct to me. Most likely you are calling it with something not a function.
Btw you can shorten this to:
var jqueryAddReadyEvent = $(document).ready

or just use $(document).ready() directly for the same effect, as it specifically does what you want to do, run functions after the load, and is actually shorter.
$(document).ready(funcA);
$(document).ready(funcB);


text:
Q: Typescript Cannot find Module "fs" even though @types/node installed I know the usual fix for this one is to install @types/node , and I have 10.12.23 of that installed.
This appears to be a strange error and I am a bit baffled by it.  I have 2 other npm modules installed:  config ( which requires @types/config ) and firebase-admin which must have it's own typescript types.  Also using VS code version 1.31   . I even tried installing an older version of @types/node
The following works fine
import admin from "firebase-admin";
import fs from "fs";

The following fails: cannot find module 'fs'
import admin from "config";
import fs from "fs";

The following fails: cannot find module 'fs'
import fs from "fs";

I am not using any other packages / webpack or anything else. Any ideas are appreciated.

A: Besides installing @types/node, check that the tsconfig.json:

*

*does not have a compilerOptions types, or make sure "node" is included there

*noResolve does not exist or is set to false

*esModuleInterop is set to true or you'll get error Module "fs" has no default export

A: Import fs in your ts/js file
import fs from 'fs'


text:
Q: Central Limit Theorem: Sample Size or Number of Samples? The central limit theorem states that if we take a take a large enough sum of random variables, the sum will approach a normal distribution. I am confused about why we focus only on the sample size and not the number of samples. The way I'm thinking about it, when we take a sample of random variables then calculate the sum, that sum is just a singular number (we "compress" the sample into one statistic). If this is correct, then don't we need more samples to get more sums so we can actually plot the distribution? If we only calculate one sum (say with a sample size of 100,000 random variables), then we only have one number which is clearly not enough to create a distribution.

A: the CLT is just telling you how the average of the sample is distributed. Just as if I tell you the throws of a die are distributed equally with probability 1/6, or that a particular coin is fair (50% heads, 50% tails)
how you check this is a different issue eg by throwing the die multiple times and creating a histogram.

A: Actually, in practice, when we conduct a survey/experiment. It is costly and takes time to reconstruct the same thing with the same controlled factors many times. Therefore, conducting one time with a large enough sample size will produce the desired results, where we can test the hypothesis under the CLT. Furthermore, some hypotheses based on observed data (eg economic and social data) cannot be reproduced. So, the sample size will give us more advantages than the number of samples.


text:
Q: newid() with Entity Framework 6 Code First I want to set the default value of my primary key of a table in SQL database with newid() via Entity Framework 6 Code First.
I know how this is done via code and also found some approaches on stackoverflow, like How to set NewId() for GUID in entity framework
BUT: I have a backup/restore mechanism which inserts the the data not via objects but just as a bulge to the database. So no Entity Framework is used here. That means that a row with a null as guid will be inserted in the SQL database and fails.
It is possible to add the Annotation
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public Nullable<Guid> Entity_OID { get; set; }

And this will successfully add NEWSEQUENTIALID() as default value, which does a similar thing as newid() (it adds a new guid which is higher than the recent guids, so you win perfomance because you have a order in the input).
But because this is a database which already exist without EF I want to do as few changes as possible. So I'm not excactly happy with NEWSEQUENTIALID(). I would rather like it if it were still just newid(). But I haven't found any Annotation/Mapping for newid() in Entity Framework 6 Code First. And by design all changes to the database have to be done via code.
Does anyone know how to add the default value newid() to the row via code?
Thanks in advance!

A: It seems that what I tried to do is not possible in Code First.
And with the
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public Nullable<Guid> Entity_OID { get; set; }

Entity Framework will also generate a new Guid, even if I set a prior to the context.SaveChanges() which is not the behavior I expected.

A: When you mark a property with DatabaseGeneratedOption.Identity EF gets generated value from DB after every insert operation and sets it to the property.
In DB you can do everything such as creating default constraint newid() for the column.


text:
Q: how javascript array value pass in php var exp_array_string = [];

exp_array_string[0] = "";
exp_array_string[1] = "maincode=P0010250&tablename=prod_fert_st_mn&prod_code=FR00001&frequency=m&highlimit=35&model=f";

exp_array_string[2] =
    "maincode=P0021000&tablename=prod_auto_st_mn&prod_code=AU00001&frequency=m&highlimit=35&model=a";
exp_array_string[3] =

maincode = P0051000&tablename=prod_oil_st_mn_ts&prod_code=OIL0030&frequency=m&highlimit=35&model=o

for (i = 1; i <= 3; i++) {

    var exp_datastring = exp_array_string[i];

    <?php
        $a = "";

    <?php $export_xls = "/index.php?$a";  ?>
    <a href = "<?php echo $export_xls;?>" >

i wan to show in export like index.php ?maincode=P0010250&tablename=prod_fert_st_mn&prod_code=FR00001&frequency=m&highli
but they showing in index.php?document.write(exp_datastring)
what can i do now

A: You can't do that, The reason is that
PHP is Server side and Javascript is client side so when PHP executes the javascript not and vice versa.
It's better to use ajax for your purpose. Currently you are doing is not the right approach.

A: You cannot, PHP is server side : means already executed when JS is executed on client, you may do something like this JS only


text:
Q: Google Analytics - Tracker Object from Activity I am creating the Google Analytics Tracker object from an Activity. The issue is that I am getting an error in the cast operation done on this.getApplication(). Please let me know how to create a tracker object from an Activity.
public void sengToGoogleAnalytics() {
    Tracker t = ((AnalyticsSampleApp) this.getApplication()).getTracker(TrackerName.APP_TRACKER);
    t.setScreenName(getString(R.string.memoryhome));
    t.send(new HitBuilders.AppViewBuilder().build());
}

Log
06-11 11:49:59.510: E/AndroidRuntime(2917): FATAL EXCEPTION: main06-11 11:49:59.510: E/AndroidRuntime(2917): java.lang.RuntimeException: Unable to start activity ComponentInfo{kids.animals.fruits.objects.brain.puzzle.memory.game.free/kids.animals.fruits.objects.brain.puzzle.memory.game.free.MemoryHome}: java.lang.ClassCastException: android.app.Application cannot be cast to kids.animals.fruits.objects.brain.puzzle.memory.game.free.AnalyticsSampleApp06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): java.lang.RuntimeException: Unable to start activity ComponentInfo{kids.animals.fruits.objects.brain.puzzle.memory.game.free/kids.animals.fruits.objects.brain.puzzle.memory.game.free.MemoryHome}: java.lang.ClassCastException: android.app.Application cannot be cast to kids.animals.fruits.objects.brain.puzzle.memory.game.free.AnalyticsSampleApp06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to kids.animals.fruits.objects.brain.puzzle.memory.game.free.AnalyticsSampleApp
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to kids.animals.fruits.objects.brain.puzzle.memory.game.free.AnalyticsSampleApp06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to kids.animals.fruits.objects.brain.puzzle.memory.game.free.AnalyticsSampleApp06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917): 06-11 11:49:59.510: E/AndroidRuntime(2917):
06-11 11:49:59.510: E/AndroidRuntime(2917):

A: Cause:
The object returned by getApplication is android.app.Application, which throws a ClassCastException, as indicated by the following line in the logcat

06-11 11:49:59.510: E/AndroidRuntime(2917): Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to kids.animals.fruits.objects.brain.puzzle.memory.game.free.AnalyticsSampleApp06-11

Solution:
This can be caused if your manifest doesn't contain the application element
<application android:name=".YourApplication"...
</application>