问:
Integrate a floating action button into linear layout with toolbar
I have the following RecyclerView to which I want to I add a floating action button. but the problem is the floating action button is separate from the RecyclerView part (it's divide the screen to two parts).

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayoutandroid:id="@+id/swifeRefresh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto">

<LinearLayout

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<android.support.v7.widget.Toolbar
    android:id="@+id/toolBar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"/>

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    />

<com.github.clans.fab.FloatingActionMenu
    android:id="@+id/material_design_android_floating_action_menu"
    android:layout_width="match_parent"
    android:layout_height="244dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="11dp"
    android:layout_marginLeft="11dp"
    android:layout_marginRight="11dp"
    fab:menu_animationDelayPerItem="55"
    fab:menu_backgroundColor="@android:color/transparent"
    fab:menu_buttonSpacing="0dp"
    fab:menu_colorNormal="#da3c2f"
    fab:menu_colorPressed="#dc4b3f"
    fab:menu_colorRipple="#99d4d4d4"
    fab:menu_fab_label="Floating Action Menu"
    fab:menu_fab_size="normal"
    fab:menu_icon="@drawable/fab_add"
    fab:menu_labels_colorNormal="#333"
    fab:menu_labels_colorPressed="#444"
    fab:menu_labels_colorRipple="#66efecec"
    fab:menu_labels_cornerRadius="3dp"
    fab:menu_labels_ellipsize="none"
    fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
    fab:menu_labels_margin="0dp"
    fab:menu_labels_maxLines="-1"
    fab:menu_labels_padding="8dp"
    fab:menu_labels_position="left"
    fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
    fab:menu_labels_showShadow="true"
    fab:menu_labels_singleLine="false"
    fab:menu_labels_textColor="#f2f1f1"
    fab:menu_labels_textSize="15sp"
    fab:menu_openDirection="up"
    fab:menu_shadowColor="#66aff198"
    fab:menu_shadowRadius="4dp"
    fab:menu_shadowXOffset="1dp"
    fab:menu_shadowYOffset="4dp"
    fab:menu_showShadow="true">

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/material_design_floating_action_menu_item1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_24dp"
        fab:fab_label="Menu Item 1"
        fab:fab_size="mini" />

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/material_design_floating_action_menu_item2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_24dp"
        fab:fab_label="Menu Item 2"
        fab:fab_size="mini" />

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/material_design_floating_action_menu_item3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_24dp"
        fab:fab_label="Menu Item 3"
        fab:fab_size="mini" />
</com.github.clans.fab.FloatingActionMenu>

</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

I would love if someone can help me to fix this problem. Thanks.

答:
Just add another RelativeLayout below ToolBar and place both RecyclerView & com.github.clans.fab.FloatingActionMenu inside RelativeLayout.

Also change your RecyclerView as below:

```<code><android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</code>```

Here is the complete working code. Try this:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swifeRefresh"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolBar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <com.github.clans.fab.FloatingActionMenu
                android:id="@+id/material_design_android_floating_action_menu"
                android:layout_width="match_parent"
                android:layout_height="244dp"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:layout_marginBottom="11dp"
                android:layout_marginLeft="11dp"
                android:layout_marginRight="11dp"
                fab:menu_animationDelayPerItem="55"
                fab:menu_backgroundColor="@android:color/transparent"
                fab:menu_buttonSpacing="0dp"
                fab:menu_colorNormal="#da3c2f"
                fab:menu_colorPressed="#dc4b3f"
                fab:menu_colorRipple="#99d4d4d4"
                fab:menu_fab_label="Floating Action Menu"
                fab:menu_fab_size="normal"
                fab:menu_icon="@drawable/fab_add"
                fab:menu_labels_colorNormal="#333"
                fab:menu_labels_colorPressed="#444"
                fab:menu_labels_colorRipple="#66efecec"
                fab:menu_labels_cornerRadius="3dp"
                fab:menu_labels_ellipsize="none"
                fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
                fab:menu_labels_margin="0dp"
                fab:menu_labels_maxLines="-1"
                fab:menu_labels_padding="8dp"
                fab:menu_labels_position="left"
                fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
                fab:menu_labels_showShadow="true"
                fab:menu_labels_singleLine="false"
                fab:menu_labels_textColor="#f2f1f1"
                fab:menu_labels_textSize="15sp"
                fab:menu_openDirection="up"
                fab:menu_shadowColor="#66aff198"
                fab:menu_shadowRadius="4dp"
                fab:menu_shadowXOffset="1dp"
                fab:menu_shadowYOffset="4dp"
                fab:menu_showShadow="true">

                <com.github.clans.fab.FloatingActionButton
                    android:id="@+id/material_design_floating_action_menu_item1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/icon_refresh"
                    fab:fab_label="Menu Item 1"
                    fab:fab_size="mini" />

                <com.github.clans.fab.FloatingActionButton
                    android:id="@+id/material_design_floating_action_menu_item2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/icon_refresh"
                    fab:fab_label="Menu Item 2"
                    fab:fab_size="mini" />

                <com.github.clans.fab.FloatingActionButton
                    android:id="@+id/material_design_floating_action_menu_item3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/icon_refresh"
                    fab:fab_label="Menu Item 3"
                    fab:fab_size="mini" />
            </com.github.clans.fab.FloatingActionMenu>
        </RelativeLayout>
    </LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>
</code>```

OUTPUT:

Hope this will help~

Body:
I have the following RecyclerView to which I want to I add a floating action button. but the problem is the floating action button is separate from the RecyclerView part (it's divide the screen to two parts).

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayoutandroid:id="@+id/swifeRefresh"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:fab="http://schemas.android.com/apk/res-auto">

<LinearLayout

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>

<android.support.v7.widget.Toolbar
    android:id="@+id/toolBar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="@color/colorPrimary"/>

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    />

<com.github.clans.fab.FloatingActionMenu
    android:id="@+id/material_design_android_floating_action_menu"
    android:layout_width="match_parent"
    android:layout_height="244dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="11dp"
    android:layout_marginLeft="11dp"
    android:layout_marginRight="11dp"
    fab:menu_animationDelayPerItem="55"
    fab:menu_backgroundColor="@android:color/transparent"
    fab:menu_buttonSpacing="0dp"
    fab:menu_colorNormal="#da3c2f"
    fab:menu_colorPressed="#dc4b3f"
    fab:menu_colorRipple="#99d4d4d4"
    fab:menu_fab_label="Floating Action Menu"
    fab:menu_fab_size="normal"
    fab:menu_icon="@drawable/fab_add"
    fab:menu_labels_colorNormal="#333"
    fab:menu_labels_colorPressed="#444"
    fab:menu_labels_colorRipple="#66efecec"
    fab:menu_labels_cornerRadius="3dp"
    fab:menu_labels_ellipsize="none"
    fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
    fab:menu_labels_margin="0dp"
    fab:menu_labels_maxLines="-1"
    fab:menu_labels_padding="8dp"
    fab:menu_labels_position="left"
    fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
    fab:menu_labels_showShadow="true"
    fab:menu_labels_singleLine="false"
    fab:menu_labels_textColor="#f2f1f1"
    fab:menu_labels_textSize="15sp"
    fab:menu_openDirection="up"
    fab:menu_shadowColor="#66aff198"
    fab:menu_shadowRadius="4dp"
    fab:menu_shadowXOffset="1dp"
    fab:menu_shadowYOffset="4dp"
    fab:menu_showShadow="true">

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/material_design_floating_action_menu_item1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_24dp"
        fab:fab_label="Menu Item 1"
        fab:fab_size="mini" />

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/material_design_floating_action_menu_item2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_24dp"
        fab:fab_label="Menu Item 2"
        fab:fab_size="mini" />

    <com.github.clans.fab.FloatingActionButton
        android:id="@+id/material_design_floating_action_menu_item3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_clear_24dp"
        fab:fab_label="Menu Item 3"
        fab:fab_size="mini" />
</com.github.clans.fab.FloatingActionMenu>

</LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>

I would love if someone can help me to fix this problem. Thanks.

Body:
Just add another RelativeLayout below ToolBar and place both RecyclerView & com.github.clans.fab.FloatingActionMenu inside RelativeLayout.

Also change your RecyclerView as below:

<android.support.v7.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Here is the complete working code. Try this:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.SwipeRefreshLayout
    android:id="@+id/swifeRefresh"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:fab="http://schemas.android.com/apk/res-auto">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolBar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/colorPrimary" />

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />

            <com.github.clans.fab.FloatingActionMenu
                android:id="@+id/material_design_android_floating_action_menu"
                android:layout_width="match_parent"
                android:layout_height="244dp"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:layout_marginBottom="11dp"
                android:layout_marginLeft="11dp"
                android:layout_marginRight="11dp"
                fab:menu_animationDelayPerItem="55"
                fab:menu_backgroundColor="@android:color/transparent"
                fab:menu_buttonSpacing="0dp"
                fab:menu_colorNormal="#da3c2f"
                fab:menu_colorPressed="#dc4b3f"
                fab:menu_colorRipple="#99d4d4d4"
                fab:menu_fab_label="Floating Action Menu"
                fab:menu_fab_size="normal"
                fab:menu_icon="@drawable/fab_add"
                fab:menu_labels_colorNormal="#333"
                fab:menu_labels_colorPressed="#444"
                fab:menu_labels_colorRipple="#66efecec"
                fab:menu_labels_cornerRadius="3dp"
                fab:menu_labels_ellipsize="none"
                fab:menu_labels_hideAnimation="@anim/fab_slide_out_to_right"
                fab:menu_labels_margin="0dp"
                fab:menu_labels_maxLines="-1"
                fab:menu_labels_padding="8dp"
                fab:menu_labels_position="left"
                fab:menu_labels_showAnimation="@anim/fab_slide_in_from_right"
                fab:menu_labels_showShadow="true"
                fab:menu_labels_singleLine="false"
                fab:menu_labels_textColor="#f2f1f1"
                fab:menu_labels_textSize="15sp"
                fab:menu_openDirection="up"
                fab:menu_shadowColor="#66aff198"
                fab:menu_shadowRadius="4dp"
                fab:menu_shadowXOffset="1dp"
                fab:menu_shadowYOffset="4dp"
                fab:menu_showShadow="true">

                <com.github.clans.fab.FloatingActionButton
                    android:id="@+id/material_design_floating_action_menu_item1"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/icon_refresh"
                    fab:fab_label="Menu Item 1"
                    fab:fab_size="mini" />

                <com.github.clans.fab.FloatingActionButton
                    android:id="@+id/material_design_floating_action_menu_item2"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/icon_refresh"
                    fab:fab_label="Menu Item 2"
                    fab:fab_size="mini" />

                <com.github.clans.fab.FloatingActionButton
                    android:id="@+id/material_design_floating_action_menu_item3"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:src="@drawable/icon_refresh"
                    fab:fab_label="Menu Item 3"
                    fab:fab_size="mini" />
            </com.github.clans.fab.FloatingActionMenu>
        </RelativeLayout>
    </LinearLayout>
</android.support.v4.widget.SwipeRefreshLayout>

OUTPUT:

Hope this will help~


来源: stackexchange

问:
Json Serialisation Swift 3 type error
I am using the following code to receive custom data from a push notification and I get the following error:

Could not cast value of type '__NSArrayM' (0x1b0776cf0) to 'NSDictionary' (0x1b0777128).

on the following line:

```<code>let jsonData = try? JSONSerialization.jsonObject(with: (customDataString?.data(using: String.Encoding.utf8))!, options: JSONSerialization.ReadingOptions.mutableContainers) as![String: Any]
</code>```

How do I resolve this error?

```<code>func onPushAccepted(_ pushManager: PushNotificationManager!, withNotification pushNotification: [AnyHashable : Any]!, onStart: Bool) {
    print("Push notification accepted: \(pushNotification!)")

    let customDataString = pushManager.getCustomPushData(pushNotification)

    if customDataString != nil {
        let jsonData = try? JSONSerialization.jsonObject(with: (customDataString?.data(using: String.Encoding.utf8))!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]

        print("*** \(jsonData?["test"]!)")
    }
</code>```

答:
Read the error:

Could not cast value of expected type Array to offered type Dictionary

That means your JSON is an array, so

```<code>if let customDataString = pushManager.getCustomPushData(pushNotification) {
   let data = customDataString.data(using: utf8)!
   let jsonData = try? JSONSerialization.jsonObject(with: data) as! [[String:Any]]
   ...
</code>```

You can omit the options parameter, because .mutableContainers is useless in Swift anyway.

ContentLicense: CC BY-SA 3.0

Title: Json Serialisation Swift 3 type error

Body:
I am using the following code to receive custom data from a push notification and I get the following error:

Could not cast value of type '__NSArrayM' (0x1b0776cf0) to 'NSDictionary' (0x1b0777128).

on the following line:

let jsonData = try? JSONSerialization.jsonObject(with: (customDataString?.data(using: String.Encoding.utf8))!, options: JSONSerialization.ReadingOptions.mutableContainers) as![String: Any]

How do I resolve this error?

func onPushAccepted(_ pushManager: PushNotificationManager!, withNotification pushNotification: [AnyHashable : Any]!, onStart: Bool) {
    print("Push notification accepted: \(pushNotification!)")

    let customDataString = pushManager.getCustomPushData(pushNotification)

    if customDataString != nil {
        let jsonData = try? JSONSerialization.jsonObject(with: (customDataString?.data(using: String.Encoding.utf8))!, options: JSONSerialization.ReadingOptions.mutableContainers) as! [String: Any]

        print("*** \(jsonData?["test"]!)")
    }

Body:
Read the error:

Could not cast value of expected type Array to offered type Dictionary

That means your JSON is an array, so

if let customDataString = pushManager.getCustomPushData(pushNotification) {
   let data = customDataString.data(using: utf8)!
   let jsonData = try? JSONSerialization.jsonObject(with: data) as! [[String:Any]]
   ...

You can omit the options parameter, because .mutableContainers is useless in Swift anyway.


问:
imageButton in RecyclerView not displaying
I've been a lurker on your forums for some time now, and they have helped me enormously on a variety of issues I've had, so thanks! :D

I'm trying to create my first app for android and it's a card game named shithead that my friends and I used to play often.

I've decided to use a RecyclerView to display your hand. I need to be able to dynamically add buttons (with card images) to the display at runtime. From what I can tell, I need an adapter for this.

Using the handy guide at "https:// guides.codepath.com/android/using-the-recyclerview" and attempting to modify it for my own purposes I've come very close to a test run of making this work. When I run the program on an emulator in Android Studio, it gives me the following display:
images displayed as grey rectangles

I feel like I've got to be really close, and I'm simply missing some crucial syntax for working with android or android studio.

In my Card object I build a String idText that correlates to the card images I have saved in my project's mipmap-hdpi, mipmap-xhdpi etc. folders (mipmap-hdpi shown below)
mipmap-hdpi folder in Android Studio

```<code>public Card(int suitInput, int rankInput)
{
    suit = suitInput;
    rank = rankInput;
    faceUp = false;
    text = RankString[rank] + " of " + SuitString[suit];
    idText = "i_" + RankString[rank] + "_of_" + SuitString[suit];
}
</code>```

I also have a function getImageId in my Card Class:

```<code>public static int getImageId(Context context) {
    return context.getResources().getIdentifier("drawable/@+id/" + idText, null, context.getPackageName());
}
</code>```

my onBindViewHolder method in my CardAdapter is below:

```<code>@Override
public void onBindViewHolder(CardAdapter.ViewHolder viewHolder, int position)
{
    //get the data model based on position
    Card card = mCards.get(position);

    //Set item views baased on views and data model
    ImageButton imageButton = viewHolder.cardButton;
    imageButton.setImageResource(card.getImageId(mContext));
    TextView textView = viewHolder.cardText;
    textView.setText(card.text);
}
</code>```

my MainActivity class does very little as of yet. It initializes one player, me, and a Deck of Card objects. It then gives me 6 cards off the top of the unshuffled deck, AKA 2 - 7 of diamonds. It then initializes the CardAdapter.

```<code>public class MainActivity extends AppCompatActivity {

Player me;
Deck deck;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testdisplay);

    //lookup the recyclerview in activity layout
    RecyclerView rvCards = (RecyclerView) findViewById(R.id.rvCards);

    me = new Player("Dr_StrangeKill");
    deck = new Deck();

    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));

    //create adapter passing in sample user data
    CardAdapter adapter = new CardAdapter(this, me.hand);
    //Attach the adapter to the recyclerView to populate items
    rvCards.setAdapter(adapter);
    //Set layout manager to position the items
    rvCards.setLayoutManager(new LinearLayoutManager(this));
}
</code>```

The Deck, Player, and Card objects all appear to be working as intended insofar as the values of the code are concerned, as the resultant display correctly shows that 'Dr_StrangeKill' has received 2 - 7 of Diamonds, but doesn't show the card images themselves! This is my first time working with images in any IDE (eclipse, visual studio, android studio), and I feel like i'm very close but off in some small but crucial way. Any help would be greatly appreciated!

答:
It looks like you're trying to get the identifier of the image resource by name.  In that case you could try:

return context.getResources().getIdentifier(idText, "mipmap", context.getPackageName());

But doing that is not recommended.  See docs for getIdentifier()
https://developer.android.com/reference/android/content/res/Resources.html#getIdentifier(java.lang.String, java.lang.String, java.lang.String)

You could just add the id (an int) to your card object and instantiate like new Card(R.mipmap.hearts_2,2,"hearts") or however you're instantiating (seems like you're using public fields and no constructor) and grab that id in your adapter to set on the imageview.

Body:
I've been a lurker on your forums for some time now, and they have helped me enormously on a variety of issues I've had, so thanks! :D

I'm trying to create my first app for android and it's a card game named shithead that my friends and I used to play often.

I've decided to use a RecyclerView to display your hand. I need to be able to dynamically add buttons (with card images) to the display at runtime. From what I can tell, I need an adapter for this.

Using the handy guide at "https:// guides.codepath.com/android/using-the-recyclerview" and attempting to modify it for my own purposes I've come very close to a test run of making this work. When I run the program on an emulator in Android Studio, it gives me the following display:
images displayed as grey rectangles

I feel like I've got to be really close, and I'm simply missing some crucial syntax for working with android or android studio.

In my Card object I build a String idText that correlates to the card images I have saved in my project's mipmap-hdpi, mipmap-xhdpi etc. folders (mipmap-hdpi shown below)
mipmap-hdpi folder in Android Studio

public Card(int suitInput, int rankInput)
{
    suit = suitInput;
    rank = rankInput;
    faceUp = false;
    text = RankString[rank] + " of " + SuitString[suit];
    idText = "i_" + RankString[rank] + "_of_" + SuitString[suit];
}

I also have a function getImageId in my Card Class:

public static int getImageId(Context context) {
    return context.getResources().getIdentifier("drawable/@+id/" + idText, null, context.getPackageName());
}

my onBindViewHolder method in my CardAdapter is below:

@Override
public void onBindViewHolder(CardAdapter.ViewHolder viewHolder, int position)
{
    //get the data model based on position
    Card card = mCards.get(position);

    //Set item views baased on views and data model
    ImageButton imageButton = viewHolder.cardButton;
    imageButton.setImageResource(card.getImageId(mContext));
    TextView textView = viewHolder.cardText;
    textView.setText(card.text);
}

my MainActivity class does very little as of yet. It initializes one player, me, and a Deck of Card objects. It then gives me 6 cards off the top of the unshuffled deck, AKA 2 - 7 of diamonds. It then initializes the CardAdapter.

public class MainActivity extends AppCompatActivity {

Player me;
Deck deck;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.testdisplay);

    //lookup the recyclerview in activity layout
    RecyclerView rvCards = (RecyclerView) findViewById(R.id.rvCards);

    me = new Player("Dr_StrangeKill");
    deck = new Deck();

    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));
    me.hand.add(deck.getCards().remove(0));

    //create adapter passing in sample user data
    CardAdapter adapter = new CardAdapter(this, me.hand);
    //Attach the adapter to the recyclerView to populate items
    rvCards.setAdapter(adapter);
    //Set layout manager to position the items
    rvCards.setLayoutManager(new LinearLayoutManager(this));
}

The Deck, Player, and Card objects all appear to be working as intended insofar as the values of the code are concerned, as the resultant display correctly shows that 'Dr_StrangeKill' has received 2 - 7 of Diamonds, but doesn't show the card images themselves! This is my first time working with images in any IDE (eclipse, visual studio, android studio), and I feel like i'm very close but off in some small but crucial way. Any help would be greatly appreciated!


问:
Fast query runs slow in SSRS
I have an SSRS report that calls out to a stored procedure.  If I run the stored procedure directly from a query window, it will return in under 2 seconds.  However, the same query run from an 2005 SSRS report takes up to 5 minutes to complete.  This is not just happening on the first run, it happens every time.  Additionally, I don't see this same problem in other environments.

Any ideas on why the SSRS report would run so slow in this particular environment?

答:
In our case, no code was required.

Note from our Help Desk: "Clearing out your Internet Setting will fix this problem."

Maybe that means "clear cache."

ContentLicense: CC BY-SA 2.5

Title: Fast query runs slow in SSRS


问:
How to give command to print on IP printer?
I want to print from IP printer. I have a url of printer. Is it possible to print without device install on my local machine. We have not set up cups server. We only have IP of printer and it is in our Intranet.</p>

答:
You should be able to print to an IP printer without the driver if you want to print raw text. I'm not sure if it will be possible for documents such as pdf / word etc.

To print raw text you would need to specify IP and Port - default port is usually 9000. You can test with something like telnet to send text to the socket. Depending on the printer used you would also have to look at the raw commands for if you wanted to cut text or change font sizes for example.


问:
Swift: parsing dynamic JSON
I am trying to parse this JSON that has a changing key for each object Im trying to find the best way to parse each object. I am very new to swift programming so any example code would be very helpful.  I don't need to store all the values received just particular field such as address, streetName, image

JSON Input

```<code>{
"a000!%5362657": {

    "address": "20 Ingram Street",
    "streetName": "Ingram Street",
    "streetNumber": "20",
    "streetDirection": "N",
    "unitNumber": "",
    "cityName": "Forest Hills",
    "countyName": "New York",
    "state": "NY",
    "zipcode": "11375",
    "listingPrice": "$1,151,000",
    "listingID": "5362657",
    "remarksConcat": "From nytimes.com: In the comics, Peter Parker, the mild-mannered photojournalist who is Spider-Man's alter ego, grew up at 20 Ingram Street, a modest, two-story boarding house run by his Aunt May in the heart of Forest Hills Gardens. The address actually exists and is home to a family named Parker: Andrew and Suzanne Parker, who moved there in 1974, and their two daughters. In 1989, the family began receiving junk mail addressed to Peter Parker. We got tons of it, Mrs. Parker said yesterday. Star Trek magazines, a Discover Card in his name, and notices from them over the years calling him a good customer. There were also prank phone calls, all of which she attributed to a teenager who found it funny that we had the same last name as Spider-Man.",
    "rntLse": "neither",
    "propStatus": "Active",
    "bedrooms": "3",
    "totalBaths": "2.75",
    "latitude": "40.712968",
    "longitude": "-73.843206",
    "acres": "0.24",
    "sqFt": "2,760",
    "displayAddress": "y",
    "listingAgentID": "8675301",
    "listingOfficeID": "lmnop",
    "sample_mlsPtID": "1",
    "sample_mlsPhotoCount": "39",
    "parentPtID": "1",
    "detailsURL": "a000/5362657",
    "idxID": "a000",
    "idxPropType": "Residential",
    "idxStatus": "active",
    "viewCount": "2",
    "mediaData": [],
    "ohCount": "0",
    "vtCount": "0",
    "featured": "n",
    "image": {
        "0": {
            "url": "http://cdn.photos.ample_mls.com/az/20151113223546806109000000.jpg",
            "caption": "17596-20"
        },
        "totalCount": "39"
    },
    "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5362657/20-Ingram-Street-Forrest-Hills-NY-11375"
},
"a000!%5358959": {
    "address": "177A Bleecker Street",
    "streetName": "Bleecker Street",
    "streetNumber": "177",
    "streetDirection": "N",
    "unitNumber": "A",
    "cityName": "Greenwich Village",
    "countyName": "New York",
    "state": "NY",
    "zipcode": "10012",
    "listingPrice": "$616,000,000",
    "listingID": "5358959",
    "remarksConcat": "Home to Dr. Stephen Vincent Strange(Doctor Strange in Marvel comics) and his faithful bodyguard and manservant Wong. Spider-Man often visits the Doctor for help when battling those with magic powers. Features: Wong's Storage Cellar, Strange's bedchambers, guest quarters, Wong's bedchamber, Study, Meditain Chamber, Library, Storage Area for Occult Artifacts.",
    "rntLse": "neither",
    "propStatus": "Active",
    "bedrooms": "2",
    "totalBaths": "2.75",
    "latitude": "40.729117",
    "longitude": "-74.000773",
    "acres": "0.31",
    "sqFt": "206800000000",
    "displayAddress": "y",
    "listingAgentID": "8675301",
    "listingOfficeID": "lmnop",
    "sample_mlsPtID": "1",
    "sample_mlsPhotoCount": "34",
    "parentPtID": "1",
    "detailsURL": "a000/5358959",
    "idxID": "a000",
    "idxPropType": "Residential",
    "idxStatus": "active",
    "viewCount": "6",
    "mediaData": [],
    "ohCount": "0",
    "vtCount": "0",
    "featured": "y",
    "image": {
        "0": {
            "url": "http://cdn.photos.sample_mls.com/az/20151105214013253867000000.jpg",
            "caption": "Front"
        },
        "totalCount": "34"
    },
    "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5358959/177A-Bleecker-Street-Greenwich-Village-NY-10012"
}
}
</code>```

swift viewController

```<code>import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

