问:
How to access a button in toolbar?
I have a custome toolbar in application like below there is a button call logout

```<code>    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_layout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/toolbar_logo_image"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="4dp"
            android:layout_centerVertical="true"
            android:background="@drawable/logo" />

        <EditText
            android:id="@+id/toolbar_search_field"
            android:layout_width="280dp"
            android:layout_height="36dp"
            android:textSize="20dp"
            android:hint="Search"
            android:textColorHint="@color/white"
            android:layout_toEndOf="@+id/toolbar_logo_image"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:background="@android:color/transparent"
            android:drawablePadding="2dp"
            android:drawableStart="@drawable/ic_search_24dp"
            tools:textColor="@android:color/black"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>
</code>```

I have include this toolbar in my main activity like below

```<code><include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_toolbar">
    </include>
</code>```

in my main activity I have get that toolbar like below

```<code>mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);
</code>```

How can I access the button in that toolbar I want to create a onclickevent
how can i do that?

答:
You can use findViewById on each View. So you can use

```<code>Button button = (Button) mToolbar.findViewById(R.id.toolbar_logo_image);
</code>```

But as you included the toolbar layout in your root layout, it should be even enough to use

```<code>Button button = (Button) findViewById(R.id.toolbar_logo_image);
</code>```

Both should work.

EDIT: Your app_bar_toolbar.xml has a FrameLayout as root element, but in code you're trying to cast it to Toolbar. That can't work and will crash with a ClassCastException. So change your FrameLayout to a Toolbar or cast the FrameLayout correctly. Depends on your needs.

Title: How to access a button in toolbar?

Body:
I have a custome toolbar in application like below there is a button call logout

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar_layout"
    android:layout_width="match_parent"
    android:layout_height="80dp"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:background="@android:color/transparent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="24dp">

        <Button
            android:id="@+id/toolbar_logo_image"
            android:layout_width="32dp"
            android:layout_height="32dp"
            android:layout_marginStart="8dp"
            android:layout_marginEnd="4dp"
            android:layout_centerVertical="true"
            android:background="@drawable/logo" />

        <EditText
            android:id="@+id/toolbar_search_field"
            android:layout_width="280dp"
            android:layout_height="36dp"
            android:textSize="20dp"
            android:hint="Search"
            android:textColorHint="@color/white"
            android:layout_toEndOf="@+id/toolbar_logo_image"
            android:layout_centerVertical="true"
            android:textColor="@android:color/white"
            android:background="@android:color/transparent"
            android:drawablePadding="2dp"
            android:drawableStart="@drawable/ic_search_24dp"
            tools:textColor="@android:color/black"/>

    </RelativeLayout>

</android.support.v7.widget.Toolbar>

I have include this toolbar in my main activity like below

<include
        android:id="@+id/main_page_toolbar"
        layout="@layout/app_bar_toolbar">
    </include>

in my main activity I have get that toolbar like below

mToolbar = (Toolbar) findViewById(R.id.main_page_toolbar);

How can I access the button in that toolbar I want to create a onclickevent
how can i do that?

Body:
You can use findViewById on each View. So you can use

Button button = (Button) mToolbar.findViewById(R.id.toolbar_logo_image);

But as you included the toolbar layout in your root layout, it should be even enough to use

Button button = (Button) findViewById(R.id.toolbar_logo_image);

Both should work.

EDIT: Your app_bar_toolbar.xml has a FrameLayout as root element, but in code you're trying to cast it to Toolbar. That can't work and will crash with a ClassCastException. So change your FrameLayout to a Toolbar or cast the FrameLayout correctly. Depends on your needs.


来源: stackexchange

问:
PHP - make if statement with two statements shorter
I have the following If statement and I want to make it shorter (eg. a one liner), without writing my if statement in one line.

```<code>    if ($start + $count > $total) {
        $count = $total;
    }
</code>```

Basically I want to achieve that $count + $total is never higher then $total and if this is the case I want to set $count equal to $total.

答:
You can use min() for that:

```<code>$count = min($total, $start + $count);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following If statement and I want to make it shorter (eg. a one liner), without writing my if statement in one line.

    if ($start + $count > $total) {
        $count = $total;
    }

Basically I want to achieve that $count + $total is never higher then $total and if this is the case I want to set $count equal to $total.

Body:
You can use min() for that:

$count = min($total, $start + $count);


问:
Whitelist AWS self in inbound connection
I am deploying a laravel installation in AWS, everything runs perfectly when I allow it to recieve all inbound traffic (EC2>Network&Security>Security Groups>Edit inbound rules.), if I turn off inbound traffic and limit it to an IP it doesnt load the webpage it gives me this error:

PDO Exception SQLSTATE[HY000] [2002] Connection timed out

However for security reasons I dont want this setup like this, I dont want anyone being able to even try to reach my webapp. Everything is being hosted in AWS, I dont have any external entities, its running in RDS and EC2. I added en elastic IP address and whitelisted it, but that didnt work either. I followed every step in this tutorial : http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/php-laravel-tutorial.html#php-laravel-tutorial-generate

Environmental variables are working as well as dependencies, well.. pretty much everything unless I restrict inbound traffic as I mentioned.

How do I whitelist AWS own instance then to make this work with better security?

Thank you!

答:
More than just adding an elastic IP address to your AWS instance you need to do two more things.

Assign the elastic IP to your AWS instance ( yes is not the same as just adding it to the instance, you must specify )

White list the internal IP that it generates once you link it to your app.

?????

Profit


问:
How to convert an Optional<T> into a Stream<T>?
I want to prepend a stream with an Optional. Since Stream.concat can only concatinate Streams I have this question:

How do I convert an Optional<T> into a Stream<T>?

Example:

```<code>Optional<String> optional = Optional.of("Hello");
Stream<String> texts = optional.stream(); // not working
</code>```

答:
I can recommend Guava's Streams.stream(optional) method if you are not on Java 9. A simple example:

```<code>Streams.stream(Optional.of("Hello"))
</code>```

Also possible to static import Streams.stream, so you can just write

```<code>stream(Optional.of("Hello"))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to prepend a stream with an Optional. Since Stream.concat can only concatinate Streams I have this question:

How do I convert an Optional<T> into a Stream<T>?

Example:

Optional<String> optional = Optional.of("Hello");
Stream<String> texts = optional.stream(); // not working

Body:
I can recommend Guava's Streams.stream(optional) method if you are not on Java 9. A simple example:

Streams.stream(Optional.of("Hello"))

Also possible to static import Streams.stream, so you can just write

stream(Optional.of("Hello"))


问:
Chef guard multiple resources with single not_if
When using chef, I only want to execute a sequence of resources if a certain condition is fulfilled. Currently, I have to add the not_if guard to each resource individually. Is there a way to wrap multiple resources inside with a single not_if guard like so:

```<code>wrap_resources do
  service 'my-service'
  package 'my-package'
  not_if certain_condition
end
</code>```

And I do not want to use that nasty notify!

答:
You can also do the following:

```<code>unless certain_condition
  service 'my-service'
  package 'my-package'
end
</code>```

So that you don't need to use a negative statement. Makes it a little more cleaner!

Body:
When using chef, I only want to execute a sequence of resources if a certain condition is fulfilled. Currently, I have to add the not_if guard to each resource individually. Is there a way to wrap multiple resources inside with a single not_if guard like so:

wrap_resources do
  service 'my-service'
  package 'my-package'
  not_if certain_condition
end

And I do not want to use that nasty notify!

Body:
You can also do the following:

unless certain_condition
  service 'my-service'
  package 'my-package'
end

So that you don't need to use a negative statement. Makes it a little more cleaner!


问:
How can I reference xaml Template from a Converter?
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

```<code>        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>
</code>```

and I have this control using this converter:

```<code><ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>
</code>```

My Converter:

```<code>public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }
</code>```

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

答:
Maybe you should think on some other implementation but here is what you're asking for:

your converter code:

```<code>public class MyConverter : IValueConverter
{
    public ControlTemplate TemplateA { get; set; }
    public ControlTemplate TemplateB { get; set; }

    ... Convert methods using TemplateA and TemplateB properties...
}
</code>```

usage in XAML:

```<code><UserControl.Resources>
    <!-- templates with 'templateA' and 'templateB' keys -->
    <Converters:MyConverter x:Key="templateConverters" TemplateA="{StaticResource templateA}" TemplateB="{StaticResource templateB}" />
<UserControl.Resources>

...

<ControlA x:Name="_controlA" >
    <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am currently stuck on a problem assigning different templates to a control via a converter.

So I have 2 templates.

        <ControlTemplate x:Name="_templateA" x:Key="templateA">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah />
            </StackPanel>
        </ControlTemplate>

        <ControlTemplate x:Name="_templateB" x:Key="templateB">
            <StackPanel Grid.Column="0" Margin="0,0,5,0">
                <Blah Blah />
            </StackPanel>
        </ControlTemplate>

and I have this control using this converter:

<ControlA x:Name="_controlA" >
     <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>

My Converter:

public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Object a;
        ControlTemplate template = null;

        try
        {
            a= value as ObjectA;
            if (value != null)
                template = a.useTemplate1 ? [templateA from xaml] : [templateB from xaml];
        }
        catch (Exception ex)
        {
            Debug.Assert(false, ex.ToString());
        }

        return toolbar;
    }

In my Converter, how am I able to get reference to my xaml file so that it allows me to assign it my desired template???

Thanks and Regards,
Kev

Body:
Maybe you should think on some other implementation but here is what you're asking for:

your converter code:

public class MyConverter : IValueConverter
{
    public ControlTemplate TemplateA { get; set; }
    public ControlTemplate TemplateB { get; set; }

    ... Convert methods using TemplateA and TemplateB properties...
}

usage in XAML:

<UserControl.Resources>
    <!-- templates with 'templateA' and 'templateB' keys -->
    <Converters:MyConverter x:Key="templateConverters" TemplateA="{StaticResource templateA}" TemplateB="{StaticResource templateB}" />
<UserControl.Resources>

...

<ControlA x:Name="_controlA" >
    <Control Template="{Binding Converter={StaticResource templateConverters}}" />
</ControlA>


问:
Is there a way to actually delete devices from Apple Developer Portal?
Our company has 11 different apps on AppStore, with different teams developing each app, we have a lot of test devices, and our "Device list" in developer.apple.com/account is completely full. We received a bunch of iPhone 8 and 8 Plus on their release, and a couple of iPhone X on its release, but none of them can be added to our provisioning profiles because our device list is full.

We know that the device list gets updated every year, at the start of our "developer year" when paying the fee. Sadly, in previous years, we have not been deleting unused devices, so we have a lot of devices registered from people who no longer work there, devices we no longer support, and employees' older phones. We can mark them as "inactive", which I guess will mean they get automatically removed when the new year starts..

The next time our membership is renewed is too far into the future. We can't release apps without testing them on these new devices.

I understand the reasoning behind allowing only 100 devices a year, disabling the opportunity to release apps to anyone anytime, but it doesn't really work for us.
There should be a way to apply for an extended list of devices.. Like, 150 would do..

Is there anything I've misunderstood, or is this actually the case? It is impossible for us to add our new devices until the next renewal, even if that's in next August?

答:
As for the initial question, there is nothing you can do to delete devices from an account in the middle of the account year.  But I would take the opportunity now to delete old devices so that you don't forget and end up in the same spot next year.

I would have all developers on the team create individual developer accounts. Then from the original company account, add the new developer accounts as team member roles.  Designate one of those accounts for the new CI/CD process until you can clean up the devices in the main account. Next year at renewal, clean up the devices just to company devices used for testing, and update your CI pipeline to use the company account again.  All developers should add their devices to their own personal developer accounts.

I have heard rumors that some companies have contacted Apple about a temporary increase to the device limit.  You could try contacting them to see if they could grant you a temporary bump.  However, I would make sure you do the other things mentioned above to ensure that you don't run into the problem again down the road.


答:
What you want is called a ternary operation.

```<code>$count = (($start + $count) > $total ? $total : null);
</code>```

References:
https://davidwalsh.name/php-shorthand-if-else-ternary-operators

http://php.net/manual/en/language.operators.comparison.php

https://www.abeautifulsite.net/how-to-use-the-php-ternary-operator

Title: PHP - make if statement with two statements shorter

Body:
What you want is called a ternary operation.

$count = (($start + $count) > $total ? $total : null);

References:
https://davidwalsh.name/php-shorthand-if-else-ternary-operators

http://php.net/manual/en/language.operators.comparison.php

https://www.abeautifulsite.net/how-to-use-the-php-ternary-operator


问:
Can not get file exist exception after Corda 1.0
previously in M14, when I upload one document which already exist in the system, the upload function will return one file exist exception. But after upgrade to V1.0, that exception never returned, even the returned hash code is the same as previously one. Does anyone encounter this issue and how to fix that?

I think below core code's function didn't return the exception which is expected.

@Throws(FileAlreadyExistsException::class, IOException::class)
fun importAttachment(jar: InputStream): AttachmentId

答:
This has been changed for V1 as you have noticed. Now, if the attachment is uploaded again, it just returns the hash with no information leakage if that attachment has already been uploaded. You can see the new code in NodeAttachmentService.kt - https://github.com/corda/corda/blob/8a5bbe7cf8da9139c647f5256e58bd3a00d4949e/node/src/main/kotlin/net/corda/node/services/persistence/NodeAttachmentService.kt#L175 (master version as of today).

Update: After a short discussion with the dev team, we are going to treat this as a bug and raise a ticket for it to be fixed. And I deleted my footnote (viewable in the s/o history)


问:
Is it possible to deploy multiple war files under the same deployment path?
Let's say I have:

foo.war

bar.war

Is it possible that I deploy them both somehow to the same deployment path? E.g., to access it at:

http://localhost/baz

Are the content of the war files merged somehow? How are file conflicts handled (e.g., let's say both of them has an index.jsp file)?

Thx in advnace!

答:
The servlet specification explicitly forbids this.  Deployed web applications may not have identical or overlapping context roots.  From the Servlet 3.0 specification, section 10.5:

Since the context path of an application determines the URL namespace of the contents of the Web application, Web containers must reject Web applications defining a context path that could cause potential conflicts in this URL namespace. This may occur, for example, by attempting to deploy a second Web application with the same context path.


问:
Where is getProtectionDomain() in jruby?
I have a staff class in Java and I can get the location on disk where it was loaded from using the following code:

```<code>Staff.class.getProtectionDomain().getCodeSource().getLocation();
</code>```

In a jruby jirb session I tried the following:

```<code>Staff.getProtectionDomain()
</code>```

and (edit)

```<code>Staff.class.getProtectionDomain()
</code>```

both of which cannot find the method: undefined method `getProtectionDomain'

Is this method masked by jruby and if so, how can I call it?

[edit] I am using jruby 1.5.6.

答:
So there are a couple gotchas here (at least they were for me).

1) You can't get the java Class using the Constant like Staff.class - this will return the ruby Class object.

2) Once you have a java instance, you can only get it's java.lang.Class by using the getClass() method.  Calling class with again give you the class object from the ruby hierarchy.

```<code>x = Java::java.lang.String.new("hi")
x.class.kind_of?(Java::java.lang.Class)  # evaluates to false
x.getClass().kind_of?(Java::java.lang.Class)  # evaluates to true
</code>```

so then I just have to have an instance of Staff (in my example in the question) like this:

```<code>Staff.new.getClass().getProtectionDomain()
</code>```

Body:
I have a staff class in Java and I can get the location on disk where it was loaded from using the following code:

Staff.class.getProtectionDomain().getCodeSource().getLocation();

In a jruby jirb session I tried the following:

Staff.getProtectionDomain()

and (edit)

Staff.class.getProtectionDomain()

both of which cannot find the method: undefined method `getProtectionDomain'

Is this method masked by jruby and if so, how can I call it?

[edit] I am using jruby 1.5.6.

Body:
So there are a couple gotchas here (at least they were for me).

1) You can't get the java Class using the Constant like Staff.class - this will return the ruby Class object.

2) Once you have a java instance, you can only get it's java.lang.Class by using the getClass() method.  Calling class with again give you the class object from the ruby hierarchy.

x = Java::java.lang.String.new("hi")
x.class.kind_of?(Java::java.lang.Class)  # evaluates to false
x.getClass().kind_of?(Java::java.lang.Class)  # evaluates to true

so then I just have to have an instance of Staff (in my example in the question) like this:

Staff.new.getClass().getProtectionDomain()


问:
How to group and pivot(?) dataframe
I have a dataframe looking like this:

```<code>ID  Species Count
1   Pine    1000
1   Spruce  1000
2   Pine    2000
3   Pine    1000
3   Spruce  500
3   Birch   500
</code>```

What i want is this:

```<code>    Pine    Spruce  Birch
ID  Count   Count   Count
1   1000    1000
2   2000
3   1000    500 500
</code>```

So im trying:

```<code>a = df.groupby(['ID']).cumcount().astype(str)
newdf = df.set_index(['ID', a]).unstack(fill_value=0).sort_index(level=1, axis=1)
</code>```

Which gives me:

```<code>ID  Count   Species Count   Species Count   Species
1   1000    Pine    1000    Spruce
2   2000    Pine
3   1000    Pine    500     Spruce  500 Spruce
</code>```

How can i fix this?

答:
Simple pivot

```<code>df.pivot('ID','Species','Count')
Out[493]:
Species  Birch    Pine  Spruce
ID
1          NaN  1000.0  1000.0
2          NaN  2000.0     NaN
3        500.0  1000.0   500.0
</code>```

Title: How to group and pivot(?) dataframe

Body:
I have a dataframe looking like this:

ID  Species Count
1   Pine    1000
1   Spruce  1000
2   Pine    2000
3   Pine    1000
3   Spruce  500
3   Birch   500

What i want is this:

    Pine    Spruce  Birch
ID  Count   Count   Count
1   1000    1000
2   2000
3   1000    500 500

So im trying:

a = df.groupby(['ID']).cumcount().astype(str)
newdf = df.set_index(['ID', a]).unstack(fill_value=0).sort_index(level=1, axis=1)

Which gives me:

ID  Count   Species Count   Species Count   Species
1   1000    Pine    1000    Spruce
2   2000    Pine
3   1000    Pine    500     Spruce  500 Spruce

How can i fix this?

Body:
Simple pivot

df.pivot('ID','Species','Count')
Out[493]:
Species  Birch    Pine  Spruce
ID
1          NaN  1000.0  1000.0
2          NaN  2000.0     NaN
3        500.0  1000.0   500.0


问:
Iteratively removing rows in a repeating R function
I've a large panel dataset in which for many participants, valid observations of a biomarker must be separated from invalid, each forming their own modal distribution.

I wish to apply the diptest for bimodality function to each set of observations, which I have separated using the split function. I need to run the dip.test 1:n times depending on the number of modes in each participants' observations, discarding those observations outside the intervals of the participants' modal, er, lumps. (It's clear which observations belong to the participant using the marker0 variable.) I apply the diptest to all observations for all participants by using the lapply and mutate functions in sequence.

The difficulty comes with repeating the diptest in the central nested function: I wish to exclude observations that each iteration shows not to belong to the participant. However, I haven't found a way to exclude those values in the repeating function (right now I'm just recoding them as x = 1. It'd be a simple case if I were only dealing with one data frame--does anyone know how I can limit my observations with each iteration?

```<code># notional measures

y1 <- rnorm(80,mean=75, sd=3)
y2 <- rnorm(100,mean=100, sd=4)
y3 <- rnorm(40, mean=150, sd=2)
mark <- append(y1,y2)
marker <- append(mark,y3)
df_y <- as.data.frame(marker)
df_y$id <- 1
df_y$marker0 <-100
df_y$lump <- 0
df_y$other <-0

z1 <- rnorm(130,mean=50, sd=2)
z2 <- rnorm(110,mean=125, sd=5)
marker <- append(z1,z2)
df_z <- as.data.frame(marker)
df_z$id <- 2
df_z$marker0 <-130
df_z$lump <- 0
df_z$other <-0

df <- rbind(df_y, df_z)

# my function

