Q:

serialize the dynamically generated HTML input elements outside the form using jQuery

We are doing a proof of concept for an application where in the HTML elements are generated from the fields configured by the user.
The sample configuration is as follows;
/// Customer SAM
$response = array(
    array (
        NAME => CUSTOMER,
        TYPE => SAM,
        ENABLEDBUTTONS => SEARCHANDADD,
        TABLENAME => "OCRD",
        FIELDS => array (
            array(
                NAME => "lblCustNr",
                TYPE => LABEL,
                WIDTH => "100px",
                VALUE => "Customer Nr.:"
            ),
            array(
                NAME => "customernr",
                TYPE => TEXT,
                WIDTH => "100px",
                COLUMNNAME => "cardcode",
                VALUE => ""
            ),
            array(
                NAME => "lblCustName",
                TYPE => LABEL,
                WIDTH => "100px",
                VALUE => "Customer Name:"
            ),
            array(
                NAME => "customername",
                TYPE => TEXTAREA,
                COLUMNNAME => "cardname",
                ROWS => "5",
                COLUMNS => "50",
                VALUE => ""
            ),
            array (
                NAME => ADDRESS,
                TYPE => SAM,
                ENABLEDBUTTONS => SEARCH,
                TABLENAME => "CRD1",
                FIELDS => array(
                    array(
                        NAME => "lblStreet",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "Street:"
                    ),
                    array(
                        NAME => "street",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "Street",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblStreetNo",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "Street No:"
                    ),
                    array(
                        NAME => "streetNo",
                        TYPE => TEXT,
                        WIDTH => "30px",
                        COLUMNNAME => "StreetNo",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblCity",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "City:"
                    ),
                    array(
                        NAME => "city",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "City",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblZipcode",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "ZipCode:"
                    ),
                    array(
                        NAME => "zipcode",
                        TYPE => TEXT,
                        WIDTH => "50px",
                        COLUMNNAME => "ZipCode",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblState",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "State:"
                    ),
                    array(
                        NAME => "state",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "State",
                        VALUE => ""
                    ),
                    array(
                        NAME => "lblCountry",
                        TYPE => LABEL,
                        WIDTH => "100px",
                        VALUE => "Country:"
                    ),
                    array(
                        NAME => "country",
                        TYPE => TEXT,
                        WIDTH => "100px",
                        COLUMNNAME => "Country",
                        VALUE => ""
                    )
                )
            )
        ),
        SEARCHQUERY => "
            SELECT cardcode, cardname
            FROM [{DATABASENAME}].dbo.OCRD
            [{WHERECLAUSE}]
        "
    )
);

By using a recursive method, the HTML elements are generated as follows;
<form method="POST" id="CustomerSAM"></form>

Customer Nr.:

<input name="customernr" id="customernr" form_id="CustomerSAM" type="text" style="width:100px" value=""
/>

Customer Name:

<textarea name="customername" form_id="CustomerSAM" rows="5" cols="50"></textarea>
<form method="POST" id="AddressSAM"></form>

Street:

<input name="street" id="street" form_id="AddressSAM" type="text" style="width:100px" value="" />

Street No:

<input name="streetNo" id="streetNo" form_id="AddressSAM" type="text" style="width:30px" value="" />

City:

<input name="city" id="city" form_id="AddressSAM" type="text" style="width:100px" value="" />

ZipCode:

<input name="zipcode" id="zipcode" form_id="AddressSAM" type="text" style="width:50px" value="" />

State:

<input name="state" id="state" form_id="AddressSAM" type="text" style="width:100px" value="" />

Country:

<input name="country" id="country" form_id="AddressSAM" type="text" style="width:100px" value="" />

    <input name="btnSearch" form_id="AddressSAM" class="button" type="submit" value="Search" tag="AddressSAM" onClick="return searchInSAM($(this));"
    /> |
    <input type="button" form_id="AddressSAM" class="button" value="Clear" onClick="return clearForm($(this));" />

    <input name="btnSearch" form_id="CustomerSAM" class="button" type="submit" value="Search" tag="CustomerSAM" onClick="return searchInSAM($(this));"
    /> |
    <input name="btnAdd" form_id="CustomerSAM" class="button" type="submit" value="Add" tag="CustomerSAM" /> |
    <input type="button" form_id="CustomerSAM" class="button" value="Clear" onClick="return clearForm($(this));" />

This approach is followed as the dynamic form generation for sub-modules were resulting in inappropriate form generation (nested forms with no form tag). HTML5 standard is used and the form_id attribute for each input and submit element is set.
We have a JavaScript function which takes the input from these elements and and searches for the data depending on the provided search keys. The method is as follows;
// search the values depending on the provided input.
            // find the form element from the accessing element.
            function searchInSAM(elem)
            {
                var tagAttr = $(elem).attr('tag');

                // will only hold the id of the form. So will have to preceed with # to access the element.
                var formElementId = $(elem).attr('form_id');
                var formElement = $('#'+formElementId);

                var divElement = formElement;
                while(true)
                {
                    divElement = getParent(divElement);
                    if(divElement.is('div'))
                    {
                        break;
                    }
                }

                var inputValues = formElement.serializeArray();
                var serverAddr = "<?php echo CLIENTHANDLER; ?>";
                var requestParams = {
                    "<?php echo METHODNAME; ?>": "<?php echo SEARCH_METHOD; ?>",
                    "<?php echo SAMNAME; ?>": tagAttr,
                    "<?php echo INPUTVALUES; ?>": JSON.stringify(inputValues),
                    "<?php echo DATABASESERVER; ?>": "SWEPROEBS4",
                    "<?php echo DATABASENAME; ?>": "SBOswedex",
                    "<?php echo USERID; ?>": 1
                };
                console.log(inputValues);
                // transfer the request to the server
                request = ajaxRequest(serverAddr,
                    "<?php echo POSTMETHOD; ?>",
                    "<?php echo MULTIPARTFORMTYPE; ?>",
                    "<?php echo JSONTYPE; ?>",
                    requestParams);

                // Callback handler that will be called on success
                request.done(function (response, textStatus, jqXHR){
                    //console.log(response);
                    $(divElement).html(response);
                });

                // Callback handler that will be called on failure
                request.fail(function (jqXHR, textStatus, errorThrown){
                    // Log the error to the element that is expecting the response
                    $(divElement).html(
                        "The following error occurred: "+
                        textStatus + "
" + errorThrown
                    );
                });

                return false;
            }

The search is always empty as the inputValues array is always empty.
The line var inputValues = formElement.serializeArray(); is always empty. I read that the serialize() and serializeArray() only serializes the elements inside the provided element.
Can you please give me some hints or solution to serialize all the elements with the provided form_id? i will have a div element that encloses the provided HTML output and this div can contain any type of elements; input, select-option, text area, radio buttons, check boxes etc.
It would be of great help if you can provide me a generic suggestion / solution which caters to all possible elements associated with the form_id.
Thanks in advance.

A:

The line var inputValues = formElement.serializeArray(); is always
  empty.

your generated HTML is the problem. If you inspect it carefully you can see that the form tag is empty and all the elements fall out of it.
Taken from your HTML
<form method="POST" id="CustomerSAM"></form>

...
<form method="POST" id="AddressSAM"></form>

But you said you maintain the form_id on all the elements that belong to one form, which is fine.
And then coming to your script,
var formElement = $('#'+formElementId);

this gives you the form tag, (Remember that the form tag is empty). And then you try to do this .
var inputValues = formElement.serializeArray();

Which will obviously be empty.
Solution: You can collect all the input elements and append it to a new form and then serialize it. like below
 var newForm = $('<form></form>')
 $.each($('[form_id="CustomerSAM"]'),function(i,v){
      $(newForm).append($(this));
 });
 var serializedData = $(newForm ).serializeArray();

Let me know if this helps.


Q:

Ошибка при установке pycurl

C:\Python27>pip install pycurl
Downloading/unpacking pycurl
 Running setup.py (path:c:\users\asus\appdata\local\temp\pip_build_asus\pycurl\setup.py) egg_info for package pycurl
  Please specify --curl-dir=/path/to/built/libcurl
  Complete output from command python setup.py egg_info:
  Please specify --curl-dir=/path/to/built/libcurl

----------------------------------------
Cleaning up...
Command python setup.py egg_info failed with error code 10 in c:\users\asus\appdata\local\temp\pip_build_asus\pycurl
Storing debug log for failure in C:\Users\asus\pip\pip.log

A:

Обновил ответ в вопросе Как найти и установить модуль pycurl в Python?. Этот вопрос закрываю, т.к. это продолжение предыдущего вопроса.


Q:

Closed-ness of $R(I-K)$ in the Fredholm alternative

Here $R$ and $N$ denote the range and the null space respectively. I need someone to tell me why letting $k_j\to\infty$ yields a contradiction, and why we can find $u_k\in[N(I-K)]^\perp$ that solves $u_k-K(u_k)=v_k$. Thank you all.

A:

For the first question, note that $(u_{k_j},u)\to(u,u)$ since the inner product $(\cdot,u)$ is continuous. By uniqueness of limits, we obtain $(u,u)=0$. Hence, $u$ is the zero vector in $H$. Given that $||u_{k_j}||=1$ for each $j$, $\{u_{k_j}\}_{j=1}^\infty$ cannot converge to the zero vector. This is a contradiction.
For the second question, we conclude from (i) that $H=N(I-K)\oplus[N(I-K)]^\perp$. The result is now obvious.


Q:

working with lists of models using the pipe syntax

I often like to fit and examine multiple models that relate two variables in an R dataframe.
I can do that using syntax like this:
require(tidyverse)
require(broom)
models <- list(hp ~ exp(cyl), hp ~ cyl)
map_df(models, ~tidy(lm(data=mtcars, formula=.x)))

But I'm used to the pipe syntax and was hoping to be able to something like this:
mtcars %>% map_df(models, ~tidy(lm(data=., formula=.x)))

That makes it clear that I'm "starting" with mtcars and then doing stuff to it to generate my output.  But that syntax doesn't work, giving an error Error: Index 1 must have length 1.
Is there a way to write my purrr:map() function in a way that I can pipe mtcars into it to get the same output as the working code above?  I.e.
mtcars %>% <<<something>>>

A:

tl/dr: mtcars %>% {map_df(models, function(.x) tidy(lm(data=., formula=.x)))}
Or mtcars %>% map_df(models, ~tidy(lm(..1,..2)), ..2 = .)

There are 2 problems with the solution you've tried.
The first is that you need to use curly braces if you want to place the dot in an unusual place.
library(magrittr)
1 %>% divide_by(2)   # 0.5     -> this works
1 %>% divide_by(2,.) # 2       -> this works as well
1 %>% divide_by(2,mean(.,3))   #  this doesn't
1 %>% divide_by(.,2,mean(.,3)) #  as it's equivalent to this one
1 %>% {divide_by(2,mean(.,3))} #  but this one works as it forces all dots to be explicit.

The second is that you can't use the dot with the ~ formulation in the way you intended, try map(c(1,2), ~ 3+.) and map(c(1,2), ~ 3+.x) (or even map(c(1,2), ~ 3+..1)) and you'll see you get the same result. By the time you use the dot in a ~ formula it's not linked to the pipe function anymore.
To make sure the dot is interpreted as mtcars you need to use the good old function(x) ... definition.
This works:
mtcars %>% {map_df(models, function(.x) tidy(lm(data=., formula=.x)))}

Finally, as a bonus, here's what I came up with, trying to find a solution without curly braces :
mtcars %>% map(models,lm,.) %>% map_df(tidy)
mtcars %>% map_df(models, ~tidy(lm(..1,..2)), ..2 = .)


Q:

Elasticsearch breaks on hyphens, dashes, spaces

I currently have my elasticsearch mappings set to analyzed by default, and I would like to keep the settings this way. However I've ran into situations where I try to query for ABC-123 or ABC 123 or ABC 123-1 and it breaks the elasticsearch query.
I'm working with an angularjs typeahead module using: https://github.com/jeff-collins/ment.io
The issue is when I start my query using the typeahead module whenever I hit a space or hyphen/dash it breaks the typeahead dropdown.
Here is the wildcard I have setup
router.get('/tagging', function(req, res) {
  switch (req.query.type) {
    case 'asset_list':
      client.search({
        index: 'core',
        type: 'assets',
        body: {
          query : {
              wildcard: {
                name: '*' + req.query.name + '*'
            }
          },
          highlight: {
              fields : {
                  display_name : {}
              }
          }
        }
      }).then(results => res.send(results), err => res.send(err));
      break;
      .....
      .....

A:

Looks like logstash handles this.
https://www.elastic.co/blog/logstash-1-3-1-released


Q:

How to notify application user whenever i add something to remote database?

I have developed my first android application.
What that application does: I update mysql database with new results on the website and the android application fetches the same data from mysql. I am using JSON.
What i want it to do: I want it to notify user that the results have been updated. It can bee a timely notification or the normal one. It does not matter. I just want the user to know about it as soon as i update database.
Code for your reference:
1) Java code that displays results inside the application.
  package in.thespl.spl.notifications;

  import java.util.ArrayList;
  import java.util.HashMap;
  import java.util.List;

  import org.apache.http.NameValuePair;
  import org.json.JSONArray;
  import org.json.JSONException;
  import org.json.JSONObject;

  import android.app.ListActivity;
  import android.app.ProgressDialog;
  import android.content.Intent;
  import android.os.AsyncTask;
  import android.os.Bundle;
  import android.util.Log;
  import android.view.View;
  import android.widget.AdapterView;
  import android.widget.AdapterView.OnItemClickListener;
  import android.widget.ListAdapter;
  import android.widget.ListView;
  import android.widget.SimpleAdapter;
  import android.widget.TextView;

  public class AllResultsActivity extends ListActivity {

// Progress Dialog
private ProgressDialog pDialog;

// Creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList<HashMap<String, String>> productsList;

// url to get all products list
private static String url_all_products = "http://mydomain.in/fetchresult.php";

// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "result";
private static final String TAG_PID = "rid";
private static final String TAG_NAME = "rname";
private static final String TAG_INFO = "rinfo";

// products JSONArray
JSONArray products = null;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.all_products);

    // Hashmap for ListView
    productsList = new ArrayList<HashMap<String, String>>();

    // Loading products in Background Thread
    new LoadAllProducts().execute();

    // Get listview
    ListView lv = getListView();

    // on seleting single product
    // launching Edit Product Screen
    lv.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {
            // getting values from selected ListItem
            String pid = ((TextView) view.findViewById(R.id.rid)).getText()
                    .toString();

            // Starting new intent
            Intent in = new Intent(getApplicationContext(),
                    AllResultsActivity.class);
            // sending pid to next activity
            in.putExtra(TAG_PID, pid);

            // starting new activity and expecting some response back
            startActivityForResult(in, 100);
        }
    });

}

// Response from Edit Product Activity
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    // if result code 100
    if (resultCode == 100) {
        // if result code 100 is received
        // means user edited/deleted product
        // reload this screen again
        Intent intent = getIntent();
        finish();
        startActivity(intent);
    }

}

/**
 * Background Async Task to Load all product by making HTTP Request
 * */
class LoadAllProducts extends AsyncTask<String, String, String> {

    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(AllResultsActivity.this);
        pDialog.setMessage("Loading results. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting All products from url
     * */
    protected String doInBackground(String... args) {
        // Building Parameters
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        // getting JSON string from URL
        JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);

        // Check your log cat for JSON reponse
        Log.d("All Products: ", json.toString());

        try {
            // Checking for SUCCESS TAG
            int success = json.getInt(TAG_SUCCESS);

            if (success == 1) {
                // products found
                // Getting Array of Products
                products = json.getJSONArray(TAG_PRODUCTS);

                // looping through All Products
                for (int i = 0; i < products.length(); i++) {
                    JSONObject c = products.getJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_PID);
                    String name = c.getString(TAG_NAME);
                    String info = c.getString(TAG_INFO);
                    // creating new HashMap
                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_PID, id);
                    map.put(TAG_NAME, name);
                    map.put(TAG_INFO, info);

                    // adding HashList to ArrayList
                    productsList.add(map);
                }
            } else {
                // no products found
                // Launch Add New product Activity
               // Intent i = new Intent(getApplicationContext(),
                //       AllResultsActivity.class);
                // Closing all previous activities
                //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
               // startActivity(i);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
        // updating UI from Background Thread
        runOnUiThread(new Runnable() {
            public void run() {
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        AllResultsActivity.this, productsList,
                        R.layout.list_item, new String[] { TAG_PID,
                                TAG_NAME, TAG_INFO },
                        new int[] { R.id.rid, R.id.rname, R.id.rinfo});
                // updating listview
                setListAdapter(adapter);
            }
         });

       }

   }
  }

Any idea how to add a notification feature in this?

A:

You have multiple ways to do that.
First way is to poll the server to ask for update.
This solution isn't really efficient and lot of params are had to choose:
Time to update-> will affect battery and reactivity.
Second way is to use Google Cloud Messaging. It provides a solution to push data from server to user. It's really simple to implement. (took me some hours).
Android documentation.
http://developer.android.com/guide/google/gcm/index.html
This second way optimizes battery and you could receive push even if your app is off.
Choose the way it's better for your needs.
Hope it helps you.


Q:

nested STL structure

I am wondering about the performance of nested STL structure related to compile and run time. So if want to implement something a nested structure e.g. that way
vector<vector<map<int, vector<> > > >

How could the access to each container effect on the whole execution time?
Thanks for any help. Giving some specific links considered this issue are very appreciated as well.
My best.

A:

How could the access to each container effects on the whole execution time?

It's not much to say, even less to reference - except for the STL. std::vector provides O(1) access performance to the elements (the random access), std::map provides O(log(n)) access performance to the elements.
IOW:
vector<vector<map<int, vector<int> > > > x;

int i,j,k,l;
x[i]   // goes via std::vector, O(1)
 [j]   // goes via std::vector, O(1)
 [k]   // goes via std::map, O(log(n))
 [l];  // goes via std::vector, O(1)

Most of the accesses would be inlined/optimized out by the compiler.
To help compiler a bit one can cache in a variable some often accessed containers, for example:
typedef map<int, vector<int> > map_type;
typedef vector<vector< map_type > > bigvec_type;
bigvec_type x;

int i,j,k,l;

map_type &m = x[i][j];
for ( /* some loop over k and l */ ) {
   m[k][l];
}

In the particular case there are not much performance concerns.
My minor nitpick would be is when code uses several such large structures (e.g. moving data from one bigvec_type container to another). Though assymptotically performance wouldn't change, the amount of code compiler need to generate would be quite large since it wouldn't be able put all required indexes and pointers into registers. To avoid that, one generally tries to split logically the structure into several layers (akin to my second code example) and provide methods which work with 1 or 2 level of containers only.


Q:

Magical Record - adding values to entity in loop

I have problem with my Magical Record code:
    Collection *collection = [Collection MR_createEntity];
    [collection setValue:name forKey:@"name"];
    [collection setValue:date forKey:@"date"];
    [collection setValue:amount forKey:@"amount"];

    for (Person *person in self.selectedPeople) {
        Payment *payment = [Payment MR_createEntity];
        [payment setValue:person forKey:@"person"];
        [payment setValue:collection forKey:@"collection"];
    }

   [[NSManagedObjectContext MR_defaultContext]  MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
        if (!success)
            NSLog(@"Error: %@", [error localizedDescription]);
        else
            NSLog(@"Item %@ added to database", collection.name);
    }];

For every person that user selected i want to create a payment in database. I'm doing that in the loop. My problem is only the last payment has collection.
For example when I have 3 people it looks like that:
Payment 1 - person:John, collection: nil
Payment 2 - person:Bill, collection: nil
Payment 3 - person:Mark, collection: Paper

Anyone can tell me why is that happening?

A:

My guess is that it's the relationship from collection to payment. You are trying to use a many-to-one from collection to payment, but you might only have a one-to-one setup in your Core Data model.
I'm not sure that a many-to-one relationship is a good idea from collection to payment. You might want to create a unique entity for each collection, but that all depends on your model.
for (Person *person in self.selectedPeople) {
    // Create a new collection entity for each payment.
    Collection *collection = [Collection MR_createEntity];
    [collection setValue:name forKey:@"name"];
    [collection setValue:date forKey:@"date"];
    [collection setValue:amount forKey:@"amount"];

    Payment *payment = [Payment MR_createEntity];
    [payment setValue:person forKey:@"person"];
    [payment setValue:collection forKey:@"collection"];
}

