text:
Q: adding images programmatically via loop in table cell + iOS I am creating an app to display listings and each listing has x number of images to be displayed in table cell.
To display the images, i have to create the UIImageView dynamically and load the images in the cell in a for loop {depending on the data received from a server call}.
Now, i am able to add the images dynamically but the number of images displayed in cell is not correct. I have checked the array value and count of loop but still not able to understand that why images are not loading properly.
PROBLEM :
first 3-4 cell that are loaded as the view is loaded shows correct number of programmatically added image views. But when i scroll to bottom of the table, the correct number of images are not displayed in the cell and shows random number of images
here is the function code :
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *Cellidentifier1 = @"VenueCell";
VenueCell *cell = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];

// Configure the cell...

long row = [indexPath row];

if (!cell.hasImageViews) {
    cell.hasImageViews = YES;
    NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

    NSLog(@"sports132431 = %@",individualSports);
    for (int t = 0; t<individualSports.count; t++) {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((250/10*t+10), 125, 20, 20)];
        if ([individualSports[t] isEqual:@"Cricket"]) {
            [imageView setImage:[UIImage imageNamed:@"cricket_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Basketball"]) {
            [imageView setImage:[UIImage imageNamed:@"basketball_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Football"]) {
            [imageView setImage:[UIImage imageNamed:@"football_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Lawn Tennis"]) {
            [imageView setImage:[UIImage imageNamed:@"lawn_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Squash"]) {
            [imageView setImage:[UIImage imageNamed:@"squash_unselected.png"]];
        } else if ([individualSports[t] isEqual:@"Table Tennis"]) {
            [imageView setImage:[UIImage imageNamed:@"table_unselected.png"]];
        }  else if ([individualSports[t] isEqual:@"Badminton"]) {
            [imageView setImage:[UIImage imageNamed:@"badminton_unselected.png"]];
        }  else if ([individualSports[t] isEqual:@"Pool"]) {
            [imageView setImage:[UIImage imageNamed:@"pool_unselected.png"]];
        }  else if ([individualSports[t] isEqual:@"Swimming"]) {
            [imageView setImage:[UIImage imageNamed:@"swiming_unselected.png"]];
        }
        [cell addSubview:imageView];
    }
    individualSports = [[NSArray alloc] init];
    NSLog(@"sports = %@",_venueSports[row]);
    NSLog(@"asx=%@",individualSports);
}

return cell;

}

// hasImageViews is a bool variable of VenueCell class
Any suggestion is good.
Thanks in advance!
Update: Here is the updated code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

long row = [indexPath row];
// Configure the cell...

long row = [indexPath row];
cell.vName.text = _venueName[row];
cell.vTiming.text = _venueTiming[row];
cell.vAreaName.text = _venueArea[row];
cell.starRatingImage.backgroundImage=[UIImage imageNamed:@"starsbackground iOS.png"];
cell.starRatingImage.starImage = [UIImage imageNamed:@"star.png"];
cell.starRatingImage.starHighlightedImage = [UIImage imageNamed:@"starhighlighted.png"];
cell.starRatingImage.maxRating = 5.0;
cell.starRatingImage.delegate = self;
cell.starRatingImage.horizontalMargin = 12;
cell.starRatingImage.editable=NO;
cell.starRatingImage.rating=[_venueAvgRating[row] floatValue] ;
cell.starRatingImage.displayMode=EDStarRatingDisplayAccurate;

NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

for (int t = 0; t<individualSports.count; t++) {
    UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((25*t+10), 125, 20, 20)];

    // Since each of your individualSports[t] options
    // first words is simply the prefix to your image file name,
    // you can simplify the contents of your loop like so:
    NSString *firstWord = (NSString*)[[individualSports[t] componentsSeparatedByString:@" "] objectAtIndex:0];
    [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_unselected.png", firstWord.lowercaseString]]];

    [cell addSubview:imageView];
}
if([_venueCategory[row] isEqualToString:@"Partner"]){

    cell.vImageCategory.image=[UIImage imageNamed:@"venue_partner.png"];
}
else if([_venueCategory[row] isEqualToString:@"Verified"]){
    cell.vImageCategory.image=[UIImage imageNamed:@"venue_verified.png"];
}
else{

    cell.vImageCategory.image=[UIImage imageNamed:@"venue_unverified.png"];
}
cell.vImage.image=[UIImage imageNamed:@"agon_logo.png"];

return cell;

}

A: First off, since you're reusing your cells, this comparison -- if (!cell.hasImageViews) { -- won't necessarily hold the appropriate value for cellForRowAtIndexPath's current cell since the cell that's being reused can be different from the current cell. For example, if 4 cells of your table view can fit on your screen at once, when you scroll to cell 5 which was originally off the table, reusing it means that it contains the contents and property values of cell 1. So that comparison is completely irrelevant.
In this specific case though, it makes no sense whatsoever to reuse your cells since the entire contents of the cells are completely different for each row. Also, since your custom table view cell seems to only contain the .hasImageViews property, using a custom cell is unnecessary in this case since, as we've already established, we won't be reusing the cells.
Lastly, you can greatly simplify the conditionals within your for loop as I've done in my code below.
To implement these changes, I recommend doing something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:nil];

    long row = [indexPath row];

    NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

    for (int t = 0; t<individualSports.count; t++) {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((25*t+10), 125, 20, 20)];

        // Since each of your individualSports[t] options
        // first words is simply the prefix to your image file name,
        // you can simplify the contents of your loop like so:
        NSString *firstWord = (NSString*)[[individualSports[t] componentsSeparatedByString:@" "] objectAtIndex:0];
        [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_unselected.png", firstWord.lowercaseString]]];

        [cell addSubview:imageView];
    }

    return cell;

}

(Note: You've spelled "swimming" incorrectly in the file name so the change I made to your conditional won't work for that one if you don't edit the file name in your bundle.)
Update: As is now clear from your updated code, VenueCell had other properties beyond the ones apparent in your original question, so perhaps it makes sense to reuse your cells after all. To do that though, you'll have to clear out your old UIImageView subviews during each call to cellForRowAtIndexPath, ex:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *Cellidentifier1 = @"VenueCell";
    VenueCell *cell = [tableView dequeueReusableCellWithIdentifier:Cellidentifier1 forIndexPath:indexPath];

    long row = [indexPath row];

    cell.vName.text = _venueName[row];
    cell.vTiming.text = _venueTiming[row];
    cell.vAreaName.text = _venueArea[row];
    cell.starRatingImage.backgroundImage=[UIImage imageNamed:@"starsbackground iOS.png"];
    // ... all the other starRatingImageCode ...
    cell.starRatingImage.displayMode=EDStarRatingDisplayAccurate;

    // Clear out any images previously added to the
    // cell during cellForRowAtIndexPath (images have been
    // assigned a tag of 1000 in the next for loop)
    for (UIView *subview in cell.subviews) {
        if (subview.tag == 1000) {
            [subview removeFromSuperview];
        }
    }

    NSArray *individualSports = [_venueSports[row] componentsSeparatedByString:@"|"] ;

    for (int t = 0; t<individualSports.count; t++) {
        UIImageView * imageView = [[UIImageView alloc]initWithFrame:CGRectMake((25*t+10), 125, 20, 20)];
        imageView.tag = 1000 //<-- Use a tag unique to these image views

        NSString *firstWord = (NSString*)[[individualSports[t] componentsSeparatedByString:@" "] objectAtIndex:0];
        [imageView setImage:[UIImage imageNamed:[NSString stringWithFormat:@"%@_unselected.png", firstWord.lowercaseString]]];

        [cell addSubview:imageView];
    }

    // Assuming the only "else" condition is "default",
    // I've similarly simplified this code as I did with
    // your other conditional
    cell.vImageCategory.image = [NSString stringWithFormat:@"venue_%@.png", _venueCategory[row].lowercaseString];
    cell.vImage.image = [UIImage imageNamed:@"agon_logo.png"];

    return cell;
}

A: Since you are reusing cells, you need to clear out the images that were previously added to the cell before you start adding the new images to it.  If you don't have a lot of cells to display, you may not want to reuse the cells at all.

A: First you have to download them backgroundly on seperate thread (don't write this code on cellForAtIndexPath(it may be in viewdidload))and upon successful dowload you have to reload the tableview. just take one custom cell with only one imageview.
     -(void)viewDidLoad
    {
       UIImage *image;
        NSMutableArray *imageArray;

        for (int i=0; i<[totalImgesURLSArray count]; i++) {
            NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:[totalImgesURLSArrayobjectAtIndex:i]]];
            image = [[UIImage alloc] initWithData:imageData];

            [imageArray addObject:image];
        }
        dispatch_async(dispatch_get_main_queue(), ^{

            [tableview reloadData];

        });
    });

}

       - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
        {

        return [imageArray count];
    }

A: for Example an Array
NSArray *sportsTypeArray=[NSArray arrayWithObjects:@"Cricket",@"Football",@"Hockey",@"Skitting",@"Running", nil];

inCellForRowAtIndex method
cell.textLabel.text=[sportsArray objectAtindex=indexPath.row];

