问:
XML Schema key/keyref - how to use them?
Long story short : i would like to know how to use the key/keyref from XSD to let elements have references to each other. it has to have a form of an example, using a simple xsd and an XML.

Long story : I am familiar with usage of ID/IDREF. I use those to connect elements for JAXB. I have been told repeatedly that the key/keyref construct in XSD offers enhanced flexibility for inter-element referencing. I have consulted the OReilly XML Schema book, that seems to teach everything about correct definition of key/keyref and how it is similar to the ID/IDREF (but better) and doesn't give a simple example of its use. It doesn't seem to be similar, because you define the ID as an attribute in one element and the IDREF in another element and voila. But key/keyref have to be defined in a common ancestor of the referencing and the referenced element (AFAIK)...

I use the XSD files to generate JAXB-bound Java classes with XJC

I have searched for how-tos, tutorials and examples, but google gives me scraps. same for searches on SO (also with google and inclusive search with '+' ).

In order to make everyone's lives easier i have prepared an XSD with already defined key/keyref pair as i have understood it.

```<code><xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="referenced">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
            <xs:element name="owner">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
    <xs:key name="aKey">
        <xs:selector xpath="owner" />
        <xs:field xpath="@id" />
    </xs:key>
    <xs:keyref name="aKeyRef" refer="aKey">
        <xs:selector xpath="referenced" />
        <xs:field xpath="@id" />
    </xs:keyref>
</xs:element>
</code>```

How would a piece of XML look like, with an 'owner'-element referencing a 'referenced'-element?

EDIT :  applied the change proposed by Tom W, changing the xpath attribute of the key element to "owner". JAXB (XJC) still doesnt care though.

Thank you

答:
JAXB doesn't support references by means of xs:key or xs:keyref. The specification states that these constraints may be checked during validation, but they have no effect on data.

However, you can achieve this (more or less) by using xs:ID and xs:IDREF instead. For an introduction, see the chapters 2.2.15 Referring to Another XML Element and 4.3 Assembling Data with Links (ID, IDREF) in the JAXB Tutorial by Wolfgang Laun.

For your sample XSD, this would meaning changing the element definition to

```<code><xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="referenced">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:ID" />
                </xs:complexType>
            </xs:element>
            <xs:element name="owner">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:IDREF" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>
</code>```

Note that identifiers with the xs:ID type are required to be globally unique in the XML document. In other words, you cannot have the same ID for two different elements in the same XML file, even if the elements are of different types.

By default, an element or attribute of type xs:IDREF binds to java.lang.Object. If you know in advance what type the referenced object will be, you can customize the mapping, either by adding JAXB annotations to the schema or through an external binding declaration (e.g., xjc -b bindings.xjb).

Example using JAXB schema annotations (not tested):

```<code><xs:element name="owner">
    <xs:complexType>
        <xs:attribute name="id" type="xs:IDREF">
            <xs:annotation>
                <xs:appinfo>
                    <jaxb:property>
                        <jaxb:baseType name=”SomeType”/>
                    </jaxb:property>
                </xs:appinfo>
            </xs:annotation>
        </xs:attribute>
    </xs:complexType>
</xs:element>
</code>```

Example using an external bindings declaration (not tested):

```<code><jaxb:bindings node="//xs:element[@name=’owner’]//xs:attribute[@name='id']”>
    <jaxb:property>
        <jaxb:basetype name="SomeType"/>
    </jaxb:property>
</jaxb:bindings>
</code>```

Body:
Long story short : i would like to know how to use the key/keyref from XSD to let elements have references to each other. it has to have a form of an example, using a simple xsd and an XML.

Long story : I am familiar with usage of ID/IDREF. I use those to connect elements for JAXB. I have been told repeatedly that the key/keyref construct in XSD offers enhanced flexibility for inter-element referencing. I have consulted the OReilly XML Schema book, that seems to teach everything about correct definition of key/keyref and how it is similar to the ID/IDREF (but better) and doesn't give a simple example of its use. It doesn't seem to be similar, because you define the ID as an attribute in one element and the IDREF in another element and voila. But key/keyref have to be defined in a common ancestor of the referencing and the referenced element (AFAIK)...

I use the XSD files to generate JAXB-bound Java classes with XJC

I have searched for how-tos, tutorials and examples, but google gives me scraps. same for searches on SO (also with google and inclusive search with '+' ).

In order to make everyone's lives easier i have prepared an XSD with already defined key/keyref pair as i have understood it.

<xs:schema elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
<xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="referenced">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
            <xs:element name="owner">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:string" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
    <xs:key name="aKey">
        <xs:selector xpath="owner" />
        <xs:field xpath="@id" />
    </xs:key>
    <xs:keyref name="aKeyRef" refer="aKey">
        <xs:selector xpath="referenced" />
        <xs:field xpath="@id" />
    </xs:keyref>
</xs:element>

How would a piece of XML look like, with an 'owner'-element referencing a 'referenced'-element?

EDIT :  applied the change proposed by Tom W, changing the xpath attribute of the key element to "owner". JAXB (XJC) still doesnt care though.

Thank you

Body:
JAXB doesn't support references by means of xs:key or xs:keyref. The specification states that these constraints may be checked during validation, but they have no effect on data.

However, you can achieve this (more or less) by using xs:ID and xs:IDREF instead. For an introduction, see the chapters 2.2.15 Referring to Another XML Element and 4.3 Assembling Data with Links (ID, IDREF) in the JAXB Tutorial by Wolfgang Laun.

For your sample XSD, this would meaning changing the element definition to

<xs:element name="root">
    <xs:complexType>
        <xs:sequence>
            <xs:element name="referenced">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:ID" />
                </xs:complexType>
            </xs:element>
            <xs:element name="owner">
                <xs:complexType>
                    <xs:attribute name="id" type="xs:IDREF" />
                </xs:complexType>
            </xs:element>
        </xs:sequence>
    </xs:complexType>
</xs:element>

Note that identifiers with the xs:ID type are required to be globally unique in the XML document. In other words, you cannot have the same ID for two different elements in the same XML file, even if the elements are of different types.

By default, an element or attribute of type xs:IDREF binds to java.lang.Object. If you know in advance what type the referenced object will be, you can customize the mapping, either by adding JAXB annotations to the schema or through an external binding declaration (e.g., xjc -b bindings.xjb).

Example using JAXB schema annotations (not tested):

<xs:element name="owner">
    <xs:complexType>
        <xs:attribute name="id" type="xs:IDREF">
            <xs:annotation>
                <xs:appinfo>
                    <jaxb:property>
                        <jaxb:baseType name=”SomeType”/>
                    </jaxb:property>
                </xs:appinfo>
            </xs:annotation>
        </xs:attribute>
    </xs:complexType>
</xs:element>

Example using an external bindings declaration (not tested):

<jaxb:bindings node="//xs:element[@name=’owner’]//xs:attribute[@name='id']”>
    <jaxb:property>
        <jaxb:basetype name="SomeType"/>
    </jaxb:property>
</jaxb:bindings>


来源: stackexchange

问:
Proper way to maintain unique usernames and extra profile data in Firebase
I am trying to create a separate datastore for unique usernames and extra profile data such as avatar etc.  I have the following schema:

```<code>mydatabase : {
   users: [{
     <actual user's id>: {
        username: "helloworld"
     },
     <actual user's id>: {
        username: "2test"
     }]
}
</code>```

Is my approach correct on this?  I didn't see a way in firebase to store usernames or extra user data in the Authentication records of firebase.  Also I noticed most examples I find online generate a push key for each row of data, but here I am using the actual user's id instead of a push key.  I want to eventually query this when a user tries to create a username to see if it's been taken already.

答:
I would use the same approach you're using. I agree that it makes sense to use the userId as the key instead of a pushId since, as you point out, you'll want to query the data later on. </p>

<p>The only potential challenge of using this structure is if you want users to pick a username at the time the user is created, they will not have read access to the database so they won't be able to check if the username is unique. As long as you're ok with creating a user first and then having them choose a username once authenticated, this won't be a problem. If you'd prefer that they choose a username first, then you could use Cloud Functions for Firebase with an HTTP trigger, and pass the username as part of the request. The request would include a query of the given username and the response would return whether the username is available or not. It could look something like this: </p>

```<code>const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.uniqueUsername = functions.https.onRequest((req, res) => {
    const username = req.query.username
    admin.database().ref('users').orderByChild('username').equalTo(username)once('value').then(snap => {
        // if the child exists, then the username is taken
        if (snap.exists()) {
            res.send('username not available');
        } else {
            res.send('username available');
        }
    })
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create a separate datastore for unique usernames and extra profile data such as avatar etc.  I have the following schema:

mydatabase : {
   users: [{
     <actual user's id>: {
        username: "helloworld"
     },
     <actual user's id>: {
        username: "2test"
     }]
}

Is my approach correct on this?  I didn't see a way in firebase to store usernames or extra user data in the Authentication records of firebase.  Also I noticed most examples I find online generate a push key for each row of data, but here I am using the actual user's id instead of a push key.  I want to eventually query this when a user tries to create a username to see if it's been taken already.

Body:
I would use the same approach you're using. I agree that it makes sense to use the userId as the key instead of a pushId since, as you point out, you'll want to query the data later on.

The only potential challenge of using this structure is if you want users to pick a username at the time the user is created, they will not have read access to the database so they won't be able to check if the username is unique. As long as you're ok with creating a user first and then having them choose a username once authenticated, this won't be a problem. If you'd prefer that they choose a username first, then you could use Cloud Functions for Firebase with an HTTP trigger, and pass the username as part of the request. The request would include a query of the given username and the response would return whether the username is available or not. It could look something like this:

const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);

exports.uniqueUsername = functions.https.onRequest((req, res) => {
    const username = req.query.username
    admin.database().ref('users').orderByChild('username').equalTo(username)once('value').then(snap => {
        // if the child exists, then the username is taken
        if (snap.exists()) {
            res.send('username not available');
        } else {
            res.send('username available');
        }
    })
}


问:
ASP.NET Processmodel Configuration Optimization
A regular ASP.NET installation will create machine.config with the following configuration:

```<code><system.web>
    <processModel autoConfig="true" />