trim.others <- function(x,a,b,c) {
repeat {
  diptest <- dip.test(x, simulate.p.value = TRUE, B=500)
  if (diptest$p.value > 0.1) break
  hm <- classIntervals(x, n=2, style="jenks", method="complete")
  b[(a < hm$brks[2])] <- 1
  b[(a > hm$brks[2])] <- 2
  c[(b == 1) & (x > hm$brks[2])] <- 1
  c[(b == 2) & (x < hm$brks[2])] <- 1
  x <- x[c==0]
  }
  return(x)
}
</code>```

Note that the function works if I run it on a single id. Here's the multimodal distribution of the marker in id = 1, followed by the unimodal distribution of y2 in the notional dataset.

```<code>df1 <- df[(df$id==1),]
plot(density(df1$marker)

dfa <- trim.others(df1$marker,df1$marker0,df1$lump,df1$other)
plot(density(dfa))
</code>```

I'd like to run my function trim.others across the entire dataset, with multiple ids. Here's the approach I took.

```<code>dfs <- split(df, f = df$id)

myfunct <- function(w,x,y,z) {
  repeat {
    diptest <- dip.test(x, simulate.p.value = TRUE, B=500)
    if (diptest$p.value > 0.1) break
    hm <- classIntervals(x, n=2, style="jenks", method="complete")
    w[(y < hm$brks[2])] <- 1
    w[(y > hm$brks[2])] <- 2
    x[(w == 1) & (x > hm$brks[2])] <- 1
    x[(w == 2) & (x < hm$brks[2])] <- 1
     }
}

library(dplyr)

anotherfunct <- function(ia) {
  mutate(ia, value = myfunct(lump,marker,marker0,other))
}

dothefunct <- lapply(df,function(i) {anotherfunct(i)})
</code>```

Thank you, group.

答:
I'd use purrr and do your splitting inside the loop:</p>

```<code>library(dplyr)
library(purrr)

trim.others2  <- function(mydf) {

  x  <- mydf$marker
  a  <- mydf$marker0
  b  <- mydf$lump
  c  <- mydf$other

  repeat {

    diptest <- dip.test(x, simulate.p.value = TRUE, B=500)

    if (diptest$p.value > 0.1) break

    hm <- classIntervals(x, n=2, style="jenks", method="complete")
    b[(a < hm$brks[2])] <- 1
    b[(a > hm$brks[2])] <- 2
    c[(b == 1) & (x > hm$brks[2])] <- 1
    c[(b == 2) & (x < hm$brks[2])] <- 1
    x <- x[c==0]

  }
  return(x)
}

all_ids  <- unique(df$id)

list_of_results  <- map(all_ids, ~df %>% filter(id == .x) %>% trim.others2 ) %>%
    setNames(all_ids)
</code>```

Body:
I've a large panel dataset in which for many participants, valid observations of a biomarker must be separated from invalid, each forming their own modal distribution.

I wish to apply the diptest for bimodality function to each set of observations, which I have separated using the split function. I need to run the dip.test 1:n times depending on the number of modes in each participants' observations, discarding those observations outside the intervals of the participants' modal, er, lumps. (It's clear which observations belong to the participant using the marker0 variable.) I apply the diptest to all observations for all participants by using the lapply and mutate functions in sequence.

The difficulty comes with repeating the diptest in the central nested function: I wish to exclude observations that each iteration shows not to belong to the participant. However, I haven't found a way to exclude those values in the repeating function (right now I'm just recoding them as x = 1. It'd be a simple case if I were only dealing with one data frame--does anyone know how I can limit my observations with each iteration?

# notional measures

y1 <- rnorm(80,mean=75, sd=3)
y2 <- rnorm(100,mean=100, sd=4)
y3 <- rnorm(40, mean=150, sd=2)
mark <- append(y1,y2)
marker <- append(mark,y3)
df_y <- as.data.frame(marker)
df_y$id <- 1
df_y$marker0 <-100
df_y$lump <- 0
df_y$other <-0

z1 <- rnorm(130,mean=50, sd=2)
z2 <- rnorm(110,mean=125, sd=5)
marker <- append(z1,z2)
df_z <- as.data.frame(marker)
df_z$id <- 2
df_z$marker0 <-130
df_z$lump <- 0
df_z$other <-0

df <- rbind(df_y, df_z)

# my function

trim.others <- function(x,a,b,c) {
repeat {
  diptest <- dip.test(x, simulate.p.value = TRUE, B=500)
  if (diptest$p.value > 0.1) break
  hm <- classIntervals(x, n=2, style="jenks", method="complete")
  b[(a < hm$brks[2])] <- 1
  b[(a > hm$brks[2])] <- 2
  c[(b == 1) & (x > hm$brks[2])] <- 1
  c[(b == 2) & (x < hm$brks[2])] <- 1
  x <- x[c==0]
  }
  return(x)
}

Note that the function works if I run it on a single id. Here's the multimodal distribution of the marker in id = 1, followed by the unimodal distribution of y2 in the notional dataset.

df1 <- df[(df$id==1),]
plot(density(df1$marker)

dfa <- trim.others(df1$marker,df1$marker0,df1$lump,df1$other)
plot(density(dfa))

I'd like to run my function trim.others across the entire dataset, with multiple ids. Here's the approach I took.

dfs <- split(df, f = df$id)

myfunct <- function(w,x,y,z) {
  repeat {
    diptest <- dip.test(x, simulate.p.value = TRUE, B=500)
    if (diptest$p.value > 0.1) break
    hm <- classIntervals(x, n=2, style="jenks", method="complete")
    w[(y < hm$brks[2])] <- 1
    w[(y > hm$brks[2])] <- 2
    x[(w == 1) & (x > hm$brks[2])] <- 1
    x[(w == 2) & (x < hm$brks[2])] <- 1
     }
}

library(dplyr)

anotherfunct <- function(ia) {
  mutate(ia, value = myfunct(lump,marker,marker0,other))
}

dothefunct <- lapply(df,function(i) {anotherfunct(i)})

Thank you, group.

Body:
I'd use purrr and do your splitting inside the loop:

library(dplyr)
library(purrr)

trim.others2  <- function(mydf) {

  x  <- mydf$marker
  a  <- mydf$marker0
  b  <- mydf$lump
  c  <- mydf$other

  repeat {

    diptest <- dip.test(x, simulate.p.value = TRUE, B=500)

    if (diptest$p.value > 0.1) break

    hm <- classIntervals(x, n=2, style="jenks", method="complete")
    b[(a < hm$brks[2])] <- 1
    b[(a > hm$brks[2])] <- 2
    c[(b == 1) & (x > hm$brks[2])] <- 1
    c[(b == 2) & (x < hm$brks[2])] <- 1
    x <- x[c==0]

  }
  return(x)
}

all_ids  <- unique(df$id)

list_of_results  <- map(all_ids, ~df %>% filter(id == .x) %>% trim.others2 ) %>%
    setNames(all_ids)


答:
You could use the ternary operator.

```<code> $count = ($total < $start+$count) ? $total : $count;
</code>```

This puts the if-logic in one line.

Body:
You could use the ternary operator.

 $count = ($total < $start+$count) ? $total : $count;

This puts the if-logic in one line.


问:
If clause optimization
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

```<code>if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}
</code>```

Is there a cleaner way to write this condition?

Thanks.

答:
A declarative solution in case of multiple conditions in business logic is definitely more verifiable and traceable. A nested if-complex is not. Declarative you have the final criteria with which you called the action.

However if you do not want to use expression language, the java scripting API, JShell, then one must do something like:

```<code>class Criteria {
    Group group;
    Privilege privilege;
    Role role;
    Level level;
}
class GuardedAction {
    String caseName; // For tracability, an auditing name.
    Predicate<Criteria> guard;
    Runnable action;
}

List<GuardedAction> guardedActions;
</code>```

Fill this list, maybe from XML. And version numbers are useful in order to retrace "bugs" that a customer reports in an old log.

```<code>Criteria criteria = ...
for (GuardedAction ga : guardedActions) {
    if (ga.guard.test(criteria)) {
        System.out.println(ga.caseName);
        Logger.log(Level.INFO(ga.toString()); // With a detailed toString.
        ga.action.run();
        break;
    }
}
</code>```

A nested if with business logic is hard to discuss on.

Title: If clause optimization

Body:
I need to write an IF clause (we're using Java 8). The relevant variables are group, privilege, role, level and class. There is an action that needs to be performed in certain case. I've written the alghoritm in the following way:

if (group == G1) {
  if (privilege == P1) {
    // Perform the action if a user has this particular privilege
    perform_action_and_exit();
  } else {
    if (role == R1) {
      if ((level <= 2 && class == C1) || (level == 1 && (class == C2 || class == C3))) {
        perform_action_and_exit();
      }
      // Ignore other combinations of level and class
    }
    // Ignore other roles
  }
} else {
  // Perform the action for any group other than G1
  perform_action_and_exit();
}

Is there a cleaner way to write this condition?

Thanks.

Body:
A declarative solution in case of multiple conditions in business logic is definitely more verifiable and traceable. A nested if-complex is not. Declarative you have the final criteria with which you called the action.

However if you do not want to use expression language, the java scripting API, JShell, then one must do something like:

class Criteria {
    Group group;
    Privilege privilege;
    Role role;
    Level level;
}
class GuardedAction {
    String caseName; // For tracability, an auditing name.
    Predicate<Criteria> guard;
    Runnable action;
}

List<GuardedAction> guardedActions;

Fill this list, maybe from XML. And version numbers are useful in order to retrace "bugs" that a customer reports in an old log.

Criteria criteria = ...
for (GuardedAction ga : guardedActions) {
    if (ga.guard.test(criteria)) {
        System.out.println(ga.caseName);
        Logger.log(Level.INFO(ga.toString()); // With a detailed toString.
        ga.action.run();
        break;
    }
}

A nested if with business logic is hard to discuss on.


问:
Python -> TypeError: unsupported operand type(s) for ^
I am struggling with Python code. I want to do this equation.

This my code:

```<code>fs= 5000
T=np.linspace(0,2.2,fs)
n=np.arange(fs*2.2)
u=[]
for x in T:
    if x < 0.2:
        u.append(x * np.sin(34*np.pi*n/fs))
    if (x >= 0.2 and x < 0.8):
        u.append(1/x * np.log10(x+1))
    if x >= 0.8 and x < 1.4:
        u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))
    if x >= 1.4:
        u.append(np.sin(20*np.pi*n/fs + x/3))
</code>```

And python returns:

```<code>  File "D:/Semestr V/Podstawy Transmisji Danych/labki-ZAD3.py", line 20, in <module>
    u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))

TypeError: unsupported operand type(s) for ^: 'numpy.float64' and 'int'
</code>```

答:
Beyond the mistake ^/**, the good way is to use np.piecewise which is intended for that for a quick vectored result:

```<code>fs= 5000
x=np.linspace(0,2.2,fs)
n=3

functions=[
lambda x : x * np.sin(34*np.pi*n/fs),
lambda x : 1/x * np.log10(x+1),
lambda x : (x**2 + 1) * np.sin(12*np.pi*n/fs),
lambda x : np.sin(20*np.pi*n/fs + x/3)]

conditions=[x < 0.2,(x >= 0.2) & (x < 0.8), (x >= 0.8) & (x < 1.4), x >= 1.4]

