问:
Facebook Graph API for iPhone -- Cancel Button Error
I'm currently using the Facebook Graph API to log a user in and post to their wall... which works great. The issue I'm having is for the user that wants to retreat... and not log in. Basically, the "Cancel" button next the the "Login" button in the webView doesn't work properly (Facebook's fault) and I'm forced to include a "Close" button on the bottom.

Here is my problem: My code that opens the login webView seems to override anything I have in the .xib. My "Close" button I want to include at the bottom will not appear. Any idea why?

Currently (from an existing tutorial), the Facebook login is appearing with the following code:

```<code>- (void)authenticateUserWithCallbackObject:(id)anObject andSelector:(SEL)selector andExtendedPermissions:(NSString *)extended_permissions andSuperView:(UIView *)super_view {

    self.callbackObject = anObject;
    self.callbackSelector = selector;

    NSString *url_string = [NSString stringWithFormat:@"https://graph.facebook.com/oauth/authorize?client_id=%@&redirect_uri=%@&scope=%@&type=user_agent&display=touch", facebookClientID, redirectUri, extended_permissions];
    NSURL *url = [NSURL URLWithString:url_string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    CGRect webFrame = [super_view frame];

    webFrame.origin.y = 20;
    UIWebView *aWebView = [[UIWebView alloc] initWithFrame:webFrame];
    [aWebView setDelegate:self];
    self.webView = aWebView;

    [webView loadRequest:request];
    [super_view addSubview:webView];

}
</code>```

Thanks so much!

答:
I figured out what I needed to do. I programmatically added a UIButton and connected it to an IBAction.

All fixed!

Body:
I'm currently using the Facebook Graph API to log a user in and post to their wall... which works great. The issue I'm having is for the user that wants to retreat... and not log in. Basically, the "Cancel" button next the the "Login" button in the webView doesn't work properly (Facebook's fault) and I'm forced to include a "Close" button on the bottom.

Here is my problem: My code that opens the login webView seems to override anything I have in the .xib. My "Close" button I want to include at the bottom will not appear. Any idea why?

Currently (from an existing tutorial), the Facebook login is appearing with the following code:

- (void)authenticateUserWithCallbackObject:(id)anObject andSelector:(SEL)selector andExtendedPermissions:(NSString *)extended_permissions andSuperView:(UIView *)super_view {

    self.callbackObject = anObject;
    self.callbackSelector = selector;

    NSString *url_string = [NSString stringWithFormat:@"https://graph.facebook.com/oauth/authorize?client_id=%@&redirect_uri=%@&scope=%@&type=user_agent&display=touch", facebookClientID, redirectUri, extended_permissions];
    NSURL *url = [NSURL URLWithString:url_string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    CGRect webFrame = [super_view frame];

    webFrame.origin.y = 20;
    UIWebView *aWebView = [[UIWebView alloc] initWithFrame:webFrame];
    [aWebView setDelegate:self];
    self.webView = aWebView;

    [webView loadRequest:request];
    [super_view addSubview:webView];

}

Thanks so much!


来源: stackexchange

问:
Codeigniter join, group by and count a row from one table
I'm struggling a bit with this code to get the count result from book_listing (totally) which is the total count of bookings. From the result, some are correct but some are multiplied by 3 or so.

Here is my code:

```<code>$this->db->where('list_status', 1)
         ->where('list_date >=', date('Y-m-d'))
         ->order_by("user_listings.list_created", "desc")
         ->limit(18, null)
         ->select('*, COUNT(user_bookings.book_listing) as totally')
         ->from('user_listings')
         ->join('user_images', 'user_images.img_listing = user_listings.list_reference')
         ->join('user_states', 'user_states.state_id = user_listings.list_state')
         ->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
         ->group_by('user_listings.list_reference')
         ->get();
</code>```

Thanks to any help :)

答:
So I solved it, the user_images table seems to be causing the issue due to multiple images being fetched while I need it to return only one.

```<code>$this->db->where('list_status', 1)
         ->where('list_date >=', date('Y-m-d'))
         ->order_by("user_listings.list_created", "desc")
         ->limit(18, null)
         ->select('user_listings.*,image.*,user_states.*')
         ->select('COUNT(user_bookings.book_listing) as totalBooked')
         ->from('user_listings')
         ->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
         ->join('(SELECT * FROM user_images WHERE user_images.img_key IN(SELECT MIN(user_images.img_key) FROM user_images GROUP BY user_images.img_listing)) AS image',
                                            'image.img_listing = user_listings.list_reference')
         ->join('user_states', 'user_states.state_id = user_listings.list_state')
         ->group_by('user_listings.list_reference')
         ->get();
</code>```

Basically, I had to do a select from the join table for user_images. Hope it helps someone else :)

ContentLicense: CC BY-SA 3.0

Body:
I'm struggling a bit with this code to get the count result from book_listing (totally) which is the total count of bookings. From the result, some are correct but some are multiplied by 3 or so.

Here is my code:

$this->db->where('list_status', 1)
         ->where('list_date >=', date('Y-m-d'))
         ->order_by("user_listings.list_created", "desc")
         ->limit(18, null)
         ->select('*, COUNT(user_bookings.book_listing) as totally')
         ->from('user_listings')
         ->join('user_images', 'user_images.img_listing = user_listings.list_reference')
         ->join('user_states', 'user_states.state_id = user_listings.list_state')
         ->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
         ->group_by('user_listings.list_reference')
         ->get();

Thanks to any help :)

Body:
So I solved it, the user_images table seems to be causing the issue due to multiple images being fetched while I need it to return only one.

$this->db->where('list_status', 1)
         ->where('list_date >=', date('Y-m-d'))
         ->order_by("user_listings.list_created", "desc")
         ->limit(18, null)
         ->select('user_listings.*,image.*,user_states.*')
         ->select('COUNT(user_bookings.book_listing) as totalBooked')
         ->from('user_listings')
         ->join('user_bookings', 'user_bookings.book_listing = user_listings.list_reference', 'left')
         ->join('(SELECT * FROM user_images WHERE user_images.img_key IN(SELECT MIN(user_images.img_key) FROM user_images GROUP BY user_images.img_listing)) AS image',
                                            'image.img_listing = user_listings.list_reference')
         ->join('user_states', 'user_states.state_id = user_listings.list_state')
         ->group_by('user_listings.list_reference')
         ->get();

Basically, I had to do a select from the join table for user_images. Hope it helps someone else :)


问:
Save as PDF hidden and protected by password EXCEL sheet
I was using this code to save as PDF a hidden worksheet and it was working perfectly:

```<code>Sub Cite()

Dim wb As Excel.Workbook
Dim Proposalname As String
Dim iVis As XlSheetVisibility
Dim xlName As Excel.Name
Dim FolderPath As String

Set wb = ActiveWorkbook
FolderPath = ActiveWorkbook.Path & "\"

Proposalname = "Cite for " & CStr(Range("B2").Value)

'Proposal
 Application.ScreenUpdating = False
 With Worksheets(2)
 iVis = .Visible
.Visible = xlSheetVisible
.ExportAsFixedFormat Type:=xlTypePDF, _
                     Filename:=ActiveWorkbook.Path & "\" & Proposalname & ".pdf", _
                     Quality:=xlQualityStandard, _
                     IncludeDocProperties:=True, _
                     IgnorePrintAreas:=True, _
                     OpenAfterPublish:=True

 .Visible = iVis

 Worksheets(2).Activate

 End With
 Application.ScreenUpdating = True
 End Sub
</code>```

However, now I protected this hidden sheet with a password so people can't unhide it. After doing this, I am not able to generate the PDF like it was working before. I tried to use the command "Unprotect password" and also did not work, it keeps saying that something is wrong with the line ".Visible = xlSheetVisible". Can somebody help me solving this problem please?

答:
You must unprotect the workbook as well as the worksheet  in order to change the visible property of a worksheet

EDIT:

```<code>   wb.unprotect "Your password here"
   With Worksheets(2)
         iVis = .Visible
         .Visible = xlSheetVisible
more code here
End With
 wb.protect "Your password here"
Application.ScreenUpdating = True
</code>```

Body:
I was using this code to save as PDF a hidden worksheet and it was working perfectly:

Sub Cite()

Dim wb As Excel.Workbook
Dim Proposalname As String
Dim iVis As XlSheetVisibility
Dim xlName As Excel.Name
Dim FolderPath As String

Set wb = ActiveWorkbook
FolderPath = ActiveWorkbook.Path & "\"

Proposalname = "Cite for " & CStr(Range("B2").Value)

'Proposal
 Application.ScreenUpdating = False
 With Worksheets(2)
 iVis = .Visible
.Visible = xlSheetVisible
.ExportAsFixedFormat Type:=xlTypePDF, _
                     Filename:=ActiveWorkbook.Path & "\" & Proposalname & ".pdf", _
                     Quality:=xlQualityStandard, _
                     IncludeDocProperties:=True, _
                     IgnorePrintAreas:=True, _
                     OpenAfterPublish:=True

 .Visible = iVis

 Worksheets(2).Activate

 End With
 Application.ScreenUpdating = True
 End Sub

However, now I protected this hidden sheet with a password so people can't unhide it. After doing this, I am not able to generate the PDF like it was working before. I tried to use the command "Unprotect password" and also did not work, it keeps saying that something is wrong with the line ".Visible = xlSheetVisible". Can somebody help me solving this problem please?