//final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
final let urlString = "https://api.idxbroker.com/clients/featured"

@IBOutlet weak var tableView: UITableView!

var nameArray = [String]()
var dobArray = [String]()
var imgURLArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.downloadJsonWithTask()
    //self.downloadJsonWithURL()

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/***********************************************************************************************/

func downloadJsonWithTask() {

    let url = NSURL(string: urlString)

    var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)

/************** Get Users Accesy Key for API CALL *************************/
    var key = String()
    let textFieldKeyConstant = "AccessKey"

    let defaults = UserDefaults.standard
    if let textFieldValue = defaults.string(forKey: textFieldKeyConstant) {
        key = textFieldValue
    }

    print(key) //accesskey debug
/******************** End Get accessKey *************************************/

/******************** Add Headers required for API CALL *************************************/
    downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    downloadTask.setValue(key, forHTTPHeaderField: "accesskey")
    downloadTask.setValue("json", forHTTPHeaderField: "outputtype")

    downloadTask.httpMethod = "GET"
    /******************** End Headers required for API CALL *************************************/

    URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in

    let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

print(jsonData ?? "Default")

/******** Parse JSON **********/

/******** End Parse JSON **********/

/******** Reload table View **********/
        OperationQueue.main.addOperation({
            self.tableView.reloadData()
        })        }).resume()
}
    /***********************************************************************************************/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nameArray.count
}
/***********************************************************************************************/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    cell.nameLabel.text = nameArray[indexPath.row]
    cell.dobLabel.text = dobArray[indexPath.row]

    let imgURL = NSURL(string: imgURLArray[indexPath.row])

    if imgURL != nil {
        let data = NSData(contentsOf: (imgURL as URL?)!)
        cell.imgView.image = UIImage(data: data! as Data)
    }

    return cell
}
/****************************************************************/

