Programs & Examples On #Genshi

Genshi is a Python library that provides an integrated set of components for parsing, generating, and processing HTML, XML or other textual content for output generation on the web.

Install pip in docker

An alternative is to use the Alpine Linux containers, e.g. python:2.7-alpine. They offer pip out of the box (and have a smaller footprint which leads to faster builds etc).

How do ports work with IPv6?

They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.

Extracting extension from filename in Python

With splitext there are problems with files with double extension (e.g. file.tar.gz, file.tar.bz2, etc..)

>>> fileName, fileExtension = os.path.splitext('/path/to/somefile.tar.gz')
>>> fileExtension 
'.gz'

but should be: .tar.gz

The possible solutions are here

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

Finding all cycles in a directed graph

If what you want is to find all elementary circuits in a graph you can use the EC algorithm, by JAMES C. TIERNAN, found on a paper since 1970.

The very original EC algorithm as I managed to implement it in php (hope there are no mistakes is shown below). It can find loops too if there are any. The circuits in this implementation (that tries to clone the original) are the non zero elements. Zero here stands for non-existence (null as we know it).

Apart from that below follows an other implementation that gives the algorithm more independece, this means the nodes can start from anywhere even from negative numbers, e.g -4,-3,-2,.. etc.

In both cases it is required that the nodes are sequential.

You might need to study the original paper, James C. Tiernan Elementary Circuit Algorithm

<?php
echo  "<pre><br><br>";

$G = array(
        1=>array(1,2,3),
        2=>array(1,2,3),
        3=>array(1,2,3)
);


define('N',key(array_slice($G, -1, 1, true)));
$P = array(1=>0,2=>0,3=>0,4=>0,5=>0);
$H = array(1=>$P, 2=>$P, 3=>$P, 4=>$P, 5=>$P );
$k = 1;
$P[$k] = key($G);
$Circ = array();


#[Path Extension]
EC2_Path_Extension:
foreach($G[$P[$k]] as $j => $child ){
    if( $child>$P[1] and in_array($child, $P)===false and in_array($child, $H[$P[$k]])===false ){
    $k++;
    $P[$k] = $child;
    goto EC2_Path_Extension;
}   }

#[EC3 Circuit Confirmation]
if( in_array($P[1], $G[$P[$k]])===true ){//if PATH[1] is not child of PATH[current] then don't have a cycle
    $Circ[] = $P;
}

#[EC4 Vertex Closure]
if($k===1){
    goto EC5_Advance_Initial_Vertex;
}
//afou den ksana theoreitai einai asfales na svisoume
for( $m=1; $m<=N; $m++){//H[P[k], m] <- O, m = 1, 2, . . . , N
    if( $H[$P[$k-1]][$m]===0 ){
        $H[$P[$k-1]][$m]=$P[$k];
        break(1);
    }
}
for( $m=1; $m<=N; $m++ ){//H[P[k], m] <- O, m = 1, 2, . . . , N
    $H[$P[$k]][$m]=0;
}
$P[$k]=0;
$k--;
goto EC2_Path_Extension;

#[EC5 Advance Initial Vertex]
EC5_Advance_Initial_Vertex:
if($P[1] === N){
    goto EC6_Terminate;
}
$P[1]++;
$k=1;
$H=array(
        1=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        2=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        3=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        4=>array(1=>0,2=>0,3=>0,4=>0,5=>0),
        5=>array(1=>0,2=>0,3=>0,4=>0,5=>0)
);
goto EC2_Path_Extension;

#[EC5 Advance Initial Vertex]
EC6_Terminate:
print_r($Circ);
?>

then this is the other implementation, more independent of the graph, without goto and without array values, instead it uses array keys, the path, the graph and circuits are stored as array keys (use array values if you like, just change the required lines). The example graph start from -4 to show its independence.

<?php

$G = array(
        -4=>array(-4=>true,-3=>true,-2=>true),
        -3=>array(-4=>true,-3=>true,-2=>true),
        -2=>array(-4=>true,-3=>true,-2=>true)
);


$C = array();


EC($G,$C);
echo "<pre>";
print_r($C);
function EC($G, &$C){

    $CNST_not_closed =  false;                          // this flag indicates no closure
    $CNST_closed        = true;                         // this flag indicates closure
    // define the state where there is no closures for some node
    $tmp_first_node  =  key($G);                        // first node = first key
    $tmp_last_node  =   $tmp_first_node-1+count($G);    // last node  = last  key
    $CNST_closure_reset = array();
    for($k=$tmp_first_node; $k<=$tmp_last_node; $k++){
        $CNST_closure_reset[$k] = $CNST_not_closed;
    }
    // define the state where there is no closure for all nodes
    for($k=$tmp_first_node; $k<=$tmp_last_node; $k++){
        $H[$k] = $CNST_closure_reset;   // Key in the closure arrays represent nodes
    }
    unset($tmp_first_node);
    unset($tmp_last_node);


    # Start algorithm
    foreach($G as $init_node => $children){#[Jump to initial node set]
        #[Initial Node Set]
        $P = array();                   // declare at starup, remove the old $init_node from path on loop
        $P[$init_node]=true;            // the first key in P is always the new initial node
        $k=$init_node;                  // update the current node
                                        // On loop H[old_init_node] is not cleared cause is never checked again
        do{#Path 1,3,7,4 jump here to extend father 7
            do{#Path from 1,3,8,5 became 2,4,8,5,6 jump here to extend child 6
                $new_expansion = false;
                foreach( $G[$k] as $child => $foo ){#Consider each child of 7 or 6
                    if( $child>$init_node and isset($P[$child])===false and $H[$k][$child]===$CNST_not_closed ){
                        $P[$child]=true;    // add this child to the path
                        $k = $child;        // update the current node
                        $new_expansion=true;// set the flag for expanding the child of k
                        break(1);           // we are done, one child at a time
            }   }   }while(($new_expansion===true));// Do while a new child has been added to the path

            # If the first node is child of the last we have a circuit
            if( isset($G[$k][$init_node])===true ){
                $C[] = $P;  // Leaving this out of closure will catch loops to
            }

            # Closure
            if($k>$init_node){                  //if k>init_node then alwaya count(P)>1, so proceed to closure
                $new_expansion=true;            // $new_expansion is never true, set true to expand father of k
                unset($P[$k]);                  // remove k from path
                end($P); $k_father = key($P);   // get father of k
                $H[$k_father][$k]=$CNST_closed; // mark k as closed
                $H[$k] = $CNST_closure_reset;   // reset k closure
                $k = $k_father;                 // update k
        }   } while($new_expansion===true);//if we don't wnter the if block m has the old k$k_father_old = $k;
        // Advance Initial Vertex Context
    }//foreach initial


}//function

?>

I have analized and documented the EC but unfortunately the documentation is in Greek.

How does `scp` differ from `rsync`?

There's a distinction to me that scp is always encrypted with ssh (secure shell), while rsync isn't necessarily encrypted. More specifically, rsync doesn't perform any encryption by itself; it's still capable of using other mechanisms (ssh for example) to perform encryption.

In addition to security, encryption also has a major impact on your transfer speed, as well as the CPU overhead. (My experience is that rsync can be significantly faster than scp.)

Check out this post for when rsync has encryption on.

Accept function as parameter in PHP

Just to add to the others, you can pass a function name:

function someFunc($a)
{
    echo $a;
}

function callFunc($name)
{
    $name('funky!');
}

callFunc('someFunc');

This will work in PHP4.

"React.Children.only expected to receive a single React element child" error when putting <Image> and <TouchableHighlight> in a <View>