[[NSManagedObjectContext MR_defaultContext]  MR_saveToPersistentStoreWithCompletion:^(BOOL success, NSError *error) {
    if (!success)
        NSLog(@"Error: %@", [error localizedDescription]);
    else
        NSLog(@"Item %@ added to database", collection.name);
}];


Q:

An alternative to LevelDB that allows you to read a subsection of the data record

I like the look of LevelDB as a database for my application but there is one issue.
I would like to store data into the database but when I read the data sometimes I only need a particular section of the data. As well as leveldb_get(db, readOptions, key, keySize, &size, &err) I'd like something like leveldb_get_subsection(db, readOptions, key, keySize, offset, size, &err) but that does not exist.
I could, of-course, index the data into smaller sections but I was wondering if there was a good alternative to LevelDB that allows me to read a subsection of a record/value which makes much more sense. Are there any recommendations?
I require atomic operations which are synchronised safely to the disk, as data integrity is important. Also I need a C interface.
Thanks.

A:

The solution was to write my own key-value database code. What I've done so far is here: https://github.com/MatthewLM/cbitcoin/tree/master/dependencies/storage


Q:

boost asio sockets keeps popping under /proc/pid/fd

I'm sure sockets get closed everywhere in my application and i keep getting this newly created fd/socket files under my /proc/pid/fd/ is this normal. I'm sure it is not.
connection.cpp
 connection::start() {
    socket_.set_option(boost::asio::ip::tcp::no_delay(true));
    boost::asio::socket_base::non_blocking_io command(true);
    socket_.io_control(command);

    read_header();

    longevity_timer_.start();

    // log_->debugStream() << "listening";
  }

void connection::stop() {
    cancel_timeout();

    boost::system::error_code ignored_ec;

    // initiate graceful connection closure & stop all asynchronous ops
    try {
      socket_.cancel();
      socket_.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ignored_ec);
      if (ignored_ec)
      {
          log_->errorStream() << "shutdown: bad socket; couldn't close cleanly" << ignored_ec.message();
      }
      socket_.close(ignored_ec);
      if (ignored_ec)
      {
          log_->errorStream() << "close: bad socket; couldn't close cleanly" << ignored_ec.message();
      }
    } catch (std::exception& e) {
      log_->errorStream() << "bad socket; couldn't close cleanly";
    }
}

lsof -p pid
dakwakd 20733 root   18u  IPv4 647843      0t0      TCP localhost:35654->localhost:amqp (ESTABLISHED)
dakwakd 20733 root   19u  IPv4 647969      0t0      TCP localhost:35695->localhost:amqp (ESTABLISHED)
dakwakd 20733 root   20u  IPv4 647599      0t0      TCP localhost:35543->localhost:amqp (ESTABLISHED)
dakwakd 20733 root   21u  IPv4 647634      0t0      TCP localhost:35567->localhost:amqp (ESTABLISHED)

Now each time I get a new connection i made sure to stop it when im done with it.
but fd/socket files still grow rapidly under /proc/pid/fd/
How can i just make sure im not doing anything wrong

A:

Try setting a breakpoint at the top of connection::start.  Then when it gets hit, go through the call stack in the debugger to see where and how the method gets called to determine if it is as expected.
In the stop method, try moving cancel_timeout() inside the try/catch block since the code won't catch or log an error if it throws right now.
Try adding a debug call to log_->errorStream() at the top of both start and stop.  Print out the address of the _socket object - which I'm assuming is unique and created elsewhere for each new connection.  Make sure that for each debug print statement in the start method, a corresponding debug print statement is seen in the stop method with the correct address of the _socket object.  I suspect that they will not match and that your stop method is not getting called properly for some reason.  If this is true, then you will then need to investigate and debug why your stop method is not getting called to close the connection.


Q:

Android Gridview error , displaying last item incorrectly

i have a grid view, this is how i implement it
<GridView
    android:horizontalSpacing="8dp"
    android:verticalSpacing="8dp"
    android:id="@+id/homeGrid"
    android:layout_width="wrap_content"
    android:layout_height="0dp"
    android:layout_marginLeft="15dp"
    android:layout_marginRight="15dp"
    android:layout_marginTop="15dp"
    android:layout_weight="3"
    android:numColumns="auto_fit" />

which aim to display 7 items using custom adapter, and this is how i implement the adapter
private Context mContext;
private final String[] item;
private final int[] imageId;

public GridAdapter(Context c, String[] item, int[] imageId) {
    mContext = c;
    this.item = item;
    this.imageId = imageId;
}

@Override
public int getCount() {
    return item.length;
}

@Override
public Object getItem(int position) {
    return item[position];
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    View grid;

    LayoutInflater inflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        grid = inflater.inflate(R.layout.home_grid_layout, null);
        TextView textView = (TextView) grid.findViewById(R.id.grid_text);
        ImageView imageView = (ImageView) grid.findViewById(R.id.grid_image);
        textView.setText(item[position]);
        imageView.setImageResource(imageId[position]);
    } else {
        grid = convertView;
    }
    return grid;

}

}
and then i initiate it in my activity like this
GridAdapter adapter = new GridAdapter(HomePage.this, title, imageId);
        GridView grid = (GridView) findViewById(R.id.homeGrid);
the problem is that the app displaying the last position which is position 6 as position 0, strangly i implement onitemclicklistener to my gridview and i got the correct position when i click the last position.
where is my mistake ?

A:

Try this code.
@Override
public View getView(int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) mContext
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.home_grid_layout, null);
    }

    TextView textView = (TextView) convertView.findViewById(R.id.grid_text);
    ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_image);

    textView.setText(item[position]);
    imageView.setImageResource(imageId[position]);

    return convertView;

}


Q:

AWS RDS instance error: Unable to find main route table - timed out

I'm receiving the following error when trying create a new RDS instance.

I'm new to AWS, what is this error referring to?

A:

This happens when there are issues on the AWS region where you are creating the instance, I was experiencing the exact same issue, then switched to another region an was able to create the instance with no issues.


Q:

In Org-Mode, is there a way to narrow the buffer to just the text under a heading?

For example, say I have a buffer that looks like this:
* Org-Mode

This is a document written in Org-Mode

** This is a subheading below that

Would it be possible to narrow the buffer to just "This is a document written in Org-Mode" and continue on then come back to the full buffer, excluding the subheading below.
(Edited to clarify regarding subheadings)

A:

org-narrow-to-subtree (C-x n s) will display only the current heading. It does however include the heading itself, not just the text. Maybe that is OK for you?
widen (C-x n w) will widen the view again.
See for example: https://stackoverflow.com/questions/17156595/in-emacs-org-mode-how-to-narrow-display-to-two-subtrees-in-two-separate-files

A:

Perhaps this does what you want?
(defun org-narrow-to-here ()
   (interactive)
   (org-narrow-to-subtree)
   (save-excursion
     (org-next-visible-heading 1)
     (narrow-to-region (point-min) (point))))

Edit: If you really really want to exclude the current heading, this more elaborate variant:
(defun org-narrow-to-here ()
  (interactive)
  (save-excursion
    (narrow-to-region
     (progn (unless (org-at-heading-p) (org-next-visible-heading -1))
            (forward-line)
            (point))
     (progn (org-next-visible-heading 1)
            (point)))))


Q:

Python virtual environment cannot find python modules

I have both Canopy and Anaconda installed. My default is Canopy, but when I launch screen I get Anaconda. That's useful for me most of the time, but this time I need to use Canopy in screen.
I think the solution is to create a virtual environment, and I did so like this:
cd /path/to/project
virtualenv my_project

Problem: the virtualenv cannot see my installed Python modules, like numpy.
Here's the rest of my process:
user@GPU5:~/path/to/my_project$ screen
user@GPU5:~/path/to/my_project$ source activate lstm_project
(lstm_project) user@GPU5:~/path/to/my_project$ python

Enthought Canopy Python 2.7.6 | 64-bit | (default, Sep 15 2014, 17:36:10)
[GCC 4.1.2 20080704 (Red Hat 4.1.2-54)] on linux2
Type "help", "copyright", "credits" or "license" for more information.

>>> import numpy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named numpy

Here is the output of sys.path:
>>> print sys.path

['', '/user/path/to/my_project',
'/opt/enthought/canopy-1.5.1/appdata/canopy-1.5.1.2730.rh5-x86_64/lib/python27.zip',
'/opt/enthought/canopy-1.5.1/appdata/canopy-1.5.1.2730.rh5-x86_64/lib/python2.7',
'/opt/enthought/canopy-1.5.1/appdata/canopy-1.5.1.2730.rh5-x86_64/lib/python2.7/plat-linux2',
'/opt/enthought/canopy-1.5.1/appdata/canopy-1.5.1.2730.rh5-x86_64/lib/python2.7/lib-tk',
'/opt/enthought/canopy-1.5.1/appdata/canopy-1.5.1.2730.rh5-x86_64/lib/python2.7/lib-old',
'/opt/enthought/canopy-1.5.1/appdata/canopy-1.5.1.2730.rh5-x86_64/lib/python2.7/lib-dynload',
'/user/path/to/my_project/lib/python2.7/site-packages']

How can I get my virtualenv to recognize the packages I have installed globally?

A:

virtualenv by default will ignore system packages. When you're creating the environment, do
$ virtualenv my_project --system-site-packages


Q:

How to configure SSL for subversion access in windows?

As the question describes, can anyone point to a good documentation or if possible give me the basic steps to configure a  windows subversion server (1.4.3) please?
I already have subversion, apache and svnserve running on the server. The existing users within the LAN are already on SSPI authentication. I need to get a few new, non-domain, non-NTLM users to access the existing repositories. I dont want to use the svn:// with passwd configuration as this transmits data and password in cleartext over the network. SSPI does not work for these users outside the LAN. So that goes out of the window as well.
I am looking to see if SSL access is feasible in our situation. Any help is greatly appreciated.

A:

Have you considered having your users tunnel via SSH?
http://svnbook.red-bean.com/en/1.4/svn.serverconfig.svnserve.html#svn.serverconfig.svnserve.sshauth


Q:

wordpress add featured image below post title