///for showing next detailed screen with the downloaded info
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
    vc.imageString = imgURLArray[indexPath.row]
    vc.nameString = nameArray[indexPath.row]
    vc.dobString = dobArray[indexPath.row]

    self.navigationController?.pushViewController(vc, animated: true)
}

}
</code>```

答:
for swift3  [String:Any] it is  a Dictionary with key has String and  Any type in Swift, which describes a value of any type

```<code> do {
      let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
        print(parsedData)

    } catch let error as NSError {
        print(error)
    }
</code>```

For example :

```<code>if  let info = parsedData["a000!%5362657"] as? [String : String]{
    if let address = info["address"]  {
        print(address)
    }
}
</code>```

Working with JSON in Swift   apple blog https://developer.apple.com/swift/blog/?id=37

Title: Swift: parsing dynamic JSON

Body:
I am trying to parse this JSON that has a changing key for each object Im trying to find the best way to parse each object. I am very new to swift programming so any example code would be very helpful.  I don't need to store all the values received just particular field such as address, streetName, image

JSON Input

{
"a000!%5362657": {

    "address": "20 Ingram Street",
    "streetName": "Ingram Street",
    "streetNumber": "20",
    "streetDirection": "N",
    "unitNumber": "",
    "cityName": "Forest Hills",
    "countyName": "New York",
    "state": "NY",
    "zipcode": "11375",
    "listingPrice": "$1,151,000",
    "listingID": "5362657",
    "remarksConcat": "From nytimes.com: In the comics, Peter Parker, the mild-mannered photojournalist who is Spider-Man's alter ego, grew up at 20 Ingram Street, a modest, two-story boarding house run by his Aunt May in the heart of Forest Hills Gardens. The address actually exists and is home to a family named Parker: Andrew and Suzanne Parker, who moved there in 1974, and their two daughters. In 1989, the family began receiving junk mail addressed to Peter Parker. We got tons of it, Mrs. Parker said yesterday. Star Trek magazines, a Discover Card in his name, and notices from them over the years calling him a good customer. There were also prank phone calls, all of which she attributed to a teenager who found it funny that we had the same last name as Spider-Man.",
    "rntLse": "neither",
    "propStatus": "Active",
    "bedrooms": "3",
    "totalBaths": "2.75",
    "latitude": "40.712968",
    "longitude": "-73.843206",
    "acres": "0.24",
    "sqFt": "2,760",
    "displayAddress": "y",
    "listingAgentID": "8675301",
    "listingOfficeID": "lmnop",
    "sample_mlsPtID": "1",
    "sample_mlsPhotoCount": "39",
    "parentPtID": "1",
    "detailsURL": "a000/5362657",
    "idxID": "a000",
    "idxPropType": "Residential",
    "idxStatus": "active",
    "viewCount": "2",
    "mediaData": [],
    "ohCount": "0",
    "vtCount": "0",
    "featured": "n",
    "image": {
        "0": {
            "url": "http://cdn.photos.ample_mls.com/az/20151113223546806109000000.jpg",
            "caption": "17596-20"
        },
        "totalCount": "39"
    },
    "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5362657/20-Ingram-Street-Forrest-Hills-NY-11375"
},
"a000!%5358959": {
    "address": "177A Bleecker Street",
    "streetName": "Bleecker Street",
    "streetNumber": "177",
    "streetDirection": "N",
    "unitNumber": "A",
    "cityName": "Greenwich Village",
    "countyName": "New York",
    "state": "NY",
    "zipcode": "10012",
    "listingPrice": "$616,000,000",
    "listingID": "5358959",
    "remarksConcat": "Home to Dr. Stephen Vincent Strange(Doctor Strange in Marvel comics) and his faithful bodyguard and manservant Wong. Spider-Man often visits the Doctor for help when battling those with magic powers. Features: Wong's Storage Cellar, Strange's bedchambers, guest quarters, Wong's bedchamber, Study, Meditain Chamber, Library, Storage Area for Occult Artifacts.",
    "rntLse": "neither",
    "propStatus": "Active",
    "bedrooms": "2",
    "totalBaths": "2.75",
    "latitude": "40.729117",
    "longitude": "-74.000773",
    "acres": "0.31",
    "sqFt": "206800000000",
    "displayAddress": "y",
    "listingAgentID": "8675301",
    "listingOfficeID": "lmnop",
    "sample_mlsPtID": "1",
    "sample_mlsPhotoCount": "34",
    "parentPtID": "1",
    "detailsURL": "a000/5358959",
    "idxID": "a000",
    "idxPropType": "Residential",
    "idxStatus": "active",
    "viewCount": "6",
    "mediaData": [],
    "ohCount": "0",
    "vtCount": "0",
    "featured": "y",
    "image": {
        "0": {
            "url": "http://cdn.photos.sample_mls.com/az/20151105214013253867000000.jpg",
            "caption": "Front"
        },
        "totalCount": "34"
    },
    "fullDetailsURL": "http://sample_return.idxbroker.com/idx/details/listing/a000/5358959/177A-Bleecker-Street-Greenwich-Village-NY-10012"
}
}

swift viewController

import UIKit

class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {

//final let urlString = "http://microblogging.wingnity.com/JSONParsingTutorial/jsonActors"
final let urlString = "https://api.idxbroker.com/clients/featured"

@IBOutlet weak var tableView: UITableView!

var nameArray = [String]()
var dobArray = [String]()
var imgURLArray = [String]()

override func viewDidLoad() {
    super.viewDidLoad()
    self.downloadJsonWithTask()
    //self.downloadJsonWithURL()

    // Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

/***********************************************************************************************/

func downloadJsonWithTask() {

    let url = NSURL(string: urlString)

    var downloadTask = URLRequest(url: (url as URL?)!, cachePolicy: URLRequest.CachePolicy.reloadIgnoringCacheData, timeoutInterval: 20)

/************** Get Users Accesy Key for API CALL *************************/
    var key = String()
    let textFieldKeyConstant = "AccessKey"

    let defaults = UserDefaults.standard
    if let textFieldValue = defaults.string(forKey: textFieldKeyConstant) {
        key = textFieldValue
    }

    print(key) //accesskey debug
/******************** End Get accessKey *************************************/

/******************** Add Headers required for API CALL *************************************/
    downloadTask.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    downloadTask.setValue(key, forHTTPHeaderField: "accesskey")
    downloadTask.setValue("json", forHTTPHeaderField: "outputtype")

    downloadTask.httpMethod = "GET"
    /******************** End Headers required for API CALL *************************************/

    URLSession.shared.dataTask(with: downloadTask, completionHandler: {(data, response, error) -> Void in

    let jsonData = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments)

print(jsonData ?? "Default")

/******** Parse JSON **********/

/******** End Parse JSON **********/

/******** Reload table View **********/
        OperationQueue.main.addOperation({
            self.tableView.reloadData()
        })        }).resume()
}
    /***********************************************************************************************/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return nameArray.count
}
/***********************************************************************************************/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
    cell.nameLabel.text = nameArray[indexPath.row]
    cell.dobLabel.text = dobArray[indexPath.row]

    let imgURL = NSURL(string: imgURLArray[indexPath.row])

    if imgURL != nil {
        let data = NSData(contentsOf: (imgURL as URL?)!)
        cell.imgView.image = UIImage(data: data! as Data)
    }

    return cell
}
/****************************************************************/

///for showing next detailed screen with the downloaded info
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    let vc = self.storyboard?.instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController
    vc.imageString = imgURLArray[indexPath.row]
    vc.nameString = nameArray[indexPath.row]
    vc.dobString = dobArray[indexPath.row]

    self.navigationController?.pushViewController(vc, animated: true)
}

}

Body:
for swift3  [String:Any] it is  a Dictionary with key has String and  Any type in Swift, which describes a value of any type

 do {
      let parsedData = try JSONSerialization.jsonObject(with: data!, options: []) as! [String:Any]
        print(parsedData)

    } catch let error as NSError {
        print(error)
    }

For example :

if  let info = parsedData["a000!%5362657"] as? [String : String]{
    if let address = info["address"]  {
        print(address)
    }
}

Working with JSON in Swift   apple blog https://developer.apple.com/swift/blog/?id=37


问:
Comparing a double to Math.PI (converting double to String)
I'm trying to write a program that compares a double (entered by the user) to the constant Math.PI, after having converted both values to Strings and then comparing them char by char. I'm getting errors but I'm not able to see where I should change my code. Any tips/help is greatly appreciated!</p>

```<code>import java.util.Scanner;

