问:
Odoo hide "Create" and "Edit" buttons depend on state and role
I would like to hide "Create" and "Edit" buttons on state and group role in form view .For example hide Create and Edit buttons when the state is not draft and user belongs to request user group.

As I understand hide buttons I can on editing views. And on group role rules I can disable create or edit.

I tried to write a rule for request user group but then user can't use the button but see it.

From view I found only way to hide default Create and Edit buttons:

```<code><form string="Request" create="false" edit="false">
</code>```

But in that way I hide them for all users for all states. Is there another way how can I hide Create and Edit buttons depend on state and group role?

I tried to expand the base.xml template on conditions state is "approved" or "done" and the group role is purchase_request_user and view id is view_purchase_request_form "Create" and "Edit" button:

```<code><?xml version="1.0" encoding="UTF-8"?>
<templates xml:space='preserve'>
    <t t-extend="FormView.buttons">
        <t t-if="widget.fields_view.state !== 'done' or widget.fields_view.state !== 'approved'">
        <div class="o_form_buttons_view">
            <button t-if="widget.is_action_enabled('edit')"
                    type="button"
                    class="oe_form_button_edit btn btn-default btn-sm" accesskey="E">
                Edit
            </button>
            <button t-if="widget.is_action_enabled('create')"
                    type="button" class="oe_form_button_create btn btn-default btn-sm"
                    accesskey="C">
                Create
            </button>
        </div>
        </t>
    </t>
</templates>
</code>```

added 'base' to dependences.

UPDATED base.xml Now I can change "Create" button name depend on my view name but nothing that depends on my module states.

```<code><templates>
<t t-extend="FormView.buttons">
    <t t-jquery="button.oe_form_button_create" t-operation="replace">
        <t t-if="widget.fields_view.name == 'purchase.request.form'">
            <button t-if="widget.is_action_enabled('create')"
                    type="button" class="oe_form_button_create btn btn-default btn-sm"
                    accesskey="C">
                New button name
            </button>
        </t>
    </t>
 </t>
</templates>
</code>```

My form view xml peace:

```<code><openerp>
    <data>
        <record model="ir.ui.view" id="view_purchase_request_form">
            <field name="name">purchase.request.form</field>
            <field name="model">purchase.request</field>
            <field name="arch" type="xml">
                <form string="Purchase Request" create="false" edit="false">
                <header>
                    <button name="%(action_sale_order_reset)d" attrs="{'invisible': [('state','not in', ('to_approve_first'))]}" string="Reset" type="action" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_to_approve_first" states="draft" string="Request approval" type="object" class="oe_highlight"/>
                    <button name="button_approved" states="to_approve_first" string="Approve" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_approvedd" states="approved" string="Return Request" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_create_order" states="approvedd" string="Create Order" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_user"/>
                    <button name="button_to_approve_second" states="create_order" string="Approve" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_approved2" states="to_approve_second" string="Done" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_rejected" states="draft,approvedd" string="Reject" type="object" groups="purchase_request.group_purchase_request_user"/>
                    <field name="state" widget="statusbar" statusbar_visible="draft,to_approve_first,approved,rejected" statusbar_colors="{"approved":"green"}"/>
                </header>
                <sheet>
                    <group>
                        <group>
                            <field name="date_start" readonly="1"/>
                            <field name="participate_process"/>
                        </group>
                        <group>
                            <field name="requested_by" readonly="1"/>
                            <field name="assigned_to" attrs="{'readonly': [('state','not in', ('draft'))]}" />
                        </group>
                  <notebook>
                        <page string="Order" attrs="{'invisible': [('state','in', ('draft', 'to_approve_first', 'approved', 'approvedd'))]}">
                            <field name="supply_ids" attrs="{'readonly': [('state','not in', ('to_approve_second'))]}"/>
                        </page>
                   </notebook>
                </sheet>
                </form>
            </field>
        </record>
</code>```

答:
You have to write a template inheriting the 'FormView.buttons' one, check the context fields, like groups and state, and put a condition based on the wanted fields.

Something like this:

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space='preserve'>
    <t t-extend="FormView.buttons">
        <t t-if="widget.fields_view.state == <wanted_state>">
            <your operations>
        </t>
    </t>
</templates>
```

Body:
I would like to hide "Create" and "Edit" buttons on state and group role in form view .For example hide Create and Edit buttons when the state is not draft and user belongs to request user group.

As I understand hide buttons I can on editing views. And on group role rules I can disable create or edit.

I tried to write a rule for request user group but then user can't use the button but see it.

From view I found only way to hide default Create and Edit buttons:

<form string="Request" create="false" edit="false">

But in that way I hide them for all users for all states. Is there another way how can I hide Create and Edit buttons depend on state and group role?

I tried to expand the base.xml template on conditions state is "approved" or "done" and the group role is purchase_request_user and view id is view_purchase_request_form "Create" and "Edit" button:

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space='preserve'>
    <t t-extend="FormView.buttons">
        <t t-if="widget.fields_view.state !== 'done' or widget.fields_view.state !== 'approved'">

            <button t-if="widget.is_action_enabled('edit')"
                    type="button"
                    class="oe_form_button_edit btn btn-default btn-sm" accesskey="E">
                Edit
            </button>
            <button t-if="widget.is_action_enabled('create')"
                    type="button" class="oe_form_button_create btn btn-default btn-sm"
                    accesskey="C">
                Create
            </button>

        </t>
    </t>
</templates>

added 'base' to dependences.

UPDATED base.xml Now I can change "Create" button name depend on my view name but nothing that depends on my module states.

<templates>
<t t-extend="FormView.buttons">
    <t t-jquery="button.oe_form_button_create" t-operation="replace">
        <t t-if="widget.fields_view.name == 'purchase.request.form'">
            <button t-if="widget.is_action_enabled('create')"
                    type="button" class="oe_form_button_create btn btn-default btn-sm"
                    accesskey="C">
                New button name
            </button>
        </t>
    </t>
 </t>
</templates>

My form view xml peace:

<openerp>
    <data>
        <record model="ir.ui.view" id="view_purchase_request_form">
            <field name="name">purchase.request.form</field>
            <field name="model">purchase.request</field>
            <field name="arch" type="xml">
                <form string="Purchase Request" create="false" edit="false">

                    <button name="%(action_sale_order_reset)d" attrs="{'invisible': [('state','not in', ('to_approve_first'))]}" string="Reset" type="action" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_to_approve_first" states="draft" string="Request approval" type="object" class="oe_highlight"/>
                    <button name="button_approved" states="to_approve_first" string="Approve" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_approvedd" states="approved" string="Return Request" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_create_order" states="approvedd" string="Create Order" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_user"/>
                    <button name="button_to_approve_second" states="create_order" string="Approve" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_approved2" states="to_approve_second" string="Done" type="object" class="oe_highlight" groups="purchase_request.group_purchase_request_manager"/>
                    <button name="button_rejected" states="draft,approvedd" string="Reject" type="object" groups="purchase_request.group_purchase_request_user"/>
                    <field name="state" widget="statusbar" statusbar_visible="draft,to_approve_first,approved,rejected" statusbar_colors="{"approved":"green"}"/>

                <sheet>
                    <group>
                        <group>
                            <field name="date_start" readonly="1"/>
                            <field name="participate_process"/>
                        </group>
                        <group>
                            <field name="requested_by" readonly="1"/>
                            <field name="assigned_to" attrs="{'readonly': [('state','not in', ('draft'))]}" />
                        </group>
                  <notebook>
                        <page string="Order" attrs="{'invisible': [('state','in', ('draft', 'to_approve_first', 'approved', 'approvedd'))]}">
                            <field name="supply_ids" attrs="{'readonly': [('state','not in', ('to_approve_second'))]}"/>
                        </page>
                   </notebook>
                </sheet>
                </form>
            </field>
        </record>


来源: stackexchange

问:
Error running ImageMagick from R: Invalid parameter
I am trying to make a GIF-animation in R. I have an array of matrices which i wish to convert into a GIF animation. My strategy is inspired from this example:

http://ryouready.wordpress.com/2010/11/21/animate-gif-images-in-r-imagemagick/

where the following code produces 11 PNG-Pictures with the "png"-function in R. Next it calls for the external ImageMagick-program "convert" to compile the GIF animation.

```<code>dir.create("examples")
setwd("examples")

# Animated countdown from 10 to "GO!".
png(file="example%02d.png", width=200, height=200)
for (i in c(10:1, "G0!")){
plot.new()
text(.5, .5, i, cex = 6)
}
dev.off()

# convert the .png files to one .gif file using ImageMagick.
system("convert -delay 80 *.png example_1.gif")
#shell("convert -delay 80 *.png example_1.gif")
</code>```

The problem is that R doesn't seem to finde the exe-file "convert" which is a part of ImageMagick and installed on the C-drive (C:\Program Files\ImageMagick-6.8.5-Q16). In the comments to the website i am linking to earlier, it is suggested for Windows users to use "shell" instead of "system" to run external programs but none of the two work. The error message is

```<code>Invalid parameter - 80
Warning message:
running command 'convert -delay 80 *.png example_1.gif' had status 4
</code>```

I've tried to change the Windows PATH enviroment variable in the systems properties, as suggested in this answer, but the PATH-variable was allready corectlly defined on my system. I also tried specifying the whole string of the convert.exe file, but also without luck...

How can i get ImageMagick to run through R?

Specs:
Windows 7 Servicepack 1,
R 3.0.0

Thanks in advance...

答:
I'm a windows 10 user, after defining the working directory I got it working in R using

```<code>shell("convert -set delay 80 -loop 0 *.jpg example_shell_test.gif")
</code>```

within cmd each command means the following

convert = open convert function from ImageMagick

-set delay x = set the delay time between each frame to x  (1000 = 1 second)

-loop 0 = loop forever, if set to 1 it will go through the images once

*.[image type]= and file of .[image type]

[name of output gif].gif = save new .gif as

I got it working first within command prompt by navigating to the directory and running the line

```<code>convert -set delay 80 -loop 0 *.jpg example_cmd_test.gif
</code>```

Before this I was using
    -delay = 80
rather than
    -set delay 80
in cmd and got error:
convert: invalid argument for option '-delay': = @ error/convert.c/ConvertImageCommand/1277.

In R using the system() command with the correct "-set delay x" I was getting error:

```<code>> system("convert -set delay = 80 -loop 0 *.jpg example_3.gif")
Invalid Parameter - delay
Warning message:
running command 'convert -set delay = 80 -loop 0 *.jpg example_3.gif' had status 4
</code>```

other errors in shell()

```<code>> shell("convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif")
convert: unable to open image '80': No such file or directory @ error/blob.c/OpenBlob/3094.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/509.
Warning messages:
1: running command 'C:\WINDOWS\system32\cmd.exe /c convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif' had status 1
2: In shell("convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif") :
  'convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif' execution failed with error code 1