Body:
You must unprotect the workbook as well as the worksheet  in order to change the visible property of a worksheet

EDIT:

   wb.unprotect "Your password here"
   With Worksheets(2)
         iVis = .Visible
         .Visible = xlSheetVisible
more code here
End With
 wb.protect "Your password here"
Application.ScreenUpdating = True


问:
Using JS prepend for a div, rather than hiding
I have some existing code with a select box, where I'm looking at the option value and matching it to the value of a hidden input for divs within a foreach loop. I got it working the way I want (where, depending on the selection, if the value of the hidden input is '0' it would hide that div). Again, the show/hide works perfectly.

However, I now need to get it working so that if the value is '1' it would prepend those affected divs or show them first. I've never used prepend or append before and I can't get this working for some reason. I tried using the value '0' with append but it just hid everything. I think prepend would be better.

Here's the previous Working 'hide' javascript:

```<code><script type="text/javascript">
$(function(){

$('#filterText').on('change', function() {
  var currentVal = $(this).val();
  console.log(currentVal)

  $(".group-container").show();
  if (currentVal == 'popularity') {
  $('.group-container input[name="topseller"]').each(function (index, value){
  if($(this).val() == "0"){
        $(this).parent('.group-container').hide();
        //console.log(currentVal)
    }
    });
  } else if (currentVal == 'recently_ordered') {
    $('.group-container input[name="reorder"]').each(function (index, value){

        if($(this).val() == "0"){
                $(this).parent('.group-container').hide();
                // console.log(currentVal)
            }
      });
  }
});
});

</script>
</code>```

Here's the HTML

```<code><div>
   <span style="color:#fff;"><strong>Sort by:</strong></span>
        <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
        <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
                                      file
        <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
       </select>
    </div>

@foreach ($orderFormData->pgroups as $pgroup)
<div class="group-container">
        <!-- <input type='hidden' name='search' value='{{ x.search }}' > -->
        <input type="hidden" name="topseller" value="{{$pgroup->topseller}}" />
        <input type="hidden" name="reorder" value="{{$pgroup->reorder}}"/>

     //rest of the content here
</code>```

And the new JS I'm attempting, but has no action:

```<code><script type="text/javascript">
$(function(){

$('#filterText').on('change', function() {
  var currentVal = $(this).val();
  console.log(currentVal)

  $(".group-container").show();

  if (currentVal == 'recently_ordered') {
    $('.group-container input[name="reorder"]').each(function (index, value)
{

        if($(this).val() == "1"){
                $(this).prepend('.group-container')
            }
      });
  }
});
});

</script>
</code>```

答:
$(this).prepend('.group-container')

This piece of code is going to just prepend the text ".group-container" within the selected element.  So you would get

```<code> <input ....>.group-container</input>
</code>```

If you instead did this:

```<code>$(this).prepend('<div class="group-container">);
</code>```

You would get it added to the beginning of your existing element:

```<code><input....><div class="group-container"></div></input>
</code>```

I think what you want is "wrap":

```<code>$(this).wrap('<div class="group-container">');
</code>```

Which should yield

```<code><div class="group-container"><input.../></div>
</code>```

http://api.jquery.com/wrap/

Body:
I have some existing code with a select box, where I'm looking at the option value and matching it to the value of a hidden input for divs within a foreach loop. I got it working the way I want (where, depending on the selection, if the value of the hidden input is '0' it would hide that div). Again, the show/hide works perfectly.

However, I now need to get it working so that if the value is '1' it would prepend those affected divs or show them first. I've never used prepend or append before and I can't get this working for some reason. I tried using the value '0' with append but it just hid everything. I think prepend would be better.

Here's the previous Working 'hide' javascript:

Here's the HTML

   Sort by:
        <select id="filterText" class="uk-text-muted" style="margin-top:10px; width:33%; height:30px; font-size: 16px;" >
        <option id="allitems" class="uk-text-muted" style="font-size: 16px;" selected data-default value="" selected data-default>All Items</option>
                                      file
        <option id="recent" class="uk-text-muted" style="font-size: 16px;" value="recently_ordered">Recently Ordered </option>
       </select>

@foreach ($orderFormData->pgroups as $pgroup)

        <input type="hidden" name="topseller" value="{{$pgroup->topseller}}" />
        <input type="hidden" name="reorder" value="{{$pgroup->reorder}}"/>

     //rest of the content here

And the new JS I'm attempting, but has no action:

Body:
$(this).prepend('.group-container')

This piece of code is going to just prepend the text ".group-container" within the selected element.  So you would get

 <input ....>.group-container</input>

If you instead did this:

$(this).prepend('<div class="group-container">);

You would get it added to the beginning of your existing element:

<input....><div class="group-container"></div></input>

I think what you want is "wrap":

$(this).wrap('<div class="group-container">');

Which should yield

<div class="group-container"><input.../></div>

http://api.jquery.com/wrap/


问:
Java + JPA: Search User in Database By first and last name return too many results. Is there a better way?
Right now my implementation is like this, so if the user type is Peter Smith, then I would a split on the query string like this:

```<code>String[] name = searchQuery.split(" "); //searchQuery is type String
</code>```

then I would loop through name array, and for each name, I match it against first name and last name fields in my db as below

```<code>@NamedQuery(name="User.findUserByName",
    query="select c from User c where c.fname LIKE :param OR c.lname LIKE :param"),

public List<User> findUser(String searchParam){
    Query query = em.createNamedQuery("User.findUserByName");
    query.setParameter("param", "%" + searchParam + "%");
    return query.getResultList();
}
</code>```

however, if I do this, it return too many results (Every thing related to Peter will be display and everything related to Smith will be as well). Is there a better way to do this?

I am using EclipseLink btw

答:
If I were you I'd use the Criteria API instead. Here's a sample implementation:

```<code>public List<User> findUsersByName(final String firstName,
    final String lastName){

    final boolean hasFirst = firstName != null && firstName.length() > 0;
    // if you use Apache Commons / Lang, do it like this:
    // final boolean hasFirst = StringUtils.isNotBlank(firstName);

    final boolean hasLast = lastName != null && lastName.length() > 0;
    if(!hasFirst && !hasLast){
        // or throw IllegalArgumentException
        return Collections.emptyList();
    }
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<User> query = cb.createQuery(User.class);
    final Root<User> root = query.from(User.class);
    if(hasFirst && hasLast){
        query.where(cb.and(
            likeExpression(cb, root,"lname", lastName),
            likeExpression(cb, root, "fname", firstName)
            ));
    } else if(hasFirst){
        query.where(likeExpression(cb, root,"fname", firstName));
    } else{
        query.where(likeExpression(cb, root,"lname", lastName));
    }
    return em.createQuery(query).getResultList();
}

private static Predicate likeExpression(final CriteriaBuilder cb,
    final Root<User> root,
    final String path, String parameter){
    return cb.like(root.<String> get(path), "*"+parameter.trim()+"*");
}
</code>```

Now you can easily create overloaded versions of this method:

```<code>public List<User> findUsersByFullName(final String fullName){
    final String[] parts = fullName.split("\\s+");
    if(parts.length != 2){
        // probably you should assemble first name from all parts
        // except the last, but I'm lazy
        throw new IllegalArgumentException("Bad name: " + fullName);
    }
    return findUsersByName(parts[0], parts[1]);
}

public List<User> findUsersByLastName(final String lastName){
    return findUsersByName(null, lastName);
}

public List<User> findUsersByFirstName(final String firstName){
    return findUsersByName(firstName, null);
}
</code>```

Reference:

Java EE 6 Tutorial: Using the Criteria API to Create Queries

ContentLicense: CC BY-SA 2.5

Body:
Right now my implementation is like this, so if the user type is Peter Smith, then I would a split on the query string like this:

String[] name = searchQuery.split(" "); //searchQuery is type String

then I would loop through name array, and for each name, I match it against first name and last name fields in my db as below

@NamedQuery(name="User.findUserByName",
    query="select c from User c where c.fname LIKE :param OR c.lname LIKE :param"),

public List<User> findUser(String searchParam){
    Query query = em.createNamedQuery("User.findUserByName");
    query.setParameter("param", "%" + searchParam + "%");
    return query.getResultList();
}

however, if I do this, it return too many results (Every thing related to Peter will be display and everything related to Smith will be as well). Is there a better way to do this?

I am using EclipseLink btw

Body:
If I were you I'd use the Criteria API instead. Here's a sample implementation:

public List<User> findUsersByName(final String firstName,
    final String lastName){

    final boolean hasFirst = firstName != null && firstName.length() > 0;
    // if you use Apache Commons / Lang, do it like this:
    // final boolean hasFirst = StringUtils.isNotBlank(firstName);

    final boolean hasLast = lastName != null && lastName.length() > 0;
    if(!hasFirst && !hasLast){
        // or throw IllegalArgumentException
        return Collections.emptyList();
    }
    final CriteriaBuilder cb = em.getCriteriaBuilder();
    final CriteriaQuery<User> query = cb.createQuery(User.class);
    final Root<User> root = query.from(User.class);
    if(hasFirst && hasLast){
        query.where(cb.and(
            likeExpression(cb, root,"lname", lastName),
            likeExpression(cb, root, "fname", firstName)
            ));
    } else if(hasFirst){
        query.where(likeExpression(cb, root,"fname", firstName));
    } else{
        query.where(likeExpression(cb, root,"lname", lastName));
    }
    return em.createQuery(query).getResultList();
}

private static Predicate likeExpression(final CriteriaBuilder cb,
    final Root<User> root,
    final String path, String parameter){
    return cb.like(root.<String> get(path), "*"+parameter.trim()+"*");
}

Now you can easily create overloaded versions of this method:

public List<User> findUsersByFullName(final String fullName){
    final String[] parts = fullName.split("\\s+");
    if(parts.length != 2){
        // probably you should assemble first name from all parts
        // except the last, but I'm lazy
        throw new IllegalArgumentException("Bad name: " + fullName);
    }
    return findUsersByName(parts[0], parts[1]);
}

public List<User> findUsersByLastName(final String lastName){
    return findUsersByName(null, lastName);
}

public List<User> findUsersByFirstName(final String firstName){
    return findUsersByName(firstName, null);
}

Reference:

Java EE 6 Tutorial: Using the Criteria API to Create Queries


问:
Delete a listview item from activity on button click from another activity
I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted  to create a button that should delete the listview item that was clicked on. Here is the code I came with.

MainActivity

```<code>package news;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> newslist_adapter;
    ArrayList<String> new_subject = new ArrayList<>();
    ArrayList<String> new_post = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView post_view = findViewById(R.id.news_feed);

        FloatingActionButton add_post_button = findViewById(R.id.post_btn);

        //create click event and pass values of arrays
        post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
                intent.putExtra("Subject", new_subject);
                intent.putExtra("Post", new_post);
                intent.putExtra("position", id);
//                getApplicationContext().startActivity(intent);
                startActivityForResult(intent, 2);
            }
        });

        //create button connection and create keylistener
        add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                startActivityForResult(intent, 1);

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final ListView post_view = findViewById(R.id.news_feed);
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                //get subject and post from second activity
                String new_subject_value = data.getStringExtra("newSubject");
                String new_post_value = data.getStringExtra("newPost");
                new_subject.add(new_subject_value);
                new_post.add(new_post_value);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);

            }
        }
        if (requestCode == 2) {
            if(resultCode == Activity.RESULT_OK){
                String item2delete = data.getStringExtra("id");
                new_subject.remove(item2delete);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);
            }
        }
    }
}
</code>```

SecondActivity

```<code>package news;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;

public class full_post_activity extends AppCompatActivity {

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

        final int id = getIntent().getExtras().getInt("id");

        //create view reference
        final TextView subject_edit = findViewById(R.id.subject_input);
        final TextView post_edit = findViewById(R.id.post_input);

        //create button reference
        Button delete_button = findViewById(R.id.full_post_delete_btn);

        //create click event
        delete_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", id);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
        ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");

        String subject_string = subject_array.get(0);
        String post_string = post_array.get(0);

        //set textview text
        subject_edit.setText(subject_string);
        post_edit.setText(post_string);
    }
}
</code>```

My problem now is that the delete button doesn't do anything besides returning to the MainActivity. What am I doing wrong?

答:
You cannot get id value to MainActivity. This line in second activity cause problem

```<code>final int id = getIntent().getExtras().getInt("id");
</code>```

In Main Activity, You can put id value using name index "position"

```<code>intent.putExtra("position", id);
</code>```

So you should change them to

In Second Activity

```<code>final int id = getIntent().getExtras().getInt("position");
</code>```

or Main Activity

```<code>intent.putExtra("id", id);
</code>```

UPDATED try this in Main Activity

```<code>intent.putExtra("id", position);
</code>```

Body:
I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted  to create a button that should delete the listview item that was clicked on. Here is the code I came with.

MainActivity

package news;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> newslist_adapter;
    ArrayList<String> new_subject = new ArrayList<>();
    ArrayList<String> new_post = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView post_view = findViewById(R.id.news_feed);

        FloatingActionButton add_post_button = findViewById(R.id.post_btn);

        //create click event and pass values of arrays
        post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
                intent.putExtra("Subject", new_subject);
                intent.putExtra("Post", new_post);
                intent.putExtra("position", id);
//                getApplicationContext().startActivity(intent);
                startActivityForResult(intent, 2);
            }
        });

        //create button connection and create keylistener
        add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                startActivityForResult(intent, 1);

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final ListView post_view = findViewById(R.id.news_feed);
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                //get subject and post from second activity
                String new_subject_value = data.getStringExtra("newSubject");
                String new_post_value = data.getStringExtra("newPost");
                new_subject.add(new_subject_value);
                new_post.add(new_post_value);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);

            }
        }
        if (requestCode == 2) {
            if(resultCode == Activity.RESULT_OK){
                String item2delete = data.getStringExtra("id");
                new_subject.remove(item2delete);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);
            }
        }
    }
}

SecondActivity

package news;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;

public class full_post_activity extends AppCompatActivity {

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

        final int id = getIntent().getExtras().getInt("id");

        //create view reference
        final TextView subject_edit = findViewById(R.id.subject_input);
        final TextView post_edit = findViewById(R.id.post_input);

        //create button reference
        Button delete_button = findViewById(R.id.full_post_delete_btn);

        //create click event
        delete_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", id);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
        ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");

        String subject_string = subject_array.get(0);
        String post_string = post_array.get(0);

        //set textview text
        subject_edit.setText(subject_string);
        post_edit.setText(post_string);
    }
}

My problem now is that the delete button doesn't do anything besides returning to the MainActivity. What am I doing wrong?

Body:
You cannot get id value to MainActivity. This line in second activity cause problem

final int id = getIntent().getExtras().getInt("id");

In Main Activity, You can put id value using name index "position"

intent.putExtra("position", id);

So you should change them to

In Second Activity

final int id = getIntent().getExtras().getInt("position");

or Main Activity

intent.putExtra("id", id);

UPDATED try this in Main Activity

intent.putExtra("id", position);


问:
not able to connect using api openstack
I am trying to use the lib cloud library to connect to my local openstack installation.

below is the code I am trying to execute:

```<code>from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# Authentication information so you can authenticate to DreamCompute
# copy the details from the OpenStack RC file
# https://dashboard.dreamcompute.com/project/access_and_security/api_access/openrc/

auth_username = 'admin'
auth_password = 'f882e2f4eaad434c'
TENANT_NAME = 'admin'
project_name = 'admin'
auth_url = 'http://192.168.56.101:5000'
#auth_url = 'http://192.168.56.101:5000'
region_name = 'RegionOne'

OpenStack = get_driver(Provider.OPENSTACK)
driver = OpenStack('auth_username',
                   'auth_password',
                   ex_force_auth_url=auth_url,
                   ex_force_base_url='http://192.168.56.101',
                   ex_force_auth_version='2.0_password',
                   ex_tenant_name='admin',
                   ex_force_service_name='nova',
                   ex_force_service_region=region_name)

print(dir(driver.list_nodes))
print(driver.api_name)
print(driver.VOLUME_STATE_MAP)
#print(driver.connection.auth_user_info)
images = driver.name
print(driver.list_volumes())
"""for image in images:
    print(image)
"""
</code>```

However I keep getting the error message resource not found:

```<code>C:\Python dev\website\music\openstack>python openstack.py
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
openstack
{'creating': 'creating', 'available': 'available', 'attaching': 'attaching', 'in-use': 'inuse', 'deleting': 'deleting', 'error': 'error', 'error_deleting': 'error', 'backing-up': 'backup', 'restoring-backup': 'backup', 'error_restoring': 'error', 'error_extending': 'error'}
Traceback (most recent call last):
  File "openstack.py", line 31, in <module>
    print(driver.list_volumes())
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\compute\drivers\openstack.py", line 265, in list_volumes
    self.connection.request('/os-volumes').object)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 223, in request
    raw=raw)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 536, in request
    action = self.morph_action_hook(action)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 290, in morph_action_hook
    self._populate_hosts_and_request_paths()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 324, in _populate_hosts_and_request_paths
    osa = osa.authenticate(**kwargs)  # may throw InvalidCreds
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 855, in authenticate
    return self._authenticate_2_0_with_password()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 880, in _authenticate_2_0_with_password
    return self._authenticate_2_0_with_body(reqbody)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 885, in _authenticate_2_0_with_body
    method='POST')
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 637, in request
    response = responseCls(**kwargs)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 157, in __init__
    message=self.parse_error())
libcloud.common.exceptions.BaseHTTPError: {"error": {"message": "The resource could not be found.", "code": 404, "title": "Not Found"}}
</code>```

I know that I am providing a malformed url but I am not able to figure out what the url should be.

答:
I use libcloud with ex_force_auth_token. But according to this page: http://libcloud.readthedocs.io/en/latest/compute/drivers/openstack.html

I believe what you want is to have:

```<code>from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

import libcloud.security

# This assumes you don't have SSL set up.
# Note: Code like this poses a security risk (MITM attack) and
# that's the reason why you should never use it for anything else
# besides testing. You have been warned.
libcloud.security.VERIFY_SSL_CERT = False

OpenStack = get_driver(Provider.OPENSTACK)
driver = OpenStack('your_auth_username', 'your_auth_password',
                   ex_force_auth_url='http://192.168.1.101:5000',
                   ex_force_auth_version='2.0_password',
                   ex_force_service_type='compute',
                   ex_force_service_name='novaCompute',
                   ex_force_service_region='MyRegion')
</code>```