if ([cell.textLabel.text isEqualToString: @"Cricket"]
{

cell.imageView.image = [UIImage imageNamed:@"cricket.png"];
}

else if ([cell.textLabel.text isEqualToString: @"Football"]
{

cell.imageView.image = [UIImage imageNamed:@"footBall.png"];
}

etc.  using loop is not good idea.Try this and tell if any problem.


text:
Q: find in string specific information I have a string and would like to find something:
String example:
INSERT INTO #__users VALUES("XXXX","First User","admin","69");

How can I find numerical id?
Where XXX - is any number.

A: You can use a preg_match function to get the value with this regex:
^INSERT\s+INTO\s+#\S+\s+VALUES\("([^"]+)

REGEX:

*

*^ - Beginning of the string (can be beginning of a line if you add a m flag)

*INSERT - literal string INSERT

*\s+ - 1 or more whitespace symbols

*INTO - literal INTO

*\s+ - 1 or more whitespace symbols

*#\S+- Literal # followed by 1 or more non-whitespace symbols

*\s+ - 1 or more whitespace symbols

*VALUES\(" - literal VALUES("

*([^"]+) - A capturing group matching 1 or more characters other than " (you may use \d+ instead if you only have digits here).

See demo. The string you need is in captured group 1, as [^"]+ will safely match everything but a double quote. In case it only contains digits, use \d+: ^INSERT\s+INTO\s+#\S+\s+VALUES\("(\d+). In case the string does not appear at the beginning of a string/line, remove ^.
$re = '/^INSERT\s+INTO\s+#\S+\s+VALUES\("([^"]+)/';
$str = "INSERT\nINTO #__users\nVALUES(\"9999\",\"First User\",\"admin\",\"69\");";
preg_match($re, $str, $matches);
echo $matches[1];

IDEONE demo

redpajama_set_name: RedPajamaStackExchange


text:
Q: Signing out using Firebase I am using firebase authentication using social media accounts. After signing up, I am unable to log out.
The following is my Javascript code:
    <script src="https://www.gstatic.com/firebasejs/4.1.3/firebase.js"></script>
<script>
  // Initialize Firebase
  var config = {
    apiKey: "*******",
    authDomain: "******",
    databaseURL: "******",
    projectId: "*******",
    storageBucket: "******",
    messagingSenderId: "*******"
  };
  firebase.initializeApp(config);

  firebase.auth().onAuthStateChanged(function(user) {
      if (user) {
        // User is signed in.
        var displayName = user.displayName;
        var email = user.email;
        var photoURL = user.photoURL;
        user.getToken().then(function(accessToken) {

            console.debug('user', user);
            document.getElementById('sign-in-status').textContent = 'Signed in';
            document.getElementById('name').textContent = JSON.stringify( displayName )
            document.getElementById('email').textContent = JSON.stringify(email)
            document.getElementById('account-details').textContent = JSON.stringify({
                displayName: displayName,
                email: email,
                photoURL: photoURL
            });
        });

      } else {
          console.log('not logged in');
        /*document.getElementById('sign-in-status').textContent = 'Signed out';
        document.getElementById('sign-in').textContent = 'Sign in';
        document.getElementById('account-details').textContent = 'null';
        */
      }

    });

    // User is signed out.
        firebase.auth().signOut().then(function() {
        // Sign-out successful.
         signOutSuccessUrl: 'https://url.html'
        }).catch(function(error) {
        // An error happened.
        });

</script>

And in the html I am calling it by:
<button class="btn btn-primary" onclick="signOut()"><i class="fa fa-sign-out">/i> Log out</button>
But on clicking the button nothing happens.
I even tried putting the signout segment in a function, but that didn't help.
Any kind of help would be greatly appreciated. Thanks.

A: if your click event handler calls a signOut method, then you have to define it somewhere. like:
window.signOut = function signOut(_e) {
  firebase.auth().signOut().then(function() {
    // Sign-out successful.
  }).catch(function(error) {
    // An error happened.
  });
}


text:
Q: Conditional Probability Help?
A standard deck of cards will be shuffled and then the cards will be turned
  over one at a time until the first ace is revealed. Let $B$ be the event that the next card
  in the deck will also be an ace.
(a) Intuitively, how do you think $P(B)$ compares in size with $1/13$ (the overall proportion
  of aces in a deck of cards)? Explain your intuition. (Give an intuitive discussion rather
  than a mathematical calculation; the goal here is to describe your intuition explicitly.)
(b) Let $C_j$ be the event that the first ace is at position $j$ in the deck. Find $P(B|C_j )$ in
  terms of $j$, fully simplified.
(c) Using the law of total probability, find an expression for $P(B)$ as a sum. (The sum
  can be left unsimplified, but it should be something that could easily be computed in
  software such as R that can calculate sums.)
(d) Find a fully simplified expression for $P(B)$ using a symmetry argument.
  Hint: If you were deciding whether to bet on the next card after the first ace being an
  ace or to bet on the last card in the deck being an ace, would you have a preference?

Intuitively, it makes more sense that the probability of getting another ace is larger, since, after drawing one ace, $P(B) = 1/12$. However, I'm having issues determining the value of $C_j$. For instance, the probability that $C_j$ is at position $j$ is just $13/52$, right? There's only one place $j$, and there's only $13$ possible aces there.

A: $B$ is the event that the first and second ace in the pack are adjacent.   Since we are only concerned with placement of the aces, consider a deck of 4 ace of hearts, and 48 jokers.
$C_j$ is the event that the first ace is at position $j$.   When given that event, there are $3$ remaining aces among the $52-j$ remaining cards, so the probability that one from these aces is the next card in the deck is: $\mathsf P(B\mid C_j) = \Box/\Box$

The Law of Total Probability says $\mathsf P(B)=\sum_{j=1}^{49} \mathsf P(C_j)\mathsf P(B\mid C_j)$.
We have $\mathsf P(B\mid C_j)$, so then, what is $\mathsf P(C_j)$?   The probability that the first ace will be at position $j$?
There are $\Box$ unbiased ways to select places in a deck of fifty two for four aces and of these, $\Box$ are ways to select places for the remaining aces among the places after position $j$.
Then put the sum together.

To find a simpler expression for $\mathsf P(B)$, we argue similarly.
There are $\Box$ unbiased ways to select places in a deck of fifty two for four aces and of these, $\Box$ are arrangements where the first and second ace are adjacent.
Therefore $\mathsf P(B)= \Box/\Box $?

A: You don't know how many cards you've drawn before drawing the first ace, and since cards are inanimate they have no memory. Thus it'd only depend on the remaining number of cards. \
You aren't supposed to determine the value of Cj. Instead you should try to determine the probability of drawing an ace, given that there are 3 aces and 52-j cards left, i.e. $P(B|C_j)$

A: Consider this,
Let's arrange cards,
No of ways to arrange cards$=52!$
Let's now arrange cards such that one ace is at $j^{th}$ position,
No of ways of selecting a ace from 4 aces to be at $j^{th}$ position$=4$
No of ways of arranging the other cards fixing the $j^{th}$ position$=51!$
Total no of ways that an ace is on $j^{th}$ position$=4×51!$
Now the probability of $C_j=\frac{4×51!}{52!}=\frac{4}{52}$

Another possible argument,

Suppose the card at $j^{th}$ be $X$
Total no of possible $X=52$
No of cases we want (aces)$=4$
Hence,$$C_j=\frac{4}{52}$$


text:
Q: Authentication over CURL I am working on an API for a WordPress site. Basically, an external application (not made using WP) is able to send JSON to a file I made (api.php) and inside that file I load WP (using wp-load.php), and create a post (custom post type) based on the received JSON.
When I reach this block of code...
$formation_fr = wp_insert_post( array(
    'post_type' => 'formation',
    'post_title' => 'example post',
    'post_status' => 'publish',
    'post_author' => 2 // This is an admin account associated with this ID
) );

... the post gets created, and everything works except for the post_author (instead, there is no author for the post). But, my external application that sent the CURL request will receive this:
Error: call to URL http://domain.com/api/api.php failed with status 500, response

Alors, on triche ?
, curl_error , curl_errno 0`

The "Alors, on triche?" error is the "Cheatin' uh?" error in French. WordPress for some reason thinks that I'm trying to circumvent capabilities.
If I try to log in the user (ID: 2) programmatically with this block of code...
private function login( $id )
{
    $wp_account = get_user_by( 'id', $id );
    $username = $wp_account->data->user_login;
    wp_set_current_user( $wp_account->ID );
    wp_set_auth_cookie( $wp_account->ID );
    do_action('wp_login', $username );
}

... then I get this:
Error: call to URL http://domain.com/api/api.php failed with status 500, response , curl_error , curl_errno 0

Which is basically the same error as above but without the "Cheatin' uh?". I didn't expect that to work though, because AFAIK a cookie won't affect a CURL connection.
So, how can I avoid running into capability errors when working over CURL? I've used wp_insert_post() many times before and never had this issue. My temporary hacky solution is to erase the wp_die() function, which fixes the issue obviously.
WordPress version is 3.9.1

A: I figured out the answer myself and I'll post it here in case anyone else has this problem. Basically in WP 3.9.1, wp_insert_post() checks the current logged in user for account capabilities (at least this is what I assume). Since I was connecting over cURL, there is no logged in user so the capability checks fail. All I had to do was send the cookie WP uses to remember logged in users:
$curl = curl_init( 'http://www.domain.com' );
$login_cookie = 'wordpress_logged_in_[hash]=xxx'; // This cookie can be found once a user is logged in.
curl_setopt( $curl, CURLOPT_COOKIE, $login_cookie );

So I simply set up a new admin account for my external application, logged it as that account (using /wp-admin), copied the cookie that WP made for me, and added it to my application.


text:
Q: XPath //div[contains(text(), 'string')] fails to select divs containing 'string' This is the HTML code:

    Elangovan

I want to write an XPath for the div based on its contained text.  I tried
//div[contains(text(),'Elangovan')]

but this is not working.

A: Replace text() with string():
//div[contains(string(), "Elangovan")]

Or, you can check that span's following text sibling contains the text:
//div[contains(span/following-sibling::text(), "Elangovan")]

Also see:

*

*Difference between text() and string()

A: Alternatively to alecxe's correct answer (+1), the following slightly simpler and somewhat more idiomatic XPath will work the same way:
//div[contains(., "Elangovan")]

The reason that your original XPath with text() does not work is that text() will select all text node children of div.  However, contains() expects a string in its first argument, and when given a node set of text nodes, it only uses the first one.  Here, the first text node contains whitespace, not the sought after string, so the test fails.   With the implicit . or the explicit string() first argument, all text node descendants are concatenated together before performing the contains() test, so the test passes.

A: To make @kjhughes's already good answer just a little more precise, what you're really asking for is a way to look for substrings in the div's string-value:

For every type of node, there is a way of determining a string-value
  for a node of that type. For some types of node, the string-value is
  part of the node; for other types of node, the string-value is
  computed from the string-value of descendant nodes.

Both the context node (. or the div itself) and the set of nodes returned by text() -- or any other argument! -- are first converted to strings when passed to contains. It's just that they're converted in different ways, because one refers to a single element and the other refers to a node-set.
A single element's string-value is the concatenation of the string-values of all its text node descendants. A node-set's string-value, on the other hand, is the string-value of the node in the set that is first in document order.
So the real difference is in what you're converting to a string and how that conversion takes place.


text:
Q: Filling in missing values with a median in postgres How can I replace avg with a median calculation in this?
select *
, coalesce(val, avg(val) over (order by t rows between 3 preceding and 1 preceding)) as fixed
from (
    values
    (1, 10),
    (2, NULL),
    (3, 10),
    (4, 15),
    (5, 11),
    (6, NULL),
    (7, NULL),
    (8, NULL),
    (9, NULL)
) as test(t, val)
;

Is there a legal version of this?
percentile_cont(0.5) within group(order by val) over (order by t rows between 3 preceding and 1 preceding)

A: Unfortunately percentile_cont() is an aggregate function, for which there is no equivalent window function.
One workaround is to use an inline subquery to do the aggregate computation.
If ids are always increasing, then you can do:
select
    t.*,
    coalesce(
        t.val,
        (
            select percentile_cont(0.5) within group(order by t1.val)
            from test t1
            where t1.id between t.id - 3 and t.id - 1
        )
    ) fixed
from test t

Otherwise, you need an additional level of nesting:
select
    t.*,
    coalesce(
        t.val,
        (
            select percentile_cont(0.5) within group(order by t1.val)
            from (select val from test t1 where t1.id < t.id order by t1.id desc limit 3) t1
        )
    ) fixed
from test t

Demo on DB Fiddle - both queries yield:

id |  val | fixed
-: | ---: | :----
 1 |   10 | 10
 2 | null | 10
 3 |   10 | 10
 4 |   15 | 15
 5 |   11 | 11
 6 | null | 11
 7 | null | 13
 8 | null | 11
 9 | null | null


text:
Q: Login with google doesn't work when apk is signed with upload key Previously I could test Sign-in with Google after signing the apk and installing it to my device.
Now, I opted in the new App signing method of Google and now I cannot test sign-in with Google button in my app after signing it with the upload key. After clicking the sign-in with google button and choosing the profile, nothing happens.
If I upload the apk and it gets signed by the App signing key by Google, the sign-in with google just works.
I am changing the code and I want to test that it works before I upload to the store. Is there any way to test this without uploading while only signing with the upload key? Or any other way of doing it?


text:
Q: [PHP][Youtube api v3] retrieving the informations for a single video I'm getting some trouble with the youtube api. I would like to retrieve the informations from a single video.
What I already got :
i can get videos from a specified playlist with all their informations (like the title, the description etc)
i get the id playlist from the Url :
$playlist = $_GET['pl'];

then i get the videos informations from the playlist :
$response = $youtube->playlistItems->listPlaylistItems('id,snippet,contentDetails', ['playlistId' => $playlist, 'maxResults' => '10']);

then i can easily get and show informations from those videos thanks to a foreach :
foreach($response['items'] as $video){
echo $video['contentDetails']['videoId'];
echo $video['snippet']['title'];
echo substr($video['snippet']['description'], 0, 430);}

What I want :
now i just put the videoId into a link :
href="index.php?requ=video&v=<?= $video['contentDetails']['videoId']; ?>&pl=<?= $playlist ?>"
this way i can get the videoId into the other page in which i embed the video :
$vid = $_GET['v'];
<iframe height ="432" width="760"  src="https://www.youtube.com/embed/<?= $vid; ?>">

but here comes the problem, i can't get any informations from this video, when i try like that :
$viewing = $youtube->videos->listVideos("snippet", ['id' => $vid]);
echo $viewing['snippet']['title'];

it returns me NULL
If someone can help me a bit, it would be awesome

A: I finally found the solution on my own.
as I want to retrieve information from a list of videos (even if in this case the list is composed of 1 element), I just had to use a foreach to retrieve like this :
<?php foreach($viewing['items'] as $view): ?>

<?= $view['snippet']['title']; ?>

<?= substr($view['snippet']['description'], 0, 430); ?>

                        <?php endforeach; ?>

Hope it can help


text:
Q: Content-Type of client request in SignalR (Silverlight client) Using SignalR Silverlight client, the request to server is not JSON. Actually, it is JSON but it is UrlEncoded as value of field "data", something like this (POST payload):
data=%7b%22I%22%3a%220%22%2c%22H%22%3a%22s3Hub%22%2c%22M%22%3a%22notify%22%2c%22A%22%3a...

with header
Content-Type: application/x-www-form-urlencoded

This is not what I can easily visually check in tools like Fiddler. The response is OK - JSON as I'd expected. How could I configure the client to use application/json as Content-Type?

A: You can't. Today we send a form urlencoded payload to the server. In a future version we might send via JSON. It's an implementation detail that really shouldn't affect your application.


text:
Q: Polygon cordinates to array I have an array of Polygons where each object looks like this
{'type': 'Polygon', 'coordinates': (((-98.03706782884247, 44.72279408402323), (-98.03706782884247, 44.71524098343729), (-98.02951472825653, 44.71524098343729), (-98.02951472825653, 44.72279408402323), (-98.03706782884247, 44.72279408402323)),)}

I need to convert the coordinates to an array and it should look like
[[[-98.03706782884247, 44.72279408402323],[-98.03706782884247, 44.71524098343729], [-98.02951472825653, 44.71524098343729], [-98.02951472825653, 44.72279408402323], [-98.03706782884247, 44.72279408402323]]]

Is there a pre-defined method which is available for polygons?

A: Since this is tagged shapely, have a look at shapely.geometry.asShape() to interpret a GeoJSON-like mapping as a shapely object
import numpy as np
from shapely.geometry import asShape

d = {'type': 'Polygon', 'coordinates': (((-98.03706782884247, 44.72279408402323), (-98.03706782884247, 44.71524098343729), (-98.02951472825653, 44.71524098343729), (-98.02951472825653, 44.72279408402323), (-98.03706782884247, 44.72279408402323)),)}

geom = asShape(d)

print(geom)

# LinearRings can be viewed as numpy arrays
print(np.asarray(geom.exterior))
for interior in geom.interiors:
    print(np.asarray(interior))

A: You could convert the coordinates key values to a list.
what_your_looking_for = list(your_json_object['coordinates'])


text: Q: Binary operations and Simple Solver I'm making a small demo to suggest Qt and OSG at my company to make some things easier to everyone working with me. But I need to do it rather quickly. I need a library for 2D and 3D binary operations on 2D and 3D geometry that will give a result mesh that can draw in OSG at the output. I also need a simple solver and mesher with which I could just define temperature on a tetrahedras within a mesh or nodes within a geometry and view a solution with OSG. I don't make solvers, I work with UI and some inner routines thus I need these libraries or something I can make a demo of a simple CAE software based on Qt and OSG. Can you suggest something?


text:
Q: How and why do the [[prototype]] slots of instances contain the Constructor.prototype at the point in time they were made (and don't get 'updated')? If you change Constructor.prototype, instances of Constructor you made before the change will 'store' the old Constructor.prototype in their [[prototype]] slot.

function F() {
}

o1 = new F();

F.prototype = {color: "red"};

o2 = new F();

console.log(o1) //it's [[proto]] contains old Object.prototype.
console.log(o2) //it's [[proto]] contains {color: "red"}.

I was under the impression the [[prototype]] slot references Object.prototype. How does it capture the old Object.prototype?

A: There's nothing magic about the [[proto]] slot, it's just like any other object property in that it can contain a reference to an object. It's not linked directly to the F.prototype slot, it just gets a reference to the value of that slot when the object is created.
So reassigning the F.prototype slot has no effect on the other references to the prototype object, just like any other object property:
o1 = { prop1: {a: 1}}
o2 = { prop1: o1.prop1 }
console.log(o2.prop1.a) // prints 1
o1.prop1 = {a: 2}
console.log(o2.prop1.a) // still prints 1

This is why we don't usually reasign F.prototype after we've created instances of the class. Instead, we assign to properties of F.prototype; since all the instances reference this object, modifying it in place affects all of them.
So in your example you would do:
F.prototype.color = "red";


text:
Q: Unable to call the WebMethod using $.ajax to pass JSON data I want to call the webmethod written in my VB Page. For that I've wrote the following code. But However it is directly going in error block and showing the message undefined.
JavaScript
function fnSaveReview(){
   var content = new Object();
   content.TableName = "BAChildProjects"
   content.ColumnName = "cIsQCApproved"
   content.ColumnValue = "Y"
   content.Refcolumn = "vWorkSpaceId"
   content.RefValue = $('#<%= HProjectId.ClientId%>').val();
   var JsonString=JSON.stringify(content);

   $.ajax({
          type: "POST",
          url: "frmBAProjectDefinition.aspx/UpdateFieldValues",
          data: JsonString,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function(data) {
               alert('Data Reviewed Successfully.');
          },
          failure: function(error) {
               alert(error);
          },
          error: function (data) {
               debugger ;
               alert(data.d);
          }
     });
}

VB.NET
<Web.Services.WebMethod()> _
    Public Shared Function UpdateFieldValues(ByVal JSONString As String) As String

        Dim objhelpDb As New WS_HelpDbTable.WS_HelpDbTable
        Dim objLambda As New WS_Lambda.WS_Lambda
        Dim eStr As String = String.Empty
        Dim ds_Save As New DataSet
        Try

            ds_Save.Tables.Add(JsonConvert.DeserializeObject(JSONString, GetType(System.Data.DataTable)))

            If Not objLambda.Save_UpdateFieldValues(WS_Lambda.DataObjOpenSaveModeEnum.DataObjOpenMode_Add, ds_Save, _
                                                 HttpContext.Current.Session(S_UserID), eStr) Then
                Return False
                Exit Function
            End If

            Return True
        Catch ex As Exception
            Return False
        End Try

    End Function

Console.log(data);
Object {readyState: 4, setRequestHeader: function, getAllResponseHeaders: function, getResponseHeader: function, overrideMimeType: function…}
abort: function (a){a=a||"abort",p&&p.abort(a),w(0,a);return this}
always: function (){return i.done.apply(i,arguments).fail.apply(i,arguments)}
complete: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
done: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
error: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
fail: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
getAllResponseHeaders: function (){return s===2?n:null}
getResponseHeader: function (a){var c;if(s===2){if(!o){o={};while(c=bJ.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c}
isRejected: function (){return!!e}
isResolved: function (){return!!e}
overrideMimeType: function (a){s||(d.mimeType=a);return this}
pipe: function (a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()}
progress: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
promise: function (a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}
readyState: 4
responseText: "
↵
↵        <title>The resource cannot be found.</title>
↵
↵
↵
↵
↵
↵
Server Error in '/BizNET' Application.

↵
↵
 The resource cannot be found.

↵
↵
↵
↵             Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable.  Please review the following URL and make sure that it is spelled correctly.
↵

↵
↵             Requested URL: /BizNET/frmBAProjectDefinition.aspx/UpdateFieldValues

↵
↵

↵
↵            Version Information: Microsoft .NET Framework Version:2.0.50727.5420; ASP.NET Version:2.0.50727.5459
↵
↵
↵
↵
↵
↵"
setRequestHeader: function (a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this}
state: function (){return e}
status: 404
statusCode: function (a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this}
statusText: "Not Found"
success: function (){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this}
then: function (a,b,c){i.done(a).fail(b).progress(c);return this}
__proto__: Object
undefined

My main problem is debugger is not even going to the WebMethod of VB.NET

A: This is an anonymous issue, I've too spent lot of time on this issue. I can resolve this issue the following manner.
Type I

*

*Clear the solution (Build -> Clear Solution)

*and then rebuild the solution (Build -> Rebuild Solution)

Type II

*

*Close the entire solution (File -> Exit)

*and then reopen your solution.

By the above steps, you can fix that issue.


text:
Q: Add remove filter an Array Javascript 1) I am looking for inbuilt jquery functions which would add/remove/get an item from an array.
Or a better way to do the same thing I have done below. Although below code works but I feel there should be some better way.
I am not very good at JavaScript so this code may look crappy :)
var items =
[
    {"Selected": false, "Text": "FirstElement", "Value": "1"},
    {"Selected": false, "Text": "SecondElement", "Value": "2"},
    {"Selected": false, "Text": "ThirdElement", "Value": "3"},
    {"Selected": false, "Text": "FourthElement", "Value": "4"}
]

function findItem(items, elementValue) {
    var item = {};

    if(elementValue == undefined || elementValue =="")
        return item;

    var i = $.map(items, function(n,i) { return i; }).length;

    while(i--){
        var temp = items[i].Value;
        if(elementValue == items[i].Value){
            item = {"Text": items[i].Text, "Value": items[i].Value};
        }
    }

    return item;
}

function removeItem(items, elementValue) {
    if(elementValue == undefined || elementValue =="")
        return items;

    var result = $.grep(items, function(e){
        return e.Value != elementValue;
    });

    return result;
}

function addItem(items, elementValue, elementText) {
    if(elementValue == undefined || elementValue =="")
        return items;

    var i = $.map(items, function(n,i) { return i; }).length;
    var x = i;

    var valueExists = false;

    while(i--){
        var temp = items[i].Value;
        if(elementValue == items[i].Value){
            valueExists = true;
        }
    }

    if(!valueExists){
        items[x] = {"Selected": false, "Value": elementValue, "Text": elementText};
    }

//I also need some sorting here on Value
    return items;
}

2) I am using
var tempItems = Object.assign({}, addItem(items, elementValue, elementText))

After adding an item I want the reference in a different temp object as I have to play around with master and filtered list. Is there a way I can add an item and get another instance of returned items.
Probably Object.assign is the root cause I am struggling with add/remove/get items.
Any suggestion is welcomed and appreciated. Thank You!

A: You can use built in javascript functions (not jquery :):
// Finding an item
items.find(function(item) { return item.Value == '3'})

// Removing/filtering out an item (returns a new copy)
items.filter(function(item) { return item.Value !== '3'})

To return a new copy of addItem, you could copy items inside the addItems function itself using Object.assign({}, ...).

A: You could actually use the native filter method that works on array. It would be something like this:

function findElement(items, elementValue) {
     let result = items.filter(function(item) {
      return item.Value === elementValue;
     })
     console.log(result); //should output the desired result
    }


text:
Q: Modified Shortest Path Problem Consider a directed, weighted graph $G=(V, E)$ where all edge weights are positive.  You have one magic star, which lets you traverse one edge of your choice for free.  In other words, you may change the weight of any one edge in $G$ to zero.
You are given two distinct vertices $s$ and $t$ in $G$.  Give an efficient algorithm to find a lowest cost path between vertices $s$ and $t$ given that $G$ is in adjacency list format.
My first attempt involves collecting all paths between $s$ and $t$, then for each path, finding the total path weight and the highest weighted edge.  I can then find the smallest path weight after subtracting the highest weighted edge from each path.  This seems inefficient, is there a better way?

A: Create a new graph $H$ which consists of two copies of graph $G$ (think of them being one over top of the other).  The edges are the edges in $G$ in each copy, plus a directed edge of weight $0$ from the bottom copy of $u$ to the top copy of $v$ whenever $(u,v)$ is an edge in $G$; taking such an edge is using the magic star.  Now apply Dijkstra from the bottom copy of $s$ to the top copy of $t$.  With standard data structures this takes $O(|E|\log|V|)$ time.


text:
Q: Error in starting the application through nodemon I am building a full stack app and after a lot of waste efforts I came here to ask you guys about the following error.
Plus, I do know what this error means as I have read about it but still I am unable to figure out the flaw that is present in somewhere.
Request you to help me out so that I can continue my work at pace.
Folder Architecture:
nearbywi-fi(Main Directory): bin, node_modules, public, server, app.js, bower.js
on, package.json, procfile, yarn-error.log, package-lock.json
Public: bootstrap, images, javascripts, stylesheets
server: controllers, routes, views
ERROR:
pinkman@pinkman:~/nearbywi-fi$ nodemon
[nodemon] 1.12.5
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node index.js`
module.js:544
throw err;
^

Error: Cannot find module '/home/pinkman/nearbywi-fi/index.js'
at Function.Module._resolveFilename (module.js:542:15)
at Function.Module._load (module.js:472:25)
at Function.Module.runMain (module.js:682:10)
at startup (bootstrap_node.js:191:16)
at bootstrap_node.js:613:3
[nodemon] app crashed - waiting for file changes before starting...

index.js
var express = require('express');
var router = express.Router();
var ctrlLocations = require('./controllers/locations');
var ctrlOthers = require('./controllers/others');

router.get('/', ctrlLocations.homelist);
router.get('/location', ctrlLocations.locationInfo);
router.get('/location/review/new', ctrlLocations.addReview);

router.get('/about', ctrlOthers.about);

module.exports = router;

app.js
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./server/routes/index');
var users = require('./server/routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'server', 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler

app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: err
    });
});
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
    message: err.message,
    error: {}
});
});

