问:
Code has no error and logcat has nothing, but still unfortunately app stopped error
```<code>package com.example.darshreddy.diser;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SQLite extends Activity {
    Button but;
    EditText nam, mail, pass;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        nam = (EditText) findViewById(R.id.name);
        pass = (EditText) findViewById(R.id.passw);
        mail = (EditText) findViewById(R.id.emi);
        but = (Button) findViewById(R.id.button2);
        but.setOnClickListener((View.OnClickListener) this);
    }
        public void onClick(View arg0){
        switch (arg0.getId()) {
            case R.id.button2:
                boolean didItwork=true;
                try {
                    String name = nam.getText().toString();
                    String passw = pass.getText().toString();
                    String eml = mail.getText().toString();

                    SQL entry = new SQL(SQLite.this);
                    entry.open();
                    entry.createEntry(name, passw, eml);
                    entry.close();
                } catch (Exception e) {
                    didItwork=false;
                }finally {
                    if (didItwork) {
                        Dialog d = new Dialog(this);
                        d.setTitle("Heck yea!!");
                        TextView tv = new TextView(this);
                        tv.setText("success");
                        d.setContentView(tv);
                        d.show();
                    }

                }
        break;}
    }
}
</code>```

This is the code I wrote for executing SQLite database related file. I had
linked a registration from with it and the error is "unfortunately the app has stopped". please help me find the error if any. or suggest me some changes.
logcat shows

"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.darshreddy.diser/com.example.darshreddy.diser.SQLite}: java.lang.ClassCastException: com.example.darshreddy.diser.SQLite cannot be cast to android.view.View$OnClickListener"

答:
You need to implement OnClickListener interface like:

```<code>public class SQLite extends Activity implements View.OnClickListener {
</code>```

Also, add e.printStackTrace() in catch block as suggested by @Brett Jeffreson to get error/crash trace in log

Body:
package com.example.darshreddy.diser;

import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SQLite extends Activity {
    Button but;
    EditText nam, mail, pass;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.register);

        nam = (EditText) findViewById(R.id.name);
        pass = (EditText) findViewById(R.id.passw);
        mail = (EditText) findViewById(R.id.emi);
        but = (Button) findViewById(R.id.button2);
        but.setOnClickListener((View.OnClickListener) this);
    }
        public void onClick(View arg0){
        switch (arg0.getId()) {
            case R.id.button2:
                boolean didItwork=true;
                try {
                    String name = nam.getText().toString();
                    String passw = pass.getText().toString();
                    String eml = mail.getText().toString();

                    SQL entry = new SQL(SQLite.this);
                    entry.open();
                    entry.createEntry(name, passw, eml);
                    entry.close();
                } catch (Exception e) {
                    didItwork=false;
                }finally {
                    if (didItwork) {
                        Dialog d = new Dialog(this);
                        d.setTitle("Heck yea!!");
                        TextView tv = new TextView(this);
                        tv.setText("success");
                        d.setContentView(tv);
                        d.show();
                    }

                }
        break;}
    }
}

This is the code I wrote for executing SQLite database related file. I had
linked a registration from with it and the error is "unfortunately the app has stopped". please help me find the error if any. or suggest me some changes.
logcat shows

"java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.darshreddy.diser/com.example.darshreddy.diser.SQLite}: java.lang.ClassCastException: com.example.darshreddy.diser.SQLite cannot be cast to android.view.View$OnClickListener"

Body:
You need to implement OnClickListener interface like:

public class SQLite extends Activity implements View.OnClickListener {

Also, add e.printStackTrace() in catch block as suggested by @Brett Jeffreson to get error/crash trace in log


来源: stackexchange

问:
Can Lazy modify elements in Array in Scala?
I want to define an array, each element of array is a data set read from certain path in the file system, because the data reading is costly and the position in array to be visited is sparse, so I want to use Lazy modifier to realize that one data set will not be read until being visited. How can define this kind of array?</p>

答:
Yes,we can define it with view function.

Instead of (0 to 10).toArray

```<code>scala> val a=(0 to 10).toArray
a: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
</code>```

View can not instantiate the array  but when ever we call then only it executes

```<code>val a=(0 to 10).view
a: scala.collection.SeqView[Int,scala.collection.immutable.IndexedSeq[Int]] = SeqView(...)

scala> for (x <- a ){
     | println(x)}
0
1
2
3
4
5
6
7
8
9
10
</code>```

I hope this answered your question

ContentLicense: CC BY-SA 3.0

Body:
Yes,we can define it with view function.

Instead of (0 to 10).toArray

scala> val a=(0 to 10).toArray
a: Array[Int] = Array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

View can not instantiate the array  but when ever we call then only it executes

val a=(0 to 10).view
a: scala.collection.SeqView[Int,scala.collection.immutable.IndexedSeq[Int]] = SeqView(...)

scala> for (x <- a ){
     | println(x)}
0
1
2
3
4
5
6
7
8
9
10

I hope this answered your question


问:
JointsWP Custom Post Type Wordpress Menu
So I followed the JointsWP custom post type templates exactly. But in the wordpress admin, in the menu my Categories and Tags are not quite right. I need to remove the Categories and Tags menu items that belong to Posts.

Here's the current state of my wordpress admin menu for the CPT....

Listings (my CPT, exactly as I want)

- All Listings (working)

- Add New (working)

- Categories (I need this gone! this is actually connected to "Posts" categories for regular blog posts)

- Tags (I need this gone! this is actually connected to "Posts" tags for regular blog posts)

- Listings Categories (working)

- Listings Tags (working)

I have already tried the hack fix in my functions.php:

```<code>// Removing some menu items
function remove_menus() {
remove_menu_page( 'edit-tags.php?taxonomy=category&post_type=listings' );
remove_menu_page( 'edit-tags.php?taxonomy=post_tag&post_type=listings' );
}
add_action( 'admin_menu', 'remove_menus' );
</code>```

Here's a copy of my functions for the CPT, it's basically just a copy of what came with JointsWP, that I edited for my own purposes

```<code>function custom_post_example() {
register_post_type( 'listings',
    array('labels' => array(
        'name' => __('Listings', 'jointswp'),
        'singular_name' => __('Listing', 'jointswp'),
        'all_items' => __('All Listings', 'jointswp'),
        'add_new' => __('Add New', 'jointswp'),
        'add_new_item' => __('Add New Listing', 'jointswp'),
        'edit' => __( 'Edit', 'jointswp' ),
        'edit_item' => __('Edit Listing', 'jointswp'),
        'new_item' => __('New Listing', 'jointswp'),
        'view_item' => __('View Listing', 'jointswp'),
        'search_items' => __('Search Listings', 'jointswp'),
        'not_found' =>  __('Nothing found in the Database.', 'jointswp'),
        'not_found_in_trash' => __('Nothing found in Trash', 'jointswp'),
        'parent_item_colon' => ''
        ),

        'description' => __( 'This is the Listing custom post type', 'jointswp' ),
        'public' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'show_ui' => true,
        'query_var' => true,
        'menu_position' => 8,
        'menu_icon' => 'dashicons-building',
        'rewrite'   => array( 'slug' => 'listings', 'with_front' => false ),
        'has_archive' => 'listings',
        'capability_type' => 'post',
        'hierarchical' => false,
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'custom-fields', 'revisions', 'sticky')

    )
);

register_taxonomy_for_object_type('category', 'listings');
register_taxonomy_for_object_type('post_tag', 'listings');
}
add_action( 'init', 'custom_post_example');

register_taxonomy( 'listing_cat',
    array('listings'),
    array('hierarchical' => true,
        'labels' => array(
            'name' => __( 'Listing Categories', 'jointswp' ),
            'singular_name' => __( 'Listing Category', 'jointswp' ),
            'search_items' =>  __( 'Search Listing Categories', 'jointswp' ),
            'all_items' => __( 'All Listing Categories', 'jointswp' ),
            'parent_item' => __( 'Parent Listing Category', 'jointswp' ),
            'parent_item_colon' => __( 'Parent Listing Category:', 'jointswp' ),
            'edit_item' => __( 'Edit Listing Category', 'jointswp' ),
            'update_item' => __( 'Update Listing Category', 'jointswp' ),
            'add_new_item' => __( 'Add New Listing Category', 'jointswp' ),
            'new_item_name' => __( 'New Listing Category Name', 'jointswp' )
        ),
        'show_admin_column' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'listing' ),
    )
);

register_taxonomy( 'listing_tag',
    array('listings'),
    array('hierarchical' => false,
        'labels' => array(
            'name' => __( 'Listing Tags', 'jointswp' ),
            'singular_name' => __( 'Listing Tag', 'jointswp' ),
            'search_items' =>  __( 'Search Listing Tags', 'jointswp' ),
            'all_items' => __( 'All Listing Tags', 'jointswp' ),
            'parent_item' => __( 'Parent Listing Tag', 'jointswp' ),
            'parent_item_colon' => __( 'Parent Listing Tag:', 'jointswp' ),
            'edit_item' => __( 'Edit Listing Tag', 'jointswp' ),
            'update_item' => __( 'Update Listing Tag', 'jointswp' ),
            'add_new_item' => __( 'Add New Listing Tag', 'jointswp' ),
            'new_item_name' => __( 'New Listing Tag Name', 'jointswp' )
        ),
        'show_admin_column' => true,
        'show_ui' => true,
        'query_var' => true,
    )
);
</code>```

答:
You might have passed following parameter while registering your custom post type:

```<code>'taxonomies'            => array( 'category', 'post_tag' ),
</code>```

This line will associate default category and tags taxonomy to your custom post type. If you don't want in your custom post type, then you need to pass empty array in that parameter as following:

```<code>'taxonomies'            => array( ),
</code>```

So here is the array of arguments to be passed while registering custom post type:

```<code>$args = array(
        'label'                 => __( '[name of CPT]', 'text_domain' ),
        'description'           => __( 'Post Type Description', 'text_domain' ),
        'labels'                => $labels, // array of labels
        'supports'              => array( ),
        'taxonomies'            => array( ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
    );
    register_post_type( [custom post type name], $args );
</code>```

Body:
So I followed the JointsWP custom post type templates exactly. But in the wordpress admin, in the menu my Categories and Tags are not quite right. I need to remove the Categories and Tags menu items that belong to Posts.

Here's the current state of my wordpress admin menu for the CPT....

Listings (my CPT, exactly as I want)

- All Listings (working)

- Add New (working)

- Categories (I need this gone! this is actually connected to "Posts" categories for regular blog posts)

- Tags (I need this gone! this is actually connected to "Posts" tags for regular blog posts)

- Listings Categories (working)

- Listings Tags (working)

I have already tried the hack fix in my functions.php:

// Removing some menu items
function remove_menus() {
remove_menu_page( 'edit-tags.php?taxonomy=category&post_type=listings' );
remove_menu_page( 'edit-tags.php?taxonomy=post_tag&post_type=listings' );
}
add_action( 'admin_menu', 'remove_menus' );

Here's a copy of my functions for the CPT, it's basically just a copy of what came with JointsWP, that I edited for my own purposes

function custom_post_example() {
register_post_type( 'listings',
    array('labels' => array(
        'name' => __('Listings', 'jointswp'),
        'singular_name' => __('Listing', 'jointswp'),
        'all_items' => __('All Listings', 'jointswp'),
        'add_new' => __('Add New', 'jointswp'),
        'add_new_item' => __('Add New Listing', 'jointswp'),
        'edit' => __( 'Edit', 'jointswp' ),
        'edit_item' => __('Edit Listing', 'jointswp'),
        'new_item' => __('New Listing', 'jointswp'),
        'view_item' => __('View Listing', 'jointswp'),
        'search_items' => __('Search Listings', 'jointswp'),
        'not_found' =>  __('Nothing found in the Database.', 'jointswp'),
        'not_found_in_trash' => __('Nothing found in Trash', 'jointswp'),
        'parent_item_colon' => ''
        ),

        'description' => __( 'This is the Listing custom post type', 'jointswp' ),
        'public' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'show_ui' => true,
        'query_var' => true,
        'menu_position' => 8,
        'menu_icon' => 'dashicons-building',
        'rewrite'   => array( 'slug' => 'listings', 'with_front' => false ),
        'has_archive' => 'listings',
        'capability_type' => 'post',
        'hierarchical' => false,
        'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'custom-fields', 'revisions', 'sticky')

    )
);

register_taxonomy_for_object_type('category', 'listings');
register_taxonomy_for_object_type('post_tag', 'listings');
}
add_action( 'init', 'custom_post_example');

register_taxonomy( 'listing_cat',
    array('listings'),
    array('hierarchical' => true,
        'labels' => array(
            'name' => __( 'Listing Categories', 'jointswp' ),
            'singular_name' => __( 'Listing Category', 'jointswp' ),
            'search_items' =>  __( 'Search Listing Categories', 'jointswp' ),
            'all_items' => __( 'All Listing Categories', 'jointswp' ),
            'parent_item' => __( 'Parent Listing Category', 'jointswp' ),
            'parent_item_colon' => __( 'Parent Listing Category:', 'jointswp' ),
            'edit_item' => __( 'Edit Listing Category', 'jointswp' ),
            'update_item' => __( 'Update Listing Category', 'jointswp' ),
            'add_new_item' => __( 'Add New Listing Category', 'jointswp' ),
            'new_item_name' => __( 'New Listing Category Name', 'jointswp' )
        ),
        'show_admin_column' => true,
        'show_ui' => true,
        'query_var' => true,
        'rewrite' => array( 'slug' => 'listing' ),
    )
);

register_taxonomy( 'listing_tag',
    array('listings'),
    array('hierarchical' => false,
        'labels' => array(
            'name' => __( 'Listing Tags', 'jointswp' ),
            'singular_name' => __( 'Listing Tag', 'jointswp' ),
            'search_items' =>  __( 'Search Listing Tags', 'jointswp' ),
            'all_items' => __( 'All Listing Tags', 'jointswp' ),
            'parent_item' => __( 'Parent Listing Tag', 'jointswp' ),
            'parent_item_colon' => __( 'Parent Listing Tag:', 'jointswp' ),
            'edit_item' => __( 'Edit Listing Tag', 'jointswp' ),
            'update_item' => __( 'Update Listing Tag', 'jointswp' ),
            'add_new_item' => __( 'Add New Listing Tag', 'jointswp' ),
            'new_item_name' => __( 'New Listing Tag Name', 'jointswp' )
        ),
        'show_admin_column' => true,
        'show_ui' => true,
        'query_var' => true,
    )
);

Body:
You might have passed following parameter while registering your custom post type:

'taxonomies'            => array( 'category', 'post_tag' ),

This line will associate default category and tags taxonomy to your custom post type. If you don't want in your custom post type, then you need to pass empty array in that parameter as following:

'taxonomies'            => array( ),

So here is the array of arguments to be passed while registering custom post type:

$args = array(
        'label'                 => __( '[name of CPT]', 'text_domain' ),
        'description'           => __( 'Post Type Description', 'text_domain' ),
        'labels'                => $labels, // array of labels
        'supports'              => array( ),
        'taxonomies'            => array( ),
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'capability_type'       => 'page',
    );
    register_post_type( [custom post type name], $args );


问:
Maximum path cost in matrix
Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down  movement is allowed in a matrix and contains negative cost. A cell can be visited any number of times and after visiting a cell its cost is replaced with 0

Constraints

1 <= nxm <= 4x10^6

INPUT

```<code>4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20
</code>```

OUTPUT

```<code>37
</code>```

Explanation is given in the image
Explanation of Output

答:
For each element in a row, find the maximum cost that can be obtained if we move horizontally across the row, given that we go through that element.

Eg. For the row

```<code>1 2 3 -1 -2
</code>```

The maximum cost for each element obtained if we move horizontally given that we pass through that element will be

```<code>6 6 6 5 3
</code>```

Explanation:

for element 3: we can move backwards horizontally touching 1 and 2. we will not move horizontally forward as the values -1 and -2, reduces the cost value.

So the maximum cost for 3 = 1 + 2 + 3 = 6

The maximum cost matrix for each of elements in a row if we move horizontally, for the input you have given in the description will be

```<code>6     6    6    5      3
-5   -7    1    2      -148
6     6    6    -144   100
24    24   24   24     24
</code>```

Since we can move vertically from one row to the below row, update the maximum cost for each element as follows:

```<code>cost[i][j] = cost[i][j] + cost[i-1][j]
</code>```

So the final cost matrix will be :

```<code>6    6    6     5      3
1    -1   7     7      -145
7    5    13    -137   -45
31   29   37    -113   -21
</code>```

Maximum value in the last row of the above matrix will be give you the required output i.e 37

Title: Maximum path cost in matrix

Body:
Can anyone tell the algorithm for finding the maximum path cost in a NxM matrix starting from top left corner and ending with bottom right corner with left ,right , down  movement is allowed in a matrix and contains negative cost. A cell can be visited any number of times and after visiting a cell its cost is replaced with 0

Constraints

1 <= nxm <= 4x10^6

INPUT

4 5
1 2 3 -1 -2
-5 -8 -1 2 -150
1 2 3 -250 100
1 1 1 1 20

OUTPUT

37

Explanation is given in the image
Explanation of Output

Body:
For each element in a row, find the maximum cost that can be obtained if we move horizontally across the row, given that we go through that element.

Eg. For the row

1 2 3 -1 -2

The maximum cost for each element obtained if we move horizontally given that we pass through that element will be

6 6 6 5 3

Explanation:

for element 3: we can move backwards horizontally touching 1 and 2. we will not move horizontally forward as the values -1 and -2, reduces the cost value.

So the maximum cost for 3 = 1 + 2 + 3 = 6

The maximum cost matrix for each of elements in a row if we move horizontally, for the input you have given in the description will be

6     6    6    5      3
-5   -7    1    2      -148
6     6    6    -144   100
24    24   24   24     24

Since we can move vertically from one row to the below row, update the maximum cost for each element as follows:

cost[i][j] = cost[i][j] + cost[i-1][j]

So the final cost matrix will be :

6    6    6     5      3
1    -1   7     7      -145
7    5    13    -137   -45
31   29   37    -113   -21

Maximum value in the last row of the above matrix will be give you the required output i.e 37


问:
email attatchment winds up being 0,0 kb
Im making an emailng function and all works like a charm LOCALLY.
But when i take it to the webserver the email attatchment is 0,0kb.. i figured it has something to do with the stream but i doesnt get any error-messages so its hard to tell.
I cant use the stream on my server?
Heres the code:

```<code> If FileUpload1.HasFile = True Then
            Dim tempFileName As String() = FileUpload1.PostedFile.FileName.Split("\"c)
            Dim emailAttach As New Attachment(FileUpload1.PostedFile.InputStream, tempFileName(tempFileName.Length - 1))

            message.Attachments.Add(emailAttach)
            emailAttach.Dispose()
        End If
</code>```

Tried several things but cant find out why there is a problem

答:
Try the following:

```<code>message.Attachments.Add(New Attachment(FileUpload1.FileContent, tempFileName(tempFileName.Length - 1), FileFileUpload1.PostedFile.ContentType)
</code>```

Remarks:

I'm using the FileContent property of the FileUpload control (although it seems that it's just an alias to PostedFile.InputStream).

I'm specifying the MIME type of the file (third parameter of the constructor).

Also the problem might be because you make a call to Dispose method which (according to Reflector) closes the input stream.

ContentLicense: CC BY-SA 2.5

Title: email attatchment winds up being 0,0 kb