I try to display a featured image below the blog-post title.
actually my posts look like:
WP-header
post-title
date | author | comments
post content
tag | category

My goal is to get a full-sized-image (featured image) between post-title & date | author | comments
Actually I am using a Corpo Theme.
Any ideas?Best Regards

A:

You can fetch featured image using following code and paste it after post-title which should be <?php the_title() ?>
<?php
 if ( has_post_thumbnail()) {
   $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');
   echo '';
   the_post_thumbnail('thumbnail');
   echo '';
 }
 ?>

Since i haven't seen your full code so i can help you up-to this.
See Codex Tutorial


Q:

Python Converting ORF to jpg - LibRawFatalError: Input/output error

I am trying to convert a directory of photos from ORF to jpg using python. The image library I am using is

https://github.com/letmaik/rawpy

An error is occuring when I try to read an image from the path. The error is below
  with rawpy.imread(fullPath) as raw:
  File "/Library/Python/2.7/site-packages/rawpy/__init__.py", line 20, in imread
    d.open_file(pathOrFile)
  File "rawpy/_rawpy.pyx", line 266, in rawpy._rawpy.RawPy.open_file
  File "rawpy/_rawpy.pyx", line 668, in rawpy._rawpy.RawPy.handle_error
rawpy._rawpy.LibRawFatalError: Input/output error

imageConversion.py
path = '/Users/Account/Desktop/ORFImages'
for (dirpath, dirnames, filenames) in walk(path):
    for l in filenames:
         fullPath = str(join(dirpath,l))
         with rawpy.imread(fullPath) as raw: #ERROR OCCURS HERE
             rgb = raw.postprocess()
             imageio.imwrite('test.jpg', rgb)

There is most definitely an ORF image at the fullpath variable.
What am I doing wrong?

A:

This code works for me.
Please note that the path should be relative to the .py file you have.
import glob
import rawpy
import imageio

path = "ORFImages/*orf"
for infile in glob.glob(path):
    with rawpy.imread(infile) as raw:
        rgb = raw.postprocess()
        imageio.imwrite('test.jpg', rgb)


Q:

Log-Maximum-Likelihood depends on log base?

I am given the following PDF:
$$f_X(z) = \begin{cases} \frac{ak^a}{z^{a+1}}, & \text{for $z \ge k$} \\
0, & \text{for $z \lt k$} \end{cases}$$
For some parameters $k$ and $a$. I am then told to find the Maximum-Likelihood estimator for $a$ if we know $k$ and have $n$ independent observations.
The Likelihood function is $$L_z(a,k) = \prod_{i=1}^{n}\frac{ak^a}{z_i^{a+1}}$$ and then the Log-Likelihood function is $$l_z(a,k) = log(L_z(a,k)) = \sum_{i=1}^{n}log(\frac{ak^a}{z_i^{a+1}}) = n \cdot \Bigl( a \cdot log(k) + log(a) \Bigr)- (a+1) \sum_{i=1}^{n}log(z_i)$$
Now we take the derivative with respect to $a$ and set it equal to $0$:
$$n \cdot (log(k) + \frac{1}{a}) - \sum_{i=1}^{n}log(z_i) = 0$$
$$\iff \frac{1}{a} = \frac{1}{n}\sum_{i=1}^{n}[log(z_i)] - log(k)$$
$$\iff a = \Bigl(\frac{1}{n}\sum_{i=1}^{n}[log(z_i)] - log(k)\Bigr)^{-1}$$
However, this estimator depends on the base of the logarithm, which shouldn't be possible. Where did I go wrong?

A:

In your step where you differentiated with respect to $a$, you used $\frac{d}{da}(\log a) = \frac{1}{a}$; in doing this, you assumed a log base of $e$.
If you redo the calculations with a general log base $b$ (where $\log_b z =\frac{\log z}{\log b}$ and $\frac{d}{dz}(\log_b z)=\frac{1}{(\log b)z}$ and $\log$ is the log with base $e$), you will see you end up at the same result, because a $\frac{1}{\log b}$ factor cancels when setting the derivative to $0$.


Q:

C# Linq to Entities - Method for determining whether an underlying data source is readonly

Is there a better approach than trying to write and just catching the exception?
We have various versions of the same database and today I'm working against a readonly version, this is fine for 99% of my tasks but the application sometimes saves its state back to the DB and I'd like to be able to try this iff the underlying SQL Server instance is writable.

A:

Run a query against the server checking what permissions your user login has for that database. There is a built-in Transact-SQL function to do this named HAS_PERMS_BY_NAME (Link to MSDN).
Example query to check if you have INSERT permissions.
SELECT HAS_PERMS_BY_NAME('database', 'OBJECT', 'INSERT');

Also have a look at FN_BUILTIN_PERMISSIONS (Link to MSDN). This MSDN page has listings of the possible values that you can use in HAS_PERMS_BY_NAME.
HTH,


Q:

RuboCop Error - Define a global variable in Cucumber RUBY files

I need to define a global variable in my Cucumber env.rb file which can be accessed throughout the framework in all step methods. Currently i am defining as this in my env.rb file:
$global_var ||= false

And i need to access this var into the Before hook as well After hook and few step methods where i am re-initializing this. It is working perfectly as i want. But the problem is, rubocop doesn't like this and throwing error as "do not use global variable". How can i resolve this ???
FYI, I tried using singleton to define this var as accessor and not quite sure where i am missing.

A:

Change the config file for rubocop. use the link:
Example to Change
Look for the passage starting with When we look in the .rubocop_todo.yml file we see something like this:  and also Configure Rubocop to be your style guide
Link to List of Configuration Changes possible:
Link to List of Styles
change .rubocop.yml file:
Style To Change:
GlobalVars: Enabled: false
Example File : Example file - how it looks like
How to Configure Style: Style/Inheritance Guide


Q:

IValueConverter error for DataGridComboBoxColumn

So I have a DataGridComboBoxColumn ColCID whose value depends on another cell of the row ColSID (see below code). I tried to implement it with an IValueConverter but I get this error:

Cannot find governing FrameworkElement or FrameworkContentElement for target element. BindingExpression:(no path); DataItem=null; target element is 'DataGridComboBoxColumn' (HashCode=18018639); target property is 'ItemsSource' (type 'IEnumerable')

XAML:
<DataGridComboBoxColumn x:Name="ColSID" Header="Guild"
                        SelectedValueBinding="{Binding SID, Mode=TwoWay}"
                        SelectedValuePath="SID"
                        DisplayMemberPath="Name" />
<DataGridComboBoxColumn x:Name="ColCID" Header="Channel"
                        ItemsSource="{ Binding ElementName=ColSID, Converter={StaticResource ChannelConverter} }"
                        SelectedValueBinding="{Binding CID, Mode=TwoWay}"
                        SelectedValuePath="CID"
                        DisplayMemberPath="Name" />

Converter:
public class ChannelConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        Guild guild = SenderView.Guilds.Find(g => g.SID == value.ToString());
        if (guild != null) return guild.Channels;
        return null;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
...
public class Guild
{
    public class Channel
    {
        public string CID { get; set; }
        public string Name { get; set; }
    }
    public string SID { get; set; }
    public string Name { get; set; }
    public List<Channel> Channels { get; set; }
}

A:

Looks to me like for each row in your grid, you want the user to be able to select a Guild, and a Channel for the Guild. Each Guild has its own collection of Channel, so we're going to select from that collection. I'm going to bind the Channel and Guild objects, not just their IDs. We could do it the other way if you prefer, but I find it easier to let the ComboBox look up the object, instead of the rest of my code having to do it. The SID or CID is right there on the selected object when I want it.
Here's how you can do that. You can't conventionally bind anything to DataGridComboBoxColumn.ItemsSource in your XAML. Any solution involving that property is going to be a little it exotic at best, but it's entirely unnecessary: You can bind the ComboBox's ItemsSource via ElementStyle and EditingElementStyle. SelectedValuePath and SelectedValueBinding do work, but I didn't use them.
I wrote a quick stand-in for the parent viewmodel, which owns the collections of Guilds that the user can select from. Note that I also moved your Channel class out of Guild. The only reason I did that was so I could have a Channel property on the Guild class for the selected channel. If you'd rather keep Channel where you had it, simply rename Guild's Channel property to SelectedChannel or something like that, and alter the bindings in the XAML accordingly.
The "framework mentor" nonsense is because the columns aren't child controls in the visual tree. They're an instruction to the DataGrid to create a column header, and also a cell in each row. Those headers and cells, and so also their templated content, are in the visual tree. SelectedItemBinding isn't a binding on the column; it's a binding that the column creation code will set on the SelectedItem property of a ComboBox that it will eventually create in the cell content. But the ItemsSource property is just a property of the column itself. You could bind it with a binding proxy, and people do, but binding proxies are the coward's way out.
XAML
<DataGrid
    ItemsSource="{Binding Selections}"
    AutoGenerateColumns="False"
    Grid.Row="1"
    >
    <DataGrid.Resources>
        <Style TargetType="ComboBox" x:Key="GuildComboStyle">
            <Setter
                Property="ItemsSource"
                Value="{Binding DataContext.Guilds, RelativeSource={RelativeSource AncestorType=DataGrid}}"
                />
        </Style>
        <Style
            TargetType="ComboBox"
            x:Key="ChannelComboStyle"
            >
            <!-- Our DataContext here is a GuildSelection object, so we look at its Guild
            property for a collection of Channels to use.
            -->
            <Setter  Property="ItemsSource" Value="{Binding Guild.Channels}" />
            <!-- If there's no selected Guild, prompt the user to select one. -->
            <Style.Triggers>
                <DataTrigger Binding="{Binding Guild}" Value="{x:Null}">
                    <Setter Property="IsEnabled" Value="False" />
                    <Setter Property="IsEditable" Value="True" />
                    <Setter Property="Text" Value="Please select a Guild" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </DataGrid.Resources>
    <DataGrid.Columns>
        <DataGridComboBoxColumn
            Header="Guild"
            SelectedItemBinding="{Binding Guild, UpdateSourceTrigger=PropertyChanged}"
            DisplayMemberPath="Name"
            ElementStyle="{StaticResource GuildComboStyle}"
            EditingElementStyle="{StaticResource GuildComboStyle}"
            Width="200"
            />
        <DataGridComboBoxColumn
            Header="Channel"
            SelectedItemBinding="{Binding Guild.Channel, UpdateSourceTrigger=PropertyChanged}"
            DisplayMemberPath="Name"
            ElementStyle="{StaticResource ChannelComboStyle}"
            EditingElementStyle="{StaticResource ChannelComboStyle}"
            Width="200"
            />

        <DataGridTextColumn Binding="{Binding Guild.SID}" Header="Guild SID" />
        <DataGridTextColumn Binding="{Binding Guild.Name}" Header="Guild Name" />
        <DataGridTextColumn Binding="{Binding Guild.Channel.CID}" Header="Channel CID" />
        <DataGridTextColumn Binding="{Binding Guild.Channel.Name}" Header="Channel Name" />
    </DataGrid.Columns>