</code>```

I would like to override few properties values in web.config like:

```<code><system.web>
   <processModel
     maxWorkerThreads="100"
     maxIoThreads="100"
     minWorkerThreads="40"
     minIoThreads="30"
     memoryLimit="60"
   />
</code>```

I would like to know that whether i have to write all default properties inside web.config or it will automatically take other default properties of processmodel from machine.config?

Following are the properties of processmodel

```<code><processModel
   enable="true|false"
   timeout="hrs:mins:secs|Infinite"
   idleTimeout="hrs:mins:secs|Infinite"
   shutdownTimeout="hrs:mins:secs|Infinite"
   requestLimit="num|Infinite"
   requestQueueLimit="num|Infinite"
   restartQueueLimit="num|Infinite"
   memoryLimit="percent"
   webGarden="true|false"
   cpuMask="num"
   userName="{username}"
   password="{secure password}"
   logLevel="All|None|Errors"
   clientConnectedCheck="hrs:mins:secs|Infinite"
   comAuthenticationLevel="Default|None|Connect|Call|
               Pkt|PktIntegrity|PktPrivacy"
   comImpersonationLevel="Default|Anonymous|Identify|
               Impersonate|Delegate"
   responseDeadlockInterval="hrs:mins:secs|Infinite"
   responseRestartDeadlockInterval="hrs:mins:secs|Infinite"
   autoConfig="true|false"
   maxWorkerThreads="num"
   maxIoThreads="num"
   minWorkerThreads="num"
   minIoThreads="num"
   serverErrorMessageFile=""
   pingFrequency="Infinite"
   pingTimeout="Infinite"
   maxAppDomains="2000"
/>
</code>```

答:
Does it make sense to answer the question now? I did a test to change the value, and using the IIS Configuration Manager, I see that the value is updated. Of course the change in on the machine.config file, to it applies to all the sites. I did not find a way to set the value per site.

The machine.config has the following

```<code>   <processModel autoConfig="false" maxIoThreads="250" />
</code>```

I did not need to set the rest of the values.

ContentLicense: CC BY-SA 2.5

Body:
A regular ASP.NET installation will create machine.config with the following configuration:

<system.web>
    <processModel autoConfig="true" />

I would like to override few properties values in web.config like:

<system.web>
   <processModel
     maxWorkerThreads="100"
     maxIoThreads="100"
     minWorkerThreads="40"
     minIoThreads="30"
     memoryLimit="60"
   />

I would like to know that whether i have to write all default properties inside web.config or it will automatically take other default properties of processmodel from machine.config?

Following are the properties of processmodel

<processModel
   enable="true|false"
   timeout="hrs:mins:secs|Infinite"
   idleTimeout="hrs:mins:secs|Infinite"
   shutdownTimeout="hrs:mins:secs|Infinite"
   requestLimit="num|Infinite"
   requestQueueLimit="num|Infinite"
   restartQueueLimit="num|Infinite"
   memoryLimit="percent"
   webGarden="true|false"
   cpuMask="num"
   userName="{username}"
   password="{secure password}"
   logLevel="All|None|Errors"
   clientConnectedCheck="hrs:mins:secs|Infinite"
   comAuthenticationLevel="Default|None|Connect|Call|
               Pkt|PktIntegrity|PktPrivacy"
   comImpersonationLevel="Default|Anonymous|Identify|
               Impersonate|Delegate"
   responseDeadlockInterval="hrs:mins:secs|Infinite"
   responseRestartDeadlockInterval="hrs:mins:secs|Infinite"
   autoConfig="true|false"
   maxWorkerThreads="num"
   maxIoThreads="num"
   minWorkerThreads="num"
   minIoThreads="num"
   serverErrorMessageFile=""
   pingFrequency="Infinite"
   pingTimeout="Infinite"
   maxAppDomains="2000"
/>

Body:
Does it make sense to answer the question now? I did a test to change the value, and using the IIS Configuration Manager, I see that the value is updated. Of course the change in on the machine.config file, to it applies to all the sites. I did not find a way to set the value per site.

The machine.config has the following

   <processModel autoConfig="false" maxIoThreads="250" />

I did not need to set the rest of the values.


问:
Regex for validating a pattern in Java
I have to validate a pattern like : abc.123456789.123 (example) where I have to check for these things:

First three should be letters only of fixed length (case insensitive)

Followed by dot (.)

Numbers in range 0-9, length should be 9

Followed by dot (.) and Numbers in range 0-9, length should be 3 (optional)

Valid Example:

```<code> abc.1
 Abc.123456789
 aBc.123.123
 ABC.123456789.12
</code>```

Invalid Exmples:

```<code> abc.1.
 abc..1.123
 .123
 abc.123w45678.123
 abc.
</code>```

What I've tried :

```<code>^[a-zA-Z]{3}\\.\\d{0,9}\\.\\d{0,3}|[a-zA-Z]{3}\\.\\d{0,9}$
</code>```

As I am new in Regex, I tried the above Regex but it is failing to pass abc.1. and abc...

答:
Simply put:

```<code>^[a-zA-Z]{3}\.\d{1,9}(?:\.\d{1,3})?$
</code>```

See here and click on Java

Title: Regex for validating a pattern in Java

Body:
I have to validate a pattern like : abc.123456789.123 (example) where I have to check for these things:

First three should be letters only of fixed length (case insensitive)

Followed by dot (.)

Numbers in range 0-9, length should be 9

Followed by dot (.) and Numbers in range 0-9, length should be 3 (optional)

Valid Example:

 abc.1
 Abc.123456789
 aBc.123.123
 ABC.123456789.12

Invalid Exmples:

 abc.1.
 abc..1.123
 .123
 abc.123w45678.123
 abc.

What I've tried :

^[a-zA-Z]{3}\\.\\d{0,9}\\.\\d{0,3}|[a-zA-Z]{3}\\.\\d{0,9}$

As I am new in Regex, I tried the above Regex but it is failing to pass abc.1. and abc...

Body:
Simply put:

^[a-zA-Z]{3}\.\d{1,9}(?:\.\d{1,3})?$

See here and click on Java


问:
Broken axis in Google charts
Is there any way to create a break in my vertical scale on the Google charts api?

I have a couple of dozen data points all about 600-2000 on the y-axis except for one value which is almost 300,000; this makes all the smaller data points nearly unreadable. I need to represent all this data and a logarithmic scale is not an option.

答:
You need use a log scale. It's a vAxis and hAxis attribute. The supported values are:

log: Conventional logarithm scale

mirrorLog: Logarithm scale that allows 0 values

```<code>var options = {
    vAxis: {
        scaleType: 'mirrorLog',
    }
};

var data = {};//your data

chart.draw(data, options);
</code>```

Title: Broken axis in Google charts

Body:
You need use a log scale. It's a vAxis and hAxis attribute. The supported values are:

log: Conventional logarithm scale

mirrorLog: Logarithm scale that allows 0 values

var options = {
    vAxis: {
        scaleType: 'mirrorLog',
    }
};

var data = {};//your data

chart.draw(data, options);


问:
Xamarin form app: Keyboard type telephone allow to input negative values in Android but not in IOS
I have made an application in Xamarin From. Design the UI in xaml. My issue is when i define the Keyboard telephone in entry field it allow to input negative value in android app but in IOS it not allowed.

```<code><StackLayout Spacing="20" Padding="0" Orientation="Horizontal" HorizontalOptions="FillAndExpand">
            <Entry Text="{Binding Item.TextProvider2017}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2017" Keyboard="Telephone" Completed="NoOfProvider_Completed" Unfocused="NoOfProvider_Unfocused"/>
            <Entry Text="{Binding Item.TextProvider2018}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2018" Keyboard="Telephone"/>
            <Entry Text="{Binding Item.TextProvider2019}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2019" Keyboard="Telephone"/>
            <Entry Text="{Binding Item.TextProvider2020}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2020" Keyboard="Telephone"/>
        </StackLayout>
</code>```

Keypad in Android:

Keypad in IOS:

In Android keypad have negative sign but IOS don't have. IS there any way to make both same.

答:
This is the old answer, see below for an updated version

You're going to want to create a custom renderer for the Entry control which has the default behavior for UWP and Android, while adding a custom InputAccessoryView to your iOS UITextField.

Here's what your custom renderer for iOS might look like:

```<code>class MinusButtonEntryRenderer : EntryRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);
        if (Control == null) return;

        UIBarButtonItem button = new UIBarButtonItem("-", UIBarButtonItemStyle.Plain, (sender, args) =>
        {
            var position = Control.SelectedTextRange.Start;
            var idx = (int) Control.GetOffsetFromPosition(Control.BeginningOfDocument, position);
            Element.Text.Insert(idx, "-");
        });
        UIToolbar toolbar = new UIToolbar()
        {
            Items = new [] { button }
        };
        Control.InputAccessoryView = toolbar;
    }
}
</code>```

This code basically creates a button, adds that to a toolbar, and then assigns that toolbar to the underlying UITextField. You will of course want to customize the toolbar and toolbar button to suit your needs.

EDIT:

There's a better way to do this using Effects in Xamarin Forms.

This class goes in the iOS project and is the main effect:

```<code>using MyApp;
using UIKit;
using Xamarin.Forms;

[assembly:ResolutionGroupName("Xamarin")]
[assembly:ExportEffect(typeof(MinusButtonEntryEffect), "MinusButtonEntryEffect")]
namespace MyApp
{
    public class MinusButtonEntryEffect : PlatformEffect<UIView, UITextField>
    {
        protected override void OnAttached()
        {
            if (Control == null) return;
            var element = Element as Entry;
            if (element == null) return;

            UIBarButtonItem button = new UIBarButtonItem("-", UIBarButtonItemStyle.Plain, (sender, args) =>
            {
                var position = Control.SelectedTextRange.Start;
                var idx = (int)Control.GetOffsetFromPosition(Control.BeginningOfDocument, position);
                element.Text = element.Text.Insert(idx, "-");
            });
            UIToolbar toolbar = new UIToolbar()
            {
                Items = new[] { button }
            };
            Control.InputAccessoryView = toolbar;
        }