Body:
Im making an emailng function and all works like a charm LOCALLY.
But when i take it to the webserver the email attatchment is 0,0kb.. i figured it has something to do with the stream but i doesnt get any error-messages so its hard to tell.
I cant use the stream on my server?
Heres the code:

 If FileUpload1.HasFile = True Then
            Dim tempFileName As String() = FileUpload1.PostedFile.FileName.Split("\"c)
            Dim emailAttach As New Attachment(FileUpload1.PostedFile.InputStream, tempFileName(tempFileName.Length - 1))

            message.Attachments.Add(emailAttach)
            emailAttach.Dispose()
        End If

Tried several things but cant find out why there is a problem

Body:
Try the following:

message.Attachments.Add(New Attachment(FileUpload1.FileContent, tempFileName(tempFileName.Length - 1), FileFileUpload1.PostedFile.ContentType)

Remarks:

I'm using the FileContent property of the FileUpload control (although it seems that it's just an alias to PostedFile.InputStream).

I'm specifying the MIME type of the file (third parameter of the constructor).

Also the problem might be because you make a call to Dispose method which (according to Reflector) closes the input stream.


问:
linq: left join in linq with different type of conditions
I've two tables like promotionalOffers and PromotionalOffersUsed

I'm getting the matching records using joins now i wanted to include different conditions like PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null

I've written query in sql using left join working expected but I'm unable to write same query in linq

here my sql query

```<code>SELECT *
FROM PromotionalOffers
left JOIN PromotionalOffersUsed ON PromotionalOffers.Id = PromotionalOffersUsed.OfferId where PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null
</code>```

my linq query is

```<code>(from s in db.PromotionalOffers
 join e in db.PromotionalOffersUsed on s.Id equals e.OfferId
 where s.ISVCSPId == iSVCSPData.Id
 select s).ToListAsync();
</code>```

I'm unable to include left join here

答:
for left join you have to do like this , following is example of left outer join in linq

```<code>var leftFinal =
        from l in lefts
        join r in rights on l equals r.Left into lrs
        from lr in lrs.DefaultIfEmpty()
        select new { LeftId = l.Id, RightId = ((l.Key==r.Key) ? r.Id : 0 };
</code>```

Query

```<code>SELECT *
FROM PromotionalOffers
left JOIN PromotionalOffersUsed ON PromotionalOffers.Id = PromotionalOffersUsed.OfferId where PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null
</code>```

Tentative query in linq

```<code>var leftFinal =
        (from l in PromotionalOffers.Where(p=> p.ISVCSPId ==10)
        join r in PromotionalOffersUsed on l.ID equals r.OfferId  into lrs
        from lr in lrs.DefaultIfEmpty()
        select
          new { LeftId = l.Id, RightId = ((l.ID==r.OfferId  ) ? r.OfferId   : -1 }
        ).where(d=> d.RightID != -1);
</code>```

Body:
I've two tables like promotionalOffers and PromotionalOffersUsed

I'm getting the matching records using joins now i wanted to include different conditions like PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null

I've written query in sql using left join working expected but I'm unable to write same query in linq

here my sql query

SELECT *
FROM PromotionalOffers
left JOIN PromotionalOffersUsed ON PromotionalOffers.Id = PromotionalOffersUsed.OfferId where PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null

my linq query is

(from s in db.PromotionalOffers
 join e in db.PromotionalOffersUsed on s.Id equals e.OfferId
 where s.ISVCSPId == iSVCSPData.Id
 select s).ToListAsync();

I'm unable to include left join here

Body:
for left join you have to do like this , following is example of left outer join in linq

var leftFinal =
        from l in lefts
        join r in rights on l equals r.Left into lrs
        from lr in lrs.DefaultIfEmpty()
        select new { LeftId = l.Id, RightId = ((l.Key==r.Key) ? r.Id : 0 };

Query

SELECT *
FROM PromotionalOffers
left JOIN PromotionalOffersUsed ON PromotionalOffers.Id = PromotionalOffersUsed.OfferId where PromotionalOffers.ISVCSPId =10 and PromotionalOffersUsed.OfferId is null

Tentative query in linq

var leftFinal =
        (from l in PromotionalOffers.Where(p=> p.ISVCSPId ==10)
        join r in PromotionalOffersUsed on l.ID equals r.OfferId  into lrs
        from lr in lrs.DefaultIfEmpty()
        select
          new { LeftId = l.Id, RightId = ((l.ID==r.OfferId  ) ? r.OfferId   : -1 }
        ).where(d=> d.RightID != -1);


问:
Multiple buttons in footer in Ionic 3
I am trying to add two buttons (left and right) in the footer section in Ionic 3 project. Either its coming side by side or in two different row. Following is my code.

```<code><ion-footer>
  <ion-buttons text-start>
    <button ion-button clear (click)="backPage()">Back</button>
  </ion-buttons>
  <ion-buttons text-end>
    <button ion-button clear (click)="nextPage()">Next</button>
  </ion-buttons>
</ion-footer>
</code>```

Following is the result

答:
Use <ion-buttons start> or <ion-buttons end>

```<code><ion-footer>
<ion-toolbar>
<ion-buttons start>
  <button ion-button (click)="func1()"> Back
  </button>
</ion-buttons>

<ion-buttons end>
  <button ion-button (click)="func2()"> Next
  </button>
</ion-buttons>
</ion-toolbar>
</ion-footer>
</code>```

Title: Multiple buttons in footer in Ionic 3

Body:
I am trying to add two buttons (left and right) in the footer section in Ionic 3 project. Either its coming side by side or in two different row. Following is my code.

<ion-footer>
  <ion-buttons text-start>
    <button ion-button clear (click)="backPage()">Back</button>
  </ion-buttons>
  <ion-buttons text-end>
    <button ion-button clear (click)="nextPage()">Next</button>
  </ion-buttons>
</ion-footer>

Following is the result

Body:
Use <ion-buttons start> or <ion-buttons end>

<ion-footer>
<ion-toolbar>
<ion-buttons start>
  <button ion-button (click)="func1()"> Back
  </button>
</ion-buttons>

<ion-buttons end>
  <button ion-button (click)="func2()"> Next
  </button>
</ion-buttons>
</ion-toolbar>
</ion-footer>


问:
Where does parameter value that not show in firefox dev edition go?
where does firefox developer edition hide the XHR request param... ?

Here the image when i open the console tools and make some XHR request but none of parameter is show. Im using POST method when XHR it...

I am using firefox-dev edition version : 57.0b11 (64-bit)

thanks u for any guide.

答:
Fortunately those litte guys comeback again to their home as this is getting solved in the newer version of firefox dev edition (58.0b4 (64-bit)

Thanks you


问:
Method not found: 'System.String System.String.Format(System.IFormatProvider, System.String, System.Object)
I have a Web API 2 project with help pages that runs fine locally but throws this error when I push it to Azure:

Method not found: 'System.String System.String.Format
      (System.IFormatProvider, System.String, System.Object)

I temporarily turned custom errors off so full stack trace can be seen here

The error is originating from this line of code:

string selectExpression = String.Format(CultureInfo.InvariantCulture, MethodExpression, GetMemberName(reflectedActionDescriptor.MethodInfo));

See Line 96 here

The full source code is available on GitHub

I'm not even sure where to go with this one.

答:
Azure Data Lake Analytics runs on .NET 4.5 today. So we don't support .NET 4.6 assembly scenarios and this kind of errors are possible.
To avoid it, you should rebuild your assembly in .NET 4.5.

The following "non-recommended" workaround might work with a .NET 4.6 assembly: Rewriting
string.Format(provider, format, arg0, arg1)
into
string.Format(provider, format, new object[] { arg0, arg1 })

ContentLicense: CC BY-SA 4.0


问:
Xamarin : Adding condition inside isvisible in xaml
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have an  inside listview-viewcell, having 250 width and height.
Sometimes the value of mediaUrl is null. I want to hide the Image for null mediaUrl values and make visible for other values.
My problem is if the value of the mediaUrl is null showing blank space in the UI. Inside isVisible property how can I apply this condition?
My code is giving below:        </p>

```<code>    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Image
                            WidthRequest="250"
                            HeightRequest="250"
                            Source="{Binding mediaUrl}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

<p>Anybody please suggest a solution with working code.
Thanks in advance       </p>

答:
You can achieve this using a value converter

Create a converter like this

```<code>public class NullToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value != null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

This will return false if the value is null

Register it in your page like this

```<code><ContentPage
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:local="clr-namespace:yourNameSpaceToWhereYourConverteClassIs"
   x:Class="yourNameSpace.Views.MyPage">
<ContentPage.Resources>
        <ResourceDictionary>
            <local:NullToBoolConverter x:Key="NullToBoolConverter"/>
        </ResourceDictionary>
</ContentPage.Resources>
</code>```

Then add it like this

```<code><StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Image
                            WidthRequest="250"
                            HeightRequest="250"
                            Source="{Binding mediaUrl}"
                            IsVisible={Binding mediaUrl, Converter={StaticResource NullToBoolConverter}}/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>
</code>```

Body:
I am new with xamarin, I am facing an issue in my xamarin forms project.
I have an  inside listview-viewcell, having 250 width and height.
Sometimes the value of mediaUrl is null. I want to hide the Image for null mediaUrl values and make visible for other values.
My problem is if the value of the mediaUrl is null showing blank space in the UI. Inside isVisible property how can I apply this condition?
My code is giving below:

    <StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Image
                            WidthRequest="250"
                            HeightRequest="250"
                            Source="{Binding mediaUrl}"/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>

Anybody please suggest a solution with working code.
Thanks in advance

Body:
You can achieve this using a value converter

Create a converter like this

public class NullToBoolConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return value != null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

This will return false if the value is null

Register it in your page like this

<ContentPage
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:local="clr-namespace:yourNameSpaceToWhereYourConverteClassIs"
   x:Class="yourNameSpace.Views.MyPage">
<ContentPage.Resources>
        <ResourceDictionary>
            <local:NullToBoolConverter x:Key="NullToBoolConverter"/>
        </ResourceDictionary>
</ContentPage.Resources>

Then add it like this

<StackLayout>
        <ListView>
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                    <StackLayout>
                        <Image
                            WidthRequest="250"
                            HeightRequest="250"
                            Source="{Binding mediaUrl}"
                            IsVisible={Binding mediaUrl, Converter={StaticResource NullToBoolConverter}}/>
                        </StackLayout>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
          </ListView>
    </StackLayout>


问:
How to save and retrieve Array of Objects value from Dictionary in Swift iOS?
I am newly to Swift programming. I am developing an app where I have an array of Objects that I need to save it into one Dictionary, means for Dictionary 'Array of Objects' should be my Value and 'ID' should be my Key.

Here 2 elements contains in my Array, how can I save and retrieve from Dictionary using any unique Key. Please suggest me. Thank you!

答:
One simple approach is:</p>

```<code>struct VideoRangeInfo {
    var name: String
}

var arrayVideoRange = [
    VideoRangeInfo(name: "Name1"),
    VideoRangeInfo(name: "Name2"),
    VideoRangeInfo(name: "Name3")
]

var dictionary = [String: VideoRangeInfo]()
for obj in arrayVideoRange {
    dictionary.updateValue(obj, forKey: obj.name)
}

print(dictionary["Name1"]!)
print(dictionary["Name2"]!)
print(dictionary["Name3"]!)
</code>```

Body:
One simple approach is:

struct VideoRangeInfo {
    var name: String
}

var arrayVideoRange = [
    VideoRangeInfo(name: "Name1"),
    VideoRangeInfo(name: "Name2"),
    VideoRangeInfo(name: "Name3")
]

var dictionary = [String: VideoRangeInfo]()
for obj in arrayVideoRange {
    dictionary.updateValue(obj, forKey: obj.name)
}

print(dictionary["Name1"]!)
print(dictionary["Name2"]!)
print(dictionary["Name3"]!)


问:
Arrange data in the table
I've been working to this kind of data in array

```<code>data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]
</code>```

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

```<code><table>
      <thead>
            <tr class="text-center location text-white">
                <th>Employee</th>
                <th>Date</th>
                <th>Time In / Time Out</th>
            </tr>
      </thead>
      <tbody>
            <ng-container *ngFor= "let da of data; ">
            <tr *ngFor= "let s of da.details">
                  <td>
                     <strong>{{da.name}}</strong>
                  </td>
                  <td>
                     {{s.date}}
                  </td>
                  <td>
                    <input type="time [value]="s.start_time">
                    <strong>/</strong>
                    <input type="time [value]="s.end_time">
                  </td>
            </tr>
            </ng-container>
      </tbody>
</table>
</code>```

can you help on how I should display my data in the table properly.
I'm using angular 2

答:
Here is the code to arrange the data in row and col along with display the date in required format </p>

```<code><tbody>
        <ng-container *ngFor= "let da of data; ">
            <tr>
             <td [rowSpan]="da.details.length+1">
                 <strong>{{da.name}}</strong>
             </td>
            </tr>
            <ng-container *ngFor= "let s of da.details">
                <tr>
                    <td > {{s.date | date:'MMM dd, yyyy'}}</td>
                    <td><input type=time [value]="s.start_time"><strong>/</strong><input type=time [value]="s.end_time"></td>
                </tr>
            </ng-container>
        </ng-container>
</tbody>
</code>```

Title: Arrange data in the table

Body:
I've been working to this kind of data in array

data:[
    0:{
     name:"Pervies, Peter"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"16:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"16:00:00"}
     ]
    }
    1:{
     name:"Ming, Edmund"
     details:[
        {date:"2017-11-17",start_time:"08:00:00",end_time:"17:00:00"},
        {date:"2017-11-18",start_time:"08:00:00",end_time:"17:00:00"}
     ]
    }
]

I want the data to be display like this:

But it always turn out like this:

I use this code below in distributing data in the table

                Employee
                Date
                Time In / Time Out

            <ng-container *ngFor= "let da of data; ">

                     {{da.name}}

                     {{s.date}}

                    <input type="time [value]="s.start_time">
                    /
                    <input type="time [value]="s.end_time">

            </ng-container>

can you help on how I should display my data in the table properly.
I'm using angular 2

Body:
Here is the code to arrange the data in row and col along with display the date in required format

<tbody>
        <ng-container *ngFor= "let da of data; ">
            <tr>
             <td [rowSpan]="da.details.length+1">
                 <strong>{{da.name}}</strong>
             </td>
            </tr>
            <ng-container *ngFor= "let s of da.details">
                <tr>
                    <td > {{s.date | date:'MMM dd, yyyy'}}</td>
                    <td><input type=time [value]="s.start_time"><strong>/</strong><input type=time [value]="s.end_time"></td>
                </tr>
            </ng-container>
        </ng-container>
</tbody>


问:
Pretty print the JSON returned by express in Node.JS
I'm trying to follow this great design recommendation documentation for my server development in Node.JS regarding the JSON pretty formatting when returning it to the caller.

I can't figure out to do so when returning a file though:

```<code>app.get('/data.txt', function(req, res){
    return res.sendFile(path.resolve(__dirname + '/views/myData.json'));
});
</code>```

Would you have any suggestion?

答:
You can simply require the JSON file using :

```<code>let fileContents = require(path.resolve(__dirname + '/views/myData.json'));
</code>```

And then

```<code>app.get('/data.txt', function(req, res){
    return res.send(fileContents);
});
</code>```

Note: This approach doesn't send the file.It sends the contents of the JSON file in response.

Body:
I'm trying to follow this great design recommendation documentation for my server development in Node.JS regarding the JSON pretty formatting when returning it to the caller.

I can't figure out to do so when returning a file though:

app.get('/data.txt', function(req, res){
    return res.sendFile(path.resolve(__dirname + '/views/myData.json'));
});

Would you have any suggestion?

Body:
You can simply require the JSON file using :

let fileContents = require(path.resolve(__dirname + '/views/myData.json'));

And then

app.get('/data.txt', function(req, res){
    return res.send(fileContents);
});

Note: This approach doesn't send the file.It sends the contents of the JSON file in response.


问:
LOOPBACK Modify another model inside a hook
I want to insert new data in Event model when the property "code" in Transaction model is equal to 3</p>

```<code> module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
          //How to access and insert data in Event model ?
        }
    });
};
</code>```

答:
This worked for me</p>

```<code>module.exports = function(Transaction) {
  Transaction.observe('before save', function(ctx, next) {
    if(ctx.data.code == 3){
      var eventModel = Transaction.app.models.Event;
      eventModel.create({"nom":"ZONA ABC"}, function(err, obj){
        //console.log('eventModel create', err);
      });
    }
  });
};
</code>```

Body:
I want to insert new data in Event model when the property "code" in Transaction model is equal to 3

 module.exports = function(Transaction) {
    Transaction.observe('before save', function(ctx, next) {
        if(ctx.data.code == 3){
          //How to access and insert data in Event model ?
        }
    });
};

Body:
This worked for me

module.exports = function(Transaction) {
  Transaction.observe('before save', function(ctx, next) {
    if(ctx.data.code == 3){
      var eventModel = Transaction.app.models.Event;
      eventModel.create({"nom":"ZONA ABC"}, function(err, obj){
        //console.log('eventModel create', err);
      });
    }
  });
};


问:
How can I use the name of a string in the form of a string variable to retrieve that string from the XML files?
I want to use the string's name or label in the form of a string variable to retrieve that string from R.string.nameOfString but can't figure out how. In the method getText() which is used to get the string, it takes "resource id for the string as a parameter," and the resource id is an int. I'm not sure how the path in a string variable can be converted to this resource id so I can retrieve that string from the XML file.

答:
1.Add it to res/values/strings.xml file

```<code> <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="nameOfString">stringvalue</string>
    </resources>
</code>```

2.Use this value in java file

```<code>Textview.setText(getResources().getString(R.string.nameOfString));
</code>```

Hope this will help you and instead of Textview use your textview name

Body:
1.Add it to res/values/strings.xml file

 <?xml version="1.0" encoding="utf-8"?>
    <resources>
        <string name="nameOfString">stringvalue</string>
    </resources>

2.Use this value in java file

Textview.setText(getResources().getString(R.string.nameOfString));

Hope this will help you and instead of Textview use your textview name


答:
Try like this;</p>

```<code>(from s in db.PromotionalOffers
 join e in db.PromotionalOffersUsed on s.Id equals e.OfferId into joinT
 from e in joinT.DefaultIfEmpty()
 where s.ISVCSPId == 10 && (e == null || e.OfferId == null)
 select new { PromotionalOffers = s, PromotionalOffersUsed = joinT } ).ToListAsync();
</code>```

Title: linq: left join in linq with different type of conditions

Body:
Try like this;

(from s in db.PromotionalOffers
 join e in db.PromotionalOffersUsed on s.Id equals e.OfferId into joinT
 from e in joinT.DefaultIfEmpty()
 where s.ISVCSPId == 10 && (e == null || e.OfferId == null)
 select new { PromotionalOffers = s, PromotionalOffersUsed = joinT } ).ToListAsync();


问:
Why does this line not compile?
The following code doesn't compile ( Ideone link : https://ideone.com/DKI9Fm ). Why?:

EDIT: As per documentation of std::map, const Key& type is accepted by std::map::find. So passing const int* to find() should be okay.

```<code>#include <iostream>
#include <map>
using namespace std;

class ConstDemo
{
    std::map<int*, int> m_Map;

public:
   ConstDemo(int count, int* pArray)
   {
       for(int i=0; i < count; ++i)
       {
          m_Map.insert(std::make_pair(&(pArray[i]),0));
       }

   }

   bool Find(const int* i) const
   {
       // DOESN"T COMPILE!
       return (m_Map.find(i) != m_Map.end());
   }

};

int main() {

    int a[10];
    ConstDemo cd(10, a);
    if(cd.Find(&a[5]))
       cout << "Found!" << std::endl;

    return 0;
}
</code>```

答:
const int* and int* const aren't same. Try changing it to int* const:

```<code>bool Find(int* const i) const
</code>```

This is because your key_type is int* (std::map<int*, int> m_Map;). And m_Map.find expects a const key_type as a parameter, i.e., int* const in your case. But you're passing a const int**.

If you pass a int* to m_Map.find, it would be okay too, because it can convert an int* to int* const, but it can't convert int* to const int*.

And also, there's a semicolon missing at the end of the following line int main:

```<code>ConstDemo cd(10, a)
</code>```

Now, see it here on Ideone.

EDIT:

After the edit in your question

As per documentation of std::map, const Key& type is accepted by std::map::find. So passing const int* to find() should be okay.

const Key& is a constant Key, so in your case, you need to pass a constant
int* now. But const int* doesn't define a constant int*, it merely defines a pointer to const int. int* const defines a constant int*, so that's why it's giving error if you pass const int*.

Title: Why does this line not compile?

Body:
The following code doesn't compile ( Ideone link : https://ideone.com/DKI9Fm ). Why?:

EDIT: As per documentation of std::map, const Key& type is accepted by std::map::find. So passing const int* to find() should be okay.

#include <iostream>
#include <map>
using namespace std;

class ConstDemo
{
    std::map<int*, int> m_Map;

public:
   ConstDemo(int count, int* pArray)
   {
       for(int i=0; i < count; ++i)
       {
          m_Map.insert(std::make_pair(&(pArray[i]),0));
       }

   }

   bool Find(const int* i) const
   {
       // DOESN"T COMPILE!
       return (m_Map.find(i) != m_Map.end());
   }

};

int main() {

    int a[10];
    ConstDemo cd(10, a);
    if(cd.Find(&a[5]))
       cout << "Found!" << std::endl;

    return 0;
}

Body:
const int* and int* const aren't same. Try changing it to int* const:

bool Find(int* const i) const

This is because your key_type is int* (std::map<int*, int> m_Map;). And m_Map.find expects a const key_type as a parameter, i.e., int* const in your case. But you're passing a const int**.

If you pass a int* to m_Map.find, it would be okay too, because it can convert an int* to int* const, but it can't convert int* to const int*.

And also, there's a semicolon missing at the end of the following line int main:

ConstDemo cd(10, a)

Now, see it here on Ideone.

EDIT:

After the edit in your question

As per documentation of std::map, const Key& type is accepted by std::map::find. So passing const int* to find() should be okay.

const Key& is a constant Key, so in your case, you need to pass a constant
int* now. But const int* doesn't define a constant int*, it merely defines a pointer to const int. int* const defines a constant int*, so that's why it's giving error if you pass const int*.


问:
Dimension xml, unable to build "error: 'float|fraction' is an invalid format."
After updating android studio to 3.0 and updating build tool version from '25.0.0' to '26.0.2', I'm getting this error msg 'float|fraction' is an invalid format.   Basically unable to build the code.

          My dimen item is:

 <item name="default_key_width" format="float|fraction" type="dimen">10%p</item>.

     Need some workaround. Also if I change float|fraction to float then I get error msg as invalid type: dimen. Please help.

答:
You should use 10.0 instead of 10%p.

```<code><item name="default_key_width" format="float" type="dimen">10.0</item>
</code>```

After that, Clean-Rebuild-RUN.

Body:
You should use 10.0 instead of 10%p.

<item name="default_key_width" format="float" type="dimen">10.0</item>

After that, Clean-Rebuild-RUN.


问:
PHP - While writing a fixed length file, PHP is not processing `\t` as Tab after the first one. Why?
I am writing a fixed length file using PHP. Each character will have a predefined length. If characters are less than the length then it will insert that number of blank spaces. Each field is separated by TAB.

```<code>$str1 = str_pad('ten',10)."\t";
$str2 = str_pad('seven',7)."\t";
$str3 = str_pad('fifteen',15)."\t";

$str = $str1.$str2.$str3;

file_put_contents("newfile.txt",$str);
</code>```

But TAB is not working as expected.

I can see TAB only after first word (ten). After that there are no more TABs in the output file.

答:
In Your Case, try this code :</p>

```<code>$str1 = str_pad('ten',10)."\t";
$str2 = str_pad('seven',7)."\t\t";
$str3 = str_pad('fifteen',15)."\t\t";

$str = $str1.$str2.$str3;

file_put_contents("newfile.txt",$str);
</code>```

Body:
I am writing a fixed length file using PHP. Each character will have a predefined length. If characters are less than the length then it will insert that number of blank spaces. Each field is separated by TAB.

$str1 = str_pad('ten',10)."\t";
$str2 = str_pad('seven',7)."\t";
$str3 = str_pad('fifteen',15)."\t";

$str = $str1.$str2.$str3;

file_put_contents("newfile.txt",$str);

But TAB is not working as expected.

I can see TAB only after first word (ten). After that there are no more TABs in the output file.

Body:
In Your Case, try this code :

$str1 = str_pad('ten',10)."\t";
$str2 = str_pad('seven',7)."\t\t";
$str3 = str_pad('fifteen',15)."\t\t";

$str = $str1.$str2.$str3;

file_put_contents("newfile.txt",$str);


问:
variable with "true" value does not meet [variable] == "true" javascript
I have a variable declared as true

```<code>var g1 = sessionStorage.getItem("g1"); //true
var g2 = sessionStorage.getItem("g2"); //false
var g3 = sessionStorage.getItem("g3"); //false
</code>```

but in my function

```<code>function checkmonitogift() {
    console.log(g1);
    if (g1 == true) {
        $("#g1").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g1").html("OK");
    }

    if (g2 == false) {
        $("#g2").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g2").html("OK");
    }

    if (g3 == false) {
        $("#g3").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g3").html("OK");
    }

}
</code>```

console return "true" but it still does not meet the condition of the if statement

答:
There are many things you can do to compare string to boolean

The two I would prefer are :

```<code>var trueStr = "true";
var g1 = (trueStr === sessionStorage.getItem("g1") );
var g2 = (trueStr === sessionStorage.getItem("g2") );
var g3 = (trueStr ===  sessionStorage.getItem("g3") );
</code>```

or

```<code>var g1 = JSON.parse(sessionStorage.getItem("g1"));
var g2 = JSON.parse(sessionStorage.getItem("g2"));
var g3 = JSON.parse(sessionStorage.getItem("g3"));
</code>```

Then your variables will be booleanadn rest will work fine.

Body:
I have a variable declared as true

var g1 = sessionStorage.getItem("g1"); //true
var g2 = sessionStorage.getItem("g2"); //false
var g3 = sessionStorage.getItem("g3"); //false

but in my function

function checkmonitogift() {
    console.log(g1);
    if (g1 == true) {
        $("#g1").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g1").html("OK");
    }

    if (g2 == false) {
        $("#g2").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g2").html("OK");
    }

    if (g3 == false) {
        $("#g3").css({
            "background-color": "rgba(176,5,8,.9)",
            "cursor": "not-allowed"
        });
        $("#g3").html("OK");
    }

}

console return "true" but it still does not meet the condition of the if statement

Body:
There are many things you can do to compare string to boolean

The two I would prefer are :

var trueStr = "true";
var g1 = (trueStr === sessionStorage.getItem("g1") );
var g2 = (trueStr === sessionStorage.getItem("g2") );
var g3 = (trueStr ===  sessionStorage.getItem("g3") );

or

var g1 = JSON.parse(sessionStorage.getItem("g1"));
var g2 = JSON.parse(sessionStorage.getItem("g2"));
var g3 = JSON.parse(sessionStorage.getItem("g3"));

Then your variables will be booleanadn rest will work fine.


问:
Debugging permission denied/rules with angularfire
I am getting "Error: permission_denied: Client doesn't have permission to access the desired data."  I am relatively sure I have a rule problem.  Is there a way to trace which client calls in angularfire failed?  The level of abstraction and ansynchronicity in this library makes it difficult to even find the function call that caused it let alone the actual firebase REST call.</p>

答:
Go to Firebase console.
On left side bar, click on "Develop" to expand.
Click on "Database" option.
On main screen click on "Rules" tab.

Copy paste the below JSON in rules

```<code>{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}
</code>```

Below is the screenshot :-

Body:
Go to Firebase console.
On left side bar, click on "Develop" to expand.
Click on "Database" option.
On main screen click on "Rules" tab.

Copy paste the below JSON in rules

{
  "rules": {
    ".read": true,
    ".write": "auth != null"
  }
}

Below is the screenshot :-


答:
Short answer:

Use

```<code>bool Find(int* i) const { ... }
</code>```

Long answer:

The declarations of std::map::find until C++11:

```<code>iterator find( const Key& key );
const_iterator find( const Key& key ) const;
</code>```

The argument type is const Key&, not Key or Key&.

In your case, Key is int*, not cons int*,

If we substitute Key in the declarations, they look like:

```<code>iterator find( int * const & key );  // Not "const int*&"
                                     // That's unforunate part
const_iterator find( int * const & key ) const;
</code>```

Such a function cannot be called with an variable whose type is const int*. That would allow the function to break the const-ness of the object that the pointer points to.

Title: Why does this line not compile?

Body:
Short answer:

Use

bool Find(int* i) const { ... }

Long answer:

The declarations of std::map::find until C++11:

iterator find( const Key& key );
const_iterator find( const Key& key ) const;

The argument type is const Key&, not Key or Key&.

In your case, Key is int*, not cons int*,

If we substitute Key in the declarations, they look like:

iterator find( int * const & key );  // Not "const int*&"
                                     // That's unforunate part
const_iterator find( int * const & key ) const;

Such a function cannot be called with an variable whose type is const int*. That would allow the function to break the const-ness of the object that the pointer points to.


问:
android getting pictures from drawables
Bitmap picture = BitmapFactory.decodeResource(getResources(),R.drawable.phscale);

apart from above code any other ways to get the bitmap from drawables

答:
If you would like to have full control over resource bits, you'd better put it either in res/asset or res/raw folders and then get access to them as:

```<code>InputStream is=this.getResources().getAssets().open("drawable.png");
//
is=this.getResources().openRawResource(R.raw.myDrawable);
</code>```

Title: android getting pictures from drawables

Body:
If you would like to have full control over resource bits, you'd better put it either in res/asset or res/raw folders and then get access to them as:

InputStream is=this.getResources().getAssets().open("drawable.png");
//
is=this.getResources().openRawResource(R.raw.myDrawable);


问:
Cannot find bundler gem for a Jekyll blog
I'm trying to setup a new Jekyll site and am running into issues after I create a new site using jekyll new testSite.

I get an error saying:

```<code>New jekyll site installed in /Users/myPath.
  Dependency Error: Yikes! It looks like you don't have bundler or one of its dependencies installed. In order to use Jekyll as currently configured, you'll need to install this gem. The full error message from Ruby is: 'cannot load such file -- bundler' If you run into trouble, you can find helpful resources at http://jekyllrb.com/help/!
jekyll 3.3.1 | Error:  bundler
</code>```

I've installed bundler already using gem install bundler, but it can't seem to find it.

bundler -v gives Bundler version 1.14.2

jekyll -v gives jekyll 3.3.1

Thanks in advance!

答:
The below command worked for me, in ubuntu. </p>

```<code>sudo apt install ruby-bundler
</code>```

Body:
I'm trying to setup a new Jekyll site and am running into issues after I create a new site using jekyll new testSite.

I get an error saying:

New jekyll site installed in /Users/myPath.
  Dependency Error: Yikes! It looks like you don't have bundler or one of its dependencies installed. In order to use Jekyll as currently configured, you'll need to install this gem. The full error message from Ruby is: 'cannot load such file -- bundler' If you run into trouble, you can find helpful resources at http://jekyllrb.com/help/!
jekyll 3.3.1 | Error:  bundler

I've installed bundler already using gem install bundler, but it can't seem to find it.

bundler -v gives Bundler version 1.14.2

jekyll -v gives jekyll 3.3.1

Thanks in advance!

Body:
The below command worked for me, in ubuntu.

sudo apt install ruby-bundler


问:
what is the db argument's value or usage for this javascript es6 fat arrow function?
```<code>initializeDb( db => {

    // internal middleware
    app.use(middleware({ config, db }));

    // api router
    app.use('/api', api({ config, db }));

    app.server.listen(process.env.PORT || config.port, () => {
        console.log(`Started on port ${app.server.address().port}`);
    });
});
</code>```

https://github.com/developit/express-es6-rest-api/blob/master/src/index.js#L27

Above situation, the db seems pop out of nowhere, to see the context, please click on the link direct to the source code.

I simulated the same way here (https://codepen.io/adamchenwei/pen/vWWmXa) the db shouldn't even be accessible. What exactly the db does then in that specific boilerplate?

答:
Above situation, the db seems pop out of nowhere

It's the parameter of the function you pass to initializeDb. initializeDb presumable creates a new database instance and passes that instance to the the function you pass to it.

That's just how functions work, they accept parameters that are provided at call time. Only in your example it is not you who calls the function, but another function (initializeDb).

Simplified example of a function that takes a callback:

function answerToEverything(callback) {
  callback(42);
}

answerToEverything(answer => console.log(answer));```

Body:
initializeDb( db => {

    // internal middleware
    app.use(middleware({ config, db }));

    // api router
    app.use('/api', api({ config, db }));

    app.server.listen(process.env.PORT || config.port, () => {
        console.log(`Started on port ${app.server.address().port}`);
    });
});

https://github.com/developit/express-es6-rest-api/blob/master/src/index.js#L27

Above situation, the db seems pop out of nowhere, to see the context, please click on the link direct to the source code.

I simulated the same way here (https://codepen.io/adamchenwei/pen/vWWmXa) the db shouldn't even be accessible. What exactly the db does then in that specific boilerplate?


问:
What is system.in
Consider this Scanner input example.

```<code>Scanner user_input = new Scanner( System.in );
</code>```

Here Scanner is the CLASS.
user_input is the OBJECT under Scanner class.
What is (System.in)? Is it a parameter passed or a object under Scanner class?.

Consider another example.

```<code>dog dog1 = new dog(25)
</code>```

Here I have set dog class to accept size as a parameter.

What exactly is System.in?

答:
Scanner class has a constructor Scanner(InputStream) in its profile i.e when we call Scanner() constructor during the object creation time it will let you to pass the object of InputStream class.

"in" is an object of "InputStream" class defined in System class(like "out" is an object of PrintStream class defined in System class).

Thus System.in is nothing but calling the "in" object of InputStream class defined in System class when Scanner constructor is called during object creation time.

Scanner(InputStream) is pre-defined constructor in Scanner class which when calls requires the object of InputStream class as the parameter and that object is System.in.

Title: What is system.in

Body:
Consider this Scanner input example.

Scanner user_input = new Scanner( System.in );

Here Scanner is the CLASS.
user_input is the OBJECT under Scanner class.
What is (System.in)? Is it a parameter passed or a object under Scanner class?.

Consider another example.

dog dog1 = new dog(25)

Here I have set dog class to accept size as a parameter.

What exactly is System.in?


问:
Xcode right pane (utilities pane) not applicable?
I was programming using Swift in Xcode, halfway through when I wanted to edit a button using the utilities pane, I realised it became "Not Applicable". Attributes inspector, Connections inspector, etc all became "Not Applicable", only the Quick Help inspector still shows.

I have selected the button in the Storyboard.

Can anybody help with this?

Attached are screenshots..

答:
Storyboard -> Viewcontroller -> Control -> (Identity / Attributes / Size / Connections' Inspector) window not works then follow below steps.

```<code>1. Open any file (like AppDelegate) but not storyboard.
2. Then close xcode.
3. Open xcode again.
</code>```

Works fine in Almost all updated version of Xcode.

Body:
Storyboard -> Viewcontroller -> Control -> (Identity / Attributes / Size / Connections' Inspector) window not works then follow below steps.

1. Open any file (like AppDelegate) but not storyboard.
2. Then close xcode.
3. Open xcode again.

Works fine in Almost all updated version of Xcode.


问:
How to pass Dictionary<string, string> object in some method
Can somebody give an example of how i pass Dictionary object in some method.???</p>

答:
You can pass a dictionary like a normal argument:

```<code>private void MyMethod(Dictionary<string,string> myDictionary) {
    //code
}
</code>```

Or you can pass it as an object and cast later like:

```<code>private void MyMethod(Object myDictionary) {
   string color = ((Dictionary<string,string>)myDictionary)["color"];
}
</code>```

Body:
You can pass a dictionary like a normal argument:

private void MyMethod(Dictionary<string,string> myDictionary) {
    //code
}

Or you can pass it as an object and cast later like:

private void MyMethod(Object myDictionary) {
   string color = ((Dictionary<string,string>)myDictionary)["color"];
}


问:
How to generate numbers that follows normal distribution but w.r.t. time in Matlab
As time moves along x-axis, the output value (may be freq or prob) be shown accordingly i.e. as time moves the values should increase initially till mean and then decrease. I have prespecified mean mu=10 and standard deviation sigma=2.</p>

答:
Do you mean you want to plot a Gaussian function? I am not sure if you also wanted some sort of animation. If not, you can modify the code below to turn off modification.</p>

```<code>clear; close all; clc;

% Set the mean and standard deviation
mu = 10;
sigma = 2;

% Time t
t = linspace(0,20,101);

% The equation for a normal distribution
f = 1/(sqrt(2*pi)*sigma)*exp( -(t-mu).^2/(2*sigma^2));

hold on;
xlim([0,20]);
ylim([0,0.25]);
axis manual;
for i=1:length(t)
    plot( t(1:i), f(1:i), 'b-');
    pause(0.1);
end
hold off;
</code>```

Body:
Do you mean you want to plot a Gaussian function? I am not sure if you also wanted some sort of animation. If not, you can modify the code below to turn off modification.

clear; close all; clc;

% Set the mean and standard deviation
mu = 10;
sigma = 2;

% Time t
t = linspace(0,20,101);

% The equation for a normal distribution
f = 1/(sqrt(2*pi)*sigma)*exp( -(t-mu).^2/(2*sigma^2));

hold on;
xlim([0,20]);
ylim([0,0.25]);
axis manual;
for i=1:length(t)
    plot( t(1:i), f(1:i), 'b-');
    pause(0.1);
end
hold off;


问:
building python 3.6.3 from scratch on openSUSE
I've been having a hard time building python 3.6.3 from source on openSUSE LEAP 42.3.

When I started configuring the build I ran:

```<code>./configure --prefix=/opt/python3.6 --with-pydebug --enable-optimizations --enable-shared
</code>```

and in another rendition

```<code>./configure --prefix=/opt/python3.6 --with-pydebug --enable-optimizations --enable-shared --with-system-expat --with-system-ffi
</code>```

prior to both, CXX was defined with

```<code>CXX = "/usr/bin/g++"
</code>```

Configuration goes well (or it seems to) and then when I start make, after some success, it ALWAYS fails with this:

gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3
  -Wall -Wstrict-prototypes    -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers   -I. -I./Include    -DPy_BUILD_CORE  -I./Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI -c ./Modules/expat/xmlparse.c -o Modules/xmlparse.o ./Modules/expat/xmlparse.c:92:3: error: #error You do not have support for any sources of high quality entropy
  enabled. For end user security, that is probably not what you want.
  Your options include: * Linux + glibc >=2.25 (getrandom):
  HAVE_GETRANDOM, * Linux + glibc <2.25 (syscall SYS_getrandom):
  HAVE_SYSCALL_GETRANDOM, * BSD / macOS >=10.7 (arc4random_buf):
  HAVE_ARC4RANDOM_BUF, * BSD / macOS <10.7 (arc4random):
  HAVE_ARC4RANDOM, * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF +
  HAVE_LIBBSD, * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, *
  Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM * Windows
  (RtlGenRandom): _WIN32. If insist on not using any of these, bypass
  this error by defining XML_POOR_ENTROPY; you have been warned. If you
  have reasons to patch this detection code away or need changes to the
  build system, please open a bug. Thank you!

I googled and I have yet to see something on this error.

One last note.  I tried various permutations of ./configure, removing various feature flags but always keeping the prefix

Can someone suggest WHY this is failing? (and how to fix it please)  This is the first time it has happened to me and I suspect very strongly that I had forgotten to install something, but expat and libexpat are all there.

My thanks

答:
OK so this answer is a workaround and for the sake of my need, it will suffice.
I remembered that SUSE has an open build service (which ROCKS \m/ - https://build.opensuse.org/)

From there, I found some enterprising dev who had created a repo for Python 3.6.3 (I will be sending them an email to find out how they did it)

But it was a simple matter of adding the repo [http://download.opensuse.org/repositories/devel:/languages:/python/openSUSE_Leap_42.3/] and then doing a repo specific distro upgrade (zypper dup --repo python3.6.3)

To be extra safe, I create a btrfs snapshot so I can roll back if things went sideways.. they did not and I am a happy camper.

Python 3.6.3 repo: Python 3.6.3 repo on OBS

Body:
I've been having a hard time building python 3.6.3 from source on openSUSE LEAP 42.3.

When I started configuring the build I ran:

./configure --prefix=/opt/python3.6 --with-pydebug --enable-optimizations --enable-shared

and in another rendition

./configure --prefix=/opt/python3.6 --with-pydebug --enable-optimizations --enable-shared --with-system-expat --with-system-ffi

prior to both, CXX was defined with

CXX = "/usr/bin/g++"

Configuration goes well (or it seems to) and then when I start make, after some success, it ALWAYS fails with this:

gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3
  -Wall -Wstrict-prototypes    -std=c99 -Wextra -Wno-unused-result -Wno-unused-parameter -Wno-missing-field-initializers   -I. -I./Include    -DPy_BUILD_CORE  -I./Modules/expat -DHAVE_EXPAT_CONFIG_H -DUSE_PYEXPAT_CAPI -c ./Modules/expat/xmlparse.c -o Modules/xmlparse.o ./Modules/expat/xmlparse.c:92:3: error: #error You do not have support for any sources of high quality entropy
  enabled. For end user security, that is probably not what you want.
  Your options include: * Linux + glibc >=2.25 (getrandom):
  HAVE_GETRANDOM, * Linux + glibc <2.25 (syscall SYS_getrandom):
  HAVE_SYSCALL_GETRANDOM, * BSD / macOS >=10.7 (arc4random_buf):
  HAVE_ARC4RANDOM_BUF, * BSD / macOS <10.7 (arc4random):
  HAVE_ARC4RANDOM, * libbsd (arc4random_buf): HAVE_ARC4RANDOM_BUF +
  HAVE_LIBBSD, * libbsd (arc4random): HAVE_ARC4RANDOM + HAVE_LIBBSD, *
  Linux / BSD / macOS (/dev/urandom): XML_DEV_URANDOM * Windows
  (RtlGenRandom): _WIN32. If insist on not using any of these, bypass
  this error by defining XML_POOR_ENTROPY; you have been warned. If you
  have reasons to patch this detection code away or need changes to the
  build system, please open a bug. Thank you!

I googled and I have yet to see something on this error.

One last note.  I tried various permutations of ./configure, removing various feature flags but always keeping the prefix

Can someone suggest WHY this is failing? (and how to fix it please)  This is the first time it has happened to me and I suspect very strongly that I had forgotten to install something, but expat and libexpat are all there.

My thanks


问:
How to Listen for Events in children components in React Native?
I want to implement an event listener from parents to children components in my React Native app, I'm using a StackNavigator as a router.

How can I listen for events occurred in the top/parent components?

答:
Simply use React Native's DeviceEventEmitter.Emit your event from parent component like below:

```<code>DeviceEventEmitter.emit('eventKey', {name:'John', age:23});
</code>```

and listen event in children component

```<code>componentDidMount(){
      //add listener
      this.eventListener = DeviceEventEmitter.addListener('eventKey',this.handleEvent);
}

handleEvent=(event)=>{
 //Do something with event object
}

componentWillUnmount(){
      //remove listener
      this.eventListener.remove();
}
</code>```

Body:
Simply use React Native's DeviceEventEmitter.Emit your event from parent component like below:

DeviceEventEmitter.emit('eventKey', {name:'John', age:23});

and listen event in children component

componentDidMount(){
      //add listener
      this.eventListener = DeviceEventEmitter.addListener('eventKey',this.handleEvent);
}

handleEvent=(event)=>{
 //Do something with event object
}

componentWillUnmount(){
      //remove listener
      this.eventListener.remove();
}


问:
Jquery - Sortable did not work when div.load is called
I have this issue that every time the div is loaded using div.load in the ajax success, the code for sortable will not work. Sortable will work again after the page is refreshed manually. What could be the possible solution for this?

```<code>$(document).on('click', '#add-song-tag', function() {

tag_id = $('#tags').val();

$.ajax({
    url: base_url + '/songtags/add_song_tag',
    type: 'POST',
    data: {
        song_info_id: song_info_id,
        tag_id: tag_id
    },
    success: function() {

        $('#category').load(window.location.href + ' #category');

        $('#modal-categories').trigger('change');
    },
    error: function(xhr) {
        console.log(xhr.responseText);
    }
})
</code>```

});

I have my code in the sortable.js like

```<code>$( function() {
$( "#sortable, #sortable1" ).sortable({
  connectWith: ".draggable-group",
  start: function(event, ui){
    $(ui.item).width($('#sortable div').width());
  }
  // containment: "parent",
  // tolerance: "pointer"
}).disableSelection();
</code>```

} );

and in the html it looks something like:

```<code><?php if($selected_tag_for_m['category_id'] == $tempo_id):?>

                <div class="btn-group draggable-group">
                  <div>
                    <a href="" data-id="<?php echo $selected_tag_for_m['info_tag_id']?>"><i class="fa fa-minus-circle fa-lg delete-a-tag" aria-hidden="true"></i></a>
                  </div>
                  <div type="button" class="btn btn-default btn-color"><i class="fa fa-circle-o custom-text-blue"></i> <?php echo $selected_tag_for_m['tag_name'];?> </div>

                  <div type="button" class="btn btn-default custom-bgcolor-blue dropdown-toggle" data-toggle="dropdown">

                    <span><i class="fa fa-pencil"></i></span>
                    <span class="sr-only">Toggle Dropdown</span>
                  </div>
                  <ul class="dropdown-menu" role="menu" id="tempo">
                    <?php foreach($tempos as $tempo):?>
                    <li data-id="<?php echo $selected_tag_for_m['info_tag_id']?>"><a href="" data-id="<?php echo $tempo['tag_id']?>" class="songtaglist" ><?php echo $tempo['tag_name'];?></a></li>
                    <?php endforeach;?>
                  </ul>

                </div>

            <?php endif;?>
</code>```

答:
I found solution to this by calling sortable.js script in body of the load function. The code looks like this:  </p>

```<code>$('#category').load(window.location.href + ' #category', function(){
                $.getScript(base_url + '/assets/js/sortable.js');
            });
</code>```

Body:
I have this issue that every time the div is loaded using div.load in the ajax success, the code for sortable will not work. Sortable will work again after the page is refreshed manually. What could be the possible solution for this?

$(document).on('click', '#add-song-tag', function() {

tag_id = $('#tags').val();

$.ajax({
    url: base_url + '/songtags/add_song_tag',
    type: 'POST',
    data: {
        song_info_id: song_info_id,
        tag_id: tag_id
    },
    success: function() {

        $('#category').load(window.location.href + ' #category');

        $('#modal-categories').trigger('change');
    },
    error: function(xhr) {
        console.log(xhr.responseText);
    }
})

});

I have my code in the sortable.js like

$( function() {
$( "#sortable, #sortable1" ).sortable({
  connectWith: ".draggable-group",
  start: function(event, ui){
    $(ui.item).width($('#sortable div').width());
  }
  // containment: "parent",
  // tolerance: "pointer"
}).disableSelection();

} );

and in the html it looks something like:

<?php if($selected_tag_for_m['category_id'] == $tempo_id):?>

                    <a href="" data-id="<?php echo $selected_tag_for_m['info_tag_id']?>">

 <?php echo $selected_tag_for_m['tag_name'];?>

                    Toggle Dropdown

                    <?php foreach($tempos as $tempo):?>
                    <li data-id="<?php echo $selected_tag_for_m['info_tag_id']?>"><a href="" data-id="<?php echo $tempo['tag_id']?>" class="songtaglist" ><?php echo $tempo['tag_name'];?>

                    <?php endforeach;?>

            <?php endif;?>

Body:
I found solution to this by calling sortable.js script in body of the load function. The code looks like this:

$('#category').load(window.location.href + ' #category', function(){
                $.getScript(base_url + '/assets/js/sortable.js');
            });


问:
Generic choose of method / infering methods in java
im not experienced at all with generics but I set up a little code.
My goal is to implement searchData(ResultSet rs) so that it chooses the correct method corresponding to data which is the given class/databaseField name.

Examples:

For data = "medium" I want to call searchMedium(rs)

For data = "customer" I want to call searchCustomer(rs)

For data = "loan" I want to call searchLoan(rs)

I do not want to realize it with if or switch case as this will turn huge for many of those methods.
I hope you can understand my intention and that there is a possibility to realize it.
Here is my code:

```<code>public class test3 {
public static void main(String[] args) {
    test3 t = new test3();
    ArrayList<?> list = t.search("medium");
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}

public <T> ArrayList<T> search(String data) {
    ArrayList<T> resultList = new ArrayList<T>();
    Connection c;
    Statement stmt;
    String sql = "Error occurred before executing SQL statement";
    try {
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:library.sqlite");
        c.setAutoCommit(false);
        stmt = c.createStatement();
        sql = "SELECT * FROM " + data + ";";
        ResultSet rs = stmt.executeQuery(sql);

        resultList = searchData(rs, data);
        rs.close();
        stmt.close();
        c.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage() + "\n" + sql + "\nSQL query for " + data
                + " failed");
    }
    return resultList;
}

private <T> ArrayList<T> searchData(ResultSet rs, String data) {
    ArrayList list = null;
    // TODO ???
    return list;
}

private ArrayList<Loan> searchLoan(ResultSet rs) throws SQLException {
    ArrayList<Loan> resultList = new ArrayList<Loan>();
    Loan match;
    while (rs.next()) {
        int loanNumber = rs.getInt("NUMBER");
        String mediumId = rs.getString("MEDIUMCODE");
        int customerNumber = rs.getInt("CUSTOMERNUMBER");
        String loanDate = rs.getString("LOANDATE");
        String targetReturndate = rs.getString("TARGETRETURNDATE");
        String returnDate = rs.getString("RETURNDATE");
        int extensions = rs.getInt("EXTENSIONS");
        match = new Loan(loanNumber, mediumId, customerNumber, targetReturndate, loanDate, returnDate, extensions);
        resultList.add(match);
    }
    return resultList;
}

private ArrayList<Medium> searchMedium(ResultSet rs) throws SQLException {
    ArrayList<Medium> resultList = new ArrayList<Medium>();
    Medium match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String isbn = rs.getString("ISBN");
        String title = rs.getString("TITLE");
        String authors = rs.getString("AUTHORS");
        String type = rs.getString("TYPE");
        String category = rs.getString("CATEGORY");
        String publishingYear = String.valueOf(rs.getInt("PUBLISHINGYEAR"));
        String publishingMonth = rs.getString("PUBLISHINGMONTH");
        String timestamp = rs.getString("TIMESTAMP");
        String loanerNumber = String.valueOf(rs.getInt("LOANERNUMBER"));
        match = new Medium(number, id, isbn, title, type, authors, category, publishingYear, publishingMonth,
                timestamp, loanerNumber);
        resultList.add(match);
    }
    return resultList;
}

private ArrayList<Customer> searchCustomer(ResultSet rs) throws SQLException {
    ArrayList<Customer> resultList = new ArrayList<Customer>();
    Customer match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String lastname = rs.getString("LASTNAME");
        String firstname = rs.getString("FIRSTNAME");
        String birthdate = rs.getString("BIRTHDATE");
        String zipcode = String.valueOf(rs.getInt("ZIPCODE"));
        String domicile = rs.getString("DOMICILE");
        String street = rs.getString("STREET");
        String housenumber = String.valueOf(rs.getInt("HOUSENUMBER"));
        String notification = rs.getString("NOTIFICATION");
        String notificationTimestamp = rs.getString("NOTIFICATIONTIMESTAMP");
        match = new Customer(number, id, lastname, firstname, birthdate, zipcode, domicile, street, housenumber,
                notification, notificationTimestamp);
        resultList.add(match);
    }
    return resultList;
}
</code>```

}

Probably my approach is a really bad one so I would be very happy for any kind of help/suggestions.

with much thanks

答:
According to my understand, here you can't use Generics to call methods dynamically. To that you have to use method overloading. If you are willing to give up Generics, then following way can be used.

```<code>private RestultSet getResultSet(String tblName){
    Connection c;
    Statement stmt;
    String sql = "Error occurred before executing SQL statement";
    try {
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:library.sqlite");
        c.setAutoCommit(false);
        stmt = c.createStatement();
        sql = "SELECT * FROM " + tblName+ ";";
        ResultSet rs = stmt.executeQuery(sql);

        return rs;
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage() + "\n" + sql + "\nSQL query for " + data
            + " failed");
    }
}

public ArrayList<Customer> search(Customer c) {
    ArrayList<Customer> resultList = new ArrayList<>();
    ResultSet rs = getRestultSet(c.getSimpleName());

    Customer match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String lastname = rs.getString("LASTNAME");
        String firstname = rs.getString("FIRSTNAME");
        String birthdate = rs.getString("BIRTHDATE");
        String zipcode = String.valueOf(rs.getInt("ZIPCODE"));
        String domicile = rs.getString("DOMICILE");
        String street = rs.getString("STREET");
        String housenumber = String.valueOf(rs.getInt("HOUSENUMBER"));
        String notification = rs.getString("NOTIFICATION");
        String notificationTimestamp = rs.getString("NOTIFICATIONTIMESTAMP");
        match = new Customer(number, id, lastname, firstname, birthdate,     zipcode, domicile, street, housenumber,
            notification, notificationTimestamp);
        resultList.add(match);
    }

    rs.close();
    return resultList;
}

public ArrayList<Medium> search(Medium m) {
    ArrayList<Medium> resultList = new ArrayList<>();
    ResultSet rs = getRestultSet(m.getSimpleName());

    Medium match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String isbn = rs.getString("ISBN");
        String title = rs.getString("TITLE");
        String authors = rs.getString("AUTHORS");
        String type = rs.getString("TYPE");
        String category = rs.getString("CATEGORY");
        String publishingYear = String.valueOf(rs.getInt("PUBLISHINGYEAR"));
        String publishingMonth = rs.getString("PUBLISHINGMONTH");
        String timestamp = rs.getString("TIMESTAMP");
        String loanerNumber = String.valueOf(rs.getInt("LOANERNUMBER"));
        match = new Medium(number, id, isbn, title, type, authors, category, publishingYear, publishingMonth,
            timestamp, loanerNumber);
        resultList.add(match);
    }

    rs.close();
    return resultList;
}
</code>```

Likewise you can put search method for Loan also.

The main method is as follows

```<code>public static void main(String[] args) {
    test3 t = new test3();
    ArrayList<?> list = t.search(new Medium());
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}
</code>```

Hope this will work... Thanks...

Body:
im not experienced at all with generics but I set up a little code.
My goal is to implement searchData(ResultSet rs) so that it chooses the correct method corresponding to data which is the given class/databaseField name.

Examples:

For data = "medium" I want to call searchMedium(rs)

For data = "customer" I want to call searchCustomer(rs)

For data = "loan" I want to call searchLoan(rs)

I do not want to realize it with if or switch case as this will turn huge for many of those methods.
I hope you can understand my intention and that there is a possibility to realize it.
Here is my code:

public class test3 {
public static void main(String[] args) {
    test3 t = new test3();
    ArrayList<?> list = t.search("medium");
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}

public <T> ArrayList<T> search(String data) {
    ArrayList<T> resultList = new ArrayList<T>();
    Connection c;
    Statement stmt;
    String sql = "Error occurred before executing SQL statement";
    try {
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:library.sqlite");
        c.setAutoCommit(false);
        stmt = c.createStatement();
        sql = "SELECT * FROM " + data + ";";
        ResultSet rs = stmt.executeQuery(sql);

        resultList = searchData(rs, data);
        rs.close();
        stmt.close();
        c.close();
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage() + "\n" + sql + "\nSQL query for " + data
                + " failed");
    }
    return resultList;
}

private <T> ArrayList<T> searchData(ResultSet rs, String data) {
    ArrayList list = null;
    // TODO ???
    return list;
}

private ArrayList<Loan> searchLoan(ResultSet rs) throws SQLException {
    ArrayList<Loan> resultList = new ArrayList<Loan>();
    Loan match;
    while (rs.next()) {
        int loanNumber = rs.getInt("NUMBER");
        String mediumId = rs.getString("MEDIUMCODE");
        int customerNumber = rs.getInt("CUSTOMERNUMBER");
        String loanDate = rs.getString("LOANDATE");
        String targetReturndate = rs.getString("TARGETRETURNDATE");
        String returnDate = rs.getString("RETURNDATE");
        int extensions = rs.getInt("EXTENSIONS");
        match = new Loan(loanNumber, mediumId, customerNumber, targetReturndate, loanDate, returnDate, extensions);
        resultList.add(match);
    }
    return resultList;
}

private ArrayList<Medium> searchMedium(ResultSet rs) throws SQLException {
    ArrayList<Medium> resultList = new ArrayList<Medium>();
    Medium match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String isbn = rs.getString("ISBN");
        String title = rs.getString("TITLE");
        String authors = rs.getString("AUTHORS");
        String type = rs.getString("TYPE");
        String category = rs.getString("CATEGORY");
        String publishingYear = String.valueOf(rs.getInt("PUBLISHINGYEAR"));
        String publishingMonth = rs.getString("PUBLISHINGMONTH");
        String timestamp = rs.getString("TIMESTAMP");
        String loanerNumber = String.valueOf(rs.getInt("LOANERNUMBER"));
        match = new Medium(number, id, isbn, title, type, authors, category, publishingYear, publishingMonth,
                timestamp, loanerNumber);
        resultList.add(match);
    }
    return resultList;
}

private ArrayList<Customer> searchCustomer(ResultSet rs) throws SQLException {
    ArrayList<Customer> resultList = new ArrayList<Customer>();
    Customer match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String lastname = rs.getString("LASTNAME");
        String firstname = rs.getString("FIRSTNAME");
        String birthdate = rs.getString("BIRTHDATE");
        String zipcode = String.valueOf(rs.getInt("ZIPCODE"));
        String domicile = rs.getString("DOMICILE");
        String street = rs.getString("STREET");
        String housenumber = String.valueOf(rs.getInt("HOUSENUMBER"));
        String notification = rs.getString("NOTIFICATION");
        String notificationTimestamp = rs.getString("NOTIFICATIONTIMESTAMP");
        match = new Customer(number, id, lastname, firstname, birthdate, zipcode, domicile, street, housenumber,
                notification, notificationTimestamp);
        resultList.add(match);
    }
    return resultList;
}

}

Probably my approach is a really bad one so I would be very happy for any kind of help/suggestions.

with much thanks

Body:
According to my understand, here you can't use Generics to call methods dynamically. To that you have to use method overloading. If you are willing to give up Generics, then following way can be used.

private RestultSet getResultSet(String tblName){
    Connection c;
    Statement stmt;
    String sql = "Error occurred before executing SQL statement";
    try {
        Class.forName("org.sqlite.JDBC");
        c = DriverManager.getConnection("jdbc:sqlite:library.sqlite");
        c.setAutoCommit(false);
        stmt = c.createStatement();
        sql = "SELECT * FROM " + tblName+ ";";
        ResultSet rs = stmt.executeQuery(sql);

        return rs;
    } catch (Exception e) {
        System.err.println(e.getClass().getName() + ": " + e.getMessage() + "\n" + sql + "\nSQL query for " + data
            + " failed");
    }
}

public ArrayList<Customer> search(Customer c) {
    ArrayList<Customer> resultList = new ArrayList<>();
    ResultSet rs = getRestultSet(c.getSimpleName());

    Customer match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String lastname = rs.getString("LASTNAME");
        String firstname = rs.getString("FIRSTNAME");
        String birthdate = rs.getString("BIRTHDATE");
        String zipcode = String.valueOf(rs.getInt("ZIPCODE"));
        String domicile = rs.getString("DOMICILE");
        String street = rs.getString("STREET");
        String housenumber = String.valueOf(rs.getInt("HOUSENUMBER"));
        String notification = rs.getString("NOTIFICATION");
        String notificationTimestamp = rs.getString("NOTIFICATIONTIMESTAMP");
        match = new Customer(number, id, lastname, firstname, birthdate,     zipcode, domicile, street, housenumber,
            notification, notificationTimestamp);
        resultList.add(match);
    }

    rs.close();
    return resultList;
}

public ArrayList<Medium> search(Medium m) {
    ArrayList<Medium> resultList = new ArrayList<>();
    ResultSet rs = getRestultSet(m.getSimpleName());

    Medium match;
    while (rs.next()) {
        String number = String.valueOf(rs.getInt("NUMBER"));
        String id = rs.getString("ID");
        String isbn = rs.getString("ISBN");
        String title = rs.getString("TITLE");
        String authors = rs.getString("AUTHORS");
        String type = rs.getString("TYPE");
        String category = rs.getString("CATEGORY");
        String publishingYear = String.valueOf(rs.getInt("PUBLISHINGYEAR"));
        String publishingMonth = rs.getString("PUBLISHINGMONTH");
        String timestamp = rs.getString("TIMESTAMP");
        String loanerNumber = String.valueOf(rs.getInt("LOANERNUMBER"));
        match = new Medium(number, id, isbn, title, type, authors, category, publishingYear, publishingMonth,
            timestamp, loanerNumber);
        resultList.add(match);
    }

    rs.close();
    return resultList;
}

Likewise you can put search method for Loan also.

The main method is as follows

public static void main(String[] args) {
    test3 t = new test3();
    ArrayList<?> list = t.search(new Medium());
    for (int i = 0; i < list.size(); i++) {
        System.out.println(list.get(i));
    }
}

Hope this will work... Thanks...


问:
SSH error during git pull
I'm trying to run git pull on my Windows machine and get this error:

```<code>fatal: unable to access '(address_here)':
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure
</code>```

How could I avoid it?

答:
It is an https error, not an ssh error: double-check the value of

```<code>git remote -v
</code>```

Try also:

the latest Git for Windows you can find, like PortableGit-2.15.0-64-bit.7z.exe (unzip it anywhere you want, no setup)

then in a CMD session, set your PATH with:

```<code>set G=c:\path\to\latest\git
set PATH=%G%\bin;%G%\usr\bin;%G%\mingw64\bin
set PATH=%PATH%;C:\windows\system32;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\
</code>```

set your HOME in that same CMD session

```<code>set HOME=%USERPROFILE%
</code>```

Finally, still from that same CMD (with its simplified PATH), cd to your Git local repo, and try your git pull again.

That would be enough to make sure you are using the latest openSSL.

And that would eliminate any interference from your current %PATH%.

Title: SSH error during git pull

Body:
I'm trying to run git pull on my Windows machine and get this error:

fatal: unable to access '(address_here)':
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure

How could I avoid it?

Body:
It is an https error, not an ssh error: double-check the value of

git remote -v

Try also:

the latest Git for Windows you can find, like PortableGit-2.15.0-64-bit.7z.exe (unzip it anywhere you want, no setup)

then in a CMD session, set your PATH with:

set G=c:\path\to\latest\git
set PATH=%G%\bin;%G%\usr\bin;%G%\mingw64\bin
set PATH=%PATH%;C:\windows\system32;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\

set your HOME in that same CMD session

set HOME=%USERPROFILE%

Finally, still from that same CMD (with its simplified PATH), cd to your Git local repo, and try your git pull again.

That would be enough to make sure you are using the latest openSSL.

And that would eliminate any interference from your current %PATH%.


问:
Is there a central SPARQL endpoint for the semantic web
We are going to have the semantic web. Now we have LOD cloud.

Every data set has its own SPARQL endpoint.

I can query the dataset triples.

How can I query the whole semantic web or LOD?

答:
No, there is no such single SPARQL endpoint, because the Semantic Web is decentralized by design. However, SPARQL 1.1 supports federated queries over different SPARQL endpoints using the SERVICE keyword. See https://www.w3.org/TR/sparql11-federated-query/ for reference. More specifically, there is a mention in the literature about how to determine which data sources might be relevant for query answering at Internet scale:

Hartig O., Bizer C., Freytag J.C. (2009) Executing SPARQL queries over the Web of Linked Data. In: Bernstein A. et al. (eds.) The Semantic Web – ISWC 2009. ISWC 2009. Lecture Notes in Computer Science, vol. 5823, pp. 293–309. Heidelberg: Springer. doi: 10.1007/978-3-642-04930-9_19


问:
change back button arrow color in ionic 3
How to change back button color in ionic 3? (From white to black color). It's screenshot with this button:

答:
You can just do it by using the css.

```<code>.back-button-icon-md {
  color: darkblue;
}
</code>```

Note: md is for android . For ios replace md to ios, For windows replace md to wp.

Body:
You can just do it by using the css.

.back-button-icon-md {
  color: darkblue;
}

Note: md is for android . For ios replace md to ios, For windows replace md to wp.