</DataGrid>

C#
public class MainViewModel
{
    public ObservableCollection<GuildSelection> Selections { get; set; }
    public ObservableCollection<Guild> Guilds { get; set; }
}

public class GuildSelection : ViewModelBase
{
    #region Guild Property
    private Guild _guild = null;
    public Guild Guild
    {
        get { return _guild; }
        set
        {
            if (value != _guild)
            {
                _guild = value;
                OnPropertyChanged();
            }
        }
    }
    #endregion Guild Property
}

public class Channel
{
    public string CID { get; set; }
    public string Name { get; set; }
}

public class Guild : ViewModelBase
{
    public string SID { get; set; }
    public string Name { get; set; }
    public List<Channel> Channels { get; set; }

    #region Channel Property
    private Channel _channel = null;
    public Channel Channel
    {
        get { return _channel; }
        set
        {
            if (value != _channel)
            {
                _channel = value;
                OnPropertyChanged();
            }
        }
    }
    #endregion Channel Property
}

#region ViewModelBase Class
public class ViewModelBase : INotifyPropertyChanged
{
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(
        [System.Runtime.CompilerServices.CallerMemberName] string propName = null)
            => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propName));
    #endregion INotifyPropertyChanged
}
#endregion ViewModelBase Class


Q:

Calling C++ function from assembly, with struct argument

I'm getting some unexpected behaviour which probably means I don't fully understand what the compiler is doing. Consider the following contrived program:
#include <stdio.h>

#pragma pack(push, 1)
struct A {
    unsigned short a;
    unsigned short b;

    explicit A() {
        printf("construct\n");
    }
    ~A() {
        printf("destruct\n");
    }
};
#pragma pack(pop)
static_assert(sizeof(A) == 4, "sizeof(A) != 4");

A  __stdcall f(int p1, A p2, int p3, int p4) {
    printf("%08X %08X %08X %08X\n", p1, p2, p3, p4);
    return p2;
}

int main() {
    __asm {
        push 4
        push 3
        push 2
        push 1
        call f

    }
    return 0;
}

The above program will crash, but if I remove the definitions of A() and ~A() from struct A it won't. The issue is related to where the compiler thinks the arguments are on the stack, with the constructor defined it thinks they're 4 bytes further than where they are. If I remove the constructors the output I get is this:
00000001 00000002 00000003 00000004
Which is what I expected, however with the constructors defined I get
00000002 00000003 00000004 00000000
Which is obviously not what I expected. When running the former the function returns with RETN 0x10 and the latter with RETN 0x14, so it looks like it thinks there should be another parameter (why?). I noticed that if I change f to be a void function, it works as expected. So, can someone explain to me what's going on and why? I have all optimizations turned off.

A:

At the assuembly level, only simple values can be returned from a function by returning them in a register, so if a more complex object needs to be returned, the compiler will treat it as if you are passing a pointer to the returned object:
void f(A *return_ptr,int p1,A p2,int p3,int p4);

Certain optimizations can be made however.  In your example, your class contains two 16-bit shorts, and those two 16-bit shorts can be packed into a single 32-bit integer and returned in a register.  However, if you define a custom destructor, the class is no longer considered simple enough to do this optimization.


Q:

Why justify-content doesn't work in my case?

Can't find an answer why .user-name-box & .user-location divs don't wanna stay on center of parent div...

.main-content{
        display: flex;
        flex-flow: row nowrap;
        justify-content: center;
        align-items: center;
        width: 600px;
        background: grey;
    }
        .user-info{
            display: inline-flex;
            flex-flow: column nowrap;
            justify-content: center;
            align-content: center;
            width: 300px;
            background: red;
        }
            .user-name-box{
                display: flex;
                width: 100px;
                height: 100px;
                background: blue;
                color: white;
            }
            .user-location{
                display: flex;
                width: 100px;
                height: 100px;
                background: yellow;
                color: black;
            }

user-name-box

user-location

Thanks in advance!

A:

It's because you are using align-content instead of align-items on .user-info.

.main-content {
  display: flex;
  flex-flow: row nowrap;
  justify-content: center;
  align-items: center;
  width: 600px;
  background: grey;
}
.user-info {
  display: inline-flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  width: 300px;
  background: red;
}
.user-name-box {
  display: flex;
  width: 100px;
  height: 100px;
  background: blue;
  color: white;
}
.user-location {
  display: flex;
  width: 100px;
  height: 100px;
  background: yellow;
  color: black;
}

user-name-box

user-location


Q:

Dice rolling, and probability.

Oliver rolls three fair standard six-sided dice. What is the probability that there is at least one pair of dice whose top faces sum to $6$? Express your answer as a common fraction.

I started by saying that there were $6^3$ total possibilities. For the next step, there are $5$ ways to roll a pair of dice and get $6$ when adding them. There is a third dice, so we multiply by $6$ to get $\frac{30}{216}$ but this is wrong! What did I do wrong? Am I on the right track? Or should I do something else to start? (BTW, yes I did simplify the fraction)

A:

I suggest you draw a probability tree.  On any toss, the probability of a 6 is 5/36.  The experiment ends if you get a 6.


Q:

Parse the number with Regex with non capturing group

I'm trying to parse phone number with regex. Exactly I want to get a string with phone number in it using function like this:
string phoneRegex = @"^([+]|00)(\d{2,12}(?:\s*-*)){1,5}$";
string formated = Regex.Match(e.Value.ToString(), phoneRegex).Value;

As you can see I'm trying to use non-capturing group (?:\s*-*) but I'm doing something wrong.
Expected resoult should be:
input (e.Value): +48 123 234 344 or +48 123234344 or +48 123-234-345
output: +48123234344
Thanks in advance for any suggestions.

A:

Regex.Match will not alter the string for you; it will simply match it. If you have a phone number string and want to format it by removing unwanted characters, you will want to use the Regex.Replace method:
// pattern for matching anything that is not '+' or a decimal digit
string replaceRegex = @"[^+\d]";
string formated = Regex.Replace("+48 123 234 344", replaceRegex, string.Empty);

In my sample the phone number is hard-coded, but it's just for demonstration purposes.
As a side note; the regex that you have in your code sample above assumes that the country code is 2 digits; this may not be the case. The United States has a one digit code (1) and many countries have 3-digit codes (perhaps there are countries with more digits than that, as well?).


Q:

Can a paragraph be a parent-element?

Should mention:
I'm not the most experienced web-coder.
Nevertheless: Currently dealing with some frontend stuff.
Yesterday I programmed some JavaScript and the results wasn't as I had expected.
I made this demo:
Every paragraph contains a headline and some text. The paragraphs are enclosed within a div-container.

Some headline ...

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.

Another headline ...

    Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus.

Let's say I have a reference to the first headline and would like to get the class-name of the first paragraph-tag.
I would to something like this:
// Get a reference to the first headline element.
var headline = document.getElementsByClassName('headline')[0];
// Access the parent of the headline element.
console.log(headline.parentNode.className);
// Result is: container

I expect as return 'paragraph' because the paragraph encloses the headline. Instead I get the class-name of the div.
Can anyone explain this behaviour?

A:

You are getting container instead of paragraph because the web-browser is correcting your malformed html code structure:

The error is that
 element should contain a text body and not other elements.
Changing your
 tag to
 makes your code work perfectly like so:

Some headline ...

    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor.

Another headline ...

    Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus.


Q:

An EventBus framework for Android

Can anybody recommend a good framework for handling events in Android?  These would be business logic events like UserUpdatedEvent.  I am looking for something similar to the EventBus provided by GWT-EVENT but for a JVM that supports weak-references.

A:

You can give guava EventBus a try - it seems to work fine and has a very clean interface.

A:

I used the built in IntentService class to handle events.  It processes requests asynchronously off the main UI thread, by way of intent requests.  Each intent is added to the IntentService’s queue and handled sequentially.
A decent getting started tutorial for IntentService is available at mobiletuts.

A:

I'm not sure an event bus makes as much sense in Android.  It's useful in GWT, because the UI's can become very complex.  In Android, they have to be very simple because resources and screen real estate is very limited.  However, if you really need one, it should be relatively simple to write your own.  It's essentially just the observer pattern.


Q:

Screenshot of Mapbox map without displaying it

