问:
How do you deal with an exception raised by celery (not your code)?
So in my flask app right now I am using Celery to deploy servers on remote machines. Right now, I have an enum, status, which indicates the lifecycle of my deployment process:

```<code>@celery.task(bind=True)
def deploy_server(self, server_id):
  server = Server.query.get(server_id)
  if not server.can_launch():
    return

  try:
    server.status = RemoteStatus.LAUNCHING
    db.session.commit()

    verify_DNS(server)

    host = server.server.ssh_user + '@' + server.server.ip
    execute(fabric_deploy_server, self, server, hosts=host)

    server.status = RemoteStatus.LAUNCHED
    db.session.commit()
  except Exception as e:
    server.status = RemoteStatus.ERROR
    db.session.commit()
    traceback.print_exc()
    raise e
</code>```

As you can see, when a server is being deployed, its status is changed to "Launching". If there is an exception, it will be changed to ERROR.

I found one exception which completely bypasses this bloc of code: when I overloaded my celery server with too many requests, I get this exception:

```<code>[2017-07-09 18:00:03,127: WARNING/PoolWorker-3] /app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py:542: RuntimeWarning: Exception raised outside body: ConnectionError('max number of clients reached',):
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py", line 427, in trace_task
    uuid, retval, task_request, publish_result,
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/base.py", line 152, in mark_as_done
    self.store_result(task_id, result, state, request=request)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/base.py", line 309, in store_result
    request=request, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/base.py", line 652, in _store_result
    self.set(self.get_key_for_task(task_id), self.encode(meta))
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/redis.py", line 204, in set
    return self.ensure(self._set, (key, value), **retry_policy)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/redis.py", line 194, in ensure
    **retry_policy)
  File "/app/.heroku/python/lib/python2.7/site-packages/kombu/utils/functional.py", line 333, in retry_over_time
    return fun(*args, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/redis.py", line 213, in _set
    pipe.execute()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/client.py", line 2641, in execute
    return execute(conn, stack, raise_on_error)
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/client.py", line 2495, in _execute_transaction
    connection.send_packed_command(all_cmds)
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 538, in send_packed_command
    self.connect()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 446, in connect
    self.on_connect()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 514, in on_connect
    if nativestr(self.read_response()) != 'OK':
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 577, in read_response
    response = self._parser.read_response()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 255, in read_response
    raise error
ConnectionError: max number of clients reached
  exc, exc_info.traceback)))
</code>```

My biggest problem with this is that this error is raised somewhere outside of my Try/Catch bloc. Hence, when this exception occurs, all my servers remain in the "Launching" mode rather than "Error".

How can I catch this exception and modify Server.status?

答:
In redis 2.4 there is a hard coded limit of max number of connections which is 10,000. In redis 2.6+ you can specify the max number of clients in redis.conf. also this is not a problem of celery your broker redis refused to accept connections that's the problem.

Set the max number of clients that can be handled by redis simultaneously using redis CLI. Check out redis clients

Body:
So in my flask app right now I am using Celery to deploy servers on remote machines. Right now, I have an enum, status, which indicates the lifecycle of my deployment process:

@celery.task(bind=True)
def deploy_server(self, server_id):
  server = Server.query.get(server_id)
  if not server.can_launch():
    return

  try:
    server.status = RemoteStatus.LAUNCHING
    db.session.commit()

    verify_DNS(server)

    host = server.server.ssh_user + '@' + server.server.ip
    execute(fabric_deploy_server, self, server, hosts=host)

    server.status = RemoteStatus.LAUNCHED
    db.session.commit()
  except Exception as e:
    server.status = RemoteStatus.ERROR
    db.session.commit()
    traceback.print_exc()
    raise e

As you can see, when a server is being deployed, its status is changed to "Launching". If there is an exception, it will be changed to ERROR.

I found one exception which completely bypasses this bloc of code: when I overloaded my celery server with too many requests, I get this exception:

[2017-07-09 18:00:03,127: WARNING/PoolWorker-3] /app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py:542: RuntimeWarning: Exception raised outside body: ConnectionError('max number of clients reached',):
Traceback (most recent call last):
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/app/trace.py", line 427, in trace_task
    uuid, retval, task_request, publish_result,
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/base.py", line 152, in mark_as_done
    self.store_result(task_id, result, state, request=request)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/base.py", line 309, in store_result
    request=request, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/base.py", line 652, in _store_result
    self.set(self.get_key_for_task(task_id), self.encode(meta))
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/redis.py", line 204, in set
    return self.ensure(self._set, (key, value), **retry_policy)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/redis.py", line 194, in ensure
    **retry_policy)
  File "/app/.heroku/python/lib/python2.7/site-packages/kombu/utils/functional.py", line 333, in retry_over_time
    return fun(*args, **kwargs)
  File "/app/.heroku/python/lib/python2.7/site-packages/celery/backends/redis.py", line 213, in _set
    pipe.execute()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/client.py", line 2641, in execute
    return execute(conn, stack, raise_on_error)
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/client.py", line 2495, in _execute_transaction
    connection.send_packed_command(all_cmds)
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 538, in send_packed_command
    self.connect()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 446, in connect
    self.on_connect()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 514, in on_connect
    if nativestr(self.read_response()) != 'OK':
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 577, in read_response
    response = self._parser.read_response()
  File "/app/.heroku/python/lib/python2.7/site-packages/redis/connection.py", line 255, in read_response
    raise error
ConnectionError: max number of clients reached
  exc, exc_info.traceback)))

My biggest problem with this is that this error is raised somewhere outside of my Try/Catch bloc. Hence, when this exception occurs, all my servers remain in the "Launching" mode rather than "Error".

How can I catch this exception and modify Server.status?


来源: stackexchange

问:
How to pass parameters from my form action to a view? Django
This is my view function: It takes one kwarg i.e block_id

```<code>def write_comment(request, block_id):
    block=get_object_or_404(Block, pk=block_id)
    if request.method=='POST':
        form=Comment_form(request.POST)
        if form.is_valid():
            #do stuff
        else:
            return render(request,'writers_block/index.html', {'comment_form':form, 'block_form':Block_form()})
</code>```

To access it from my template form I use:

```<code>{%for block in block_list%}
<form method="post" action="{%url 'write_comment' block_id=block.id%}">
{%csrf_token%}
{{comment_form}}
<input type="submit" value="submit">
</form>
{%endfor%}
</code>```

Somehow I'm always getting a NoReverseMatch saying that write_comment with that arguments is not found:

The urlpattern is:

```<code>url(r'^write_comment', writers_block.views.write_comment, name='write_comment')
</code>```

Can you help me?

答:
Can you change your url like this and try..
       url(r'^write_comment/(?P<block_id>\d+)/$', writers_block.views.write_comment, name='write_comment')

ContentLicense: CC BY-SA 3.0

Body:
This is my view function: It takes one kwarg i.e block_id

def write_comment(request, block_id):
    block=get_object_or_404(Block, pk=block_id)
    if request.method=='POST':
        form=Comment_form(request.POST)
        if form.is_valid():
            #do stuff
        else:
            return render(request,'writers_block/index.html', {'comment_form':form, 'block_form':Block_form()})

To access it from my template form I use:

{%for block in block_list%}
<form method="post" action="{%url 'write_comment' block_id=block.id%}">
{%csrf_token%}
{{comment_form}}
<input type="submit" value="submit">
</form>
{%endfor%}

Somehow I'm always getting a NoReverseMatch saying that write_comment with that arguments is not found:

The urlpattern is:

url(r'^write_comment', writers_block.views.write_comment, name='write_comment')

Can you help me?


问:
Converting static link library to dynamic dll
I have .lib file with its header (.h) file. This file have a few functions that need to be used in C# application.

After googling I found that I need to create a dynamic DLL from this static library and call this dynamic DLL from C# code using interop.

I have created a win32 project and selected type DLL.

Included header file and added .lib to additional dependencies.

I am able to see the functions defined in the static library (when I press ctrl + space).

As a total newbie I do not know how I can export the function, which is, in .lib with following signature:

```<code>void testfun( char* inp_buff, unsigned short* inp_len, char* buffer_decomp,unsigned *output_len,unsigned short *errorCode)
</code>```

I want same signature in my dynamic DLL with a different name.

What to write in header file and .cpp file?

答:
there are two versions of LIB can be generated,
the fist is the dynamic lib, (source file + header+ dynamic lib) --> to access the DLL

or static lib=(dynamic lib+DLL) --> (Source file+header) --> to access the DLL.

if you have the Dynamic Lib > there is no way to create the DLL (you cannot get something from nothing), dynamic lib is just an interface,

but if you have the Static Lib then there is no need to DLL to access it is functions.

Body:
I have .lib file with its header (.h) file. This file have a few functions that need to be used in C# application.

After googling I found that I need to create a dynamic DLL from this static library and call this dynamic DLL from C# code using interop.

I have created a win32 project and selected type DLL.

Included header file and added .lib to additional dependencies.

I am able to see the functions defined in the static library (when I press ctrl + space).

As a total newbie I do not know how I can export the function, which is, in .lib with following signature:

void testfun( char* inp_buff, unsigned short* inp_len, char* buffer_decomp,unsigned *output_len,unsigned short *errorCode)

I want same signature in my dynamic DLL with a different name.

What to write in header file and .cpp file?

ContentLicense: CC BY-SA 2.5


问:
Google App Engine : Lucene org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out
In Google APP engine, I am using Lucene 4.1.

I am able to generate index file in local, but on the google server I am getting following exception (although the same code works fine in local machine):

```<code>org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out:
   com.googlecode.lucene.appengine.GaeLockFactory$1@104a681
</code>```

Here is my code:

```<code>package com.search.domain;

import java.io.IOException;
import java.util.Set;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.util.Version;

import com.domain.dataobjects.Item;
import com.googlecode.lucene.appengine.GaeDirectory;
import com.googlecode.lucene.appengine.GaeLuceneUtil;

public class ItemDataIndexWriter {

public String createIndexes(){
    IndexWriter indexWriter = null;
    GaeDirectory indexDirectory = null;
try{
        indexDirectory = new GaeDirectory();

        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_41 );

        IndexWriterConfig config = GaeLuceneUtil.getIndexWriterConfig(Version.LUCENE_41, analyzer);//get configuration

        config.setOpenMode(OpenMode.CREATE_OR_APPEND);
        indexWriter = new IndexWriter(indexDirectory, config);

        addToDoc(indexWriter,"test");
 }catch(Exception e){
     e.printStackTrace();
     System.out.println(e.getMessage());
     return e.toString();
 }
 finally{
     try {
        if(indexWriter!=null)
             indexWriter.close();
        if(indexDirectory!=null)
             indexDirectory.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
 }
return "Good";
}

private static void addToDoc(IndexWriter w, String item) throws IOException {

    Document doc = new Document();
    doc.add(new TextField("item", item, Field.Store.YES));
    w.addDocument(doc);
}
}
</code>```

Can anyone guide me ? what is wrong?

答:
I had the same problem, but in a test, in the cloud works pretty well.
I did this in groovy:

```<code>    final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService()
    final PreparedQuery pq = datastore.prepare(new Query())
    def list = pq.asList(FetchOptions.Builder.withDefaults())
    datastore.delete(list.collect {it.key})

    GetIndexesRequest builder = GetIndexesRequest.newBuilder().build()
    GetResponse<Index> indexes = SearchServiceFactory.getSearchService().getIndexes(builder)

    for (Index index : indexes) {

        Results<ScoredDocument> result = index.search("")

        for (Document document : result) {
            index.deleteAsync(document.id)
        }
    }
</code>```

It's supposed to clean all data in datastore and all indexes in before each test.
But throws an error in the index.deleteAsync(document.id) line

Body:
In Google APP engine, I am using Lucene 4.1.

I am able to generate index file in local, but on the google server I am getting following exception (although the same code works fine in local machine):

org.apache.lucene.store.LockObtainFailedException: Lock obtain timed out:
   com.googlecode.lucene.appengine.GaeLockFactory$1@104a681

Here is my code:

package com.search.domain;

import java.io.IOException;
import java.util.Set;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.util.Version;

import com.domain.dataobjects.Item;
import com.googlecode.lucene.appengine.GaeDirectory;
import com.googlecode.lucene.appengine.GaeLuceneUtil;

public class ItemDataIndexWriter {

public String createIndexes(){
    IndexWriter indexWriter = null;
    GaeDirectory indexDirectory = null;
try{
        indexDirectory = new GaeDirectory();

        StandardAnalyzer analyzer = new StandardAnalyzer(Version.LUCENE_41 );

        IndexWriterConfig config = GaeLuceneUtil.getIndexWriterConfig(Version.LUCENE_41, analyzer);//get configuration

        config.setOpenMode(OpenMode.CREATE_OR_APPEND);
        indexWriter = new IndexWriter(indexDirectory, config);

        addToDoc(indexWriter,"test");
 }catch(Exception e){
     e.printStackTrace();
     System.out.println(e.getMessage());
     return e.toString();
 }
 finally{
     try {
        if(indexWriter!=null)
             indexWriter.close();
        if(indexDirectory!=null)
             indexDirectory.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.out.println(e.getMessage());
    }
 }
return "Good";
}

private static void addToDoc(IndexWriter w, String item) throws IOException {

    Document doc = new Document();
    doc.add(new TextField("item", item, Field.Store.YES));
    w.addDocument(doc);
}
}

Can anyone guide me ? what is wrong?

Body:
I had the same problem, but in a test, in the cloud works pretty well.
I did this in groovy:

    final DatastoreService datastore = DatastoreServiceFactory.getDatastoreService()
    final PreparedQuery pq = datastore.prepare(new Query())
    def list = pq.asList(FetchOptions.Builder.withDefaults())
    datastore.delete(list.collect {it.key})

    GetIndexesRequest builder = GetIndexesRequest.newBuilder().build()
    GetResponse<Index> indexes = SearchServiceFactory.getSearchService().getIndexes(builder)

    for (Index index : indexes) {

        Results<ScoredDocument> result = index.search("")

        for (Document document : result) {
            index.deleteAsync(document.id)
        }
    }

It's supposed to clean all data in datastore and all indexes in before each test.
But throws an error in the index.deleteAsync(document.id) line


问:
CSS positioning and z-index on card
I'm trying to code this card design:

However, I need some help with the positioning and z-index. This is how far I've come:

.card {
  width: 450px;
  height: 400px;
  background: lightblue;
}