I notice that you put the ex_force_base_url there as well. That should work but your ex_force_base_url should be http://192.168.56.101:8774/v2

Here port 8774 is for nova and v2 is the nova version. You should check the version of nova you are using. A simple way to check is to use the CLI or the OpenStack Dashboard.

HTH.

Title: not able to connect using api openstack

Body:
I am trying to use the lib cloud library to connect to my local openstack installation.

below is the code I am trying to execute:

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

# Authentication information so you can authenticate to DreamCompute
# copy the details from the OpenStack RC file
# https://dashboard.dreamcompute.com/project/access_and_security/api_access/openrc/

auth_username = 'admin'
auth_password = 'f882e2f4eaad434c'
TENANT_NAME = 'admin'
project_name = 'admin'
auth_url = 'http://192.168.56.101:5000'
#auth_url = 'http://192.168.56.101:5000'
region_name = 'RegionOne'

OpenStack = get_driver(Provider.OPENSTACK)
driver = OpenStack('auth_username',
                   'auth_password',
                   ex_force_auth_url=auth_url,
                   ex_force_base_url='http://192.168.56.101',
                   ex_force_auth_version='2.0_password',
                   ex_tenant_name='admin',
                   ex_force_service_name='nova',
                   ex_force_service_region=region_name)

print(dir(driver.list_nodes))
print(driver.api_name)
print(driver.VOLUME_STATE_MAP)
#print(driver.connection.auth_user_info)
images = driver.name
print(driver.list_volumes())
"""for image in images:
    print(image)
"""

However I keep getting the error message resource not found:

C:\Python dev\website\music\openstack>python openstack.py
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__func__', '__ge__', '__get__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
openstack
{'creating': 'creating', 'available': 'available', 'attaching': 'attaching', 'in-use': 'inuse', 'deleting': 'deleting', 'error': 'error', 'error_deleting': 'error', 'backing-up': 'backup', 'restoring-backup': 'backup', 'error_restoring': 'error', 'error_extending': 'error'}
Traceback (most recent call last):
  File "openstack.py", line 31, in <module>
    print(driver.list_volumes())
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\compute\drivers\openstack.py", line 265, in list_volumes
    self.connection.request('/os-volumes').object)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 223, in request
    raw=raw)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 536, in request
    action = self.morph_action_hook(action)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 290, in morph_action_hook
    self._populate_hosts_and_request_paths()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack.py", line 324, in _populate_hosts_and_request_paths
    osa = osa.authenticate(**kwargs)  # may throw InvalidCreds
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 855, in authenticate
    return self._authenticate_2_0_with_password()
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 880, in _authenticate_2_0_with_password
    return self._authenticate_2_0_with_body(reqbody)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\openstack_identity.py", line 885, in _authenticate_2_0_with_body
    method='POST')
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 637, in request
    response = responseCls(**kwargs)
  File "C:\Users\C5265680\AppData\Local\Programs\Python\Python36\lib\site-packages\libcloud\common\base.py", line 157, in __init__
    message=self.parse_error())
libcloud.common.exceptions.BaseHTTPError: {"error": {"message": "The resource could not be found.", "code": 404, "title": "Not Found"}}

I know that I am providing a malformed url but I am not able to figure out what the url should be.

Body:
I use libcloud with ex_force_auth_token. But according to this page: http://libcloud.readthedocs.io/en/latest/compute/drivers/openstack.html

I believe what you want is to have:

from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver

import libcloud.security

# This assumes you don't have SSL set up.
# Note: Code like this poses a security risk (MITM attack) and
# that's the reason why you should never use it for anything else
# besides testing. You have been warned.
libcloud.security.VERIFY_SSL_CERT = False

OpenStack = get_driver(Provider.OPENSTACK)
driver = OpenStack('your_auth_username', 'your_auth_password',
                   ex_force_auth_url='http://192.168.1.101:5000',
                   ex_force_auth_version='2.0_password',
                   ex_force_service_type='compute',
                   ex_force_service_name='novaCompute',
                   ex_force_service_region='MyRegion')

I notice that you put the ex_force_base_url there as well. That should work but your ex_force_base_url should be http://192.168.56.101:8774/v2

Here port 8774 is for nova and v2 is the nova version. You should check the version of nova you are using. A simple way to check is to use the CLI or the OpenStack Dashboard.

HTH.


问:
How to create HTML5 100% offline applications?
Sometimes I need to write a small program just to represent some data in a chart, or similar stuff. I have been wanting to do this kind of things through the browser, with HTML5. I think it would be nice to use its canvas to create a nice UI for simple apps.

I have read some articles related to offline applications with HTML5, but they focus on downloading all the data you need and save it to the cache to use it offline later. You even need to set up an Apache server (or similar) to create your app.

I don't need my app to be online, just in my computer. I just want to create a simple application, nothing to do with internet at all.

How can I do this? Is it even possible or worthy? Is there any "Hello world!" tutorial about this around there?

答:
If you ever find you need to read static HTML+Javascript files locally then I'd recommend using this python command in the console:

```<code>python -m SimpleHTTPServer
</code>```