I need to display a few previews of addresses on the map on the same screen. To do that I'm going to display ImageViews with bitmaps instead of making multiple instances of MapView. But for that I need to find a way to capture these bitmaps.
I found snapshot function in MapboxMap (https://github.com/mapbox/mapbox-gl-native/issues/6062), but it requires displaying of the map.
val position = CameraPosition.Builder()
        .target(addressLatLng)
        .zoom(zoom)
        .build()
mapboxMap.cameraPosition = position

mapboxMap.snapshot { bitmap: Bitmap ->
    imageView.setImageBitmap(bitmap)
}

So, can I take a snapshot of the map without displaying it on the screen?

A:

I've finally found the solution! The class I needed to use was MapSnapshotter.
val width = imageView.width
val height = imageView.height
val location = CameraPosition.Builder()
        .target(LatLng(55.7558, 37.6173))
        .zoom(16.0)
        .build()
val options = MapSnapshotter.Options(width, height)
        .withCameraPosition(location)
MapSnapshotter(context, options).start { snapshot ->
    imageView.setImageBitmap(snapshot.bitmap)
}


Q:

Is a quad in a triangular shape still bad for topology?

I am trying to make an anime style model with a good topology but I keep running into quads (faces with 4 vertices). If I tried to make it square it would really mess up the model. The model is supposed to be for animations. I have the quads on the cheeks of the mesh and I do plan on rigging the face.

A:

A good trig or quad topology depends on what you intend to use it for.
If you want to use blender modeling function (such as subsurf, snooth and other deformations) it is better to use quad since trig can make ugly/buggy result.
Some publications say trig can be usefull in animation or game but it depend what software you use. But usually quad is  better.


Q:

How to convert POJO to map with types retained?

I need to convert a POJO to a map. I tried using Object mapper but types like timestamp are coming either as String or as Long in the final map. Is there some tool that would do a simple conversion that would result in a map having exactly the same objects as in the POJO ? (I know I can use reflection but want to see if there is an easier way.)

A:

This can be done directly with BeanUtils describe or BeanMap:
Map<Object, Object> map = BeanUtils.describe(object);

Map<Object, Object> map = new BeanMap(object);


Q:

Is there a way to pass additional data to UserInfo dictionary using NSNotificationCenter with UIKeyboardDidShowNotification

I have these lines of code:
-(void)someMethod:(UIScrollView*)scrollView{
 [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(keyboardWasShown:)
     name:UIKeyboardDidShowNotification object:nil];
}
-(void)keyboardWasShown:(NSNotification *)aNotification{
// I want to get scrollView over here
}

Is there a way to make this possible? I've tried to perform this staff according to

How to pass a NSDictionary with postNotificationName:object:

but aNotification.userInfo doesn't contain my data
  [[NSNotificationCenter defaultCenter]
postNotificationName:UIKeyboardDidShowNotification
object:self
 userInfo:@{@"scrollView":scrollView}];

A:

You are listening to UIKeyboardDidShowNotification and then you post UIKeyboardWillHideNotification that won't work. First maybe you like create your own notification name i.e XYZKeyboardDidShowNotification and then register for that and post using that name with the additional data you want. And then you can do:
-(void)keyboardWasShown:(NSNotification *)aNotification{
    UIScrollView *scrollView = aNotification.userInfo[@"scrollView"];
}


Q:

Keep getting 404 error and "No User matches the given query." message on form submission

I am trying to let my user post onto a project page, however when submitting the post form I get a 404 and the message "No User matches the given query." I am also not sure If I have got my form_valid part correct.
I want my user to be able to make posts on different project pages they have and for each post to be related to the correct project.
Any help and example code would be much appreciated!
views
class NewPost(CreateView):
    model = ProjectPost
    form_class = ProjectPostForm
    template_name = 'howdidu/new_post.html'

    def form_valid(self, form):
        self.object = form.save(commit=False)
        project = UserProject.objects.get(slug=self.kwargs["slug"])
        self.object.project = project
        self.object.save()
        return super(NewPost, self).form_valid(form)

    def get_success_url(self):
        project_username = self.request.user.username
        project_slug = self.object.slug
        return reverse('user_project', kwargs={'username':project_username, 'slug': project_slug})

urls
urlpatterns = patterns('',
        url(r'^$', views.index, name='index'),
        url(r'^register_profile/$', views.register_profile, name='register_profile'),
        url(r'^update_profile/$', views.update_profile, name='update_profile'),
        url(r'^create_project/$', login_required(views.CreateProject.as_view()), name='create_project'),
        url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/new_post/$', login_required(views.NewPost.as_view()), name='new_post'),
        url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/update_project/$', login_required(views.UpdateProject.as_view()), name='update_project'),
        url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/delete_project/$', login_required(views.DeleteProject.as_view()), name='delete_project'),
        url(r'^(?P<username>\w+)/$', views.profile_page, name='user_profile'),
        url(r'^(?P<username>\w+)/(?P<slug>[-\w]+)/$', views.project_page, name='user_project'),

        )

models
class UserProject(models.Model):
    user = models.ForeignKey(User)
    title = models.CharField(max_length=100)
    project_overview = models.CharField(max_length=1000)
    project_picture = models.ImageField(upload_to='project_images', blank=True)
    date_created = models.DateTimeField(auto_now_add=True)
    project_views = models.IntegerField(default=0)
    project_likes = models.IntegerField(default=0)
    project_followers = models.IntegerField(default=0)
    slug = models.SlugField(max_length=100, unique=True) #should this be unique or not?

    def save(self, *args, **kwargs):
        self.slug = slugify(self.title)
        super(UserProject, self).save(*args, **kwargs)

    def __unicode__(self):
        return self.title

class ProjectPost(models.Model):
    project = models.ForeignKey(UserProject)
    title = models.CharField(max_length=100)
    post_overview = models.CharField(max_length=1000)
    date_created = models.DateTimeField(auto_now_add=True)
    post_views = models.IntegerField(default=0)
    post_likes = models.IntegerField(default=0)

forms
#form to add project details
class UserProjectForm(forms.ModelForm):

    class Meta:
        model = UserProject
        fields = ('title', 'project_picture', 'project_overview')

#form to create a post
class ProjectPostForm(forms.ModelForm):

    class Meta:
        model = ProjectPost
        fields = ('title', 'post_overview')

template
{% extends 'howdidu/base.html' %}

{% load staticfiles %}

{% block title %}New Post{% endblock %}

{% block body_block %}

Create a new post

        <form enctype="multipart/form-data" id="ProjectPostForm" method="post" action="/new_post/">
          {% csrf_token %}
          {{ form.as_p }}
          <input type="submit" name="submit" value="Create" />
        </form>

{% endblock %}

A:

You're posting your form to /new_project/, but that doesn't exist in your urls.py. You probably meant /create_project/.


Q:

Dealing with character monopolizing game

I've recently started a campaign with one particular player who seems to be taking up most of the screen time and unilaterally setting the direction of the party. He's an extroverted person playing an extroverted character (the other players, including me, are more introverted), and the game so far has mostly consisted of him having detailed conversations with various NPCs while we stand around and watch, occasionally trying to interrupt and getting dimissed or shushed. The PC in question is socially-oriented with modest combat abilities, and thus prefers peaceful NPC interactions and avoiding combat whenever possible; in fact, I was yelled at out-of-character for escalating a social confrontation into a combat one. The group dynamics seem to have settled into a situation where he's become the de facto leader of the party and the rest of us are his lackeys. Given the introversion of the rest of the party, though, I seem to be the only person who objects to this.
This situation can't be uncommon in RPGs; I've even encountered it in some past games I've played in, though I haven't found a solution to the underlying problem. Is this just an inherent problem in group role-playing games, or is there is something useful I can do as a player?

A:

Talk to your DM about it
From the sounds of things, especially the extra information in the comment to the other answer, you have enjoyed playing with everyone but the extroverted player, and the extroverted player is new to the group. It sounds like the extrovert is not a good fit for your group. From a GM perspective, the best way to handle this is to talk to the player in question to see if they can change their behavior, and to kick them out if that doesn't help.
Making sure everyone has an enjoyable time is one of the duties of the GM of the game. If you have a problem with another player, talk to your GM privately, outside of the game. Tell him that you feel that the new player is not a good fit, and that he is trouncing everyone else. Tell him that you're not enjoying the game as is, and that you feel the new player is the cause of this, and ask him to talk to the new player. Remember that you might not be alone in feeling this way, especially since the other original players are all introverted. Also, show him the next part of this answer.
Advice for your GM
One of your players has a problem with another player. As the GM, it falls on you to resolve conflicts like this. The problem seems to be that you have a group of introverted players, and you introduced an extroverted player who is now taking the focus away from the other players. There is nothing wrong with introducing new players, but it appears that this particular player is not a good fit for the existing group. So, how do you resolve this?
Start off by talking to the new player about this. He is most likely not doing it on purpose, and likely doesn't even notice. Bring it up by saying that "some players" are feeling that he is hogging the spotlight, and ask him to let the other players have spotlight time as well. Make sure that you do not mention who voiced the concern, as this may lead to bad blood between these players. Concerns about other players has to be anonymous. Leave it at that for now, and see how it goes.
I would also make it clear, if you haven't already, that you are willing to listen to feedback. Let them know that they can feel safe voicing concerns to you.
Now, if talking to the new player doesn't help the situation (ask the players who raised concerns!), kick out the new player from the group. The new player is having fun at the expense of your other players, and this is not something you want. If this continues for too long, you risk losing your other players. Losing one player can sometimes lead to a chain reaction, as people realize that they can leave the game at any time.
If this doesn't work, walk away
If your GM doesn't talk to the other player (or remove him), it may be best for you to walk away from this game. This doesn't necessarily mean walking away from the group, though. Tell people that you're not having fun as is, and that you'd prefer not playing in this campaign (if that is actually the case). If you're the only one that feels this way, the problem is solved for the group, and everyone is having fun. If other players feel the same way you do, it is not unlikely that they will walk away from the game as well. If the game collapses, talk to your GM about a new game without the problem player, or even picking up where you left off.
Keep in mind that this last part should only be done if the other methods don't work.

A:

As i see t there a two challenges here:
One is you are all introverts, he is extrovert. This is a difficult constellation.
Your group should play a few weeks without him, so you all can work your shyness.
Your "friend" "who yells at" and "dismisses and shushes" you,
sounds like a spoiled brat, maybe you should rethink what friendship means. Friends should show respect for each other, this sounds more like bullying.
A RPG is an group experience, if you feel like you are his lackeys or do things you dont want to, like talking instead of fighting, you're not having fun, so you might as well quit that.
He needs to understand that it's not always his birthday, he has to share gametime, or find a new group.
Second is you have different playing goals.
If you resolve problem one, this is cake. Talk about what each of you expect and try to give everyone at least one spotlight per session.
Example: A Social Encounter with the Baroness for him. A Battle with her Guards for you, maybe at the same time?


Q:

About SQL SERVER LEFT JOIN and Group by

I have two tables,Blog table has a FK BlogTagID column point to BlogTag table:
Blog table:
BlogID BlogTagID BlogTitle
  1       2        test1
  2       1        test2
  3       2        test3

BlogTag table:
BlogTagID BlogTagName
  1        JAVA
  2        .NET
  3        PHP

I would like to get the result:
BlogTagName  count
   JAVA         1
   .NET         2
   PHP          0

How to get this?Thank you very much!

A:

try this code
select BlogTagName, count(blogid)
from BlogTag bt
left join Blog b on b.blogtagid = bt.BlogTagID
group by BlogTagName

SQL FIDDLE : http://sqlfiddle.com/#!3/356c5/8/0


Q:

YouTube Analytics API Localhost 8080 error

My script is the same as https://github.com/youtube/api-samples/pull/45/commits/e5ec5453233c287cbfe1ecd296ae0ed18c4ce523 (written in Python) where I specified the CLIENT_SECRETS_FILE = "client_secret_xxx.com.json"
The client secret is created under OAuth 2.0 client IDs as "other".
When I run it, it throws the following error:
This site can’t be reached
The connection was reset.
ERR_CONNECTION_RESET
While the url is http://localhost:8080/?code=4/Wulz_B8fgMauanVxtPocdgwE1sNndZZe6BGrVLI7wLU#
Any idea what is causing the error?

A:

When running the script, execute python file_name.py --noauth_local_webserver.
Here are the steps:
1)      Execute “python youtube_api.py --noauth_local_webserver”
        It will show you a long URL