        protected override void OnDetached()
        {
            Control.InputAccessoryView = null;
        }
    }
}
</code>```

This code goes in the PCL and allows us to access the effect from XAML:

```<code>public class MinusButtonEntryEffect : RoutingEffect
{
    public MinusButtonEntryEffect () : base ("Xamarin.MinusButtonEntryEffect") { }
}
</code>```

So your XAML would look something like this:

```<code><Entry Text="{Binding Item.TextProvider2017}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2017" Keyboard="Telephone">
    <Entry.Effects>
        <local:MinusButtonEntryEffect />
    </Entry.Effects>
</Entry>
</code>```

Make sure that local is whatever namespace your effect is in, for example:

```<code>xmlns:local="clr-namespace:MyApp"
</code>```

Body:
I have made an application in Xamarin From. Design the UI in xaml. My issue is when i define the Keyboard telephone in entry field it allow to input negative value in android app but in IOS it not allowed.

<StackLayout Spacing="20" Padding="0" Orientation="Horizontal" HorizontalOptions="FillAndExpand">
            <Entry Text="{Binding Item.TextProvider2017}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2017" Keyboard="Telephone" Completed="NoOfProvider_Completed" Unfocused="NoOfProvider_Unfocused"/>
            <Entry Text="{Binding Item.TextProvider2018}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2018" Keyboard="Telephone"/>
            <Entry Text="{Binding Item.TextProvider2019}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2019" Keyboard="Telephone"/>
            <Entry Text="{Binding Item.TextProvider2020}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2020" Keyboard="Telephone"/>
        </StackLayout>

Keypad in Android:

Keypad in IOS:

In Android keypad have negative sign but IOS don't have. IS there any way to make both same.

Body:
This is the old answer, see below for an updated version

You're going to want to create a custom renderer for the Entry control which has the default behavior for UWP and Android, while adding a custom InputAccessoryView to your iOS UITextField.

Here's what your custom renderer for iOS might look like:

class MinusButtonEntryRenderer : EntryRenderer
{
    protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
    {
        base.OnElementChanged(e);
        if (Control == null) return;

        UIBarButtonItem button = new UIBarButtonItem("-", UIBarButtonItemStyle.Plain, (sender, args) =>
        {
            var position = Control.SelectedTextRange.Start;
            var idx = (int) Control.GetOffsetFromPosition(Control.BeginningOfDocument, position);
            Element.Text.Insert(idx, "-");
        });
        UIToolbar toolbar = new UIToolbar()
        {
            Items = new [] { button }
        };
        Control.InputAccessoryView = toolbar;
    }
}

This code basically creates a button, adds that to a toolbar, and then assigns that toolbar to the underlying UITextField. You will of course want to customize the toolbar and toolbar button to suit your needs.

EDIT:

There's a better way to do this using Effects in Xamarin Forms.

This class goes in the iOS project and is the main effect:

using MyApp;
using UIKit;
using Xamarin.Forms;

[assembly:ResolutionGroupName("Xamarin")]
[assembly:ExportEffect(typeof(MinusButtonEntryEffect), "MinusButtonEntryEffect")]
namespace MyApp
{
    public class MinusButtonEntryEffect : PlatformEffect<UIView, UITextField>
    {
        protected override void OnAttached()
        {
            if (Control == null) return;
            var element = Element as Entry;
            if (element == null) return;

            UIBarButtonItem button = new UIBarButtonItem("-", UIBarButtonItemStyle.Plain, (sender, args) =>
            {
                var position = Control.SelectedTextRange.Start;
                var idx = (int)Control.GetOffsetFromPosition(Control.BeginningOfDocument, position);
                element.Text = element.Text.Insert(idx, "-");
            });
            UIToolbar toolbar = new UIToolbar()
            {
                Items = new[] { button }
            };
            Control.InputAccessoryView = toolbar;
        }

        protected override void OnDetached()
        {
            Control.InputAccessoryView = null;
        }
    }
}

This code goes in the PCL and allows us to access the effect from XAML:

public class MinusButtonEntryEffect : RoutingEffect
{
    public MinusButtonEntryEffect () : base ("Xamarin.MinusButtonEntryEffect") { }
}

So your XAML would look something like this:

<Entry Text="{Binding Item.TextProvider2017}" HorizontalTextAlignment="End" FontSize="Small" WidthRequest="140" MinimumWidthRequest="60" Placeholder="For 2017" Keyboard="Telephone">
    <Entry.Effects>
        <local:MinusButtonEntryEffect />
    </Entry.Effects>
</Entry>

Make sure that local is whatever namespace your effect is in, for example:

xmlns:local="clr-namespace:MyApp"


问:
Facebook Login - cannot convert value of type 'URL' to expected argument type 'URL!'

Pod

Using FBSDKCoreKit (4.23.0)

Using FBSDKLoginKit (4.23.0)

I simply cannot go pass through this function because i cannot cast URL to URL!. I did try to cast is with ! but it wont let me through. Did i miss something during the proses ?

Cheers

PS: i did create a github issues for this but it seems they did not check their github repo periodically.

答:
You are likely using the wrong method.

It's pretty standard stuff for using FBSDK. You should use

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {}

to return

application(app, open: url, sourceApplication: sourceApplication, annotation: nil)

Typically the function should look like below in your AppDelegate-

```<code>func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

        let sourceApplication: String? = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
        return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: sourceApplication, annotation: nil)

    }
</code>```

Also, assuming that you have this, in your didFinishLaunchingWithOptions

```<code> func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

        return true
    }
</code>```

Also, you should be using the Facebook Swift pods-

```<code>pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'
</code>```

See this for more info.

Body:
You are likely using the wrong method.

It's pretty standard stuff for using FBSDK. You should use

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {}

to return

application(app, open: url, sourceApplication: sourceApplication, annotation: nil)

Typically the function should look like below in your AppDelegate-

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {

        let sourceApplication: String? = options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String
        return FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: sourceApplication, annotation: nil)

    }

Also, assuming that you have this, in your didFinishLaunchingWithOptions

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

        return true
    }

Also, you should be using the Facebook Swift pods-

pod 'FacebookCore'
pod 'FacebookLogin'
pod 'FacebookShare'

See this for more info.


问:
How do I adjust the fidelity of a chart control?
This is what the chart currently looks like:

This is all the data in the database that it is currently using. (please excuse how the headers are not properly aligning here)

```<code>Id(Key)   Confidence Love   Stress         Date/Time
    193     0   0   0   12/3/2010 11:33:47 PM
    194     55  55  55  12/3/2010 11:34:04 PM
    195     30  40  20  12/3/2010 11:34:11 PM
    196     40  50  30  12/3/2010 11:34:20 PM
    197     50  60  40  12/3/2010 11:34:28 PM
    198     60  70  50  12/3/2010 11:34:45 PM
    199     70  80  60  12/3/2010 11:34:53 PM
    200     80  90  70  12/3/2010 11:34:59 PM
    201     20  3   11  12/3/2010 11:36:42 PM
    202     20  3   11  12/3/2010 11:37:08 PM
    203     76  34  34  12/3/2010 11:37:41 PM
    204     3   4   2   12/4/2010 12:14:15 AM
    205     5   100 8   12/4/2010 12:17:57 AM
    206     77  89  3   12/12/2010 8:08:49 PM