res=np.piecewise(x,conditions,functions)
plt.plot(x,res)
</code>```

just loop on n for all the values.

Body:
I am struggling with Python code. I want to do this equation.

This my code:

fs= 5000
T=np.linspace(0,2.2,fs)
n=np.arange(fs*2.2)
u=[]
for x in T:
    if x < 0.2:
        u.append(x * np.sin(34*np.pi*n/fs))
    if (x >= 0.2 and x < 0.8):
        u.append(1/x * np.log10(x+1))
    if x >= 0.8 and x < 1.4:
        u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))
    if x >= 1.4:
        u.append(np.sin(20*np.pi*n/fs + x/3))

And python returns:

  File "D:/Semestr V/Podstawy Transmisji Danych/labki-ZAD3.py", line 20, in <module>
    u.append((x^2 + 1) * np.sin(12*np.pi*n/fs))

TypeError: unsupported operand type(s) for ^: 'numpy.float64' and 'int'

Body:
Beyond the mistake ^/**, the good way is to use np.piecewise which is intended for that for a quick vectored result:

fs= 5000
x=np.linspace(0,2.2,fs)
n=3

functions=[
lambda x : x * np.sin(34*np.pi*n/fs),
lambda x : 1/x * np.log10(x+1),
lambda x : (x**2 + 1) * np.sin(12*np.pi*n/fs),
lambda x : np.sin(20*np.pi*n/fs + x/3)]

conditions=[x < 0.2,(x >= 0.2) & (x < 0.8), (x >= 0.8) & (x < 1.4), x >= 1.4]

res=np.piecewise(x,conditions,functions)
plt.plot(x,res)

just loop on n for all the values.


问:
Service postgresql is stopped in the running docker container with postgres image
I have running container docker run -it --rm -d postgres. I can even connect to it with 172.17.0...:5432 IP. But

```<code>$service --status-all
 [ - ]  cron
 [ - ]  exim4
 [ ? ]  hwclock.sh
 [ - ]  postgresql
 [ - ]  procps
 [ - ]  sysstat
</code>```

How can postgres work if service even hasn't been started ?

答:
You do not provide any port mappings when starting the container. My guess is that you are connecting to your locally installed Postgres instance instead of your postgres container.

Start the postgres container with: docker run --rm -p:5433:5432 -d postgres

Then connect by using the port 5433.

Body:
I have running container docker run -it --rm -d postgres. I can even connect to it with 172.17.0...:5432 IP. But

$service --status-all
 [ - ]  cron
 [ - ]  exim4
 [ ? ]  hwclock.sh
 [ - ]  postgresql
 [ - ]  procps
 [ - ]  sysstat

How can postgres work if service even hasn't been started ?


问:
Keeping pages inside an iframe
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?</p>

```<code>if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}
</code>```

答: Web pages cannot disable JavaScript, if they could, it would be mayhem.</p>

Title: Keeping pages inside an iframe

Body:
I am trying to put a website inside an iframe, but this code on the site keeps changing the window of the page. Is there anyway I can get around this? Or better yet, can I disable javascript in an iframe?

if(top!=self){
  if(top.location)
    top.location=self.location;
  else
    top.location='http://example.com/not_subframe.html';
}


问:
Problems with session ids on parallel threads
So I am trying to use multiprocessing to iterate concurrently through files in separate folders. I have a function that calls the parallel process:

```<code>from multiprocessing.dummy import Pool

lsFolders = ['Folder1', 'Folder2']

pool = Pool( processes = 6 )

iterateThroughFiles = IterateThroughFiles() # instantiated by call to pool.map()

pool.map( iterateThroughFiles.runProcess, lsFolders )
</code>```

Then I have the implementation of the IterateThroughFiles-class:

```<code>class IterateThroughFiles( object ):

  def runProcess( self, folder ):
      self.sessionId = uuid.uuid4()
      print( self.sessionId )             # Prints a correct sessionId
      logAtLevel( "INFO", "Session ID of: "
                         + str( self.sessionId )
                         + " has been generated for folder: "
                         + folder
                           )

      print( self.sessionId )             # Prints only the second generated
      #                                   # session id for both threads
      print( folder )                     # Prints the correct folder
</code>```

When I generate the sessionId and print it directly after, the sessionId is correct, additionally the logAtLevel() wrapper function logs the correct value of the sessionId.

The next print statement, though, prints only the second session id and apparently the first sessionId is forgotten in the thread.

Does anyone know why this is happening? I thought when running in parallel each thread was distinct in terms of the objects it created and its memory? Is this incorrect? Does this have something to with the uuid generator?

答:
The issue is that  you are only generating one instance of IterateThroughFiles which is being used in both threads.
Instead, you want something like the following

```<code>def factory(folder):
    return IterateThroughFiles().runProcess(folder)
</code>```

and pass that factory function into map.
That way you will get two instances.

Body:
So I am trying to use multiprocessing to iterate concurrently through files in separate folders. I have a function that calls the parallel process:

from multiprocessing.dummy import Pool

lsFolders = ['Folder1', 'Folder2']

pool = Pool( processes = 6 )

iterateThroughFiles = IterateThroughFiles() # instantiated by call to pool.map()

pool.map( iterateThroughFiles.runProcess, lsFolders )

Then I have the implementation of the IterateThroughFiles-class:

class IterateThroughFiles( object ):

  def runProcess( self, folder ):
      self.sessionId = uuid.uuid4()
      print( self.sessionId )             # Prints a correct sessionId
      logAtLevel( "INFO", "Session ID of: "
                         + str( self.sessionId )
                         + " has been generated for folder: "
                         + folder
                           )

      print( self.sessionId )             # Prints only the second generated
      #                                   # session id for both threads
      print( folder )                     # Prints the correct folder

When I generate the sessionId and print it directly after, the sessionId is correct, additionally the logAtLevel() wrapper function logs the correct value of the sessionId.

The next print statement, though, prints only the second session id and apparently the first sessionId is forgotten in the thread.

Does anyone know why this is happening? I thought when running in parallel each thread was distinct in terms of the objects it created and its memory? Is this incorrect? Does this have something to with the uuid generator?

Body:
The issue is that  you are only generating one instance of IterateThroughFiles which is being used in both threads.
Instead, you want something like the following

def factory(folder):
    return IterateThroughFiles().runProcess(folder)

and pass that factory function into map.
That way you will get two instances.


问:
Cloud Firestore : Is compound range query in more than 2 fields available now?
I need to get ranged data like this.

```<code>ex) 10 < a < 20 ,  30 < b < 40
</code>```

a and b both fields are index key now.

I think in this situation compound range query is the easy way.

But in Cloud Firestore, range queries are possible only for one field.

```<code>ex)   (possible) citiesRef.where("state", "==", "CA").where("population", "<", 1000000)

    (impossible) citiesRef.where("state", ">=", "CA").where("population", ">", 100000)
</code>```

How can I range query in 2 fields?

答:
As writing, this is not possible with Cloud Firestore and will likely never be available. Depending on your requirements though, there are workarounds by rethinking your data model and queries slightly.

Option 1: Precompute a range

In this option you can add a field called population_bracket. In here, you essentially place the population value into a bracket you can test. Either decide by hand what the ranges are depending on your need, or use some automated method like ceil(log(population))

As an example the population of CA is roughly 39250000, so using the log method ceil(log(population)) we get 8 which is what we'd store in population_bracket. If we're okay with the population range filter being changed to <= 1000000, then we can make the population filter a simple equality check using population_bracket == 6. CA gets correctly excluded!

Option 2: client-side filter

In this option you make an educated guess which range filter will reduce the resultset the most, then simply do client-side filter of the results for the second filter (e.g, just ignore every state < "CA")

Body:
I need to get ranged data like this.

ex) 10 < a < 20 ,  30 < b < 40

a and b both fields are index key now.

I think in this situation compound range query is the easy way.

But in Cloud Firestore, range queries are possible only for one field.

ex)   (possible) citiesRef.where("state", "==", "CA").where("population", "<", 1000000)

    (impossible) citiesRef.where("state", ">=", "CA").where("population", ">", 100000)

How can I range query in 2 fields?


问:
BelongsTo relationship returns null when using relation name "user"
When creating a simple one-to-one relationship in Laravel 5.5, $person->user is returning a null value whenever I use the method/relation name user. If I change the name to foo, User, or login the code seems to work fine. This is the second project I've had this same issue on. Can anyone see what I'm doing wrong?

In Person model:

```<code>public function user() {
    return $this->belongsTo(User::class, 'user_id', 'id');
}
public function foo() {
    return $this->belongsTo(User::class, 'user_id', 'id');
}
public function getUser() {
    if ($this->user_id) {
        return User::find($this->user_id);
    } else {
        return null;
    }
}
</code>```

In PersonTest:

```<code>$user = factory(User::class)->create();
$person = factory(Person::class)->create(['user_id' => $user->id]);

// This works
$this->assertTrue( $person->getUser()->is($user) );

// This works
$this->assertTrue( !is_null($person->foo) );
if ( $person->foo ) {
    $this->assertTrue( $person->foo->is($user) );
}

// This fails
$this->assertTrue( !is_null($person->user) );
if ( $person->user ) {
    $this->assertTrue( $person->user->is($user) );
}
</code>```

By request, here is all of the code relating to Person,
Entire App\Models\Person.php:

```<code>use App\Models\User;
use App\Models\Asset;
use App\Traits\HasGuid;
use App\Traits\HasNotes;
use App\Traits\HasModifiedBy;
use App\Traits\HasAttachments;
use App\Traits\HasRelationships;
use App\Transformers\PersonTransformer;
use App\Models\Abstracts\HasTypeModelAbstract;
use App\Models\Interfaces\HasTypeModelInterface;

class Person extends HasTypeModelAbstract implements HasTypeModelInterface {

    use HasModifiedBy,
        HasNotes,
        HasAttachments,
        HasRelationships;

    protected $fillable = [
        'person_type_id',
        'email',
        'fname',
        'lname',
        'user_id',
        'modified_by_user_id',
        'audited_at',
        'custom_attributes'
    ];
    protected $casts = [
        'custom_attributes' => 'json',
        'user_id' => 'integer',
        'modified_by_user_id' => 'integer',
        'person_type_id' => 'integer'
    ];
    protected $dates = [
        'audited_at'
    ];

    public static $transformer = PersonTransformer::class;

    public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function type() {
        return $this->belongsTo(PersonType::class, 'person_type_id');
    }

    public function assets() {
        return $this->hasMany(Asset::class, 'person_id');
    }
</code>```

Traits:

```<code>trait HasNotes {

    protected static function bootHasNotes() {
        static::deleting(function ($instance) {
            $instance->notes->each(function ($note) {
                $note->delete();
            });
        });
    }

    public function notes() {
        return $this->morphMany(Note::class, 'notable');
    }

}

trait HasModifiedBy {

    protected static function bootHasModifiedBy() {
        static::saving(function ($instance) {
            $instance->modified_by_user_id = Auth::id();
        });
    }

    public function modifiedBy() {
        return $this->belongsTo(User::class, 'modified_by_user_id');
    }

}

trait HasAttachments {