module.exports = app;

package.json
{
 "name": "Nearbywi-fi",
 "version": "v1.3.2",
 "private": true,
 "scripts": {
 "start": "node ./bin/www",
 "postinstall": "node -e \"try { require('fs').symlinkSync(require('path').resolve('node_modules/@bower_components'), 'bower_components', 'junction') } catch (e) { }\""},
  "dependencies": {
  "body-parser": "~1.18.2",
  "cookie-parser": "~1.4.3",
  "debug": "~2.6.9",
  "express": "~4.15.5",
  "jade": "^1.11.0",
  "jquery": "^3.2.1",
  "jstransformer": "^1.0.0",
  "morgan": "~1.9.0",
  "nodemon": "^1.12.5",
  "pug": "^2.0.0-rc.4",
  "serve-favicon": "~2.4.5"
  },
  "main": "index.js",
  "author": "vivek Gupta",
  "license": "MIT",
  "devDependencies": {
  "bootstrap": "^4.0.0-alpha.6"
  },
  "engines": {
  "yarn": ">= 1.0.0"
  }
 }

A: Using nodemon by itself will try and run index.js
In your case, this file is a route, not the main application, and it's not even in the root directory. So you want to run nodemon app.js
This is pretty much summed up in the log and your error:
[nodemon] starting `node index.js`
Error: Cannot find module '/home/pinkman/nearbywi-fi/index.js'