</code>```

I ran it in R with shell() after and it seems to work fine

```<code>shell("convert -set delay = 80 -loop 0 *.jpg example_shell_test.gif")
</code>```

Do have a look at this thread also

ImageMagick - Issue with Windows and convert function

ContentLicense: CC BY-SA 3.0

Body:
I am trying to make a GIF-animation in R. I have an array of matrices which i wish to convert into a GIF animation. My strategy is inspired from this example:

http://ryouready.wordpress.com/2010/11/21/animate-gif-images-in-r-imagemagick/

where the following code produces 11 PNG-Pictures with the "png"-function in R. Next it calls for the external ImageMagick-program "convert" to compile the GIF animation.

dir.create("examples")
setwd("examples")

# Animated countdown from 10 to "GO!".
png(file="example%02d.png", width=200, height=200)
for (i in c(10:1, "G0!")){
plot.new()
text(.5, .5, i, cex = 6)
}
dev.off()

# convert the .png files to one .gif file using ImageMagick.
system("convert -delay 80 *.png example_1.gif")
#shell("convert -delay 80 *.png example_1.gif")

The problem is that R doesn't seem to finde the exe-file "convert" which is a part of ImageMagick and installed on the C-drive (C:\Program Files\ImageMagick-6.8.5-Q16). In the comments to the website i am linking to earlier, it is suggested for Windows users to use "shell" instead of "system" to run external programs but none of the two work. The error message is

Invalid parameter - 80
Warning message:
running command 'convert -delay 80 *.png example_1.gif' had status 4

I've tried to change the Windows PATH enviroment variable in the systems properties, as suggested in this answer, but the PATH-variable was allready corectlly defined on my system. I also tried specifying the whole string of the convert.exe file, but also without luck...

How can i get ImageMagick to run through R?

Specs:
Windows 7 Servicepack 1,
R 3.0.0

Thanks in advance...

Body:
I'm a windows 10 user, after defining the working directory I got it working in R using

shell("convert -set delay 80 -loop 0 *.jpg example_shell_test.gif")

within cmd each command means the following

convert = open convert function from ImageMagick

-set delay x = set the delay time between each frame to x  (1000 = 1 second)

-loop 0 = loop forever, if set to 1 it will go through the images once

*.[image type]= and file of .[image type]

[name of output gif].gif = save new .gif as

I got it working first within command prompt by navigating to the directory and running the line

convert -set delay 80 -loop 0 *.jpg example_cmd_test.gif

Before this I was using
    -delay = 80
rather than
    -set delay 80
in cmd and got error:
convert: invalid argument for option '-delay': = @ error/convert.c/ConvertImageCommand/1277.

In R using the system() command with the correct "-set delay x" I was getting error:

> system("convert -set delay = 80 -loop 0 *.jpg example_3.gif")
Invalid Parameter - delay
Warning message:
running command 'convert -set delay = 80 -loop 0 *.jpg example_3.gif' had status 4

other errors in shell()

> shell("convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif")
convert: unable to open image '80': No such file or directory @ error/blob.c/OpenBlob/3094.
convert: no decode delegate for this image format `' @ error/constitute.c/ReadImage/509.
Warning messages:
1: running command 'C:\WINDOWS\system32\cmd.exe /c convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif' had status 1
2: In shell("convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif") :
  'convert -set delay = 80 -loop 0 *.jpg example_shell_test11.gif' execution failed with error code 1

I ran it in R with shell() after and it seems to work fine

shell("convert -set delay = 80 -loop 0 *.jpg example_shell_test.gif")

Do have a look at this thread also

ImageMagick - Issue with Windows and convert function


问:
creating multiple Django model fields
I need to create 100 same fields in Django model. Maybe there is the simple way of doing this or I need to add it like this:

```<code>    Field1 = models.CharField(max_length=40)
    Field2 = models.CharField(max_length=40)
    Field3 = models.CharField(max_length=40)
    ...
</code>```

?

答:
If your columns count are 100+. I advice you to use Django JsonField and save data like JsonFormat
for more information please read this link
https://docs.djangoproject.com/en/1.10/ref/contrib/postgres/fields/#jsonfield

Title: creating multiple Django model fields

Body:
I need to create 100 same fields in Django model. Maybe there is the simple way of doing this or I need to add it like this:

    Field1 = models.CharField(max_length=40)
    Field2 = models.CharField(max_length=40)
    Field3 = models.CharField(max_length=40)
    ...

?


问:
Using pandas' groupby with shifting
I am looking to use pd.rolling_mean in a groupby operation. I want to have in each group a rolling mean of the previous elemnets within the same group. Here is an example:

```<code>id    val
0     1
0     2
0     3
1     4
1     5
2     6
</code>```

Grouping by id, this should be transformed into:

```<code>id    val
0     nan
0     1
0     1.5
1     nan
1     4
2     nan
</code>```

答:
I believe you want pd.Series.expanding

```<code>df.groupby('id').val.apply(lambda x: x.expanding().mean().shift())

0    NaN
1    1.0
2    1.5
3    NaN
4    4.0
5    NaN
Name: val, dtype: float64
</code>```

Title: Using pandas' groupby with shifting

Body:
I am looking to use pd.rolling_mean in a groupby operation. I want to have in each group a rolling mean of the previous elemnets within the same group. Here is an example:

id    val
0     1
0     2
0     3
1     4
1     5
2     6

Grouping by id, this should be transformed into:

id    val
0     nan
0     1
0     1.5
1     nan
1     4
2     nan

Body:
I believe you want pd.Series.expanding

df.groupby('id').val.apply(lambda x: x.expanding().mean().shift())

0    NaN
1    1.0
2    1.5
3    NaN
4    4.0
5    NaN
Name: val, dtype: float64


问:
adding variables numical values (newb question)
Yesterday i had a look at how to set values of variables from nummbers stored in external txt files

the variables then needed to be added up so i used trial and  error first

((XVAL) + (NEWVAL))

assuming that XVAL was set to 10 and NEWVAL was set to 20 i expected to get the answer of thirty but waqs presented with the new value of 10 20

VB.net pysicaly added the two values together but i wanted the mathematical product of the two which is ((10) + (20)) = 30

yep its a newb question could anyone explain how to achieve what im affter

答:
XVAL and NEWVAL are strings, so they are simply being concatenated together. You need to convert them to integers, so that VB.NET will treat them as such. To do this, use the Int32.Parse() method.

```<code>Dim intXVAL As Integer = Int32.Parse(XVAL)
Dim intNEWVAL as Integer = Int32.Parse(NEWVAL)

Dim result = intXVAL + intNEWVAL
</code>```

ContentLicense: CC BY-SA 2.5

Body:
XVAL and NEWVAL are strings, so they are simply being concatenated together. You need to convert them to integers, so that VB.NET will treat them as such. To do this, use the Int32.Parse() method.

Dim intXVAL As Integer = Int32.Parse(XVAL)
Dim intNEWVAL as Integer = Int32.Parse(NEWVAL)

Dim result = intXVAL + intNEWVAL


问:
crash before app starts : SecurityException: Permission Denial: INTERACT_ACROSS_USERS_FULL

Background

I have a rooted device, which is Galaxy S3 I9300 , with Samsung stock based ROM, based on Android 4.3.

I never had any problems running an app i'm working on with this device.

The problem