</code>```

This is the SQL statement I have the chart configured too:

SELECT [ConfidenceLevel], [LoveLevel],
  [DateTime], [StressLevel] FROM
  [UserData]

My issue is in cases like this example, the data recorded around 12/4 looses it's fidelity and is un - "see able", it all blends together.

How can I configure the chart so that the last 20 days are always readable on the chart and that they don't blur together?

Thank You.

答:
i think the issue is with the chart type you selected as compared to the density/sparsity of your data.

this maybe reminds me of a box-and-whisker type chart,

also consider a bubble chart.

Body:
This is what the chart currently looks like:

This is all the data in the database that it is currently using. (please excuse how the headers are not properly aligning here)

Id(Key)   Confidence Love   Stress         Date/Time
    193     0   0   0   12/3/2010 11:33:47 PM
    194     55  55  55  12/3/2010 11:34:04 PM
    195     30  40  20  12/3/2010 11:34:11 PM
    196     40  50  30  12/3/2010 11:34:20 PM
    197     50  60  40  12/3/2010 11:34:28 PM
    198     60  70  50  12/3/2010 11:34:45 PM
    199     70  80  60  12/3/2010 11:34:53 PM
    200     80  90  70  12/3/2010 11:34:59 PM
    201     20  3   11  12/3/2010 11:36:42 PM
    202     20  3   11  12/3/2010 11:37:08 PM
    203     76  34  34  12/3/2010 11:37:41 PM
    204     3   4   2   12/4/2010 12:14:15 AM
    205     5   100 8   12/4/2010 12:17:57 AM
    206     77  89  3   12/12/2010 8:08:49 PM

This is the SQL statement I have the chart configured too:

SELECT [ConfidenceLevel], [LoveLevel],
  [DateTime], [StressLevel] FROM
  [UserData]

My issue is in cases like this example, the data recorded around 12/4 looses it's fidelity and is un - "see able", it all blends together.

How can I configure the chart so that the last 20 days are always readable on the chart and that they don't blur together?

Thank You.


问:
Exception when downloading file from box.com - Android
I am trying to download a file using the Box android SDK. The problem seems to be with the destinationFile parameter. The box.com call is checking whether the destinationFile exists - but why? I get java.io.FileNotFoundException.</p>

```<code>destinationFile = new File(getFilesDir(), "myfile.crs");
        // destinationFile = new File(getFilesDir(),"/");
        try {
            BoxDownload fileDownload = mFileApi.getDownloadRequest(destinationFile, fileID)
                    // Optional: Set a listener to track download progress.
                    .setProgressListener(new ProgressListener() {
                        @Override
                        public void onProgressChanged(long numBytes, long totalBytes) {
                            // Update a progress bar, etc.
                        }
                    })
                    .send();
        } catch (BoxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
</code>```

答:
To do All the checks

```<code>Log.i(getClass().getName(),"Does File exists:"+(destinationFile.exists()?"Yes":"No"));
        Log.i(getClass().getName(),"Is it A file:"+(destinationFile.isFile()?"Yes":"No"));
        Log.i(getClass().getName(),"Is it Writable:"+(destinationFile.canWrite()?"Yes":"No"));
        Log.i(getClass().getName(),"Is it A Readable:"+(destinationFile.canRead()?"Yes":"No"));
        Log.i(getClass().getName(),"Path:"+destinationFile.getAbsolutePath());
</code>```

you are most likely to found file does not exists then do this before using it.

```<code>if(!destinationFile.exists()){
            try {
                destinationFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
</code>```

Body:
I am trying to download a file using the Box android SDK. The problem seems to be with the destinationFile parameter. The box.com call is checking whether the destinationFile exists - but why? I get java.io.FileNotFoundException.

destinationFile = new File(getFilesDir(), "myfile.crs");
        // destinationFile = new File(getFilesDir(),"/");
        try {
            BoxDownload fileDownload = mFileApi.getDownloadRequest(destinationFile, fileID)
                    // Optional: Set a listener to track download progress.
                    .setProgressListener(new ProgressListener() {
                        @Override
                        public void onProgressChanged(long numBytes, long totalBytes) {
                            // Update a progress bar, etc.
                        }
                    })
                    .send();
        } catch (BoxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

Body:
To do All the checks

Log.i(getClass().getName(),"Does File exists:"+(destinationFile.exists()?"Yes":"No"));
        Log.i(getClass().getName(),"Is it A file:"+(destinationFile.isFile()?"Yes":"No"));
        Log.i(getClass().getName(),"Is it Writable:"+(destinationFile.canWrite()?"Yes":"No"));
        Log.i(getClass().getName(),"Is it A Readable:"+(destinationFile.canRead()?"Yes":"No"));
        Log.i(getClass().getName(),"Path:"+destinationFile.getAbsolutePath());

you are most likely to found file does not exists then do this before using it.

if(!destinationFile.exists()){
            try {
                destinationFile.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


问:
Reloading Keras Tokenizer during Testing
I followed the tutorial here: (https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html)

However, I modified the code to be able to save the generated model through h5py. Thus, after running the training script, I have a generated model.h5 in my directory.

Now, when I want to load it, my problem is that I'm confused as to how to re-initiate the Tokenizer. The tutorial has the following line of code:

```<code>tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)
</code>```

But hypothetically, if I reload the model.h5 in a different module, I'll need to create another Tokenizer to tokenize the test set. But then, the new Tokenizer will be fit on the test data thus creating a completely different word table.

Therefore, my question is: How do I reload the Tokenizer that was trained on the training dataset? Am I in some way misunderstanding the functionality of the Embedding layer in Keras? Right now, I'm assuming that since we mapped certain word indices to their corresponding embedding vectors based on the pre-trained word embeddings, the word indices need to be consistent. However, this is not possible if we perform another fit_on_texts on the test dataset.

Thank you and looking forward to your answers!

答:
Check out this question
The commenter recommends using a pickle to save the object & state, though the question still remains why this kind of functionality is not built into keras. </p>

Body:
I followed the tutorial here: (https://blog.keras.io/using-pre-trained-word-embeddings-in-a-keras-model.html)

However, I modified the code to be able to save the generated model through h5py. Thus, after running the training script, I have a generated model.h5 in my directory.

Now, when I want to load it, my problem is that I'm confused as to how to re-initiate the Tokenizer. The tutorial has the following line of code:

tokenizer = Tokenizer(nb_words=MAX_NB_WORDS)
tokenizer.fit_on_texts(texts)
sequences = tokenizer.texts_to_sequences(texts)

But hypothetically, if I reload the model.h5 in a different module, I'll need to create another Tokenizer to tokenize the test set. But then, the new Tokenizer will be fit on the test data thus creating a completely different word table.

Therefore, my question is: How do I reload the Tokenizer that was trained on the training dataset? Am I in some way misunderstanding the functionality of the Embedding layer in Keras? Right now, I'm assuming that since we mapped certain word indices to their corresponding embedding vectors based on the pre-trained word embeddings, the word indices need to be consistent. However, this is not possible if we perform another fit_on_texts on the test dataset.

Thank you and looking forward to your answers!


问:
Node.js or Express.js is server side language like PHP or not
Sorry, My question sounds dumb but i am bit confused about Node.js .I am a PHP developer and i know that php has operations and functions that execute on server and return result to client screen.

I want to ask in clear words, Do Node.js/Express.Js does the same as PHP does?
Do Node.js is for same work as php is?

should i move to Node.js from PHP (if both are for same purpose {mean back-end purpose})?

Which one is better choice in sense of Speed and security?

Which one has better scope in future?

Please help me in sorting out this confusion.

Please donot degrade my question.I a new in programming and answer in simple words as well...please please please.

Thanks.

答:
Nodejs

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it lightweight and efficient. Node.js' package ecosystem, npm, is the largest ecosystem of open source libraries in the world.

Express is a framework that is built on top of Nodejs

This is a popular content that compares Node and PHP.


问:
Updating the properties of an item
I'm attempting to use the Data Management API to update the display name of an item within BIM 360 Docs, it looks like this API call is the one I'm after, however the documentation for it is less than helpful.

I can see the call should be...

developer.api.autodesk.com/data/v1/projects/PROJECT ID/items/ITEM ID

which makes sense, its the body that is less than descriptive

-d '{ "jsonapi": { "version": "1.0" }, "data": { "type": "items", "id": "urn:adsk.wipprod:dm.lineage:AeYgDtcTSuqYoyMweWFhhQ", "attributes": { "displayName": "new name for drawing.dwg" } } }'

Theres no indication as to what the urn is and how i should go about getting it, I've tried just using the item ID again with no joy, if anyone could help me it would be much appreciated,

image of postman response

Thanks!

答:
The body should look like as following if you want to use PATCH request for BIM360 Docs:

```<code>               {
                    "jsonapi": {
                        "version": "1.0"
                    },
                    "data": {
                        "type": "items",
                        "id": "urn:adsk.wipprod:dm.lineage:ABCD",
                        "attributes": { "displayName": "new name for drawing.dwg" },
                        "relationships": {
                            "parent": {
                                "data": {
                                    "type": "folders",
                                    "id": "urn:adsk.wipprod:fs.folder:ABCD"
                                }
                            }
                        }
                    }
                }
</code>```

Additional pproperty is relatioinships which defines which folder to look at for the update.

Title: Updating the properties of an item

Body:
The body should look like as following if you want to use PATCH request for BIM360 Docs:

               {
                    "jsonapi": {
                        "version": "1.0"
                    },
                    "data": {
                        "type": "items",
                        "id": "urn:adsk.wipprod:dm.lineage:ABCD",
                        "attributes": { "displayName": "new name for drawing.dwg" },
                        "relationships": {
                            "parent": {
                                "data": {
                                    "type": "folders",
                                    "id": "urn:adsk.wipprod:fs.folder:ABCD"
                                }
                            }
                        }
                    }
                }

Additional pproperty is relatioinships which defines which folder to look at for the update.


问:
How to get id or name of iframe using javascript?
I have one iframe:

```<code><iframe id="frame" name="frame" src="test.html"></iframe>
</code>```

Now, I want to get id or name that iframe and alert it, I used:

```<code>if (document.getelementbyid('frame') = frame) alert('OK');
</code>```

But it doesn't work.

答:
```<code>var iframe = document.querySelector("iframe");

if(iframe .getAttribute("id") == "frame") {
   alert('iFrame has an ID called frame');
}
if(iframe .getAttribute("name") == "frame") {
   alert('The iFrame has a NAME called frame');
}
</code>```

Body:
I have one iframe:

Now, I want to get id or name that iframe and alert it, I used:

if (document.getelementbyid('frame') = frame) alert('OK');

But it doesn't work.


问:
sending out input events to windows
I am attempting to make a joystick driver via hidapi;  I would like to know how to send events to the os of any joystick activity.</p>

答: That all depends on your OS, as drivers are platform specific. Some IDEs like Visual Studio (Windows) provide templates for drivers which you can use, and a great deal of documentation about doing so.</p>

Title: sending out input events to windows


问:
JavaFx and Floating button
I have a problem with a GUI made in JavaFX, you can see the gui here.

As you can see there is a center pane with Cards and an action Button on the right bottom edge of the GUI, i realized this effect with this piece fo code

```<code>public class MainFrame extends BorderPane{

private Header header   = new Header();
private Sidebar sidebar = new Sidebar();
private GhostAbsolutePane ghostPaneWithPlay = new GhostAbsolutePane();
private HomePane homePane                      = new HomePane();

private final StackPane mainPane = new StackPane();

   public MainFrame() {
        mainPane.getStyleClass().add("main-stack-pane");
        mainPane.getChildren().addAll(homePane, ghostPaneWithPlay);

        this.setTop(header);
        this.setLeft(sidebar);
        this.setCenter(mainPane);
    }
}
</code>```

I have filled the center of the MainFrame with a StackPane where the first child contains a pane with the cards in a GridBagLayout and the second child is a generic pane made like that

```<code>public class GhostAbsolutePane extends Region{

    private Button run = new Button("");

    private double diameter = 56;

    public GhostAbsolutePane() {

        run.setMinWidth(diameter);
        run.setMaxWidth(diameter);

        run.setMinHeight(diameter);
        run.setMaxHeight(diameter);

        this.getChildren().add(run);

        this.setMouseTransparent(true);

        this.widthProperty().addListener((obs, oldVal, newVal)->{
            onResize();
        });

        this.heightProperty().addListener((obs, oldVal, newVal)->{
            onResize();
        });

    }

    private void onResize(){
        double h = getHeight();
        double w = getWidth();

        run.setTranslateX(w-diameter);
        run.setTranslateY(h-diameter);
    }
}
</code>```

The problem is simple. If I set to the pane ghostPaneWithPlay the setMouseTransparent property to true I can interact with the cards but I cannot hit the button; otherwise I can hit the button but cannot interact with the cards.

How can I avoid this unwanted behavior?

答:
If I understand you correctly, you are trying to place the “Play” button (the circular button with ▶) in the lower right corner.

You should not be using StackPane for this.  Just use a BorderPane, and let it handle the positioning:

```<code>private final BorderPane mainPane = new BorderPane();

// ...

    Button playButton = new Button("\u25b6");
    playButton.getStyleClass().add("play");

    mainPane.setCenter(homePane);
    HBox buttonPane = new HBox(12, playButton);
    buttonPane.setAlignment(Pos.CENTER_RIGHT);
    mainPane.setBottom(buttonPane);
</code>```

Title: JavaFx and Floating button

Body:
I have a problem with a GUI made in JavaFX, you can see the gui here.

As you can see there is a center pane with Cards and an action Button on the right bottom edge of the GUI, i realized this effect with this piece fo code

public class MainFrame extends BorderPane{

private Header header   = new Header();
private Sidebar sidebar = new Sidebar();
private GhostAbsolutePane ghostPaneWithPlay = new GhostAbsolutePane();
private HomePane homePane                      = new HomePane();

private final StackPane mainPane = new StackPane();

   public MainFrame() {
        mainPane.getStyleClass().add("main-stack-pane");
        mainPane.getChildren().addAll(homePane, ghostPaneWithPlay);

        this.setTop(header);
        this.setLeft(sidebar);
        this.setCenter(mainPane);
    }
}

I have filled the center of the MainFrame with a StackPane where the first child contains a pane with the cards in a GridBagLayout and the second child is a generic pane made like that

public class GhostAbsolutePane extends Region{

    private Button run = new Button("");

    private double diameter = 56;

    public GhostAbsolutePane() {

        run.setMinWidth(diameter);
        run.setMaxWidth(diameter);

        run.setMinHeight(diameter);
        run.setMaxHeight(diameter);

        this.getChildren().add(run);

        this.setMouseTransparent(true);

        this.widthProperty().addListener((obs, oldVal, newVal)->{
            onResize();
        });

        this.heightProperty().addListener((obs, oldVal, newVal)->{
            onResize();
        });

    }

    private void onResize(){
        double h = getHeight();
        double w = getWidth();

        run.setTranslateX(w-diameter);
        run.setTranslateY(h-diameter);
    }
}

The problem is simple. If I set to the pane ghostPaneWithPlay the setMouseTransparent property to true I can interact with the cards but I cannot hit the button; otherwise I can hit the button but cannot interact with the cards.

How can I avoid this unwanted behavior?

Body:
If I understand you correctly, you are trying to place the “Play” button (the circular button with ▶) in the lower right corner.

You should not be using StackPane for this.  Just use a BorderPane, and let it handle the positioning:

private final BorderPane mainPane = new BorderPane();

// ...

    Button playButton = new Button("\u25b6");
    playButton.getStyleClass().add("play");

    mainPane.setCenter(homePane);
    HBox buttonPane = new HBox(12, playButton);
    buttonPane.setAlignment(Pos.CENTER_RIGHT);
    mainPane.setBottom(buttonPane);


问:
AWS API Get Any Resource By ARN
I have a bunch AWS resource ARNs. I can easily write a switch/case statement on the namespace of the ARN and call the appropriate describeXYZ method on the correct AWS API class to get the resource details. But is there a way of taking any arbitrary ARN and getting a description for it? Something like aws.describeResource({arn:myArn}, callback)?

答:
I don't know what description exactly you are looking for, I don't know of the existence of such service. However, the ARN itself includes some information that could or could not be helpful to you, if you parse it, you could get at least:

Service

Region

Account ID

Type of Resource

Resource Name

For example

```<code>arn:aws:iot:us-west-2:27401367543654:policy/MyApplicationDefaultPolicy
         ^      ^          ^           ^                ^
         |      |          |           |                |
      Service Region   AccountID  ResourceType     ResourceName
</code>```

Sorry if this is not enough, is the best I can think of right now.

From here you can get a more detailed description:
http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-arns

```<code>arn:partition:service:region:account-id:resource
arn:partition:service:region:account-id:resourcetype/resource
arn:partition:service:region:account-id:resourcetype:resource
</code>```

Title: AWS API Get Any Resource By ARN

Body:
I don't know what description exactly you are looking for, I don't know of the existence of such service. However, the ARN itself includes some information that could or could not be helpful to you, if you parse it, you could get at least:

Service

Region

Account ID

Type of Resource

Resource Name

For example

arn:aws:iot:us-west-2:27401367543654:policy/MyApplicationDefaultPolicy
         ^      ^          ^           ^                ^
         |      |          |           |                |
      Service Region   AccountID  ResourceType     ResourceName

Sorry if this is not enough, is the best I can think of right now.

From here you can get a more detailed description:
http://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html#genref-arns

arn:partition:service:region:account-id:resource
arn:partition:service:region:account-id:resourcetype/resource
arn:partition:service:region:account-id:resourcetype:resource


问:
Jackson XML problems on Serializing
I'm having problems on serializing a list of Abstract object, jackson duplicates wrapper on tags.

Here are some results that I obtain :

```<code><visibility>
    <allowed/>
    <autoSubscribed>
        <autoSubscribed>
             <regex attribute="isMemberOf" pattern="\Qxertif\E"/>
        </autoSubscribed>
    </autoSubscribed>
    <obliged>
        <obliged>
            <regex attribute="isMemberOf" pattern="\QQadddsssss\E"/>
        </obliged>
        <obliged>
            <regex attribute="isMemberOf" pattern="\Qabcdef\E"/>
        </obliged>
    </obliged>
</visibility>
</code>```

or when i remove the @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, visible = true) from my abstract class i obtain :

```<code><visibility>
    <allowed/>
    <autoSubscribed>
        <autoSubscribed attribute="isMemberOf" pattern="\Qxertif\E"/>
    </autoSubscribed>
    <obliged>
        <obliged attribute="isMemberOf" pattern="\QQadddsssss\E"/>
        <obliged attribute="isMemberOf" pattern="\Qabcdef\E"/>
    </obliged>
</visibility>
</code>```

This is nearly good but i want the type in the tag.
something like :

```<code><visibility>
    <allowed/>
    <autoSubscribed>
        <regex attribute="isMemberOf" pattern="\Qxertif\E"/>
    </autoSubscribed>
    <obliged>
        <regex attribute="isMemberOf" pattern="\QQadddsssss\E"/>
        <regex attribute="isMemberOf" pattern="\Qabcdef\E"/>
    </obliged>
</visibility>
</code>```

Here are my objects :

```<code>@Data // from lombok
public class Visibility implements Serializable {

    private List<VisibilityAbstract> allowed = new ArrayList<>();

    private List<VisibilityAbstract> autoSubscribed = new ArrayList<>();

    private List<VisibilityAbstract> obliged = new ArrayList<>();

}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = VisibilityGroup.class, name = "group"),
    @JsonSubTypes.Type(value = VisibilityRegex.class, name = "regex"),
    @JsonSubTypes.Type(value = VisibilityRegular.class, name = "regular")
})
public abstract class VisibilityAbstract implements Serializable {
}