Edit:
Based on the package.json that you've provided, it seems the entry point should actually be "./bin/www", so you'll want "nodemon ./bin/www" instead.
Also, in your package.json, it says "main": "index.js", but this should be "main": "bin/www",


text:
Q: Cellcolor overwrites partial horizontal lines (\cline) So I need to make a colored table with multirows, together with the use of partial horizontal lines. I used \cline which does not work: the \cellcolor-command overwrites the line. This question told me to change it to \hhline which will not be overwritten by \cellcolor. Instead, \hhline overwrites the color.
To make it more clear:
Without color:
\documentclass{article}

\usepackage{colortbl}
\usepackage{multirow}

\begin{document}

  \begin{tabular}{|c|c|}
    \hline
    \bfseries ColumnOne & \bfseries ColumnTwo\\ \hline
    First data & 932\\ \hline
     & 239\\ \cline{2-2}  % or \hhline{|~|-|}
     & 137\\ \cline{2-2}  % or \hhline{|~|-|}
    \multirow{-3}{*}{More data} & 319\\ \hline
    Last data & 132\\ \hline
  \end{tabular}

\end{document}

With color:
Using \cline
\documentclass{article}

\usepackage{colortbl}
\usepackage{multirow}

\begin{document}

  \begin{tabular}{|>{\columncolor{red}}c|>{\columncolor{blue}}c|}
    \hline
    \bfseries ColumnOne & \bfseries ColumnTwo\\ \hline
    First data & 932\\ \hline
     & 239\\ \cline{2-2}
     & 137\\ \cline{2-2}
    \multirow{-3}{*}{More data} & 319\\ \hline
    Last data & 132\\ \hline
  \end{tabular}

\end{document}

Makes the lines in the right column disappear.
Using \hhline
\documentclass{article}

\usepackage{colortbl}
\usepackage{multirow}
\usepackage{hhline}

\begin{document}

  \begin{tabular}{|>{\columncolor{red}}c|>{\columncolor{blue}}c|}
    \hline
    \bfseries ColumnOne & \bfseries ColumnTwo\\ \hline
    First data & 932\\ \hline
     & 239\\ \hhline{|~|-|}
     & 137\\ \hhline{|~|-|}
    \multirow{-3}{*}{More data} & 319\\ \hline
    Last data & 132\\ \hline
  \end{tabular}

\end{document}

Creates white lines on the left column.
Is there any possible way on how to resolve this?

A: It's easy peasy with tblr environment of the new LaTeX3 package tabularray: multirow, cline and cellcolor work well together as expected. You can even replace \cline{2}'s with \hlines in the following code.
\documentclass{article}

\usepackage{xcolor}
\usepackage{tabularray}

\begin{document}

\begin{tblr}{
  colspec = {|Q[c,red7]|Q[c,blue7]|},
  cell{3}{1} = {r=3}{m}, % multirow
  row{1} = {font=\bfseries},
}
  \hline
    ColumnOne & ColumnTwo \\
  \hline
    First data & 932      \\
  \hline
    More data  & 239      \\
  \cline{2}
               & 137      \\
  \cline{2}
               & 319      \\
  \hline
    Last data  & 132      \\
  \hline
\end{tblr}

\end{document}

A: I'm sorry the interface is not brilliant here: But you can do this:
\documentclass{article}

\usepackage{colortbl}
\usepackage{multirow}
\usepackage{hhline}

\begin{document}

  \begin{tabular}{|>{\columncolor{red}}c|>{\columncolor{blue}}c|}
    \hline
    \bfseries ColumnOne & \bfseries ColumnTwo\\ \hline
    First data & 932\\ \hline
     & 239\\ \hhline{|>{\arrayrulecolor{red}}->{\arrayrulecolor{black}}|-|}
     & 137\\ \hhline{|>{\arrayrulecolor{red}}->{\arrayrulecolor{black}}|-|}
    \multirow{-3}{*}{More data} & 319\\ \hline
    Last data & 132\\ \hline
  \end{tabular}

\end{document}

Result:

A: The environment {NiceTabular} of nicematrix is a solution to that problem. The commands \cline are respected. Moreover, \cline{2} can be used as a syntactic shortcut for \cline{2-2}.
\documentclass{article}
\usepackage{xcolor}
\usepackage{nicematrix}