    protected static function bootHasAttachments() {

        static::deleting(function ($instance) {
            $instance->attachments->each(function ($attachment) {
                $attachment->delete();
            });
        });
    }

    public function attachments() {
        return $this->morphMany(Attachment::class, 'attachable');
    }

}

trait HasRelationships {

    protected static function bootHasRelationships()
    {
        static::deleting(function ($instance) {
            Relation::forObject( $instance )->delete();
        });
    }

    public function related() { ...[long polymorphic relationship here]... }
</code>```

/App/Models/Abstracts/HasTypeModelAbstract

```<code>use Illuminate\Database\Eloquent\Model;

// This thing just appends some custom attributes dynamically in the JSON and array forms. And no, 'user' is not a custom attribute key.

abstract class HasTypeModelAbstract extends Model {

public function newFromBuilder($attributes = array(), $connection = NULL) {
    $instance = parent::newFromBuilder($attributes);
    $instance->appendCustomAttributes();
    return $instance;
}

protected function appendCustomAttributes() {
    $this->append( $this->getCustomAttributesFromType() );
}

public function getCustomAttributesFromType() {
    if ($this->type) {
        return $this->type->custom_attributes ?
                array_keys((array) $this->type->custom_attributes) : [];
    } else {
        return [];
    }
}

protected function setCustomAttributesFromType($attributes = array()) {
    if ($this->type) {
        $custom_attribute_keys = $this->getCustomAttributesFromType();
        $custom_attributes = (array) $this->custom_attributes ?: [];
        foreach ($custom_attribute_keys as $key) {
            $attributes[$key] = array_get($custom_attributes, $key);
        }
    }
    return $attributes;
}

protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes) {

    $this->appendCustomAttributes($this, $attributes);
    $attributes = $this->setCustomAttributesFromType($attributes);
    return parent::addMutatedAttributesToArray($attributes, $mutatedAttributes);
}

protected function mutateAttribute($key, $value)
{
    $keys = $this->getCustomAttributesFromType();
    if ( in_array($key, $keys) ) {
        return $this->getCustomAttributeValue( $key, $value );
    }
    return parent::mutateAttribute($key, $value);
}

protected function getCustomAttributeValue($key, $value) {
    $custom_attributes = (array) $this->custom_attributes ?: [];
    return array_get($custom_attributes, $key, $value);
}
</code>```

答:
I have to be honest - quickly looking at the code I don't see anything wrong but it doesn't mean everything is for sure ok.

If I were you, I would try to limit Person model just to:

```<code>class Person extends \Illuminate\Database\Eloquent\Model {

    protected $fillable = [
        'person_type_id',
        'email',
        'fname',
        'lname',
        'user_id',
        'modified_by_user_id',
        'audited_at',
        'custom_attributes'
    ];
    protected $casts = [
        'custom_attributes' => 'json',
        'user_id' => 'integer',
        'modified_by_user_id' => 'integer',
        'person_type_id' => 'integer'
    ];
    protected $dates = [
        'audited_at'
    ];

    public static $transformer = PersonTransformer::class;

    public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function type() {
        return $this->belongsTo(PersonType::class, 'person_type_id');
    }

    public function assets() {
        return $this->hasMany(Asset::class, 'person_id');
    }

}
</code>```

and now I would verify if everything is fine. If it's fine, now you could investigate this further, add one trait and verify, add second trait and verify, finally extend from same class.

There must be bug somewhere but looking at this code it's hard do find anything

Body:
When creating a simple one-to-one relationship in Laravel 5.5, $person->user is returning a null value whenever I use the method/relation name user. If I change the name to foo, User, or login the code seems to work fine. This is the second project I've had this same issue on. Can anyone see what I'm doing wrong?

In Person model:

public function user() {
    return $this->belongsTo(User::class, 'user_id', 'id');
}
public function foo() {
    return $this->belongsTo(User::class, 'user_id', 'id');
}
public function getUser() {
    if ($this->user_id) {
        return User::find($this->user_id);
    } else {
        return null;
    }
}

In PersonTest:

$user = factory(User::class)->create();
$person = factory(Person::class)->create(['user_id' => $user->id]);

// This works
$this->assertTrue( $person->getUser()->is($user) );

// This works
$this->assertTrue( !is_null($person->foo) );
if ( $person->foo ) {
    $this->assertTrue( $person->foo->is($user) );
}

// This fails
$this->assertTrue( !is_null($person->user) );
if ( $person->user ) {
    $this->assertTrue( $person->user->is($user) );
}

By request, here is all of the code relating to Person,
Entire App\Models\Person.php:

use App\Models\User;
use App\Models\Asset;
use App\Traits\HasGuid;
use App\Traits\HasNotes;
use App\Traits\HasModifiedBy;
use App\Traits\HasAttachments;
use App\Traits\HasRelationships;
use App\Transformers\PersonTransformer;
use App\Models\Abstracts\HasTypeModelAbstract;
use App\Models\Interfaces\HasTypeModelInterface;

class Person extends HasTypeModelAbstract implements HasTypeModelInterface {

    use HasModifiedBy,
        HasNotes,
        HasAttachments,
        HasRelationships;

    protected $fillable = [
        'person_type_id',
        'email',
        'fname',
        'lname',
        'user_id',
        'modified_by_user_id',
        'audited_at',
        'custom_attributes'
    ];
    protected $casts = [
        'custom_attributes' => 'json',
        'user_id' => 'integer',
        'modified_by_user_id' => 'integer',
        'person_type_id' => 'integer'
    ];
    protected $dates = [
        'audited_at'
    ];

    public static $transformer = PersonTransformer::class;

    public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function type() {
        return $this->belongsTo(PersonType::class, 'person_type_id');
    }

    public function assets() {
        return $this->hasMany(Asset::class, 'person_id');
    }

Traits:

trait HasNotes {

    protected static function bootHasNotes() {
        static::deleting(function ($instance) {
            $instance->notes->each(function ($note) {
                $note->delete();
            });
        });
    }

    public function notes() {
        return $this->morphMany(Note::class, 'notable');
    }

}

trait HasModifiedBy {

    protected static function bootHasModifiedBy() {
        static::saving(function ($instance) {
            $instance->modified_by_user_id = Auth::id();
        });
    }

    public function modifiedBy() {
        return $this->belongsTo(User::class, 'modified_by_user_id');
    }

}

trait HasAttachments {

    protected static function bootHasAttachments() {

        static::deleting(function ($instance) {
            $instance->attachments->each(function ($attachment) {
                $attachment->delete();
            });
        });
    }

    public function attachments() {
        return $this->morphMany(Attachment::class, 'attachable');
    }

}

trait HasRelationships {

    protected static function bootHasRelationships()
    {
        static::deleting(function ($instance) {
            Relation::forObject( $instance )->delete();
        });
    }

    public function related() { ...[long polymorphic relationship here]... }

/App/Models/Abstracts/HasTypeModelAbstract

use Illuminate\Database\Eloquent\Model;

// This thing just appends some custom attributes dynamically in the JSON and array forms. And no, 'user' is not a custom attribute key.

abstract class HasTypeModelAbstract extends Model {

public function newFromBuilder($attributes = array(), $connection = NULL) {
    $instance = parent::newFromBuilder($attributes);
    $instance->appendCustomAttributes();
    return $instance;
}

protected function appendCustomAttributes() {
    $this->append( $this->getCustomAttributesFromType() );
}

public function getCustomAttributesFromType() {
    if ($this->type) {
        return $this->type->custom_attributes ?
                array_keys((array) $this->type->custom_attributes) : [];
    } else {
        return [];
    }
}

protected function setCustomAttributesFromType($attributes = array()) {
    if ($this->type) {
        $custom_attribute_keys = $this->getCustomAttributesFromType();
        $custom_attributes = (array) $this->custom_attributes ?: [];
        foreach ($custom_attribute_keys as $key) {
            $attributes[$key] = array_get($custom_attributes, $key);
        }
    }
    return $attributes;
}

protected function addMutatedAttributesToArray(array $attributes, array $mutatedAttributes) {

    $this->appendCustomAttributes($this, $attributes);
    $attributes = $this->setCustomAttributesFromType($attributes);
    return parent::addMutatedAttributesToArray($attributes, $mutatedAttributes);
}

protected function mutateAttribute($key, $value)
{
    $keys = $this->getCustomAttributesFromType();
    if ( in_array($key, $keys) ) {
        return $this->getCustomAttributeValue( $key, $value );
    }
    return parent::mutateAttribute($key, $value);
}

protected function getCustomAttributeValue($key, $value) {
    $custom_attributes = (array) $this->custom_attributes ?: [];
    return array_get($custom_attributes, $key, $value);
}

Body:
I have to be honest - quickly looking at the code I don't see anything wrong but it doesn't mean everything is for sure ok.

If I were you, I would try to limit Person model just to:

class Person extends \Illuminate\Database\Eloquent\Model {

    protected $fillable = [
        'person_type_id',
        'email',
        'fname',
        'lname',
        'user_id',
        'modified_by_user_id',
        'audited_at',
        'custom_attributes'
    ];
    protected $casts = [
        'custom_attributes' => 'json',
        'user_id' => 'integer',
        'modified_by_user_id' => 'integer',
        'person_type_id' => 'integer'
    ];
    protected $dates = [
        'audited_at'
    ];

    public static $transformer = PersonTransformer::class;

    public function user() {
        return $this->belongsTo(User::class, 'user_id', 'id');
    }

    public function type() {
        return $this->belongsTo(PersonType::class, 'person_type_id');
    }

    public function assets() {
        return $this->hasMany(Asset::class, 'person_id');
    }

}

and now I would verify if everything is fine. If it's fine, now you could investigate this further, add one trait and verify, add second trait and verify, finally extend from same class.

There must be bug somewhere but looking at this code it's hard do find anything


答:
```<code>In [94]: df.set_index(['ID', 'Species'])['Count'].unstack(fill_value=0)
Out[94]:
Species  Birch  Pine  Spruce
ID
1            0  1000    1000
2            0  2000       0
3          500  1000     500
</code>```

Title: How to group and pivot(?) dataframe


问:
Angular: ng-model=value *0.5, possible?
My code is like that:

  I want that, while user modify the value of testVaalue in the first input, the second input changed automatically. Is it possible?

Thank you very much

答:
No, you can't do it like that, but should be able to do:

```<code><input type="text" readonly value="{{(value * 0.5) || 0}}" />
</code>```

Or you could just display the result as text:

```<code>{{(value * 0.5) || 0}}
</code>```

Title: Angular: ng-model=value *0.5, possible?

Body:
No, you can't do it like that, but should be able to do:

<input type="text" readonly value="{{(value * 0.5) || 0}}" />

Or you could just display the result as text:

{{(value * 0.5) || 0}}


问:
deleting certain lines out of a urllib url
```<code>import csv
import urllib.request
from pylab import *

eventurl = "http://data.hisparc.nl/show/source/eventtime/501/2017/1/1/"
data = urllib.request.urlopen(eventurl)
print(data.read())
</code>```

When I run the code and the data from the eventurl is printed, this is what terminal shows:

```<code>b"# HiSPARC eventtime histogram source\n#\n# Station: 501\n# Data from 2017-1-1\n#\n# HiSPARC data is licensed under Creative Commons Attribution-ShareAlike 4.0.\n#\n#\n# Please note: the 'bin' is the left bin edge. The width of the bin is 1\n# hour.  So bin 0 means between 0:00 and 1:00. Value means the number of\n# events which were measured during 1 hour.\n#\n# This data contains the following columns:\n#\n# bin:   time [hour of day]\n# value: number of events [counts]\n#\n#\n# bin\tvalue\n0\t2265\n1\t2354\n2\t2302\n3\t2353\n4\t2369\n5\t2378\n6\t2280\n7\t2411\n8\t2340\n9\t2431\n10\t2353\n11\t2394\n12\t2412\n13\t2470\n14\t2404\n15\t2540\n16\t2492\n17\t2390\n18\t2454\n19\t2404\n20\t2451\n21\t2467\n22\t2471\n23\t2371\n\n"
</code>```

what we want to have, is just two rows with the bins and the values. Is there a code that can help us get rid of the rest and make it easy to use the numbers for a histogram?

Body:
import csv
import urllib.request
from pylab import *

eventurl = "http://data.hisparc.nl/show/source/eventtime/501/2017/1/1/"
data = urllib.request.urlopen(eventurl)
print(data.read())

When I run the code and the data from the eventurl is printed, this is what terminal shows:

b"# HiSPARC eventtime histogram source\n#\n# Station: 501\n# Data from 2017-1-1\n#\n# HiSPARC data is licensed under Creative Commons Attribution-ShareAlike 4.0.\n#\n#\n# Please note: the 'bin' is the left bin edge. The width of the bin is 1\n# hour.  So bin 0 means between 0:00 and 1:00. Value means the number of\n# events which were measured during 1 hour.\n#\n# This data contains the following columns:\n#\n# bin:   time [hour of day]\n# value: number of events [counts]\n#\n#\n# bin\tvalue\n0\t2265\n1\t2354\n2\t2302\n3\t2353\n4\t2369\n5\t2378\n6\t2280\n7\t2411\n8\t2340\n9\t2431\n10\t2353\n11\t2394\n12\t2412\n13\t2470\n14\t2404\n15\t2540\n16\t2492\n17\t2390\n18\t2454\n19\t2404\n20\t2451\n21\t2467\n22\t2471\n23\t2371\n\n"

what we want to have, is just two rows with the bins and the values. Is there a code that can help us get rid of the rest and make it easy to use the numbers for a histogram?

Body:
Using Python regex re module

import csv
import urllib.request
import re
l = []
eventurl = "http://data.hisparc.nl/show/source/eventtime/501/2017/1/1/"
data = urllib.request.urlopen(eventurl)
for line in data.readlines():
    line = str(line,'utf-8').strip()
    if re.search(r'\d+\t\d+', line):
        l.append(line.split()[1])

print (l)

Output:

['2265', '2354', '2302', '2353', '2369', '2378', '2280', '2411', '2340', '2431', '2353', '2394', '2412', '2470', '2404', '2540', '2492', '2390', '2454', '2404', '2451', '2467', '2471', '2371']


问:
How to specify my databases name into JDBC -> MySQL connection?
What is the way to connect with JDBC to a mySql database that is online?

mysql.info.mi.us:3006 = corresponds to the server of the database

mydatabases_2 = my databases

my try returning this error:

java.lang.NullPointerException

```<code>Class.forName("com.mysql.jdbc.Driver")
connexion = DriverManager.getConnection("jdbc:mysql://mysql.info.mi.us:3306", "user", "password");
</code>```

答:
Just append it:</p>

```<code>connexion = DriverManager.getConnection("jdbc:mysql://mysql.info.mi.us:3006/mydatabases_2", "user", "password");
</code>```

Body:
What is the way to connect with JDBC to a mySql database that is online?

mysql.info.mi.us:3006 = corresponds to the server of the database

mydatabases_2 = my databases

my try returning this error:

java.lang.NullPointerException

Class.forName("com.mysql.jdbc.Driver")
connexion = DriverManager.getConnection("jdbc:mysql://mysql.info.mi.us:3306", "user", "password");

Body:
Just append it:

connexion = DriverManager.getConnection("jdbc:mysql://mysql.info.mi.us:3006/mydatabases_2", "user", "password");


答:
I would suggest declaring a new variable which can track half value.

Example

Template

```<code><div ng-controller="MyCtrl">
  value:{{value}} half:{{value*0.5}}!
  <br>
  <input ng-model="value" type="text">
  <input ng-model="half" type="text">
</div>
</code>```

controller code

```<code>var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.value = 5;
    $scope.half = $scope.value * 0.5;