@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, visible = true)
@JsonTypeName(value = "group")
public class VisibilityGroup extends VisibilityAbstract implements Serializable {

    @NonNull
    @JacksonXmlProperty(isAttribute = true)
    private String name;

}
</code>```

All "extends" class have differents properties but are configured like VisibilityGroup.

I'm with spring boot 1.2.2 with jackson 2.4.6 and with woodstox 4.4.1.

On Json all is good, but not in XML.

Any idea on how to solve the problem ?

thanks

答:
This may help.</p>

```<code>JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper mapper = new XmlMapper(module);
</code>```

Title: Jackson XML problems on Serializing

Body:
I'm having problems on serializing a list of Abstract object, jackson duplicates wrapper on tags.

Here are some results that I obtain :

<visibility>
    <allowed/>
    <autoSubscribed>
        <autoSubscribed>
             <regex attribute="isMemberOf" pattern="\Qxertif\E"/>
        </autoSubscribed>
    </autoSubscribed>
    <obliged>
        <obliged>
            <regex attribute="isMemberOf" pattern="\QQadddsssss\E"/>
        </obliged>
        <obliged>
            <regex attribute="isMemberOf" pattern="\Qabcdef\E"/>
        </obliged>
    </obliged>
</visibility>

or when i remove the @JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, visible = true) from my abstract class i obtain :

<visibility>
    <allowed/>
    <autoSubscribed>
        <autoSubscribed attribute="isMemberOf" pattern="\Qxertif\E"/>
    </autoSubscribed>
    <obliged>
        <obliged attribute="isMemberOf" pattern="\QQadddsssss\E"/>
        <obliged attribute="isMemberOf" pattern="\Qabcdef\E"/>
    </obliged>
</visibility>

This is nearly good but i want the type in the tag.
something like :

<visibility>
    <allowed/>
    <autoSubscribed>
        <regex attribute="isMemberOf" pattern="\Qxertif\E"/>
    </autoSubscribed>
    <obliged>
        <regex attribute="isMemberOf" pattern="\QQadddsssss\E"/>
        <regex attribute="isMemberOf" pattern="\Qabcdef\E"/>
    </obliged>
</visibility>

Here are my objects :

@Data // from lombok
public class Visibility implements Serializable {

    private List<VisibilityAbstract> allowed = new ArrayList<>();

    private List<VisibilityAbstract> autoSubscribed = new ArrayList<>();

    private List<VisibilityAbstract> obliged = new ArrayList<>();

}

@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, visible = true)
@JsonSubTypes({
    @JsonSubTypes.Type(value = VisibilityGroup.class, name = "group"),
    @JsonSubTypes.Type(value = VisibilityRegex.class, name = "regex"),
    @JsonSubTypes.Type(value = VisibilityRegular.class, name = "regular")
})
public abstract class VisibilityAbstract implements Serializable {
}

@Data
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT, visible = true)
@JsonTypeName(value = "group")
public class VisibilityGroup extends VisibilityAbstract implements Serializable {

    @NonNull
    @JacksonXmlProperty(isAttribute = true)
    private String name;

}

All "extends" class have differents properties but are configured like VisibilityGroup.

I'm with spring boot 1.2.2 with jackson 2.4.6 and with woodstox 4.4.1.

On Json all is good, but not in XML.

Any idea on how to solve the problem ?

thanks

Body:
This may help.

JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper mapper = new XmlMapper(module);


问:
Passing an array to a collection
I am trying to pass an array to a collection, but I cannot seem to get the collection to populate.</p>

```<code>Public Function CreateCol(ws As Worksheet, ary, col As collection)
Dim rng As Range, collect As collection
Dim y, skey, svalue

    On Error Resume Next
    'populate fund list

    For y = LBound(ary) To UBound(ary)
        If ary(y) <> "" Then
            skey = Trim(ary(y))
            svalue = WorksheetFunction.SumIf(ws.Range("A:A"), ary(y), ws.Range("P:P"))
            collect.Add svalue, skey
        End If
    Next y