\begin{document}

\begin{NiceTabular}{|c|c|}
 \CodeBefore
   \columncolor{red!15}{1}
   \columncolor{blue!15}{2}
 \Body
  \hline
  \RowStyle{\bfseries}
  ColumnOne    & ColumnTwo \\ \hline
  First data             & 932 \\ \hline
  \Block{3-1}{More data} & 239 \\ \cline{2-2}
                         & 137 \\ \cline{2}
                         & 319 \\ \hline
  Last data              & 132 \\ \hline
\end{NiceTabular}

\end{document}

In fact, in this case, it's possible to simplify the code. With the key hvlines, all the horizontal and vertical rules will be drawn except in the blocks (created by the commands \Block of nicematrix). That's what we need.
\documentclass{article}
\usepackage{xcolor}
\usepackage{nicematrix}

\begin{document}

\begin{NiceTabular}{cc}[hvlines]
 \CodeBefore
   \columncolor{red!15}{1}
   \columncolor{blue!15}{2}
 \Body
   \RowStyle{\bfseries}
   ColumnOne              & ColumnTwo \\
   First data             & 932 \\
   \Block{3-1}{More data} & 239 \\
                          & 137 \\
                          & 319 \\
   Last data              & 132 \\
\end{NiceTabular}

\end{document}

A: I'm late to the party. And, to be sure, this fix is hacky and does not provide a solution without some fiddling. It did solve my problem fairly cleanly, and since I found this discussion, I'll add my answer here.
It appears that the color fill on the cell can be "tricked" into not covering up the cline by adding a carriage return and then taking away some vertical space, such that the line is left in place while the cell is slightly moved downward.
I had to compile your code a few times with the fix in place, to get the correct vertical spacing of -4.1mm, but it avoids a lot of rework if one needs a quick fix.
\documentclass{article}

\usepackage{colortbl}
\usepackage{multirow}

\begin{document}

  \begin{tabular}{|>{\columncolor{red}}c|>{\columncolor{blue}}c|}
    \hline
    \bfseries ColumnOne & \bfseries ColumnTwo\\ \hline
    First data & 932\\ \hline
     & 239\\ \cline{2-2}\\[-4.1mm]
     & 137\\ \cline{2-2}\\[-4.1mm]
    \multirow{-3}{*}{More data} & 319\\ \hline
    Last data & 132\\ \hline
  \end{tabular}

\end{document}

Result:


text:
Q: Static files from node module for client Im making a module for node.js and it is meant to serve javascript on the server side (like most nodejs modules) but also needs to enable a javascript file to be shared with a client (browser).
The client is served by an express server, dealing with the routes.
However I can't seem to find a way to server the javascript file from the node module, as a static file (without it having to, either be placed to a static folder by the user or having to parse the app as parameter to the module).
These are two posibilities that I'd like to avoid, as I noticed Socket.IO does not take these steps to share its socket.io-client code.
I looked into their code, to look in how they did it but can't seem to find it.
So I am wondering what the best way is, to share a static javascript file to a client from a node module.


text:
Q: Can I Replace A Deleted Key In The Registry Win XP SP3? I deleted the key HKEY_LOCAL_MACHINE/SYSTEM/CONTROLSET001/SERVICES/TUNMP
in order to uninstall the Miniport Adapter but found I still couldn't uninstall it.
the machine tells me it 'might be needed for bootup' or somesuch.
I was following these helpful instructions: http://forums.whirlpool.net.au/forum-replies.cfm?t=2139271#r13
Now I can't even start the adapter because of the registry hole and I seem to need it for somethings, for instance my Blaze DTV.
Can I somehow find a way to complete that uninstall?
Or Can I somehow replace this Key?  This key exists in Controlset003 and 4. Could I copy that over and have it work okay?

A: Unfortunately, when you delete a key from the windows registry, it's gone, there is no way to get it back. In your case, you might have success copying the similar key from one of the other control sets. If that fails, then hopefully you have a system backup, because the only other option would be a system rebuild


text:
Q: ShieldUI Grid Column min width Is there a property or a way to specify a minimum width for a column in a ShieldUI Grid?
$("#grid1").shieldGrid({
                dataSource: {
                    data: products,
                    sort: [ { path: "['Category']['CategoryName']", desc: true } ],
                    filter: { field: "ProductID", value: "1" }
                },
                rowHover: false,
                columns: [
                "ProductName",
                { field: "['Category']['CategoryName']", title: "CategoryName", format: "{0:c}", width: "330px" },
                { field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
                { field: "UnitsInStock", title: "Units In Stock", width: "130px" },
                { field: "Discontinued", width: "130px" },
                {
                    buttons: [
                            {
                                cls: "mybuttonCssClass",
                                caption: " Delete",
                                commandName: "details", // build in - edit, delete
                                click: function (rowIndex) {
                                    var grid = this;
                                    // custom actions ...
                                    console.log(grid.options);
                                    alert(rowIndex);
                                }
                            },
                        { commandName: "delete" } // delete, edit, expand
                    ]
                }
                ]
            });

A: Yes, there is a minWidth property, described like this:

The minimum width which the column can take when user resize it. In
  order to use this property the resizing of the grid needs to be turned
  on.


text:
Q: How can I get the data in the adapter and display it in the fragment? I have trouble getting data from adapter to fragment. I want to display some information through recycler view but the problem is that I have an error in getting the data arraylist in my VaccineAdapter.
This is my patientlogin class once the user login the account. I want to display his/her personal information as well as the his her vaccine history in a recyclerView order.
  @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_patient_login);

        name = findViewById(R.id.fullName);
        IdNo = findViewById(R.id.idNumber);

    }
    // Validate name
    private Boolean validateName(){
        String val = name.getText().toString();

        if(val.isEmpty()){
            name.setError("Field is Empty");
            return false;
        }else{
            name.setError(null);
            name.setEnabled(false);
            return true;
        }
    }

    // Validate ID number
    private Boolean validateIdNumber(){
        String val = IdNo.getText().toString();

        if(val.isEmpty()){
            IdNo.setError("Field cannot be empty");
            return false;
        }else{
            IdNo.setError(null);
            name.setEnabled(false);
            return true;
        }
    }

        public void loginPatient(View view){

        //validate Login info
        if (!validateName() | !validateIdNumber()) {
            return;
        }else{
            isUser();
        }
    }
    //if validation is correct
    private void isUser() {

        final String userEnteredIdNo = IdNo.getText().toString().trim();
        final String userEnteredName = name.getText().toString().trim();

        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Patient List");

        Query checkUser = reference.orderByChild("id").equalTo(userEnteredIdNo);

        checkUser.addListenerForSingleValueEvent(new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                if(dataSnapshot.exists()){
                    IdNo.setError(null);
                    IdNo.setEnabled(false);

                    String IdNoFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);

                    if(IdNoFromDB.equals(userEnteredName)){
                        IdNo.setError(null);
                        IdNo.setEnabled(false);

                        String imageFromDB = dataSnapshot.child(userEnteredIdNo).child("image").getValue(String.class);
                        String idFromDB = dataSnapshot.child(userEnteredIdNo).child("id").getValue(String.class);
                        String nameFromDB = dataSnapshot.child(userEnteredIdNo).child("name").getValue(String.class);
                        String ageFromDB = dataSnapshot.child(userEnteredIdNo).child("age").getValue(String.class);
                        String birthdayFromDB = dataSnapshot.child(userEnteredIdNo).child("birthday").getValue(String.class);
                        String addressFromDB = dataSnapshot.child(userEnteredIdNo).child("address").getValue(String.class);
                        String vaccineNameFromDB= dataSnapshot.child(userEnteredIdNo).child("vaccine_Name").getValue(String.class);
                        String institutionNameFromDB = dataSnapshot.child(userEnteredIdNo).child("institution_Name").getValue(String.class);
                        String vaccineDateFromDB = dataSnapshot.child(userEnteredIdNo).child("vaccine_Date").getValue(String.class);

                        PatientInfoHelperClass helperClass = new PatientInfoHelperClass(imageFromDB , idFromDB , nameFromDB , ageFromDB , birthdayFromDB ,addressFromDB ,vaccineNameFromDB , vaccineDateFromDB , institutionNameFromDB);

                        Intent intent = new Intent( patientLogin.this , patientProfile.class);
                        Bundle bundle = new Bundle();
                        bundle.putParcelable("helperClass", Parcels.wrap(helperClass));
                        intent.putExtras(bundle);

                        startActivity(intent);

                    }
                    else{
                        name.setError("No such name exists");
                        name.requestFocus();
                    }
                }
                else{
                    IdNo.setError("Wrong Id Number");
                    IdNo.requestFocus();
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        });
    }

This is my VaccineAdapter this is the adapter
 public VaccineAdapter(Context context, List<PatientInfoHelperClass> mList) {
        this.mList = mList;
        this.context = context;
    }

    @NonNull
    @Override
    public VaccineAdapter.MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.vaccine_list,parent,false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VaccineAdapter.MyViewHolder holder, int position) {
        //get data
        String vName = mList.get(position).getVaccine_Name();
        String iName = mList.get(position).getInstitution_Name();
        String vDate = mList.get(position).getVaccine_Date();

        //set data
        holder.vaccine_Name.setText(vName);
        holder.institution_Name.setText(iName);
        holder.vaccine_Date.setText(vDate);
    }

    @Override
    public int getItemCount() {
        return mList.size();
    }

class MyViewHolder extends RecyclerView.ViewHolder{
    TextView vaccine_Name, institution_Name, vaccine_Date;
    public MyViewHolder(View itemView){
        super(itemView);

        vaccine_Name = itemView.findViewById(R.id.vaccineName);
        institution_Name = itemView.findViewById(R.id.institutionName);
        vaccine_Date = itemView.findViewById(R.id.vaccineDate);
    }
}

This is my HistoryFragment connected to vaccine adapter where I want to display vaccine history in a recyclerview order.
RecyclerView recyclerView;
List<PatientInfoHelperClass> mList;
VaccineAdapter adapter;

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

public HistoryFragment() {
    // Required empty public constructor
}

/**
 * Use this factory method to create a new instance of
 * this fragment using the provided parameters.
 *
 * @param param1 Parameter 1.
 * @param param2 Parameter 2.
 * @return A new instance of fragment HistoryFragment.
 */