I had this same error, even when I only had one child under the TouchableHighlight. The issue was that I had a few others commented out but incorrectly. Make sure you are commenting out appropriately: http://wesbos.com/react-jsx-comments/

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Vuejs: v-model array in multiple input

Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
  },_x000D_
  methods: {_x000D_
    addUser: function () {_x000D_
      this.users.push({ name: '',email:'' });_x000D_
    },_x000D_
    deleteUser: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.users.splice(index, 1);_x000D_
      if(index===0)_x000D_
      this.addUser()_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Add user</h1>_x000D_
  <div v-for="(user, index) in users">_x000D_
    <input v-model="user.name">_x000D_
    <input v-model="user.email">_x000D_
    <button @click="deleteUser(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addUser">_x000D_
    New User_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to include a sub-view in Blade templates?

When you use laravel modules, you may add the name's module:

@include('cimple::shared.posts_list')

Can't access RabbitMQ web management interface after fresh install

If on Windows and installed using chocolatey make sure firewall is allowing the default ports for it:

netsh advfirewall firewall add rule name="RabbitMQ Management" dir=in action=allow protocol=TCP localport=15672
netsh advfirewall firewall add rule name="RabbitMQ" dir=in action=allow protocol=TCP localport=5672

for the remote access.

Check if one list contains element from the other

To shorten Narendra's logic, you can use this:

boolean var = lis1.stream().anyMatch(element -> list2.contains(element));

Is it possible to disable floating headers in UITableView with UITableViewStylePlain?

This can be achieved by assigning the header view manually in the UITableViewController's viewDidLoad method instead of using the delegate's viewForHeaderInSection and heightForHeaderInSection. For example in your subclass of UITableViewController, you can do something like this:

- (void)viewDidLoad {
    [super viewDidLoad];

    UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    [headerView setBackgroundColor:[UIColor magentaColor]];
    [headerView setTextAlignment:NSTextAlignmentCenter];
    [headerView setText:@"Hello World"];
    [[self tableView] setTableHeaderView:headerView];
}

The header view will then disappear when the user scrolls. I don't know why this works like this, but it seems to achieve what you're looking to do.

COUNT DISTINCT with CONDITIONS

Try the following statement:

select  distinct A.[Tag],
     count(A.[Tag]) as TAG_COUNT,
     (SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
     from [TagTbl] AS A GROUP BY A.[Tag]

The first field will be the tag the second will be the whole count the third will be the positive ones count.

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

CROSS JOIN vs INNER JOIN in SQL

CROSS JOIN

AThe CROSS JOIN is meant to generate a Cartesian Product.

A Cartesian Product takes two sets A and B and generates all possible permutations of pair records from two given sets of data.

For instance, assuming you have the following ranks and suits database tables:

The ranks and suits tables

And the ranks has the following rows:

| name  | symbol | rank_value |
|-------|--------|------------|
| Ace   | A      | 14         |
| King  | K      | 13         |
| Queen | Q      | 12         |
| Jack  | J      | 11         |
| Ten   | 10     | 10         |
| Nine  | 9      |  9         |

While the suits table contains the following records:

| name    | symbol |
|---------|--------|
| Club    | ?      |
| Diamond | ?      |
| Heart   | ?      |
| Spade   | ?      |

As CROSS JOIN query like the following one:

SELECT
   r.symbol AS card_rank,
   s.symbol AS card_suit
FROM
   ranks r
CROSS JOIN
   suits s

will generate all possible permutations of ranks and suites pairs:

| card_rank | card_suit |
|-----------|-----------|
| A         | ?         |
| A         | ?         |
| A         | ?         |
| A         | ?         |
| K         | ?         |
| K         | ?         |
| K         | ?         |
| K         | ?         |
| Q         | ?         |
| Q         | ?         |
| Q         | ?         |
| Q         | ?         |
| J         | ?         |
| J         | ?         |
| J         | ?         |
| J         | ?         |
| 10        | ?         |
| 10        | ?         |
| 10        | ?         |
| 10        | ?         |
| 9         | ?         |
| 9         | ?         |
| 9         | ?         |
| 9         | ?         |

INNER JOIN

On the other hand, INNER JOIN does not return the Cartesian Product of the two joining data sets.

Instead, the INNER JOIN takes all elements from the left-side table and matches them against the records on the right-side table so that:

  • if no record is matched on the right-side table, the left-side row is filtered out from the result set
  • for any matching record on the right-side table, the left-side row is repeated as if there was a Cartesian Product between that record and all its associated child records on the right-side table.

For instance, assuming we have a one-to-many table relationship between a parent post and a child post_comment tables that look as follows:

One-to-many table relationship

Now, if the post table has the following records:

| id | title     |
|----|-----------|
| 1  | Java      |
| 2  | Hibernate |
| 3  | JPA       |

and the post_comments table has these rows:

| id | review    | post_id |
|----|-----------|---------|
| 1  | Good      | 1       |
| 2  | Excellent | 1       |
| 3  | Awesome   | 2       |

An INNER JOIN query like the following one:

SELECT
   p.id AS post_id,
   p.title AS post_title,
   pc.review  AS review
FROM post p
INNER JOIN post_comment pc ON pc.post_id = p.id

is going to include all post records along with all their associated post_comments:

| post_id | post_title | review    |
|---------|------------|-----------|
| 1       | Java       | Good      |
| 1       | Java       | Excellent |
| 2       | Hibernate  | Awesome   |

Basically, you can think of the INNER JOIN as a filtered CROSS JOIN where only the matching records are kept in the final result set.

Task not serializable: java.io.NotSerializableException when calling function outside closure only on classes not objects

Grega's answer is great in explaining why the original code does not work and two ways to fix the issue. However, this solution is not very flexible; consider the case where your closure includes a method call on a non-Serializable class that you have no control over. You can neither add the Serializable tag to this class nor change the underlying implementation to change the method into a function.

Nilesh presents a great workaround for this, but the solution can be made both more concise and general:

def genMapper[A, B](f: A => B): A => B = {
  val locker = com.twitter.chill.MeatLocker(f)
  x => locker.get.apply(x)
}

This function-serializer can then be used to automatically wrap closures and method calls:

rdd map genMapper(someFunc)

This technique also has the benefit of not requiring the additional Shark dependencies in order to access KryoSerializationWrapper, since Twitter's Chill is already pulled in by core Spark

How to import an existing directory into Eclipse?

There is no need to create a Java project and let unnecessary Java dependencies and libraries to cling into the project. The question is regarding importing an existing directory into eclipse

Suppose the directory is present in C:/harley/mydir. What you have to do is the following:

  • Create a new project (Right click on Project explorer, select New -> Project; from the wizard list, select General -> Project and click next.)

  • Give to the project the same name of your target directory (in this case mydir)

  • Uncheck Use default location and give the exact location, for example C:/harley/mydir

  • Click on Finish

You are done. I do it this way.

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

For anyone attempting to compile code from an external source that uses an automated build utility such as Make, to avoid having to track down the explicit gcc compilation calls you can set an environment variable. Enter on command prompt or put in .bashrc (or .bash_profile on Mac):

export CFLAGS="-std=c99"

Note that a similar solution applies if you run into a similar scenario with C++ compilation that requires C++ 11, you can use:

export CXXFLAGS="-std=c++11"

Sort matrix according to first column in R

The accepted answer works like a charm unless you're applying it to a vector. Since a vector is non-recursive, you'll get an error like this

$ operator is invalid for atomic vectors

You can use [ in that case

foo[order(foo["V1"]),]

How can I concatenate two arrays in Java?

Import java.util.*;

String array1[] = {"bla","bla"};
String array2[] = {"bla","bla"};

ArrayList<String> tempArray = new ArrayList<String>(Arrays.asList(array1));
tempArray.addAll(Arrays.asList(array2));
String array3[] = films.toArray(new String[1]); // size will be overwritten if needed

You could replace String by a Type/Class of your liking

Im sure this can be made shorter and better, but it works and im to lazy to sort it out further...

difference between variables inside and outside of __init__()

class foo(object):
    mStatic = 12

    def __init__(self):
        self.x = "OBj"

Considering that foo has no access to x at all (FACT)

the conflict now is in accessing mStatic by an instance or directly by the class .

think of it in the terms of Python's memory management :

12 value is on the memory and the name mStatic (which accessible from the class)

points to it .

c1, c2 = foo(), foo() 

this line makes two instances , which includes the name mStatic that points to the value 12 (till now) .

foo.mStatic = 99 

this makes mStatic name pointing to a new place in the memory which has the value 99 inside it .

and because the (babies) c1 , c2 are still following (daddy) foo , they has the same name (c1.mStatic & c2.mStatic ) pointing to the same new value .

but once each baby decides to walk alone , things differs :

c1.mStatic ="c1 Control"
c2.mStatic ="c2 Control"

from now and later , each one in that family (c1,c2,foo) has its mStatica pointing to different value .

[Please, try use id() function for all of(c1,c2,foo) in different sates that we talked about , i think it will make things better ]

and this is how our real life goes . sons inherit some beliefs from their father and these beliefs still identical to father's ones until sons decide to change it .

HOPE IT WILL HELP

How to programmatically close a JFrame

Based on the answers already provided here, this is the way I implemented it:

JFrame frame= new JFrame()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// frame stuffs here ...

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

The JFrame gets the event to close and upon closing, exits.

How can I link a photo in a Facebook album to a URL

You can only do this to you own photos. Due to recent upgrades, Facebook has made this more difficult. To do this, go to the album page where the photo is that you want to link to. You should see thumbnail images of the photos in the album. Hold down the "Control" or "Command" key while clicking the photo that you wish to link to. A new browser tab will open with the picture you clicked. Under the picture there is a URL that you can send to others to share the photo. You might have to have the privacy settings for that album set so that anyone can see the photos in that album. If you don't the person who clicks the link may have to be signed in and also be your "friend."

Here is an example of one of my photos: http://www.facebook.com/photo.php?pid=43764341&l=0d8a526a64&id=25502298 -it's my cat.

Update:

The link below the photo no longer appears. Once you open the photo in a new tab you can right click the photo (Control+click for Mac users) and click "Copy Image URL" or similar and then share this link. Based on my tests the person who clicks the link doesn't need to use Facebook. The photo will load without the Facebook interface. Like this - http://a1.sphotos.ak.fbcdn.net/hphotos-ak-ash4/189088_867367406856_25502298_43764341_1304758_n.jpg

How can I make sticky headers in RecyclerView? (Without external lib)

For those who may concern. Based on Sevastyan's answer, should you want to make it horizontal scroll. Simply change all getBottom() to getRight() and getTop() to getLeft()

Shrink to fit content in flexbox, or flex-basis: content workaround?

It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.

You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:

http://jsfiddle.net/2w157dyL/1/

However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.

So the fix is very, very simple - add enough right padding to account for the scrollbar:

http://jsfiddle.net/2w157dyL/2/

_x000D_
_x000D_
  main > section {_x000D_
    overflow-y: auto;_x000D_
    padding-right: 2em;_x000D_
  }
_x000D_
_x000D_
_x000D_

It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!

Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help

Division in Python 2.7. and 3.3

In Python 3, / is float division

In Python 2, / is integer division (assuming int inputs)

In both 2 and 3, // is integer division

(To get float division in Python 2 requires either of the operands be a float, either as 20. or float(20))

C# Select elements in list as List of string

List<string> empnames = (from e in emplist select e.Enaame).ToList();

Or

string[] empnames = (from e in emplist select e.Enaame).ToArray();

Etc...

Android Studio 3.0 Flavor Dimension Issue

If you have simple flavors (free/pro, demo/full etc.) then add to build.gradle file:

android {
...
flavorDimensions "version"
productFlavors {
        free{
            dimension "version"
            ...
            }
        pro{
            dimension "version"
            ...
            }
}

By dimensions you can create "flavors in flavors". Read more.

Why am I getting "IndentationError: expected an indented block"?

in python intended block mean there is every thing must be written in manner in my case I written it this way

 def btnClick(numbers):
 global operator
 operator = operator + str(numbers)
 text_input.set(operator)

Note.its give me error,until I written it in this way such that "giving spaces " then its giving me a block as I am trying to show you in function below code

def btnClick(numbers):
___________________________
|global operator
|operator = operator + str(numbers)
|text_input.set(operator)

Size of Matrix OpenCV

If you are using the Python wrappers, then (assuming your matrix name is mat):

  • mat.shape gives you an array of the type- [height, width, channels]

  • mat.size gives you the size of the array

Sample Code:

import cv2
mat = cv2.imread('sample.png')
height, width, channel = mat.shape[:3]
size = mat.size

How to align td elements in center

The best way to center content in a table (for example <video> or <img>) is to do the following:

_x000D_
_x000D_
<table width="100%" border="0" cellspacing="0" cellpadding="100%">
<tr>
<td>Video Tag 1 Here</td>
<td>Video Tag 2 Here</td>
</tr>
</table>
_x000D_
_x000D_
_x000D_

Show a number to two decimal places

Use the PHP number_format() function.

For example,

$num = 7234545423;
echo number_format($num, 2);

The output will be:

7,234,545,423.00

Asynchronous shell exec in PHP

On linux you can do the following:

$cmd = 'nohup nice -n 10 php -f php/file.php > log/file.log & printf "%u" $!';
$pid = shell_exec($cmd);

This will execute the command at the command prompty and then just return the PID, which you can check for > 0 to ensure it worked.

This question is similar: Does PHP have threading?

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

I setup a short cut (using windows) and set the target to

C:\Python36\pythonw.exe c:/python36/Lib/idlelib/idle.py

works great

Also found this works

with open('FILE.py') as f:
    exec(f.read())

Combine Multiple child rows into one row MYSQL

I appreciate the help, I do think I have found a solution if someone would comment on the effectiveness I would appreciate it. Essentially what I did is. I realize it is somewhat static in its implementation but I does what I need it to do (forgive incorrect syntax)

SELECT
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  Options1.Value
  Options2.Value
FROM ORDERED_ITEMS
LEFT JOIN (Ordered_Options as Options1)
    ON (Options1.Ordered_Item.ID = Ordered_Options.Ordered_Item_ID 
        AND Options1.Option_Number = 43)
LEFT JOIN (Ordered_Options as Options2)
    ON (Options2.Ordered_Item.ID = Ordered_Options.Ordered_Item_ID
        AND Options2.Option_Number = 44);

How to embed matplotlib in pyqt - for Dummies

It is not that complicated actually. Relevant Qt widgets are in matplotlib.backends.backend_qt4agg. FigureCanvasQTAgg and NavigationToolbar2QT are usually what you need. These are regular Qt widgets. You treat them as any other widget. Below is a very simple example with a Figure, Navigation and a single button that draws some random data. I've added comments to explain things.

import sys
from PyQt4 import QtGui

from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure

import random

class Window(QtGui.QDialog):
    def __init__(self, parent=None):
        super(Window, self).__init__(parent)

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # Just some button connected to `plot` method
        self.button = QtGui.QPushButton('Plot')
        self.button.clicked.connect(self.plot)

        # set the layout
        layout = QtGui.QVBoxLayout()
        layout.addWidget(self.toolbar)
        layout.addWidget(self.canvas)
        layout.addWidget(self.button)
        self.setLayout(layout)

    def plot(self):
        ''' plot some random stuff '''
        # random data
        data = [random.random() for i in range(10)]

        # create an axis
        ax = self.figure.add_subplot(111)

        # discards the old graph
        ax.clear()

        # plot data
        ax.plot(data, '*-')

        # refresh canvas
        self.canvas.draw()

if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)

    main = Window()
    main.show()

    sys.exit(app.exec_())

Edit:

Updated to reflect comments and API changes.

  • NavigationToolbar2QTAgg changed with NavigationToolbar2QT
  • Directly import Figure instead of pyplot
  • Replace deprecated ax.hold(False) with ax.clear()

Different class for the last element in ng-repeat

To elaborate on Paul's answer, this is the controller logic that coincides with the template code.

// HTML
<div class="row" ng-repeat="thing in things">
  <div class="well" ng-class="isLast($last)">
      <p>Data-driven {{thing.name}}</p>
  </div>
</div>

// CSS
.last { /* Desired Styles */}

// Controller
$scope.isLast = function(check) {
    var cssClass = check ? 'last' : null;
    return cssClass;
};

Its also worth noting that you really should avoid this solution if possible. By nature CSS can handle this, making a JS-based solution is unnecessary and non-performant. Unfortunately if you need to support IE8> this solution won't work for you (see MDN support docs).

CSS-Only Solution

// Using the above example syntax
.row:last-of-type { /* Desired Style */ }

How can I get the first two digits of a number?

You can convert your number to string and use list slicing like this:

int(str(number)[:2])

Output:

>>> number = 1520
>>> int(str(number)[:2])
15

How to add fixed button to the bottom right of page

This will be helpful for the right bottom rounded button

HTML :

      <a class="fixedButton" href>
         <div class="roundedFixedBtn"><i class="fa fa-phone"></i></div>
      </a>
    

CSS:

       .fixedButton{
            position: fixed;
            bottom: 0px;
            right: 0px; 
            padding: 20px;
        }
        .roundedFixedBtn{
          height: 60px;
          line-height: 80px;  
          width: 60px;  
          font-size: 2em;
          font-weight: bold;
          border-radius: 50%;
          background-color: #4CAF50;
          color: white;
          text-align: center;
          cursor: pointer;
        }
    

Here is jsfiddle link http://jsfiddle.net/vpthcsx8/11/

Python Image Library fails with message "decoder JPEG not available" - PIL

Same problem here, JPEG support available but still got IOError: decoder/encoder jpeg not available, except I use Pillow and not PIL.

I tried all of the above and more, but after many hours I realized that using sudo pip install does not work as I expected, in combination with virtualenv. Silly me.

Using sudo effectively launches the command in a new shell (my understanding of this may not be entirely correct) where the virtualenv is not activated, meaning that the packages will be installed in the global environment instead. (This messed things up, I think I had 2 different installations of Pillow.)

I cleaned things up, changed user to root and reinstalled in the virtualenv and now it works.
Hopefully this will help someone!

How do you reindex an array in PHP but with indexes starting from 1?

Here is the best way:

# Array
$array = array('tomato', '', 'apple', 'melon', 'cherry', '', '', 'banana');

that returns

Array
(
    [0] => tomato
    [1] => 
    [2] => apple
    [3] => melon
    [4] => cherry
    [5] => 
    [6] => 
    [7] => banana
)

by doing this

$array = array_values(array_filter($array));

you get this

Array
(
    [0] => tomato
    [1] => apple
    [2] => melon
    [3] => cherry
    [4] => banana
)

Explanation

array_values() : Returns the values of the input array and indexes numerically.

array_filter() : Filters the elements of an array with a user-defined function (UDF If none is provided, all entries in the input table valued FALSE will be deleted.)

Get Today's date in Java at midnight time

Here is a Java 8 based solution, using the new java.time package (Tutorial).

If you can use Java 8 objects in your code, use LocalDateTime:

LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();


If you require legacy dates, i.e. java.util.Date:

Convert the LocalDateTime you created above to Date using these conversions:

LocalDateTime -> ZonedDateTime -> Instant -> Date

  1. Call atZone(zone) with a specified time-zone (or ZoneId.systemDefault() for the system default time-zone) to create a ZonedDateTime object, adjusted for DST as needed.

    ZonedDateTime zdt = midnight.atZone(ZoneId.of("America/Montreal"));
    
  2. Call toInstant() to convert the ZonedDateTime to an Instant:

    Instant i = zdt.toInstant()
    
  3. Finally, call Date.from(instant) to convert the Instant to a Date:

    Date d1 = Date.from(i)
    


In summary it will look similar to this for you:

LocalDateTime now = LocalDateTime.now(); // current date and time
LocalDateTime midnight = now.toLocalDate().atStartOfDay();
Date d1 = Date.from(midnight.atZone(ZoneId.systemDefault()).toInstant());
Date d2 = Date.from(now.atZone(ZoneId.systemDefault()).toInstant());


See also section Legacy Date-Time Code (The Javaâ„¢ Tutorials) for interoperability of the new java.time functionality with legacy java.util classes.

static const vs #define

If you are defining a constant to be shared among all the instances of the class, use static const. If the constant is specific to each instance, just use const (but note that all constructors of the class must initialize this const member variable in the initialization list).

Create <div> and append <div> dynamically

    while(i<10){
               $('#Postsoutput').prepend('<div id="first'+i+'">'+i+'</div>');
               /* get the dynamic Div*/
               $('#first'+i).hide(1000);
               $('#first'+i).show(1000);
                i++;
                }

How to check if a text field is empty or not in swift

Swift 4.2

You can use a general function for your every textField just add the following function in your base controller

// White space validation.
func checkTextFieldIsNotEmpty(text:String) -> Bool
{
    if (text.trimmingCharacters(in: .whitespaces).isEmpty)
    {
        return false

    }else{
        return true
    }
}

Rotating a point about another point (2D)

If you rotate point (px, py) around point (ox, oy) by angle theta you'll get:

p'x = cos(theta) * (px-ox) - sin(theta) * (py-oy) + ox

p'y = sin(theta) * (px-ox) + cos(theta) * (py-oy) + oy

this is an easy way to rotate a point in 2D.

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

How can I prevent the TypeError: list indices must be integers, not tuple when copying a python list to a numpy array?

The variable mean_data is a nested list, in Python accessing a nested list cannot be done by multi-dimensional slicing, i.e.: mean_data[1,2], instead one would write mean_data[1][2].

This is becausemean_data[2] is a list. Further indexing is done recursively - since mean_data[2] is a list, mean_data[2][0] is the first index of that list.

Additionally, mean_data[:][0] does not work because mean_data[:] returns mean_data.

The solution is to replace the array ,or import the original data, as follows:

mean_data = np.array(mean_data)

numpy arrays (like MATLAB arrays and unlike nested lists) support multi-dimensional slicing with tuples.

How to retrieve the LoaderException property?

Another Alternative for those who are probing around and/or in interactive mode:

$Error[0].Exception.LoaderExceptions

Note: [0] grabs the most recent Error from the stack

Transparent background in JPEG image

JPG does not support a transparent background, you can easily convert it to a PNG which does support a transparent background by opening it in near any photo editor and save it as a.PNG

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

Oracle will try to recompile invalid objects as they are referred to. Here the trigger is invalid, and every time you try to insert a row it will try to recompile the trigger, and fail, which leads to the ORA-04098 error.

You can select * from user_errors where type = 'TRIGGER' and name = 'NEWALERT' to see what error(s) the trigger actually gets and why it won't compile. In this case it appears you're missing a semicolon at the end of the insert line:

INSERT INTO Users (userID, firstName, lastName, password)
VALUES ('how', 'im', 'testing', 'this trigger')

So make it:

CREATE OR REPLACE TRIGGER newAlert
AFTER INSERT OR UPDATE ON Alerts
  BEGIN
        INSERT INTO Users (userID, firstName, lastName, password)
        VALUES ('how', 'im', 'testing', 'this trigger');
  END;           
/

If you get a compilation warning when you do that you can do show errors if you're in SQL*Plus or SQL Developer, or query user_errors again.

Of course, this assumes your Users tables does have those column names, and they are all varchar2... but presumably you'll be doing something more interesting with the trigger really.

Java8: sum values from specific field of the objects in a list

Try:

int sum = lst.stream().filter(o -> o.field > 10).mapToInt(o -> o.field).sum();

Solution for "Fatal error: Maximum function nesting level of '100' reached, aborting!" in PHP

Another solution if you are running php script in CLI(cmd)

The php.ini file that needs edit is different in this case. In my WAMP installation the php.ini file that is loaded in command line is:

\wamp\bin\php\php5.5.12\php.ini

instead of \wamp\bin\apache\apache2.4.9\bin\php.ini which loads when php is run from browser

How to use Oracle's LISTAGG function with a unique filter?

below is undocumented and not recomended by oracle. and can not apply in function, show error

select wm_concat(distinct name) as names from demotable group by group_id

regards zia

What would be the best method to code heading/title for <ul> or <ol>, Like we have <caption> in <table>?

Would the use of <caption> be allowed?

<ul>
  <caption> Title of List </caption>
  <li> Item 1 </li>
  <li> Item 2 </li>
</ul>

How do I enable php to work with postgresql?

I have to add in httpd.conf this line (Windows):

LoadFile "C:/Program Files (x86)/PostgreSQL/8.3/bin/libpq.dll"

How to set underline text on textview?

you're almost there: just don't call toString() on Html.fromHtml() and you get a Spanned Object which will do the job ;)

tvHide.setText(Html.fromHtml("<p><u>Hide post</u></p>"));

How to make Java honor the DNS Caching Timeout?

This has obviously been fixed in newer releases (SE 6 and 7). I experience a 30 second caching time max when running the following code snippet while watching port 53 activity using tcpdump.

/**
 * http://stackoverflow.com/questions/1256556/any-way-to-make-java-honor-the-dns-caching-timeout-ttl
 *
 * Result: Java 6 distributed with Ubuntu 12.04 and Java 7 u15 downloaded from Oracle have
 * an expiry time for dns lookups of approx. 30 seconds.
 */

import java.util.*;
import java.text.*;
import java.security.*;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Test {
    final static String hostname = "www.google.com";
    public static void main(String[] args) {
        // only required for Java SE 5 and lower:
        //Security.setProperty("networkaddress.cache.ttl", "30");

        System.out.println(Security.getProperty("networkaddress.cache.ttl"));
        System.out.println(System.getProperty("networkaddress.cache.ttl"));
        System.out.println(Security.getProperty("networkaddress.cache.negative.ttl"));
        System.out.println(System.getProperty("networkaddress.cache.negative.ttl"));

        while(true) {
            int i = 0;
            try {
                makeRequest();
                InetAddress inetAddress = InetAddress.getLocalHost();
                System.out.println(new Date());
                inetAddress = InetAddress.getByName(hostname);
                displayStuff(hostname, inetAddress);
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
            try {
                Thread.sleep(5L*1000L);
            } catch(Exception ex) {}
            i++;
        }
    }

    public static void displayStuff(String whichHost, InetAddress inetAddress) {
        System.out.println("Which Host:" + whichHost);
        System.out.println("Canonical Host Name:" + inetAddress.getCanonicalHostName());
        System.out.println("Host Name:" + inetAddress.getHostName());
        System.out.println("Host Address:" + inetAddress.getHostAddress());
    }

    public static void makeRequest() {
        try {
            URL url = new URL("http://"+hostname+"/");
            URLConnection conn = url.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            InputStreamReader ird = new InputStreamReader(is);
            BufferedReader rd = new BufferedReader(ird);
            String res;
            while((res = rd.readLine()) != null) {
                System.out.println(res);
                break;
            }
            rd.close();
        } catch(Exception ex) {
            ex.printStackTrace();
        }
    }
}

Import Android volley to Android Studio

it also available on repository mavenCentral() ...

dependencies {
    // https://mvnrepository.com/artifact/com.android.volley/volley
    api "com.android.volley:volley:1.1.0'
}

Making Python loggers output all messages to stdout in addition to log file

Here is a solution based on the powerful but poorly documented logging.config.dictConfig method. Instead of sending every log message to stdout, it sends messages with log level ERROR and higher to stderr and everything else to stdout. This can be useful if other parts of the system are listening to stderr or stdout.

import logging
import logging.config
import sys

class _ExcludeErrorsFilter(logging.Filter):
    def filter(self, record):
        """Only returns log messages with log level below ERROR (numeric value: 40)."""
        return record.levelno < 40


config = {
    'version': 1,
    'filters': {
        'exclude_errors': {
            '()': _ExcludeErrorsFilter
        }
    },
    'formatters': {
        # Modify log message format here or replace with your custom formatter class
        'my_formatter': {
            'format': '(%(process)d) %(asctime)s %(name)s (line %(lineno)s) | %(levelname)s %(message)s'
        }
    },
    'handlers': {
        'console_stderr': {
            # Sends log messages with log level ERROR or higher to stderr
            'class': 'logging.StreamHandler',
            'level': 'ERROR',
            'formatter': 'my_formatter',
            'stream': sys.stderr
        },
        'console_stdout': {
            # Sends log messages with log level lower than ERROR to stdout
            'class': 'logging.StreamHandler',
            'level': 'DEBUG',
            'formatter': 'my_formatter',
            'filters': ['exclude_errors'],
            'stream': sys.stdout
        },
        'file': {
            # Sends all log messages to a file
            'class': 'logging.FileHandler',
            'level': 'DEBUG',
            'formatter': 'my_formatter',
            'filename': 'my.log',
            'encoding': 'utf8'
        }
    },
    'root': {
        # In general, this should be kept at 'NOTSET'.
        # Otherwise it would interfere with the log levels set for each handler.
        'level': 'NOTSET',
        'handlers': ['console_stderr', 'console_stdout', 'file']
    },
}

logging.config.dictConfig(config)

Call a stored procedure with parameter in c#

public void myfunction(){
        try
        {
            sqlcon.Open();
            SqlCommand cmd = new SqlCommand("sp_laba", sqlcon);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.ExecuteNonQuery();
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            sqlcon.Close();
        }
}

How to deep merge instead of shallow merge?

My use case for this was to merge default values into a configuration. If my component accepts a configuration object that has a deeply nested structure, and my component defines a default configuration, I wanted to set default values in my configuration for all configuration options that were not supplied.

Example usage:

export default MyComponent = ({config}) => {
  const mergedConfig = mergeDefaults(config, {header:{margins:{left:10, top: 10}}});
  // Component code here
}

This allows me to pass an empty or null config, or a partial config and have all of the values that are not configured fall back to their default values.

My implementation of mergeDefaults looks like this:

export default function mergeDefaults(config, defaults) {
  if (config === null || config === undefined) return defaults;
  for (var attrname in defaults) {
    if (defaults[attrname].constructor === Object) config[attrname] = mergeDefaults(config[attrname], defaults[attrname]);
    else if (config[attrname] === undefined) config[attrname] = defaults[attrname];
  }
  return config;
}


And these are my unit tests

import '@testing-library/jest-dom/extend-expect';
import mergeDefaults from './mergeDefaults';

describe('mergeDefaults', () => {
  it('should create configuration', () => {
    const config = mergeDefaults(null, { a: 10, b: { c: 'default1', d: 'default2' } });
    expect(config.a).toStrictEqual(10);
    expect(config.b.c).toStrictEqual('default1');
    expect(config.b.d).toStrictEqual('default2');
  });
  it('should fill configuration', () => {
    const config = mergeDefaults({}, { a: 10, b: { c: 'default1', d: 'default2' } });
    expect(config.a).toStrictEqual(10);
    expect(config.b.c).toStrictEqual('default1');
    expect(config.b.d).toStrictEqual('default2');
  });
  it('should not overwrite configuration', () => {
    const config = mergeDefaults({ a: 12, b: { c: 'config1', d: 'config2' } }, { a: 10, b: { c: 'default1', d: 'default2' } });
    expect(config.a).toStrictEqual(12);
    expect(config.b.c).toStrictEqual('config1');
    expect(config.b.d).toStrictEqual('config2');
  });
  it('should merge configuration', () => {
    const config = mergeDefaults({ a: 12, b: { d: 'config2' } }, { a: 10, b: { c: 'default1', d: 'default2' }, e: 15 });
    expect(config.a).toStrictEqual(12);
    expect(config.b.c).toStrictEqual('default1');
    expect(config.b.d).toStrictEqual('config2');
    expect(config.e).toStrictEqual(15);
  });
});

How to access property of anonymous type in C#?

The accepted answer correctly describes how the list should be declared and is highly recommended for most scenarios.

But I came across a different scenario, which also covers the question asked. What if you have to use an existing object list, like ViewData["htmlAttributes"] in MVC? How can you access its properties (they are usually created via new { @style="width: 100px", ... })?

For this slightly different scenario I want to share with you what I found out. In the solutions below, I am assuming the following declaration for nodes:

List<object> nodes = new List<object>();

nodes.Add(
new
{
    Checked = false,
    depth = 1,
    id = "div_1" 
});

1. Solution with dynamic

In C# 4.0 and higher versions, you can simply cast to dynamic and write:

if (nodes.Any(n => ((dynamic)n).Checked == false))
    Console.WriteLine("found a  not checked  element!");

Note: This is using late binding, which means it will recognize only at runtime if the object doesn't have a Checked property and throws a RuntimeBinderException in this case - so if you try to use a non-existing Checked2 property you would get the following message at runtime: "'<>f__AnonymousType0<bool,int,string>' does not contain a definition for 'Checked2'".

2. Solution with reflection

The solution with reflection works both with old and new C# compiler versions. For old C# versions please regard the hint at the end of this answer.

Background

As a starting point, I found a good answer here. The idea is to convert the anonymous data type into a dictionary by using reflection. The dictionary makes it easy to access the properties, since their names are stored as keys (you can access them like myDict["myProperty"]).

Inspired by the code in the link above, I created an extension class providing GetProp, UnanonymizeProperties and UnanonymizeListItems as extension methods, which simplify access to anonymous properties. With this class you can simply do the query as follows:

if (nodes.UnanonymizeListItems().Any(n => (bool)n["Checked"] == false))
{
    Console.WriteLine("found a  not checked  element!");
}

or you can use the expression nodes.UnanonymizeListItems(x => (bool)x["Checked"] == false).Any() as if condition, which filters implicitly and then checks if there are any elements returned.

To get the first object containing "Checked" property and return its property "depth", you can use:

var depth = nodes.UnanonymizeListItems()
             ?.FirstOrDefault(n => n.Contains("Checked")).GetProp("depth");

or shorter: nodes.UnanonymizeListItems()?.FirstOrDefault(n => n.Contains("Checked"))?["depth"];

Note: If you have a list of objects which don't necessarily contain all properties (for example, some do not contain the "Checked" property), and you still want to build up a query based on "Checked" values, you can do this:

if (nodes.UnanonymizeListItems(x => { var y = ((bool?)x.GetProp("Checked", true)); 
                                      return y.HasValue && y.Value == false;}).Any())
{
    Console.WriteLine("found a  not checked   element!");
}

This prevents, that a KeyNotFoundException occurs if the "Checked" property does not exist.


The class below contains the following extension methods:

  • UnanonymizeProperties: Is used to de-anonymize the properties contained in an object. This method uses reflection. It converts the object into a dictionary containing the properties and its values.
  • UnanonymizeListItems: Is used to convert a list of objects into a list of dictionaries containing the properties. It may optionally contain a lambda expression to filter beforehand.
  • GetProp: Is used to return a single value matching the given property name. Allows to treat not-existing properties as null values (true) rather than as KeyNotFoundException (false)

For the examples above, all that is required is that you add the extension class below:

public static class AnonymousTypeExtensions
{
    // makes properties of object accessible 
    public static IDictionary UnanonymizeProperties(this object obj)
    {
        Type type = obj?.GetType();
        var properties = type?.GetProperties()
               ?.Select(n => n.Name)
               ?.ToDictionary(k => k, k => type.GetProperty(k).GetValue(obj, null));
        return properties;
    }
    
    // converts object list into list of properties that meet the filterCriteria
    public static List<IDictionary> UnanonymizeListItems(this List<object> objectList, 
                    Func<IDictionary<string, object>, bool> filterCriteria=default)
    {
        var accessibleList = new List<IDictionary>();
        foreach (object obj in objectList)
        {
            var props = obj.UnanonymizeProperties();
            if (filterCriteria == default
               || filterCriteria((IDictionary<string, object>)props) == true)
            { accessibleList.Add(props); }
        }
        return accessibleList;
    }

    // returns specific property, i.e. obj.GetProp(propertyName)
    // requires prior usage of AccessListItems and selection of one element, because
    // object needs to be a IDictionary<string, object>
    public static object GetProp(this object obj, string propertyName, 
                                 bool treatNotFoundAsNull = false)
    {
        try 
        {
            return ((System.Collections.Generic.IDictionary<string, object>)obj)
                   ?[propertyName];
        }
        catch (KeyNotFoundException)
        {
            if (treatNotFoundAsNull) return default(object); else throw;
        }
    }
}

Hint: The code above is using the null-conditional operators, available since C# version 6.0 - if you're working with older C# compilers (e.g. C# 3.0), simply replace ?. by . and ?[ by [ everywhere (and do the null-handling traditionally by using if statements or catch NullReferenceExceptions), e.g.

var depth = nodes.UnanonymizeListItems()
            .FirstOrDefault(n => n.Contains("Checked"))["depth"];

As you can see, the null-handling without the null-conditional operators would be cumbersome here, because everywhere you removed them you have to add a null check - or use catch statements where it is not so easy to find the root cause of the exception resulting in much more - and hard to read - code.

If you're not forced to use an older C# compiler, keep it as is, because using null-conditionals makes null handling much easier.

Note: Like the other solution with dynamic, this solution is also using late binding, but in this case you're not getting an exception - it will simply not find the element if you're referring to a non-existing property, as long as you keep the null-conditional operators.

What might be useful for some applications is that the property is referred to via a string in solution 2, hence it can be parameterized.

sql: check if entry in table A exists in table B

The classical answer that works in almost every environment is

SELECT ID, Name, blah, blah
FROM TableB TB
LEFT JOIN TableA TA
ON TB.ID=TA.ID
WHERE TA.ID IS NULL

sometimes NOT EXISTS may be not implemented (not working).

Rename all files in a folder with a prefix in a single command

Also works for items with spaces and ignores directories

for f in *; do [[ -f "$f" ]] && mv "$f" "unix_$f"; done

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Assuming that your search is stylus photo 2100. Try the following example is using RLIKE.

SELECT * FROM `buckets` WHERE `bucketname` RLIKE REPLACE('stylus photo 2100', ' ', '+.*');

EDIT

Another way is to use FULLTEXT index on bucketname and MATCH ... AGAINST syntax in your SELECT statement. So to re-write the above example...

SELECT * FROM `buckets` WHERE MATCH(`bucketname`) AGAINST (REPLACE('stylus photo 2100', ' ', ','));

In plain English, what does "git reset" do?

Remember that in git you have:

  • the HEAD pointer, which tells you what commit you're working on
  • the working tree, which represents the state of the files on your system
  • the staging area (also called the index), which "stages" changes so that they can later be committed together

Please include detailed explanations about:

--hard, --soft and --merge;

In increasing order of dangerous-ness:

  • --soft moves HEAD but doesn't touch the staging area or the working tree.
  • --mixed moves HEAD and updates the staging area, but not the working tree.
  • --merge moves HEAD, resets the staging area, and tries to move all the changes in your working tree into the new working tree.
  • --hard moves HEAD and adjusts your staging area and working tree to the new HEAD, throwing away everything.

concrete use cases and workflows;

  • Use --soft when you want to move to another commit and patch things up without "losing your place". It's pretty rare that you need this.

--

# git reset --soft example
touch foo                            // Add a file, make some changes.
git add foo                          // 
git commit -m "bad commit message"   // Commit... D'oh, that was a mistake!
git reset --soft HEAD^               // Go back one commit and fix things.
git commit -m "good commit"          // There, now it's right.

--

  • Use --mixed (which is the default) when you want to see what things look like at another commit, but you don't want to lose any changes you already have.

  • Use --merge when you want to move to a new spot but incorporate the changes you already have into that the working tree.

  • Use --hard to wipe everything out and start a fresh slate at the new commit.

How to resolve ORA 00936 Missing Expression Error?

Remove the coma at the end of your SELECT statement (VALUE,), and also remove the one at the end of your FROM statement (rrf b,)

When does System.gc() do something?

If you use direct memory buffers, the JVM doesn't run the GC for you even if you are running low on direct memory.

If you call ByteBuffer.allocateDirect() and you get an OutOfMemoryError you can find this call is fine after triggering a GC manually.

Does Django scale?

You can definitely run a high-traffic site in Django. Check out this pre-Django 1.0 but still relevant post here: http://menendez.com/blog/launching-high-performance-django-site/

POST request with a simple string in body with Alamofire

Based on Illya Krit's answer

Details

  • Xcode Version 10.2.1 (10E1001)
  • Swift 5
  • Alamofire 4.8.2

Solution

import Alamofire

struct BodyStringEncoding: ParameterEncoding {

    private let body: String

    init(body: String) { self.body = body }

    func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {
        guard var urlRequest = urlRequest.urlRequest else { throw Errors.emptyURLRequest }
        guard let data = body.data(using: .utf8) else { throw Errors.encodingProblem }
        urlRequest.httpBody = data
        return urlRequest
    }
}

extension BodyStringEncoding {
    enum Errors: Error {
        case emptyURLRequest
        case encodingProblem
    }
}

extension BodyStringEncoding.Errors: LocalizedError {
    var errorDescription: String? {
        switch self {
            case .emptyURLRequest: return "Empty url request"
            case .encodingProblem: return "Encoding problem"
        }
    }
}

Usage

Alamofire.request(url, method: .post, parameters: nil, encoding: BodyStringEncoding(body: text), headers: headers).responseJSON { response in
     print(response)
}

Can I compile all .cpp files in src/ to .o's in obj/, then link to binary in ./?

Makefile part of the question

This is pretty easy, unless you don't need to generalize try something like the code below (but replace space indentation with tabs near g++)

SRC_DIR := .../src
OBJ_DIR := .../obj
SRC_FILES := $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES := $(patsubst $(SRC_DIR)/%.cpp,$(OBJ_DIR)/%.o,$(SRC_FILES))
LDFLAGS := ...
CPPFLAGS := ...
CXXFLAGS := ...

main.exe: $(OBJ_FILES)
   g++ $(LDFLAGS) -o $@ $^

$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp
   g++ $(CPPFLAGS) $(CXXFLAGS) -c -o $@ $<

Automatic dependency graph generation

A "must" feature for most make systems. With GCC in can be done in a single pass as a side effect of the compilation by adding -MMD flag to CXXFLAGS and -include $(OBJ_FILES:.o=.d) to the end of the makefile body:

CXXFLAGS += -MMD
-include $(OBJ_FILES:.o=.d)

And as guys mentioned already, always have GNU Make Manual around, it is very helpful.

Fatal error: unexpectedly found nil while unwrapping an Optional values

I had the same problem on Xcode 7.3. My solution was to make sure my cells had the correct reuse identifiers. Under the table view section set the table view cell to the corresponding identifier name you are using in the program, make sure they match.

Understanding the ngRepeat 'track by' expression

If you are working with objects track by the identifier(e.g. $index) instead of the whole object and you reload your data later, ngRepeat will not rebuild the DOM elements for items it has already rendered, even if the JavaScript objects in the collection have been substituted for new ones.

C# 30 Days From Todays Date

You need to store the first run time of the program in order to do this. How I'd probably do it is using the built in application settings in visual studio. Make one called InstallDate which is a User Setting and defaults to DateTime.MinValue or something like that (e.g. 1/1/1900).

Then when the program is run the check is simple:

if (appmode == "trial")
{
  // If the FirstRunDate is MinValue, it's the first run, so set this value up
  if (Properties.Settings.Default.FirstRunDate == DateTime.MinValue)
  {
    Properties.Settings.Default.FirstRunDate = DateTime.Now;
    Properties.Settings.Default.Save(); 
  }

  // Now check whether 30 days have passed since the first run date
  if (Properties.Settings.Default.FirstRunDate.AddMonths(1) < DateTime.Now)
  {
    // Do whatever you want to do on expiry (exception message/shut down/etc.)
  }
}

User settings are stored in a pretty weird location (something like C:\Documents and Settings\YourName\Local Settings\Application Data) so it will be pretty hard for average joe to find it anyway. If you want to be paranoid, just encrypt the date before saving it to settings.

EDIT: Sigh, misread the question, not as complex as I thought >.>

Why is `input` in Python 3 throwing NameError: name... is not defined

You're running your Python 3 code with a Python 2 interpreter. If you weren't, your print statement would throw up a SyntaxError before it ever prompted you for input.

The result is that you're using Python 2's input, which tries to eval your input (presumably sdas), finds that it's invalid Python, and dies.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Can't drop table: A foreign key constraint fails

Use show create table tbl_name to view the foreign keys

You can use this syntax to drop a foreign key:

ALTER TABLE tbl_name DROP FOREIGN KEY fk_symbol

There's also more information here (see Frank Vanderhallen post): http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

Should functions return null or an empty object?

I agree with most posts here, which tend towards null.

My reasoning is that generating an empty object with non-nullable properties may cause bugs. For example, an entity with an int ID property would have an initial value of ID = 0, which is an entirely valid value. Should that object, under some circumstance, get saved to database, it would be a bad thing.

For anything with an iterator I would always use the empty collection. Something like

foreach (var eachValue in collection ?? new List<Type>(0))

is code smell in my opinion. Collection properties shouldn't be null, ever.

An edge case is String. Many people say, String.IsNullOrEmpty isn't really necessary, but you cannot always distinguish between an empty string and null. Furthermore, some database systems (Oracle) won't distinguish between them at all ('' gets stored as DBNULL), so you're forced to handle them equally. The reason for that is, most string values either come from user input or from external systems, while neither textboxes nor most exchange formats have different representations for '' and null. So even if the user wants to remove a value, he cannot do anything more than clearing the input control. Also the distinction of nullable and non-nullable nvarchar database fields is more than questionable, if your DBMS is not oracle - a mandatory field that allows '' is weird, your UI would never allow this, so your constraints do not map. So the answer here, in my opinion is, handle them equally, always.

Concerning your question regarding exceptions and performance: If you throw an exception which you cannot handle completely in your program logic, you have to abort, at some point, whatever your program is doing, and ask the user to redo whatever he just did. In that case, the performance penalty of a catch is really the least of your worries - having to ask the user is the elephant in the room (which means re-rendering the whole UI, or sending some HTML through the internet). So if you don't follow the anti-pattern of "Program Flow with Exceptions", don't bother, just throw one if it makes sense. Even in borderline cases, such as "Validation Exception", performance is really not an issue, since you have to ask the user again, in any case.

Using FFmpeg in .net?

GPL-compiled ffmpeg can be used from non-GPL program (commercial project) only if it is invoked in the separate process as command line utility; all wrappers that are linked with ffmpeg library (including Microsoft's FFMpegInterop) can use only LGPL build of ffmpeg.

You may try my .NET wrapper for FFMpeg: Video Converter for .NET (I'm an author of this library). It embeds FFMpeg.exe into the DLL for easy deployment and doesn't break GPL rules (FFMpeg is NOT linked and wrapper invokes it in the separate process with System.Diagnostics.Process).

How to calculate an angle from three points?

_x000D_
_x000D_
function p(x, y) {return {x,y}}_x000D_
_x000D_
function normaliseToInteriorAngle(angle) {_x000D_
 if (angle < 0) {_x000D_
  angle += (2*Math.PI)_x000D_
 }_x000D_
 if (angle > Math.PI) {_x000D_
  angle = 2*Math.PI - angle_x000D_
 }_x000D_
 return angle_x000D_
}_x000D_
_x000D_
function angle(p1, center, p2) {_x000D_
 const transformedP1 = p(p1.x - center.x, p1.y - center.y)_x000D_
 const transformedP2 = p(p2.x - center.x, p2.y - center.y)_x000D_
_x000D_
 const angleToP1 = Math.atan2(transformedP1.y, transformedP1.x)_x000D_
 const angleToP2 = Math.atan2(transformedP2.y, transformedP2.x)_x000D_
_x000D_
 return normaliseToInteriorAngle(angleToP2 - angleToP1)_x000D_
}_x000D_
_x000D_
function toDegrees(radians) {_x000D_
 return 360 * radians / (2 * Math.PI)_x000D_
}_x000D_
_x000D_
console.log(toDegrees(angle(p(-10, 0), p(0, 0), p(0, -10))))
_x000D_
_x000D_
_x000D_

What is C# equivalent of <map> in C++?

Take a look at the Dictionary class in System::Collections::Generic.

Dictionary<myComplex, int> myMap = new Dictionary<myComplex, int>();

Simplest/cleanest way to implement a singleton in JavaScript

You did not say "in the browser". Otherwise, you can use Node.js modules. These are the same for each require call. Basic example:

The contents of foo.js:

const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);

The contents of circle.js:

const PI = Math.PI;

exports.area = (r) => PI * r * r;

exports.circumference = (r) => 2 * PI * r;

Note that you cannot access circle.PI, as it is not exported.

While this does not work in the browser, it is simple and clean.

Uninstalling an MSI file from the command line without using msiexec

I would try the following syntax - it works for me.

msiexec /x filename.msi /q 

Android Device Chooser -- device not showing up

One thing to do is swap cables. I was using one that was only capable of charging!

Get all object attributes in Python?

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

How to detect the character encoding of a text file?

Several answers are here but nobody has posted usefull code.

Here is my code that detects all encodings that Microsoft detects in Framework 4 in the StreamReader class.

Obviously you must call this function immediately after opening the stream before reading anything else from the stream because the BOM are the first bytes in the stream.

This function requires a Stream that can seek (for example a FileStream). If you have a Stream that cannot seek you must write a more complicated code that returns a Byte buffer with the bytes that have already been read but that are not BOM.

/// <summary>
/// UTF8    : EF BB BF
/// UTF16 BE: FE FF
/// UTF16 LE: FF FE
/// UTF32 BE: 00 00 FE FF
/// UTF32 LE: FF FE 00 00
/// </summary>
public static Encoding DetectEncoding(Stream i_Stream)
{
    if (!i_Stream.CanSeek || !i_Stream.CanRead)
        throw new Exception("DetectEncoding() requires a seekable and readable Stream");

    // Try to read 4 bytes. If the stream is shorter, less bytes will be read.
    Byte[] u8_Buf = new Byte[4];
    int s32_Count = i_Stream.Read(u8_Buf, 0, 4);
    if (s32_Count >= 2)
    {
        if (u8_Buf[0] == 0xFE && u8_Buf[1] == 0xFF)
        {
            i_Stream.Position = 2;
            return new UnicodeEncoding(true, true);
        }

        if (u8_Buf[0] == 0xFF && u8_Buf[1] == 0xFE)
        {
            if (s32_Count >= 4 && u8_Buf[2] == 0 && u8_Buf[3] == 0)
            {
                i_Stream.Position = 4;
                return new UTF32Encoding(false, true);
            }
            else
            {
                i_Stream.Position = 2;
                return new UnicodeEncoding(false, true);
            }
        }

        if (s32_Count >= 3 && u8_Buf[0] == 0xEF && u8_Buf[1] == 0xBB && u8_Buf[2] == 0xBF)
        {
            i_Stream.Position = 3;
            return Encoding.UTF8;
        }

        if (s32_Count >= 4 && u8_Buf[0] == 0 && u8_Buf[1] == 0 && u8_Buf[2] == 0xFE && u8_Buf[3] == 0xFF)
        {
            i_Stream.Position = 4;
            return new UTF32Encoding(true, true);
        }
    }

    i_Stream.Position = 0;
    return Encoding.Default;
}

String vs. StringBuilder

StringBuilder is preferable IF you are doing multiple loops, or forks in your code pass... however, for PURE performance, if you can get away with a SINGLE string declaration, then that is much more performant.

For example:

string myString = "Some stuff" + var1 + " more stuff"
                  + var2 + " other stuff" .... etc... etc...;

is more performant than

StringBuilder sb = new StringBuilder();
sb.Append("Some Stuff");
sb.Append(var1);
sb.Append(" more stuff");
sb.Append(var2);
sb.Append("other stuff");
// etc.. etc.. etc..

In this case, StringBuild could be considered more maintainable, but is not more performant than the single string declaration.

9 times out of 10 though... use the string builder.

On a side note: string + var is also more performant that the string.Format approach (generally) that uses a StringBuilder internally (when in doubt... check reflector!)

How to parse JSON in Scala using standard Scala classes?

I like @huynhjl's answer, it led me down the right path. However, it isn't great at handling error conditions. If the desired node does not exist, you get a cast exception. I've adapted this slightly to make use of Option to better handle this.

class CC[T] {
  def unapply(a:Option[Any]):Option[T] = if (a.isEmpty) {
    None
  } else {
    Some(a.get.asInstanceOf[T])
  }
}

object M extends CC[Map[String, Any]]
object L extends CC[List[Any]]
object S extends CC[String]
object D extends CC[Double]
object B extends CC[Boolean]

for {
  M(map) <- List(JSON.parseFull(jsonString))
  L(languages) = map.get("languages")
  language <- languages
  M(lang) = Some(language)
  S(name) = lang.get("name")
  B(active) = lang.get("is_active")
  D(completeness) = lang.get("completeness")
} yield {
  (name, active, completeness)
}

Of course, this doesn't handle errors so much as avoid them. This will yield an empty list if any of the json nodes are missing. You can use a match to check for the presence of a node before acting...

for {
  M(map) <- Some(JSON.parseFull(jsonString))
} yield {
  map.get("languages") match {
    case L(languages) => {
      for {
        language <- languages
        M(lang) = Some(language)
        S(name) = lang.get("name")
        B(active) = lang.get("is_active")
        D(completeness) = lang.get("completeness")
      } yield {
        (name, active, completeness)
      }        
    }
    case None => "bad json"
  }
}

Set default option in mat-select

Normally you are going to do this in your template with FormGroup, Reactive Forms, etc...

    this.myForm = this.fb.group({
      title: ['', Validators.required],
      description: ['', Validators.required],
      isPublished: ['false',Validators.required]
    });

How to add facebook share button on my website?

Share Dialog without requiring Facebook login

You can Trigger a Share Dialog using the FB.ui function with the share method parameter to share a link. This dialog is available in the Facebook SDKs for JavaScript, iOS, and Android by performing a full redirect to a URL.

You can trigger this call:

FB.ui({
  method: 'share',
  href: 'https://developers.facebook.com/docs/', // Link to share
}, function(response){});

You can also include open graph meta tags on the page at this URL to customise the story that is shared back to Facebook.

Note that response.error_message will appear only if someone using your app has authenticated your app with Facebook Login.

Also you can directly share link with call by having Javascript Facebook SDK.

https://www.facebook.com/dialog/share&app_id=145634995501895&display=popup&href=https%3A%2F%2Fdevelopers.facebook.com%2Fdocs%2F&redirect_uri=https%3A%2F%2Fdevelopers.facebook.com%2Ftools%2Fexplorer

https://www.facebook.com/dialog/share&app_id={APP_ID}&display=popup&href={LINK_TO_SHARE}&redirect_uri={REDIRECT_AFTER_SHARE}
  • app_id => Your app's unique identifier. (Required.)

  • redirect_uri => The URL to redirect to after a person clicks a button on the dialog. Required when using URL redirection.

  • display => Determines how the dialog is rendered.

If you are using the URL redirect dialog implementation, then this will be a full page display, shown within Facebook.com. This display type is called page. If you are using one of our iOS or Android SDKs to invoke the dialog, this is automatically specified and chooses an appropriate display type for the device. If you are using the Facebook SDK for JavaScript, this will default to a modal iframe type for people logged into your app or async when using within a game on Facebook.com, and a popup window for everyone else. You can also force the popup or page types when using the Facebook SDK for JavaScript, if necessary. Mobile web apps will always default to the touch display type. share Parameters

  • href => The link attached to this post. Required when using method share. Include open graph meta tags in the page at this URL to customize the story that is shared.

Linux find and grep command together

You are looking for -H option in gnu grep.

find . -name '*bills*' -exec grep -H "put" {} \;

Here is the explanation

    -H, --with-filename
      Print the filename for each match.

Android, How to create option Menu

IF your Device is running Android v.4.1.2 or before,
the menu is not displayed in the action-bar.
But it can be accessed through the Menu-(hardware)-Button.

Django: List field in model?

If you are using PostgreSQL, you can use ArrayField with a nested ArrayField: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/

This way, the data structure will be known to the underlying database. Also, the ORM brings special functionality for it.

Note that you will have to create a GIN index by yourself, though (see the above link, further down: https://docs.djangoproject.com/en/2.2/ref/contrib/postgres/fields/#indexing-arrayfield).

(Edit: updated links to newest Django LTS, this feature exists at least since 1.8.)

How link to any local file with markdown syntax?

If the file is in the same directory as the one where the .md is, then just putting [Click here](MY-FILE.md) should work.

Otherwise, can create a path from the root directory of the project. So if the entire project/git-repo root directory is called 'my-app', and one wants to point to my-app/client/read-me.md, then try [My hyperlink](/client/read-me.md).

At least works from Chrome.

'dict' object has no attribute 'has_key'

I think it is considered "more pythonic" to just use in when determining if a key already exists, as in

if start not in graph:
    return None

How to insert a timestamp in Oracle?

INSERT INTO TABLE_NAME (TIMESTAMP_VALUE) VALUES (TO_TIMESTAMP('2014-07-02 06:14:00.742000000', 'YYYY-MM-DD HH24:MI:SS.FF'));

Spring Boot yaml configuration for a list of strings

In addition to Ahmet's answer you can add line breaks to the coma separated string using > symbol.

application.yml:

ignoreFilenames: >
  .DS_Store, 
  .hg

Java code:

@Value("${ignoreFilenames}")    
String[] ignoreFilenames;

jquery getting post action url

$('#signup').on("submit", function(event) {
    $form = $(this); //wrap this in jQuery

    alert('the action is: ' + $form.attr('action'));
});

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

Setting environment variable JAVA_HOME to JDK 5 or 6 (instead of JDK 7) fixed the error.

Angular is automatically adding 'ng-invalid' class on 'required' fields

Since the inputs are empty and therefore invalid when instantiated, Angular correctly adds the ng-invalid class.

A CSS rule you might try:

input.ng-dirty.ng-invalid {
  color: red
}

Which basically states when the field has had something entered into it at some point since the page loaded and wasn't reset to pristine by $scope.formName.setPristine(true) and something wasn't yet entered and it's invalid then the text turns red.

Other useful classes for Angular forms (see input for future reference )

ng-valid-maxlength - when ng-maxlength passes
ng-valid-minlength - when ng-minlength passes
ng-valid-pattern - when ng-pattern passes
ng-dirty - when the form has had something entered since the form loaded
ng-pristine - when the form input has had nothing inserted since loaded (or it was reset via setPristine(true) on the form)
ng-invalid - when any validation fails (required, minlength, custom ones, etc)

Likewise there is also ng-invalid-<name> for all these patterns and any custom ones created.

How to fetch data from local JSON file on react native?

ES6/ES2015 version:

import customData from './customData.json';

in linux terminal, how do I show the folder's last modification date, taking its content into consideration?

Something like:

find /path/ -type f -exec stat \{} --printf="%y\n" \; | 
     sort -n -r | 
     head -n 1

Explanation:

  • the find command will print modification time for every file recursively ignoring directories (according to the comment by IQAndreas you can't rely on the folders timestamps)
  • sort -n (numerically) -r (reverse)
  • head -n 1: get the first entry

Compiling an application for use in highly radioactive environments

One point no-one seems to have mentioned. You say you're developing in GCC and cross-compiling onto ARM. How do you know that you don't have code which makes assumptions about free RAM, integer size, pointer size, how long it takes to do a certain operation, how long the system will run for continuously, or various stuff like that? This is a very common problem.

The answer is usually automated unit testing. Write test harnesses which exercise the code on the development system, then run the same test harnesses on the target system. Look for differences!

Also check for errata on your embedded device. You may find there's something about "don't do this because it'll crash, so enable that compiler option and the compiler will work around it".

In short, your most likely source of crashes is bugs in your code. Until you've made pretty damn sure this isn't the case, don't worry (yet) about more esoteric failure modes.

Remove or uninstall library previously added : cocoapods

  1. Remove pod name(which to remove) from Podfile and then
  2. Open Terminal, set project folder path
  3. Run pod install --no-integrate

PHP - regex to allow letters and numbers only

  • Missing end anchor $
  • Missing multiplier
  • Missing end delimiter

So it should fail anyway, but if it may work, it matches against just one digit at the beginning of the string.

/^[a-z0-9]+$/i

Is it possible to center text in select box?

try this :

select {
    padding-left: 50% !important;
    width: 100%;
}

How to set the default value of an attribute on a Laravel model

You should set default values in migrations:

$table->tinyInteger('role')->default(1);

Better way to sort array in descending order

Depending on the sort order, you can do this :

    int[] array = new int[] { 3, 1, 4, 5, 2 };
    Array.Sort<int>(array,
                    new Comparison<int>(
                            (i1, i2) => i2.CompareTo(i1)
                    ));

... or this :

    int[] array = new int[] { 3, 1, 4, 5, 2 };
    Array.Sort<int>(array,
                    new Comparison<int>(
                            (i1, i2) => i1.CompareTo(i2)
                    ));

i1 and i2 are just reversed.

Updating a dataframe column in spark

DataFrames are based on RDDs. RDDs are immutable structures and do not allow updating elements on-site. To change values, you will need to create a new DataFrame by transforming the original one either using the SQL-like DSL or RDD operations like map.

A highly recommended slide deck: Introducing DataFrames in Spark for Large Scale Data Science.

Applying a single font to an entire website with CSS

Please place this in the head of your Page(s) if the "body" needs the use of 1 and the same font:

<style type="text/css">
body {font-family:FONT-NAME ;
     }
</style>

Everything between the tags <body> and </body>will have the same font

Create HTML table using Javascript

The problem is that if you try to write a <table> or a <tr> or <td> tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.

Instead of writing your table line by line, concatenate your table into a variable and insert it once created:

<script language="javascript" type="text/javascript">
<!--

var myArray    = new Array();
    myArray[0] = 1;
    myArray[1] = 2.218;
    myArray[2] = 33;
    myArray[3] = 114.94;
    myArray[4] = 5;
    myArray[5] = 33;
    myArray[6] = 114.980;
    myArray[7] = 5;

    var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
    myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
    myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";

    myTable+="<tr><td style='width: 100px;                   '>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td></tr>";

  for (var i=0; i<8; i++) {
    myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
    myArray[i] = myArray[i].toFixed(3);
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
  }  
   myTable+="</table>";

 document.write( myTable);

//-->
</script> 

If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:

<div id="tablePrint"> </div>

And in JS instead of document.write(myTable) use the following code:

document.getElementById('tablePrint').innerHTML = myTable;

List only stopped Docker containers

docker container list -f "status=exited"

or

docker container ls -f "status=exited"

or

 docker ps -f "status=exited"

How can I do a BEFORE UPDATED trigger with sql server?

MSSQL does not support BEFORE triggers. The closest you have is INSTEAD OF triggers but their behavior is different to that of BEFORE triggers in MySQL.

You can learn more about them here, and note that INSTEAD OF triggers "Specifies that the trigger is executed instead of the triggering SQL statement, thus overriding the actions of the triggering statements." Thus, actions on the update may not take place if the trigger is not properly written/handled. Cascading actions are also affected.

You may instead want to use a different approach to what you are trying to achieve.

What is the best free SQL GUI for Linux for various DBMS systems

I tried many GUI's, and the best for me continue being "SQLyog-comunity" by using wine. Is complete, is nice, and is intuitive. (and in wine work perfect)

What's the difference between Apache's Mesos and Google's Kubernetes

"I understand both are server cluster management software."

This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).

Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).

How to force a script reload and re-execute?

Here's a method which is similar to Kelly's but will remove any pre-existing script with the same source, and uses jQuery.

<script>
    function reload_js(src) {
        $('script[src="' + src + '"]').remove();
        $('<script>').attr('src', src).appendTo('head');
    }
    reload_js('source_file.js');
</script>

Note that the 'type' attribute is no longer needed for scripts as of HTML5. (http://www.w3.org/html/wg/drafts/html/master/scripting-1.html#the-script-element)

Hook up Raspberry Pi via Ethernet to laptop without router?

configure static ip on the raspberry pi:

sudo nano /etc/network/interfaces

and then add:

iface eth0 inet static
     address 169.254.0.2
     netmask 255.255.255.0
     broadcast 169.254.0.255

then you can acces your raspberry via ssh

ssh [email protected]

Setting transparent images background in IrfanView

If you are using the batch conversion, in the window click "options" in the "Batch conversion settings-output format" and tick the two boxes "save transparent color" (one under "PNG" and the other under "ICO").

Meaning of = delete after function declaration

A deleted function is implicitly inline

(Addendum to existing answers)

... And a deleted function shall be the first declaration of the function (except for deleting explicit specializations of function templates - deletion should be at the first declaration of the specialization), meaning you cannot declare a function and later delete it, say, at its definition local to a translation unit.

Citing [dcl.fct.def.delete]/4:

A deleted function is implicitly inline. ( Note: The one-definition rule ([basic.def.odr]) applies to deleted definitions. — end note ] A deleted definition of a function shall be the first declaration of the function or, for an explicit specialization of a function template, the first declaration of that specialization. [ Example:

struct sometype {
  sometype();
};
sometype::sometype() = delete;      // ill-formed; not first declaration

— end example )

A primary function template with a deleted definition can be specialized

Albeit a general rule of thumb is to avoid specializing function templates as specializations do not participate in the first step of overload resolution, there are arguable some contexts where it can be useful. E.g. when using a non-overloaded primary function template with no definition to match all types which one would not like implicitly converted to an otherwise matching-by-conversion overload; i.e., to implicitly remove a number of implicit-conversion matches by only implementing exact type matches in the explicit specialization of the non-defined, non-overloaded primary function template.

Before the deleted function concept of C++11, one could do this by simply omitting the definition of the primary function template, but this gave obscure undefined reference errors that arguably gave no semantic intent whatsoever from the author of primary function template (intentionally omitted?). If we instead explicitly delete the primary function template, the error messages in case no suitable explicit specialization is found becomes much nicer, and also shows that the omission/deletion of the primary function template's definition was intentional.

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t);

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    //use_only_explicit_specializations(str); // undefined reference to `void use_only_explicit_specializations< ...
}

However, instead of simply omitting a definition for the primary function template above, yielding an obscure undefined reference error when no explicit specialization matches, the primary template definition can be deleted:

#include <iostream>
#include <string>

template< typename T >
void use_only_explicit_specializations(T t) = delete;

template<>
void use_only_explicit_specializations<int>(int t) {
    std::cout << "int: " << t;
}

int main()
{
    const int num = 42;
    const std::string str = "foo";
    use_only_explicit_specializations(num);  // int: 42
    use_only_explicit_specializations(str);
    /* error: call to deleted function 'use_only_explicit_specializations' 
       note: candidate function [with T = std::__1::basic_string<char>] has 
       been explicitly deleted
       void use_only_explicit_specializations(T t) = delete; */
}

Yielding a more more readable error message, where the deletion intent is also clearly visible (where an undefined reference error could lead to the developer thinking this an unthoughtful mistake).

Returning to why would we ever want to use this technique? Again, explicit specializations could be useful to implicitly remove implicit conversions.

#include <cstdint>
#include <iostream>

void warning_at_best(int8_t num) { 
    std::cout << "I better use -Werror and -pedantic... " << +num << "\n";
}

template< typename T >
void only_for_signed(T t) = delete;

template<>
void only_for_signed<int8_t>(int8_t t) {
    std::cout << "UB safe! 1 byte, " << +t << "\n";
}

template<>
void only_for_signed<int16_t>(int16_t t) {
    std::cout << "UB safe! 2 bytes, " << +t << "\n";
}

int main()
{
    const int8_t a = 42;
    const uint8_t b = 255U;
    const int16_t c = 255;
    const float d = 200.F;

    warning_at_best(a); // 42
    warning_at_best(b); // implementation-defined behaviour, no diagnostic required
    warning_at_best(c); // narrowing, -Wconstant-conversion warning
    warning_at_best(d); // undefined behaviour!

    only_for_signed(a);
    only_for_signed(c);

    //only_for_signed(b);  
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = unsigned char] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */

    //only_for_signed(d);
    /* error: call to deleted function 'only_for_signed' 
       note: candidate function [with T = float] 
             has been explicitly deleted
       void only_for_signed(T t) = delete; */
}

Unsupported major.minor version 52.0 when rendering in Android Studio

Also, if issue appears while executing ./gradlew command, setting java home in gradle.properties file, solves this issue:

org.gradle.java.home=/usr/java/jdk1.8.0_45/

Why call super() in a constructor?

There is an implicit call to super() with no arguments for all classes that have a parent - which is every user defined class in Java - so calling it explicitly is usually not required. However, you may use the call to super() with arguments if the parent's constructor takes parameters, and you wish to specify them. Moreover, if the parent's constructor takes parameters, and it has no default parameter-less constructor, you will need to call super() with argument(s).

An example, where the explicit call to super() gives you some extra control over the title of the frame:

class MyFrame extends JFrame
{
    public MyFrame() {
        super("My Window Title");
        ...
    }
}

Open and write data to text file using Bash?

You can redirect the output of a command to a file:

$ cat file > copy_file

or append to it

$ cat file >> copy_file

If you want to write directly the command is echo 'text'

$ echo 'Hello World' > file

What are the First and Second Level caches in (N)Hibernate?

by default, NHibernate uses first level caching which is Session Object based. but if you are running in a multi-server environment, then the first level cache may not very scalable along with some performance issues. it is happens because of the fact that it has to make very frequent trips to the database as the data is distributed over multiple servers. in other words NHibernate provides a basic, not-so-sophisticated in-process L1 cache out of box. However, it doesn’t provide features that a caching solution must have to have a notable impact on the application performance.

so the questions of all these problem is the use of a L2 cache which is associated with the session factory objects. it reduces the time consuming trips to the database so ultimately increases the app response time.

What is a software framework?

The summary at Wikipedia (Software Framework) (first google hit btw) explains it quite well:

A software framework, in computer programming, is an abstraction in which common code providing generic functionality can be selectively overridden or specialized by user code providing specific functionality. Frameworks are a special case of software libraries in that they are reusable abstractions of code wrapped in a well-defined Application programming interface (API), yet they contain some key distinguishing features that separate them from normal libraries.

Software frameworks have these distinguishing features that separate them from libraries or normal user applications:

  1. inversion of control - In a framework, unlike in libraries or normal user applications, the overall program's flow of control is not dictated by the caller, but by the framework.[1]
  2. default behavior - A framework has a default behavior. This default behavior must actually be some useful behavior and not a series of no-ops.
  3. extensibility - A framework can be extended by the user usually by selective overriding or specialized by user code providing specific functionality.
  4. non-modifiable framework code - The framework code, in general, is not allowed to be modified. Users can extend the framework, but not modify its code.

You may "need" it because it may provide you with a great shortcut when developing applications, since it contains lots of already written and tested functionality. The reason is quite similar to the reason we use software libraries.

getActivity() returns null in Fragment function

This happened when you call getActivity() in another thread that finished after the fragment has been removed. The typical case is calling getActivity() (ex. for a Toast) when an HTTP request finished (in onResponse for example).

To avoid this, you can define a field name mActivity and use it instead of getActivity(). This field can be initialized in onAttach() method of Fragment as following:

@Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (context instanceof Activity){
        mActivity =(Activity) context;
    }
}

In my projects, I usually define a base class for all of my Fragments with this feature:

public abstract class BaseFragment extends Fragment {

    protected FragmentActivity mActivity;

    @Override
public void onAttach(Context context) {
    super.onAttach(context);

    if (context instanceof Activity){
        mActivity =(Activity) context;
    }
}
}

Happy coding,

Questions every good .NET developer should be able to answer?

I found these lists on Scott Hanselman's blog:

Here are what I think are the most important questions from these posts divided into categories. I edited and re-arranged them. Fortunately for most of these questions there is already a good answer on Stack Overflow. Just follow the links (I will update them all ASAP).

Platform independent .NET questions

ASP.NET

MySQL foreach alternative for procedure

Here's the mysql reference for cursors. So I'm guessing it's something like this:

  DECLARE done INT DEFAULT 0;
  DECLARE products_id INT;
  DECLARE result varchar(4000);
  DECLARE cur1 CURSOR FOR SELECT products_id FROM sets_products WHERE set_id = 1;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

  OPEN cur1;

  REPEAT
    FETCH cur1 INTO products_id;
    IF NOT done THEN
      CALL generate_parameter_list(@product_id, @result);
      SET param = param + "," + result; -- not sure on this syntax
    END IF;
  UNTIL done END REPEAT;

  CLOSE cur1;

  -- now trim off the trailing , if desired

How does the getView() method work when creating your own custom adapter?

  1. Layout inflator inflates/adds external XML to your current view.

  2. getView() is called numerous times including when scrolled. So if it already has view inflated we don't wanna do it again since inflating is a costly process.. thats why we check if its null and then inflate it.

  3. The parent view is single cell of your List..

Create two threads, one display odd & other even numbers

package p.Threads;

public class PrintEvenAndOddNum  {

    private  Object obj = new Object();

    private static final PrintEvenAndOddNum peon = new PrintEvenAndOddNum();

    private PrintEvenAndOddNum(){}

    public static PrintEvenAndOddNum getInstance(){
        return peon;
    }

    public  void printOddNum()  {
        for(int i=1;i<10;i++){
            if(i%2 != 0){
                synchronized (obj) {
                    System.out.println(i);

                    try {
                        System.out.println("oddNum going into waiting state ....");
                        obj.wait();

                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    System.out.println("resume....");
                    obj.notify();
                }
            }
        }
    }

    public  void printEvenNum()  {
        for(int i=1;i<11;i++){
            if(i%2 == 0){
                synchronized(obj){
                    System.out.println(i);
                    obj.notify();
                    try {
                        System.out.println("evenNum going into waiting state ....");
                        obj.wait();
                        System.out.println("Notifying waiting thread ....");
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
        }
    }   
}

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

Debugging iframes with Chrome developer tools

Currently evaluation in the console is performed in the context of the main frame in the page and it adheres to the same cross-origin policy as the main frame itself. This means that you cannot access elements in the iframe unless the main frame can. You can still set breakpoints in and debug your code using Scripts panel though.

Update: This is no longer true. See Metagrapher's answer.

Write lines of text to a file in R

What about a simple write.table()?

text = c("Hello", "World")
write.table(text, file = "output.txt", col.names = F, row.names = F, quote = F)

The parameters col.names = FALSE and row.names = FALSE make sure to exclude the row and column names in the txt, and the parameter quote = FALSE excludes those quotation marks at the beginning and end of each line in the txt. To read the data back in, you can use text = readLines("output.txt").

The endpoint reference (EPR) for the Operation not found is

By removing cache wsdl-* files in /tmp folder, my problem was solved

see https://www.drupal.org/node/1132926#comment-6283348

be careful about permission to delete

I'm in ubuntu os

CSS filter: make color image with transparency white

You can use

filter: brightness(0) invert(1);

_x000D_
_x000D_
html {_x000D_
  background: red;_x000D_
}_x000D_
p {_x000D_
  float: left;_x000D_
  max-width: 50%;_x000D_
  text-align: center;_x000D_
}_x000D_
img {_x000D_
  display: block;_x000D_
  max-width: 100%;_x000D_
}_x000D_
.filter {_x000D_
  -webkit-filter: brightness(0) invert(1);_x000D_
  filter: brightness(0) invert(1);_x000D_
}
_x000D_
<p>_x000D_
  Original:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" />_x000D_
</p>_x000D_
<p>_x000D_
  Filter:_x000D_
  <img src="http://i.stack.imgur.com/jO8jP.gif" class="filter" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

First, brightness(0) makes all image black, except transparent parts, which remain transparent.

Then, invert(1) makes the black parts white.

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

You might check Select2 plugin:

http://ivaynberg.github.io/select2/

Select2 is a jQuery based replacement for select boxes. It supports searching, remote data sets, and infinite scrolling of results.

It's quite popular and very maintainable. It should cover most of your needs if not all.

MongoDB: Combine data from multiple collections into one..how?

Yes you can: Take this utility function that I have written today:

function shangMergeCol() {
  tcol= db.getCollection(arguments[0]);
  for (var i=1; i<arguments.length; i++){
    scol= db.getCollection(arguments[i]);
    scol.find().forEach(
        function (d) {
            tcol.insert(d);
        }
    )
  }
}

You can pass to this function any number of collections, the first one is going to be the target one. All the rest collections are sources to be transferred to the target one.

How do you format the day of the month to say "11th", "21st" or "23rd" (ordinal indicator)?

There is a simpler and sure way of doing this. The function you'll need to use is getDateFromDateString(dateString); It basically removes the st/nd/rd/th off of a date string and simply parses it. You can change your SimpleDateFormat to anything and this will work.

public static final SimpleDateFormat sdf = new SimpleDateFormat("d");
public static final Pattern p = Pattern.compile("([0-9]+)(st|nd|rd|th)");

private static Date getDateFromDateString(String dateString) throws ParseException {
     return sdf.parse(deleteOrdinal(dateString));
}

private static String deleteOrdinal(String dateString) {
    Matcher m = p.matcher(dateString);
    while (m.find()) {
        dateString = dateString.replaceAll(Matcher.quoteReplacement(m.group(0)), m.group(1));
    }
    return dateString;

}

Call Class Method From Another Class

In Python function are first class citezens, so you can just assign it to a property like any other value. Here we are assigning the method of A's hello to a property on B. After __init__, hello will be attached to B as self.hello, which is actually a reference to A's hello:

class A:
    def hello(self, msg):
        print(f"Hello {msg}")
    
class B:
    hello = A.hello

print(A.hello)
print(B.hello)

b = B()
b.hello("good looking!")

Prints:

<function A.hello at 0x7fcce55b9e50>
<function A.hello at 0x7fcce55b9e50>
Hello good looking!

How can I reconcile detached HEAD with master/origin?

I had the same problem. I stash my changes with git stash and hard reset the branch in local to a previous commit(I thought it caused that) then did a git pull and I am not getting that head detached now. Dont forget git stash apply to have your changes again.

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

Well, from sourceTree I couldn't resolve this issue but I created sshkey from bash and at least it works from git-bash.

https://confluence.atlassian.com/bitbucket/set-up-an-ssh-key-728138079.html

How do I parse JSON into an int?

You may use parseInt :

int id = Integer.parseInt(jsonObj.get("id"));

or better and more directly the getInt method :

int id = jsonObj.getInt("id");

Maximum execution time in phpMyadmin

I faced the same problem while executing a curl. I got it right when I changed the following in the php.ini file:

max_execution_time = 1000 ;

and also

max_input_time = 1000 ;

Probably your problem should be solved by making above two changes and restarting the apache server.

Even after changing the above the problem persists and if you think it's because of some database operation using mysql you can try changing this also:

mysql.connect_timeout = 1000 ; // this is not neccessary

All this should be changed in php.ini file and apache server should be restarted to see the changes.

Git add and commit in one command

Just combine your commands:

git add -A && git commit -m "comment" 

Python: most idiomatic way to convert None to empty string?

A neat one-liner to do this building on some of the other answers:

s = (lambda v: v or '')(a) + (lambda v: v or '')(b)

or even just:

s = (a or '') + (b or '')

Generate insert script for selected records?

You could create a view with your criteria and then export the view?

Can I convert a boolean to Yes/No in a ASP.NET GridView

I use this code for VB:

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>

And this should work for C# (untested):

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>

jQuery UI Color Picker

Perhaps I am very late, but as of now there's another way to use it using the jquery ui slider.

Here's how its shown in the jquery ui docs:

_x000D_
_x000D_
function hexFromRGB(r, g, b) {_x000D_
    var hex = [_x000D_
      r.toString( 16 ),_x000D_
      g.toString( 16 ),_x000D_
      b.toString( 16 )_x000D_
    ];_x000D_
    $.each( hex, function( nr, val ) {_x000D_
      if ( val.length === 1 ) {_x000D_
        hex[ nr ] = "0" + val;_x000D_
      }_x000D_
    });_x000D_
    return hex.join( "" ).toUpperCase();_x000D_
  }_x000D_
  function refreshSwatch() {_x000D_
    var red = $( "#red" ).slider( "value" ),_x000D_
      green = $( "#green" ).slider( "value" ),_x000D_
      blue = $( "#blue" ).slider( "value" ),_x000D_
      hex = hexFromRGB( red, green, blue );_x000D_
    $( "#swatch" ).css( "background-color", "#" + hex );_x000D_
  }_x000D_
  $(function() {_x000D_
    $( "#red, #green, #blue" ).slider({_x000D_
      orientation: "horizontal",_x000D_
      range: "min",_x000D_
      max: 255,_x000D_
      value: 127,_x000D_
      slide: refreshSwatch,_x000D_
      change: refreshSwatch_x000D_
    });_x000D_
    $( "#red" ).slider( "value", 255 );_x000D_
    $( "#green" ).slider( "value", 140 );_x000D_
    $( "#blue" ).slider( "value", 60 );_x000D_
  });
_x000D_
#red, #green, #blue {_x000D_
float: left;_x000D_
clear: left;_x000D_
width: 300px;_x000D_
margin: 15px;_x000D_
}_x000D_
#swatch {_x000D_
width: 120px;_x000D_
height: 100px;_x000D_
margin-top: 18px;_x000D_
margin-left: 350px;_x000D_
background-image: none;_x000D_
}_x000D_
#red .ui-slider-range { background: #ef2929; }_x000D_
#red .ui-slider-handle { border-color: #ef2929; }_x000D_
#green .ui-slider-range { background: #8ae234; }_x000D_
#green .ui-slider-handle { border-color: #8ae234; }_x000D_
#blue .ui-slider-range { background: #729fcf; }_x000D_
#blue .ui-slider-handle { border-color: #729fcf; }
_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
_x000D_
<script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
<p class="ui-state-default ui-corner-all ui-helper-clearfix" style="padding:4px;">_x000D_
  <span class="ui-icon ui-icon-pencil" style="float:left; margin:-2px 5px 0 0;"></span>_x000D_
  Simple Colorpicker_x000D_
</p>_x000D_
 _x000D_
<div id="red"></div>_x000D_
<div id="green"></div>_x000D_
<div id="blue"></div>_x000D_
 _x000D_
<div id="swatch" class="ui-widget-content ui-corner-all"></div>
_x000D_
_x000D_
_x000D_

Mongodb: Failed to connect to 127.0.0.1:27017, reason: errno:10061

The problem is that I missed out 'db' folder for the dbpath in the command:

C:\mongodb\bin> mongod --directoryperdb --dbpath C:\mongodb\data\db --logpath C:\mongodb\log\mongodb.log --logappend -rest --install

iPhone Debugging: How to resolve 'failed to get the task for process'?

I Had the same issue, but resolved it by following simple following steps :

  1. Make sure you have selected debug rather than release.
  2. In Debug configurations, in project settings, you should have selected developer's profile & no need of specifying the entitlements plist.
  3. Also same setting are there under: Targets: , if not manuall change them to the above for the debug config. It will work.

All the best.

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

'parent.relativePath' points at wrong local POM @ myGroup:myParentArtifactId:1.0, C:\myProjectDir\parent\pom.xml

This indicates that maven did search locally for the parent pom, but found that it was not the correct pom.

  • Does pom.xml of parentpom correctly define the parent pom as the pom.xml of rootpom?
  • Does rootpom folder contain pom.xml as well as the paretpom folder?

How to pass credentials to the Send-MailMessage command for sending emails

in addition to UseSsl, you have to include smtp port 587 to make it work.

Send-MailMessage -SmtpServer smtp.gmail.com -Port 587 -Credential $credential -UseSsl -From '[email protected]' -To '[email protected]' -Subject 'TEST'

Set transparent background of an imageview on Android

Try this code :)

Its an fully transparent hexa code - "#00000000"

Load image from resources area of project in C#

JDS's answer worked best. C# example loading image:

  • Include the image as Resource (Project tree->Resources, right click to add the desirable file ImageName.png)
  • Embedded Resource (Project tree->Resources->ImageName.png, right click select properties)
  • .png file format (.bmp .jpg should also be OK)

pictureBox1.Image = ProjectName.Properties.Resources.ImageName;

Note the followings:

  • The resource image file is "ImageName.png", file extension should be omitted.
  • ProjectName may perhaps be more adequately understood as "Assembly name", which is to be the respective text entry on the Project->Properties page.

The example code line is run successfully using VisualStudio 2015 Community.

Pointer to incomplete class type is not allowed

You get this error when declaring a forward reference inside the wrong namespace thus declaring a new type without defining it. For example:

namespace X
{
  namespace Y
  {
    class A;

    void func(A* a) { ... } // incomplete type here!
  }
}

...but, in class A was defined like this:

namespace X
{
  class A { ... };
}

Thus, A was defined as X::A, but I was using it as X::Y::A.

The fix obviously is to move the forward reference to its proper place like so:

namespace X
{
  class A;
  namespace Y
  {
    void func(X::A* a) { ... } // Now accurately referencing the class`enter code here`
  }
}

How to generate .env file for laravel?

Just tried both ways and in both ways I got generated .env file:

enter image description here

Composer should automatically create .env file. In the post-create-project-cmd section of the composer.json you can find:

"post-create-project-cmd": [
  "php -r \"copy('.env.example', '.env');\"",
  "php artisan key:generate"
]

Both ways use the same composer.json file, so there shoudn't be any difference.

I suggest you to update laravel/installer to the last version: 1.2 and try again:

composer global require "laravel/installer=~1.2"

You can always generate .env file manually by running:

cp .env.example .env
php artisan key:generate

Difference between Hive internal tables and external tables?

An internal table data is stored in the warehouse folder, whereas an external table data is stored at the location you mentioned in table creation.

So when you delete an internal table, it deletes the schema as well as the data under the warehouse folder, but for an external table it's only the schema that you will loose.

So when you want an external table back you again after deleting it, can create a table with the same schema again and point it to the original data location. Hope it is clear now.

How to encode a URL in Swift

If it's possible that the value that you're adding to your URL can have reserved characters (as defined by section 2 of RFC 3986), you might have to refine your percent-escaping. Notably, while & and + are valid characters in a URL, they're not valid within a URL query parameter value (because & is used as delimiter between query parameters which would prematurely terminate your value, and + is translated to a space character). Unfortunately, the standard percent-escaping leaves those delimiters unescaped.

Thus, you might want to percent escape all characters that are not within RFC 3986's list of unreserved characters:

Characters that are allowed in a URI but do not have a reserved purpose are called unreserved. These include uppercase and lowercase letters, decimal digits, hyphen, period, underscore, and tilde.

     unreserved  = ALPHA / DIGIT / "-" / "." / "_" / "~"

Later, in section 3.4, the RFC further contemplates adding ? and / to the list of allowed characters within a query:

The characters slash ("/") and question mark ("?") may represent data within the query component. Beware that some older, erroneous implementations may not handle such data correctly when it is used as the base URI for relative references (Section 5.1), apparently because they fail to distinguish query data from path data when looking for hierarchical separators. However, as query components are often used to carry identifying information in the form of "key=value" pairs and one frequently used value is a reference to another URI, it is sometimes better for usability to avoid percent- encoding those characters.

Nowadays, you'd generally use URLComponents to percent escape the query value:

var address = "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India"
var components = URLComponents(string: "http://maps.googleapis.com/maps/api/geocode/json")!
components.queryItems = [URLQueryItem(name: "address", value: address)]
let url = components.url!

By the way, while it's not contemplated in the aforementioned RFC, section 5.2, URL-encoded form data, of the W3C HTML spec says that application/x-www-form-urlencoded requests should also replace space characters with + characters (and includes the asterisk in the characters that should not be escaped). And, unfortunately, URLComponents won't properly percent escape this, so Apple advises that you manually percent escape it before retrieving the url property of the URLComponents object:

// configure `components` as shown above, and then:

components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
let url = components.url!

For Swift 2 rendition, where I manually do all of this percent escaping myself, see the previous revision of this answer.

The action or event has been blocked by Disabled Mode

No. Go to database tools (for 2007) and click checkmark on the Message Bar. Then, after the message bar apears, click on Options, and then Enable. Hope this helps.

Dimitri

Including a groovy script in another groovy

Groovy doesn't have an import keyword like typical scripting languages that will do a literal include of another file's contents (alluded to here: Does groovy provide an include mechanism?).
Because of its object/class oriented nature, you have to "play games" to make things like this work. One possibility is to make all your utility functions static (since you said they don't use objects) and then perform a static import in the context of your executing shell. Then you can call these methods like "global functions".
Another possibility would be using a Binding object (http://groovy.codehaus.org/api/groovy/lang/Binding.html) while creating your Shell and binding all the functions you want to the methods (the downside here would be having to enumerate all methods in the binding but you could perhaps use reflection). Yet another solution would be to override methodMissing(...) in the delegate object assigned to your shell which allows you to basically do dynamic dispatch using a map or whatever method you'd like.

Several of these methods are demonstrated here: http://www.nextinstruction.com/blog/2012/01/08/creating-dsls-with-groovy/. Let me know if you want to see an example of a particular technique.

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

Should I use alias or alias_method?

alias_method new_method, old_method

old_method will be declared in a class or module which is being inherited now to our class where new_method will be used.

these can be variable or method both.

Suppose Class_1 has old_method, and Class_2 and Class_3 both of them inherit Class_1.

If, initialization of Class_2 and Class_3 is done in Class_1 then both can have different name in Class_2 and Class_3 and its usage.

Where can I find MySQL logs in phpMyAdmin?

Use performance_schema database and the tables:

  1. events_statements_current
  2. events_statemenets_history
  3. events_statemenets_history_long

Check the manual here

string in namespace std does not name a type

You need to add:

#include <string>

In your header file.

Writing numerical values on the plot with Matplotlib

You can use the annotate command to place text annotations at any x and y values you want. To place them exactly at the data points you could do this

import numpy
from matplotlib import pyplot

x = numpy.arange(10)
y = numpy.array([5,3,4,2,7,5,4,6,3,2])

fig = pyplot.figure()
ax = fig.add_subplot(111)
ax.set_ylim(0,10)
pyplot.plot(x,y)
for i,j in zip(x,y):
    ax.annotate(str(j),xy=(i,j))

pyplot.show()

If you want the annotations offset a little, you could change the annotate line to something like

ax.annotate(str(j),xy=(i,j+0.5))

How to resolve "Could not find schema information for the element/attribute <xxx>"?

What fixed the "Could not find schema information for the element ..." for me was

  • Opening my app.config.
  • Right-clicking in the editor window and selecting Properties.
  • In the properties box, there is a row called Schemas, I clicked that row and selected the browse ... box that appears in the row.
  • I simply checked the use box for all the rows that had my project somewhere in them, and also for the current version of .Net I was using. For instance: DotNetConfig30.xsd.

After that everything went to working fine.

How those schema rows with my project got unchecked I'm not sure, but when I made sure they were checked, I was back in business.

Error: Generic Array Creation

The following will give you an array of the type you want while preserving type safety.

PCB[] getAll(Class<PCB[]> arrayType) {  
    PCB[] res = arrayType.cast(java.lang.reflect.Array.newInstance(arrayType.getComponentType(), list.size()));  
    for (int i = 0; i < res.length; i++)  {  
        res[i] = list.get(i);  
    }  
    list.clear();  
    return res;  
}

How this works is explained in depth in my answer to the question that Kirk Woll linked as a duplicate.

Multiple Java versions running concurrently under Windows

It should be possible changing setting the JAVA_HOME environment variable differently for specific applications.

When starting from the command line or from a batch script you can use set JAVA_HOME=C:\...\j2dskXXX to change the JAVA_HOME environment.

It is possible that you also need to change the PATH environment variable to use the correct java binary. To do this you can use set PATH=%JAVA_HOME%\bin;%PATH%.

In c# is there a method to find the max of 3 numbers?

Linq has a Max function.

If you have an IEnumerable<int> you can call this directly, but if you require these in separate parameters you could create a function like this:

using System.Linq;

...

static int Max(params int[] numbers)
{
    return numbers.Max();
}

Then you could call it like this: max(1, 6, 2), it allows for an arbitrary number of parameters.

How do I use a delimiter with Scanner.useDelimiter in Java?

For example:

String myInput = null;
Scanner myscan = new Scanner(System.in).useDelimiter("\\n");
System.out.println("Enter your input: ");
myInput = myscan.next();
System.out.println(myInput);

This will let you use Enter as a delimiter.

Thus, if you input:

Hello world (ENTER)

it will print 'Hello World'.

Checking if a character is a special character in Java

What I would do:

char c;
int cint;
for(int n = 0; n < str.length(); n ++;)
{
    c = str.charAt(n);
    cint = (int)c;
    if(cint <48 || (cint > 57 && cint < 65) || (cint > 90 && cint < 97) || cint > 122)
    {
        specialCharacterCount++
    }
}

That is a simple way to do things, without having to import any special classes. Stick it in a method, or put it straight into the main code.

ASCII chart: http://www.gophoto.it/view.php?i=http://i.msdn.microsoft.com/dynimg/IC102418.gif#.UHsqxFEmG08

SQL Stored Procedure: If variable is not null, update statement

Yet another approach is ISNULL().

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = ISNULL(@ABC, [ABC]),
    [ABCD] = ISNULL(@ABCD, [ABCD])

The difference between ISNULL and COALESCE is the return type. COALESCE can also take more than 2 arguments, and use the first that is not null. I.e.

select COALESCE(null, null, 1, 'two') --returns 1
select COALESCE(null, null, null, 'two') --returns 'two'

Proper way to set response status and JSON content in a REST API made with nodejs and express

FOR IIS

If you are using iisnode to run nodejs through IIS, keep in mind that IIS by default replaces any error message you send.

This means that if you send res.status(401).json({message: "Incorrect authorization token"}) You would get back You do not have permission to view this directory or page.

This behavior can be turned off by using adding the following code to your web.config file under <system.webServer> (source):

<httpErrors existingResponse="PassThrough" />

How to kill all processes with a given partial name?

it's best and safest to use pgrep -f with kill, or just pkill -f, greping ps's output can go wrong.

Unlike using ps | grep with which you need to filter out the grep line by adding | grep -v or using pattern tricks, pgrep just won't pick itself by design.

Moreover, should your pattern appear in ps's UID/USER, SDATE/START or any other column, you'll get unwanted processes in the output and kill them, pgrep+pkill don't suffer from this flaw.

also I found that killall -r/ -regexp didn't work with my regular expression.

pkill -f "^python3 path/to/my_script$"

man pkill

Reflection generic get field value

You are calling get with the wrong argument.

It should be:

Object value = field.get(object);

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

When you're working with strings in PHP you'll need to pay special attention to the formation, using " or '

$string = 'Hello, world!';
$string = "Hello, world!";

Both of these are valid, the following is not:

$string = "Hello, world';

You must also note that ' inside of a literal started with " will not end the string, and vice versa. So when you have a string which contains ', it is generally best practice to use double quotation marks.

$string = "It's ok here";

Escaping the string is also an option

$string = 'It\'s ok here too';

More information on this can be found within the documentation

how to import csv data into django models

define class in models.py and a function in it.

class all_products(models.Model):
    def get_all_products():
        items = []
        with open('EXACT FILE PATH OF YOUR CSV FILE','r') as fp:
            # You can also put the relative path of csv file
            # with respect to the manage.py file
            reader1 = csv.reader(fp, delimiter=';')
            for value in reader1:
                items.append(value)
        return items

You can access ith element in the list as items[i]

Problems with installation of Google App Engine SDK for php in OS X

It's likely that the download was corrupted if you are getting an error with the disk image. Go back to the downloads page at https://developers.google.com/appengine/downloads and look at the SHA1 checksum. Then, go to your Terminal app on your mac and run the following:

openssl sha1 [put the full path to the file here without brackets] 

For example:

openssl sha1 /Users/me/Desktop/myFile.dmg 

If you get a different value than the one on the Downloads page, you know your file is not properly downloaded and you should try again.

How to show all shared libraries used by executables in Linux?

Check shared library dependencies of a program executable

To find out what libraries a particular executable depends on, you can use ldd command. This command invokes dynamic linker to find out library dependencies of an executable.

> $ ldd /path/to/program

Note that it is NOT recommended to run ldd with any untrusted third-party executable because some versions of ldd may directly invoke the executable to identify its library dependencies, which can be security risk.

Instead, a safer way to show library dependencies of an unknown application binary is to use the following command.

$ objdump -p /path/to/program | grep NEEDED

for more info

SharePoint : How can I programmatically add items to a custom list instance

I had a similar problem and was able to solve it by following the below approach (similar to other answers but needed credentials too),

1- add Microsoft.SharePointOnline.CSOM by tools->NuGet Package Manager->Manage NuGet Packages for solution->Browse-> select and install

2- Add "using Microsoft.SharePoint.Client; "

then the below code

        string siteUrl = "https://yourcompany.sharepoint.com/sites/Yoursite";
        SecureString passWord = new SecureString();

        var password = "Your password here";
        var securePassword = new SecureString();
        foreach (char c in password)
        {
            securePassword.AppendChar(c);
        }
        ClientContext clientContext = new ClientContext(siteUrl);
        clientContext.Credentials = new SharePointOnlineCredentials("[email protected]", securePassword);/*passWord*/
        List oList = clientContext.Web.Lists.GetByTitle("The name of your list here");
        ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();
        ListItem oListItem = oList.AddItem(itemCreateInfo);
        oListItem["PK"] = "1";
        oListItem["Precinct"] = "Mangere";
        oListItem["Title"] = "Innovation";
        oListItem["Project_x005F_x0020_Name"] = "test from C#";
        oListItem["Project_x005F_x0020_ID"] = "ID_123_from C#";
        oListItem["Project_x005F_x0020_start_x005F_x0020_date"] = "2020-05-01 01:01:01";
        oListItem.Update();

        clientContext.ExecuteQuery();

Remember that your fields may be different with what you see, for example in my list I see "Project Name", while the actual value is "Project_x005F_x0020_ID". How to get these values (i.e. internal filed values)?

A few approaches:

1- Use MS flow and see them

2- https://mstechtalk.com/check-column-internal-name-sharepoint-list/ or https://sharepoint.stackexchange.com/questions/787/finding-the-internal-name-and-display-name-for-a-list-column

3- Use a C# reader and read your sharepoint list

The rest of operations (update/delete): https://docs.microsoft.com/en-us/previous-versions/office/developer/sharepoint-2010/ee539976(v%3Doffice.14)

How to escape the % (percent) sign in C's printf?

Nitpick:
You don't really escape the % in the string that specifies the format for the printf() (and scanf()) family of functions.

The %, in the printf() (and scanf()) family of functions, starts a conversion specification. One of the rules for conversion specification states that a % as a conversion specifier (immediately following the % that started the conversion specification) causes a '%' character to be written with no argument converted.

The string really has 2 '%' characters inside (as opposed to escaping characters: "a\bc" is a string with 3 non null characters; "a%%b" is a string with 4 non null characters).

Select box arrow style

for any1 using ie8 and dont want to use a plugin i've made something inspired by Rohit Azad and Bacotasan's blog, i just added a span using JS to show the selected value.

the html:

<div class="styled-select">
   <select>
      <option>Here is the first option</option>
      <option>The second option</option>
   </select>
   <span>Here is the first option</span>
</div>

the css (i used only an arrow for BG but you could put a full image and drop the positioning):

.styled-select div
{
    display:inline-block;
    border: 1px solid darkgray;
    width:100px;
    background:url("/Style Library/Nifgashim/Images/drop_arrrow.png") no-repeat 10px 10px;
    position:relative;
}

.styled-select div select
{
    height: 30px;
    width: 100px;
    font-size:14px;
    font-family:ariel;

    -moz-opacity: 0.00;
    opacity: .00;
    filter: alpha(opacity=00);
}

.styled-select div span
{
    position: absolute;
    right: 10px;
    top: 6px;
    z-index: -5;
}

the js:

$(".styled-select select").change(function(e){
     $(".styled-select span").html($(".styled-select select").val());
});

How to setup Main class in manifest file in jar produced by NetBeans project

This is a problem still as of 7.2.1 . Create a library cause you do not know what it will do if you make it an application & you are screwed.

Did find how to fix this though. Edit nbproject/project.properties, change the following line to false as shown:

mkdist.disabled=false

After this you can change the main class in properties and it will be reflected in manifest.

AngularJS - Passing data between pages

app.factory('persistObject', function () {

        var persistObject = [];

        function set(objectName, data) {
            persistObject[objectName] = data;
        }
        function get(objectName) {
            return persistObject[objectName];
        }

        return {
            set: set,
            get: get
        }
    });

Fill it with data like this

persistObject.set('objectName', data); 

Get the object data like this

persistObject.get('objectName'); 

Style disabled button with CSS

Add the below code in your page. Trust me, no changes made to button events, to disable/enable button simply add/remove the button class in Javascript.

Method 1

 <asp Button ID="btnSave" CssClass="disabledContent" runat="server" />

<style type="text/css">
    .disabledContent 
    {
        cursor: not-allowed;
        background-color: rgb(229, 229, 229) !important;
    }

    .disabledContent > * 
    {
        pointer-events:none;
    }
</style>

Method 2

<asp Button ID="btnSubmit" CssClass="btn-disable" runat="server" />

<style type="text/css">
    .btn-disable
        {
        cursor: not-allowed;
        pointer-events: none;

        /*Button disabled - CSS color class*/
        color: #c0c0c0;
        background-color: #ffffff;

        }
</style>

Hexadecimal To Decimal in Shell Script

Various tools are available to you from within a shell. Sputnick has given you an excellent overview of your options, based on your initial question. He definitely deserves votes for the time he spent giving you multiple correct answers.

One more that's not on his list:

[ghoti@pc ~]$ dc -e '16i BFCA3000 p'
3217698816

But if all you want to do is subtract, why bother changing the input to base 10?

[ghoti@pc ~]$ dc -e '16i BFCA3000 17FF - p 10o p'
3217692673
BFCA1801
[ghoti@pc ~]$ 

The dc command is "desk calc". It will also take input from stdin, like bc, but instead of using "order of operations", it uses stacking ("reverse Polish") notation. You give it inputs which it adds to a stack, then give it operators that pop items off the stack, and push back on the results.

In the commands above we've got the following:

  • 16i -- tells dc to accept input in base 16 (hexadecimal). Doesn't change output base.
  • BFCA3000 -- your initial number
  • 17FF -- a random hex number I picked to subtract from your initial number
  • - -- take the two numbers we've pushed, and subtract the later one from the earlier one, then push the result back onto the stack
  • p -- print the last item on the stack. This doesn't change the stack, so...
  • 10o -- tells dc to print its output in base "10", but remember that our input numbering scheme is currently hexadecimal, so "10" means "16".
  • p -- print the last item on the stack again ... this time in hex.

You can construct fabulously complex math solutions with dc. It's a good thing to have in your toolbox for shell scripts.

How to configure nginx to enable kinda 'file browser' mode?

All answers contain part of the answer. Let me try to combine all in one.

Quick setup "file browser" mode on freshly installed nginx server:

  1. Edit default config for nginx:

    sudo vim /etc/nginx/sites-available/default
    
  2. Add following to config section:

    location /myfolder {  # new url path
       alias /home/username/myfolder/; # directory to list
       autoindex on;
    }
    
  3. Create folder and sample file there:

    mkdir -p /home/username/myfolder/
    ls -la >/home/username/myfolder/mytestfile.txt
    
  4. Restart nginx

    sudo systemctl restart nginx
    
  5. Check result: http://<your-server-ip>/myfolder for example http://192.168.0.10/myfolder/

enter image description here

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example: http://jsfiddle.net/ftkbL/1/

How do I copy an entire directory of files into an existing directory using Python?

Here is my pass at the problem. I modified the source code for copytree to keep the original functionality, but now no error occurs when the directory already exists. I also changed it so it doesn't overwrite existing files but rather keeps both copies, one with a modified name, since this was important for my application.

import shutil
import os


def _copytree(src, dst, symlinks=False, ignore=None):
    """
    This is an improved version of shutil.copytree which allows writing to
    existing folders and does not overwrite existing files but instead appends
    a ~1 to the file name and adds it to the destination path.
    """

    names = os.listdir(src)
    if ignore is not None:
        ignored_names = ignore(src, names)
    else:
        ignored_names = set()

    if not os.path.exists(dst):
        os.makedirs(dst)
        shutil.copystat(src, dst)
    errors = []
    for name in names:
        if name in ignored_names:
            continue
        srcname = os.path.join(src, name)
        dstname = os.path.join(dst, name)
        i = 1
        while os.path.exists(dstname) and not os.path.isdir(dstname):
            parts = name.split('.')
            file_name = ''
            file_extension = parts[-1]
            # make a new file name inserting ~1 between name and extension
            for j in range(len(parts)-1):
                file_name += parts[j]
                if j < len(parts)-2:
                    file_name += '.'
            suffix = file_name + '~' + str(i) + '.' + file_extension
            dstname = os.path.join(dst, suffix)
            i+=1
        try:
            if symlinks and os.path.islink(srcname):
                linkto = os.readlink(srcname)
                os.symlink(linkto, dstname)
            elif os.path.isdir(srcname):
                _copytree(srcname, dstname, symlinks, ignore)
            else:
                shutil.copy2(srcname, dstname)
        except (IOError, os.error) as why:
            errors.append((srcname, dstname, str(why)))
        # catch the Error from the recursive copytree so that we can
        # continue with other files
        except BaseException as err:
            errors.extend(err.args[0])
    try:
        shutil.copystat(src, dst)
    except WindowsError:
        # can't copy file access times on Windows
        pass
    except OSError as why:
        errors.extend((src, dst, str(why)))
    if errors:
        raise BaseException(errors)

What is the purpose of Node.js module.exports and how do you use it?

A module encapsulates related code into a single unit of code. When creating a module, this can be interpreted as moving all related functions into a file.

Suppose there is a file Hello.js which include two functions

sayHelloInEnglish = function() {
  return "Hello";
};
sayHelloInSpanish = function() {
  return "Hola";
};

We write a function only when utility of the code is more than one call.

Suppose we want to increase utility of the function to a different file say World.js,in this case exporting a file comes into picture which can be obtained by module.exports.

You can just export both the function by the code given below

var anyVariable={
 sayHelloInEnglish = function() {
      return "Hello";
    };
  sayHelloInSpanish = function() {
      return "Hola";
    }; 
}
module.export=anyVariable;

Now you just need to require the file name into World.js inorder to use those functions

var world= require("./hello.js");

Entity Framework Code First - two Foreign Keys from same table

InverseProperty in EF Core makes the solution easy and clean.

InverseProperty

So the desired solution would be:

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty(nameof(Match.HomeTeam))]
    public ICollection<Match> HomeMatches{ get; set; }

    [InverseProperty(nameof(Match.GuestTeam))]
    public ICollection<Match> AwayMatches{ get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public Team HomeTeam { get; set; }
    public Team GuestTeam { get; set; }
}

Reverse a string in Python

What is the best way of implementing a reverse function for strings?

My own experience with this question is academic. However, if you're a pro looking for the quick answer, use a slice that steps by -1:

>>> 'a string'[::-1]
'gnirts a'

or more readably (but slower due to the method name lookups and the fact that join forms a list when given an iterator), str.join:

>>> ''.join(reversed('a string'))
'gnirts a'

or for readability and reusability, put the slice in a function

def reversed_string(a_string):
    return a_string[::-1]

and then:

>>> reversed_string('a_string')
'gnirts_a'

Longer explanation

If you're interested in the academic exposition, please keep reading.

There is no built-in reverse function in Python's str object.

Here is a couple of things about Python's strings you should know:

  1. In Python, strings are immutable. Changing a string does not modify the string. It creates a new one.

  2. Strings are sliceable. Slicing a string gives you a new string from one point in the string, backwards or forwards, to another point, by given increments. They take slice notation or a slice object in a subscript:

    string[subscript]
    

The subscript creates a slice by including a colon within the braces:

    string[start:stop:step]

To create a slice outside of the braces, you'll need to create a slice object:

    slice_obj = slice(start, stop, step)
    string[slice_obj]

A readable approach:

While ''.join(reversed('foo')) is readable, it requires calling a string method, str.join, on another called function, which can be rather relatively slow. Let's put this in a function - we'll come back to it:

def reverse_string_readable_answer(string):
    return ''.join(reversed(string))

Most performant approach:

Much faster is using a reverse slice:

'foo'[::-1]

But how can we make this more readable and understandable to someone less familiar with slices or the intent of the original author? Let's create a slice object outside of the subscript notation, give it a descriptive name, and pass it to the subscript notation.

start = stop = None
step = -1
reverse_slice = slice(start, stop, step)
'foo'[reverse_slice]

Implement as Function

To actually implement this as a function, I think it is semantically clear enough to simply use a descriptive name:

def reversed_string(a_string):
    return a_string[::-1]

And usage is simply:

reversed_string('foo')

What your teacher probably wants:

If you have an instructor, they probably want you to start with an empty string, and build up a new string from the old one. You can do this with pure syntax and literals using a while loop:

def reverse_a_string_slowly(a_string):
    new_string = ''
    index = len(a_string)
    while index:
        index -= 1                    # index = index - 1
        new_string += a_string[index] # new_string = new_string + character
    return new_string

This is theoretically bad because, remember, strings are immutable - so every time where it looks like you're appending a character onto your new_string, it's theoretically creating a new string every time! However, CPython knows how to optimize this in certain cases, of which this trivial case is one.

Best Practice

Theoretically better is to collect your substrings in a list, and join them later:

def reverse_a_string_more_slowly(a_string):
    new_strings = []
    index = len(a_string)
    while index:
        index -= 1                       
        new_strings.append(a_string[index])
    return ''.join(new_strings)

However, as we will see in the timings below for CPython, this actually takes longer, because CPython can optimize the string concatenation.

Timings

Here are the timings:

>>> a_string = 'amanaplanacanalpanama' * 10
>>> min(timeit.repeat(lambda: reverse_string_readable_answer(a_string)))
10.38789987564087
>>> min(timeit.repeat(lambda: reversed_string(a_string)))
0.6622700691223145
>>> min(timeit.repeat(lambda: reverse_a_string_slowly(a_string)))
25.756799936294556
>>> min(timeit.repeat(lambda: reverse_a_string_more_slowly(a_string)))
38.73570013046265

CPython optimizes string concatenation, whereas other implementations may not:

... do not rely on CPython's efficient implementation of in-place string concatenation for statements in the form a += b or a = a + b . This optimization is fragile even in CPython (it only works for some types) and isn't present at all in implementations that don't use refcounting. In performance sensitive parts of the library, the ''.join() form should be used instead. This will ensure that concatenation occurs in linear time across various implementations.

What does the explicit keyword mean?

The keyword explicit accompanies either

  • a constructor of class X that cannot be used to implicitly convert the first (any only) parameter to type X

C++ [class.conv.ctor]

1) A constructor declared without the function-specifier explicit specifies a conversion from the types of its parameters to the type of its class. Such a constructor is called a converting constructor.

2) An explicit constructor constructs objects just like non-explicit constructors, but does so only where the direct-initialization syntax (8.5) or where casts (5.2.9, 5.4) are explicitly used. A default constructor may be an explicit constructor; such a constructor will be used to perform default-initialization or valueinitialization (8.5).

  • or a conversion function that is only considered for direct initialization and explicit conversion.

C++ [class.conv.fct]

2) A conversion function may be explicit (7.1.2), in which case it is only considered as a user-defined conversion for direct-initialization (8.5). Otherwise, user-defined conversions are not restricted to use in assignments and initializations.