2)      Copy that URL and open in a browser
3)      It will ask you to login on your Google account and pick the channel
4)      It will show you a “Verification Code” (something like 4/j6KgOnbVU08kbBpi-GVOq9D6p-Vm6inOQUOJiTYWQqs)
5)      Copy Verification Code and paste within the EC2 window. Click Enter
You're done. From now on it will execute whatever parameters you indicate within the script


Q:

Complete classification of six dimensional non-semi simple Lie algebra

I would aim to know the complete classification of 6 dimensional non-semi simple Lie algebra (here the dimension stands for the generators; or the dimension $\leq 6$).
In this paper, in page 7, it stated that: "There is no complete classification of the six-dimensional real Lie algebras. However, all nilpotent six-dimensional Lie algebras are known." I also found this paper: J.Math.Phys. 17 (1976) 986, which lists nilpotent six-dimensional Lie algebras in Table III, p.991.
My question, again, is that: whether complete classification of 6 dimensional non-semi simple Lie algebra is known; for both real/complex non-semi simple Lie algebra of dimension 6? What is the most complete result? (In which paper/ref can I find a table of their Lie algebra?) Is that Table III a complete or incomplete for all real/complex non-semi simple Lie algebra of dimension 6?
Deep appreciation to whom concern and reply. (My question is motivated by a problem in topological field theory.)

A:

I am considering the complex case.
The list you wrote is complete for the NILPOTENT Lie algebras and was first obtained by Morozov in 1958 (paper in Russian). To obtain the calssification of ALL Lie algebras of dimension 6 one has to consider two more case:

non solvable
solvable but not nilpotent

As for the non solvable case there are only three possibilities:
1) ${\mathfrak sl}_2(\mathbb C)\oplus {\mathfrak sl}_2(\mathbb C)$
2) ${\mathfrak sl}_2(\mathbb C)\ltimes \mathbb C^3$ where the semidirect product is given by the adjoint action;
3) ${\mathfrak sl}_2(\mathbb C)\ltimes {\mathfrak n}_3(\mathbb C)$ where the semidirect product is by a sutable action on the Heisenberg -Lie algebra  ${\mathfrak n}_3(\mathbb C)$ (3-dimensional, nilpotent).
Then you need to classify the solvable ones. This was achieved by Yamaguchi Mem. Fac. Sci. Kyushu Univ. Ser. A 35, pages 341-351 (1981). Some more informations are contained in a paper by Goze-Ancochea Bermudez (1985) where the variety of Lie algebras is studied as an algebraic variety for dimension up to 7. The relevant information connected to Clark's comment, is the number of irreducible components.

A:

I should add one reference, for the case of real numbers, namely the classification
of all solvable real six-dimensional Lie algebras by Turkowsky:
P. Turkowski. Solvable Lie algebras of dimension six. J. Math. Phys. 31 (1990), 1344-1350.
As mentioned before, the classification of nilpotent Lie algebras of dimension $6$ has been done earlier by Morozow in $1958$, valid for all fields of characteristic zero. Recently this classification has been extended to arbitrary fields, by Serena Cicalo, Willem A de Graaf and Csaba Schneider here:http://arxiv.org/abs/1011.0361.


Q:

json_encode() returns false

This is the first time i ever face, that var_dumping json_encode of an array resulting boolean value.
I have an array that was resulted from unserialization. I var_dumped it and  made sure that it is a valid array. The result is like below. This is just a piece, not entire debug view.
array (size=3)
'id' => string 'asco-power-technologies-l-p' (length=27)
  'name' => string 'asco-power-technologies-l-p' (length=27)
  'children' =>
    array (size=2)
      0 =>
        array (size=4)
          'id' => string 'apl-logistics' (length=13)
          'name' => string 'APL LOGISTICS' (length=13)
          'data' =>
            array (size=2)
              'band' => string 'ASCO POWER TECHNOLOGIES ,L.P.' (length=29)
              'relation' => string 'Buyer of band' (length=13)
          'children' =>
            array (size=11)
              0 => &
                array (size=3)
                  'id' => string 'trisa-ag' (length=8)
                  'name' => string 'TRISA AG' (length=8)
                  'data' =>
                    array (size=2)
                      'band' => string 'APL LOGISTICS' (length=13)
                      'relation' => string 'Buyer of band' (length=13)
              1 => &
                array (size=3)
                  'id' => string 'colgate-sanxiao-co-ltd' (length=22)
                  'name' => string 'COLGATE SANXIAO CO LTD' (length=22)
                  'data' =>
                    array (size=2)
                      'band' => string 'APL LOGISTICS' (length=13)
                      'relation' => string 'Buyer of band' (length=13)

.....
Aterwards i json_encode it with max depth=3. Note, i am using PHP 5.5 and running on Apache 2.4, so that it supports depth parameter on json_encode(). This is what i was doing.
    $array = unserialize($serial);
    var_dump($array);
    $json = json_encode($array, JSON_PRETTY_PRINT, 3);
    var_dump($json);