.card-hover-state {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(-180deg, #000000 0%, rgba(216,216,216,0.00) 100%);
  opacity: 0.6;
}

.card-hover-state-title {
  font-size: 15px;
  color: #FFFFFF;
  max-width: 60%;
}

.card-hover-state-button {
  font-size: 11px;
  color: #FFFFFF;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
  <div class="card-hover-state"></div>
  <div class="information-container">
    <div class="card-hover-state-title">Brace yourself - A fancy Lorem Ipsum Title is comming</div>
    <div class="card-hover-state-button">READ MORE</div>
  </div>
</div></code>```

However, the text isn't showing. What am I missing?

答:
Use position: relative on .card, then you actually don't need .card-hover-state - you can use a pseudo element instead. Whichever of those you use, you need to add position: absolute; top: 0; left: 0; to position it over the .card background.

Then I would make .information-center a flex parent and use justify-content: space-between to separate its children, and align-items: center to center them vertically, and add position: relative so it will have a position that puts it on top of the absolutely positioned pseudo element (or .card-hover-state) that comes before it.

.card {
  width: 450px;
  height: 400px;
  background: lightblue;
  position: relative;
}

.card::before {
  content: '';
  position: absolute;
  top: 0; left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(
    -180deg,
    #000000 0%,
    rgba(216, 216, 216, 0.00) 100%
  );
  opacity: 0.6;
}

.information-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  color: #fff;
}

.card-hover-state-title {
  font-size: 15px;
  max-width: 60%;
}

.card-hover-state-button {
  font-size: 11px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
  <div class="information-container">
    <div class="card-hover-state-title">Brace yourself - A fancy Lorem Ipsum Title is comming</div>
    <div class="card-hover-state-button">READ MORE</div>
  </div>
</div></code>```

Title: CSS positioning and z-index on card

Body:
I'm trying to code this card design:

However, I need some help with the positioning and z-index. This is how far I've come:

.card {
  width: 450px;
  height: 400px;
  background: lightblue;
}

.card-hover-state {
  position: relative;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(-180deg, #000000 0%, rgba(216,216,216,0.00) 100%);
  opacity: 0.6;
}

.card-hover-state-title {
  font-size: 15px;
  color: #FFFFFF;
  max-width: 60%;
}

.card-hover-state-button {
  font-size: 11px;
  color: #FFFFFF;
}

Brace yourself - A fancy Lorem Ipsum Title is comming

READ MORE

However, the text isn't showing. What am I missing?

Body:
Use position: relative on .card, then you actually don't need .card-hover-state - you can use a pseudo element instead. Whichever of those you use, you need to add position: absolute; top: 0; left: 0; to position it over the .card background.

Then I would make .information-center a flex parent and use justify-content: space-between to separate its children, and align-items: center to center them vertically, and add position: relative so it will have a position that puts it on top of the absolutely positioned pseudo element (or .card-hover-state) that comes before it.

.card {
  width: 450px;
  height: 400px;
  background: lightblue;
  position: relative;
}

.card::before {
  content: '';
  position: absolute;
  top: 0; left: 0;
  width: 100%;
  height: 100%;
  background-image: linear-gradient(
    -180deg,
    #000000 0%,
    rgba(216, 216, 216, 0.00) 100%
  );
  opacity: 0.6;
}

.information-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  color: #fff;
}

.card-hover-state-title {
  font-size: 15px;
  max-width: 60%;
}

.card-hover-state-button {
  font-size: 11px;
}

<div class="card">
  <div class="information-container">
    <div class="card-hover-state-title">Brace yourself - A fancy Lorem Ipsum Title is comming</div>
    <div class="card-hover-state-button">READ MORE</div>
  </div>
</div>


问:
jquery validation plugin working ok first time you validate but not subsequent times
I have the following form which is added to a page via ajax

```<code><script>
    $(document).ready(function() {

        jQuery.validator.setDefaults({
            errorPlacement: function(error, element) {
                 error.appendTo('#invalid_' + element.attr('id'));
            }
        });

        var validator = $("#login_form").validate({
            rules: {
                user_email: {
                  required: true,
                  email: true
                },
                password: {
                    required: true
                }
            }
        });
    });

</script>

<form id="login_form">
<center><br/><br/><br/>
    <div class="login_div">
        <center><h3>Log In</h3>
        <table align="center" width="400px">
            <tr><td class="input_td">Email:</td><td class="textfield_td"><input type="text" class="textfield" id="user_email" name="user_email"/></td></tr>
            <tr><td colspan="2" id="invalid_user_email"></td></tr>
            <tr><td class="input_td">Password:</td><td class="textfield_td"><input type="password" class="textfield" id="password" name="password"/></td></tr>
            <tr><td colspan="2" id="invalid_password"></td></tr>
            <tr><td colspan="2" class="error_text" id="login_error"></td></tr>
        </table>
        <input  type="button" onclick="check_login();" value="Log In"/></center>
    </div>
</center>
</form>
</code>```

The check_login method has this structure: if($("#login_form").valid()) {do something} else {return;}

When i click the Log in button the first time the form validates correctly e.g. If fields are missing or an invalid email is supplied then the appropriate error messages are shown. However if i then click the log in button again the valid() method returns true even if fields are missing or there is an invalid email and no error messages are shown.

thanks for any light you can shed on this

EDIT: This solution appears to work where login is the id of the button

```<code>$("#login").click(function() {

    validator.resetForm();
    if(validator.form()) {
         alert('valid');

    }
    else {
        return;
    }

});
</code>```

答:
This is my form:

```<code><form method="post" class="form" name="form_destination" id="form_destination">
  <label style="margin-bottom: 10px" class="white block text-left">Enter country code followed by phone number then click Search <span class="badge badge-primary pointer tax-help" data-container="body" data-toggle="popover" data-placement="top" data-content="Enter the number you wish to call, recharge or send sms to. You must first enter the country code followed by the phone number, then press Search." data-original-title="" title="" aria-describedby="popover">?</span></label>
       <div class="input-group">
          <input type="tel" class="form-control text-center" placeholder="Type number" style="font-weight: 400;font-size: x-large;" name="destination" id="destination">
          <span class="input-group-addon pointer btn-naranja" id="btn_buscar"><i class="fa fa-search"></i> Search</span>
       </div>
</form>
</code>```

JavaScript solution:

```<code>$('#form_destination').on('submit', function(e) {
    e.preventDefault();
    $('#destination').focus();
    $('#form_destination').validate({
        rules: {
            destination: {
                required: true,
                minlength: 7,
                digits: true,
            }
        },
        messages: {
            destination: {
                required: "Please enter a phone number",
                minlength: "Please write at least 7 phone numbers",
                digits: "Please enter the phone number",
            }
        },
        submitHandler(form) {
            /* AJAX JQuery */
            /* your code */
        }
    });
});

$('#btn_buscar').on('click', function(event) {
    $('#form_destination').submit();
    $('#form_destination').submit();
    /* this my solution */
});
</code>```

Body:
I have the following form which is added to a page via ajax

<form id="login_form">

Log In

Email:	<input type="text" class="textfield" id="user_email" name="user_email"/>

Password:	<input type="password" class="textfield" id="password" name="password"/>

        <input  type="button" onclick="check_login();" value="Log In"/>

</form>

The check_login method has this structure: if($("#login_form").valid()) {do something} else {return;}

When i click the Log in button the first time the form validates correctly e.g. If fields are missing or an invalid email is supplied then the appropriate error messages are shown. However if i then click the log in button again the valid() method returns true even if fields are missing or there is an invalid email and no error messages are shown.

thanks for any light you can shed on this

EDIT: This solution appears to work where login is the id of the button

$("#login").click(function() {

    validator.resetForm();
    if(validator.form()) {
         alert('valid');

    }
    else {
        return;
    }

});

Body:
This is my form:

<form method="post" class="form" name="form_destination" id="form_destination">
  <label style="margin-bottom: 10px" class="white block text-left">Enter country code followed by phone number then click Search <span class="badge badge-primary pointer tax-help" data-container="body" data-toggle="popover" data-placement="top" data-content="Enter the number you wish to call, recharge or send sms to. You must first enter the country code followed by the phone number, then press Search." data-original-title="" title="" aria-describedby="popover">?</span></label>
       <div class="input-group">
          <input type="tel" class="form-control text-center" placeholder="Type number" style="font-weight: 400;font-size: x-large;" name="destination" id="destination">
          <span class="input-group-addon pointer btn-naranja" id="btn_buscar"><i class="fa fa-search"></i> Search</span>
       </div>
</form>

JavaScript solution:

$('#form_destination').on('submit', function(e) {
    e.preventDefault();
    $('#destination').focus();
    $('#form_destination').validate({
        rules: {
            destination: {
                required: true,
                minlength: 7,
                digits: true,
            }
        },
        messages: {
            destination: {
                required: "Please enter a phone number",
                minlength: "Please write at least 7 phone numbers",
                digits: "Please enter the phone number",
            }
        },
        submitHandler(form) {
            /* AJAX JQuery */
            /* your code */
        }
    });
});

$('#btn_buscar').on('click', function(event) {
    $('#form_destination').submit();
    $('#form_destination').submit();
    /* this my solution */
});


答: The type of Y should be int. That is, it should consist of integers that represent the class labels. However, in your data frame the Y column consists of floats, and hence you get this error.

Title: Python: Logistic Regression gives ValueError: Unknown label type: 'continuous'

Body:
I have a question related to Logistic Regression where I am getting ValueError

Here's my dataset:

             sub1         sub2              sub3       sub4
pol_1     0.000000      0.000000            0.0      0.000000
pol_2     0.000000      0.000000            0.0      0.000000
pol_3     0.050000      0.000000            0.0      0.000000
pol_4     0.000000      0.000000            0.0      0.000000
pol_5     0.000000      0.000000            0.0      0.000000
pol_6     0.000000      0.000000            0.0      0.000000
pol_7     0.000000      0.000000            0.0      0.000000
pol_8     0.000000      0.000000            0.0      0.000000
pol_9     0.000000      0.000000            0.0      0.000000
pol_10    0.000000      0.000000            0.0      0.032423
pol_11    0.000000      0.000000            0.0      0.000000
pol_12    0.000000      0.000000            0.0      0.000000
pol_13    0.000000      0.000000            0.0      0.000000
pol_14    0.000000      0.053543            0.0      0.000000
pol_15    0.000000      0.000000            0.0      0.000000
pol_16    0.000000      0.000000            0.0      0.000000
pol_17    0.000000      0.000000            0.0      0.000000
pol_18    0.000000      0.000000            0.0      0.053453
pol_19    0.000000      0.058344            0.0      0.000000
pol_20    0.054677      0.000000            0.0      0.000000

This is my code:

array = df.values
X = array[:,0:3]
Y = array[:,3]
validation_size = 0.20
seed = 7
X_train, X_validation, Y_train, Y_validation =
model_selection.train_test_split(X, Y, test_size=validation_size,
random_state=seed)

seed = 7
scoring = 'accuracy'

kfold = model_selection.KFold(n_splits=10, random_state=seed)
cv_results = model_selection.cross_val_score(LogisticRegression(), X_train, Y_train, cv=kfold, scoring=scoring)
print(cv_results)

This gives me the following error:

ValueError: Unknown label type: 'continuous'

How can this issue be tackled?

Also, I looked through certain links and found that the issue could be related to datatype which in my case is:

print(df.dtypes)
print(X_train.dtype)

pol_1     float64
pol_2     float64
pol_3     float64
pol_4     float64
pol_5     float64
pol_6     float64
pol_7     float64
pol_8     float64
pol_9     float64
pol_10    float64
pol_11    float64
pol_12    float64
pol_13    float64
pol_14    float64
pol_15    float64
pol_16    float64
pol_17    float64
pol_18    float64
pol_19    float64
pol_20    float64
Length: 20, dtype: object
float64

I tried to convert the datatype for X_train and Y_train to string but got the same error.

Thanks!


问:
JS delete duplicated items from array without higher order functions
I know it's a stupid question, but I only learning programming 3 months now.

How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?

Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed

I got this so far, but I think It's a dead end...

```<code>const array = [1, 2, 3, 3, 1];

const removeDuplicate = () => {
    let shortArray = [];
    let index = 0;
    for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array.length; j++) {
            if (i != j) {
                if (array[i] == array[j]) {
                    shortArray[index] += array[i]
                    console.log(array[i]);
                }
            }
        }
    }
    return shortArray;
}

console.log(removeDuplicate());
</code>```

return this:

```<code>1
3
3
1
[ NaN ]
</code>```

thanks!

答:
Use an object as a helper. If a value appears in the helper, it's not unique and can be ignored. If it's not in the helper it's unique, push it into the result array, and add it to the helper object.

const array = [1, 2, 3, 3, 1];

const removeDuplicate = (arr) => {
  const helperMap = {};
  const result = [];

  for (let i = 0; i < arr.length; i++) {
    const item = arr[i];

    if (!helperMap[item]) {
      result[result.length] = item;

      helperMap[item] = true;
    }
  }

  return result;
};

console.log(removeDuplicate(array));```

Body:
I know it's a stupid question, but I only learning programming 3 months now.

How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?

Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed

I got this so far, but I think It's a dead end...

const array = [1, 2, 3, 3, 1];

const removeDuplicate = () => {
    let shortArray = [];
    let index = 0;
    for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array.length; j++) {
            if (i != j) {
                if (array[i] == array[j]) {
                    shortArray[index] += array[i]
                    console.log(array[i]);
                }
            }
        }
    }
    return shortArray;
}

console.log(removeDuplicate());

return this:

1
3
3
1
[ NaN ]

thanks!


问:
X3D Volume Rendering using PNG file instead of NRRD file
So I was wondering if it's at all possible to use a PNG file in place of an NRRD file when rendering volume in X3D? I know there's something in the API called TextureAtlas that I think might be what I'm looking for but I can't seem to find a working example anywhere online. Any help would be greatly appreciated.</p>

答: So it turns out the X3D player I was using, that being instantplayer by instantreality, does not support the TextureAtlas node in the first place. So it appears the only player that might support the different nodes I need is X3DOM, seeing as how I was able to find an example in a slideshow online.</p>


问:
What in the parse body code makes the header read to not fail?
I am trying to build a simple web scraper to get some corpus of text from wikipedia. I would like to use their REST API building a simple HTTP client in Haskell.

To do so, I've turned to the Network.HTTP.Simple package.  In their tutorial they provide the following snippet, which i can get to run nicely.

```<code>#!/usr/bin/env stack
{- stack --install-ghc --resolver lts-5.13 runghc
    --package http-conduit
    --package yaml
-}
{-# LANGUAGE OverloadedStrings #-}
import           Data.Aeson            (Value)
import qualified Data.ByteString.Char8 as S8
import qualified Data.Yaml             as Yaml
import           Network.HTTP.Simple

main :: IO ()
main = do
    response <- httpJSON "http://httpbin.org/get"

    putStrLn $ "The status code was: " ++
               show (getResponseStatusCode response)
    print $ getResponseHeader "Content-Type" response
    S8.putStrLn $ Yaml.encode (getResponseBody response :: Value)
</code>```

Trying to understand the code I commented out the last line (the one starting S8.putStrLn..., and now the code breaks. The error is

```<code>No instance for (Yaml.FromJSON a0) arising from a use of ‘httpJSON’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance Yaml.FromJSON
                 aeson-1.2.1.0:Data.Aeson.Types.Internal.DotNetTime
        -- Defined in ‘aeson-1.2.1.0:Data.Aeson.Types.FromJSON’
      instance Yaml.FromJSON Value
        -- Defined in ‘aeson-1.2.1.0:Data.Aeson.Types.FromJSON’
      instance Yaml.FromJSON
                 attoparsec-0.13.1.0:Data.Attoparsec.Number.Number
        -- Defined in ‘aeson-1.2.1.0:Data.Aeson.Types.FromJSON’
      ...plus 78 others
</code>```

So my questions are:
(1) So my guess is that the getResponseBody forces the type signature of httpJSON, so the ambiguity is lifted. But how?
(2) Can I disambiguate the expression without calling getResponseBody? What options do I have to fix the return type of polymorphic functions?

Edit: I am running this with cabal run since i have not installed Stack. I did not expect that to change things, but who knows... Might provide a clue.

答:
Type checking

We have this signature: getResponseBody :: Response a -> a.

At first, just after httpJSON, we have response :: Response a0 for some yet unknown a0.

Then we write getResponseBody response, which has type a0, still unknown.

Then we annotate getResponseBody response :: Value, so a0 ~ Value, and now instance resolution has a concrete type to work with.

Alternative ways to restrict the type of response

You can annotate the response value directly wherever it gets used, for instance you could write getResponseStatusCode (response :: Response Value) in the middle of your snippet.

With the ScopedTypeVariables extension, you can also annotate the pattern which binds it: (response :: Response Value) <- httpJSON "...".

The a0 type variable also occurs in the result type of httpJSON, so you can also annotate it.

```<code>response <- httpJSON "..." :: IO (Response Value)
</code>```

With TypeApplications, here are more alternatives, any one should be sufficient for the type checker to deduce a0 ~ Value:

```<code>response <- httpJSON @_ @Value "..."

getResponseStatusCode @Value response
getResponseHeader @Value "..." response
getResponseBody @Value response
</code>```

Body:
I am trying to build a simple web scraper to get some corpus of text from wikipedia. I would like to use their REST API building a simple HTTP client in Haskell.

To do so, I've turned to the Network.HTTP.Simple package.  In their tutorial they provide the following snippet, which i can get to run nicely.

#!/usr/bin/env stack
{- stack --install-ghc --resolver lts-5.13 runghc
    --package http-conduit
    --package yaml
-}
{-# LANGUAGE OverloadedStrings #-}
import           Data.Aeson            (Value)
import qualified Data.ByteString.Char8 as S8
import qualified Data.Yaml             as Yaml
import           Network.HTTP.Simple

main :: IO ()
main = do
    response <- httpJSON "http://httpbin.org/get"

    putStrLn $ "The status code was: " ++
               show (getResponseStatusCode response)
    print $ getResponseHeader "Content-Type" response
    S8.putStrLn $ Yaml.encode (getResponseBody response :: Value)

Trying to understand the code I commented out the last line (the one starting S8.putStrLn..., and now the code breaks. The error is

No instance for (Yaml.FromJSON a0) arising from a use of ‘httpJSON’
    The type variable ‘a0’ is ambiguous
    Note: there are several potential instances:
      instance Yaml.FromJSON
                 aeson-1.2.1.0:Data.Aeson.Types.Internal.DotNetTime
        -- Defined in ‘aeson-1.2.1.0:Data.Aeson.Types.FromJSON’
      instance Yaml.FromJSON Value
        -- Defined in ‘aeson-1.2.1.0:Data.Aeson.Types.FromJSON’
      instance Yaml.FromJSON
                 attoparsec-0.13.1.0:Data.Attoparsec.Number.Number
        -- Defined in ‘aeson-1.2.1.0:Data.Aeson.Types.FromJSON’
      ...plus 78 others

So my questions are:
(1) So my guess is that the getResponseBody forces the type signature of httpJSON, so the ambiguity is lifted. But how?
(2) Can I disambiguate the expression without calling getResponseBody? What options do I have to fix the return type of polymorphic functions?

Edit: I am running this with cabal run since i have not installed Stack. I did not expect that to change things, but who knows... Might provide a clue.

Body:
Type checking

We have this signature: getResponseBody :: Response a -> a.

At first, just after httpJSON, we have response :: Response a0 for some yet unknown a0.

Then we write getResponseBody response, which has type a0, still unknown.

Then we annotate getResponseBody response :: Value, so a0 ~ Value, and now instance resolution has a concrete type to work with.

Alternative ways to restrict the type of response

You can annotate the response value directly wherever it gets used, for instance you could write getResponseStatusCode (response :: Response Value) in the middle of your snippet.

With the ScopedTypeVariables extension, you can also annotate the pattern which binds it: (response :: Response Value) <- httpJSON "...".

The a0 type variable also occurs in the result type of httpJSON, so you can also annotate it.

response <- httpJSON "..." :: IO (Response Value)

With TypeApplications, here are more alternatives, any one should be sufficient for the type checker to deduce a0 ~ Value:

response <- httpJSON @_ @Value "..."

getResponseStatusCode @Value response
getResponseHeader @Value "..." response
getResponseBody @Value response


问:
IDE for C application development that you admire most
I am looking for a good Integrated development environment for developing applictaions in C language for both windows and linux.

IDE should have:

good interface,

easy file management,

auto filling and

any advanced options.

Tell me which IDE you most admire for these tasks

For general PC application development

For embedded application development in C

If you think it is more specific question then you may also take it as a general case.
Thanks in advance.

答:
Apart from TextMate on OS X which is more a very featurefull text editor, I'd say NetBeans or Eclipse.

EDIT: yes, if you have a mac, you can do PC development with VMWare/Paralles as easily as you would in a "real" PC and you get OS X as a bonus.

OwnerDisplayName: Manoj Doubts

OwnerDisplayName: Keltia


问:
adding a passed in number to a MySQL cell with PHP
I am trying to add a number to a number already in a MySQL table. I am using POST to pass in the number.

```<code>    <?php
    require "connection.php";

    $id = $_POST["id"];
    $number = $_POST["number"];
</code>```

Do I have to make 2 separate queries, one to retrieve the current value and set is as a variable and one to insert the new value by adding the number to the variable or can I accomplish this with one query with something like this:

```<code>    $update_query = "update Table set value = (value + $number) where id like '$id';"
</code>```

答:
update field to add value to existing value:

```<code>UPDATE table SET value = value + $number WHERE id = $id;
</code>```

update field to contact value to existing value:

use the CONCAT function :

```<code>UPDATE table SET value= CONCAT('$number',value) WHERE id=$id;
</code>```

Body:
I am trying to add a number to a number already in a MySQL table. I am using POST to pass in the number.

    <?php
    require "connection.php";

    $id = $_POST["id"];
    $number = $_POST["number"];

Do I have to make 2 separate queries, one to retrieve the current value and set is as a variable and one to insert the new value by adding the number to the variable or can I accomplish this with one query with something like this:

    $update_query = "update Table set value = (value + $number) where id like '$id';"

Body:
update field to add value to existing value:

UPDATE table SET value = value + $number WHERE id = $id;

update field to contact value to existing value:

use the CONCAT function :

UPDATE table SET value= CONCAT('$number',value) WHERE id=$id;


问:
What is the difference between ios::app and ios::noreplace modes in file handling?
I am studying File Handling in C++, but I am unable to see the difference between ios::app and ios::noreplace modes. Kindly help.

Note: ios::noreplace is a non-standard mode in some older version yet I am curious to know about it!

答:
IIRC ios::noreplace was a nonstandard part of some old version of the MS run-time library. It is not standard C++ so there's one difference to begin with.

The other difference is that ios::noreplace does not append at all: It simply fails if the file is present (thus the name no replace) and opens it only if it did not exist in the first place. ios::app opens the file if present or creates a new one and seeks to the end before each write.


问:
Span (long text) with image to the right
Could you help me with this?
I have a span and an img inside a li in a sidebar. What I want is the span to always have the img to the right and also that the img is vertically centered, no matter how long the text inside the span gets (I dont know how long or short it can gets).

Right now I have this:

HTML:

```<code><li class="sidebar-menu-item">
     <p class="sidebar-menu-button" ><img src="img/logout.png"/>Text that could be very long</p>
</li>
</code>```

What I want:

Any help would be very appreciated :)

答:
Use flex on the parent, and align-items: center to vertically align it's children.

li {
  list-style: none;
}

li p {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><li class="sidebar-menu-item">
     <p class="sidebar-menu-button">Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br><img src="http://kenwheeler.github.io/slick/img/lazyfonz2.png"/></p>
</li></code>```

Body:
Could you help me with this?
I have a span and an img inside a li in a sidebar. What I want is the span to always have the img to the right and also that the img is vertically centered, no matter how long the text inside the span gets (I dont know how long or short it can gets).

Right now I have this:

HTML:

Text that could be very long

What I want:

Any help would be very appreciated :)

Body:
Use flex on the parent, and align-items: center to vertically align it's children.

li {
  list-style: none;
}

li p {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

<li class="sidebar-menu-item">
     <p class="sidebar-menu-button">Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br>Text that could be very long<br><img src="http://kenwheeler.github.io/slick/img/lazyfonz2.png"/></p>
</li>


问:
How to change the cookbooks default directory
When I create my cookbooks using the knife command I would like them to get saved into a specified directory.
I know I can use the -o flag and specify the directory. However, I would like to make a specified directory a default directory. Is there a setting that I can change to accomplish that?
THank you.</p>

答:
You can specify default directory under knife.rb file by inserting the following code</p>

```<code>cookbook_path [
  '/your/cookbook/default_directory'
]
</code>```

Body:
You can specify default directory under knife.rb file by inserting the following code

cookbook_path [
  '/your/cookbook/default_directory'
]


问:
Place to write laravel RAW queries?
We are currently working with a big laravel 5.2 project. For our query, we always try to use Eloquent ORM. But sometimes we need to use RAW queries.

We think in future, we have to write more RAW queries. So we need a separate place and a well-organised way to write RAW queries.We don’t want to write raw query in our controller and model.

Is there any other place where we can put raw queries. Or what is the best procedure to write raw queries(Write a separate file or repository etc.)

答:
You could use scopes

For each group of related queries, I would create a file in scopes directory structured according to your models structure.

This will give you a central place where you could add or edit your raw queries.

Title: Place to write laravel RAW queries?


问:
Create k size permutations without to define more functions
is it possible to implement Scheme function (one function - its important) that gets a list and k, and retreive the permutations in size of k, for example: (1 2 3), k=2 will output { (1,1) , (1,2) , (1,3) , (2,1) , (2,2) , ..... } (9 options).?</p>

答:
Its possible to do anything without defining anything as long as you have lambda:

(define (fib n)
  ;; bad internal definition
  (define (helper n a b)
    (if (zero? n)
        a
        (helper (- n 1) b (+ a b))))
  (helper n 0 1))
```

<p>Using Z combinator:</p>

```(define Z
  (lambda (f)
    ((lambda (g)
       (f (lambda args (apply (g g) args))))
     (lambda (g)
       (f (lambda args (apply (g g) args)))))))

(define (fib n)
  ((Z (lambda (helper)
        (lambda (n a b)
          (if (zero? n)
              a
              (helper (- n 1) b (+ a b))))))
   n 0 1))
```

<p>Now we are never calling Z so we can substitute the value of Z for Z in the function and it will do the same:</p>

```(define (fib n)
  (((lambda (f)
      ((lambda (g)
         (f (lambda args (apply (g g) args))))
       (lambda (g)
         (f (lambda args (apply (g g) args))))))
    (lambda (helper)
      (lambda (n a b)
        (if (zero? n)
            a
            (helper (- n 1) b (+ a b))))))
   n 0 1))
```

There you go, Saved by Alonzo Church.

Body:
Its possible to do anything without defining anything as long as you have lambda:

(define (fib n)
  ;; bad internal definition
  (define (helper n a b)
    (if (zero? n)
        a
        (helper (- n 1) b (+ a b))))
  (helper n 0 1))

Using Z combinator:

(define Z
  (lambda (f)
    ((lambda (g)
       (f (lambda args (apply (g g) args))))
     (lambda (g)
       (f (lambda args (apply (g g) args)))))))

(define (fib n)
  ((Z (lambda (helper)
        (lambda (n a b)
          (if (zero? n)
              a
              (helper (- n 1) b (+ a b))))))
   n 0 1))

Now we are never calling Z so we can substitute the value of Z for Z in the function and it will do the same:

(define (fib n)
  (((lambda (f)
      ((lambda (g)
         (f (lambda args (apply (g g) args))))
       (lambda (g)
         (f (lambda args (apply (g g) args))))))
    (lambda (helper)
      (lambda (n a b)
        (if (zero? n)
            a
            (helper (- n 1) b (+ a b))))))
   n 0 1))

There you go, Saved by Alonzo Church.


问:
Using C#, how can I read the content of dynamic created textboxes?
Hy,

I have created some dynamic textboxes with standard content.

Does anyone know how can I read the content of these textboxes (assuming that user modified the standard content) when I press one button?

Thanks a lot.

Jeff

Update

This is how I am creating the textboxes:

```<code>foreach (string name in listOfNames)
{
   TextBox tb = new TextBox();
   tb.Text = name;
   tb.BorderStyle = BorderStyle.None;
   tb.BorderWidth = 0;
   tb.Font.Name = "Arial";
   tb.Font.Size = 8;
}
</code>```

答:
You need to ensure that the text boxes are recreated on every postback.

If you do not recreate them, you will not be able to access their properties or events.

The best place to create dynamic controls is the page Init event handler.

I suggest reading up on the ASP.NET page life cycle.

Update (following updated question)

Make sure to set an ID (and a different one, at that) for the text boxes, so you can refer to them later on.

I can't see where you are adding these controls to the page either.

Body:
Hy,

I have created some dynamic textboxes with standard content.

Does anyone know how can I read the content of these textboxes (assuming that user modified the standard content) when I press one button?

Thanks a lot.

Jeff

Update

This is how I am creating the textboxes:

foreach (string name in listOfNames)
{
   TextBox tb = new TextBox();
   tb.Text = name;
   tb.BorderStyle = BorderStyle.None;
   tb.BorderWidth = 0;
   tb.Font.Name = "Arial";
   tb.Font.Size = 8;
}


问:
RxJS Observable: Emit every specific change in the array
I have a list of user IDs, and for each user in the list I want to retrieve extra information.
So I want to know when the list changes, but also when the information of each user changes.
For example:

name: Anna, age:28

name: Peter, age:23

name: Paul, age 21

If Anna's age changes I want to be able to update the list, and if another user is added to the list I also want to keep track of that.

This is what I've done:

```<code>private getUserData(userId:string):Observable<User>{...}

let userIds$:Observable<string[]> = getUserIds();

let users$ = userIds$.flatMap(x=>x)   //get the string[]
                     .map(userId => this.getUserData(chatId)) //for each ID get the data
                     .mergeAll();

users$.subscribe(x =>{console.log(x)});
</code>```

This kind of does what I want, but my problem is that every time the list is updated (add elements, or remove), each element in the list subscribes again for changes.
So for example, if I add and 2 elements to the list, and then I update Anna's age, I receive the object Anna 3 times.

For what I've read probably switchMap would fix it, but I've tried using it, and I haven't been able to make it work.

Thanks

答:
Welcome to Stack Overflow!

What you need is to emit a value which is a difference between the current and previous list of objects.

Creating a diff can be achieved by using lodash's difference function.

Let's assume that the structure of data looks like this:

```<code>[
  { name: 'Anna', age: 28 },
  { name: 'Peter', age: 23 },
  { name: 'Paul', age: 21 },
]
</code>```

There can be many ways to answer your question but the solution I came up is:

Store list in a variable which shouldn't be accessible from the outside.

Create one BehaviorSubject which will emit the whole array when changed and Observable emitting the difference.

Create functions which will modify the array and tell BehaviorSubject that we have a new array.

EDIT: If somebody reading this has the ambition to create a fully reactive solution, consider using scan operator to contain the
  state with whole functionality in one stream. (spoiler: you'll reinvent redux what isn't a bad thing). The example here was written this way for the sake of simplicity.

I won't try to emulate your implementation (you're fetching data from server API) but I'll give you a pattern which you can take inspiration from.

```<code>const userList = {
  current: [],
  previous: [],
};

const userListChanged$ = new Rx.BehaviorSubject(userList.current);
const userListDifference$ = userListChanged$.map(current => {
  return _.difference(current, userList.previous);
});

function currentToPrevious() {
  userList.previous = [].concat(userList.current);
}

function addUser(name, age) {
  currentToPrevious();
  userList.current.push({name, age});
  userListChanged$.next(userList.current);
}

function modifyUser(index, object) {
  currentToPrevious();
  userList.current[index] = Object.assign({}, userList.current[index], object);
  userListChanged$.next(userList.current);
}

userListChanged$.subscribe(value => console.log('list', value));
userListDifference$.subscribe(value => console.log('diff', value));

addUser('Peter', 29);
addUser('Tom', 30);
addUser('Anna', 21);
modifyUser(2, { age: 20 });
</code>```

JSFiddle

userListDifference$ output:

[ { name: 'Peter', age: 29 } ]

[ { name: 'Tom', age: 30 } ]

[ { name: 'Anna', age: 21 } ]

[ { name: 'Anna', age: 20 } ]

userListChanged$ output:

[ { name: 'Peter', age: 29 } ]

[ { name: 'Peter', age: 29 }, { name: 'Tom', age: 30 } ]

[ { name: 'Peter', age: 29 }, { name: 'Tom', age: 30 }, { name: 'Anna', age: 21 } ]

[ { name: 'Peter', age: 29 }, { name: 'Tom', age: 30 }, { name: 'Anna', age: 20 } ]

Body:
I have a list of user IDs, and for each user in the list I want to retrieve extra information.
So I want to know when the list changes, but also when the information of each user changes.
For example:

name: Anna, age:28

name: Peter, age:23

name: Paul, age 21

If Anna's age changes I want to be able to update the list, and if another user is added to the list I also want to keep track of that.

This is what I've done:

private getUserData(userId:string):Observable<User>{...}

let userIds$:Observable<string[]> = getUserIds();

let users$ = userIds$.flatMap(x=>x)   //get the string[]
                     .map(userId => this.getUserData(chatId)) //for each ID get the data
                     .mergeAll();

users$.subscribe(x =>{console.log(x)});

This kind of does what I want, but my problem is that every time the list is updated (add elements, or remove), each element in the list subscribes again for changes.
So for example, if I add and 2 elements to the list, and then I update Anna's age, I receive the object Anna 3 times.

For what I've read probably switchMap would fix it, but I've tried using it, and I haven't been able to make it work.

Thanks

Body:
Welcome to Stack Overflow!

What you need is to emit a value which is a difference between the current and previous list of objects.

Creating a diff can be achieved by using lodash's difference function.

Let's assume that the structure of data looks like this:

[
  { name: 'Anna', age: 28 },
  { name: 'Peter', age: 23 },
  { name: 'Paul', age: 21 },
]

There can be many ways to answer your question but the solution I came up is:

Store list in a variable which shouldn't be accessible from the outside.

Create one BehaviorSubject which will emit the whole array when changed and Observable emitting the difference.

Create functions which will modify the array and tell BehaviorSubject that we have a new array.

EDIT: If somebody reading this has the ambition to create a fully reactive solution, consider using scan operator to contain the
  state with whole functionality in one stream. (spoiler: you'll reinvent redux what isn't a bad thing). The example here was written this way for the sake of simplicity.

I won't try to emulate your implementation (you're fetching data from server API) but I'll give you a pattern which you can take inspiration from.

const userList = {
  current: [],
  previous: [],
};

const userListChanged$ = new Rx.BehaviorSubject(userList.current);
const userListDifference$ = userListChanged$.map(current => {
  return _.difference(current, userList.previous);
});

function currentToPrevious() {
  userList.previous = [].concat(userList.current);
}

function addUser(name, age) {
  currentToPrevious();
  userList.current.push({name, age});
  userListChanged$.next(userList.current);
}

function modifyUser(index, object) {
  currentToPrevious();
  userList.current[index] = Object.assign({}, userList.current[index], object);
  userListChanged$.next(userList.current);
}

userListChanged$.subscribe(value => console.log('list', value));
userListDifference$.subscribe(value => console.log('diff', value));

addUser('Peter', 29);
addUser('Tom', 30);
addUser('Anna', 21);
modifyUser(2, { age: 20 });

JSFiddle

userListDifference$ output:

[ { name: 'Peter', age: 29 } ]

[ { name: 'Tom', age: 30 } ]

[ { name: 'Anna', age: 21 } ]

[ { name: 'Anna', age: 20 } ]

userListChanged$ output:

[ { name: 'Peter', age: 29 } ]

[ { name: 'Peter', age: 29 }, { name: 'Tom', age: 30 } ]

[ { name: 'Peter', age: 29 }, { name: 'Tom', age: 30 }, { name: 'Anna', age: 21 } ]

[ { name: 'Peter', age: 29 }, { name: 'Tom', age: 30 }, { name: 'Anna', age: 20 } ]


问:
Android Studio Emulator and "Process finished with exit code -1073741511 (0xC0000139)"
I'm trying to emulate my application using Android Studio Emulator (i'm developing by Android Studio) but I receive this error message:

Emulator: Process finished with exit code -1073741511 (0xC0000139)

Do what can I do?

Problem image:

答: try increasing the ram size of your emulator.</p>

ContentLicense: CC BY-SA 4.0


问:
Intellij - create custom setter for immutable objects
I'm trying to write a setter template in Intellij that will generate conventional immutable setters, those that create and return a new object instance upon setting a member.
e.g.

```<code>Person setName(String name) {
  return new Person(age, name);
}
</code>```

Has anyone been here before?

答:
Under setting->Editor->Live Templates, you can use live templates with a template something like:

```<code>$TYPE$ set$NAME$($IN_TYPE$ $PARAM$) {
    return new $TYPE$($PARAM$);
}
</code>```

Where PARAM is defined with the expression "camelCase(NAME)"
and TYPE is defined with the expression "className()"

Body:
I'm trying to write a setter template in Intellij that will generate conventional immutable setters, those that create and return a new object instance upon setting a member.
e.g.

Person setName(String name) {
  return new Person(age, name);
}

Has anyone been here before?

Body:
Under setting->Editor->Live Templates, you can use live templates with a template something like:

$TYPE$ set$NAME$($IN_TYPE$ $PARAM$) {
    return new $TYPE$($PARAM$);
}

Where PARAM is defined with the expression "camelCase(NAME)"
and TYPE is defined with the expression "className()"


问:
How can i remove the commas between words and make them go under each subheading
my python code so far is:

```<code>list=("Member ID, Surname, Year joined, Nights booked, Membership status, Points balance")
f = open("SampleData2017.txt")
print(list)
for surname in f.readlines():
   print(surname)
</code>```

however when i run it the items are only seperated by commas and not under each subheading

i want it to look like:

```<code>MemberID  Surname  Year  joined Membershipstatus  Nightsbooked  Points balance
Gri33415 Griffiths    2015         Gold               35          40000

Smi22316  Smith       2016        Silver              3            7500
</code>```

how would i fix this? as simple as possible please

答:
I guess you can use python built in csv module to achieve what you want

Edit 1:

Observe headers is assigned initially as string and then converted list

added ljust to each items to give an idea how this can be achieved, but definitely not the exact alignment the way you want.

```<code>import csv
headers="Member ID, Surname, Year joined, Nights booked, Membership status, Points balance"
headers = headers.split(',')

print ('\t'.join(x.ljust(5) for x in headers))

with open('WorkingDirectory\stars.csv', 'r') as mycsv:
    rows = csv.reader(mycsv)
    for row in rows:
        print ('\t'.join(x.ljust(15) for x in row))
</code>```

Original Answer:

```<code>import csv

headers=["Member ID, Surname, Year joined, Nights booked, Membership status, Points balance"]

print ('\t'.join(headers))

with open('SampleData2017.txt', 'r') as mycsv:
    rows = csv.reader(mycsv)
    for row in rows:
        print ('\t'.join(row))
</code>```

Output:

```<code>Member ID, Surname, Year joined, Nights booked, Membership status, Points balance
Gri33415    Griffiths   2015    Gold    35  40000
Smi22316    Smith   2016    Silver  3   7500
</code>```

Body:
my python code so far is:

list=("Member ID, Surname, Year joined, Nights booked, Membership status, Points balance")
f = open("SampleData2017.txt")
print(list)
for surname in f.readlines():
   print(surname)

however when i run it the items are only seperated by commas and not under each subheading

i want it to look like:

MemberID  Surname  Year  joined Membershipstatus  Nightsbooked  Points balance
Gri33415 Griffiths    2015         Gold               35          40000

Smi22316  Smith       2016        Silver              3            7500

how would i fix this? as simple as possible please

Body:
I guess you can use python built in csv module to achieve what you want

Edit 1:

Observe headers is assigned initially as string and then converted list

added ljust to each items to give an idea how this can be achieved, but definitely not the exact alignment the way you want.

import csv
headers="Member ID, Surname, Year joined, Nights booked, Membership status, Points balance"
headers = headers.split(',')

print ('\t'.join(x.ljust(5) for x in headers))

with open('WorkingDirectory\stars.csv', 'r') as mycsv:
    rows = csv.reader(mycsv)
    for row in rows:
        print ('\t'.join(x.ljust(15) for x in row))

Original Answer:

import csv

headers=["Member ID, Surname, Year joined, Nights booked, Membership status, Points balance"]

print ('\t'.join(headers))

with open('SampleData2017.txt', 'r') as mycsv:
    rows = csv.reader(mycsv)
    for row in rows:
        print ('\t'.join(row))

Output:

Member ID, Surname, Year joined, Nights booked, Membership status, Points balance
Gri33415    Griffiths   2015    Gold    35  40000
Smi22316    Smith   2016    Silver  3   7500


答:
Request.Form is a collection of Key-Value pairs that represents all of the data coming back from the ASP.NET request. If you access that you can get any value whether its control is specified in the ASPX code or dynamically created in the code behind file.

You can also get their values placed back in them automatically if you recreate them during the init part of the page lifecycle. If you do this, their values will be set when ASP.NET recreates the state of the page and applies the values from the form.

Title: Using C#, how can I read the content of dynamic created textboxes?


问:
Missing Child While Using lxml to Parse Children of Paragraph Tag
I am using the Python library lxml to perform XML parsing on the HTML retrieved from this url. I have had no trouble using lxml in the past, however I may have just encountered a bug in the form of a missing child element (in the lxml tree) which plainly appears in the HTML.

Here is the Python code I am using to parse the HTML:

```<code>from urllib.request import urlopen
from lxml import etree

html_response = urlopen("http://ohhla.com/YFA_natedogg.html")
html_parser = etree.HTMLParser()
tree = etree.parse(html_response, html_parser)
tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0]
</code>```

A simplified version of the HTML code from the website I am parsing looks like this:

```<code><table id='AutoNumber7'>
    <tbody>
        <tr></tr>
        <tr>
            <td>
                # ... (irrelevant tags) ...
                <p>
                    <a></a>
                    # The following <table> tag is what I need to target:
                    <table></table>
                </p>
                # ... (seven <p> tags identical to the above) ...
            </td>
        </tr>
    </tbody>
</code>```

When I run tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren()
 in the console, lxml only detects the initial anchor tag  and ignores the sibling
 tag that I need to select (denoted by the above comment in the code).

Here is the console output:

```<code>tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren()
Out[22]: [<Element a at 0x2904a2a5808>]
</code>```

What I expect to see is:

```<code>tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren()
Out[22]: [<Element a at 0x2904a2a5808>, <Element table at 0x???????????>]
</code>```

Any ideas why the
 tag is missing from the
 tag's children?
How can I select this
 tag? I need to parse all content from the table tag, but lxml seems to not recognize it as a valid child element. If anyone can provide a working xpath selector for the desired
 tag I would be very greatful!

Note: I understand that I should really be seeing [<Element tr at 0x??????????>, <Element tr at 0x???????????>, ...] not [<Element table at 0x??????????>] but I was trying to be more concise.

EDIT: For those who don't consider the above code reproducible, literally just copy and paste this into the console:

```<code>from urllib.request import urlopen
from lxml import etree

html_response = urlopen("http://ohhla.com/YFA_natedogg.html")
html_parser = etree.HTMLParser()
tree = etree.parse(html_response, html_parser)
print(tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren())
</code>```

As before the HTML I am trying to parse is located here.

I don't really know how to be more concise than this. Constructive comments are appreciated (as always).

Linking to pages I have already read (e.g. How to create a Minimal,
Complete, and Verifiable
example) without commentary
is not constructive criticism.

Pointing out what steps I may have missed, or what to improve upon in the future (from a particular resource) is constructive criticism that is beneficial to both myself and the community as a whole.

I gladly accept advice on how to improve my posts, but please provide actual recommendations. Remember that several people may read the same resource and come to separate conclusions.

答:
I think the problem is that lxml tries to play by the rules of HTML. According to those rules,
 (a block level element) cannot be a child of
. See https://www.w3.org/TR/html4/struct/text.html#h-9.3.1.

Short demo:

```<code>from lxml import html

test = """
<html>
  <p>
    <table>
      <tr>
        <td>XXX</td>
      </tr>
    </table>
  </p>
</html>"""

root = html.fromstring(test)

# Just print the string representation of the parsed HTML
print(html.tostring(root).decode("UTF-8"))
</code>```

In the output from this code we can see that lxml refuses to interpret
 as a child of
:

```<code><html>
  <body><p>
    </p><table>
      <tr>
        <td>XXX</td>
      </tr>
    </table>

</body></html>
</code>```

 is an inline element so it makes sense that it is included in the return value from getchildren(). You will have to find some other way to identify the
 elements that you are interested in.

The http://ohhla.com/YFA_natedogg.html document claims to be XHTML, but it has many errors and it cannot be parsed as an XML document.

Body:
I am using the Python library lxml to perform XML parsing on the HTML retrieved from this url. I have had no trouble using lxml in the past, however I may have just encountered a bug in the form of a missing child element (in the lxml tree) which plainly appears in the HTML.

Here is the Python code I am using to parse the HTML:

from urllib.request import urlopen
from lxml import etree

html_response = urlopen("http://ohhla.com/YFA_natedogg.html")
html_parser = etree.HTMLParser()
tree = etree.parse(html_response, html_parser)
tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0]

A simplified version of the HTML code from the website I am parsing looks like this:

                # ... (irrelevant tags) ...

                    # The following
 tag is what I need to target:

                # ... (seven
 tags identical to the above) ...

When I run tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren()
 in the console, lxml only detects the initial anchor tag  and ignores the sibling
 tag that I need to select (denoted by the above comment in the code).

Here is the console output:

tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren()
Out[22]: [<Element a at 0x2904a2a5808>]

What I expect to see is:

tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren()
Out[22]: [<Element a at 0x2904a2a5808>, <Element table at 0x???????????>]

Any ideas why the
 tag is missing from the
 tag's children?
How can I select this
 tag? I need to parse all content from the table tag, but lxml seems to not recognize it as a valid child element. If anyone can provide a working xpath selector for the desired
 tag I would be very greatful!

Note: I understand that I should really be seeing [<Element tr at 0x??????????>, <Element tr at 0x???????????>, ...] not [<Element table at 0x??????????>] but I was trying to be more concise.

EDIT: For those who don't consider the above code reproducible, literally just copy and paste this into the console:

from urllib.request import urlopen
from lxml import etree

html_response = urlopen("http://ohhla.com/YFA_natedogg.html")
html_parser = etree.HTMLParser()
tree = etree.parse(html_response, html_parser)
print(tree.xpath("//table[@id='AutoNumber7']/tr[2]/td/p[1]")[0].getchildren())

As before the HTML I am trying to parse is located here.

I don't really know how to be more concise than this. Constructive comments are appreciated (as always).

Linking to pages I have already read (e.g. How to create a Minimal,
Complete, and Verifiable
example) without commentary
is not constructive criticism.

Pointing out what steps I may have missed, or what to improve upon in the future (from a particular resource) is constructive criticism that is beneficial to both myself and the community as a whole.

I gladly accept advice on how to improve my posts, but please provide actual recommendations. Remember that several people may read the same resource and come to separate conclusions.

Body:
I think the problem is that lxml tries to play by the rules of HTML. According to those rules, <table> (a block level element) cannot be a child of <p>. See https://www.w3.org/TR/html4/struct/text.html#h-9.3.1.

Short demo:

from lxml import html

test = """
<html>
  <p>
    <table>
      <tr>
        <td>XXX</td>
      </tr>
    </table>
  </p>
</html>"""

root = html.fromstring(test)

# Just print the string representation of the parsed HTML
print(html.tostring(root).decode("UTF-8"))

In the output from this code we can see that lxml refuses to interpret <table> as a child of <p>:

<html>
  <body><p>
    </p><table>
      <tr>
        <td>XXX</td>
      </tr>
    </table>

</body></html>

<a> is an inline element so it makes sense that it is included in the return value from getchildren(). You will have to find some other way to identify the <table> elements that you are interested in.

The http://ohhla.com/YFA_natedogg.html document claims to be XHTML, but it has many errors and it cannot be parsed as an XML document.


答:
```<code>function unique(arr) {
  var obj = {};

  for (var i = 0; i < arr.length; i++) {
    var value = arr[i];
    obj[value] = true; // set as key
  }

  return Object.keys(obj); //return all keys
}
</code>```

Title: JS delete duplicated items from array without higher order functions

Body:
I know it's a stupid question, but I only learning programming 3 months now.

How would you solve this problem, if you can't use higher order functions and built-in methods, like filter or indexOf?

Create a function that takes a list of numbers and returns a new list where all the duplicate values are removed

I got this so far, but I think It's a dead end...

const array = [1, 2, 3, 3, 1];

const removeDuplicate = () => {
    let shortArray = [];
    let index = 0;
    for (let i = 0; i < array.length; i++) {
        for (let j = 0; j < array.length; j++) {
            if (i != j) {
                if (array[i] == array[j]) {
                    shortArray[index] += array[i]
                    console.log(array[i]);
                }
            }
        }
    }
    return shortArray;
}

console.log(removeDuplicate());

return this:

1
3
3
1
[ NaN ]

thanks!


问:
streaming a mp3 from a site/server
hi guys me and a few other djs want to be able to upload our mixes to a site that could then be streamed direct in to my app. at the moment i have the files stored on google drive. they will download and then i can play via a media player. but i want the user to be able to just stream the music direct from the site..

1) what site would you suggest for uploading of the music. i have a firebase account would this be an idea or would the data from the files i upload be expensive? im on the pay as you go account type.
****EDIT
So ive found out that firebase could be a n actual viable option for doing this

2) what would be the best way to implement the code so that it streams the music direct rather than downloading it first?

****EDIT
ive found some code while trawling the internet that could make this viable but i seam to be getting a null pointer error on the setDatasource

this is my code

i have this my onchild added

```<code> final String url = dataSnapshot.child("url").getValue(String.class);
  urlList.add(url);
</code>```

then in my onitemclick i use

```<code>mp3url = urlList.get(i);
 fetchAudioUrlFromFirebase();
</code>```

finally the method for streaming the mp3

```<code> private void fetchAudioUrlFromFirebase() {
    String mp3 = mp3url;
    final FirebaseStorage storage = FirebaseStorage.getInstance();
    storageRef = storage.getReferenceFromUrl(mp3);
    storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            try {
                // Download url of file
                final String url = uri.toString();
                mMediaplayer.setDataSource(url);
                // wait for media player to get prepare
                mMediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.start();
                    }
                });
                mMediaplayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("TAG", e.getMessage());
                }
            });

}
</code>```

this is my full logcat with the null pointer error

```<code>07-11 18:39:45.326 2565-2565/com.example.harrops.h20droidapp2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.harrops.h20droidapp2, PID: 2565
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(java.lang.String)' on a null object reference
                                                                                at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:198)
                                                                                at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:192)
                                                                                at com.google.android.gms.tasks.zze$1.run(Unknown Source)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