It launches a simple HTTP server (who'd of guessed) that serves files from the current working directory. Effectively, it's the same as launching an apache webserver, putting some static assets in /var/www/... etc. etc.

You could also just browse to the assets at file:///some/folder; however, most browsers will prevent javascript from using AJAX when files are loaded in that way, which will manifest as a bunch of bugs when you go to load it.

Body:
If you ever find you need to read static HTML+Javascript files locally then I'd recommend using this python command in the console:

python -m SimpleHTTPServer

It launches a simple HTTP server (who'd of guessed) that serves files from the current working directory. Effectively, it's the same as launching an apache webserver, putting some static assets in /var/www/... etc. etc.

You could also just browse to the assets at file:///some/folder; however, most browsers will prevent javascript from using AJAX when files are loaded in that way, which will manifest as a bunch of bugs when you go to load it.


问:
download gzip file via php cURL
I want to download file and save it.
I am using this code for downloading gzip file.

```<code>$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_params['url']);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_POST, true);
$post = array("image_id"=>  $this->_response_id, "format"=>$this->_response_format);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);
</code>```

But when I print type of result I am seeing string(i get  file with string format).

How can a resolve this problem?

Thank's

答:
you i think need to also include following option.

```<code>CURLOPT_ENCODING
</code>```

it deals with the contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip".

p.s : start accepting answers or stop asking questions. maybe u also need to know this

ALSO check out this link and try using the patch.

OwnerDisplayName: newprog

LastEditorDisplayName: newprog

Title: download gzip file via php cURL

Body:
I want to download file and save it.
I am using this code for downloading gzip file.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->_params['url']);
curl_setopt($ch, CURLOPT_VERBOSE, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
curl_setopt($ch, CURLOPT_POST, true);
$post = array("image_id"=>  $this->_response_id, "format"=>$this->_response_format);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$response = curl_exec($ch);
curl_close($ch);

But when I print type of result I am seeing string(i get  file with string format).

How can a resolve this problem?

Thank's

Body:
you i think need to also include following option.

CURLOPT_ENCODING

it deals with the contents of the "Accept-Encoding: " header. This enables decoding of the response. Supported encodings are "identity", "deflate", and "gzip".

p.s : start accepting answers or stop asking questions. maybe u also need to know this

ALSO check out this link and try using the patch.


问:
Pass data to custom npm package module
I'm new to building custom npm packages and I'm getting lost configuring it with data coming from the application it is using it.

EDIT: This is just an example but the app will have more methods and those fake a and b will be used from many of those methods.

Basically on App I'm requiring my package in this way:

```<code>var a = 'a';
var b = 'b';
var module = require('module')(a, b);
module.test();
</code>```

My module in his index file has:

```<code>var a;
var b;

function test() {
  return {
    a: a,
    b: b
  };
}

module.exports = function(_a, _b) {
  a = _a;
  b = _b;

  return {
    test: test
  }
};
</code>```

As you can guess it is not working as I was expecting... How can I pass my custom data to my npm package and be able using that data along my methods?

答:
Your definition of a module is absolutely fine but it depends on how you plan on using it!

If you would like to use it as though it were published on the npm-registry then you need to use the process described here: Installing a local module using npm?

I know that this is an example but for other readers - you shouldn't use the name module as this is already in use by Node.

If you are simply using a modular approach to producing a larger app and you want to use the exports of your file, then you require the file by pointing to it. For example, if  this file was called module.js and is in the same directory as the script which is requiring it then use:

```<code>  var myModule = require('./module.js')(a, b);
</code>```

If you have it in another directory then use the normal relative path navigation syntax like ../module.js if it is up one directory or ./lib/module.js if it is in a sub-directory called lib

Title: Pass data to custom npm package module

Body:
I'm new to building custom npm packages and I'm getting lost configuring it with data coming from the application it is using it.

EDIT: This is just an example but the app will have more methods and those fake a and b will be used from many of those methods.

Basically on App I'm requiring my package in this way:

var a = 'a';
var b = 'b';
var module = require('module')(a, b);
module.test();

My module in his index file has:

var a;
var b;

function test() {
  return {
    a: a,
    b: b
  };
}

module.exports = function(_a, _b) {
  a = _a;
  b = _b;

  return {
    test: test
  }
};

As you can guess it is not working as I was expecting... How can I pass my custom data to my npm package and be able using that data along my methods?

Body:
Your definition of a module is absolutely fine but it depends on how you plan on using it!

If you would like to use it as though it were published on the npm-registry then you need to use the process described here: Installing a local module using npm?

I know that this is an example but for other readers - you shouldn't use the name module as this is already in use by Node.

If you are simply using a modular approach to producing a larger app and you want to use the exports of your file, then you require the file by pointing to it. For example, if  this file was called module.js and is in the same directory as the script which is requiring it then use:

  var myModule = require('./module.js')(a, b);

If you have it in another directory then use the normal relative path navigation syntax like ../module.js if it is up one directory or ./lib/module.js if it is in a sub-directory called lib


问:
mysql query returns undefined in nodeJS
This code returns an error because 'results(mysql.query)' returns undefined value. I have created a database table of 7~10 rows using mysql command shell and the database works perfectly from both workbench and command shell. is it because I have installed mysql in a wrong way? or code fault? I have tested the very same stuff in a  different computer and it worked perfectly from there and suddenly it doesn't work. I didn't copy the file, just wrote/typed the same stuff from memory.

I have searched stackoverflow already and it seems everybody talks about async problem, which isn't really the one in my case.(same thing worked before)

used npm install mysql,
mysql version is community 5.7

crudserver.js(main file)

```<code>const fs = require("fs"); //filesystem
const ejs = require("ejs");
const mysql = require("mysql");
const express = require("express"); //handles all the middlewares
const bodyParser = require("body-parser"); //handles "POST"

const client = mysql.createConnection({
  user:"****",
  password:"****",
  database:"testdb"
});

let app = express();
app.use(bodyParser.urlencoded({
  extended:false
}));

app.listen(52273, function(){
  console.log("server running at http://127.0.0.1:52273");
});

app.get("/",function (request,response){
  fs.readFile("crudlist.ejs","utf8",function(error,data){
    client.query("SELECT * FROM products", function(error,results){
      response.send(ejs.render(data,{
        data:results,
        mytitle:"title1",
        mytitlesub:"title2"
      }));
    });
  });
});
</code>```

crudlist.ejs

```<code> <% data.forEach(function (itm,index){ %>
 some codes....
 <% } >
</code>```

and it says the 'data' is undefined.

Cannot read property 'forEach' of undefined
    at eval (eval at compile (F:\mycoding\node_modules\ejs\lib\ejs.js:549:12), :17:12)
    at returnedFn (F:\mycoding\node_modules\ejs\lib\ejs.js:580:17)
    at Object.exports.render (F:\mycoding\node_modules\ejs\lib\ejs.js:384:37)
    at Query._callback (F:\mycoding\crudserver.js:25:25)
    at Query.Sequence.end (F:\mycoding\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:398:18
    at Array.forEach (native)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:397:13
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

答: problem solved: reinstalled mySQL. setup port to default 3306. I did set up my port to some custom numbers when I was installing, and it was the real cause of the problem. do not change port number from 3306 unless it is necessary.</p>

Title: mysql query returns undefined in nodeJS

Body:
This code returns an error because 'results(mysql.query)' returns undefined value. I have created a database table of 7~10 rows using mysql command shell and the database works perfectly from both workbench and command shell. is it because I have installed mysql in a wrong way? or code fault? I have tested the very same stuff in a  different computer and it worked perfectly from there and suddenly it doesn't work. I didn't copy the file, just wrote/typed the same stuff from memory.

I have searched stackoverflow already and it seems everybody talks about async problem, which isn't really the one in my case.(same thing worked before)

used npm install mysql,
mysql version is community 5.7

crudserver.js(main file)

const fs = require("fs"); //filesystem
const ejs = require("ejs");
const mysql = require("mysql");
const express = require("express"); //handles all the middlewares
const bodyParser = require("body-parser"); //handles "POST"

const client = mysql.createConnection({
  user:"****",
  password:"****",
  database:"testdb"
});

let app = express();
app.use(bodyParser.urlencoded({
  extended:false
}));

app.listen(52273, function(){
  console.log("server running at http://127.0.0.1:52273");
});

app.get("/",function (request,response){
  fs.readFile("crudlist.ejs","utf8",function(error,data){
    client.query("SELECT * FROM products", function(error,results){
      response.send(ejs.render(data,{
        data:results,
        mytitle:"title1",
        mytitlesub:"title2"
      }));
    });
  });
});

crudlist.ejs

 <% data.forEach(function (itm,index){ %>
 some codes....
 <% } >

and it says the 'data' is undefined.

Cannot read property 'forEach' of undefined
    at eval (eval at compile (F:\mycoding\node_modules\ejs\lib\ejs.js:549:12), :17:12)
    at returnedFn (F:\mycoding\node_modules\ejs\lib\ejs.js:580:17)
    at Object.exports.render (F:\mycoding\node_modules\ejs\lib\ejs.js:384:37)
    at Query._callback (F:\mycoding\crudserver.js:25:25)
    at Query.Sequence.end (F:\mycoding\node_modules\mysql\lib\protocol\sequences\Sequence.js:88:24)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:398:18
    at Array.forEach (native)
    at F:\mycoding\node_modules\mysql\lib\protocol\Protocol.js:397:13
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)


问:
Using s3 to extend summary function
Using below code I'm attempting to re-write the summary function so that just the coefficient is returned :

```<code>summary <- function(x)
   {
      UseMethod("GetFirst",x)
   }

summary <- function(x)
  {
      return(x$Coefficient)
}

class(summary) <- "mysum"

tosum = as_tibble(c(1,2,3))
tosum

summary(tosum)
</code>```

This returns an error :

```<code>> summary(tosum)
NULL
Warning message:
Unknown or uninitialised column: 'Coefficient'.
</code>```

How to read the available properties on the summary function and invoke using s3 ?

答:
summary is already a Generic function so you don't need UseMethod. In order to extend its functionality you need to add another method which will work with the class you want.

See an example:

```<code>summary.myclass <- function(x)
{
  return(x$Coefficient)
}

tosum = data.frame(Coefficient = c(1,2,3))
class(tosum) <- c('myclass', 'data.frame')
summary(tosum)
#[1] 1 2 3
</code>```

Here I am defining an extension of summary (called method) for the myclass class. When I use summary on tosum which is of that class then summary.myclass is dispatched and the column Coefficiet is returned.

Title: Using s3 to extend summary function

Body:
Using below code I'm attempting to re-write the summary function so that just the coefficient is returned :

summary <- function(x)
   {
      UseMethod("GetFirst",x)
   }

summary <- function(x)
  {
      return(x$Coefficient)
}

class(summary) <- "mysum"

tosum = as_tibble(c(1,2,3))
tosum

summary(tosum)

This returns an error :

> summary(tosum)
NULL
Warning message:
Unknown or uninitialised column: 'Coefficient'.

How to read the available properties on the summary function and invoke using s3 ?

Body:
summary is already a Generic function so you don't need UseMethod. In order to extend its functionality you need to add another method which will work with the class you want.

See an example:

summary.myclass <- function(x)
{
  return(x$Coefficient)
}

tosum = data.frame(Coefficient = c(1,2,3))
class(tosum) <- c('myclass', 'data.frame')
summary(tosum)
#[1] 1 2 3

Here I am defining an extension of summary (called method) for the myclass class. When I use summary on tosum which is of that class then summary.myclass is dispatched and the column Coefficiet is returned.


问:
RecyclerView Multiple View Type
I've a list of following model:

```<code>name
categoryName
</code>```

Now, I've to build a recyclerview that groups all the entities with the same categoryName:

```<code>categoryName1
    name1
    name2
    name3
categoryName2
    name4
categoryName3
    name5
    name6
</code>```

So I have two different row type (different styles). The list is ordered. I don't necessary need the code, but, what's the algorithm to use for the adapter? Can I solve this with only one cycle?

I'd like to avoid adding view to a vertical LinearLayout from code.

答:
Your data should look like this:

```<code>public class CategorizedName {

    private Category category;
    private Collection<Name> names = null;

    public Category getCategory() {
        return category;
    }

    public Collection<Name> getNames() {
        return names;
    }

    // override hashCode and equals ...
}
</code>```

In your adapter you should do something like this:

```<code>private static final int CATEGORY = 1;
private static final int NAME = 2;

private Collection<CategorizedName> data;

@Override
public int getItemViewType(int position) {
    if (items.get(position) instanceof Category) {
        return CATEGORY;
    } else if (items.get(position) instanceof Name) {
        return NAME;
    }
    throw new RuntimeException('error');
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

    RecyclerView.ViewHolder viewHolder;
    LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());

    switch (viewType) {
        case CATEGORY:
            View categoryView = inflater.inflate(R.layout.viewholder_category, viewGroup, false);
            viewHolder = new CategoryViewHolder(categoryView);
            break;
        case NAME:
            View nameView = inflater.inflate(R.layout.viewholder_name, viewGroup, false);
            viewHolder = new NameViewHolder(nameView);
            break;
    }
    return viewHolder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
      switch (viewHolder.getItemViewType()) {
          case USER:
              CategoryViewHolder categoryViewHolder = (CategoryViewHolder) viewHolder;
              bindCategoryViewHolder(categoryViewHolder, position);
              break;
          case IMAGE:
              NameViewHolder nameViewHolder = (NameViewHolder) viewHolder;
              bindNameViewHolder(nameViewHolder, position);
              break;
      }
}
</code>```

Don't forget to create view holders.

EDIT 1: added data structure for adapter

Title: RecyclerView Multiple View Type

Body:
I've a list of following model:

name
categoryName

Now, I've to build a recyclerview that groups all the entities with the same categoryName:

categoryName1
    name1
    name2
    name3
categoryName2
    name4
categoryName3
    name5
    name6

So I have two different row type (different styles). The list is ordered. I don't necessary need the code, but, what's the algorithm to use for the adapter? Can I solve this with only one cycle?

I'd like to avoid adding view to a vertical LinearLayout from code.

Body:
Your data should look like this:

public class CategorizedName {

    private Category category;
    private Collection<Name> names = null;

    public Category getCategory() {
        return category;
    }

    public Collection<Name> getNames() {
        return names;
    }

    // override hashCode and equals ...
}

In your adapter you should do something like this:

private static final int CATEGORY = 1;
private static final int NAME = 2;

private Collection<CategorizedName> data;

@Override
public int getItemViewType(int position) {
    if (items.get(position) instanceof Category) {
        return CATEGORY;
    } else if (items.get(position) instanceof Name) {
        return NAME;
    }
    throw new RuntimeException('error');
}

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {

    RecyclerView.ViewHolder viewHolder;
    LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());

    switch (viewType) {
        case CATEGORY:
            View categoryView = inflater.inflate(R.layout.viewholder_category, viewGroup, false);
            viewHolder = new CategoryViewHolder(categoryView);
            break;
        case NAME:
            View nameView = inflater.inflate(R.layout.viewholder_name, viewGroup, false);
            viewHolder = new NameViewHolder(nameView);
            break;
    }
    return viewHolder;
}

@Override
public void onBindViewHolder(RecyclerView.ViewHolder viewHolder, int position) {
      switch (viewHolder.getItemViewType()) {
          case USER:
              CategoryViewHolder categoryViewHolder = (CategoryViewHolder) viewHolder;
              bindCategoryViewHolder(categoryViewHolder, position);
              break;
          case IMAGE:
              NameViewHolder nameViewHolder = (NameViewHolder) viewHolder;
              bindNameViewHolder(nameViewHolder, position);
              break;
      }
}

Don't forget to create view holders.

EDIT 1: added data structure for adapter


问:
How to change working directory in Julia Jupyter?
How to change working directory in Julia Jupyter?

I tried and read everything, still have no idea how to do that. It only allows me to select directories under my home ~/ dir. I can't find any button to go up to /.

答:
you need to create the config file, using cmd :
jupyter notebook --generate -config
Then, search for C:\Users\your_username\.jupyter folder (Search for that folder), and right click edit the jupyter_notebook_config.py.

Then, Ctrl+F: #c.NotebookApp.notebook_dir ='' . Note that the quotes are single quotes. Select your directory you want to have as home for your jupyter, and copy it with Ctrl+C, for example: C:\Users\username\JuliaProjects.

Then on that line, paste it like this : c.NotebookApp.notebook_dir = 'C:\\Users\\username\\JuliaProjects'

Make sure to remove #, as it is as comment.

Make sure to double slash \\ on each name of your path.
Ctrl+S to save the config.py file !!!

Go back to your cmd and run jupyter notebook. It should be in your directory of choice. Test it by making a folder and watch your directory from your computer.


问:
Reading a column file of x y z into table in Lua
Been trying to find my way through Lua, so I have a file containing N lines of numbers, 3 per line, it is actually x,y,z coordinates. I could make it a CSV file and use some Lua CSV parser, but I guess it's better if I learn how to do this regardless.

So what would be the best way to deal with this? So far I am able to read each line into a table line by the code snippet below, but 1) I don't know if this is a string or number table, 2) if I print tbllinesx[1], it prints the whole line of three numbers. I would like to be able to have tbllines[1][1], tbllines[1][2] and tbllines[1][3] corresponding to the first 3 number of 1st line of my file.

```<code>local file = io.open("locations.txt")
local tbllinesx = {}
local i = 0
if file then
for line in file:lines() do
 i = i + 1
 tbllinesx[i] = line
end
file:close()
else
error('file not found')
end
</code>```

答:
From Programming in Lua https://www.lua.org/pil/21.1.html

You can call read with multiple options; for each argument, the
  function will return the respective result. Suppose you have a file
  with three numbers per line:

6.0       -3.23     15e12

4.3       234       1000001

... Now you want to print the maximum of each line. You can read all three numbers in a single call to read:

```<code>while true do
  local n1, n2, n3 = io.read("*number", "*number", "*number")
  if not n1 then break end
  print(math.max(n1, n2, n3))
end
</code>```

In any case, you should always consider the alternative of reading the
  whole file with option "*all" from io.read and then using
  gfind to break it up:

```<code>local pat = "(%S+)%s+(%S+)%s+(%S+)%s+"
for n1, n2, n3 in string.gfind(io.read("*all"), pat) do
  print(math.max(n1, n2, n3))
end
</code>```

I'm sure you can figure out how to modify this to put the numbers into table fields on your own.

If you're using three captures you can just use table.pack to create your line table with three entries.

Body:
Been trying to find my way through Lua, so I have a file containing N lines of numbers, 3 per line, it is actually x,y,z coordinates. I could make it a CSV file and use some Lua CSV parser, but I guess it's better if I learn how to do this regardless.

So what would be the best way to deal with this? So far I am able to read each line into a table line by the code snippet below, but 1) I don't know if this is a string or number table, 2) if I print tbllinesx[1], it prints the whole line of three numbers. I would like to be able to have tbllines[1][1], tbllines[1][2] and tbllines[1][3] corresponding to the first 3 number of 1st line of my file.