public class Main {

    private static int matches = 0;

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter value to compare");
        double compare = scan.nextDouble();
        compare(compare);
    }

    public static int compare(double value){

        String input = String.valueOf(value);
        String original = String.valueOf(3.523);
                //String.valueOf(Math.PI);

        if(input.charAt(0) == 3){
            for(int i = 3; i <= input.length(); i++){
              if(input.charAt(i) == (original.charAt(i))){
                matches++;
              }
            }
            return matches;
        } else
            return matches;
    }
}
</code>```

答:
Your question is not clear

What is concretely the expected behavior here?

I can't manage to understand your thought process in the compare method.

If you wan't to compare a double with Math.PI, it is easy as double are  primitive variables, you can use the "==" operator, just do:

```<code> if (scannedValue == Math.PI)
          System.out.println ("values are equals");
</code>```

And for the runtime exception that you have it is because you did not pass a correct double variable to your scanner.

https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html

Body:
I'm trying to write a program that compares a double (entered by the user) to the constant Math.PI, after having converted both values to Strings and then comparing them char by char. I'm getting errors but I'm not able to see where I should change my code. Any tips/help is greatly appreciated!

import java.util.Scanner;

public class Main {

    private static int matches = 0;

    public static void main(String[] args) {

        Scanner scan = new Scanner(System.in);
        System.out.println("Enter value to compare");
        double compare = scan.nextDouble();
        compare(compare);
    }

    public static int compare(double value){

        String input = String.valueOf(value);
        String original = String.valueOf(3.523);
                //String.valueOf(Math.PI);

        if(input.charAt(0) == 3){
            for(int i = 3; i <= input.length(); i++){
              if(input.charAt(i) == (original.charAt(i))){
                matches++;
              }
            }
            return matches;
        } else
            return matches;
    }
}

Body:
Your question is not clear

What is concretely the expected behavior here?

I can't manage to understand your thought process in the compare method.

If you wan't to compare a double with Math.PI, it is easy as double are  primitive variables, you can use the "==" operator, just do:

 if (scannedValue == Math.PI)
          System.out.println ("values are equals");

And for the runtime exception that you have it is because you did not pass a correct double variable to your scanner.

https://docs.oracle.com/javase/7/docs/api/java/util/InputMismatchException.html


问:
consulting database when data is today, tomorrow, after tomorrow
I need to consult a table using mysql...for today, tomorrow, after tomorrow,..

by now I use the following code where data is the day in format YYYY-MM-DD

```<code>$data_query = mysqli_query($conexionbd,'select * from `Meteo` where `data` >= "2017-03-31" ');
</code>```

what should I insert in where data >= in order to get the data for today, tomorrow...without inserting manually the date?

答:
You could use now()
and between interval 2 days</p>

```<code> data_query = mysqli_query($conexionbd,'select *
              from `Meteo`
              where `data` between now() and date_add(date(now() ), interval 2 day)) ;