// TODO: Rename and change types and number of parameters
public static HistoryFragment newInstance(String param1, String param2) {

    HistoryFragment fragment = new HistoryFragment();
    Bundle bundle = new Bundle();
    bundle.putString(ARG_PARAM1, param1);
    bundle.putString(ARG_PARAM2, param2);
    fragment.setArguments(bundle);
    return fragment;

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    Bundle args = getActivity().getIntent().getExtras();
    View v = inflater.inflate(R.layout.fragment_history, container, false);
    recyclerView = v.findViewById(R.id.historyRecyclerView);
    mList = args.getParcelable("helperClass");
    adapter = new VaccineAdapter (getActivity(), mList);
    recyclerView.setAdapter(adapter);
    recyclerView.setHasFixedSize(true);
    recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));

    return v;
}

This is my PatientInfoHelperClass
   @Parcel
public class PatientInfoHelperClass {
    String image, name, id, age, birthday, address, institution_Name, vaccine_Name, vaccine_Date;

    public PatientInfoHelperClass() {
    }

    public PatientInfoHelperClass(String image, String name, String id, String age, String birthday, String address, String institution_Name, String vaccine_Name, String vaccine_Date) {
        this.image = image;
        this.name = name;
        this.id = id;
        this.age = age;
        this.birthday = birthday;
        this.address = address;
        this.institution_Name = institution_Name;
        this.vaccine_Name = vaccine_Name;
        this.vaccine_Date = vaccine_Date;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getBirthday() {
        return birthday;
    }

    public void setBirthday(String birthday) {
        this.birthday = birthday;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getInstitution_Name() {
        return institution_Name;
    }

    public void setInstitution_Name(String institution_Name) {
        this.institution_Name = institution_Name;
    }

    public String getVaccine_Name() {
        return vaccine_Name;
    }

    public void setVaccine_Name(String vaccine_Name) {
        this.vaccine_Name = vaccine_Name;
    }

    public String getVaccine_Date() {
        return vaccine_Date;
    }

    public void setVaccine_Date(String vaccine_Date) {
        this.vaccine_Date = vaccine_Date;
    }
}

I want to display the vaccine_Name, institution_Name, and vaccine_Date that I call in my adapter. but  don't know how to get the data from my vaccineAdapter to the HistoryFragment.
This is the error I get.
This is the design of the app. Once I clicked the history in the bottomNavigation the error will appear.

A: The error is in your fragment in the line mList = getActivity().getIntent();
The getIntent() method essentially returns intent not a list so you can't equate your mList to getActivity().getIntent()! getIntent() is used to pass data from activity to activity/fragment to activity. It returns the intent that started the activity.
Example of getIntent(),
If you start an Activity with some data,
String someData = "StackOverflow is awesome";
Intent intent = new Intent(context, SomeActivity.class);
intent.putExtra("someKey", someData);

you can retrieve this data using getIntent in the receiver activity:
 Intent intent = getIntent();
 if (intent != null)
     String gotBackSomeKey = intent.getExtra("someKey");

Now for passing data between fragments or from an activity to a fragment, we use Bundle.(Your case)
Example of Bundle,
 Bundle bundle = new Bundle();
 bundle.putParceableArrayList("YourListTag",mList);
 FragmentClass fragInfo = new FragmentClass();
 fragInfo.setArguments(bundle);
 transaction.replace(R.id.fragment_single, fragInfo);
 transaction.commit();

Make sure, unlike String or Int, you cannot pass List to your Bundle/Intent directly if you have a customized list. You will have to make your object of the list Parcelable or Serializable and then pass it like above example. You can read how to implement Parcelable/Serializable here
https://developer.android.com/reference/android/os/Parcelable
https://developer.android.com/reference/java/io/Serializable


text:
Q: Configure Auto-Number with initials related to another object I have an object called Project where stored the name of the project and its key, respectively:
My Project Name,  MPN
Then I have a direct child object called Sprint followed by Issue where I have a auto-number field and I need to select the project/ sprint related to it.
How could I customize my auto-number value based on the project related to it?
In other words:
Issue 1
Project Name: Sample Project Here
Project Key: SPH
Issue Name: SPH-0001
Issue 2
Project Name: Another Project There
Project Key: APT
Issue Name: APT-0001

A: It is not possible. Once configured, an auto-number field will generate auto-numbers in specified format with defined prefix. You can change the format, but it will affect only records created after the field change.
Possible solution of your problem could be a formula field that generate a text   prefix depending on the related object key/name.

A: Create an autonumber field with the 4 digit number.  In a separate, editable 'Issue Name' text field populate the project reference and the autonumber output either via a workflow rule or an Apex trigger.
Example: Autonumber value = 1024, project initals = SPH ==> the 'Issue Name' field will hold SPH-1024.


text:
Q: List of generic algorithms and data structures As part of a library project, I want to include a plethora of generic algorithms and data structures. This includes algorithms for searching and sorting, data structures like linked lists and binary trees, path-finding algorithms like A*... the works.
Basically, any generic algorithm or data structure you can think of that you think might be useful in such a library, please post or add it to the list. Thanks! (NOTE: Because there is no single right answer I've of course placed this in community wiki... and also, please don't suggest algorithms which are too specialized to be provided by a generic library)
The List:

*

*Data structures

*

*AVL tree

*B-tree

*

*B*-tree

*B+-tree

*Binary tree

*

*Binary heap

*Binary search tree

*Linked lists

*

*Singly linked list

*Doubly linked list

*Stack

*Queue

*Sorting algorithms

*

*Binary tree sort

*Bubble sort

*Heapsort

*Insertion sort

*Merge sort

*Quicksort

*Selection sort

*Searching algorithms

A: Have you tried Wikipedia?

*

*http://en.wikipedia.org/wiki/List_of_data_structures

*http://en.wikipedia.org/wiki/List_of_algorithms

A: Algorithms, Data Structures.
There's already a resource for this sort of material. I'm voting to close as not a real question.


text:
Q: Can we squeeze atoms? Lets consider few water molecules (or monoatomic noble gas or $H^+$ ions or electron gas) to be present inside a vessel, now if we enclose the vessel with certain hard material which could act as piston (assume that vessel is completely covered). Now, if we apply tremendous force on the piston (and no molecules are rushing out of the covering), can we watch the molecules to be squeezing?
I have heard about particle accelerators, where we start with electrons or protons, accelerate  them to high energy and smash into the target. In general, heavier the particle we want to produce, the higher must be energy of collision.
It seems that keeping the high energy particles stationary and then squeezing them (if possible) with highly accelerated pistons from either side, is better than colliding high energy particles head-on.
The problem in not using pistons, I must think, must be because of our inability to accelerate the massive pistons to a high extent as like accelerating particles itself. But, the head-on collision of pistons with high energy particles in between, will be better than head-on collision of particles itself, I think.
In case of head on collision of particles I think, we can accelerate them to high extent, but we can't expect effective collision.
Balancing both mass and acceleration of piston, can we have the same result, as we get in particle accelerators? If we can, can we avoid constructing those large particle accelerators like Stanford linear accelerator center (see the picture)?
Can we create such piston squeezer? I know there might be some difficulties? What can we do to overcome it?

Sometimes, I might have misunderstood, if so, pardon me and explain.

A:
Can we squeeze atoms?

Yes. High pressure changes the wavefunctions of electrons in atoms.  See for example Accurate Wavefuctions for the Confined Hydrogen Atom at High Pressures.
One effect of this is to increase the rate of electron capture by the nucleus, since s electrons will spend more time at/in the nucleus at high pressure.
See the lecture: Pressure and Chemistry Dependent Electron Capture for more information.
You definitely will not reach the energy levels of an accelerator however, as others have explained.

A: The experiments at LHC hit protons on each other at total energy of 7 TeV.
In comparison, a flying moscquito has a kinetic energy of

1 TeV: a trillion electronvolts, or 1.602×10−7 J, about the kinetic energy of a flying mosquito[12]

Could one collide two flying bees  of 3.5TeV kinetic energy and get a proton proton collision? i.e. give the total energy of the bee on a proton of each bee's proboscis?
The answer is "no" because macroscopic objects as the bee's proboscis have a surface composed by a very large number of atoms and the contact of the two proboscises will disperse the energy among those atoms much before it can reach one proton.
So it is true that macroscopic objects have a lot of kinetic energy in TeV, but to get it on an elementary particle level is a problem that has not been solved. Actually, maybe, with nanotechnology something might be devised, with magnetic fields and electric fields and God knows what, but certainly it will not be with pistons.

A: Degenerate matter is essentially squezed atoms.
It's not man-made,
But it is perfectly squeezed atoms, all of them.
And real squezed in the sense of static pressure.
In cores of stars, the pressure get's so high - only after the end of hydrogen burning - that the electrons can no longer stay withe the nuclei.
See Degenerate matter  and Electron degeneracy pressure
(That can even happen further regarding various subatomic particles,squeezing even what was left from the atoms)

A: Once you get up to relativistic speeds, there's no such thing as a "hard" material.  If you could get a pair of macroscopic pistons to collide at the location of a test atom, the dynamics of the collision would be dominated by collisions between the atoms in the pistons.
You can collide a light particle with a heavy nucleus — this is what's done at RHIC and LHC in the proton-gold and proton-lead collisions.  And you can collide two heavy nuclei — gold-gold, or lead-lead.  But the heavy-nucleus collisions are quite messy.  Even if you could make the beams dense enough to make a gold-proton-gold collision (which you couldn't), a gold nucleus has 197 nucleons in it; it'd be pretty tough to distinguish between a gold-gold collision involving 394 nucleons and a gold-proton-gold collision involving 395 nucleons.

A: The short answer would be not really (at least the way you've described it). The problem with any sort of physical piston is that high energy particles vibrate and will collide with the piston. This would have several undesirable effects. Firstly, it could damage the piston depending on how its made. Secondly, the collision would heat up the piston causing the particles to lose energy.
However, it is possible to use magnetic fields or lasers to confine particles. These paricles can be confined at high energies (essentially squeezed as you put it). This is the idea behind nuclear fusion. Note fusion particle energies tend to be on the order of $keV$ compared to $7~TeV$ at the LHC so it can't really tell you the same physics.
An alternative idea of squeezing atons would be a Bose-Einstien condensate or similar. This is almost the complete opposite in that the gas is cooled to very near absolute zero. In this case all the particles occupy the lowest possible quantum state so in one sense they are as squeezed as possible.


text:
Q: Making JettyRunner serve up static content (like CSS and JavaScript) with UTF-8 encoding I'm running a Java project via Jetty Runner (7.6.15). I've been trying to play with D3.js lately, and I needed to serve it up unminified in order to debug some mystery problem. Well, D3 has some non-Latin Unicode characters in some variable names (like var π = Math.PI).
When I try to use that unminified file, I get errors because my browser thinks the character encoding is ISO-8859-1 instead of UTF-8. Sure enough, the "Content-Type" header in the server response has no character set.
I'm launching Jetty Runner with LANG and LC_ALL both set to "en_US.UTF-8", and I'm passing a system property file.encoding set to "UTF-8" as well on the Java command line. That apparently is not enough. I can look at the source file on my host and it's definitely intact; in fact if I load the JavaScript file directly from the browser address bar and manually tell Firefox that it's Unicode, then it looks fine.
I'm not launching Jetty Runner with a configuration file because I have no idea how to do that. It seems to add an explicit ISO-8859-1 marker to the content type header on the main HTML page (it's a single-page application), and that of course overrides the <meta charset> tag in the document head.
So is there a way to do this? Sometimes I feel like I'm one of the only 12 people on earth who use Jetty Runner :)

A: This turned out to be as simple as a clause in my web.xml:
  <mime-mapping>
    <extension>js</extension>
    <mime-type>application/javascript; charset=UTF-8</mime-type>
  </mime-mapping>

I don't know how something this obvious escaped my notice. It doesn't even have much to do with Jetty per se.


text:
Q: How to convert an Object {} to an Array [] of key-value pairs in JavaScript I want to convert an object like this:
{"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}

into an array of key-value pairs like this:
[[1,5],[2,7],[3,0],[4,0]...].

How can I convert an Object to an Array of key-value pairs in JavaScript?

A: You can use Object.values([]), you might need this polyfill if you don't already:
const objectToValuesPolyfill = (object) => {
  return Object.keys(object).map(key => object[key]);
};
Object.values = Object.values || objectToValuesPolyfill;

https://stackoverflow.com/a/54822153/846348
Then you can just do:
var object = {1: 'hello', 2: 'world'};
var array = Object.values(object);

Just remember that arrays in js can only use numerical keys so if you used something else in the object then those will become `0,1,2...x``
It can be useful to remove duplicates for example if you have a unique key.
var obj = {};
object[uniqueKey] = '...';

A:
Object.entries() returns an array whose elements are arrays corresponding to the enumerable property [key, value] pairs found directly upon object. The ordering of the properties is the same as that given by looping over the property values of the object manually.
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries#Description

The Object.entries function returns almost the exact output you're asking for, except the keys are strings instead of numbers.

const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

console.log(Object.entries(obj));

If you need the keys to be numbers, you could map the result to a new array with a callback function that replaces the key in each pair with a number coerced from it.

const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

const toNumericPairs = input => {
    const entries = Object.entries(input);
    return entries.map(entry => Object.assign(entry, { 0: +entry[0] }));
}

console.log(toNumericPairs(obj));

I use an arrow function and Object.assign for the map callback in the example above so that I can keep it in one instruction by leveraging the fact that Object.assign returns the object being assigned to, and a single instruction arrow function's return value is the result of the instruction.
This is equivalent to:
entry => {
    entry[0] = +entry[0];
    return entry;
}

As mentioned by @TravisClarke in the comments, the map function could be shortened to:
entry => [ +entry[0], entry[1] ]

However, that would create a new array for each key-value pair, instead of modifying the existing array in place, hence doubling the amount of key-value pair arrays created. While the original entries array is still accessible, it and its entries will not be garbage collected.
Now, even though using our in-place method still uses two arrays that hold the key-value pairs (the input and the output arrays), the total number of arrays only changes by one. The input and output arrays aren't actually filled with arrays, but rather references to arrays and those references take up a negligible amount of space in memory.

*

*Modifying each key-value pair in-place results in a negligible amount of memory growth, but requires typing a few more characters.

*Creating a new array for each key-value pair results in doubling the amount of memory required, but requires typing a few less characters.

You could go one step further and eliminate growth altogether by modifying the entries array in-place instead of mapping it to a new array:

const obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

const toNumericPairs = input => {
  const entries = Object.entries(obj);
  entries.forEach(entry => entry[0] = +entry[0]);
  return entries;
}

console.log(toNumericPairs(obj));

A: With lodash, in addition to the answer provided above, you can also have the key in the output array.
Without the object keys in the output array
for:
const array = _.values(obj);

If obj is the following:
{ "art": { id: 1,  title: "aaaa" }, "fiction": { id: 22,  title: "7777"} }

Then array will be:
[ { id: 1, title: "aaaa" }, { id: 22, title: "7777" } ]

With the object keys in the output array
If you write instead ('genre' is a string that you choose):
const array= _.map(obj, (val, id) => {
    return { ...val, genre: key };
  });

You will get:
[
  { id: 1, title: "aaaa" , genre: "art"},
  { id: 22, title: "7777", genre: "fiction" }
]

A: If you are using lodash, it could be as simple as this:
var arr = _.values(obj);

A: You can use Object.keys() and map() to do this

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map((key) => [Number(key), obj[key]]);

console.log(result);

A: var obj = { "1": 5, "2": 7, "3": 0, "4": 0, "5": 0, "6": 0, "7": 0, "8": 0, "9": 0, "10": 0, "11": 0, "12": 0 }
let objectKeys = Object.keys(obj);

let answer = objectKeys.map(value => {
    return [value + ':' + obj[value]]
});

A: const persons = {
    john: { age: 23, year:2010},
    jack: { age: 22, year:2011},
    jenny: { age: 21, year:2012}
}
const resultArray = Object.keys(persons).map(index => {
    let person = persons[index];
    return person;
});

//use this for not indexed object to change array

A: To recap some of these answers now on 2018, where ES6 is the standard.
Starting with the object:
let const={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};

*

*Just blindly getting the values on an array, do not care of the keys:

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.values(obj));
//[9,8,7,6,5,4,3,2,1,0,5]

*

*Simple getting the pairs on an array:

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj));
//[["1",9],["2",8],["3",7],["4",6],["5",5],["6",4],["7",3],["8",2],["9",1],["10",0],["12",5]]

*

*Same as previous, but with numeric keys on each pair:

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).map(([k,v])=>[+k,v]));
//[[1,9],[2,8],[3,7],[4,6],[5,5],[6,4],[7,3],[8,2],[9,1],[10,0],[12,5]]

*

*Using the object property as key for a new array (could create sparse arrays):

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5};
console.log(Object.entries(obj).reduce((ini,[k,v])=>(ini[k]=v,ini),[]));
//[undefined,9,8,7,6,5,4,3,2,1,0,undefined,5]

This last method, it could also reorganize the array order depending the value of keys. Sometimes this could be the desired behaviour (sometimes don't). But the advantage now is that the values are indexed on the correct array slot, essential and trivial to do searches on it.

*

*Map instead of Array

Finally (not part of the original question, but for completeness), if you need to easy search using the key or the value, but you don't want sparse arrays, no duplicates and no reordering without the need to convert to numeric keys (even can access very complex keys), then array (or object) is not what you need. I will recommend Map instead:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
let r=new Map(Object.entries(obj));
r.get("4"); //6
r.has(8); //true

A: In Ecmascript 6,
var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

var res = Object.entries(obj);

console.log(res);

var obj = {
  "1": 5,
  "2": 7,
  "3": 0,
  "4": 0,
  "5": 0,
  "6": 0,
  "7": 0,
  "8": 0,
  "9": 0,
  "10": 0,
  "11": 0,
  "12": 0
};
var res = Object.entries(obj);
console.log(res);

A:
This is my solution, i have the same issue and its seems like this solution work for me.

yourObj = [].concat(yourObj);

A: or you can use Object.assign():

const obj = { 0: 1, 1: 2, 2: 3};
const arr = Object.assign([], obj);
console.log(arr)
// arr is [1, 2, 3]

A: The best way is to do:

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.entries(obj);

console.log(result);

Calling entries, as shown here, will return [key, value] pairs, as the caller requested.
Alternatively, you could call Object.values(obj), which would return only values.

A: Yet another solution if Object.entries won't work for you.

const obj = {
      '1': 29,
      '2': 42
    };
const arr = Array.from(Object.keys(obj), k=>[`${k}`, obj[k]]);
console.log(arr);

A: Here is a "new" way with es6 using the spread operator in conjunction with Object.entries.
const data = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

const dataSpread = [...Object.entries(data)];

// data spread value is now:
[
  [ '1', 5 ],  [ '2', 7 ],
  [ '3', 0 ],  [ '4', 0 ],
  [ '5', 0 ],  [ '6', 0 ],
  [ '7', 0 ],  [ '8', 0 ],
  [ '9', 0 ],  [ '10', 0 ],
  [ '11', 0 ], [ '12', 0 ]
]

A: you can use 3 methods convert object into array (reference for anyone not only for this question (3rd on is the most suitable,answer for this question)
Object.keys() ,Object.values(),andObject.entries()
examples for 3 methods
use Object.keys()
const text= {
    quote: 'hello world',
    author: 'unknown'
};

const propertyNames = Object.keys(text);

console.log(propertyNames);

result
[ 'quote', 'author' ]

use Object.values()
const propertyValues = Object.values(text);

console.log(propertyValues);

result
[ 'Hello world', 'unknown' ]

use Object.entires()
const propertyValues = Object.entires(text);

console.log(propertyValues);

result
[ [ 'quote', 'Hello world' ], [ 'author', 'unknown' ] ]

A: Use Object.keys and Array#map methods.

var obj = {
  "1": 5,
  "2": 7,
  "3": 0,
  "4": 0,
  "5": 0,
  "6": 0,
  "7": 0,
  "8": 0,
  "9": 0,
  "10": 0,
  "11": 0,
  "12": 0
};
// get all object property names
var res = Object.keys(obj)
  // iterate over them and generate the array
  .map(function(k) {
    // generate the array element
    return [+k, obj[k]];
  });

console.log(res);

A: Use Object.entries to get each element of Object in key & value format, then map through them like this:

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}

var res = Object.entries(obj).map(([k, v]) => ([Number(k), v]));

console.log(res);

But, if you are certain that the keys will be in progressive order you can use Object.values and Array#map to do something like this:

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0};

                        // idx is the index, you can use any logic to increment it (starts from 0)
let result = Object.values(obj).map((e, idx) => ([++idx, e]));

console.log(result);

A: Use for in
var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
            "8":0, "9":0, "10":0, "11":0, "12":0 };

var objectToArray = function(obj) {
    var _arr = [];

    for (var key in obj) {
        _arr.push([key, obj[key]]);
    }
    return _arr;
}

console.log(objectToArray(obj));

A: Recursive convert object to array
function is_object(mixed_var) {
    if (mixed_var instanceof Array) {
        return false;
    } else {
        return (mixed_var !== null) && (typeof( mixed_var ) == 'object');
    }
}

function objectToArray(obj) {
    var array = [], tempObject;
    for (var key in obj) {

        tempObject = obj[key];

        if (is_object(obj[key])) {
            tempObject = objectToArray(obj[key]);
        }
        array[key] = tempObject;
    }
    return array;
}

A: We can change Number to String type for Key like below:

var obj = {"1":5,"2":7,"3":0,"4":0,"5":0,"6":0,"7":0,"8":0,"9":0,"10":0,"11":0,"12":0}
var result = Object.keys(obj).map(function(key) {
  return [String(key), obj[key]];
});

console.log(result);

A: you can use _.castArray(obj).
example:

_.castArray({ 'a': 1 });
// => [{ 'a': 1 }]

A:

const obj={"1":9,"2":8,"3":7,"4":6,"5":5,"6":4,"7":3,"8":2,"9":1,"10":0,"12":5}

result = Object.entries(obj).map((key,value) => [parseInt(key,10), value])

console.log(result);


text:
Q: How to combine FFMPEG commands of multiple RTSP to HLS I have some of cameras with different RTSP url and I want to convert all of them from RTSP to HLS so as to show on my website. I'm using single command in Command prompt for each camera now.
Example:
ffmpeg -i "rtsp://admin:admin@192.168.1.2:554/Streaming/Channels/101" -hls_time 2 -hls_wrap 10 "camera1.m3u8"
ffmpeg -i "rtsp://admin:admin@192.168.1.2:554/Streaming/Channels/201" -hls_time 2 -hls_wrap 10 "camera2.m3u8"
ffmpeg -i "rtsp://admin:admin@192.168.1.2:554/Streaming/Channels/301" -hls_time 2 -hls_wrap 10 "camera3.m3u8"
I must run 3 commands in 3 Command prompt. Can I combine multiple commands into single command?


text:
Q: Java synchronize an external file Are there anyway to syncronize the reading and writing of a file between two process in Java?
I found FileLock, with this I can lock a file while it is writing, but I need to have a process polling for the reading, that is not efficient. I would like to simulate the semaphores, to make it efficient:
class Process<E> {
  private E e;

  private final Semaphore read = new Semaphore(0);
  private final Semaphore write = new Semaphore(1);

  public final void write(final E e) {
    write.acquire();
    this.e = e;
    read.release();
  }

  public final E read() {
    read.acquire();
    E e = this.e;
    write.release();
    return e;
  }
}

Are there anyway to do it with Filelock or other class?
Thanks in advance.

A: Forgotten about Java pipes? Like PipedInputStream and PipedOutputStream need to use different threads to efficiently exchange data.


text:
Q: Including Superagent as AMD I am a little confused about multiple ways of importing files in Javascript (script tag, RequireJS, Component - if it is another way to include files). In my project, I am using AMD with RequireJS.
Now, I want to use superagent library.
I donwnloaded superagent.js file, and I included it in some test pages using script tag. Then, I can use a require function (defined in superagent.js), and I definitely have access to superagent functions, if I write:
var request = require('superagent');

in my JS file.
Is there a way to use Superagent library in my poject, which is based on RequireJS? I hope to still use:
var request = require('superagent');

, but clearly it is not working.

A: You can try this:
require(["superagent"], function(superagent){
    console.log(superagent)
    // there your code
})

A: Eventually, I found a sort of workaround.
I used "component" version of the library (even if I have no precise idea of what is component, so any help in this sense is appreciated), and I envelope it in a classical define RequireJS, without explicitly using require, as args passed to defining function (I don't need a require function, because it is defined in the library itself).
define(function () {
.... [all library content]...
return require("superagent");

});

I just added first line, and return before last line of library (which was simply require("superagent")).
It seems to work, even if I remain confused about multiple ways to include JS files, and including JS libraries is nowaday every time an adventure...

A: This works for me :
Create a require.config.js file call it say bootstrap.js, within that  choose a simple name for superagent. It'll look something like:
requirejs.config({
   map: {},
  paths: {
    'superagent': 'libs/superagent/superagent',
  },
  shim: {},
  packages: []
});

require(['js/main/main']);

In your index.html point require.js to bootsrap.js
e.g.
Now in your modules use
define(
    ['superagent'],
    function(request) {
    }
);


text:
Q: Multiple MongoDb filters in C# To handle multiple MongoDb filters in C#, I had wrote below method;
        public string MultipleFilters(string collectionName, Dictionary<string, string> dictFilters)
        {
            var filter = Builders<BsonDocument>.Filter.Eq("", "");

            foreach (KeyValuePair<string, string> entry in dictFilters)
            {
                filter = filter & Builders<BsonDocument>.Filter.Eq(entry.Key, entry.Value);
            }

            var collection = this.database.GetCollection<BsonDocument>(collectionName);
            var document = collection.Find(filter).First();

            return document.ToJson();
        }

But it throws the error:
System.InvalidOperationException: 'Sequence contains no elements'

A: Builders<BsonDocument>.Filter.Eq("", "") is a valid MongoDB filter which tries to find a document with an empty key and empty value (example),
it's better to use Builders<BsonDocument>.Filter.Empty instead.
Also you're running .First() on after .Find() method so you're assuming that there's always at least one value. That's fine if you want Sequence contains no elements to be thrown when something goes wrong however you can try to handle that more gracefully by using .FirstOrDefault()


text:
Q: Sending email in Emacs programs Is there a way to build up an email message from a region or buffer, set up a recipient and then send a message in elisp code?
I've configured emacs to send mail via my gmail account  and I'd like to be able to send myself emails from elisp programs. The command used is message-mail.

A: Here's a wrapper for message-mail that prompts you for the 'to' and 'subject' lines:
(defun my-message-mail-region (b e to subject)
  "Send the current region in an email"
  (interactive "r\nsRecipient: \nsSubject: ")
  (let ((orig-buffer (current-buffer)))
    (message-mail to subject)
    (message-goto-body)
    (insert (save-excursion (set-buffer orig-buffer)
                            (buffer-substring-no-properties b e)))
    (message-send-and-exit)))


text:
Q: Conditional jump or move depends on uninitialised value(s) memory leak struct stat My homework consists of a C program which, for each argument in the command line creates a child process and writes in a pipe the following: if it is a file, the size, if it is a directory, the number of text files, otherwise a random number between 5 and 15. It works fine, but when running with valgrind, I get some memory leaks (32 bytes) for every process.
Here's the code:
typedef struct{    //defining a structure that holds the results organized.
    int value;
    char argument[100];
}result;
int main(int argc, char* argv[]){

int a2b[2],b2a[2],pid[argc-1];

pipe(a2b);pipe(b2a);

for (int i=1;i<argc;i++)
{
    pid[i]=fork(); //create argc - 1 processes
    if(pid[i]==0){
       close(b2a[0]); //close the unnecessary ends of pipes
       close(a2b[0]);
       close(a2b[1]);

       struct stat buf;
       char *filename = malloc(sizeof(char)*100);
       strcpy(filename, argv[i]);
       stat(filename,&buf);

       if((buf.st_mode & S_IFREG) == S_IFREG) { //checks if argument is a file
            //printf("%s is a file \n",argv[i]);
            int size= buf.st_size; //obtains the size
            printf("Writing size of file %s to pipe: %d\n",argv[i],size);
            result *r1 = malloc(sizeof(result));
            memset(r1,0,sizeof(result));
            strcpy(r1->argument,argv[i]);
            r1->value=size;
            write(b2a[1],r1,sizeof(result));
            free(r1);            //write the size to the pipe
         }

        else if((buf.st_mode & S_IFDIR) == S_IFDIR) { /// check if argument is a directory
            //printf("Dir: %s\n",argv[i]);
            char cmd[100];
            strcpy(cmd,"./files.sh "); //construct the shell command which is used
            strcat(cmd,argv[i]);
            FILE *f= popen(cmd,"r"); //run it and store the result
            char r[100];
            fgets(r,sizeof(int),f); // read the result and store it into a string
            //printf("%s in child\n",r);
            int pp=atoi(r);  // convert the string to an int
            printf("Writing number of text files in directory %s to pipe: %d\n",argv[i],pp);
            result *r2 = malloc(sizeof(result));
            memset(r2,0,sizeof(result));
            strcpy(r2->argument,argv[i]);
            r2->value=pp;
            write(b2a[1],r2,sizeof(result));
            // write(b2a[1],&pp,sizeof(int)); //write the number of text files to the pipe
            free(r2);
            fclose(f);
        }
        else {                                          //if the arg is neither a file or a directory
            srand (pid[i] ); //assign time as the seed of rand
            int random_number = 5 + rand()%11;
            printf("%s is neither, writing a random number in [5,15] to pipe: %d\n",argv[i],random_number);
            result *r3 = malloc(sizeof(result));
            memset(r3,0,sizeof(result));
            strcpy(r3->argument,argv[i]);
            r3->value=random_number;
            write(b2a[1],r3,sizeof(result));
            free(r3);
            //write(b2a[1],&random_number,sizeof(int)); // write the result to the pipe
        }
        free(filename);
        close(b2a[1]);
        exit(0);
    }
}

for (int i=1;i<argc;i++)
{
    wait(0); //wait for all the processes
}

for(int i = 1; i<argc ; i++){
    result k;
    read(b2a[0],&k,sizeof(result));
    printf("%s:  %d\n",k.argument,k.value); //read from the pipe the info about all arguments
}

close(a2b[0]); //close all the pipes
close(a2b[1]);
close(b2a[1]);
close(b2a[0]);
return 0;

}
The shell file which is used by the popen only echos the number of text files in the directory.
Valgrind shows me this:
==4647== Conditional jump or move depends on uninitialised value(s)
==4647==    at 0x100000893: main (homework.c:38)
==4647==  Uninitialised value was created by a stack allocation
==4647==    at 0x100000734: main (homework.c:18)

It also shows me this for lines 38 & 50, which are:
if((buf.st_mode & S_IFREG) == S_IFREG)
if((buf.st_mode & S_IFDIR) == S_IFDIR)

Also this:
==4647== HEAP SUMMARY:
==4647==     in use at exit: 35,727 bytes in 201 blocks
==4647==   total heap usage: 282 allocs, 81 frees, 42,059 bytes allocated

I can't figure out why I'm getting this.


text:
Q: Not able to render HighChart to a smaller div I am rendering a bunch of High Charts to different divs. I'm trying to achieve a scenario where I show all the charts on the home page in smaller divs. One screen shot of all the charts together. I couldn't do it dynamically so I have different files for all the charts. One copy of all 6 charts (graph1.js, graph2.js ..) named as tinygraph1.js, tinygraph2.js and so on. These tinygraphs are the smaller version of graphs.
My problem is I can render 3 of them all fine by just changing the variable   "renderTo".
renderTo: graph1 changedTo renderTo: tinygraph1

Its not working for 2 of the graphs when everything is exactly same as other four. Any suggestion/idea is appreciated.
If more details are required let me know. I have never used High Charts before so I apologize if I didnot explain properly.