local file = io.open("locations.txt")
local tbllinesx = {}
local i = 0
if file then
for line in file:lines() do
 i = i + 1
 tbllinesx[i] = line
end
file:close()
else
error('file not found')
end

Body:
From Programming in Lua https://www.lua.org/pil/21.1.html

You can call read with multiple options; for each argument, the
  function will return the respective result. Suppose you have a file
  with three numbers per line:

6.0       -3.23     15e12

4.3       234       1000001

... Now you want to print the maximum of each line. You can read all three numbers in a single call to read:

while true do
  local n1, n2, n3 = io.read("*number", "*number", "*number")
  if not n1 then break end
  print(math.max(n1, n2, n3))
end

In any case, you should always consider the alternative of reading the
  whole file with option "*all" from io.read and then using
  gfind to break it up:

local pat = "(%S+)%s+(%S+)%s+(%S+)%s+"
for n1, n2, n3 in string.gfind(io.read("*all"), pat) do
  print(math.max(n1, n2, n3))
end

I'm sure you can figure out how to modify this to put the numbers into table fields on your own.

If you're using three captures you can just use table.pack to create your line table with three entries.


问:
GNU parallel: execute one command parallel for all files in a folder
I am trying to parallelize particle simulations with different parameters to save some time. Therefore I wanted to use GNUparallel to run a bash script for the different parameters. The script reads a file and then performs the simulation eg :

$bash script <<< input file

However:-

$cd ~/parameter_files ls | parallel bash script <<< {}

does not work at all. I am a total newbie to Linux and GNUparallel, so hopefully someone can  help.

答:
You can use parallel like this on each file of ~/parameter_files directory:

```<code>find ~/parameter_files -maxdepth 1 -type f -print0 | parallel -0 bash ../script
</code>```

find command finds all the files inside ~/parameter_files directory and returns them NUL terminated

parallel -0 bash ... feeds each filename to your shell script and executes it.

Body:
You can use parallel like this on each file of ~/parameter_files directory:

find ~/parameter_files -maxdepth 1 -type f -print0 | parallel -0 bash ../script

find command finds all the files inside ~/parameter_files directory and returns them NUL terminated

parallel -0 bash ... feeds each filename to your shell script and executes it.


问:
AngularJs - work with service
I am very new to Angular. I have watched some tutorials and read some of the documentation and I start coding.

this is my code:

```<code>angular.module('CourseStoryApp').service("CourseStoryService", ['$http', '$routeParams', function ($http, $routeParams) {
    return $http({
        url: "CourseStoryWebService.asmx/Course",
        method: "GET",
        params: { eID: $routeParams.eid }
    }).then(function (response) {
        return response.data;
    });
}]);

angular.module('CourseStoryApp').controller('HeaderController', ['$scope', 'CourseStoryService', function ($scope, CourseStoryService) {
   CourseStoryService.then(function (data) {
     $scope.courseStory = data;
   });
}]);
</code>```

is this the correct way to create a service and call it on controller?

答:
Your Service should contain some methods which are in the context of CourseStories. You may want to get a specific Item, delete one and stuff like this. It would be silly to create seperate services for each of these use cases.

To create methods which are publicly available, assign them to the this variable inside the service.

So your Service could look like this:

```<code>angular
  .module('CourseStoryApp')
  .service('CourseStoryService', ['$http', function($http) {

    // Better to uncouple the service from the router, so you have a generic
    // 'getStory' method.
    this.getStory = function(id) {
      return $http({
        url: "CourseStoryWebService.asmx/Course",
        method: "GET",
        params: { eID: id }
      }).then(function(response) {
        return response.data;
      }, function() {
        // Error handling
        // Maybe write some logs etc.
      });
    };
  }]);
</code>```