Overview

Explicit conversion functions and constructors can only be used for explicit conversions (direct initialization or explicit cast operation) while non-explicit constructors and conversion functions can be used for implicit as well as explicit conversions.

/*
                                 explicit conversion          implicit conversion

 explicit constructor                    yes                          no

 constructor                             yes                          yes

 explicit conversion function            yes                          no

 conversion function                     yes                          yes

*/

Example using structures X, Y, Z and functions foo, bar, baz:

Let's look at a small setup of structures and functions to see the difference between explicit and non-explicit conversions.

struct Z { };

struct X { 
  explicit X(int a); // X can be constructed from int explicitly
  explicit operator Z (); // X can be converted to Z explicitly
};

struct Y{
  Y(int a); // int can be implicitly converted to Y
  operator Z (); // Y can be implicitly converted to Z
};

void foo(X x) { }
void bar(Y y) { }
void baz(Z z) { }

Examples regarding constructor:

Conversion of a function argument:

foo(2);                     // error: no implicit conversion int to X possible
foo(X(2));                  // OK: direct initialization: explicit conversion
foo(static_cast<X>(2));     // OK: explicit conversion

bar(2);                     // OK: implicit conversion via Y(int) 
bar(Y(2));                  // OK: direct initialization
bar(static_cast<Y>(2));     // OK: explicit conversion