End Function
</code>```

答: As Mat's Mug said, make sure to set the collection to an object reference.  One way to do this is to put set collect = new collection before your for loop.

Title: Passing an array to a collection

Body:
I am trying to pass an array to a collection, but I cannot seem to get the collection to populate.

Public Function CreateCol(ws As Worksheet, ary, col As collection)
Dim rng As Range, collect As collection
Dim y, skey, svalue

    On Error Resume Next
    'populate fund list

    For y = LBound(ary) To UBound(ary)
        If ary(y) <> "" Then
            skey = Trim(ary(y))
            svalue = WorksheetFunction.SumIf(ws.Range("A:A"), ary(y), ws.Range("P:P"))
            collect.Add svalue, skey
        End If
    Next y

End Function


问:
iOS 11 - disable smart quotes
iOS 11 adds smart quotes when typing. In macOS we can disable smart quotes on a NSTextView by setting:

```<code>textView.automaticQuoteSubstitutionEnabled = NO;
</code>```

Neither UITextField or UITextView seem to have this property or the enabledTextCheckingTypes property. How can smart quotes be disabled on iOS 11?

答:
Smart quotes and other features such as smart dashes are controlled via the UITextInputTraits Protocol which is adopted by both UITextField and UITextView.

Specifically, the smartQuotesType property can be set to one of .default, .yes or .no. At this time there is no further documentation on these values, but .yes and .no are self-explanatory. My guess on .default is that the system will use properties such as textContentType and isSecureTextEntry to determine the appropriate behaviour.

For example a text content type of email, password or URL would probably disable smart quotes by default while job title may default to enabled. I imagine secure text entry fields would also have smarts disabled by default.

Setting an appropriate text content type for your input views can significantly improve the user experience and is highly recommended.

Title: iOS 11 - disable smart quotes

Body:
iOS 11 adds smart quotes when typing. In macOS we can disable smart quotes on a NSTextView by setting:

textView.automaticQuoteSubstitutionEnabled = NO;

Neither UITextField or UITextView seem to have this property or the enabledTextCheckingTypes property. How can smart quotes be disabled on iOS 11?


问:
Ionic 3 - POST Data to Heroku Endpoint
so I have a back-end service running on Heroku at the endpoint https://sample.herokuapp.com/. I am trying to POST the following JSON object to the /bug/ endpoint:

```<code>{
    "email": "email@gmail.com",
    "name": "Anthony",
    "text": "Test Bug",
    "picture": "Empty"
}
</code>```

If I POST this data in Insomnia or Postman, it works perfectly and returns an HTML response with the parsed information. However, when I POST this data using the following code in Ionic 3,

```<code>sendMail(type:string, text:string):void {
            this.nativeStorage.getItem('sample').then((sample) => {
                  var data = new Object();
                  data["name"] = sample.name
                  data["email"] = sample.email;
                  data["picture"] = sample.picture;
                  data["text"] = text;

                  this.db.object('/general/sample').take(1).subscribe((sample) => {
                        var xhr = new XMLHttpRequest();
                        var endpoint = sample.address + sample.endpoints[type];

                        xhr.addEventListener("readystatechange", function () {
                        if (this.readyState === 4) {
                            console.log("Got response: " + this.responseText);
                        }
                    });

                        xhr.open("POST", endpoint);
                        xhr.setRequestHeader("Accept", "application/json");
                    xhr.setRequestHeader("Content-Type", "application/json");
                        console.log("sample sending: " + JSON.stringify(data, undefined, 2));
                        console.log("sample endpoint: " + endpoint);

                    xhr.send(JSON.stringify(data));
                  })
            })
    }
</code>```

I received the following error log in Heroku:

```<code>2017-07-05T17:02:24.707431+00:00 heroku[router]: at=info method=OPTIONS path="/bug" host=sample.herokuapp.com request_id=5e679c8e-cac7-4ff2-9277-dec80a250c11 fwd="150.108.242.198" dyno=web.1 connect=1ms service=3ms status=200 bytes=215 protocol=https
</code>```

I have done much research on this issue, and I believe this is a CORS issue. However, I have tried using the Access-Control-Allow-... headers to solve this issue, but have been receiving the same errors.

I have installed the Cordova whitelist plugin and included the meta tag to my index.html.

This is a pretty complicated issue, so I appreciate all the help!

答:
On the heroku side do you have cors configured?

```<code> var app = express();
 /* cors conig */
 var corOptions = {
     "origin": "*",
     "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
     "preflightContinue": true,
     allowedHeaders:  'Content-Type,Authorization,X-Requested-With'
 }
 app.use(cors(corOptions));
</code>```

my cors dependency: "cors": "^2.8.1"

Title: Ionic 3 - POST Data to Heroku Endpoint

Body:
so I have a back-end service running on Heroku at the endpoint https://sample.herokuapp.com/. I am trying to POST the following JSON object to the /bug/ endpoint:

{
    "email": "email@gmail.com",
    "name": "Anthony",
    "text": "Test Bug",
    "picture": "Empty"
}

If I POST this data in Insomnia or Postman, it works perfectly and returns an HTML response with the parsed information. However, when I POST this data using the following code in Ionic 3,

sendMail(type:string, text:string):void {
            this.nativeStorage.getItem('sample').then((sample) => {
                  var data = new Object();
                  data["name"] = sample.name
                  data["email"] = sample.email;
                  data["picture"] = sample.picture;
                  data["text"] = text;

                  this.db.object('/general/sample').take(1).subscribe((sample) => {
                        var xhr = new XMLHttpRequest();
                        var endpoint = sample.address + sample.endpoints[type];

                        xhr.addEventListener("readystatechange", function () {
                        if (this.readyState === 4) {
                            console.log("Got response: " + this.responseText);
                        }
                    });

                        xhr.open("POST", endpoint);
                        xhr.setRequestHeader("Accept", "application/json");
                    xhr.setRequestHeader("Content-Type", "application/json");
                        console.log("sample sending: " + JSON.stringify(data, undefined, 2));
                        console.log("sample endpoint: " + endpoint);

                    xhr.send(JSON.stringify(data));
                  })
            })
    }

I received the following error log in Heroku:

2017-07-05T17:02:24.707431+00:00 heroku[router]: at=info method=OPTIONS path="/bug" host=sample.herokuapp.com request_id=5e679c8e-cac7-4ff2-9277-dec80a250c11 fwd="150.108.242.198" dyno=web.1 connect=1ms service=3ms status=200 bytes=215 protocol=https

I have done much research on this issue, and I believe this is a CORS issue. However, I have tried using the Access-Control-Allow-... headers to solve this issue, but have been receiving the same errors.

I have installed the Cordova whitelist plugin and included the meta tag to my index.html.

This is a pretty complicated issue, so I appreciate all the help!

Body:
On the heroku side do you have cors configured?

 var app = express();
 /* cors conig */
 var corOptions = {
     "origin": "*",
     "methods": "GET,HEAD,PUT,PATCH,POST,DELETE",
     "preflightContinue": true,
     allowedHeaders:  'Content-Type,Authorization,X-Requested-With'
 }
 app.use(cors(corOptions));

my cors dependency: "cors": "^2.8.1"


问:
Multiplying the values in two columns: TypeError: can't multiply sequence by non-int of type 'float'
I am trying to multiply the values in two separate columns

The type of the elements in the first column is 'numpy.float64'

That of the second column is 'float'

When I do

```<code>new_column = df['first_column'] * df['second column']
</code>```

I get

'TypeError: can't multiply sequence by non-int of type 'float'

I don't really understand why I cannot multiply the values of numpy.float64 and float. Aren't they similar to each other and multipliable?

答:
You could try unsafe casting like so:</p>

```<code>numpy.multiply(A, B, out=A, casting='unsafe')
</code>```

Body:
I am trying to multiply the values in two separate columns

The type of the elements in the first column is 'numpy.float64'

That of the second column is 'float'

When I do

new_column = df['first_column'] * df['second column']

I get

'TypeError: can't multiply sequence by non-int of type 'float'

I don't really understand why I cannot multiply the values of numpy.float64 and float. Aren't they similar to each other and multipliable?

Body:
You could try unsafe casting like so:

numpy.multiply(A, B, out=A, casting='unsafe')


问:
If I restart the Rest server, H2 database reset
I used file db as below:

```<code>spring.datasource.url=jdbc:h2:file:./data/meet
</code>```

And I can find file "meet.mv.db" in my working directory.

If I add tuples to the file and restart the server, the size of the file increases.
However, I cannot get what is inside the file after restarting.
That means there is no persistency at all.

Can anyone help me to find how to obtain persistency?

In case you need my source code:
https://github.com/jihunim/meet_n_eat_server

答:
I ran into a similar problem and I discovered it was because I had this property set in the persistence.xml file:

```<code><property name="hibernate.hbm2ddl.auto" value="create-drop" />
</code>```

Removing this line fixed the issue and data was still there after server restart.

Body:
I used file db as below:

spring.datasource.url=jdbc:h2:file:./data/meet

And I can find file "meet.mv.db" in my working directory.

If I add tuples to the file and restart the server, the size of the file increases.
However, I cannot get what is inside the file after restarting.
That means there is no persistency at all.

Can anyone help me to find how to obtain persistency?

In case you need my source code:
https://github.com/jihunim/meet_n_eat_server

Body:
I ran into a similar problem and I discovered it was because I had this property set in the persistence.xml file:

<property name="hibernate.hbm2ddl.auto" value="create-drop" />

Removing this line fixed the issue and data was still there after server restart.


问:
What would be equivalent of pytorch's torch.nn.CosineEmbeddingLoss in tensorflow?
CosineEmbeddingLoss in Pytorch is the perfect function I am looking for in tensorflow, but I can only find tf.losses.cosine_distance. Is there a way or code that writes CosineEmbeddingLoss in tensorflow?</p>

答:
A TensorFlow version of CosineEmbeddingLoss:

```<code>import tensorflow as tf
from tensorflow import keras