    $scope.$watch('value', function() {
        $scope.half = $scope.value * 0.5;
    });
}
</code>```

Title: Angular: ng-model=value *0.5, possible?

Body:
My code is like that:

  I want that, while user modify the value of testVaalue in the first input, the second input changed automatically. Is it possible?

Thank you very much

Body:
I would suggest declaring a new variable which can track half value.

Example

Template

<div ng-controller="MyCtrl">
  value:{{value}} half:{{value*0.5}}!
  <br>
  <input ng-model="value" type="text">
  <input ng-model="half" type="text">
</div>

controller code

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
    $scope.value = 5;
    $scope.half = $scope.value * 0.5;

    $scope.$watch('value', function() {
        $scope.half = $scope.value * 0.5;
    });
}


问:
Sum of rows in SQL with GROUP BY
I am having a table with data like:

```<code>ID  OrderId TAX%    Quantity UnitCost
1     5      28    2       1280
2     5      18    1       1180
</code>```

I want the output like:

```<code>ORDERID    TaxableValue       TaxValue
   5           3000               740
</code>```

How can I achieve this? I tried with:

```<code>SELECT orderid,
       ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2) AS taxValue,
       ROUND(SUM(unitCost*quantity)-ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2),2) AS taxableValue
FROM table1
GROUP BY OrderId;
</code>```

But the query above is not working.

Sorry all, That is the Tax percentage. This is the new Updated Query. Please consider this.

答:
Pretty sure it is as simple as doing a little math.

```<code>select OrderID
    , TaxableValue = SUM(UnitCost - TAX)
    , TaxValue = SUM(TAX * Quantity)
from YourTable
group by OrderID
</code>```

EDIT: The math was slightly off on the TaxableValue

For those who want proof that this works.

```<code>declare @Something table
(
    ID int
    , OrderId int
    , TAX int
    , Quantity int
    , UnitCost int
)

insert @Something values
(1, 5, 28, 2, 228)
, (2, 5, 18, 1, 118)

select OrderID
    , TaxableValue = SUM(UnitCost - TAX)
    , TaxValue = SUM(TAX * Quantity)
from @Something
group by OrderID
</code>```

Title: Sum of rows in SQL with GROUP BY

Body:
I am having a table with data like:

ID  OrderId TAX%    Quantity UnitCost
1     5      28    2       1280
2     5      18    1       1180

I want the output like:

ORDERID    TaxableValue       TaxValue
   5           3000               740

How can I achieve this? I tried with:

SELECT orderid,
       ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2) AS taxValue,
       ROUND(SUM(unitCost*quantity)-ROUND((SUM(UnitCost*Quantity)*TAX)/(100+TAX),2),2) AS taxableValue
FROM table1
GROUP BY OrderId;

But the query above is not working.

Sorry all, That is the Tax percentage. This is the new Updated Query. Please consider this.

Body:
Pretty sure it is as simple as doing a little math.

select OrderID
    , TaxableValue = SUM(UnitCost - TAX)
    , TaxValue = SUM(TAX * Quantity)
from YourTable
group by OrderID

EDIT: The math was slightly off on the TaxableValue

For those who want proof that this works.

declare @Something table
(
    ID int
    , OrderId int
    , TAX int
    , Quantity int
    , UnitCost int
)

insert @Something values
(1, 5, 28, 2, 228)
, (2, 5, 18, 1, 118)

select OrderID
    , TaxableValue = SUM(UnitCost - TAX)
    , TaxValue = SUM(TAX * Quantity)
from @Something
group by OrderID


问:
Try - Catch Laravel on Index function
Hi everyone

I've a question, and it's about Try - Catch, I've a function where I've 3 variables, from two differents models. The problem is, when the model don't have any records in DB, I try redirect the user from the home page, but dind't work, !important, one function had a request for an ajax function inside the view; here my code:

This one is with Try and Catch

```<code>try
      {
        $events = Event::all();
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));
      } catch (\Exception $e) {
          return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
</code>```

I used also and IF and ELSE, like this one:

```<code>public function show_events(Request $request)
    {
      $events = Event::all();
      if($events) {
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));

      } else {
        return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
    }
</code>```

But didn't work to, if someone can help me, I'll be really gratefull!

答: You could use if(count($events)>0) instead of if($events) . then your else contion will work.</p>

Title: Try - Catch Laravel on Index function

Body:
Hi everyone

I've a question, and it's about Try - Catch, I've a function where I've 3 variables, from two differents models. The problem is, when the model don't have any records in DB, I try redirect the user from the home page, but dind't work, !important, one function had a request for an ajax function inside the view; here my code:

This one is with Try and Catch

try
      {
        $events = Event::all();
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));
      } catch (\Exception $e) {
          return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }

I used also and IF and ELSE, like this one:

public function show_events(Request $request)
    {
      $events = Event::all();
      if($events) {
        $competitions = Competition::orderBy('id', 'DESC')->get();
        $ultimos = Event::orderBy('id', 'DESC')->paginate(5);

        if ($request->ajax()) {
            return Response::json(\View::make('events.partials.last', array('ultimos' => $ultimos))->render());
        }

        return View('events.index', compact('events', 'ultimos', 'competitions'));

      } else {
        return redirect('/')->with('errors', 'Ha ocurrido un errror, lo sentimos');
      }
    }

But didn't work to, if someone can help me, I'll be really gratefull!


问:
Debugging keyboard events like 'Ctrl+Up Arrow'
I want to debug a part of a program that is intended to respond to keyboard input such as Ctrl+↑.

So, I put a breakpoint in the code in the area interest. However, once I press the Ctrl key the program jumps to that breakpoint. This happens before I have pressed an arrow key, so I'm finding this situation difficult to debug.

So, how can I debug a multi-key input event such as Ctrl+↑?

答: What event do you use? KeyDown? Try using KeyUp. It won't fire until you release CTRL+key combination.</p>


问:
Is there a better way to perform multiple output with Dash by Plotly?
As we can see in Interactivity part of Getting started, one callback function can accept multiple inputs but always has single output.

Assume that we have two blocks separately that must be updated after input change. Of course, the simplest way is to make two callbacks with same input for each of the blocks. The problem is that request performs twice while one is enough to get all data.

```<code>@app.callback(
    dash.dependencies.Output('element_1', 'children'),
    [dash.dependencies.Input('filter', 'value')])