Object initialization:

X x2 = 2;                   // error: no implicit conversion int to X possible
X x3(2);                    // OK: direct initialization
X x4 = X(2);                // OK: direct initialization
X x5 = static_cast<X>(2);   // OK: explicit conversion 

Y y2 = 2;                   // OK: implicit conversion via Y(int)
Y y3(2);                    // OK: direct initialization
Y y4 = Y(2);                // OK: direct initialization
Y y5 = static_cast<Y>(2);   // OK: explicit conversion

Examples regarding conversion functions:

X x1{ 0 };
Y y1{ 0 };

Conversion of a function argument:

baz(x1);                    // error: X not implicitly convertible to Z
baz(Z(x1));                 // OK: explicit initialization
baz(static_cast<Z>(x1));    // OK: explicit conversion

baz(y1);                    // OK: implicit conversion via Y::operator Z()
baz(Z(y1));                 // OK: direct initialization
baz(static_cast<Z>(y1));    // OK: explicit conversion

Object initialization:

Z z1 = x1;                  // error: X not implicitly convertible to Z
Z z2(x1);                   // OK: explicit initialization
Z z3 = Z(x1);               // OK: explicit initialization
Z z4 = static_cast<Z>(x1);  // OK: explicit conversion

Z z1 = y1;                  // OK: implicit conversion via Y::operator Z()
Z z2(y1);                   // OK: direct initialization
Z z3 = Z(y1);               // OK: direct initialization
Z z4 = static_cast<Z>(y1);  // OK: explicit conversion