cosine_similarity_loss = keras.losses.CosineSimilarity(
    reduction='none'
)

# target variable can be also passed along with margin
# it can be either target=1 or target = -1
# by this, CosineEmbeddingLoss methoc can be used
# inside the `model.compile` with ease.
def CosineEmbeddingLoss(margin=0.):
    def cosine_embedding_loss_fn(input_one, input_two, target):
        similarity = - cosine_similarity_loss(input_one, input_two)
        return tf.reduce_mean(
            tf.where(
                tf.equal(target, 1),
                1. - similarity,
                tf.maximum(
                    tf.zeros_like(similarity), similarity - margin
                )
            )
        )
    return cosine_embedding_loss_fn
</code>```

Running it alongside Torch's version:

```<code>import numpy as np
import torch
from torch.autograd import Variable

first_values = numpy.random.normal(size=[100, 3])
second_values = numpy.random.normal(size=[100, 3])
labels = numpy.random.randint(2, size=[100]) * 2 - 1

torch_result = torch.nn.CosineEmbeddingLoss(margin=0.5)(
    Variable(torch.FloatTensor(first_values)),
    Variable(torch.FloatTensor(second_values)),
    Variable(torch.IntTensor(labels))
).data.numpy()

tf_result = CosineEmbeddingLoss(margin=0.5)(
    first_values, second_values, labels
).numpy()

print(torch_result, tf_result)
</code>```

Seems to match to within reasonable precision:

```<code>0.58433354 0.5843335801639801
</code>```

Body:
A TensorFlow version of CosineEmbeddingLoss:

import tensorflow as tf
from tensorflow import keras

cosine_similarity_loss = keras.losses.CosineSimilarity(
    reduction='none'
)

# target variable can be also passed along with margin
# it can be either target=1 or target = -1
# by this, CosineEmbeddingLoss methoc can be used
# inside the `model.compile` with ease.
def CosineEmbeddingLoss(margin=0.):
    def cosine_embedding_loss_fn(input_one, input_two, target):
        similarity = - cosine_similarity_loss(input_one, input_two)
        return tf.reduce_mean(
            tf.where(
                tf.equal(target, 1),
                1. - similarity,
                tf.maximum(
                    tf.zeros_like(similarity), similarity - margin
                )
            )
        )
    return cosine_embedding_loss_fn

Running it alongside Torch's version:

import numpy as np
import torch
from torch.autograd import Variable

first_values = numpy.random.normal(size=[100, 3])
second_values = numpy.random.normal(size=[100, 3])
labels = numpy.random.randint(2, size=[100]) * 2 - 1

torch_result = torch.nn.CosineEmbeddingLoss(margin=0.5)(
    Variable(torch.FloatTensor(first_values)),
    Variable(torch.FloatTensor(second_values)),
    Variable(torch.IntTensor(labels))
).data.numpy()

tf_result = CosineEmbeddingLoss(margin=0.5)(
    first_values, second_values, labels
).numpy()

print(torch_result, tf_result)

Seems to match to within reasonable precision:

0.58433354 0.5843335801639801

ContentLicense: CC BY-SA 4.0


问:
How to get current rule name into outlook VBA
Does anyone know how to parse the current rule name into outlook VBA

For example take the code below

The line(s) at the end could either use a number in the colrules.item statement, which will return the rule specified by the number, or you could be explicit if you knew the name of the rule so in the example if you knew the rule was called "My Rule" you could call that

However I don't want either of those, I want to return the name of the current rule that has called this piece of script when I don't know either the name of the rule or its index number

```<code>Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
    Dim orule As Outlook.Rule 'this will be the specific rule
    Dim colrules As Outlook.Rules 'this will be the collection of rules, this is needed first to choose the specific rule from
      'Firstly we will get the current rule into our script so we can use the rule name to parse the vendor account into the filename
    Set colrules = Application.Session.DefaultStore.GetRules() ' get the collection of rules
    ' choose the specific rule that called this script
   Stop
    Set orule = colrules.Item(1)