</code>```

答:
Q1: i have no idea about a site do this, sorry

Q2: you have to learn how to use MediaPlayer class in android and here is an example :

```<code>String link = "your link.mp3"; //usually it's ends with .mp3
Mediaplayer player = new MediaPlayer();
player.setDataSource(link);
player.prepare();//prepare to play
player.start();
</code>```

Its a quick and very simple example.
You can edit this as your need.

Title: streaming a mp3 from a site/server

Body:
hi guys me and a few other djs want to be able to upload our mixes to a site that could then be streamed direct in to my app. at the moment i have the files stored on google drive. they will download and then i can play via a media player. but i want the user to be able to just stream the music direct from the site..

1) what site would you suggest for uploading of the music. i have a firebase account would this be an idea or would the data from the files i upload be expensive? im on the pay as you go account type.
****EDIT
So ive found out that firebase could be a n actual viable option for doing this

2) what would be the best way to implement the code so that it streams the music direct rather than downloading it first?

****EDIT
ive found some code while trawling the internet that could make this viable but i seam to be getting a null pointer error on the setDatasource

this is my code

i have this my onchild added

 final String url = dataSnapshot.child("url").getValue(String.class);
  urlList.add(url);

then in my onitemclick i use

mp3url = urlList.get(i);
 fetchAudioUrlFromFirebase();

finally the method for streaming the mp3

 private void fetchAudioUrlFromFirebase() {
    String mp3 = mp3url;
    final FirebaseStorage storage = FirebaseStorage.getInstance();
    storageRef = storage.getReferenceFromUrl(mp3);
    storageRef.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
        @Override
        public void onSuccess(Uri uri) {
            try {
                // Download url of file
                final String url = uri.toString();
                mMediaplayer.setDataSource(url);
                // wait for media player to get prepare
                mMediaplayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                    @Override
                    public void onPrepared(MediaPlayer mp) {
                        mp.start();
                    }
                });
                mMediaplayer.prepareAsync();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    })
            .addOnFailureListener(new OnFailureListener() {
                @Override
                public void onFailure(@NonNull Exception e) {
                    Log.i("TAG", e.getMessage());
                }
            });

}

this is my full logcat with the null pointer error

07-11 18:39:45.326 2565-2565/com.example.harrops.h20droidapp2 E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            Process: com.example.harrops.h20droidapp2, PID: 2565
                                                                            java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.setDataSource(java.lang.String)' on a null object reference
                                                                                at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:198)
                                                                                at com.example.harrops.h20droidapp2.Mixes$3.onSuccess(Mixes.java:192)
                                                                                at com.google.android.gms.tasks.zze$1.run(Unknown Source)
                                                                                at android.os.Handler.handleCallback(Handler.java:751)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:154)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:6119)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)

Body:
Q1: i have no idea about a site do this, sorry

Q2: you have to learn how to use MediaPlayer class in android and here is an example :

String link = "your link.mp3"; //usually it's ends with .mp3
Mediaplayer player = new MediaPlayer();
player.setDataSource(link);
player.prepare();//prepare to play
player.start();

Its a quick and very simple example.
You can edit this as your need.


问:
Making a char function parameter const?
Consider this function declaration:

```<code>int IndexOf(const char *, char);
</code>```

where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const? I always try to use const on pointer parameters but when something is called by value, I normally leave the const away.

What are your thoughts?

答: I don't think it is necessary, as the char's value will be copied and any change to it won't be reflected outside of its scope.</p>

Title: Making a char function parameter const?

Body:
Consider this function declaration:

int IndexOf(const char *, char);

where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const? I always try to use const on pointer parameters but when something is called by value, I normally leave the const away.

What are your thoughts?


问:
TypeScript: can't disable type definitions for one special library

TypeScript Version:  2.4.1

For example I want to consume a library from npm called awesome-lib. This library already ships with a TypeScript type definition but this one is outdated and buggy. The author of the library doesn't update this one.

I've tried to disable that type definition completely in my own declarations.d.ts file in my project:

```<code>declare module 'awesome-lib';
</code>```

Unfortunately TypeScript reads first the type definition in the library and throws some errors. So it is not possible for me to disable / hide this library for my project.

Does anyone know how to disable type checking for one special library?

答: It may not be a real solution, but if the library is abandoned and broken, you could fork that library, modify its typings and use that in your project.</p>

Body:
TypeScript Version:  2.4.1

For example I want to consume a library from npm called awesome-lib. This library already ships with a TypeScript type definition but this one is outdated and buggy. The author of the library doesn't update this one.

I've tried to disable that type definition completely in my own declarations.d.ts file in my project:

declare module 'awesome-lib';

Unfortunately TypeScript reads first the type definition in the library and throws some errors. So it is not possible for me to disable / hide this library for my project.

Does anyone know how to disable type checking for one special library?


问:
"source" attribute of the package resource in chef
I am a beginner with the chef and slowly diving deep into it. I have a doubt regarding the "source" attribute of the resource "Package". The documentation says the "source" attribute uses local file system stored files and not HTTP or FTP. I have a 'TOMCAT tar' file and 'Java RPM' package to be installed on nodes.

Just like how the resource "cookbook_file" has files saved in "file" Directory in the cookbooks directory:
tree structure of apache cookbook

on which local file system does the "source" attribute of the resource "package" take files from? Does it grab files from the same 'files' directory? or in any other folders? I have written a simple cookbook assuming that the "source" attribute would take files from the "file" dir by default. but that is not working out:

package 'Installing JAVA' do
  source 'jdk-8u131-linux-x64'
  action :install
end

package 'Installing tomcat version 9' do
    source 'apache-tomcat-9.0.0.M22.tar'
    action :install
end

Kindly help me out!

答:
You are missing a lot here. The package resource is used to declare packages you want to install and you don't have to tell chef how or where to get the package you declared to be installed. Chef will use your local system repo using your distro package manager to do this, but you don't need to tell chef this. Also you wouldn't need the tomcat and java file in the file directory in that case. it will figure it out it self.

As i see above you want to install apache-tomcat-9.0.0.M22.tar.gz and jdk-8u131-linux-x64.rpm. I see the files are in file DIR which is OK. In this case you will need another chef reosurce. See below on how you could achieve this

1) Use the cookbook_file resource to transfer files from a sub-directory of COOKBOOK_NAME/files/ to a specified path located on the remote host that is running your chef-client.

```<code>cookbook_file '/opt/apache-tomcat-9.0.0.M22.tar.gz' do
  source 'apache-tomcat-9.0.0.M22.tar.gz'
  owner 'tomcat_user'
  group 'tomcat_user'
  mode '0755'
  action :create