def callback_element_1(filter):
    return get_data(filter).el1

@app.callback(
    dash.dependencies.Output('element_2', 'children'),
    [dash.dependencies.Input('filter', 'value')])
def callback_element_2(filter):
    return get_data(filter).el2
</code>```

Solution I find is to wrap these elements in single block and re-render it completely with a single request. But in this case all static content in the wrapper will be refreshed too, especially if initial elements are far from each other in DOM.

```<code>@app.callback(
    dash.dependencies.Output('wrapper', 'children'),
    [dash.dependencies.Input('filter', 'value')])
def callback_element_wrapper(filter):
    data = get_data(filter)
    return html.Div(
        children=[
            data.el1,
            # more static content
            data.el2,
        ]
    )
</code>```

So maybe there are more elegant way to output in two or more elements with a single request?

答:
Based on this,
there is a way.

What you can do is to update a hidden "Signal Element" (this can be a text input for example), which in turn, updates the two main elements.

Run the get_data(filter) once, and store the result in a global variable. Then instead of updating element_1 and element_2,
update that signal element.

```<code>result = []

@app.callback(
dash.dependencies.Output('signal', 'value'),
[dash.dependencies.Input('filter', 'value')])
def callback_signal(filter):
    global result
    result = get_data(filter)
    return filter

@app.callback(
dash.dependencies.Output('element_1', 'children'),
[dash.dependencies.Input('signal', 'value')])
def callback_element_1(filter):
    return result.el1

@app.callback(
dash.dependencies.Output('element_2', 'children'),
[dash.dependencies.Input('signal', 'value')])
def callback_element_2(filter):
    return result.el2
</code>```

In my case, I was using Dash in a single user environment, and using the global variable was not an issue. In case you have multiple users who will be running the app at the same time, the alternatives are available, and you can find them in the same link.

Body:
As we can see in Interactivity part of Getting started, one callback function can accept multiple inputs but always has single output.

Assume that we have two blocks separately that must be updated after input change. Of course, the simplest way is to make two callbacks with same input for each of the blocks. The problem is that request performs twice while one is enough to get all data.

@app.callback(
    dash.dependencies.Output('element_1', 'children'),
    [dash.dependencies.Input('filter', 'value')])
def callback_element_1(filter):
    return get_data(filter).el1

@app.callback(
    dash.dependencies.Output('element_2', 'children'),
    [dash.dependencies.Input('filter', 'value')])
def callback_element_2(filter):
    return get_data(filter).el2

Solution I find is to wrap these elements in single block and re-render it completely with a single request. But in this case all static content in the wrapper will be refreshed too, especially if initial elements are far from each other in DOM.

@app.callback(
    dash.dependencies.Output('wrapper', 'children'),
    [dash.dependencies.Input('filter', 'value')])
def callback_element_wrapper(filter):
    data = get_data(filter)
    return html.Div(
        children=[
            data.el1,
            # more static content
            data.el2,
        ]
    )

So maybe there are more elegant way to output in two or more elements with a single request?

Body:
Based on this,
there is a way.

What you can do is to update a hidden "Signal Element" (this can be a text input for example), which in turn, updates the two main elements.

Run the get_data(filter) once, and store the result in a global variable. Then instead of updating element_1 and element_2,
update that signal element.

result = []

@app.callback(
dash.dependencies.Output('signal', 'value'),
[dash.dependencies.Input('filter', 'value')])
def callback_signal(filter):
    global result
    result = get_data(filter)
    return filter

@app.callback(
dash.dependencies.Output('element_1', 'children'),
[dash.dependencies.Input('signal', 'value')])
def callback_element_1(filter):
    return result.el1

@app.callback(
dash.dependencies.Output('element_2', 'children'),
[dash.dependencies.Input('signal', 'value')])
def callback_element_2(filter):
    return result.el2

In my case, I was using Dash in a single user environment, and using the global variable was not an issue. In case you have multiple users who will be running the app at the same time, the alternatives are available, and you can find them in the same link.


问:
How to convert data stored in a matrix-like form to one (continuous) time series object in R?
I have a data set stored as follows (only the first 3 rows of data):

The real data set extends until the year 2010. In other words, I have 20 years of data - 240 data points - stored in a matrix-like form whose lines are the years and the columns are the months from January to December.

I would like to know how to convert this data into a time series object, with the first occurrence taking place in Jan. 1990, and the last in Dec. 2010.

I tried:

```<code>myData.st = ts(myData, start = c(1990,1), end = c(2010,12), frequency = 12)
</code>```

but it didn't work correctly. It seems that if I execute the line above, I'll have 20 independent time series objects, each one with only 12 data points.

I want one single time-series object from Jan. 1990 to Dec.2010. One of the main difficulties for me is how to "let R know" that after one row ends in December of a given year, the next value should be taken from January of the next year.

I have found examples of how to convert a data frame into a time series object. However, the data frames in the examples I came across would have a specific column which to convert. Not in this case. Here, all columns have data points of interest.

How can I accomplish that? Would I be able to accomplish this with either the zoo or the xls packages?

Thank you.

Body:
I have a data set stored as follows (only the first 3 rows of data):

The real data set extends until the year 2010. In other words, I have 20 years of data - 240 data points - stored in a matrix-like form whose lines are the years and the columns are the months from January to December.

I would like to know how to convert this data into a time series object, with the first occurrence taking place in Jan. 1990, and the last in Dec. 2010.

I tried:

myData.st = ts(myData, start = c(1990,1), end = c(2010,12), frequency = 12)

but it didn't work correctly. It seems that if I execute the line above, I'll have 20 independent time series objects, each one with only 12 data points.

I want one single time-series object from Jan. 1990 to Dec.2010. One of the main difficulties for me is how to "let R know" that after one row ends in December of a given year, the next value should be taken from January of the next year.

I have found examples of how to convert a data frame into a time series object. However, the data frames in the examples I came across would have a specific column which to convert. Not in this case. Here, all columns have data points of interest.

How can I accomplish that? Would I be able to accomplish this with either the zoo or the xls packages?

Thank you.

Body:
It depends on what you have.  If it is an R matrix like this then:

m <- matrix(1:240, 12) # test input
ts(c(m), start = 1990, freq = 12)

or if you have an R data frame like this:

DF <- as.data.frame(m)

then convert it to a matrix, m <- as.matrix(DF), and then use the code shown.

Note that print will show such a time series with months along the top and years along the side but it is not two dimensional -- that is just how it prints.

The output is:

     Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
1990   1   2   3   4   5   6   7   8   9  10  11  12
1991  13  14  15  16  17  18  19  20  21  22  23  24
1992  25  26  27  28  29  30  31  32  33  34  35  36
1993  37  38  39  40  41  42  43  44  45  46  47  48
1994  49  50  51  52  53  54  55  56  57  58  59  60
1995  61  62  63  64  65  66  67  68  69  70  71  72
1996  73  74  75  76  77  78  79  80  81  82  83  84
1997  85  86  87  88  89  90  91  92  93  94  95  96
1998  97  98  99 100 101 102 103 104 105 106 107 108
1999 109 110 111 112 113 114 115 116 117 118 119 120
2000 121 122 123 124 125 126 127 128 129 130 131 132
2001 133 134 135 136 137 138 139 140 141 142 143 144
2002 145 146 147 148 149 150 151 152 153 154 155 156
2003 157 158 159 160 161 162 163 164 165 166 167 168
2004 169 170 171 172 173 174 175 176 177 178 179 180
2005 181 182 183 184 185 186 187 188 189 190 191 192
2006 193 194 195 196 197 198 199 200 201 202 203 204
2007 205 206 207 208 209 210 211 212 213 214 215 216
2008 217 218 219 220 221 222 223 224 225 226 227 228
2009 229 230 231 232 233 234 235 236 237 238 239 240


答:
Have a look at the Debug.Assert method. It will allow you to only go to debug based on a condition. Execution will continue until the condition is false. You could do something like (pseudo-code): Debug.Assert(NOT up key pressed);
This will make it ignore any key presses but the up key.

Title: Debugging keyboard events like 'Ctrl+Up Arrow'

Body:
I want to debug a part of a program that is intended to respond to keyboard input such as Ctrl+↑.

So, I put a breakpoint in the code in the area interest. However, once I press the Ctrl key the program jumps to that breakpoint. This happens before I have pressed an arrow key, so I'm finding this situation difficult to debug.

So, how can I debug a multi-key input event such as Ctrl+↑?


问:
Can't Sendkeys to input field in Android
I'm trying to set some  text to input for ELEMENT
But when I trying do this like ELEMENT.SendKeys() nothing happens.
I can click into the input field (It means ELEMENT with right XPath).

Xpath looks like: "//android.widget.EditText[@resource-id="amount"]"

Text value is empty
only @content-desc have a value

What should I do for simulating set text to the field ELEMENT?

答:
First, since you are using Xpath you need to put full resourceId value (with package name)
Assuming you are using instance of AndroidDriver as driver you can do this in Java:

```<code>AndroidElement editElement = driver.findElement(By.id("amount"));
editElement.setValue(value);
</code>```

Body:
First, since you are using Xpath you need to put full resourceId value (with package name)
Assuming you are using instance of AndroidDriver as driver you can do this in Java:

AndroidElement editElement = driver.findElement(By.id("amount"));
editElement.setValue(value);


问:
How to add a string with superscript in an THREE.TextGeometry?
I'm working on a dimensioning tool with Three.js.
I would like to write dimensioning of distances over a line between two objects.
I want to write 2.455 as shown in the picture.

Sadly, as in Threejs R88 is HTML encoding not possible to get, for example, the superscript function in TextGeometry.  A solution would be to append a second text geometry (with the superscript number) to the main one. But I would like to avoid this solution since I think it's not a very wise/clean one.
Do you have any ideas how to solve this?

someting like this doesn't work obviously:

```<code>var ss = '5'.sup();

var geometry = new THREE.TextGeometry( '2.45' + ss, {
        font: font,
        size: 80,
        height: 5});