</code>```

Body:
I need to consult a table using mysql...for today, tomorrow, after tomorrow,..

by now I use the following code where data is the day in format YYYY-MM-DD

$data_query = mysqli_query($conexionbd,'select * from `Meteo` where `data` >= "2017-03-31" ');

what should I insert in where data >= in order to get the data for today, tomorrow...without inserting manually the date?

Body:
You could use now()
and between interval 2 days

 data_query = mysqli_query($conexionbd,'select *
              from `Meteo`
              where `data` between now() and date_add(date(now() ), interval 2 day)) ;


问:
Lockable is not working in Devise
I have implemented Devise on two user accounts Admin and Customer. Register sign_in functions are working fine. I'm trying to implement lockable on an admin account. I'm using Devise 3.2.4.

After entering wrong credentials for specific time the account is still active and it doesn't record failed_attempts.

I have followed this guide HERE.

My devise.rb:

```<code>Devise.setup do |config|
  config.secret_key = 'XXXXX_the_secret_key_XXXXXXX'

  config.mailer_sender = 'mymail@domain.com'

  require 'devise/orm/active_record'

  # config.authentication_keys = [ :email ]

  # config.request_keys = []

  config.case_insensitive_keys = [ :email ]

  config.strip_whitespace_keys = [ :email ]

  # config.params_authenticatable = true

  # config.http_authenticatable = false

  # config.http_authenticatable_on_xhr = true

  # config.http_authentication_realm = 'Application'

  # config.paranoid = true

  # passing :skip => :sessions to `devise_for` in your config/routes.rb
  config.skip_session_storage = [:http_auth]

  # config.clean_up_csrf_token_on_authentication = true

  config.stretches = Rails.env.test? ? 1 : 10

  # config.pepper = '38635688e9d775b28e8da07b695dfced7b3bd4899c0a9a2a0f9b5ed5a8113e79864f76039166f827ef0134452fc0080f279adc4d1724362e079d0af3361edaf5'

  # config.allow_unconfirmed_access_for = 2.days

  # config.confirm_within = 3.days

  config.reconfirmable = true

  # config.confirmation_keys = [ :email ]

  # config.remember_for = 2.weeks

  # config.extend_remember_period = false

  # config.rememberable_options = {}

  # Range for password length.
  config.password_length = 8..128

  # config.email_regexp = /\A[^@]+@[^@]+\z/

  # config.timeout_in = 30.minutes

  # config.expire_auth_token_on_timeout = false

  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  config.unlock_keys = [ :email ]
  # config.unlock_keys = [ :time ]

  config.unlock_strategy = :both
  # config.unlock_strategy = :time

  config.maximum_attempts = 3

  config.unlock_in = 2.hour

  # config.last_attempt_warning = false

  config.reset_password_within = 24.hours

  # config.encryptor = :sha512

  config.sign_out_via = :delete

end
</code>```

My Admin model:

```<code>class Admin < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :lockable
end
</code>```

My migration to add lockable on admin:

```<code>class AddLockableToAdmin < ActiveRecord::Migration
  def change
    add_column :admins, :failed_attempts, :integer, default: 0
    add_column :admins, :unlock_token, :string
    add_column :admins, :locked_at, :datetime
  end
end
</code>```

My routes.rb:

```<code>devise_for :admins
</code>```

答:
After following the advice of Benj, I failed to get it to work. When debugging lib/devise/models/lockable.rb the code entered the if super && !access_locked? condition.

It turns out my issue was in the sign-in procedure, where I used the valid_for_authentication? function incorrectly. I.e. I did a check similar to this:

```<code>if user.valid_for_authentication? && user.valid_password?(params[:password])
</code>```

instead of supplying password verification in a block:

```<code>if user.valid_for_authentication? { user.valid_password?(params[:password]) }
</code>```

Title: Lockable is not working in Devise

Body:
I have implemented Devise on two user accounts Admin and Customer. Register sign_in functions are working fine. I'm trying to implement lockable on an admin account. I'm using Devise 3.2.4.

After entering wrong credentials for specific time the account is still active and it doesn't record failed_attempts.

I have followed this guide HERE.

My devise.rb:

Devise.setup do |config|
  config.secret_key = 'XXXXX_the_secret_key_XXXXXXX'

  config.mailer_sender = 'mymail@domain.com'

  require 'devise/orm/active_record'

  # config.authentication_keys = [ :email ]

  # config.request_keys = []

  config.case_insensitive_keys = [ :email ]

  config.strip_whitespace_keys = [ :email ]

  # config.params_authenticatable = true

  # config.http_authenticatable = false

  # config.http_authenticatable_on_xhr = true

  # config.http_authentication_realm = 'Application'

  # config.paranoid = true

  # passing :skip => :sessions to `devise_for` in your config/routes.rb
  config.skip_session_storage = [:http_auth]

  # config.clean_up_csrf_token_on_authentication = true

  config.stretches = Rails.env.test? ? 1 : 10

  # config.pepper = '38635688e9d775b28e8da07b695dfced7b3bd4899c0a9a2a0f9b5ed5a8113e79864f76039166f827ef0134452fc0080f279adc4d1724362e079d0af3361edaf5'

  # config.allow_unconfirmed_access_for = 2.days

  # config.confirm_within = 3.days

  config.reconfirmable = true

  # config.confirmation_keys = [ :email ]

  # config.remember_for = 2.weeks

  # config.extend_remember_period = false

  # config.rememberable_options = {}

  # Range for password length.
  config.password_length = 8..128

  # config.email_regexp = /\A[^@]+@[^@]+\z/

  # config.timeout_in = 30.minutes

  # config.expire_auth_token_on_timeout = false

  # :failed_attempts = Locks an account after a number of failed attempts to sign in.
  # :none            = No lock strategy. You should handle locking by yourself.
  config.lock_strategy = :failed_attempts

  # Defines which key will be used when locking and unlocking an account
  config.unlock_keys = [ :email ]
  # config.unlock_keys = [ :time ]

  config.unlock_strategy = :both
  # config.unlock_strategy = :time

  config.maximum_attempts = 3

  config.unlock_in = 2.hour

  # config.last_attempt_warning = false

  config.reset_password_within = 24.hours

  # config.encryptor = :sha512

  config.sign_out_via = :delete

end

My Admin model:

class Admin < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :lockable
end

My migration to add lockable on admin:

class AddLockableToAdmin < ActiveRecord::Migration
  def change
    add_column :admins, :failed_attempts, :integer, default: 0
    add_column :admins, :unlock_token, :string
    add_column :admins, :locked_at, :datetime
  end
end

My routes.rb:

devise_for :admins

Body:
After following the advice of Benj, I failed to get it to work. When debugging lib/devise/models/lockable.rb the code entered the if super && !access_locked? condition.

It turns out my issue was in the sign-in procedure, where I used the valid_for_authentication? function incorrectly. I.e. I did a check similar to this:

if user.valid_for_authentication? && user.valid_password?(params[:password])

instead of supplying password verification in a block:

if user.valid_for_authentication? { user.valid_password?(params[:password]) }


问:
Import text file with uneven column number and complicated delimiter
Say I have text file like below:

```<code>apple  pear  banana,  peach orange grape

dog  cat  white horse

salmon

tiger  lion  eagle hawk  monkey
</code>```

Looking for output like:

```<code>"apple", "pear", "banana", "peach orange grape"

"dog", "cat", "white horse"

"salmon"

"tiger", "lion", "eagle hawk", "monkey"
</code>```

Two problems,

each row I only want separate them by double space '   '

column number of each row could be random, from 1 to 100

How can I load them into a pandas dataframe?

In fact I am wondering if it is possible to complete this without reading line by line, because I initial solution is:

read each line, use REX

re.split(r'\s{2,}', line)

to split by double space

after split by double space, insert each row into DF

however, coz the column number is random, I can't simply generate a DF by that.
Adding names=[] in pd.read_csv() will handle uneven columns, but this requires pre define column names and number.

Any suggestion?

Thank you!

答:
To provide another example in addition to the one provided by @JD Long, you could use a regular expression plus a list comprehension:

```<code>import re, pandas as pd

string = """
apple  pear  banana  peach orange grape

dog  cat  white horse

salmon

tiger  lion  eagle hawk  monkey
"""

rx = re.compile(r'''[ ]{2,}''')

items = [(rx.split(line)) for line in string.split("\n") if line]

df = pd.DataFrame.from_records(items)
print(df)
</code>```

... which yields:

```<code>        0     1            2                   3
0   apple  pear       banana  peach orange grape
1     dog   cat  white horse                None
2  salmon  None         None                None
3   tiger  lion   eagle hawk              monkey
</code>```

Body:
Say I have text file like below:

apple  pear  banana,  peach orange grape

dog  cat  white horse

salmon

tiger  lion  eagle hawk  monkey

Looking for output like:

"apple", "pear", "banana", "peach orange grape"

"dog", "cat", "white horse"

"salmon"

"tiger", "lion", "eagle hawk", "monkey"

Two problems,

each row I only want separate them by double space '   '

column number of each row could be random, from 1 to 100

How can I load them into a pandas dataframe?

In fact I am wondering if it is possible to complete this without reading line by line, because I initial solution is:

read each line, use REX

re.split(r'\s{2,}', line)

to split by double space

after split by double space, insert each row into DF

however, coz the column number is random, I can't simply generate a DF by that.
Adding names=[] in pd.read_csv() will handle uneven columns, but this requires pre define column names and number.

Any suggestion?

Thank you!

Body:
To provide another example in addition to the one provided by @JD Long, you could use a regular expression plus a list comprehension:

import re, pandas as pd

string = """
apple  pear  banana  peach orange grape

dog  cat  white horse

salmon

tiger  lion  eagle hawk  monkey
"""

rx = re.compile(r'''[ ]{2,}''')

items = [(rx.split(line)) for line in string.split("\n") if line]

df = pd.DataFrame.from_records(items)
print(df)

... which yields:

        0     1            2                   3
0   apple  pear       banana  peach orange grape
1     dog   cat  white horse                None
2  salmon  None         None                None
3   tiger  lion   eagle hawk              monkey


问:
What's the proper way to dynamically insert HTML?
I have a chatbox like so (simplified version):

```<code>        <!-- Chat Container -->
        <div id="chat-window">
            <div class="message-container">
                <!-- Begin messages -->

                <!-- End messages -->
            </div>
        </div>