ever since yesterday (and I didn't change anything on the device), each time I open the app, it shows for a very short time, closes itself without any crash dialog yet it shows the next log:

```<code>01-30 09:27:18.325: E/DatabaseUtils(2366): Writing exception to parcel
01-30 09:27:18.325: E/DatabaseUtils(2366): java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
01-30 09:27:18.325: E/DatabaseUtils(2366):  at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:13140)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:2038)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at com.android.providers.settings.SettingsProvider.callFromPackage(SettingsProvider.java:607)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.content.ContentProvider$Transport.call(ContentProvider.java:279)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:273)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.os.Binder.execTransact(Binder.java:388)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at dalvik.system.NativeStart.run(Native Method)
</code>```

it doesn't even get to the code of the class that extends Application ...

What I've found

It seems that this problem is very common (many have reported about it), but I can't find any solution and why it occurs, other than having a rooted device.

People also say the permission that is written here is actually a system permission, but I never even heard of it, let alone use it (not even sure what it is).

Problem is, the app I'm working on doesn't have anything related to root, plus it worked just a few days ago.

I've tried to re-install the ROM (Omega ROM v54) and also disable anything related to xposed framework. it didn't help.

The question

How do I fix this issue? How would I know other users won't have this problem?

Is it even related to rooted devices?

EDIT: i thought i've found an answer that fixes it, by choosing "revoke USB debugging..." on the developers section of the settings screen. it seemed to work at first, but later the problem returned and clicking it didn't do anything helpful anymore...

EDIT: I think it's just a bug on the app itself or the ROM, since I can't reproduce it anymore. It's quite weird since I'm quite sure I've tried to debug the app and put a breakpoint on the onCreate method of the acitivity (and maybe of the application class itself) and it didn't stop there.

答:
```<code>01-30 09:27:18.325: E/DatabaseUtils(2366): java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
</code>```

This error comes from where you get/set any user/system settings in your app. This particular error log is showing your settings get/set (from your app code) is calling from user 0 (USER_OWNER), but the setting you're changing is for user -2 (USER_CURRENT).

You can't change other users' settings without the permission android.permission.INTERACT_ACROSS_USERS_FULL.

You're probably not considering the case of having different userID's (between calling userID and userID whom the setting is for) in your code and calling set/get settings with the incorrect userID (I don't know why they're different when this happened - for ex, it might happen when there are more than one user accounts on the device).

You need to modify the code to take the correct userID into logic and call the settings set/get for the appropriate userID (the calling userID and the userID for whom the settings is modified for should be the same).

Body:
Background

I have a rooted device, which is Galaxy S3 I9300 , with Samsung stock based ROM, based on Android 4.3.

I never had any problems running an app i'm working on with this device.

The problem

ever since yesterday (and I didn't change anything on the device), each time I open the app, it shows for a very short time, closes itself without any crash dialog yet it shows the next log:

01-30 09:27:18.325: E/DatabaseUtils(2366): Writing exception to parcel
01-30 09:27:18.325: E/DatabaseUtils(2366): java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL
01-30 09:27:18.325: E/DatabaseUtils(2366):  at com.android.server.am.ActivityManagerService.handleIncomingUser(ActivityManagerService.java:13140)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.app.ActivityManager.handleIncomingUser(ActivityManager.java:2038)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at com.android.providers.settings.SettingsProvider.callFromPackage(SettingsProvider.java:607)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.content.ContentProvider$Transport.call(ContentProvider.java:279)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:273)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at android.os.Binder.execTransact(Binder.java:388)
01-30 09:27:18.325: E/DatabaseUtils(2366):  at dalvik.system.NativeStart.run(Native Method)

it doesn't even get to the code of the class that extends Application ...

What I've found

It seems that this problem is very common (many have reported about it), but I can't find any solution and why it occurs, other than having a rooted device.

People also say the permission that is written here is actually a system permission, but I never even heard of it, let alone use it (not even sure what it is).

Problem is, the app I'm working on doesn't have anything related to root, plus it worked just a few days ago.

I've tried to re-install the ROM (Omega ROM v54) and also disable anything related to xposed framework. it didn't help.

The question

How do I fix this issue? How would I know other users won't have this problem?

Is it even related to rooted devices?

EDIT: i thought i've found an answer that fixes it, by choosing "revoke USB debugging..." on the developers section of the settings screen. it seemed to work at first, but later the problem returned and clicking it didn't do anything helpful anymore...

EDIT: I think it's just a bug on the app itself or the ROM, since I can't reproduce it anymore. It's quite weird since I'm quite sure I've tried to debug the app and put a breakpoint on the onCreate method of the acitivity (and maybe of the application class itself) and it didn't stop there.

Body:
01-30 09:27:18.325: E/DatabaseUtils(2366): java.lang.SecurityException: Permission Denial: get/set setting for user asks to run as user -2 but is calling from user 0; this requires android.permission.INTERACT_ACROSS_USERS_FULL

This error comes from where you get/set any user/system settings in your app. This particular error log is showing your settings get/set (from your app code) is calling from user 0 (USER_OWNER), but the setting you're changing is for user -2 (USER_CURRENT).

You can't change other users' settings without the permission android.permission.INTERACT_ACROSS_USERS_FULL.

You're probably not considering the case of having different userID's (between calling userID and userID whom the setting is for) in your code and calling set/get settings with the incorrect userID (I don't know why they're different when this happened - for ex, it might happen when there are more than one user accounts on the device).

You need to modify the code to take the correct userID into logic and call the settings set/get for the appropriate userID (the calling userID and the userID for whom the settings is modified for should be the same).


问:
How to retrieve the local TIMESTAMP from a Firebase database when initially was set using ServerValue.TIMESTAMP with Android?
I use ServerValue.TIMESTAMP to set the data and time of an item that was added to a list in a Firebase database with Android. I know that is initially set as a Map and when we retrieve it, we retrieve it  as a Long and in order to display the date and time, i use a method that looks like this:

```<code>public static String getTimeDate(long timeStamp){
    try{
        DateFormat dateFormat = getDateTimeInstance();
        Date netDate = (new Date(timeStamp));
        return dateFormat.format(netDate);
    }
    catch(Exception e){
        return "date";
    }
}
</code>```

Because i am located away from the server by 7 hours, when is display the date and time, is with 7 hours earlier. How can i display the correct date and time when using ServerValue.TIMESTAMP. Is there any possibility to this?

This how i display the time and date:

```<code>ValueEventListener listener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
    Long timeStampLong = (Long) map.get("timeStamp");
    String timeStamp = getTimeDate(timeStampLong);
    arrayList.add(timeStamp);

    arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list, arrayList);
    listView.setAdapter(arrayAdapter);
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(listener);
</code>```

Thanks in advance!

答:
This code snippet formats the time in the local time zone.  You could try using this as a basis for what you need.  I'm not sure why your code doesn't work.  Can you post the DateFormatyou are using?

```<code>    DatabaseReference timeRef = FirebaseDatabase.getInstance().getReference("time-test");

    timeRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                long time = dataSnapshot.getValue(Long.class);
                String s = DateFormat.getDateTimeInstance().format(new Date(time));
                Log.d(TAG, "onDataChange: " + s);
            } else {
                Log.d(TAG, "onDataChange: No data");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });

    timeRef.setValue(ServerValue.TIMESTAMP);
</code>```

Body:
I use ServerValue.TIMESTAMP to set the data and time of an item that was added to a list in a Firebase database with Android. I know that is initially set as a Map and when we retrieve it, we retrieve it  as a Long and in order to display the date and time, i use a method that looks like this:

public static String getTimeDate(long timeStamp){
    try{
        DateFormat dateFormat = getDateTimeInstance();
        Date netDate = (new Date(timeStamp));
        return dateFormat.format(netDate);
    }
    catch(Exception e){
        return "date";
    }
}

Because i am located away from the server by 7 hours, when is display the date and time, is with 7 hours earlier. How can i display the correct date and time when using ServerValue.TIMESTAMP. Is there any possibility to this?

This how i display the time and date:

ValueEventListener listener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
    Map<String, Object> map = (Map<String, Object>) dataSnapshot.getValue();
    Long timeStampLong = (Long) map.get("timeStamp");
    String timeStamp = getTimeDate(timeStampLong);
    arrayList.add(timeStamp);

    arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list, arrayList);
    listView.setAdapter(arrayAdapter);
}

@Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(listener);

Thanks in advance!

Body:
This code snippet formats the time in the local time zone.  You could try using this as a basis for what you need.  I'm not sure why your code doesn't work.  Can you post the DateFormatyou are using?

    DatabaseReference timeRef = FirebaseDatabase.getInstance().getReference("time-test");

    timeRef.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()) {
                long time = dataSnapshot.getValue(Long.class);
                String s = DateFormat.getDateTimeInstance().format(new Date(time));
                Log.d(TAG, "onDataChange: " + s);
            } else {
                Log.d(TAG, "onDataChange: No data");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
            throw databaseError.toException();
        }
    });

    timeRef.setValue(ServerValue.TIMESTAMP);


问:
Draw canvas shape
I need to draw the following canvas shape. I can't figure out how to make it. I tried to use lineTo() but I'm having a hard time positioning those line segments. Moreover it doesn't take a curve shape.

The <canvas> size should be equal to 600x450. Thanks in advance.