end

cookbook_file '/opt/jdk-8u131-linux-x64.rpm' do
  source 'jdk-8u131-linux-x64.rpm'
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end
</code>```

2) Now unpack the  tomcat file using execute resources

```<code>execute 'extract tomcat' do
  command "tar xf /opt/apache-tomcat-9.0.0.M22.tar.gz -C /opt --strip-components=1"

end
</code>```

3) Now install the java rpm package as follow

```<code>rpm_package 'jdk-8u131-linux-x64.rpm'
</code>```

https://docs.chef.io/resource_file.html

https://docs.chef.io/resource_cookbook_file.html

https://docs.chef.io/resource_package.html

https://docs.chef.io/resource_rpm_package.html

https://docs.chef.io/resource_execute.html

Body:
You are missing a lot here. The package resource is used to declare packages you want to install and you don't have to tell chef how or where to get the package you declared to be installed. Chef will use your local system repo using your distro package manager to do this, but you don't need to tell chef this. Also you wouldn't need the tomcat and java file in the file directory in that case. it will figure it out it self.

As i see above you want to install apache-tomcat-9.0.0.M22.tar.gz and jdk-8u131-linux-x64.rpm. I see the files are in file DIR which is OK. In this case you will need another chef reosurce. See below on how you could achieve this

1) Use the cookbook_file resource to transfer files from a sub-directory of COOKBOOK_NAME/files/ to a specified path located on the remote host that is running your chef-client.

cookbook_file '/opt/apache-tomcat-9.0.0.M22.tar.gz' do
  source 'apache-tomcat-9.0.0.M22.tar.gz'
  owner 'tomcat_user'
  group 'tomcat_user'
  mode '0755'
  action :create
end

cookbook_file '/opt/jdk-8u131-linux-x64.rpm' do
  source 'jdk-8u131-linux-x64.rpm'
  owner 'root'
  group 'root'
  mode '0755'
  action :create
end

2) Now unpack the  tomcat file using execute resources

execute 'extract tomcat' do
  command "tar xf /opt/apache-tomcat-9.0.0.M22.tar.gz -C /opt --strip-components=1"

end

3) Now install the java rpm package as follow

rpm_package 'jdk-8u131-linux-x64.rpm'

https://docs.chef.io/resource_file.html

https://docs.chef.io/resource_cookbook_file.html

https://docs.chef.io/resource_package.html

https://docs.chef.io/resource_rpm_package.html

https://docs.chef.io/resource_execute.html


问:
Watch Connectivity transfer messages
Tell me, is it possible in the Watch Connectivity framework to transfer the following types of objects from the iOS application to WatchOS via the session.sendMessage method? If this is possible, then how?

Types of objects to send:

MyCustomClass

[MyCustomClass]

Result < MyCustomClass > (Realm)

Thank you for the answers!

答:
You have two options: (1) Pass the data using the PropertyList method as described by bdash or, (2) by passing the data in the sendMessage(_:replyHandler:errorHandler:) method by building the message variable as a dictionary of type [String:Any] and then handling the response in the Watch Extension's didReceiveMessage method.

For an example of this approach, view here: https://github.com/markfilter/iOS_WatchConnectivity_Tutorial

Title: Watch Connectivity transfer messages


问:
how to delete from mysql multiple rows depending on other rows in another table
I have a table Called phones contains all members phone numbers each member has unique id and there is another table called posts the posts table has many rows each post has its member id and another cells

I need to collect all members IDs from the posts table depending on the branches cell and delete from phones table where the members ids collected from the posts table

I tried this but it give me error message that mysql server lost the connection

```<code>delete from `phones` where `mid` in(select `uid` from `posts` where `branches` = 'contact');
</code>```

Note: I'm using mysql workbench with my local server

UPDATED

this query also worked after I setup the Preferences below

Go to Edit -> Preferences -> SQL Editor and increase the parameter: DBMS connection read time out (in seconds). For instance: 86400.

Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.

Thanks to @scaisEdge

答:
your query seems correct  .. anyway you can try with a inner join

```<code>delete  `phones`.*
from `phones`
inner join `posts`  on `phones`.`mid`  = `posts`.`uid`
        and `posts`.`branches` = 'contact'