</code>```

I have a function that appends a static block of html stored in javascript

Said block of code:

```<code>        var messageTemplate =
        '<!-- Begin message -->' +
        '<div id="message">' +
        '<div id="message-name">' + name + '</div>' +
        '<div id="message-division" class="badge">' + division + '</div>' +
        '<div id="message-time"><i class="fa fa-clock-o" aria-hidden="true"></i><abbr class="timeago" title="' + time + '">' + time + ' </abbr> </div>' +
        '<div id="message-content">' +
        '<div id="message-tag" class="label label-primary">' + tag + '</div>' +
        '<div id="message-text">' +
        text +
        '</div>' +
        '</div>' +
        '<hr>' +
        '</div>' +
        '<!-- End message -->';
</code>```

Jquery appends this to my messages-container

However I feel that there's a much cleaner solution to do this, which I haven't been able to find.

Can someone point me to the right direction for inserting new objects into web pages without having to pre-define these objects in quoted javascript?

答:
As others have suggested you can look for a more formal templating engine, but your use-case looks pretty simple.  You could just use JQuery methods like createElement(), attr(), and text() to do this functionally.  Here is this approach wrapped with a newDiv function since that seems to be the major thing you need here. It adds an id you pass in and creates a div element as a child to the second parameter of newDiv().  Anything beyond that like adding text can be chained onto the newDiv function result.</p>

```<code>var name = "foo";
var division = "bar";

// this is your parent element
var message = newDiv("message",$(".message-container"));

// here are your children, add as many as you want:
newDiv("message-name",message).text(name);
newDiv("message-division",message).text(division);

function newDiv(id,parent) {
    var element = document.createElement("div");
    $(element).attr("id",id);
    parent.append(element);
    return $(element);
}
</code>```

Body:
I have a chatbox like so (simplified version):

I have a function that appends a static block of html stored in javascript

Said block of code:

        var messageTemplate =
        '' +
        '
' +
        '
' + name + '
' +
        '
' + division + '
' +
        '
' + time + '
' +
        '
' +
        '
' + tag + '
' +
        '
' +
        text +
        '
' +
        '
' +
        '
' +
        '
' +
        '';

Jquery appends this to my messages-container

However I feel that there's a much cleaner solution to do this, which I haven't been able to find.

Can someone point me to the right direction for inserting new objects into web pages without having to pre-define these objects in quoted javascript?

Body:
As others have suggested you can look for a more formal templating engine, but your use-case looks pretty simple.  You could just use JQuery methods like createElement(), attr(), and text() to do this functionally.  Here is this approach wrapped with a newDiv function since that seems to be the major thing you need here. It adds an id you pass in and creates a div element as a child to the second parameter of newDiv().  Anything beyond that like adding text can be chained onto the newDiv function result.

var name = "foo";
var division = "bar";

// this is your parent element
var message = newDiv("message",$(".message-container"));

// here are your children, add as many as you want:
newDiv("message-name",message).text(name);
newDiv("message-division",message).text(division);

function newDiv(id,parent) {
    var element = document.createElement("div");
    $(element).attr("id",id);
    parent.append(element);
    return $(element);
}


问:
How to evaluate a mathematical expression saved in nvarchar variable in SQL Server
i want to evaluate a mathematical expression saved in a variable in sql server

i google this a lot and found 3 solution but not applicable in my scenario

1- this solution cannot be executed inside a function but i need it inside a function

```<code>declare @expression nvarchar(max)
set @expression = '2*3*100'

declare @sql nvarchar(max)
set @sql = 'select @result = ' + @expression

declare @result int
exec sp_executesql @sql, N'@result int output', @result = @result out

select @result
</code>```

2- this cannot be saved into a variable but i need to store the result into a variable

```<code>DECLARE @LocalVariable VARCHAR(32);
SET @LocalVariable = '2*3*100';
EXEC('SELECT ' + @LocalVariable);
</code>```

3- the last solution i found gives me a error

```<code>DECLARE @x xml
DECLARE @v decimal(20,4)
SET @x = ''
DECLARE @calculatedDataString nvarchar(1000) = '(1 div 100)*((118 div 100)*300.000000)'
SET @v= @x.value('sql:variable("@calculatedDataString")', 'decimal(20,4)')
SELECT @v
</code>```

the error is

```<code>Msg 8114, Level 16, State 5, Line 5
Error converting data type nvarchar to numeric.
</code>```

please advice

答:
Perhaps this may help.

The following will evaluate a series of expressions, save the results to a #temp table.  From there you can store the individual results into a variable

This is a dramatically scaled down version.  The full one was built for macro substituions (i.e. calculate a series or Finanancial Ratios for multiple datasets)

If you provide a more robust USE CASE, perhaps I can help further

Example

```<code>Declare @Expression table (ID int,Expression varchar(max))
Insert Into @Expression values
 (1,'(1/100.0)*((118/100.0)*300.00000)')           -- Simple Calculation
,(2,'datediff(DD,''2016-07-29'',GetDate())')       -- System Functions
,(3,'(Select max(name) from master..spt_values)')  -- Select Value From Table
,(4,'convert(date,GetDate())')                     -- Get Today's Date

IF OBJECT_ID(N'tempdb..#Results') IS NOT NULL
BEGIN
    DROP TABLE #Results
END
Create table #Results (ID int,Value varchar(max))

Declare @SQL varchar(max)=''
Select  @SQL = @SQL+concat(',(',ID,',cast(',Expression,' as varchar(max)))') From @Expression
Select  @SQL = 'Insert Into #Results Select * From ('+Stuff(@SQL,1,1,'values')+') N(ID,Value)'
Exec(@SQL)

Select * From #Results