Finally i got $array var_dumped properly and $json var_dumped with result of false boolean value. What's wrong with it? Is it due to early PHP release that unproper var_dump would result false boolean? Have anyone ever faced this?
UPDATE:
This is the serialize string. The entire string is too bunch so i paste only a piece.
a:3:{s:2:"id";s:27:"asco-power-technologies-l-p";s:4:"name";s:27:"asco-power-technologies-l-p";s:8:"children";a:2:{i:0;a:4:{s:2:"id";s:13:"apl-logistics";s:4:"name";s:13:"APL LOGISTICS";s:4:"data";a:2:{s:4:"band";s:29:"ASCO POWER TECHNOLOGIES ,L.P.";s:8:"relation";s:13:"Buyer of band";}s:8:"children";a:11:{i:0;a:3:{s:2:"id";s:8:"trisa-ag";s:4:"name";s:8:"TRISA AG";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:1;a:3:{s:2:"id";s:22:"colgate-sanxiao-co-ltd";s:4:"name";s:22:"COLGATE SANXIAO CO LTD";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:2;a:3:{s:2:"id";s:25:"apll-on-behalf-oftongfang";s:4:"name";s:25:"APLL ON BEHALF OFTONGFANG";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:3;a:3:{s:2:"id";s:26:"apll-on-behalf-of-zhejiang";s:4:"name";s:26:"APLL ON BEHALF OF ZHEJIANG";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:4;a:3:{s:2:"id";s:33:"apll-on-behalf-of-tongfang-global";s:4:"name";s:33:"APLL ON BEHALF OF TONGFANG GLOBAL";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:5;a:3:{s:2:"id";s:34:"apll-on-behalf-of-ningbo-xiangyuan";s:4:"name";s:34:"APLL ON BEHALF OF NINGBO XIANGYUAN";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:6;a:3:{s:2:"id";s:33:"apll-on-behalf-of-ningbo-homestar";s:4:"name";s:33:"APLL ON BEHALF OF NINGBO HOMESTAR";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:7;a:3:{s:2:"id";s:17:"apll-on-behalf-of";s:4:"name";s:17:"APLL ON BEHALF OF";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:8;a:3:{s:2:"id";s:21:"apl-logistics-sdn-bhd";s:4:"name";s:21:"APL LOGISTICS SDN BHD";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}}i:9;a:4:{s:2:"id";s:21:"apl-logistics-limited";s:4:"name";s:21:"APL LOGISTICS LIMITED";s:4:"data";a:2:{s:4:"band";s:13:"APL LOGISTICS";s:8:"relation";s:13:"Buyer of band";}s:8:"children";a:27:{i:0;a:3:{s:2:"id";s:26:"tri-phil-international-inc";s:4:"name";s:27:"TRI-PHIL INTERNATIONAL INC.";s:4:"data";a:2:{s:4:"band";s:21:"APL LOGISTICS LIMITED";s:8:"relation";s:13:"Buyer of band";}}i:1;a:3:{s:2:"id";s:16:"pt-apl-logistics";s:4:"name";s:17:"PT. APL LOGISTICS";s:4:"data";a:2:{s:4:"band";s:21:"APL LOGISTICS LIMITED";s:8:"relation";s:13:"Buyer of band";}}i:2;a:3:{s:2:"id";s:25:"keygold-manufacturing-inc";s:4:"name";s:26:"KEYGOLD ...

A:

The depth of $array is definitely greater than 3. Just make depth a larger number.
On a side note, you may also use json_last_error to see the error message in the case that json_encode fails.


Q:

Does the "running technique" of Seiho players exist in real life?

In Episode 7, when they play against Seiho, it shows that the way the Seiho players run is different from the common way (specifically, the way they swing their arms).
Does this running technique exist in real life?

A:

I don't know this running technique, but I can tell you how important it is to swing your arms properly while running.
Have a Look here ->
LiveScience Arm Swinging.

The scientists found that swinging the arms reduced energy costs by 3 percent compared with holding the hands behind the back, 9 percent compared with holding the arms across the chest, and 13 percent compared with holding the hands on top of the head.

If you have a look at professional runners, you will recognize how focused they move their arms. I can't tell if this special arm swinging is working, but there are surely different techniques to reduce your energy cost by swinging your arms.


Q:

Use LINQ without putting data in memory

I have a large number of records of data in a binary file, and I want to search for something in it. Is there any way that could I use LINQ statement on the file data without putting all the data in memory (likeList<T>)?
I have this methods that use List<Book> :
private Book Read(long position)
{
    Book book;
    using (Stream st = File.Open(HttpContext.Current.Server.MapPath("/") + "library.majid", FileMode.OpenOrCreate, FileAccess.Read))
    {
        st.Position = position;
        using (BinaryReader reader = new BinaryReader(st))
        {
            if (!reader.ReadBoolean())
                return null;
            book = new Book()
            {
                Id = reader.ReadInt32(),
                Name = reader.ReadString(),
                Dewey = reader.ReadString()
            };
            try
            {
                book.Subject = reader.ReadString();
                book.RegDate = reader.ReadInt32();
                book.PubDate = reader.ReadInt32();
            }
                catch (EndOfStreamException) { }
            }
        }
        return book;
    }
        private List<Book> getAll( int recordLength = 100)//sorted results by Id!!
    {
        long Len;
        using (Stream st = File.Open(HttpContext.Current.Server.MapPath("/") + "library.majid", FileMode.OpenOrCreate, FileAccess.Read))
        {
            Len = st.Length;
        }
        List<Book> res = new List<Book>();
        Book ReadedBook = null;
        for (int i = 0; i < Len/100; i++)
        {
            ReadedBook = Read(i * 100);
            if (ReadedBook != null)
                res.Add(ReadedBook);
        }
        res.Sort((x, y) => x.Id.CompareTo(y.Id));
        return res;
    }

A:

If it is a text file, you can use File.ReadLines(filename) which returns IEnumerable<string>, without loading the file to memory.
See http://msdn.microsoft.com/en-us/library/dd383503.aspx

The ReadLines and ReadAllLines methods differ as follows: When you use ReadLines, you can start enumerating the collection of strings before the whole collection is returned; when you use ReadAllLines, you must wait for the whole array of strings be returned before you can access the array. Therefore, when you are working with very large files, ReadLines can be more efficient.

For ex;
var count = File.ReadLines(somefile)
                .Where(line => line.StartsWith("something"))
                .Count();

EDIT

what If it be a binary file?

Then you can write a method similar to this:
public static IEnumerable<Book> ReadBooks(string filename)
{
    using (var f = File.Open(filename, FileMode.Open))
    {
        using (BinaryReader rdr = new BinaryReader(f))
        {
            Book b = new Book();
            //.....
            yield return b;
        }
    }
}


Q:

"Method must have a return type"

"Method must have a return type" in regards to Public Send(SerialPort serialPort1). What am I specifically missing? That is the part where I would like to begin writing to the com port. From looking at other issues online I notice that I may be missing an assembly reference or body portion for that class.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TEST_Listbox
{
    public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
        comboBox1.Items.Add(new Command { DisplayText = "Part 1", CommandText = "01P00101##" });
        comboBox1.Items.Add(new Command { DisplayText = "Part 2", CommandText = "02P00102##" });
    }

    private void button1_Click(object sender, EventArgs e)
    {
        serialPort1.PortName = "COM3";
        serialPort1.BaudRate = 9600;
        serialPort1.Parity = Parity.None;
        serialPort1.DataBits = 8;
        serialPort1.StopBits = StopBits.One;
        serialPort1.Handshake = Handshake.None;
        serialPort1.RtsEnable = true;
        serialPort1.DtrEnable = true;

        serialPort1.Open();
        if (serialPort1.IsOpen)
        {
            serialPort1.WriteTimeout = 500;
            button1.Enabled = false;
        }
    }

    public class Command
    {
        public string DisplayText { get; set; }
        public string CommandText { get; set; }

        public Send(SerialPort serialPort1)
        {
            if (serialPort1.IsOpen)
            {
                var content = new List<byte>();
                content.Add(2);
                content.AddRange(Encoding.ASCII.GetBytes(CommandText));
                content.Add(3);
                byte[] buffer = content.ToArray();
                serialPort1.Write(buffer, 0, buffer.Length);
            }
        }

        public override string ToString()
        {
            return DisplayText;
        }
    }

    private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
        var command = (Command)comboBox1.SelectedItem;
        if (command != null)
        {
            command.Send(serialPort1);
        }
    }

 }
}

A:

It means that you'r Send method does not have a return type. Meaning that you don't return anything in that method. If that method shouldn't return anything, then just add void as a return type:
public void Send(SerialPort serialPort1)
    {
        if (serialPort1.IsOpen)
        {
            var content = new List<byte>();
            content.Add(2);
            content.AddRange(Encoding.ASCII.GetBytes(CommandText));
            content.Add(3);
            byte[] buffer = content.ToArray();
            serialPort1.Write(buffer, 0, buffer.Length);
        }
    }


Q:

Specific Parameter-Passing Styles: Call-By-Value, Call-By-Name, etc

Studying for my final exam, and came across this past exam question:
Consider the following program written in a C-like notation:
int i = 1;
A[] = {4, 0, 1, 2};

void mystery05(int from, int to)
{
    int temp;
    temp = A[from];
    A[from] = A[to];
    A[to] = temp;
    i = i + 2;
    to = -1;
}

int main(void)
{
    mystery05(A[i+2], A[i]);
}

In the table below, fill in the boxes with the appropriate variable values after the call to mystery05 in main.  Each row corresponds to a specific parameter-passing style (ie.  use the style listed instead of the default C-language semantics).  Assume arrays are indexed from 0.
style               |___i___|__A[0]__|__A[1]__|__A[2]__|__A[3]__|
call-by-value       |_______|________|________|________|________|
call-by-name        |_______|________|________|________|________|
call-by-reference   |_______|________|________|________|________|
call-by-value-result|_______|________|________|________|________|

I'm not sure on how to go about this, but if it was regular C semantics, I supposed the answers would be
i = 3; A[0] = 4; A[1] = 2; A[2] = 1; A[3] = 0

A:

@S.Lott :
I thought 'pointer's to strings and arrays are call by reference. Am I wrong?
I agree: don't want to do all the question. If he has an exam he ought to be more clued up.
I would like to answer the first line though just to see if i have understood correctly.
So I could be wrong!
Call by value:  doesn't change the values unless the variables are global
and in this case they have to be; for how otherwise can the proc make use of i.
Both i and the A array are global.
What happens in the proc changes the values.
i begins with value 1 so values of A[3] and A[1] swapped.
A[3] now 0 , A[1] now 2 . A[0] and A[2] unchanged.
finally i value changed to 3
I think the exam q missed a trick by not asking about the value of 'to' after the proc call.


Q:

Gradle window in missing in android studio for my flutter project

The gradle window is missing in the android studio for my flutter project but it is available for my Kotlin project.

I have to generate the signing certificate SHA-1 to register my app in Firebase.

A:

You won't find a gradle window view in flutter project, so here is a solution for that..
In command prompt navigate to bin folder of jdk and run this command
keytool -list -v -keystore "C:\Users\yourus\.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android

then you can copy sha from there


Q:

Converting Linq Expression to C# EF

I have been at this two days now. I am not very good at Linq expressions so please forgive the simplicity. I have two related tables and writing a join in TSQL would be easy but I am using Entity Framework and Linq.
I hacked out a query in LINQPad (via reading articles and tutorials) and it is returning the results as I want finally.
Now I need help turning that into C# code. I have google for translator site and find plenty of SQL to Linq but none for what I am doing....quite possibly because I don't even know that I am using the correct search terms.
My LINQPad code is this:
DashboardNavigations
.OrderBy(x => x.Id)
.Select(x => new
{
    x.Id,
    x.Name,
    x.Description,
    x.ImageUrl,
    SubDash = SubDashNavs
        .Where(s => s.DashId == x.Id)
        .Select(y => new { y.Id, y.Name, y.Description })

})

I am used to writing SIMPLE Linq expressions to entity framework like this:
var query = _mlsDashboardNavRepository.Table;
query = query.OrderBy(c => c.Id);
var dashnav = query.ToList();

As you can see I have the main records returning but cant get the join right.
What i am needing help with is translating the code from LINQPad to C# / EF / LINQ to SQL....????

A:

As stated in comments I suggest that your _mlsDashboardNavRepository only refers to DashboardNavigations since you say you retrieve your main records using only _mlsDashboardNavRepository.Tables; Where is your DashboardNavigations reference? To perform your query you need a context that refers to (all) your database tables. Below is code in LINQ format using a database context, that might be easier on you if you're used to SQL syntax.
var query = (from d in context.DashboardNavigations
             join s in context.SubDashNavs on d.Id equals s.Id
             orderby d.Id ascending
             select new
             {
                d.Id,
                d.Name,
                d.Description,
                d.ImageUrl,
                SubDash = s
             });

var dashNavs = query.ToList();


Q:

Excess comma replace issue after creating auto links from tags

My issue is inside the if statement below. My tags structure is like this: tag1, tag2, tag3
I achieved auto linking of each tag of each article but if the number of tags is more than 1, I need to replace two characters that are 1 comma+1 space character and inside the related

 couple. These 2 characters {1 comma+1 space} are before the last
 tag. Explicitly I mean:
My input is (html source):

Etiketler: tag1, tag2,

and my desired output is (html source)

Etiketler: tag1, tag2

my custom function is below> Now, you see the preg_replace but I also tried str_replace. My encoding is utf-8 if it helps. I read the php.net manual for these 2 functions but I couldn't get rid of those 2 characters.
Can you help me please?
function etiketleri_link_yap ($article_tags)
{
    $array_of_tags = explode(", ", $article_tags);
    if (count($array_of_tags) >= 2)
        {
            $ely ='';
            for ($i = 0; $i < count($array_of_tags); $i++)
                {
                    $ely .= ''.$array_of_tags[$i].', ';
                }
            $arabunu ="/<\/a>, <\/p>/"; $degistir  = '
';
            $ely = preg_replace($arabunu, $degistir, $ely);
            return $ely;
        }
    else
        {
            $ely =''.$array_of_tags[0].'';
            return $ely;
        }
}

A:

There is no closing
 tag in your $ely variable, just  tags so your regex never matches.
I would build an array of tags / tag links and implode them at the end:
$links = array();
for ($i = 0; $i < count($array_of_tags); $i++)
{
   $links[] = ''.$array_of_tags[$i].'';
}
$ely = implode(', ', $links);

By the way, I would also use a foreach to loop over $array_of_tags but if you are sure the index starts at 0 and there are no missing indices, the result should be the same.