</code>```

the inner join don't use a IN clause so you can bypass the involved  limitation

if the error persist  try increment the read time out

Go to Edit -> Preferences -> SQL Editor and icrease the parameter: DBMS connection read time out (in seconds). For instance: 86400.

Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.

Body:
I have a table Called phones contains all members phone numbers each member has unique id and there is another table called posts the posts table has many rows each post has its member id and another cells

I need to collect all members IDs from the posts table depending on the branches cell and delete from phones table where the members ids collected from the posts table

I tried this but it give me error message that mysql server lost the connection

delete from `phones` where `mid` in(select `uid` from `posts` where `branches` = 'contact');

Note: I'm using mysql workbench with my local server

UPDATED

this query also worked after I setup the Preferences below

Go to Edit -> Preferences -> SQL Editor and increase the parameter: DBMS connection read time out (in seconds). For instance: 86400.

Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.

Thanks to @scaisEdge

Body:
your query seems correct  .. anyway you can try with a inner join

delete  `phones`.*
from `phones`
inner join `posts`  on `phones`.`mid`  = `posts`.`uid`
        and `posts`.`branches` = 'contact'

the inner join don't use a IN clause so you can bypass the involved  limitation

if the error persist  try increment the read time out

Go to Edit -> Preferences -> SQL Editor and icrease the parameter: DBMS connection read time out (in seconds). For instance: 86400.

Close and reopen MySQL Workbench. Kill your previously query that probably is running and run the query again.