Declare @Var decimal(10,4) = (Select Value From #Results where ID=1)
Select @Var  -- 3.5400
</code>```

Temp Table

```<code>ID  Value
1   3.54000000000000000
2   243
3   YES OR NO
4   2017-03-29
</code>```

Body:
i want to evaluate a mathematical expression saved in a variable in sql server

i google this a lot and found 3 solution but not applicable in my scenario

1- this solution cannot be executed inside a function but i need it inside a function

declare @expression nvarchar(max)
set @expression = '2*3*100'

declare @sql nvarchar(max)
set @sql = 'select @result = ' + @expression

declare @result int
exec sp_executesql @sql, N'@result int output', @result = @result out

select @result

2- this cannot be saved into a variable but i need to store the result into a variable

DECLARE @LocalVariable VARCHAR(32);
SET @LocalVariable = '2*3*100';
EXEC('SELECT ' + @LocalVariable);

3- the last solution i found gives me a error

DECLARE @x xml
DECLARE @v decimal(20,4)
SET @x = ''
DECLARE @calculatedDataString nvarchar(1000) = '(1 div 100)*((118 div 100)*300.000000)'
SET @v= @x.value('sql:variable("@calculatedDataString")', 'decimal(20,4)')
SELECT @v

the error is

Msg 8114, Level 16, State 5, Line 5
Error converting data type nvarchar to numeric.

please advice

Body:
Perhaps this may help.

The following will evaluate a series of expressions, save the results to a #temp table.  From there you can store the individual results into a variable

This is a dramatically scaled down version.  The full one was built for macro substituions (i.e. calculate a series or Finanancial Ratios for multiple datasets)

If you provide a more robust USE CASE, perhaps I can help further

Example

Declare @Expression table (ID int,Expression varchar(max))
Insert Into @Expression values
 (1,'(1/100.0)*((118/100.0)*300.00000)')           -- Simple Calculation
,(2,'datediff(DD,''2016-07-29'',GetDate())')       -- System Functions
,(3,'(Select max(name) from master..spt_values)')  -- Select Value From Table
,(4,'convert(date,GetDate())')                     -- Get Today's Date

IF OBJECT_ID(N'tempdb..#Results') IS NOT NULL
BEGIN
    DROP TABLE #Results
END
Create table #Results (ID int,Value varchar(max))

Declare @SQL varchar(max)=''
Select  @SQL = @SQL+concat(',(',ID,',cast(',Expression,' as varchar(max)))') From @Expression
Select  @SQL = 'Insert Into #Results Select * From ('+Stuff(@SQL,1,1,'values')+') N(ID,Value)'
Exec(@SQL)

Select * From #Results

Declare @Var decimal(10,4) = (Select Value From #Results where ID=1)
Select @Var  -- 3.5400

Temp Table

ID  Value
1   3.54000000000000000
2   243
3   YES OR NO
4   2017-03-29


问:
MongoDB nested Document Validation for sub-documents
I got a document structured like the following. My question is how do I do the nested part "roles" validation on the database side. My requirements are:

the roles size could be 0 or more than 1.

the presence of name and created_by for a role if a role is created.

```<code>{
  "_id": "123456",
  "name": "User Name",
  "roles": [
    {
      "name": "mobiles_user",
       "last_usage_at": {
         "$date": 1457000592991
        },
        "created_by": "987654",
        "created_at": {
          "$date": 1457000592991
        }
    },
    {
      "name": "webs_user",
       "last_usage_at": {
         "$date": 1457000592991
        },
        "created_by": "987654",
        "created_at": {
          "$date": 1457000592991
        }
    },
  ]
}
</code>```

At the moment, I am only doing the following for those none nested attributes:

```<code>db.createCollection( "users",
   { "validator" : {
     "_id" : {
         "$type" : "string"
      },
      "email" : {
         "$regex" : /@gmail\.com$/
      },
      "name" : {
         "$type" : "string"
      }
   }
} )
</code>```

Could anyone please advise that how to do the nested document validation?

答:
Yes, you can validate all sub-documents in a document by negating $elemMatch, and you can ensure that the size is not 1.  It's sure not pretty though!  And not exactly obvious either.

```<code>> db.createCollection('users', {
...   validator: {
...     name: {$type: 'string'},
...     roles: {$exists: 'true'},
...     $nor: [
...       {roles: {$size: 1}},
...       {roles: {$elemMatch: {
...         $or: [
...           {name: {$not: {$type: 'string'}}},
...           {created_by: {$not: {$type: 'string'}}},
...         ]
...       }}}
...     ],
...   }
... })
{ "ok" : 1 }
</code>```

This is confusing, but it works!  What it means is only accept documents where neither the size of roles is 1 nor roles has an element with a name that isn't a string or a created_by that isn't a string.

This is based upon the fact that in logic terms,

for all x: f(x) and g(x)

Is equivalent to

not exists x s.t.: not f(x) or not g(x)

We have to use the latter since MongoDB only gives us an exists operator.

Proof

Valid documents work:

```<code>> db.users.insert({
...   name: 'hello',
...   roles: [],
... })
WriteResult({ "nInserted" : 1 })

> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...     {name: 'bar', created_by: '3333'},
...   ]
... })
WriteResult({ "nInserted" : 1 })
</code>```

If a field is missing from roles, it fails:

```<code>> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...     {created_by: '3333'},
...   ]
... })
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})
</code>```

If a field in roles has the wrong type, it fails:

```<code>> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...     {name: 'bar', created_by: 3333},
...   ]
... })
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})
</code>```

If roles has size 1 it fails:

```<code>> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...   ]
... })
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})
</code>```

The only thing I can't figure out unfortunately is how to ensure that roles is an array.  roles: {$type: 'array'} seems to fail everything, I presume because it's actually checking that the elements are of type 'array'?

Body:
I got a document structured like the following. My question is how do I do the nested part "roles" validation on the database side. My requirements are:

the roles size could be 0 or more than 1.

the presence of name and created_by for a role if a role is created.

{
  "_id": "123456",
  "name": "User Name",
  "roles": [
    {
      "name": "mobiles_user",
       "last_usage_at": {
         "$date": 1457000592991
        },
        "created_by": "987654",
        "created_at": {
          "$date": 1457000592991
        }
    },
    {
      "name": "webs_user",
       "last_usage_at": {
         "$date": 1457000592991
        },
        "created_by": "987654",
        "created_at": {
          "$date": 1457000592991
        }
    },
  ]
}

At the moment, I am only doing the following for those none nested attributes:

db.createCollection( "users",
   { "validator" : {
     "_id" : {
         "$type" : "string"
      },
      "email" : {
         "$regex" : /@gmail\.com$/
      },
      "name" : {
         "$type" : "string"
      }
   }
} )

Could anyone please advise that how to do the nested document validation?

Body:
Yes, you can validate all sub-documents in a document by negating $elemMatch, and you can ensure that the size is not 1.  It's sure not pretty though!  And not exactly obvious either.

> db.createCollection('users', {
...   validator: {
...     name: {$type: 'string'},
...     roles: {$exists: 'true'},
...     $nor: [
...       {roles: {$size: 1}},
...       {roles: {$elemMatch: {
...         $or: [
...           {name: {$not: {$type: 'string'}}},
...           {created_by: {$not: {$type: 'string'}}},
...         ]
...       }}}
...     ],
...   }
... })
{ "ok" : 1 }

This is confusing, but it works!  What it means is only accept documents where neither the size of roles is 1 nor roles has an element with a name that isn't a string or a created_by that isn't a string.

This is based upon the fact that in logic terms,

for all x: f(x) and g(x)

Is equivalent to

not exists x s.t.: not f(x) or not g(x)

We have to use the latter since MongoDB only gives us an exists operator.

Proof

Valid documents work:

> db.users.insert({
...   name: 'hello',
...   roles: [],
... })
WriteResult({ "nInserted" : 1 })

> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...     {name: 'bar', created_by: '3333'},
...   ]
... })
WriteResult({ "nInserted" : 1 })

If a field is missing from roles, it fails:

> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...     {created_by: '3333'},
...   ]
... })
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})

If a field in roles has the wrong type, it fails:

> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...     {name: 'bar', created_by: 3333},
...   ]
... })
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})

If roles has size 1 it fails:

> db.users.insert({
...   name: 'hello',
...   roles: [
...     {name: 'foo', created_by: '2222'},
...   ]
... })
WriteResult({
    "nInserted" : 0,
    "writeError" : {
        "code" : 121,
        "errmsg" : "Document failed validation"
    }
})

The only thing I can't figure out unfortunately is how to ensure that roles is an array.  roles: {$type: 'array'} seems to fail everything, I presume because it's actually checking that the elements are of type 'array'?


问:
How to split a sequence in F# based on another sequence in an idiomatic way
I have, in F#, 2 sequences, each containing distinct integers, strictly in ascending order: listMaxes and numbers.

If not Seq.isEmpty numbers, then it is guaranteed that not Seq.isEmpty listMaxes and Seq.last listMaxes >= Seq.last numbers.

I would like to implement in F# a function that returns a list of list of integers, whose List.length equals Seq.length listMaxes, containing the elements of numbers divided in lists, where the elements of listMaxes limit each group.

For example: called with the arguments

```<code>listMaxes = seq [ 25; 56; 65; 75; 88 ]
numbers = seq [ 10; 11; 13; 16; 20; 25; 31; 38; 46; 55; 65; 76; 88 ]
</code>```

this function should return

```<code>[ [10; 11; 13; 16; 20; 25]; [31; 38; 46; 55]; [65]; List.empty; [76; 88] ]
</code>```

I can implement this function, iterating over numbers only once:

```<code>let groupByListMaxes listMaxes numbers =
    if Seq.isEmpty numbers then
        List.replicate (Seq.length listMaxes) List.empty
    else
        List.ofSeq (seq {
            use nbe = numbers.GetEnumerator ()
            ignore (nbe.MoveNext ())
            for lmax in listMaxes do
                yield List.ofSeq (seq {
                    if nbe.Current <= lmax then
                        yield nbe.Current
                    while nbe.MoveNext () && nbe.Current <= lmax do
                        yield nbe.Current
                })
        })
</code>```

But this code feels unclean, ugly, imperative, and very un-F#-y.

Is there any functional / F#-idiomatic way to achieve this?

答:
Here's a version based on list interpretation, which is quite functional in style.  You can use Seq.toList to convert between them, whenever you want to handle that.  You could also use Seq.scan in conjunction with Seq.partition ((>=) max) if you want to use only library functions, but beware that it's very very easy to introduce a quadratic complexity in either computation or memory when doing that.

This is linear in both:

```<code>let splitAt value lst =
    let rec loop l1 = function
        | []                    -> List.rev l1, []
        | h :: t when h > value -> List.rev l1, (h :: t)
        | h :: t                -> loop (h :: l1) t
    loop [] lst

let groupByListMaxes listMaxes numbers =
    let rec loop acc lst = function
        | []     -> List.rev acc
        | h :: t ->
            let out, lst' = splitAt h lst
            loop (out :: acc) lst' t
    loop [] numbers listMaxes