Why use explicit conversion functions or constructors?

Conversion constructors and non-explicit conversion functions may introduce ambiguity.

Consider a structure V, convertible to int, a structure U implicitly constructible from V and a function f overloaded for U and bool respectively.

struct V {
  operator bool() const { return true; }
};

struct U { U(V) { } };

void f(U) { }
void f(bool) {  }

A call to f is ambiguous if passing an object of type V.

V x;
f(x);  // error: call of overloaded 'f(V&)' is ambiguous

The compiler does not know wether to use the constructor of U or the conversion function to convert the V object into a type for passing to f.

If either the constructor of U or the conversion function of V would be explicit, there would be no ambiguity since only the non-explicit conversion would be considered. If both are explicit the call to f using an object of type V would have to be done using an explicit conversion or cast operation.

Conversion constructors and non-explicit conversion functions may lead to unexpected behaviour.

Consider a function printing some vector:

void print_intvector(std::vector<int> const &v) { for (int x : v) std::cout << x << '\n'; }

If the size-constructor of the vector would not be explicit it would be possible to call the function like this:

print_intvector(3);

What would one expect from such a call? One line containing 3 or three lines containing 0? (Where the second one is what happens.)

Using the explicit keyword in a class interface enforces the user of the interface to be explicit about a desired conversion.