And your Controller could use this Service like this:

```<code>angular
  .module('CourseStoryApp')
  .controller('HeaderController', ['$scope', '$routeParams', 'CourseStoryService', function($scope, $routeParams, CourseStoryService) {

    // Consume your Service Method like this.
    CourseStoryService.getStory($routeParams.eid).then(function(data) {
      $scope.courseStory = data;
    }, function() {
      // Error Handler
      // Notify user etc.
    });
  }]);
</code>```

Note that the $http provider from angular has some shortcut methods for specific request types like $http.get() etc. You can read more in the official docs.

Title: AngularJs - work with service

Body:
I am very new to Angular. I have watched some tutorials and read some of the documentation and I start coding.

this is my code:

angular.module('CourseStoryApp').service("CourseStoryService", ['$http', '$routeParams', function ($http, $routeParams) {
    return $http({
        url: "CourseStoryWebService.asmx/Course",
        method: "GET",
        params: { eID: $routeParams.eid }
    }).then(function (response) {
        return response.data;
    });
}]);

angular.module('CourseStoryApp').controller('HeaderController', ['$scope', 'CourseStoryService', function ($scope, CourseStoryService) {
   CourseStoryService.then(function (data) {
     $scope.courseStory = data;
   });
}]);

is this the correct way to create a service and call it on controller?

Body:
Your Service should contain some methods which are in the context of CourseStories. You may want to get a specific Item, delete one and stuff like this. It would be silly to create seperate services for each of these use cases.

To create methods which are publicly available, assign them to the this variable inside the service.

So your Service could look like this:

angular
  .module('CourseStoryApp')
  .service('CourseStoryService', ['$http', function($http) {

    // Better to uncouple the service from the router, so you have a generic
    // 'getStory' method.
    this.getStory = function(id) {
      return $http({
        url: "CourseStoryWebService.asmx/Course",
        method: "GET",
        params: { eID: id }
      }).then(function(response) {
        return response.data;
      }, function() {
        // Error handling
        // Maybe write some logs etc.
      });
    };
  }]);

And your Controller could use this Service like this:

angular
  .module('CourseStoryApp')
  .controller('HeaderController', ['$scope', '$routeParams', 'CourseStoryService', function($scope, $routeParams, CourseStoryService) {

    // Consume your Service Method like this.
    CourseStoryService.getStory($routeParams.eid).then(function(data) {
      $scope.courseStory = data;
    }, function() {
      // Error Handler
      // Notify user etc.
    });
  }]);

Note that the $http provider from angular has some shortcut methods for specific request types like $http.get() etc. You can read more in the official docs.


问:
NodeJS Server - Multiple URL Rewrite Config
I'm looking to use a NodeJS server as a temporary solve to test some AngularJS apps that were built in a .NET environment (I'm on a mac). Both apps use the <base> tag and the web.config has rewrite rules to avoid 404's on refresh, etc.

I found a potential approach discussed here, however, I'm having trouble updating the example to includes multiple rules.

The dir structure I'm trying to test looks something like this:

```<code>|-- global (both apps use assets located inside of global)
|-- apps
    |-- myApp1
    |-- myApp2
</code>```

The apps themselves use relative to root paths for all assets. So, for example:

myApp1:

```<code>/global/images/image.jpg
/apps/myApp1/images/image.jpg
/apps/myApp1/css/styles.css
/apps/myApp1/js/scripts.js
</code>```

The following rules are depicted in the web.config:

```<code>    <rule name="AngularJS Route for myApp1" stopProcessing="true">
        <match url="^myApp1/.*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/apps/myApp1/default.aspx" />
    </rule>
    <rule name="AngularJS Route for myApp2" stopProcessing="true">
        <match url="^myApp2/.*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/apps/myApp2/default.aspx" />
    </rule>
</code>```

Both apps can be accessed using their respective aliases:

```<code>mydomain.com/myApp1/
mydomain.com/myApp2/
</code>```

So, with that said, I'm trying to create a very simple nodejs server to emulate the above and am not looking for something that will run a production ready server. Just something I can spin up anytime this client sends me stuff to test.

I started looking at a few links, like the one above, but am having a hard time figuring out how I could do it with multiple rewrites using the code below:

server.js

```<code>const express = require('express');
const app = express();

app.use((req, res, next) => {
    if (req.url === 'myApp1') {

        //what do I do here?
        //tell it to reference the orig path?

        req.url = '/apps/myApp1/';

        //or do I use the router approach that's discussed in my reference link above?
    }

    next();
});

app.use(express.static(__dirname + '/'));

app.listen(3000, () => {
    console.log('Listening on port 3000')
});
</code>```

It seems like this question is asked a lot, but I have yet to see it applied to multiple rewrites, while also keeping in mind a shared global dir that both apps pull from. Anyone ever had to do anything like this before?

答:
Think I figured it out. Here's my solve for those looking at this in the future. Not sure if it's the best method, but it seems to be working for me:</p>

```<code>const express = require('express');
const path = require('path');
const router = express.Router();
const app = express();

const static = router.use('/', express.static(__dirname + '/', { redirect: false }));

const app1 = router.get('/myApp1*', (req, res, next) => {
    res.sendFile(path.resolve('apps/myApp1/index.html'));
});

const app2 = router.get('/myApp2*', (req, res, next) => {
    res.sendFile(path.resolve('apps/myApp2/index.html'));
});

app.use(static, app1, app2);

app.listen(3000, () => {
    console.log('Listening on port 3000');
});
</code>```

Body:
I'm looking to use a NodeJS server as a temporary solve to test some AngularJS apps that were built in a .NET environment (I'm on a mac). Both apps use the <base> tag and the web.config has rewrite rules to avoid 404's on refresh, etc.

I found a potential approach discussed here, however, I'm having trouble updating the example to includes multiple rules.

The dir structure I'm trying to test looks something like this:

|-- global (both apps use assets located inside of global)
|-- apps
    |-- myApp1
    |-- myApp2

The apps themselves use relative to root paths for all assets. So, for example:

myApp1:

/global/images/image.jpg
/apps/myApp1/images/image.jpg
/apps/myApp1/css/styles.css
/apps/myApp1/js/scripts.js

The following rules are depicted in the web.config:

    <rule name="AngularJS Route for myApp1" stopProcessing="true">
        <match url="^myApp1/.*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/apps/myApp1/default.aspx" />
    </rule>
    <rule name="AngularJS Route for myApp2" stopProcessing="true">
        <match url="^myApp2/.*" />
        <conditions logicalGrouping="MatchAll">
            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
        </conditions>
        <action type="Rewrite" url="/apps/myApp2/default.aspx" />
    </rule>

Both apps can be accessed using their respective aliases:

mydomain.com/myApp1/
mydomain.com/myApp2/

So, with that said, I'm trying to create a very simple nodejs server to emulate the above and am not looking for something that will run a production ready server. Just something I can spin up anytime this client sends me stuff to test.

I started looking at a few links, like the one above, but am having a hard time figuring out how I could do it with multiple rewrites using the code below:

server.js

const express = require('express');
const app = express();

app.use((req, res, next) => {
    if (req.url === 'myApp1') {

        //what do I do here?
        //tell it to reference the orig path?

        req.url = '/apps/myApp1/';

        //or do I use the router approach that's discussed in my reference link above?
    }

    next();
});

app.use(express.static(__dirname + '/'));

app.listen(3000, () => {
    console.log('Listening on port 3000')
});

It seems like this question is asked a lot, but I have yet to see it applied to multiple rewrites, while also keeping in mind a shared global dir that both apps pull from. Anyone ever had to do anything like this before?

Body:
Think I figured it out. Here's my solve for those looking at this in the future. Not sure if it's the best method, but it seems to be working for me:

const express = require('express');
const path = require('path');
const router = express.Router();
const app = express();

const static = router.use('/', express.static(__dirname + '/', { redirect: false }));

const app1 = router.get('/myApp1*', (req, res, next) => {
    res.sendFile(path.resolve('apps/myApp1/index.html'));
});

const app2 = router.get('/myApp2*', (req, res, next) => {
    res.sendFile(path.resolve('apps/myApp2/index.html'));
});

app.use(static, app1, app2);

app.listen(3000, () => {
    console.log('Listening on port 3000');
});


问:
Find a database with a particular table OR Find a table in every database of SQL Server
I have a SQL Server with hundreds of databases and each database having hundreds of tables.
Now I would like to find where in these databases is a table that I am looking for.

I could find if a table existed in individual database using

```<code>use myDatabase
select * from sys.tables  where name = 'mytable'
GO
</code>```

but using this means I have to manually change the database for hundreds of times .
I would like to find the database name only.
Is there a way out ?

答:
```<code>exec sp_msforeachdb @command1='
USE ?;
select * from sys.tables where name = ''CLIENTS'''
</code>```

Body:
I have a SQL Server with hundreds of databases and each database having hundreds of tables.
Now I would like to find where in these databases is a table that I am looking for.

I could find if a table existed in individual database using

use myDatabase
select * from sys.tables  where name = 'mytable'
GO

but using this means I have to manually change the database for hundreds of times .
I would like to find the database name only.
Is there a way out ?


问:
cordova Android requirements failed: "Could not find an installed version of Gradle"
I'm trying to build a Cordova Android project using the most recent tools. I followed the instructions here:

```<code>$ cordova create myApp com.myCompany.myApp myApp
$ cd myApp
$ cordova platform add android@6.2.1 --save
$ cordova requirements android --verbose
</code>```

But the result is:

```<code>Running command: android list targets
Command finished with error code 0: android list,targets

Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-25,android-23
Gradle: not installed
Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio
Error: CordovaError: Some of requirements check failed
    at /usr/local/nodejs_next/lib/node_modules/cordova/src/cli.js:401:45
    at _fulfilled (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:787:54)
    at self.promiseDispatch.done (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:816:30)
    at Promise.promise.promiseDispatch (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:749:13)
    at /usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:557:44
    at flush (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:108:17)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)
</code>```

It doesn't seem to be able to find Gradle (not sure where that's supposed to be).

I've seen reports of issues with Cordova and Android SDK Tools 25.3, but this seems to be different, and I have 25.2.3 (see below).

I have the following (this is on CentOS 6.8):

```<code>$ cordova --version
6.5.0

$ node --version
v6.10.2

$ npm --version
3.10.10

$ java -version
openjdk version "1.8.0_121"

$ echo $JAVA_HOME
/usr/lib/jvm/java-1.8.0

$ echo $ANDROID_HOME
/usr/local/android-sdk

# I installed the Android SDK from here
# https://developer.android.com/studio/index.html#downloads
# under "Get just the command line tools"

$ /usr/local/android-sdk/tools/bin/sdkmanager --list
Installed packages:
  Path                        | Version | Description                    | Location
  -------                     | ------- | -------                        | -------
  build-tools;23.0.3          | 23.0.3  | Android SDK Build-Tools 23.0.3 | build-tools/23.0.3/
  build-tools;25.0.2          | 25.0.2  | Android SDK Build-Tools 25.0.2 | build-tools/25.0.2/
  extras;android;m2repository | 47.0.0  | Android Support Repository     | extras/android/m2repository/
  extras;google;m2repository  | 46      | Google Repository              | extras/google/m2repository/
  patcher;v4                  | 1       | SDK Patch Applier v4           | patcher/v4/
  platform-tools              | 25.0.4  | Android SDK Platform-Tools     | platform-tools/
  platforms;android-23        | 3       | Android SDK Platform 23        | platforms/android-23/
  platforms;android-25        | 3       | Android SDK Platform 25        | platforms/android-25/
  tools                       | 25.2.3  | Android SDK Tools 25.2.3       | tools/
</code>```

UPDATE:

It doesn't seem to be mentioned anywhere in Cordova's or Android's docs, but if you're using the Android command-line tools without Android Studio, you have to manually install Gradle. Once you do, and it's on your PATH, this error will go away.

An additional thing that was confusing me: in older versions of Android SDK tools, there was a Gradle wrapper script in tools/templates/gradle/wrapper/gradlew. This can also be used to install Gradle, but I found it easier to just install it manually. This seems to have been removed as of the latest version.

答:
For Windows:

-Download last version of Gradle (https://gradle.org/releases)

-Create a folder and unzip files (I use C:\Program Files (x86)\gradle)

-Copy the path with the bin directory included (C:\Program Files (x86)\gradle\bin)

-Set the path C:\Program Files (x86)\gradle\bin (in my exemple) to "Path Environment Variables"

Variable name "Path" and variable value "C:\Program Files (x86)\gradle\bin" for both: User Variable table and System Variables table

You may need to reopen the "Prompt commad line"

To test, type gradle in prompt.

Body:
I'm trying to build a Cordova Android project using the most recent tools. I followed the instructions here:

$ cordova create myApp com.myCompany.myApp myApp
$ cd myApp
$ cordova platform add android@6.2.1 --save
$ cordova requirements android --verbose

But the result is:

Running command: android list targets
Command finished with error code 0: android list,targets

Requirements check results for android:
Java JDK: installed 1.8.0
Android SDK: installed true
Android target: installed android-25,android-23
Gradle: not installed
Could not find an installed version of Gradle either in Android Studio,
or on your system to install the gradle wrapper. Please include gradle
in your path, or install Android Studio
Error: CordovaError: Some of requirements check failed
    at /usr/local/nodejs_next/lib/node_modules/cordova/src/cli.js:401:45
    at _fulfilled (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:787:54)
    at self.promiseDispatch.done (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:816:30)
    at Promise.promise.promiseDispatch (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:749:13)
    at /usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:557:44
    at flush (/usr/local/nodejs_next/lib/node_modules/cordova/node_modules/q/q.js:108:17)
    at _combinedTickCallback (internal/process/next_tick.js:73:7)
    at process._tickCallback (internal/process/next_tick.js:104:9)

It doesn't seem to be able to find Gradle (not sure where that's supposed to be).

I've seen reports of issues with Cordova and Android SDK Tools 25.3, but this seems to be different, and I have 25.2.3 (see below).

I have the following (this is on CentOS 6.8):

$ cordova --version
6.5.0

$ node --version
v6.10.2

$ npm --version
3.10.10

$ java -version
openjdk version "1.8.0_121"

$ echo $JAVA_HOME
/usr/lib/jvm/java-1.8.0

$ echo $ANDROID_HOME
/usr/local/android-sdk

# I installed the Android SDK from here
# https://developer.android.com/studio/index.html#downloads
# under "Get just the command line tools"

$ /usr/local/android-sdk/tools/bin/sdkmanager --list
Installed packages:
  Path                        | Version | Description                    | Location
  -------                     | ------- | -------                        | -------
  build-tools;23.0.3          | 23.0.3  | Android SDK Build-Tools 23.0.3 | build-tools/23.0.3/
  build-tools;25.0.2          | 25.0.2  | Android SDK Build-Tools 25.0.2 | build-tools/25.0.2/
  extras;android;m2repository | 47.0.0  | Android Support Repository     | extras/android/m2repository/
  extras;google;m2repository  | 46      | Google Repository              | extras/google/m2repository/
  patcher;v4                  | 1       | SDK Patch Applier v4           | patcher/v4/
  platform-tools              | 25.0.4  | Android SDK Platform-Tools     | platform-tools/
  platforms;android-23        | 3       | Android SDK Platform 23        | platforms/android-23/
  platforms;android-25        | 3       | Android SDK Platform 25        | platforms/android-25/
  tools                       | 25.2.3  | Android SDK Tools 25.2.3       | tools/

UPDATE:

It doesn't seem to be mentioned anywhere in Cordova's or Android's docs, but if you're using the Android command-line tools without Android Studio, you have to manually install Gradle. Once you do, and it's on your PATH, this error will go away.

An additional thing that was confusing me: in older versions of Android SDK tools, there was a Gradle wrapper script in tools/templates/gradle/wrapper/gradlew. This can also be used to install Gradle, but I found it easier to just install it manually. This seems to have been removed as of the latest version.


问:
Replace substring of text matching regexp
I have text that looks like something like this:

```<code>1. Must have experience in Java 2. Team leader...
</code>```

I want to render this in HTML as an ordered list. Now adding the
 tag to the end is simple enough:

```<code>s = replace(s, ". ", "</li>");
</code>```

But how do I go about replacing the 1., 2. etc with
?

I have the regular expression \d*\.$ which matches a number with a period, but the problem is is that is a substring so matching 1. Must have experience in Java 2. Team leader with \d*\.$ returns false.

答:
But how do I go about replacing the 1., 2. etc with
?

You can use String#replaceAll which can allow regex instead of replace :

```<code>s = s.replaceAll("\\d+\\.\\s", "</li>");
</code>```

Note

You don't need to use $ in the end of your regex.

You have to escape dot . because it's mean any character in regex

You can use \s for one space or \s* for zero or more spaces or \s+ for one or more space

Body:
I have text that looks like something like this:

1. Must have experience in Java 2. Team leader...

I want to render this in HTML as an ordered list. Now adding the
 tag to the end is simple enough:

s = replace(s, ". ", "
");

But how do I go about replacing the 1., 2. etc with
?

I have the regular expression \d*\.$ which matches a number with a period, but the problem is is that is a substring so matching 1. Must have experience in Java 2. Team leader with \d*\.$ returns false.

Body:
But how do I go about replacing the 1., 2. etc with <li>?

You can use String#replaceAll which can allow regex instead of replace :

s = s.replaceAll("\\d+\\.\\s", "</li>");

Note

You don't need to use $ in the end of your regex.

You have to escape dot . because it's mean any character in regex

You can use \s for one space or \s* for zero or more spaces or \s+ for one or more space


问:
How to make the web site design more flexible
I wanna to ask the following question about the design of any web application.

When maximizing ,, minimizing , zooming the browser ,, i note many problems happen to my web application design for example the horizontal menu like the one exists in SO site when minimizing the window  the items of the menu in my website go down the other .. and other things make the site sucks and distracts the design .. how to make the design more flexible with the changes in monitor size , the preferences of the browser , maximizing ,and minimizing the browser ,, how to make the site design more flexible about all those issues .

Please any instructions , advice should i take care to reduce these errors.

答:
A site that makes heavy use of float: and no width: values in its CSS will run into problems when people get crazy with the window sizes.

You can either nail everything in place by specifying width:  px; all over your CSS, or you can go liquid and use width: %; for your objects. The former is considerably easier to pull off than the latter.

ContentLicense: CC BY-SA 4.0