</code>```

Body:
I have, in F#, 2 sequences, each containing distinct integers, strictly in ascending order: listMaxes and numbers.

If not Seq.isEmpty numbers, then it is guaranteed that not Seq.isEmpty listMaxes and Seq.last listMaxes >= Seq.last numbers.

I would like to implement in F# a function that returns a list of list of integers, whose List.length equals Seq.length listMaxes, containing the elements of numbers divided in lists, where the elements of listMaxes limit each group.

For example: called with the arguments

listMaxes = seq [ 25; 56; 65; 75; 88 ]
numbers = seq [ 10; 11; 13; 16; 20; 25; 31; 38; 46; 55; 65; 76; 88 ]

this function should return

[ [10; 11; 13; 16; 20; 25]; [31; 38; 46; 55]; [65]; List.empty; [76; 88] ]

I can implement this function, iterating over numbers only once:

let groupByListMaxes listMaxes numbers =
    if Seq.isEmpty numbers then
        List.replicate (Seq.length listMaxes) List.empty
    else
        List.ofSeq (seq {
            use nbe = numbers.GetEnumerator ()
            ignore (nbe.MoveNext ())
            for lmax in listMaxes do
                yield List.ofSeq (seq {
                    if nbe.Current <= lmax then
                        yield nbe.Current
                    while nbe.MoveNext () && nbe.Current <= lmax do
                        yield nbe.Current
                })
        })

But this code feels unclean, ugly, imperative, and very un-F#-y.

Is there any functional / F#-idiomatic way to achieve this?

Body:
Here's a version based on list interpretation, which is quite functional in style.  You can use Seq.toList to convert between them, whenever you want to handle that.  You could also use Seq.scan in conjunction with Seq.partition ((>=) max) if you want to use only library functions, but beware that it's very very easy to introduce a quadratic complexity in either computation or memory when doing that.

This is linear in both:

let splitAt value lst =
    let rec loop l1 = function
        | []                    -> List.rev l1, []
        | h :: t when h > value -> List.rev l1, (h :: t)
        | h :: t                -> loop (h :: l1) t
    loop [] lst

let groupByListMaxes listMaxes numbers =
    let rec loop acc lst = function
        | []     -> List.rev acc
        | h :: t ->
            let out, lst' = splitAt h lst
            loop (out :: acc) lst' t
    loop [] numbers listMaxes


问:
Give user an error if invalid Date entered
As part of a task for my first programming assignment we were required to create a program which tells the user how old they are in days, I've completed that however we need to use a try/catch. We've never been taught anything about them just basic concepts like classes/variables/arrays. Here is my code I need to add something in to simply tell the user if the DateTime object DateOfBirth is invalid in a text box and to start again, currently an invalid DOB just crashes the program. Here is is the code which calculates everything.</p>

```<code>private void buttonDaysOld_Click(object sender, EventArgs e)
{
    DateTime DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text+" you are "+(AgeInDays.ToString())+ " Days Old");
}
</code>```

答:
I'm guessing the error you're getting that crashes your application is a InvalidCastException when you try to cast your combobox values to a int. So all you need to do is surround your code with a try catch and do what you need in the catch part.

```<code>try {

    DateTime DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text + " you are " + (AgeInDays.ToString()) + " Days Old");
}
catch (InvalidCastException)
{
    MessageBox.Show("Wrong Format");
}
</code>```

Note you should probably check the exact error you're getting and place it in the catch(your_error).

You can always put:

```<code>catch (Exception)
</code>```

Which would catch all exception but it is not recommended that you do that, there's a post about that topic here.

If you're getting multiple exceptions that you need to handle, there's a great question about that, that explain how to handle it. You can learn more on try-catch and how they work by reading the documentation here.

Body:
As part of a task for my first programming assignment we were required to create a program which tells the user how old they are in days, I've completed that however we need to use a try/catch. We've never been taught anything about them just basic concepts like classes/variables/arrays. Here is my code I need to add something in to simply tell the user if the DateTime object DateOfBirth is invalid in a text box and to start again, currently an invalid DOB just crashes the program. Here is is the code which calculates everything.

private void buttonDaysOld_Click(object sender, EventArgs e)
{
    DateTime DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text+" you are "+(AgeInDays.ToString())+ " Days Old");
}

Body:
I'm guessing the error you're getting that crashes your application is a InvalidCastException when you try to cast your combobox values to a int. So all you need to do is surround your code with a try catch and do what you need in the catch part.

try {

    DateTime DateOfBirth = new DateTime((int)comboBoxYear.SelectedItem, comboBoxMonth.SelectedIndex + 1, (int)comboBoxDay.SelectedItem);
    TimeSpan diff = DateTime.Now - DateOfBirth;
    int AgeInDays = (int)diff.TotalDays;
    MessageBox.Show(textBoxName.Text + " you are " + (AgeInDays.ToString()) + " Days Old");
}
catch (InvalidCastException)
{
    MessageBox.Show("Wrong Format");
}

Note you should probably check the exact error you're getting and place it in the catch(your_error).

You can always put:

catch (Exception)

Which would catch all exception but it is not recommended that you do that, there's a post about that topic here.

If you're getting multiple exceptions that you need to handle, there's a great question about that, that explain how to handle it. You can learn more on try-catch and how they work by reading the documentation here.


问:
Strikethrough in Emacs image mode
With a .emacs loading iimage-mode and adoc-mode:

```<code>;; Don't glare 200W in my eyes all day:
(set-foreground-color "white")
(set-background-color "black")

;; Use adoc as major mode for any file with the extension .adoc.
(require 'adoc-mode)
(setq auto-mode-alist (cons '("\\.adoc\\'" . adoc-mode) auto-mode-alist))

;; Use iimage-mode as minor mode whenever we're in adoc-mode.
(add-hook 'adoc-mode-hook 'my-adoc-mode-hook)
(defun my-adoc-mode-hook ()
  "Custom `adoc-mode' behaviours."
  (iimage-mode 1))
</code>```

if I convert the file file.adoc

```<code>.A PNG smiley
image::smiley.png[]
</code>```

to HTML using Asciidoctor

```<code>asciidoctor file.adoc
</code>```

I get the nicely formatted HTML file

but Emacs shows a distracting strikethrough

How do I get rid of it?

答:
It looks like you're running into adoc's markup fontification for internal references. I was able to make that line go away by removing the underlining from markup-internal-reference-face. Something like this added to your .emacs might fix it:

```<code>(custom-set-faces
 '(markup-internal-reference-face ((t (:inherit markup-meta-face)))))
</code>```

Title: Strikethrough in Emacs image mode

Body:
With a .emacs loading iimage-mode and adoc-mode:

;; Don't glare 200W in my eyes all day:
(set-foreground-color "white")
(set-background-color "black")

;; Use adoc as major mode for any file with the extension .adoc.
(require 'adoc-mode)
(setq auto-mode-alist (cons '("\\.adoc\\'" . adoc-mode) auto-mode-alist))

;; Use iimage-mode as minor mode whenever we're in adoc-mode.
(add-hook 'adoc-mode-hook 'my-adoc-mode-hook)
(defun my-adoc-mode-hook ()
  "Custom `adoc-mode' behaviours."
  (iimage-mode 1))

if I convert the file file.adoc

.A PNG smiley
image::smiley.png[]

to HTML using Asciidoctor

asciidoctor file.adoc

I get the nicely formatted HTML file

but Emacs shows a distracting strikethrough

How do I get rid of it?

Body:
It looks like you're running into adoc's markup fontification for internal references. I was able to make that line go away by removing the underlining from markup-internal-reference-face. Something like this added to your .emacs might fix it:

(custom-set-faces
 '(markup-internal-reference-face ((t (:inherit markup-meta-face)))))


问:
Ionic Angular js IDE
Is there an IDE like Xcode to develop cross platform apps using ionic? I played with creator.ionic.io but they charge 40$ per month for the complete app development. Can you suggest some open source IDEs? Basically I wanted something similar to ionic where I can drag and drop objects to build the UI</p>

答:
I think community gets totally confused about the OP's question here.He is asking not about an IDE for developing Ionic apps.He is asking the IDE like an Ionic creator.Which is the IDE anyone can create ionic apps without writing a code.

What is an Ionic Creator? See here.

Creator is a simple drag-&-drop tool for going from  idea to App
  Store, with just the drag of a mouse.

There is no such free and open source tool but the price you have mentioned is not correct with the official Ionic creator. It is $24/mo.You can see details here.

PRO

$24/mo for individuals

Unlimited Projects

Private Projects

In-Tool Code Editing

Basic & Native Exporting

Creator Mobile App

Note:

By using above tool you can create Ionic 1 apps only.There is no support for Ionic 2 yet. You can see the Roadmap of Ionic 2 creator here.

Title: Ionic Angular js IDE


问:
What's the difference between MySQLdb, mysqlclient and MySQL connector/Python?
So I've been trying to do some database update with python and while setting up the whole dev environment, I came across these three things which made me dizzy.

There's MySQLdb

There's mysqlclient

And then there's a mysql connector python

What's each of them, the difference and where to use them? Thanks

答:
MySQLdb is a thin python wrapper around C module which implements API for MySQL database.

There was MySQLDb1 version of wrapper used some time ago and now it is considered to be a legacy. As MySQLDb1 started evolving to MySQLDb2 with bug fixes and Python3 support, a MySQLDb1 was forked and here is how mysqlclient appeared, with bugfixes and Python3 support. Sum up, so now we have MySQLDb2 which is not ready for production use, MySQLDb1 as an outdated driver and a community supported mysqlclient with bug fixes and Python3 support.

Now, to solve that mess, MySQL provides their own version of MySQL adapter - mysql connector, an all-in python module that uses MySQL API with no C modules dependencies and only standard python modules used.

So now the question comes down to: mysqlclient vs mysql connector.

As for me, I would go with officially supported library, however mysqlclient should be a good choice as well.
Both of them are being actively updated with fixes and new features which you can see by active commits in last days.

Note: I did not have much experience with them, so there might be cases when one or another does not suite your needs. Both libraries follow PEP-249 standard which means you should be fine with at least base functionality everywhere.

Installation and Dependencies

mysqlclient

As a fork of C wrapper it requires C modules to work with MySQL which adds python header files to build these extensions (read python-dev). Installation depends on the system you use, just make sure you aware of package names and can install them.

mysql connector
Main documentation is pretty clear, however you should be aware of Protobuf C++ dependency (for mysql connector versions >= 2.2.3).


问:
To run commands on different linux nide by jenkins
I want to jenkins to execute a list of commands on different linux node in a network.
What steps should I take to run a command on another linux node by adrressing its ip address</p>

答:
if I understood you correctly you should add this node as a slave machine to the Jenkins.
go to Manage Jenkins section and then to Manage Nodes and just add a new Node</p>


问:
Get the number of times a unique value appears in a table
I have a table like so:

```<code>Email | Number
a     |  0.5
a     |  1
a     |  1.1
b     |  5
b     |  3.7
</code>```

I want to preserve the same table layout, but get the instance number of a unique email based on the ranked order of the Number column:

```<code>Email | Number | RankOrder
a     |  0.5   |  3
a     |  1     |  2
a     |  1.1   |  1
b     |  7.7   |  1
b     |  6     |  2
</code>```

答:
If I understand correctly, you want the row_number() function (this is an ANSI standard function available in most databases):

```<code>select email, number,
        row_number() over (partition by email order by number desc) as rankorder
from t;
</code>```

Body:
I have a table like so:

Email | Number
a     |  0.5
a     |  1
a     |  1.1
b     |  5
b     |  3.7

I want to preserve the same table layout, but get the instance number of a unique email based on the ranked order of the Number column:

Email | Number | RankOrder
a     |  0.5   |  3
a     |  1     |  2
a     |  1.1   |  1
b     |  7.7   |  1
b     |  6     |  2

Body:
If I understand correctly, you want the row_number() function (this is an ANSI standard function available in most databases):

select email, number,
        row_number() over (partition by email order by number desc) as rankorder
from t;


答:
You can do this with a windowed Row_Number():

```<code>Select  Email, Number,
        Row_Number() Over (Partition By Email Order By Number Desc) As RankOrder
From    LikeSo;
</code>```

Title: Get the number of times a unique value appears in a table

Body:
You can do this with a windowed Row_Number():

Select  Email, Number,
        Row_Number() Over (Partition By Email Order By Number Desc) As RankOrder
From    LikeSo;