Set orule = colrules.Item("My Rule")
</code>```

答: Unfortunately there is no way to determine the current rule, or when certain rules have fired.</p>

Body:
Does anyone know how to parse the current rule name into outlook VBA

For example take the code below

The line(s) at the end could either use a number in the colrules.item statement, which will return the rule specified by the number, or you could be explicit if you knew the name of the rule so in the example if you knew the rule was called "My Rule" you could call that

However I don't want either of those, I want to return the name of the current rule that has called this piece of script when I don't know either the name of the rule or its index number

Public Sub saveAttachtoDisk(itm As Outlook.MailItem)
Dim objAtt As Outlook.Attachment
    Dim orule As Outlook.Rule 'this will be the specific rule
    Dim colrules As Outlook.Rules 'this will be the collection of rules, this is needed first to choose the specific rule from
      'Firstly we will get the current rule into our script so we can use the rule name to parse the vendor account into the filename
    Set colrules = Application.Session.DefaultStore.GetRules() ' get the collection of rules
    ' choose the specific rule that called this script
   Stop
    Set orule = colrules.Item(1)
Set orule = colrules.Item("My Rule")


问:
open an activity from a CordovaPlugin
I have written a CordavaPlugin derived class.

```<code>public class ShowMap extends CordovaPlugin {

@Override
public boolean execute(String action, JSONArray args,
        CallbackContext callbackContext) throws JSONException {

    if (action.compareTo("showMap") == 0)
    {
        String message = args.getString(0);
        this.echo(message, callbackContext);

        Intent i = new Intent();

        return true;
    }

    return false;
}

private void echo(String message, CallbackContext callbackContext) {
    if (message != null && message.length() > 0) {
        callbackContext.success(message);
    } else {
        callbackContext.error("Expected one non-empty string argument.");
    }
}

}
</code>```

I want from this class to open a new activity.
How do I get access to the original context of the phonegap based class?

答:
Post now in 2017, because it's the top-ranked google search result for "cordova plugin activity" and top-voted answer, along with Cordova plugin guide are both missing the following critical information, that took me many hours to figure out... the parent attrib of config-file and the specific code:

Added to plugin.xml, customized according to your needs:

```<code><!-- separate config-file here targeting AndroidManifest with parent NOT equal to /* -->
<config-file target="AndroidManifest.xml"
    parent="/manifest/application">
    <activity
        android:name=com.custompackage.MyCustomActivity">
    </activity>
</config-file>
</code>```

Updating launching code with above package & activity:

```<code>Context context=this.cordova.getActivity().getApplicationContext();
//or Context context=cordova.getActivity().getApplicationContext();
Intent intent=new Intent(context, com.custompackage.MyCustomActivity.class);

context.startActivity(intent);
//or cordova.getActivity().startActivity(intent);
</code>```

Title: open an activity from a CordovaPlugin

Body:
I have written a CordavaPlugin derived class.

public class ShowMap extends CordovaPlugin {

@Override
public boolean execute(String action, JSONArray args,
        CallbackContext callbackContext) throws JSONException {

    if (action.compareTo("showMap") == 0)
    {
        String message = args.getString(0);
        this.echo(message, callbackContext);

        Intent i = new Intent();

        return true;
    }

    return false;
}

private void echo(String message, CallbackContext callbackContext) {
    if (message != null && message.length() > 0) {
        callbackContext.success(message);
    } else {
        callbackContext.error("Expected one non-empty string argument.");
    }
}

}

I want from this class to open a new activity.
How do I get access to the original context of the phonegap based class?

Body:
Post now in 2017, because it's the top-ranked google search result for "cordova plugin activity" and top-voted answer, along with Cordova plugin guide are both missing the following critical information, that took me many hours to figure out... the parent attrib of config-file and the specific code:

Added to plugin.xml, customized according to your needs:

<!-- separate config-file here targeting AndroidManifest with parent NOT equal to /* -->
<config-file target="AndroidManifest.xml"
    parent="/manifest/application">
    <activity
        android:name=com.custompackage.MyCustomActivity">
    </activity>
</config-file>

Updating launching code with above package & activity:

Context context=this.cordova.getActivity().getApplicationContext();
//or Context context=cordova.getActivity().getApplicationContext();
Intent intent=new Intent(context, com.custompackage.MyCustomActivity.class);

context.startActivity(intent);
//or cordova.getActivity().startActivity(intent);


问:
Using ScrollView Programmatically in Swift 3
I have searched other questions and seem to still have some trouble creating my scrollView programmatically with autolayout in swift 3. I am able to get my scrollview to show up as shown in the picture below, but when I scroll to the bottom my other label does not show up and the 'scroll top' label does not disappear.

Hoping someone can help review my code below!

```<code>import UIKit

class ViewController: UIViewController {

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    scrollView.addSubview(labelOne)
    scrollView.addSubview(labelTwo)

    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    view.addSubview(scrollView)

    // Visual Format Constraints
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))

    // Using iOS 9 Constraints in order to place the label past the iPhone 7 view
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: labelOne, attribute: .bottom, multiplier: 1, constant: screenHeight + 200))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .right, relatedBy: .equal, toItem: labelOne, attribute: .right, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .left, relatedBy: .equal, toItem: labelOne, attribute: .left, multiplier: 1, constant: 0)

    }

}
</code>```

答:
It is easy to use constraints to define the scroll content size - so you don't have to do any manual calculations.

Just remember:

The content elements of your scroll view must have left / top / width / height values. In the case of objects such as labels, they have intrinsic sizes, so you only have to define the left & top.

The content elements of your scroll view also define the bounds of the scrollable area - the contentSize - but they do so with the bottom & right constraints.

Combining those two concepts, you see that you need a "continuous chain" with at least one element defining the top / left / bottom / right extents.

Here is a simple example, that will run directly in a Playground page:

```<code>import UIKit
import PlaygroundSupport

class TestViewController : UIViewController {

    let labelOne: UILabel = {
        let label = UILabel()
        label.text = "Scroll Top"
        label.backgroundColor = .red
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let labelTwo: UILabel = {
        let label = UILabel()
        label.text = "Scroll Bottom"
        label.backgroundColor = .green
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let scrollView: UIScrollView = {
        let v = UIScrollView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the scroll view to self.view
        self.view.addSubview(scrollView)

        // constrain the scroll view to 8-pts on each side
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 8.0).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 8.0).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -8.0).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -8.0).isActive = true

        // add labelOne to the scroll view
        scrollView.addSubview(labelOne)

        // constrain labelOne to left & top with 16-pts padding
        // this also defines the left & top of the scroll content
        labelOne.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 16.0).isActive = true
        labelOne.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 16.0).isActive = true

        // add labelTwo to the scroll view
        scrollView.addSubview(labelTwo)

        // constrain labelTwo at 400-pts from the left
        labelTwo.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 400.0).isActive = true

        // constrain labelTwo at 1000-pts from the top
        labelTwo.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 1000).isActive = true

        // constrain labelTwo to right & bottom with 16-pts padding
        labelTwo.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -16.0).isActive = true
        labelTwo.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -16.0).isActive = true

    }

}

let vc = TestViewController()
vc.view.backgroundColor = .yellow
PlaygroundPage.current.liveView = vc
</code>```

Edit - since this answer still gets occasional attention, I've updated the code to use more modern syntax, to respect the safe-area, and to use the scroll view's .contentLayoutGuide:

```<code>class TestViewController : UIViewController {

    let labelOne: UILabel = {
        let label = UILabel()
        label.text = "Scroll Top"
        label.backgroundColor = .yellow
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let labelTwo: UILabel = {
        let label = UILabel()
        label.text = "Scroll Bottom"
        label.backgroundColor = .green
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let scrollView: UIScrollView = {
        let v = UIScrollView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the scroll view to self.view
        self.view.addSubview(scrollView)

        // add labelOne to the scroll view
        scrollView.addSubview(labelOne)

        // add labelTwo to the scroll view
        scrollView.addSubview(labelTwo)

        // always a good idea to respect safe area
        let safeG = view.safeAreaLayoutGuide

        // we want to constrain subviews to the scroll view's Content Layout Guide
        let contentG = scrollView.contentLayoutGuide

        NSLayoutConstraint.activate([

            // constrain the scroll view to safe area with 8-pts on each side
            scrollView.topAnchor.constraint(equalTo: safeG.topAnchor, constant: 8.0),
            scrollView.leadingAnchor.constraint(equalTo: safeG.leadingAnchor, constant: 8.0),
            scrollView.trailingAnchor.constraint(equalTo: safeG.trailingAnchor, constant: -8.0),
            scrollView.bottomAnchor.constraint(equalTo: safeG.bottomAnchor, constant: -8.0),

            // constrain labelOne to leading & top of Content Layout Guide with 16-pts padding
            // this also defines the left & top of the scroll content
            labelOne.topAnchor.constraint(equalTo: contentG.topAnchor, constant: 16.0),
            labelOne.leadingAnchor.constraint(equalTo: contentG.leadingAnchor, constant: 16.0),

            // constrain labelTwo leading at 400-pts from labelOne trailing
            labelTwo.leadingAnchor.constraint(equalTo: labelOne.trailingAnchor, constant: 400.0),

            // constrain labelTwo top at 1000-pts from the labelOne bottom
            labelTwo.topAnchor.constraint(equalTo: labelOne.bottomAnchor, constant: 1000),

            // constrain labelTwo to trailing & bottom of Content Layout Guide with 16-pts padding
            // this also defines the right & bottom of the scroll content
            labelTwo.trailingAnchor.constraint(equalTo: contentG.trailingAnchor, constant: -16.0),
            labelTwo.bottomAnchor.constraint(equalTo: contentG.bottomAnchor, constant: -16.0),

        ])

    }

}
</code>```

Body:
I have searched other questions and seem to still have some trouble creating my scrollView programmatically with autolayout in swift 3. I am able to get my scrollview to show up as shown in the picture below, but when I scroll to the bottom my other label does not show up and the 'scroll top' label does not disappear.

Hoping someone can help review my code below!

import UIKit

class ViewController: UIViewController {

let labelOne: UILabel = {
    let label = UILabel()
    label.text = "Scroll Top"
    label.backgroundColor = .red
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

let labelTwo: UILabel = {
    let label = UILabel()
    label.text = "Scroll Bottom"
    label.backgroundColor = .green
    label.translatesAutoresizingMaskIntoConstraints = false
    return label
}()

override func viewDidLoad() {
    super.viewDidLoad()

    let screensize: CGRect = UIScreen.main.bounds
    let screenWidth = screensize.width
    let screenHeight = screensize.height
    var scrollView: UIScrollView!
    scrollView = UIScrollView(frame: CGRect(x: 0, y: 120, width: screenWidth, height: screenHeight))
    scrollView.contentSize = CGSize(width: screenWidth, height: 2000)
    scrollView.addSubview(labelOne)
    scrollView.addSubview(labelTwo)

    view.addSubview(labelOne)
    view.addSubview(labelTwo)
    view.addSubview(scrollView)

    // Visual Format Constraints
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))
    view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-100-[v0]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": labelOne]))

    // Using iOS 9 Constraints in order to place the label past the iPhone 7 view
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .top, relatedBy: .equal, toItem: labelOne, attribute: .bottom, multiplier: 1, constant: screenHeight + 200))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .right, relatedBy: .equal, toItem: labelOne, attribute: .right, multiplier: 1, constant: 0))
    view.addConstraint(NSLayoutConstraint(item: labelTwo, attribute: .left, relatedBy: .equal, toItem: labelOne, attribute: .left, multiplier: 1, constant: 0)

    }

}

Body:
It is easy to use constraints to define the scroll content size - so you don't have to do any manual calculations.

Just remember:

The content elements of your scroll view must have left / top / width / height values. In the case of objects such as labels, they have intrinsic sizes, so you only have to define the left & top.

The content elements of your scroll view also define the bounds of the scrollable area - the contentSize - but they do so with the bottom & right constraints.

Combining those two concepts, you see that you need a "continuous chain" with at least one element defining the top / left / bottom / right extents.

Here is a simple example, that will run directly in a Playground page:

import UIKit
import PlaygroundSupport

class TestViewController : UIViewController {

    let labelOne: UILabel = {
        let label = UILabel()
        label.text = "Scroll Top"
        label.backgroundColor = .red
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let labelTwo: UILabel = {
        let label = UILabel()
        label.text = "Scroll Bottom"
        label.backgroundColor = .green
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let scrollView: UIScrollView = {
        let v = UIScrollView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the scroll view to self.view
        self.view.addSubview(scrollView)

        // constrain the scroll view to 8-pts on each side
        scrollView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 8.0).isActive = true
        scrollView.topAnchor.constraint(equalTo: view.topAnchor, constant: 8.0).isActive = true
        scrollView.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -8.0).isActive = true
        scrollView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -8.0).isActive = true

        // add labelOne to the scroll view
        scrollView.addSubview(labelOne)

        // constrain labelOne to left & top with 16-pts padding
        // this also defines the left & top of the scroll content
        labelOne.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 16.0).isActive = true
        labelOne.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 16.0).isActive = true

        // add labelTwo to the scroll view
        scrollView.addSubview(labelTwo)

        // constrain labelTwo at 400-pts from the left
        labelTwo.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor, constant: 400.0).isActive = true

        // constrain labelTwo at 1000-pts from the top
        labelTwo.topAnchor.constraint(equalTo: scrollView.topAnchor, constant: 1000).isActive = true

        // constrain labelTwo to right & bottom with 16-pts padding
        labelTwo.rightAnchor.constraint(equalTo: scrollView.rightAnchor, constant: -16.0).isActive = true
        labelTwo.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor, constant: -16.0).isActive = true

    }

}

let vc = TestViewController()
vc.view.backgroundColor = .yellow
PlaygroundPage.current.liveView = vc

Edit - since this answer still gets occasional attention, I've updated the code to use more modern syntax, to respect the safe-area, and to use the scroll view's .contentLayoutGuide:

class TestViewController : UIViewController {

    let labelOne: UILabel = {
        let label = UILabel()
        label.text = "Scroll Top"
        label.backgroundColor = .yellow
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let labelTwo: UILabel = {
        let label = UILabel()
        label.text = "Scroll Bottom"
        label.backgroundColor = .green
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()

    let scrollView: UIScrollView = {
        let v = UIScrollView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.backgroundColor = .cyan
        return v
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        // add the scroll view to self.view
        self.view.addSubview(scrollView)

        // add labelOne to the scroll view
        scrollView.addSubview(labelOne)

        // add labelTwo to the scroll view
        scrollView.addSubview(labelTwo)

        // always a good idea to respect safe area
        let safeG = view.safeAreaLayoutGuide

        // we want to constrain subviews to the scroll view's Content Layout Guide
        let contentG = scrollView.contentLayoutGuide

        NSLayoutConstraint.activate([

            // constrain the scroll view to safe area with 8-pts on each side
            scrollView.topAnchor.constraint(equalTo: safeG.topAnchor, constant: 8.0),
            scrollView.leadingAnchor.constraint(equalTo: safeG.leadingAnchor, constant: 8.0),
            scrollView.trailingAnchor.constraint(equalTo: safeG.trailingAnchor, constant: -8.0),
            scrollView.bottomAnchor.constraint(equalTo: safeG.bottomAnchor, constant: -8.0),

            // constrain labelOne to leading & top of Content Layout Guide with 16-pts padding
            // this also defines the left & top of the scroll content
            labelOne.topAnchor.constraint(equalTo: contentG.topAnchor, constant: 16.0),
            labelOne.leadingAnchor.constraint(equalTo: contentG.leadingAnchor, constant: 16.0),

            // constrain labelTwo leading at 400-pts from labelOne trailing
            labelTwo.leadingAnchor.constraint(equalTo: labelOne.trailingAnchor, constant: 400.0),

            // constrain labelTwo top at 1000-pts from the labelOne bottom
            labelTwo.topAnchor.constraint(equalTo: labelOne.bottomAnchor, constant: 1000),

            // constrain labelTwo to trailing & bottom of Content Layout Guide with 16-pts padding
            // this also defines the right & bottom of the scroll content
            labelTwo.trailingAnchor.constraint(equalTo: contentG.trailingAnchor, constant: -16.0),
            labelTwo.bottomAnchor.constraint(equalTo: contentG.bottomAnchor, constant: -16.0),

        ])

    }

}