As Bjarne Stroustrup puts it (in "The C++ Programming Language", 4th Ed., 35.2.1, pp. 1011) on the question why std::duration cannot be implicitly constructed from a plain number:

If you know what you mean, be explicit about it.

How do I activate a virtualenv inside PyCharm's terminal?

Thanks Chris, your script worked for some projects but not all on my machine. Here is a script that I wrote and I hope anyone finds it useful.

#Stored in ~/.pycharmrc 

ACTIVATERC=$(python -c 'import re
import os
from glob import glob

try:
  #sets Current Working Directory to _the_projects .idea folder
  os.chdir(os.getcwd()+"/.idea") 

  #gets every file in the cwd and sets _the_projects iml file
  for file in glob("*"): 
    if re.match("(.*).iml", file):
      project_iml_file = file

  #gets _the_virtual_env for _the_project
  for line in open(project_iml_file):
    env_name = re.findall("~/(.*)\" jdkType", line.strip())
    # created or changed a virtual_env after project creation? this will be true
    if env_name:
      print env_name[0] + "/bin/activate"
      break

    inherited = re.findall("type=\"inheritedJdk\"", line.strip())
    # set a virtual_env during project creation? this will be true
    if inherited:
      break

  # find _the_virtual_env in misc.xml
  if inherited:
    for line in open("misc.xml").readlines():
      env_at_project_creation = re.findall("\~/(.*)\" project-jdk", line.strip())
      if env_at_project_creation:
        print env_at_project_creation[0] + "/bin/activate"
        break
finally:
  pass
')

if [ "$ACTIVATERC" ] ; then . "$HOME/$ACTIVATERC" ; fi