答:
Using the bezier curve as Cezar Augusto demonstrated can be combined with the canvas 2D API's dash settings. setLineDash(array) create a dashed line from the array argument. lineDashOffset is the offset to where to start the sequence of dashes and gaps

    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var w = canvas.width = innerWidth - 20;
    var h = canvas.height = innerHeight - 20;
    document.body.appendChild(canvas)
    ctx.setLineDash([14, 16]);
    ctx.lineDashOffset = 2;
    ctx.lineWidth = 4;
    ctx.setTransform(1,0,0,1,0,h/2);
    ctx.beginPath();
    ctx.moveTo(0,0);
    ctx.bezierCurveTo(w / 2, h, w / 2, -h, w, 0);
    ctx.stroke();    ```

setLineDash takes an array of numbers that represent the number of pixels for the dash then space and so on. If the array length is odd it is repeated to repeat at the start of a dash.

Title: Draw canvas shape

Body:
Using the bezier curve as Cezar Augusto demonstrated can be combined with the canvas 2D API's dash settings. setLineDash(array) create a dashed line from the array argument. lineDashOffset is the offset to where to start the sequence of dashes and gaps

    var canvas = document.createElement("canvas");
    var ctx = canvas.getContext("2d");
    var w = canvas.width = innerWidth - 20;
    var h = canvas.height = innerHeight - 20;
    document.body.appendChild(canvas)
    ctx.setLineDash([14, 16]);
    ctx.lineDashOffset = 2;
    ctx.lineWidth = 4;
    ctx.setTransform(1,0,0,1,0,h/2);
    ctx.beginPath();
    ctx.moveTo(0,0);
    ctx.bezierCurveTo(w / 2, h, w / 2, -h, w, 0);
    ctx.stroke();

setLineDash takes an array of numbers that represent the number of pixels for the dash then space and so on. If the array length is odd it is repeated to repeat at the start of a dash.


问:
MPMoviePlayerController: Removing ±1sec black screen, when changing contentURL?
I'm working on an iPad project where i have to play short video files one after another smoothly. For playing the videos i'm using MPMoviePlayerController. The problem i'm facing is that when i call

 [self.moviePlayer setContentURL:videoURL]

it does start the next video, but there is ±1 sec delay of black screen before it starts to play the next video (the videos are read from the disk, not streamed). I need to avoid this black screen as well as the delay.

So maybe some of you also experienced this problem and have some solutions? Thanks.

Btw, for now, as to at least avoid the black screen, I capture the last frame of the ending video, show it in a UIImageView, and remove it after 1 sec delay. But i'm hoping to find a more elegant fix.

答:
I think that the problem is that the controller will fade out and back in between the movies.
You can control the background view color and contents, but I'm not sure that you can eliminate the fade in/out.</p>


问:
Search text file and return values after equal sign
I am reading in a file and want to return certain values after the equal sign

The text file looks like this

```<code>slicenum=1
imageWidth=100
ID=1
</code>```

etc. and then repeats for each slice of the image

For now, I am focusing on ID, but eventually I want to have an array I guess of all the values I want to extract.

When I do this, it just prints the whole file. How do I print just the value after the equals sign of the ID?

```<code>string ID;
string line;
while (getline(inFile, line)) {
        if (line.find(ID) != string::npos)
            cout << line << std::endl;
}
</code>```

答:
I think this will help you: </p>

```<code>#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    ifstream in("Text.txt");
    string beforeEqual = "";
    string afterEqual = "";
    while (!in.eof())
    {
        getline(in, beforeEqual, '='); //grtting string upto =
        getline(in, afterEqual, '\n'); //getting string after =
        cout << afterEqual << endl; //printing string agter =
    }
    system("pause");
    return 0;
}
</code>```

Body:
I am reading in a file and want to return certain values after the equal sign

The text file looks like this

slicenum=1
imageWidth=100
ID=1

etc. and then repeats for each slice of the image

For now, I am focusing on ID, but eventually I want to have an array I guess of all the values I want to extract.

When I do this, it just prints the whole file. How do I print just the value after the equals sign of the ID?

string ID;
string line;
while (getline(inFile, line)) {
        if (line.find(ID) != string::npos)
            cout << line << std::endl;
}

Body:
I think this will help you:

#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main()
{
    ifstream in("Text.txt");
    string beforeEqual = "";
    string afterEqual = "";
    while (!in.eof())
    {
        getline(in, beforeEqual, '='); //grtting string upto =
        getline(in, afterEqual, '\n'); //getting string after =
        cout << afterEqual << endl; //printing string agter =
    }
    system("pause");
    return 0;
}


问:
AJAX dyamic content "event delegation" replacement for "each"
I'm implementing AJAX "load more" pagination on a website.

In order for .click() events to work for dynamically loaded content, I replaced all the .click() code with...

```<code>$(document).on('click', ".selector", function (event){
</code>```

That's all working fine for clickable stuff.

Now I'm trying to get some non-click based init code working in the same way as well.  This is the old version of my code that works for normal non-AJAX content:

```<code>var now = moment();
$('time').each(function(i, e) {
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});
</code>```

How would I get this code to also work on the dynamically loaded <time> tags?

I tried the following, but it's obviously wrong (using this code none of the <time> tags work at all):

```<code>var now = moment();
$(document).on('each', 'time', function (event){
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});
</code>```

答:
You need to add back your listener to the newly add time.

Jquery is setting it's listener once at the loading of the page that's why they are not accessible once you loaded them. I suggest using a method to add your listener and simple recall the method at the end of your success callback.

Body:
I'm implementing AJAX "load more" pagination on a website.

In order for .click() events to work for dynamically loaded content, I replaced all the .click() code with...

$(document).on('click', ".selector", function (event){

That's all working fine for clickable stuff.

Now I'm trying to get some non-click based init code working in the same way as well.  This is the old version of my code that works for normal non-AJAX content:

var now = moment();
$('time').each(function(i, e) {
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});

How would I get this code to also work on the dynamically loaded <time> tags?

I tried the following, but it's obviously wrong (using this code none of the <time> tags work at all):

var now = moment();
$(document).on('each', 'time', function (event){
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});


问:
Getting variable from javascript to PHP on the same page
I am completely new to JS and PHP programming. Please help me with the following code..

```<code><?php

echo'
<button id="checkin" onclick="myFunction()">CheckIn</button>
<script>
function myFunction() {
document.getElementById("checkin").disabled = true;
var CheckinoutStatus=true;
        $(function(){
        $.ajax({
              type: "POST",
              url: "functions.php",
              data: "&CheckinoutStatus="+CheckinoutStatus,
              success: function(data)
              {
                 alert("Checked In");
              }
            });
        });
   }
 </script>
 ';
 if(isset($_POST['CheckinoutStatus']))
 {

     $CheckinoutStatus=isset($_POST['CheckinoutStatus']);
     $update = $db->query("UPDATE Details SET     CheckinoutStatus='$CheckinoutStatus' where date='$date' ");

}
?>
</code>```

Clicking the checkin button should disable the button, send a CheckinoutStatus variable value of true to the database using an AJAX call, and then show a "Checked In" alert after the database has been updated.

I am defining and setting the variable CheckinoutStatus to true in js, and
using AJAX, am trying to get that value in PHP and update that data in an existing table.  I have not been able to pass the value from js to php.

答:
Unless your table only has one record, you will also need to pass a key of some sort so you can update the correct record. Fir the line below, I'll presume you have a hidden field with an id of "key" in your form.

Change the line:

```<code>data: "&CheckinoutStatus="+CheckinoutStatus,
</code>```

To:

```<code>data: "&CheckinoutStatus=1&key="+$('#key').val(),
</code>```

Then create a PHP file named functions.php which checks $_GET['CheckinoutStatus'] for the value and save it to your table using update with a where clause similar to:

```<code>UPDATE `mystatustable`
SET `checkinoutstatus` = $_GET['key']
WHERE `id` = $_GET['key'];
</code>```

Body:
I am completely new to JS and PHP programming. Please help me with the following code..

<?php

echo'
<button id="checkin" onclick="myFunction()">CheckIn</button>

 ';
 if(isset($_POST['CheckinoutStatus']))
 {

     $CheckinoutStatus=isset($_POST['CheckinoutStatus']);
     $update = $db->query("UPDATE Details SET     CheckinoutStatus='$CheckinoutStatus' where date='$date' ");

}
?>

Clicking the checkin button should disable the button, send a CheckinoutStatus variable value of true to the database using an AJAX call, and then show a "Checked In" alert after the database has been updated.

I am defining and setting the variable CheckinoutStatus to true in js, and
using AJAX, am trying to get that value in PHP and update that data in an existing table.  I have not been able to pass the value from js to php.

Body:
Unless your table only has one record, you will also need to pass a key of some sort so you can update the correct record. Fir the line below, I'll presume you have a hidden field with an id of "key" in your form.

Change the line:

data: "&CheckinoutStatus="+CheckinoutStatus,

To:

data: "&CheckinoutStatus=1&key="+$('#key').val(),

Then create a PHP file named functions.php which checks $_GET['CheckinoutStatus'] for the value and save it to your table using update with a where clause similar to:

UPDATE `mystatustable`
SET `checkinoutstatus` = $_GET['key']
WHERE `id` = $_GET['key'];


问:
Reprinting  tags with all attributes
I'm reworking a WordPress plugin that I've made which specifies image dimensions that are missing width and/or height attributes.

As you can see in my current version on GitHub, I manually list all of the attributes for the  tag (L38). However, if a user were to add custom attribute, it would get omitted since it's not listed in my $attributes variable:

```<code># Before
<img src="http://example.com/img.png" class="img" data-sample="test">
# After
<img src="http://example.com/img.png" class="img" width="100" height="30">
</code>```

Creating a simple test file, I was able to update the regex to store all attributes that are found in the  tags. Yes, I'm aware of the recommendation to use DOMDocument, but it has caused more issues with WordPress in the past.

```<code>preg_match_all( '/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images );
</code>```

In order to not fill up this post with too much code, I have the current working test file on my GitHub Gist here.

Using var_dump( $images );, this gives me the following output from my sample images (I added ... at the end of each array to save space):

```<code>    0 =>
      array (size=19)
        0 => string '<img src="https://placehold.it/250x100/99cc00/000.jpg?text=JPG"' (length=63)
        1 => string ' alt="JPG"' (length=10)
        2 => string '<img src="https://placehold.it/250x100.gif?text=GIF"' (length=52)
        ...
    1 =>
      array (size=19)
        0 => string 'src' (length=3)
        1 => string 'alt' (length=3)
        2 => string 'src' (length=3)
        ...
    2 =>
      array (size=19)
        0 => string 'https://placehold.it/250x100/99cc00/000.jpg?text=JPG' (length=52)
        1 => string 'JPG' (length=3)
        2 => string 'https://placehold.it/250x100.gif?text=GIF' (length=41)
        ...
</code>```

My goal is to recreate the image tags with all of their attributes and values after the dimensions are calculated. From my tests, I've tried the following, but it hasn't given me the results I'm expecting:

```<code>foreach ( $images[1] as $attributes[1] => $value ) {
    echo( '< img ' . $value . '="' . 'value' . '" ><br>' );
}
</code>```

答:
Your Code:

```<code>$content = <<<EOT
<p>List of sample images.</p>
<img src="https://placehold.it/250x100/99cc00/000.jpg?text=JPG" alt="JPG" /><br>
<img src="https://placehold.it/250x100.gif?text=GIF" alt="GIF" /><br>
<img src="https://placehold.it/250x100/ff6600/000.png?text=PNG" alt="PNG" /><br>
<img class="no-ext" src="https://placehold.it/350x150?text=No Extension" alt="No Ext" /><br>
<img src="https://placehold.it/250x100.png" custom-attr="custom1" another-attr="custom2" /><br>
<img class="svg" src="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" alt="SVG" /><br>
<img class="webp" src="https://gstatic.com/webp/gallery/1.webp" width="100" alt="webP" /><br>
EOT;
# Find all content with <img> tags
preg_match_all( '/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images );
foreach ( $images[1] as $attributes[1] => $value ) {
    echo( '< img ' . $value . '="' . 'value' . '" ><br>' );
}
</code>```

Solution:

```<code>//echo "```"; print_r($images);
$temp = array();
foreach($images[0] as $key=>$img){
    $pos = strpos($img,'$v){
    $str[] = implode(' ', $v) . ' />';
}

$finalStr = implode('
', $str);

echo $finalStr;
```

Click here to check output

Title: Reprinting <img> tags with all attributes

Body:
I'm reworking a WordPress plugin that I've made which specifies image dimensions that are missing width and/or height attributes.

As you can see in my current version on GitHub, I manually list all of the attributes for the  tag (L38). However, if a user were to add custom attribute, it would get omitted since it's not listed in my $attributes variable:

# Before

# After

Creating a simple test file, I was able to update the regex to store all attributes that are found in the  tags. Yes, I'm aware of the recommendation to use DOMDocument, but it has caused more issues with WordPress in the past.

preg_match_all( '/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images );

In order to not fill up this post with too much code, I have the current working test file on my GitHub Gist here.

Using var_dump( $images );, this gives me the following output from my sample images (I added ... at the end of each array to save space):

    0 =>
      array (size=19)
        0 => string ' string ' alt="JPG"' (length=10)
        2 => string '
      array (size=19)
        0 => string 'src' (length=3)
        1 => string 'alt' (length=3)
        2 => string 'src' (length=3)
        ...
    2 =>
      array (size=19)
        0 => string 'https://placehold.it/250x100/99cc00/000.jpg?text=JPG' (length=52)
        1 => string 'JPG' (length=3)
        2 => string 'https://placehold.it/250x100.gif?text=GIF' (length=41)
        ...

My goal is to recreate the image tags with all of their attributes and values after the dimensions are calculated. From my tests, I've tried the following, but it hasn't given me the results I'm expecting:

foreach ( $images[1] as $attributes[1] => $value ) {
    echo( '
' );
}

Body:
Your Code:

$content = <<<EOT
<p>List of sample images.</p>
<img src="https://placehold.it/250x100/99cc00/000.jpg?text=JPG" alt="JPG" /><br>
<img src="https://placehold.it/250x100.gif?text=GIF" alt="GIF" /><br>
<img src="https://placehold.it/250x100/ff6600/000.png?text=PNG" alt="PNG" /><br>
<img class="no-ext" src="https://placehold.it/350x150?text=No Extension" alt="No Ext" /><br>
<img src="https://placehold.it/250x100.png" custom-attr="custom1" another-attr="custom2" /><br>
<img class="svg" src="https://upload.wikimedia.org/wikipedia/commons/0/02/SVG_logo.svg" alt="SVG" /><br>
<img class="webp" src="https://gstatic.com/webp/gallery/1.webp" width="100" alt="webP" /><br>
EOT;
# Find all content with <img> tags
preg_match_all( '/(?:<img|(?<!^)\G)\h*([-\w]+)="([^"]+)"(?=.*?\/>)/', $content, $images );
foreach ( $images[1] as $attributes[1] => $value ) {
    echo( '< img ' . $value . '="' . 'value' . '" ><br>' );
}

Solution:

//echo "<pre>"; print_r($images);
$temp = array();
foreach($images[0] as $key=>$img){
    $pos = strpos($img,'<img');
    if($pos === false){
        $temp[$key_2][] = $img;
    }else{
        $temp[$key][] = $img;
        $key_2 = $key;
    }
}
foreach($temp as $k=>$v){
    $str[] = implode(' ', $v) . ' />';
}

$finalStr = implode('<br />', $str);

echo $finalStr;

Click here to check output


问:
Class vs Struct for data only?
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

```<code>class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};
</code>```

Versus:

```<code>struct Foo {
   struct Pos { int x, y, z } Pos;
};
</code>```

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

答: struct and class mean exactly the same thing in C++ with the exception that the default access for struct members and bases is public whereas it is private for classes. I tend to chose struct for classes that only have public members and classes for everything else, but it's only a style issue.

OwnerDisplayName: Daniel

Title: Class vs Struct for data only?

Body:
Is there any advantage over using a class over a struct in cases such as these?
(note: it will only hold variables, there will never be functions)

class Foo {
private:
   struct Pos { int x, y, z };
public:
   Pos Position;
};

Versus:

struct Foo {
   struct Pos { int x, y, z } Pos;
};

Similar questions:

When should you use a class vs a struct in C++?

What are the differences between struct and class in C++?

When should I use a struct instead of a class?

LastEditorDisplayName: dmckee

OwnerDisplayName: Charles Bailey

LastEditorDisplayName: Roger Pate


问:
What is the easiest way to interact with the APNS Server for sending Push Notifications to iOS devices?
I am running a PHP/MySQL Application on my webserver and I need to send Push Notifications to iOS Devices.

What is the easiest way implementing this? Are they any PHP libraries I can use? Or are there even any service providers in between who will do it for me? (interact with the APNS server)..

What's your experience? How big is the effort to implement Push with PHP?

答:
There's a previous question about hosted APNS services; however, some of those services now appear to be defunct.

Two current services seem to be Urban Airship and iLime.  Both offer free service up to a certain number of messages.  I haven't (yet) used either so I cannot comment on how well they work, but I do know Urban Airship has been around since the early days of APNS which is a bit reassuring..


问:
Cakephp 3 Callback method not reached
I have a problem with the afterDelete callback method. I can't use them.

Inside one of my "Storages" plugin controllers I want to delete a record and after that I want to do some other thinks, but the callback method is not reached. I have checked this with adding a log message inside the afterDelete() callback method.

This is the controller where I removed a record:

```<code>namespace Storages\Controller;

class StoragecontainerBlocksController extends AppController {

   public function initialize() {
       parent::initialize();
       $this->loadComponent('RequestHandler');
   }

   public function ajaxDeleteBlockElement() {
       $this->autoRender = false;

       // load model
       $this->loadModel("StoragecontainerBlockElements");

       // get element id
       $elementId = $this->request->data('id');

       $this->request->allowMethod(['post', 'delete']);

       // delete element
       $storagecontainerBlockElement = $this->StoragecontainerBlockElements->get($elementId);
       $this->StoragecontainerBlockElements->delete($storagecontainerBlockElement);
   }
}
</code>```

This is the (model) table where the afterDelete callback is defined:

```<code>  use Cake\Log\Log;
  class StoragecontainerBlockElementsTable extends Table {

   public function afterDelete(Event $event) {
       Log::debug('Got here');
   }
  }
</code>```

Update:

When I debugged Log::debug($this->StoragecontainerBlockElements); inside the ajaxDeleteBlockElement function I got the following array inside debug.log file:

```<code>2017-03-31 07:03:48 Debug: Cake\ORM\Table Object
(
    [registryAlias] => StoragecontainerBlockElements
    [table] => storagecontainer_block_elements
    [alias] => StoragecontainerBlockElements
    [entityClass] => \Cake\ORM\Entity
    [associations] => Array
        (
        )

    [behaviors] => Array
        (
        )

    [defaultConnection] => default
    [connectionName] => default
</code>```

Update:

```<code>namespace Storages\Model\Table;

use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Log\Log;

class StoragecontainerBlockElementsTable extends Table {

    public function initialize(array $config) {
       parent::initialize($config);
    }

    public function afterDelete(Event $event) {
       Log::debug('Got here');
    }
}
</code>```

答:
As can be seen in the debugging results, $this->StoragecontainerBlockElements is not what you thought it is, it is a so called "auto-table" or "generic table", that is, an instance of \Cake\ORM\Table instead of a concrete subclass thereof.

Your StoragecontainerBlockElementsTable class/file cannot be found/loaded for some reason, hence the fallback to \Cake\ORM\Table. Might be caused by

a typo in the filename, classname, or the namespace

or the namespace is missing completely (it's not in your question)

or the class lives in a plugin, and you didn't used plugin notation for loading it

or the file permissions do not allow reading file

or the file is missing (not deployed)

...

See also

Cookbook > Configuration > Disabling Generic Tables

Title: Cakephp 3 Callback method not reached

Body:
I have a problem with the afterDelete callback method. I can't use them.

Inside one of my "Storages" plugin controllers I want to delete a record and after that I want to do some other thinks, but the callback method is not reached. I have checked this with adding a log message inside the afterDelete() callback method.

This is the controller where I removed a record:

namespace Storages\Controller;

class StoragecontainerBlocksController extends AppController {

   public function initialize() {
       parent::initialize();
       $this->loadComponent('RequestHandler');
   }

   public function ajaxDeleteBlockElement() {
       $this->autoRender = false;

       // load model
       $this->loadModel("StoragecontainerBlockElements");

       // get element id
       $elementId = $this->request->data('id');

       $this->request->allowMethod(['post', 'delete']);

       // delete element
       $storagecontainerBlockElement = $this->StoragecontainerBlockElements->get($elementId);
       $this->StoragecontainerBlockElements->delete($storagecontainerBlockElement);
   }
}

This is the (model) table where the afterDelete callback is defined:

  use Cake\Log\Log;
  class StoragecontainerBlockElementsTable extends Table {

   public function afterDelete(Event $event) {
       Log::debug('Got here');
   }
  }

Update:

When I debugged Log::debug($this->StoragecontainerBlockElements); inside the ajaxDeleteBlockElement function I got the following array inside debug.log file:

2017-03-31 07:03:48 Debug: Cake\ORM\Table Object
(
    [registryAlias] => StoragecontainerBlockElements
    [table] => storagecontainer_block_elements
    [alias] => StoragecontainerBlockElements
    [entityClass] => \Cake\ORM\Entity
    [associations] => Array
        (
        )

    [behaviors] => Array
        (
        )

    [defaultConnection] => default
    [connectionName] => default

Update:

namespace Storages\Model\Table;

use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Log\Log;

class StoragecontainerBlockElementsTable extends Table {

    public function initialize(array $config) {
       parent::initialize($config);
    }

    public function afterDelete(Event $event) {
       Log::debug('Got here');
    }
}


问:
Getting Error Message Error: spawn EACCES using IONIC Framework
I am trying to learn ionic cross platform tool. i have setup thing required for example application ionic serve  is working fine but when i try to run sudo ionic build android  or sudo ionic run/emulate android it returns with error message.

```<code>Error: spawn EACCES
    at exports._errnoException (util.js:746:11)
    at ChildProcess.spawn (child_process.js:1162:11)
    at Object.exports.spawn (child_process.js:995:9)
    at Object.exports.spawn (/usr/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:103:31)
    at runScriptViaChildProcessSpawn (/usr/lib/node_modules/cordova/node_modules/cordova-lib/src/hooks/HooksRunner.js:189:23)
    at runScript (/usr/lib/node_modules/cordova/node_modules/cordova-lib/src/hooks/HooksRunner.js:132:16)
    at /usr/lib/node_modules/cordova/node_modules/cordova-lib/src/hooks/HooksRunner.js:115:20
    at _fulfilled (/usr/lib/node_modules/cordova/node_modules/q/q.js:787:54)
    at self.promiseDispatch.done (/usr/lib/node_modules/cordova/node_modules/q/q.js:816:30)
    at Promise.promise.promiseDispatch (/usr/lib/node_modules/cordova/node_modules/q/q.js:749:13)
</code>```

i am unable to understand what does its mean. i have google this thing but after appling all of those solutions i got same error. i ll highly thankful if any one can tell me what is going wrong with me.

答:
While the given solution did take me a step further, adding execute permissions to android sdk was also needed.

```<code>chmod +x -R /home/username/Android/Sdk
</code>```

see Error: spawn EACCES when trying to build Ionic app in Ubuntu 15.10

Body:
I am trying to learn ionic cross platform tool. i have setup thing required for example application ionic serve  is working fine but when i try to run sudo ionic build android  or sudo ionic run/emulate android it returns with error message.

Error: spawn EACCES
    at exports._errnoException (util.js:746:11)
    at ChildProcess.spawn (child_process.js:1162:11)
    at Object.exports.spawn (child_process.js:995:9)
    at Object.exports.spawn (/usr/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:103:31)
    at runScriptViaChildProcessSpawn (/usr/lib/node_modules/cordova/node_modules/cordova-lib/src/hooks/HooksRunner.js:189:23)
    at runScript (/usr/lib/node_modules/cordova/node_modules/cordova-lib/src/hooks/HooksRunner.js:132:16)
    at /usr/lib/node_modules/cordova/node_modules/cordova-lib/src/hooks/HooksRunner.js:115:20
    at _fulfilled (/usr/lib/node_modules/cordova/node_modules/q/q.js:787:54)
    at self.promiseDispatch.done (/usr/lib/node_modules/cordova/node_modules/q/q.js:816:30)
    at Promise.promise.promiseDispatch (/usr/lib/node_modules/cordova/node_modules/q/q.js:749:13)

i am unable to understand what does its mean. i have google this thing but after appling all of those solutions i got same error. i ll highly thankful if any one can tell me what is going wrong with me.

Body:
While the given solution did take me a step further, adding execute permissions to android sdk was also needed.

chmod +x -R /home/username/Android/Sdk

see Error: spawn EACCES when trying to build Ionic app in Ubuntu 15.10


问:
Assist with simple count out of a list
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

```<code>public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}
</code>```

答:
Try this:

```<code>int breakCount = 0;
foreach(var agent in newAgentList)
{
    if (!string.IsNullOrEmpty(agent.AuxReasons) && agent.AuxReasons.StartsWith("Break"))
      breakCount++;
}
</code>```

You should also create new object in each iteration:

```<code>foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}
</code>```

Title: Assist with simple count out of a list

Body:
I'm trying to count the number of people marked as Break in a column in a list.

currently when I run my foreach loop (the one at the bottom) to count the number of breaks listed it throws the error message cannot convert type char to string. I understand that my class of NewAgent does not contain all string values but I'm only trying to reference one string.  I need a way to count the number of times break appears in my list. Break would appear under newAgent.auxreason

public List newAgentList;
List<NewAgent> newAgentList = new List<NewAgent>();

NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

foreach (var item in e.CmsData.Agents)
{

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}

int breakCount = 0;
foreach(string s in newAgents.AuxReasons)
{
    if (s != null && s.StartsWith("Break")) breakCount++;
}

Body:
Try this:

int breakCount = 0;
foreach(var agent in newAgentList)
{
    if (!string.IsNullOrEmpty(agent.AuxReasons) && agent.AuxReasons.StartsWith("Break"))
      breakCount++;
}

You should also create new object in each iteration:

foreach (var item in e.CmsData.Agents)
{
    NewAgent newAgents = new ScoreBoardClientTest.NewAgent();

    newAgents.AgentName = item.AgName;

    newAgents.AgentExtension = item.Extension;

    newAgents.AgentDateTimeChange = ConvertedDateTimeUpdated;

    newAgents.AuxReasons = item.AuxReasonDescription;

    newAgents.LoginIdentifier = item.LoginId;

    newAgents.AgentState = item.WorkModeDirectionDescription;

    var timeSpanSince = DateTime.Now - item.DateTimeUpdated;
    newAgents.AgentDateTimeStateChange = timeSpanSince;

    newAgentList.Add(newAgents);
}


问:
Is there an easy way to increase the value of a Map object value?
I currently have this code, where speciesMap is a map in which the keys have maps as values.

```<code>var speciesMap = new Map();
...
if(!speciesMap.get(species)) {
    let obj = new Map();
    obj.set('count', 0);
    obj.set('vol', 0);
    speciesMap.set(species, obj);
}
</code>```

I want to increase the count of a given specie by 1, but the only way I found to do it was like this.

```<code>speciesMap.get(species).set('count', speciesMap.get(species).get('count') + 1);
</code>```

Is there a cleaner and simpler way to increase the value instead of going down the whole map again to retrieve its value? Same goes for volume, I need to go down the object and add + vol to it.

Wanted something like

```<code>speciesMap.get(species).set('count', this+1);
</code>```

which obviously doesn't work.

答:
You can use a helper function:

```<code>function update(map, key, callback) {
    map.set(key, callback(map.get(key)));
}
</code>```

Then your long expression becomes

```<code>update(speciesMap.get(species), 'count', v => v+1);
</code>```

Body:
I currently have this code, where speciesMap is a map in which the keys have maps as values.

var speciesMap = new Map();
...
if(!speciesMap.get(species)) {
    let obj = new Map();
    obj.set('count', 0);
    obj.set('vol', 0);
    speciesMap.set(species, obj);
}

I want to increase the count of a given specie by 1, but the only way I found to do it was like this.

speciesMap.get(species).set('count', speciesMap.get(species).get('count') + 1);

Is there a cleaner and simpler way to increase the value instead of going down the whole map again to retrieve its value? Same goes for volume, I need to go down the object and add + vol to it.

Wanted something like

speciesMap.get(species).set('count', this+1);

which obviously doesn't work.

Body:
You can use a helper function:

function update(map, key, callback) {
    map.set(key, callback(map.get(key)));
}

Then your long expression becomes

update(speciesMap.get(species), 'count', v => v+1);


问:
How to create Espresso androidTest.apk out side of Android Studio environment?
I have Jenkins job that gets the source code out of GitHub and creates release APK.
I would like to include in this job the creation of androidTest.apk, so I would upload it together with the release APK to test Environment like Google Test Lab and run Espresso tests.
I have managed to run gradlew assembleDebugAndroidTest, but first it is Debug and not release and second it didn't have my latest test, only old test.</p>

答:
How to create Espresso androidTest.apk out side of Android Studio environment?

Navigate to your project directory and execute this in terminal:

```<code>./gradlew assembleAndroidTest
</code>```

This will create instrumented debug apk.

To run instrumented tests perform:

```<code>./gradlew connectedDebugAndroidTest
</code>```

or

```<code>./gradlew connectedCheck
</code>```

Body:
How to create Espresso androidTest.apk out side of Android Studio environment?

Navigate to your project directory and execute this in terminal:

./gradlew assembleAndroidTest

This will create instrumented debug apk.

To run instrumented tests perform:

./gradlew connectedDebugAndroidTest

or

./gradlew connectedCheck


问:
handling subprocess.check_output return with quotes
I have a subprocess, and it contains a way to validate a credential and returns a response like this:

```<code>{
"isvalid" : false
}
</code>```

Im using this to get the response and to check if the credential passed the test:

```<code>def slraddresstest():
        while True:
                solarcoin_address = raw_input ("What is your SolarCoin Address: ")
                output = subprocess.check_output(['solarcoind', 'validateaddress', solarcoin_address], shell=False)
                if output != "{\"isvalid\" : false}"
                        return solarcoin_address
                else:
                        print ("Error: SolarCoin address invlaid, check and try again")
</code>```

But on running the code I get:

```<code>if output != "{\"isvalid\" : false}"
                                   ^
SyntaxError: invalid syntax
</code>```

I also tried if output != '{"isvalid" : false}' and if output != """{"isvalid" : false}""" but am getting similar syntax errors.

答:
Yo forgot the :</p>

```<code>if output != "{\"isvalid\" : false}":
</code>```

Body:
I have a subprocess, and it contains a way to validate a credential and returns a response like this:

{
"isvalid" : false
}

Im using this to get the response and to check if the credential passed the test:

def slraddresstest():
        while True:
                solarcoin_address = raw_input ("What is your SolarCoin Address: ")
                output = subprocess.check_output(['solarcoind', 'validateaddress', solarcoin_address], shell=False)
                if output != "{\"isvalid\" : false}"
                        return solarcoin_address
                else:
                        print ("Error: SolarCoin address invlaid, check and try again")

But on running the code I get:

if output != "{\"isvalid\" : false}"
                                   ^
SyntaxError: invalid syntax

I also tried if output != '{"isvalid" : false}' and if output != """{"isvalid" : false}""" but am getting similar syntax errors.

Body:
Yo forgot the :

if output != "{\"isvalid\" : false}":


问:
nodeJS (express,connect) - Dynamically add middleware in current flow
I am currently working on formBuilder (client javascript <=> JSON <=> node), so i need effective way to handle JSON data on server. All forms are bind on one route, catched by middleware, so i need something like this:

Code is simplified (no regexs, req validators etc ..)

```<code>var middleware = require('../middleware'); // simple dir to object export

exports = module.exports =function(req,res,next) {
  if(req.xhr && req.is('application/json')) {
    var i, items = req.body.events.length;
    for(i = 0; i < items; i++) {
      var event = req.body.events[i];
      if(middleware.forms[event] {
        // -----------------
        and here add that middleware into current flow ..
        // -----------------
      }
    }
  } else {
    return next();
}
</code>```

Easiest way is to prepare list of middleware, which will be used and call them in final route witch async .. but that i donw regard this as good way ..

So, i there any way to add requested middlwares to current flow, but before filan route ?

答:
I wrote something very similar:</p>

```<code>let isActive1 = false;
let isActive2 = false;
let func1MD = (req, res, next) { /* ... */ }
let func2MD = (req, res, next) { /* ... */ }

let middleware = (function () {

  // middleware #1
  function func1(req, res, next) {
    if (!isActive1) { return next(); }

    return func1MD.call(null, req, res, next);
  }

  // middleware #2
  function func2(req, res, next) {
    if (!isActive2) { return next(); }

    return func2MD.call(null, req, res, next);
  }

  // Returning an array of all middlewares to be called sequentially
  return [
    func1,
    func2
  ]
})();

app.use(middleware);
</code>```

Body:
I am currently working on formBuilder (client javascript <=> JSON <=> node), so i need effective way to handle JSON data on server. All forms are bind on one route, catched by middleware, so i need something like this:

Code is simplified (no regexs, req validators etc ..)

var middleware = require('../middleware'); // simple dir to object export

exports = module.exports =function(req,res,next) {
  if(req.xhr && req.is('application/json')) {
    var i, items = req.body.events.length;
    for(i = 0; i < items; i++) {
      var event = req.body.events[i];
      if(middleware.forms[event] {
        // -----------------
        and here add that middleware into current flow ..
        // -----------------
      }
    }
  } else {
    return next();
}

Easiest way is to prepare list of middleware, which will be used and call them in final route witch async .. but that i donw regard this as good way ..

So, i there any way to add requested middlwares to current flow, but before filan route ?

Body:
I wrote something very similar:

let isActive1 = false;
let isActive2 = false;
let func1MD = (req, res, next) { /* ... */ }
let func2MD = (req, res, next) { /* ... */ }

let middleware = (function () {

  // middleware #1
  function func1(req, res, next) {
    if (!isActive1) { return next(); }

    return func1MD.call(null, req, res, next);
  }

  // middleware #2
  function func2(req, res, next) {
    if (!isActive2) { return next(); }

    return func2MD.call(null, req, res, next);
  }

  // Returning an array of all middlewares to be called sequentially
  return [
    func1,
    func2
  ]
})();

app.use(middleware);


问:
Angular 2 ngIf clears value
I want to hide a tablerow if the string value of the url property of my project is empty.
So this is my code:

```<code><div class="tableRow" *ngIf="(project | async)?.Url">
     <div class="tableCell"><a target="_blank" href="{{ (project | async)?.Url}}">{{ this.localizationService.localized['projectUrl'] }}</a></div>
</div>
</code>```

The problem is that if i use the code above the row is beeing displayed but the url value in the href is empty.

As soon as i delete the ngIf the row is shown as well but this time the url is not empty.

```<code><div class="tableRow">
         <div class="tableCell"><a target="_blank" href="{{ (project | async)?.Url}}">{{ this.localizationService.localized['projectUrl'] }}</a></div>
    </div>
</code>```

what am i doing wrong?

EDIT:
The project is requested from our backend in the projectservice. I have an observable in the project component.

I'm terrible at explaining, im sorry...

ProjectComponent

```<code>private project: Observable<ProjectDetail>;
constructor() {
            super();

            // init projects stream
            this.project = projectsService.projectDetail;
    }
</code>```

ProjectService

```<code>public getProjectDetail(id: number) {
        this.http.get(this.projectDetailUrl + id)
            .map(this.utilService.extractData)
            .map(this.mapProjectDetails)
            .subscribe(data => {
                this.dataStore.projectDetail = data;
                this.projectDetail$.next(this.dataStore.projectDetail);
            },
            err => {
                this.httpErrorHandler.handleError(err);
            });
    }
</code>```

答:
Try something like:

```<code><div class="tableRow" *ngIf="(project | async)?.Url.length > 0">
   <div class="tableCell"><a target="_blank" href="{{ (project | async)?.Url}}">{{ this.localizationService.localized['projectUrl'] }}</a></div>
</div>
</code>```

*ngIf may display for empty strings, but not nulls, so if your variable is returning an empty string, your row might display. I would base it off the string length.

Title: Angular 2 ngIf clears value

Body:
I want to hide a tablerow if the string value of the url property of my project is empty.
So this is my code:

{{ this.localizationService.localized['projectUrl'] }}

The problem is that if i use the code above the row is beeing displayed but the url value in the href is empty.

As soon as i delete the ngIf the row is shown as well but this time the url is not empty.

{{ this.localizationService.localized['projectUrl'] }}

what am i doing wrong?

EDIT:
The project is requested from our backend in the projectservice. I have an observable in the project component.

I'm terrible at explaining, im sorry...

ProjectComponent

private project: Observable<ProjectDetail>;
constructor() {
            super();

            // init projects stream
            this.project = projectsService.projectDetail;
    }

ProjectService

public getProjectDetail(id: number) {
        this.http.get(this.projectDetailUrl + id)
            .map(this.utilService.extractData)
            .map(this.mapProjectDetails)
            .subscribe(data => {
                this.dataStore.projectDetail = data;
                this.projectDetail$.next(this.dataStore.projectDetail);
            },
            err => {
                this.httpErrorHandler.handleError(err);
            });
    }

Body:
Try something like:

<div class="tableRow" *ngIf="(project | async)?.Url.length > 0">
   <div class="tableCell"><a target="_blank" href="{{ (project | async)?.Url}}">{{ this.localizationService.localized['projectUrl'] }}</a></div>
</div>

*ngIf may display for empty strings, but not nulls, so if your variable is returning an empty string, your row might display. I would base it off the string length.


问:
Colour Scatterplot according to Y value ggplot
My scatterplot
I'm not the best with R, but I'm trying to introduce colour into this plot.

```<code>SecondPlot <- ggplot(sur11, aes(x=standec, y=compnoanti)) +
geom_point(col ="black", size = 0.5) +
geom_text(label=sur11$concatena, hjust = 0, nudge_x = 0.3, size = 2.5)
SecondPlot
SecondPlot + geom_abline(intercept = 50, slope = 0, size = 0.2)
</code>```

How can I:

1) Colour all Y values beyond 75 points red?

2) Introduce scaled colouring so that I use an existing R brewer scale, e.g "Blues", to colour the Y value depending on their value?

I have tried assigning each y value to a point of 1 to 10 and then used the argument size = factor(Z) but this didn't work.

Thank you.

答:
Try this:

1) Colour all Y values beyond 75 points red

```<code>SecondPlot <- ggplot(sur11, aes(x=standec, y=compnoanti)) +
  geom_point(col = ifelse(sur11$compnoanti > 75, "red", "black"), size = 0.5) +
  geom_text(label=sur11$concatena, hjust = 0, nudge_x = 0.3, size = 2.5)
SecondPlot
</code>```

2) Introduce scaled colouring so that I use an existing R brewer scale, e.g "Blues", to colour the Y value depending on their value?

```<code>#Interpolate Brewer palette
library(RColorBrewer)
colourCount = length(unique(sur11$compnoanti))
getPalette = colorRampPalette(brewer.pal(9, "Blues"))

SecondPlot <- ggplot(mtcars, aes(x=standec, y=compnoanti)) +
  geom_point(aes(col = compnoanti), size = 0.5) +
  geom_text(label=sur11$concatena, hjust = 0, nudge_x = 0.3, size = 2.5) +
  scale_colour_gradientn(colours=getPalette(colourCount))
SecondPlot
</code>```

Since you didn't provide a reproducible example, I tested it using a generic dataset. This is the generic version:

```<code># Color points above a certain value red
SecondPlot <- ggplot(mtcars, aes(x=mpg, y=disp)) +
  geom_point(col = ifelse(mtcars$disp > 120, "red", "black"), size = 0.5) +
  geom_text(label=rownames(mtcars), hjust = 0, nudge_x = 0.3, size = 2.5)
SecondPlot

#Interpolate Brewer palette
library(RColorBrewer)
colourCount = length(unique(mtcars$disp))
getPalette = colorRampPalette(brewer.pal(9, "Blues"))

SecondPlot <- ggplot(mtcars, aes(x=mpg, y=disp)) +
  geom_point(aes(col = disp), size = 0.5) +
  geom_text(label=rownames(mtcars), hjust = 0, nudge_x = 0.3, size = 2.5) +
  scale_colour_gradientn(colours=getPalette(colourCount))
SecondPlot
</code>```

Body:
My scatterplot
I'm not the best with R, but I'm trying to introduce colour into this plot.

SecondPlot <- ggplot(sur11, aes(x=standec, y=compnoanti)) +
geom_point(col ="black", size = 0.5) +
geom_text(label=sur11$concatena, hjust = 0, nudge_x = 0.3, size = 2.5)
SecondPlot
SecondPlot + geom_abline(intercept = 50, slope = 0, size = 0.2)

How can I:

1) Colour all Y values beyond 75 points red?

2) Introduce scaled colouring so that I use an existing R brewer scale, e.g "Blues", to colour the Y value depending on their value?

I have tried assigning each y value to a point of 1 to 10 and then used the argument size = factor(Z) but this didn't work.

Thank you.

Body:
Try this:

1) Colour all Y values beyond 75 points red

SecondPlot <- ggplot(sur11, aes(x=standec, y=compnoanti)) +
  geom_point(col = ifelse(sur11$compnoanti > 75, "red", "black"), size = 0.5) +
  geom_text(label=sur11$concatena, hjust = 0, nudge_x = 0.3, size = 2.5)
SecondPlot

2) Introduce scaled colouring so that I use an existing R brewer scale, e.g "Blues", to colour the Y value depending on their value?

#Interpolate Brewer palette
library(RColorBrewer)
colourCount = length(unique(sur11$compnoanti))
getPalette = colorRampPalette(brewer.pal(9, "Blues"))

SecondPlot <- ggplot(mtcars, aes(x=standec, y=compnoanti)) +
  geom_point(aes(col = compnoanti), size = 0.5) +
  geom_text(label=sur11$concatena, hjust = 0, nudge_x = 0.3, size = 2.5) +
  scale_colour_gradientn(colours=getPalette(colourCount))
SecondPlot

Since you didn't provide a reproducible example, I tested it using a generic dataset. This is the generic version:

# Color points above a certain value red
SecondPlot <- ggplot(mtcars, aes(x=mpg, y=disp)) +
  geom_point(col = ifelse(mtcars$disp > 120, "red", "black"), size = 0.5) +
  geom_text(label=rownames(mtcars), hjust = 0, nudge_x = 0.3, size = 2.5)
SecondPlot

#Interpolate Brewer palette
library(RColorBrewer)
colourCount = length(unique(mtcars$disp))
getPalette = colorRampPalette(brewer.pal(9, "Blues"))

SecondPlot <- ggplot(mtcars, aes(x=mpg, y=disp)) +
  geom_point(aes(col = disp), size = 0.5) +
  geom_text(label=rownames(mtcars), hjust = 0, nudge_x = 0.3, size = 2.5) +
  scale_colour_gradientn(colours=getPalette(colourCount))
SecondPlot


问:
Sraping with Beautifulsoup-Python
I am trying to scrape some data from the link: http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100

For example I am trying with BeautifulSoup to extract the name of each reviewer but it doesn't work. I have tried before to use BeautifulSoup with other website and it worked perfectly! I don't know what is happening. Can you help me. The code is the following:

```<code>from bs4 import BeautifulSoup
import os
import urllib.request

file1 = open(os.path.expanduser(r"~/Desktop/Skytrax Reviews1.csv"), "wb")

file1.write(b"Reviewer" + b"\n")

WebSites = ["http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100"]

# looping through each site until it hits a break. I will create a loop. It is not ready yet
for theurl in WebSites:
    thepage = urllib.request.urlopen(theurl)
    print(thepage)
    soup = BeautifulSoup(thepage,'lxml')
    print(soup)    #<-------This is the main problem

#Maybe it is not correct too but the main problem is at the above lines
    for Reviewer in soup.findAll(attrs={"class": "text_sub_header userStatusWrapper"}).text:
        print(Reviewer)

        Record1 = Reviewer
        file1.write(bytes(Record1, encoding="ascii", errors='ignore') + b"\n")

file1.close()
</code>```

答:
If you open that website with Chrome Network Tools or Firebug you'll noticed that it uses cookies to validate the requests.

You can emulate the cookies by creating a dict with Python and send them with your request.

In my example I'm using requests. Also, you shouldn't put .text in your loop, it'll give you an error.

```<code>from bs4 import BeautifulSoup
import requests

cookies = {
'PHPSESSID':'1gd0sknluds2uvumsglth523g5',
'visid_incap_965359':'UGNtvJR1TAmP1y+/M85QuJ1s3lgAAAAAQUIPAAAAAAB5IOYuRCw/9mMOpTnRDCJ6',
'incap_ses_315_965359':'PRZ8WIgqnhyeicz5PxxfBLFs3lgAAAAAYWoblc6exwqhEeGRPqgA5Q=='
}

response = requests.get('http://www.airlinequality.com/airline-
reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100', cookies=cookies)
soup = BeautifulSoup(response.content, "html.parser")
for Reviewer in soup.findAll(attrs={"class": "text_sub_header userStatusWrapper"}):
    print(Reviewer.get_text(strip=True))
</code>```

ContentLicense: CC BY-SA 4.0

Title: Sraping with Beautifulsoup-Python

Body:
I am trying to scrape some data from the link: http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100

For example I am trying with BeautifulSoup to extract the name of each reviewer but it doesn't work. I have tried before to use BeautifulSoup with other website and it worked perfectly! I don't know what is happening. Can you help me. The code is the following:

from bs4 import BeautifulSoup
import os
import urllib.request

file1 = open(os.path.expanduser(r"~/Desktop/Skytrax Reviews1.csv"), "wb")

file1.write(b"Reviewer" + b"\n")

WebSites = ["http://www.airlinequality.com/airline-reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100"]

# looping through each site until it hits a break. I will create a loop. It is not ready yet
for theurl in WebSites:
    thepage = urllib.request.urlopen(theurl)
    print(thepage)
    soup = BeautifulSoup(thepage,'lxml')
    print(soup)    #<-------This is the main problem

#Maybe it is not correct too but the main problem is at the above lines
    for Reviewer in soup.findAll(attrs={"class": "text_sub_header userStatusWrapper"}).text:
        print(Reviewer)

        Record1 = Reviewer
        file1.write(bytes(Record1, encoding="ascii", errors='ignore') + b"\n")

file1.close()

Body:
If you open that website with Chrome Network Tools or Firebug you'll noticed that it uses cookies to validate the requests.

You can emulate the cookies by creating a dict with Python and send them with your request.

In my example I'm using requests. Also, you shouldn't put .text in your loop, it'll give you an error.

from bs4 import BeautifulSoup
import requests

cookies = {
'PHPSESSID':'1gd0sknluds2uvumsglth523g5',
'visid_incap_965359':'UGNtvJR1TAmP1y+/M85QuJ1s3lgAAAAAQUIPAAAAAAB5IOYuRCw/9mMOpTnRDCJ6',
'incap_ses_315_965359':'PRZ8WIgqnhyeicz5PxxfBLFs3lgAAAAAYWoblc6exwqhEeGRPqgA5Q=='
}

response = requests.get('http://www.airlinequality.com/airline-
reviews/vietjetair/?sortby=post_date%3ADesc&pagesize=100', cookies=cookies)
soup = BeautifulSoup(response.content, "html.parser")
for Reviewer in soup.findAll(attrs={"class": "text_sub_header userStatusWrapper"}):
    print(Reviewer.get_text(strip=True))


问:
Social Media Buttons Not Center in

I try to center the social media buttons in a
, but it keeps on aligning left.

```<code>echo '<div class="socialWrapper">';
echo '<div class="fb-like" data-href=" '  . $_SERVER['REQUEST_URI'] . '" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="true" style="vertical-align:top;zoom:1;*display:inline;"></div> ';
echo '<a href="https://twitter.com/share" class="twitter-share-button" data-show-count="false"></a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> ';
echo '<div class="g-plusone" data-size="medium"></div>';
echo '</div>';
</code>```

CSS file

```<code>div.socialWrapper{
    margin:auto;
    width:100%;
    text-align:center;
}
</code>```

答:
The parent
, socialWrapper, has a width of 100%, and will only appear centered by using margin: 0 auto if you give it a width of less than 100%.

 is a block-level element (its default behaviour is to be display as a block, so new elements will appear on a new line). Use  instead, because it is an inline element.

This means the nested
 elements will need to be explicitly set as display: inline-block. (text-align: center will only be applied to elements whose default behaviour is display: inline, I think).

HTML/PHP

```<code>echo '<div class="socialWrapper">';
echo '<span class="fb-like" data-href=" '  . $_SERVER['REQUEST_URI'] . '" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="true" style="vertical-align:top;zoom:1;*display:inline;"></span> ';
echo '<a href="https://twitter.com/share" class="twitter-share-button" data-show-count="false"></a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> ';
echo '<span class="g-plusone" data-size="medium"></span>';
echo '</div>';
</code>```

CSS

```<code>div.socialWrapper{
    margin: 0 auto;
    width: 50%;
    text-align:center;
}
</code>```

I made a CodePen demo for you:

See the Pen Social toolbar by Yvonne Aburrow (@vogelbeere) on CodePen.

Title: Social Media Buttons Not Center in <div>

Body:
I try to center the social media buttons in a
, but it keeps on aligning left.

echo '
';
echo '

 ';
echo ' ';
echo '

';
echo '
';

CSS file

div.socialWrapper{
    margin:auto;
    width:100%;
    text-align:center;
}

Body:
The parent <div>, socialWrapper, has a width of 100%, and will only appear centered by using margin: 0 auto if you give it a width of less than 100%.

<div> is a block-level element (its default behaviour is to be display as a block, so new elements will appear on a new line). Use <span> instead, because it is an inline element.

This means the nested <div> elements will need to be explicitly set as display: inline-block. (text-align: center will only be applied to elements whose default behaviour is display: inline, I think).

HTML/PHP

echo '<div class="socialWrapper">';
echo '<span class="fb-like" data-href=" '  . $_SERVER['REQUEST_URI'] . '" data-layout="button_count" data-action="like" data-size="small" data-show-faces="true" data-share="true" style="vertical-align:top;zoom:1;*display:inline;"></span> ';
echo '<a href="https://twitter.com/share" class="twitter-share-button" data-show-count="false"></a><script async src="//platform.twitter.com/widgets.js" charset="utf-8"></script> ';
echo '<span class="g-plusone" data-size="medium"></span>';
echo '</div>';

CSS

div.socialWrapper{
    margin: 0 auto;
    width: 50%;
    text-align:center;
}

I made a CodePen demo for you:

See the Pen Social toolbar by Yvonne Aburrow (@vogelbeere) on CodePen.


问:
How to open Microphone properties window
How do I open the microphone properties window when I click a button?</p>

答:
There is nothing built in to WPF for opening the Microphone properties window. This is a .NET feature. Are you using C#?

If you want to open the Volume Control on Windows, you could just run the sndvol32.exe executable:

```<code>string lWinDir = Environment.GetEnvironmentVariable("windir");
string lSndVolPath = lWinDir + @"\system32\sndvol32.exe";
Process lVolumeControl = Process.Start(lSndVolPath);
</code>```

See also How to adjust microphone gain from C# (needs to work on XP & W7)….

Body:
There is nothing built in to WPF for opening the Microphone properties window. This is a .NET feature. Are you using C#?

If you want to open the Volume Control on Windows, you could just run the sndvol32.exe executable:

string lWinDir = Environment.GetEnvironmentVariable("windir");
string lSndVolPath = lWinDir + @"\system32\sndvol32.exe";
Process lVolumeControl = Process.Start(lSndVolPath);

See also How to adjust microphone gain from C# (needs to work on XP & W7)….


问:
AJAX dyamic content "event delegation" replacement for "each"
I'm implementing AJAX "load more" pagination on a website.

In order for .click() events to work for dynamically loaded content, I replaced all the .click() code with...

```<code>$(document).on('click', ".selector", function (event){
</code>```

That's all working fine for clickable stuff.

Now I'm trying to get some non-click based init code working in the same way as well.  This is the old version of my code that works for normal non-AJAX content:

```<code>var now = moment();
$('time').each(function(i, e) {
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});
</code>```

How would I get this code to also work on the dynamically loaded <time> tags?

I tried the following, but it's obviously wrong (using this code none of the <time> tags work at all):

```<code>var now = moment();
$(document).on('each', 'time', function (event){
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});
</code>```

答:
To do what you require the logic in your first block is correct - you just need to execute it again when the new <time> elements have been added to the DOM. The easiest way to do this is to extract the logic to a function, something like this:

```<code>function setTime($container) {
  $container = $container || $(document);
  var now = moment();
  $container.find('time').each(function(i, e) {
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
  });
}

setTime(); // on load

$.ajax({
  url: '/foo',
  success: function(html) {
    var $container = $('.container').append(html);
    setTime($container); // after the AJAX call
  }
})
</code>```

Body:
I'm implementing AJAX "load more" pagination on a website.

In order for .click() events to work for dynamically loaded content, I replaced all the .click() code with...

$(document).on('click', ".selector", function (event){

That's all working fine for clickable stuff.

Now I'm trying to get some non-click based init code working in the same way as well.  This is the old version of my code that works for normal non-AJAX content:

var now = moment();
$('time').each(function(i, e) {
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});

How would I get this code to also work on the dynamically loaded <time> tags?

I tried the following, but it's obviously wrong (using this code none of the <time> tags work at all):

var now = moment();
$(document).on('each', 'time', function (event){
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
});

Body:
To do what you require the logic in your first block is correct - you just need to execute it again when the new <time> elements have been added to the DOM. The easiest way to do this is to extract the logic to a function, something like this:

function setTime($container) {
  $container = $container || $(document);
  var now = moment();
  $container.find('time').each(function(i, e) {
    var time = moment($(e).attr('datetime'));
    $(e).html(time.from(now));
    $(e).attr('title', time.format('D MMM YYYY h:mma'));
  });
}

setTime(); // on load

$.ajax({
  url: '/foo',
  success: function(html) {
    var $container = $('.container').append(html);
    setTime($container); // after the AJAX call
  }
})