</code>```

Thank you in advance, I'm open to every suggestion.

答:
The Font you load must support the characters you want to use.

After a brief inspection, I was able to find "²" in the helvetiker_regular.typeface.json font file. That does not guarantee that it will include the characters you're looking for. For example, I was unable to find a definition for "⁶" in the same file.

Of course, the easiest workaround is to create normal-scale numbers, then scale/position them into a suberscript position. Three.js also provides methods for combining geometries, so you would make fewer meshes in the process (addressing your "not clean" concern).

Body:
I'm working on a dimensioning tool with Three.js.
I would like to write dimensioning of distances over a line between two objects.
I want to write 2.455 as shown in the picture.

Sadly, as in Threejs R88 is HTML encoding not possible to get, for example, the superscript function in TextGeometry.  A solution would be to append a second text geometry (with the superscript number) to the main one. But I would like to avoid this solution since I think it's not a very wise/clean one.
Do you have any ideas how to solve this?

someting like this doesn't work obviously:

var ss = '5'.sup();

var geometry = new THREE.TextGeometry( '2.45' + ss, {
        font: font,
        size: 80,
        height: 5});

Thank you in advance, I'm open to every suggestion.


问:
okhttp 3 very slow
I try to get json from a server, I use https on the server and every http request will go to the https version.

I get the data <s>and the data that I send works to </s>but it takes up to 45 sec to get a response back. The same code was faster with the build in http handler of android.

How can I speed up the request?

```<code>try {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder formBuilder = new FormBody.Builder().add("key", "2285");
        //formBuilder.add("phone", "000000");

        RequestBody formBody = formBuilder.build();
        Log.v("JsonRespons", reqUrl);
        Request request = new Request.Builder()
                .url(reqUrl)
                .post(formBody)
                .build();

        okhttp3.Response response = null;

        response = client.newCall(request).execute();

        if (!response.isSuccessful()) {
            throw new IOException(response.message() + " " + response.toString());
        } else {
            output = response.body().string();
        }

        if(output != null) {
            Log.v("JsonRespons", output.toString());
        }
    } catch (IOException e) {
         e.printStackTrace();
    }
</code>```

答:
You must consider some important things :

Executing Okhttp3 request away from UI thread, like AsyncTask.

Don't forget to close response body after complete.

```<code>    new AsyncTask<String,Void,String>(){

    @Override
    protected String doInBackground(String... strings) {
        String strResponse = null;
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                strResponse = response.body().string();
                response.close();  // DON't forget to close body =@response.body().close();
            }

        }catch (Exception ex){
        }
        return strResponse;
    }

    @Override
    protected void onPostExecute(String s) {
        // Update UI here
    }
};
</code>```

Using okhttp3 thread using enqueue

```<code>client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // When failure
        mActivity.runOnUiThread(); // If need to update UI
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()){
            String result = response.body().string();
            mActivity.runOnUiThread(); // update UI under UI thread.
            response.close();  // close response body.
        }
    }
});
</code>```

Creating OkHttp3Client and configure timeout.

```<code>private static OkHttpClient createHttpclient() {
final OkHttpClient.Builder builder =  new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS);
setSocketFactory(builder); // To handle SSL certificate.
return builder.build();
}
</code>```

Title: okhttp 3 very slow

Body:
I try to get json from a server, I use https on the server and every http request will go to the https version.

I get the data <s>and the data that I send works to </s>but it takes up to 45 sec to get a response back. The same code was faster with the build in http handler of android.

How can I speed up the request?

try {
        OkHttpClient client = new OkHttpClient();
        FormBody.Builder formBuilder = new FormBody.Builder().add("key", "2285");
        //formBuilder.add("phone", "000000");

        RequestBody formBody = formBuilder.build();
        Log.v("JsonRespons", reqUrl);
        Request request = new Request.Builder()
                .url(reqUrl)
                .post(formBody)
                .build();

        okhttp3.Response response = null;

        response = client.newCall(request).execute();

        if (!response.isSuccessful()) {
            throw new IOException(response.message() + " " + response.toString());
        } else {
            output = response.body().string();
        }

        if(output != null) {
            Log.v("JsonRespons", output.toString());
        }
    } catch (IOException e) {
         e.printStackTrace();
    }

Body:
You must consider some important things :

Executing Okhttp3 request away from UI thread, like AsyncTask.

Don't forget to close response body after complete.

    new AsyncTask<String,Void,String>(){

    @Override
    protected String doInBackground(String... strings) {
        String strResponse = null;
        try {
            Response response = client.newCall(request).execute();
            if (response.isSuccessful()) {
                strResponse = response.body().string();
                response.close();  // DON't forget to close body =@response.body().close();
            }

        }catch (Exception ex){
        }
        return strResponse;
    }

    @Override
    protected void onPostExecute(String s) {
        // Update UI here
    }
};

Using okhttp3 thread using enqueue

client.newCall(request).enqueue(new Callback() {
    @Override
    public void onFailure(Call call, IOException e) {
        // When failure
        mActivity.runOnUiThread(); // If need to update UI
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.isSuccessful()){
            String result = response.body().string();
            mActivity.runOnUiThread(); // update UI under UI thread.
            response.close();  // close response body.
        }
    }
});

Creating OkHttp3Client and configure timeout.

private static OkHttpClient createHttpclient() {
final OkHttpClient.Builder builder =  new OkHttpClient.Builder()
        .connectTimeout(10, TimeUnit.SECONDS)
        .writeTimeout(10, TimeUnit.SECONDS)
        .readTimeout(30, TimeUnit.SECONDS);
setSocketFactory(builder); // To handle SSL certificate.
return builder.build();
}


问:
Snap UICollection View Cell to centre using Objective C
I am implementing a Horizontal UICollectionView in Objective C. I want to snap the cell to the centre of the collection view as shown in image below. When an item is snapped to centre I want the items on left and right partially visible. How can I achieve this?

I have used custom IOCOllectionViewFlowLayout and override the

```<code>- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity
</code>```

but its not working for me ,

```<code>CGFloat approximatePage = self.collectionView.contentOffset.x / self.pageWidth;
    CGFloat currentPage = (velocity.x < 0.0) ? floor(approximatePage) : ceil(approximatePage);

    NSInteger flickedPages = ceil(velocity.x / self.flickVelocity);
    float pageWidth = self.pageWidth;
    if (flickedPages) {
        proposedContentOffset.x = flickedPages * self.pageWidth;
    } else {
        proposedContentOffset.x = currentPage * self.pageWidth;
    }
    return proposedContentOffset;
</code>```

How to implement it using Objective C?

答: In this case when you need to be centered horizontally, you will need to implement delegate method scrollViewWillEndDragging as kirander mentioned. When you detect that user stopped scrolling, detect visible cell and put it on the center with this code: projectSelectionCollectionView.scrollToItem(at: indexPath, at: .centeredHorizontally, animated: true)

Body:
I am implementing a Horizontal UICollectionView in Objective C. I want to snap the cell to the centre of the collection view as shown in image below. When an item is snapped to centre I want the items on left and right partially visible. How can I achieve this?

I have used custom IOCOllectionViewFlowLayout and override the

- (CGPoint)targetContentOffsetForProposedContentOffset:(CGPoint)proposedContentOffset withScrollingVelocity:(CGPoint)velocity

but its not working for me ,

CGFloat approximatePage = self.collectionView.contentOffset.x / self.pageWidth;
    CGFloat currentPage = (velocity.x < 0.0) ? floor(approximatePage) : ceil(approximatePage);

    NSInteger flickedPages = ceil(velocity.x / self.flickVelocity);
    float pageWidth = self.pageWidth;
    if (flickedPages) {
        proposedContentOffset.x = flickedPages * self.pageWidth;
    } else {
        proposedContentOffset.x = currentPage * self.pageWidth;
    }
    return proposedContentOffset;

How to implement it using Objective C?


问:
Using dplyr `enquo` after calling argument
I have a function that roughly follows this structure:

```<code>TestFunc <- function(dat, point) {
    if (!(point %in% c("NW", "SE", "SW")))
        stop("point must be one of 'SW', 'SE', 'NW'")

    point <- enquo(point)

    return(dat %>% filter(point == !!point))
</code>```

The issue is that I get the following error when I include the check for values:

```<code>Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated
</code>```

The error disappears when I remove the check.  How can I keep both?

答:
Because of technical reasons that have to do with how R optimises code, you can only capture arguments that have not been evaluated yet.

So you first have to capture with enquo() and then proceed to check the value. However if you have to mix both quoting and value-based code it often indicates a design problem.

As Hong suggested it seems that in your case you can directly unquote the value without capturing it. Unquoting will ensure the right value is found (since you gave the same name to that variable as the column in your data frame).

Body:
I have a function that roughly follows this structure:

TestFunc <- function(dat, point) {
    if (!(point %in% c("NW", "SE", "SW")))
        stop("point must be one of 'SW', 'SE', 'NW'")

    point <- enquo(point)

    return(dat %>% filter(point == !!point))

The issue is that I get the following error when I include the check for values:

Error in (function (x, strict = TRUE)  :
  the argument has already been evaluated

The error disappears when I remove the check.  How can I keep both?


问:
Limit images show in post to last six
I have with me a set of posts created from a scaffold and images uploaded using paperclip gem. I would like to show on each users profile the last six images from the users last posts and for that I am filtering as such

```<code><% @posts.limit(6).each do |tweet| %>
  <% if post.media.present? %>
    <%= link_to image_tag(post.media.url(:thumb)), tweet %><br>
  <% end %>
<% end %>
</code>```

In my controller I have the posts arranged as such

```<code>@posts = user.posts.order('created_at desc')
</code>```

My question is. Why is it that when using the above code, NO image is displayed. On upping the count to 9, I get three images displayed, to 12 i get six images displayed and so on

答:
First of all, you should not make the calls to the db/model (with limit) in the views. Call it directly in the controller :
@posts = user.posts.order(created_at: :desc).limit(6)

Then, I would do some debugging to be sure you have the records you want.

Use byebug for instance and call it just after you set you @posts instance variable to see what it contains. Do all the posts contain a media ?

Title: Limit images show in post to last six

Body:
I have with me a set of posts created from a scaffold and images uploaded using paperclip gem. I would like to show on each users profile the last six images from the users last posts and for that I am filtering as such

<% @posts.limit(6).each do |tweet| %>
  <% if post.media.present? %>
    <%= link_to image_tag(post.media.url(:thumb)), tweet %>

  <% end %>
<% end %>

In my controller I have the posts arranged as such

@posts = user.posts.order('created_at desc')

My question is. Why is it that when using the above code, NO image is displayed. On upping the count to 9, I get three images displayed, to 12 i get six images displayed and so on