Programs & Examples On #Passphrase

A passphrase is a sequence of words or other text used to control access to a computer system, program or data. Passphrases are often used to control both access to, and operation of, cryptographic programs and systems.

How do I remove the passphrase for the SSH key without having to create a new key?

In windows for me it kept saying "id_ed25135: No such file or directory" upon entering above commands. So I went to the folder, copied the path within folder explorer and added "\id_ed25135" at the end.

This is what I ended up typing and worked:
ssh-keygen -p -f C:\Users\john\.ssh\id_ed25135

This worked. Because for some reason, in Cmder the default path was something like this C:\Users\capit/.ssh/id_ed25135 (some were backslashes: "\" and some were forward slashes: "/")

How to reset or change the passphrase for a GitHub SSH key?

If you had generate a SSH-key with passphrase and then you forget your passphrase for this SSH-key,there's no way to recover it, You'll need to generate a brand new SSH keypair or switch to HTTPS cloning so you can use your GitHub password instead.

BUT,there are exceptions

If you configured your SSH passphrase with the OS X Keychain, you may be able to recover it.

  1. In Finder, search for the Keychain Access app.
  2. In Keychain Access, search for SSH.
  3. Double click on the entry for your SSH key to open a new dialog box.
  4. Keychain access dialogIn the lower-left corner, select Show password.
  5. You'll be prompted for your administrative password. Type it into the "Keychain Access" dialog box.
  6. Your password will be revealed.

Refer to Github help - How do I recover my SSH key passphrase?

Styling JQuery UI Autocomplete

You can overwrite the classes in your own css using !important, e.g. if you want to get rid of the rounded corners.

.ui-corner-all
{
border-radius: 0px !important;
}

Auto-increment on partial primary key with Entity Framework Core

First of all you should not merge the Fluent Api with the data annotation so I would suggest you to use one of the below:

make sure you have correclty set the keys

modelBuilder.Entity<Foo>()
            .HasKey(p => new { p.Name, p.Id });
modelBuilder.Entity<Foo>().Property(p => p.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);

OR you can achieve it using data annotation as well

public class Foo
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key, Column(Order = 0)]
    public int Id { get; set; }

    [Key, Column(Order = 1)]
    public string Name{ get; set; }
}

WCF Service , how to increase the timeout?

In your binding configuration, there are four timeout values you can tweak:

<bindings>
  <basicHttpBinding>
    <binding name="IncreasedTimeout"
             sendTimeout="00:25:00">
    </binding>
  </basicHttpBinding>

The most important is the sendTimeout, which says how long the client will wait for a response from your WCF service. You can specify hours:minutes:seconds in your settings - in my sample, I set the timeout to 25 minutes.

The openTimeout as the name implies is the amount of time you're willing to wait when you open the connection to your WCF service. Similarly, the closeTimeout is the amount of time when you close the connection (dispose the client proxy) that you'll wait before an exception is thrown.

The receiveTimeout is a bit like a mirror for the sendTimeout - while the send timeout is the amount of time you'll wait for a response from the server, the receiveTimeout is the amount of time you'll give you client to receive and process the response from the server.

In case you're send back and forth "normal" messages, both can be pretty short - especially the receiveTimeout, since receiving a SOAP message, decrypting, checking and deserializing it should take almost no time. The story is different with streaming - in that case, you might need more time on the client to actually complete the "download" of the stream you get back from the server.

There's also openTimeout, receiveTimeout, and closeTimeout. The MSDN docs on binding gives you more information on what these are for.

To get a serious grip on all the intricasies of WCF, I would strongly recommend you purchase the "Learning WCF" book by Michele Leroux Bustamante:

Learning WCF http://ecx.images-amazon.com/images/I/51GNuqUJq%2BL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

and you also spend some time watching her 15-part "WCF Top to Bottom" screencast series - highly recommended!

For more advanced topics I recommend that you check out Juwal Lowy's Programming WCF Services book.

Programming WCF http://ecx.images-amazon.com/images/I/41odWcLoGAL._BO2,204,203,200_PIsitb-sticker-arrow-click,TopRight,35,-76_AA240_SH20_OU01_.jpg

remove borders around html input

Try this

#generic_search_button
{
    float: left;
    width: 24px; /*new width*/
    height: 24px; /*new width*/
    border: none !important; /* no border and override any inline styles*/
    margin-top: 7px;
    cursor: pointer;
    background-color: White;
    background-image: url(/Images/search.png);
    background-repeat: no-repeat;
    background-position: center center;
}

I think the image size might be wrong

How do you make a div follow as you scroll?

Using styling from CSS, you can define how something is positioned. If you define the element as fixed, it will always remain in the same position on the screen at all times.

div
{
    position:fixed;
    top:20px;
}

MySQL Job failed to start

Reinstallation will works because it will reset all the value to default. It is better to find what the real culprits (my.cnf editing mistake does happens, e.g. bad/outdated parameter suggestion during mysql tuning.)

Here is the mysql diagnosis if you suspect some value is wrong inside my.cnf : Run the mysqld to show you the results.

sudo -u mysql  mysqld 

Afterwards, fix all the my.cnf key error that pop out from the screen until mysqld startup successfully.

Then restart it using

sudo service mysql restart

How to edit the legend entry of a chart in Excel?

The data series names are defined by the column headers. Add the names to the column headers that you would like to use as titles for each of your data series, select all of the data (including the headers), then re-generate your graph. The names in the headers should then appear as the names in the legend for each series.

Column headers become data series titles in graph legend

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

Display an image into windows forms

I display images in windows forms when I put it in Load event like this:

    private void Form1_Load( object sender , EventArgs e )
    {
        pictureBox1.ImageLocation = "./image.png"; //path to image
        pictureBox1.SizeMode = PictureBoxSizeMode.AutoSize;
    }

How to concat string + i?

You can concatenate strings using strcat. If you plan on concatenating numbers as strings, you must first use num2str to convert the numbers to strings.

Also, strings can't be stored in a vector or matrix, so f must be defined as a cell array, and must be indexed using { and } (instead of normal round brackets).

f = cell(N, 1);
for i=1:N
   f{i} = strcat('f', num2str(i));
end

How to check whether a int is not null or empty?

An integer can't be null but there is a really simple way of doing what you want to do. Use an if-then statement in which you check the integer's value against all possible values.

Example:

int x;

// Some Code...

if (x <= 0 || x > 0){
    // What you want the code to do if x has a value
} else {
    // What you want the code to do if x has no value 
}

Disclaimer: I am assuming that Java does not automatically set values of numbers to 0 if it doesn't see a value.

Difference between Git and GitHub

Git is a revision control system, a tool to manage your source code history.

GitHub is a hosting service for Git repositories.

So they are not the same thing: Git is the tool, GitHub is the service for projects that use Git.

To get your code to GitHub, have a look here.

Using Google Translate in C#

The reason the first code sample doesn't work is because the layout of the page changed. As per the warning on that page: "The translated string is fetched by the RegEx close to the bottom. This could of course change, and you have to keep it up to date." I think this should work for now, at least until they change the page again.


public string TranslateText(string input, string languagePair)
{
    string url = String.Format("http://www.google.com/translate_t?hl=en&ie=UTF8&text={0}&langpair={1}", input, languagePair);
    WebClient webClient = new WebClient();
    webClient.Encoding = System.Text.Encoding.UTF8;
    string result = webClient.DownloadString(url);
    result = result.Substring(result.IndexOf("<span title=\"") + "<span title=\"".Length);
    result = result.Substring(result.IndexOf(">") + 1);
    result = result.Substring(0, result.IndexOf("</span>"));
    return result.Trim();
}

Selenium Webdriver move mouse to Point

Why use java.awt.Robot when org.openqa.selenium.interactions.Actions.class would probably work fine? Just sayin.

Actions builder = new Actions(driver);

builder.keyDown(Keys.CONTROL)
   .click(someElement)
   .moveByOffset( 10, 25 );
   .click(someOtherElement)
   .keyUp(Keys.CONTROL).build().perform();

How to make the background DIV only transparent using CSS

I don't know if this has changed. But from my experience. nested elements have a maximum opacity equal to the fathers.

Which mean:

<div id="a">
<div id="b">
</div></div>

Div#a has 0.6 opacity
div#b has 1 opacity

Has #b is within #a then it's maximum opacity is always 0.6

If #b would have 0.5 opacity. In reallity it would be 0.6*0.5 == 0.3 opacity

Cannot resolve the collation conflict between "SQL_Latin1_General_CP1_CI_AS" and "Latin1_General_CI_AS" in the equal to operation

Check the level of collation that is mismatched (server, database,table,column,character).

If it is the server, these steps helped me once:

  1. Stop the server
  2. Find your sqlservr.exe tool
  3. Run this command:

    sqlservr -m -T4022 -T3659 -s"name_of_insance" -q "name_of_collation"

  4. Start your sql server:

    net start name_of_instance

  5. Check the collation of your server again.

Here is more info:

https://www.mssqltips.com/sqlservertip/3519/changing-sql-server-collation-after-installation/

Pure CSS checkbox image replacement

You are close already. Just make sure to hide the checkbox and associate it with a label you style via input[checkbox] + label

Complete Code: http://gist.github.com/592332

JSFiddle: http://jsfiddle.net/4huzr/

cannot connect to pc-name\SQLEXPRESS

try using IP instead of pc name. If the ip working, then it might be the name pipe is not enable. If it;s still not working then the login using windows might be disabled.

Name attribute in @Entity and @Table

@Entity(name = "someThing") => this name will be used to name the Entity
@Table(name = "someThing")  => this name will be used to name a table in DB

So, in the first case your table and entity will have the same name, that will allow you to access your table with the same name as the entity while writing HQL or JPQL.

And in second case while writing queries you have to use the name given in @Entity and the name given in @Table will be used to name the table in the DB.

So in HQL your someThing will refer to otherThing in the DB.

Bash scripting missing ']'

Change

if [ -s "p1"];  #line 13

into

if [ -s "p1" ];  #line 13

note the space.

Add quotation at the start and end of each line in Notepad++

  • One simple way is replace \n(newline) with ","(double-quote comma double-quote) after this append double-quote in the start and end of file.

example:

      AliceBlue
      AntiqueWhite
      Aqua
      Aquamarine
      Beige
  • Replcae \n with ","

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

If your text contains blank lines in between you can use regular expression \n+ instead of \n

example:

      AliceBlue

      AntiqueWhite
      Aqua


      Aquamarine
      Beige
  • Replcae \n+ with "," (in regex mode)

      AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige
    
  • Now append "(double-quote) at the start and end

     "AliceBlue","AntiqueWhite","Aqua","Aquamarine","Beige"
    

How to roundup a number to the closest ten?

You can use the function MROUND(<reference cell>, <round to multiple of digit needed>).

Example:

  1. For a value A1 = 21 round to multiple of 10 it would be written as =MROUND(A1,10) for which Result = 20

  2. For a value Z4 = 55.1 round to multiple of 10 it would be written as =MROUND(Z4,10) for which Result = 60

Save the console.log in Chrome to a file

This may or may not be helpful but on Windows you can read the console log using Event Tracing for Windows

http://msdn.microsoft.com/en-us/library/ms751538.aspx

Our integration tests are run in .NET so I use this method to add the console log to our test output. I've made a sample console project to demonstrate here: https://github.com/jkells/chrome-trace

--enable-logging --v=1 doesn't seem to work on the latest version of Chrome.

How to add one column into existing SQL Table

Its work perfectly

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL;

But if you want more precise in table then you can try AFTER.

ALTER TABLE `products` ADD `LastUpdate` varchar(200) NULL AFTER `column_name`;

It will add LastUpdate column after specified column name (column_name).

Receiving "Attempted import error:" in react app

I guess I am coming late, but this info might be useful to anyone I found out something, which might be simple but important. if you use export on a function directly i.e

export const addPost = (id) =>{
  ...
 }

Note while importing you need to wrap it in curly braces i.e. import {addPost} from '../URL';

But when using export default i.e

const addPost = (id) =>{
  ...
 }

export default addPost,

Then you can import without curly braces i.e. import addPost from '../url';

export default addPost

I hope this helps anyone who got confused as me.

Change User Agent in UIWebView

Modern Swift

Here's a suggestion for Swift 3+ projects from StackOverflow users PassKit and Kheldar:

UserDefaults.standard.register(defaults: ["UserAgent" : "Custom Agent"])

Source: https://stackoverflow.com/a/27330998/128579

Earlier Objective-C Answer

With iOS 5 changes, I recommend the following approach, originally from this StackOverflow question: UIWebView iOS5 changing user-agent as pointed out in an answer below. In comments on that page, it appears to work in 4.3 and earlier also.

Change the "UserAgent" default value by running this code once when your app starts:

NSDictionary *dictionary = @{@"UserAgent": @"Your user agent"};
[[NSUserDefaults standardUserDefaults] registerDefaults:dictionary];
[[NSUserDefaults standardUserDefaults] synchronize];

See previous edits on this post if you need methods that work in versions of iOS before 4.3/5.0. Note that because of the extensive edits, the following comments / other answers on this page may not make sense. This is a four year old question, after all. ;-)

Why can a function modify some arguments as perceived by the caller, but not others?

I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.

a = 'string'
a.replace('t', '_')
print(a)
>>> 'string'

a = a.replace('t', '_')
print(a)
>>> 's_ring'

b = 100
b + 1
print(b)
>>> 100

b = b + 1
print(b)
>>> 101

def test_id(arg):
    c = id(arg)
    arg = 123
    d = id(arg)
    return

a = 'test ids'
b = id(a)
test_id(a)
e = id(a)

# b = c  = e != d
# this function do change original value
del change_like_mutable(arg):
    arg.append(1)
    arg.insert(0, 9)
    arg.remove(2)
    return

test_1 = [1, 2, 3]
change_like_mutable(test_1)



# this function doesn't 
def wont_change_like_str(arg):
     arg = [1, 2, 3]
     return


test_2 = [1, 1, 1]
wont_change_like_str(test_2)
print("Doesn't change like a imutable", test_2)

This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.

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.

HTML table with fixed headers and a fixed column?

I know you can do it for MSIE and this limited example seems to work for firefox (not sure how extensible the technique is).

Converting <br /> into a new line for use in a text area

The answer by @Mobilpadde is nice. But this is my solution with regex using preg_replace which might be faster according to my tests.

echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");

function function_one() {
    preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}

function function_two() {
    str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}

function benchmark() {
    $count = 10000000;
    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_one();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function one\n";



    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_two();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();

Results:

1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)

iterrows pandas get next rows value

There is a pairwise() function example in the itertools document:

from itertools import tee, izip
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = tee(iterable)
    next(b, None)
    return izip(a, b)

import pandas as pd
df = pd.DataFrame(['AA', 'BB', 'CC'], columns = ['value'])

for (i1, row1), (i2, row2) in pairwise(df.iterrows()):
    print i1, i2, row1["value"], row2["value"]

Here is the output:

0 1 AA BB
1 2 BB CC

But, I think iter rows in a DataFrame is slow, if you can explain what's the problem you want to solve, maybe I can suggest some better method.

Select all DIV text with single mouse click

_x000D_
_x000D_
function selectText(containerid) {_x000D_
    if (document.selection) { // IE_x000D_
        var range = document.body.createTextRange();_x000D_
        range.moveToElementText(document.getElementById(containerid));_x000D_
        range.select();_x000D_
    } else if (window.getSelection) {_x000D_
        var range = document.createRange();_x000D_
        range.selectNode(document.getElementById(containerid));_x000D_
        window.getSelection().removeAllRanges();_x000D_
        window.getSelection().addRange(range);_x000D_
    }_x000D_
}
_x000D_
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>
_x000D_
_x000D_
_x000D_

Now you have to pass the ID as an argument, which in this case is "selectable", but it's more global, allowing you to use it anywhere multiple times without using, as chiborg mentioned, jQuery.

How to run a script at a certain time on Linux?

Look at the following:

echo "ls -l" | at 07:00

This code line executes "ls -l" at a specific time. This is an example of executing something (a command in my example) at a specific time. "at" is the command you were really looking for. You can read the specifications here:

http://manpages.ubuntu.com/manpages/precise/en/man1/at.1posix.html http://manpages.ubuntu.com/manpages/xenial/man1/at.1posix.html

Hope it helps!

Reading inputStream using BufferedReader.readLine() is too slow

I have a longer test to try. This takes an average of 160 ns to read each line as add it to a List (Which is likely to be what you intended as dropping the newlines is not very useful.

public static void main(String... args) throws IOException {
    final int runs = 5 * 1000 * 1000;

    final ServerSocket ss = new ServerSocket(0);
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                Socket serverConn = ss.accept();
                String line = "Hello World!\n";
                BufferedWriter br = new BufferedWriter(new OutputStreamWriter(serverConn.getOutputStream()));
                for (int count = 0; count < runs; count++)
                    br.write(line);
                serverConn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }).start();

    Socket conn = new Socket("localhost", ss.getLocalPort());

    long start = System.nanoTime();
    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
    String line;

    List<String> responseData = new ArrayList<String>();
    while ((line = in.readLine()) != null) {
        responseData.add(line);
    }
    long time = System.nanoTime() - start;
    System.out.println("Average time to read a line was " + time / runs + " ns.");
    conn.close();
    ss.close();
}

prints

Average time to read a line was 158 ns.

If you want to build a StringBuilder, keeping newlines I would suggets the following approach.

Reader r = new InputStreamReader(conn.getInputStream());
String line;

StringBuilder sb = new StringBuilder();
char[] chars = new char[4*1024];
int len;
while((len = r.read(chars))>=0) {
    sb.append(chars, 0, len);
}

Still prints

Average time to read a line was 159 ns.

In both cases, the speed is limited by the sender not the receiver. By optimising the sender, I got this timing down to 105 ns per line.

What is the best way to uninstall gems from a rails3 project?

Bundler is launched from your app's root directory so it makes sure all needed gems are present to get your app working.If for some reason you no longer need a gem you'll have to run the

    gem uninstall gem_name 

as you stated above.So every time you run bundler it'll recheck dependencies

EDIT - 24.12.2014

I see that people keep coming to this question I decided to add a little something. The answer I gave was for the case when you maintain your gems global. Consider using a gem manager such as rbenv or rvm to keep sets of gems scoped to specific projects.

This means that no gems will be installed at a global level and therefore when you remove one from your project's Gemfile and rerun bundle then it, obviously, won't be loaded in your project. Then, you can run bundle clean (with the project dir) and it will remove from the system all those gems that were once installed from your Gemfile (in the same dir) but at this given time are no longer listed there.... long story short - it removes unused gems.

Finding absolute value of a number without using Math.abs()

Although this shouldn't be a bottle neck as branching issues on modern processors isn't normally a problem, but in the case of integers you could go for a branch-less solution as outlined here: http://graphics.stanford.edu/~seander/bithacks.html#IntegerAbs.

(x + (x >> 31)) ^ (x >> 31);

This does fail in the obvious case of Integer.MIN_VALUE however, so this is a use at your own risk solution.

Change the Value of h1 Element within a Form with JavaScript

document.getElementById("myh1id").innerHTML = "my text"

Dynamically updating css in Angular 2

All the above answers are great. But if you were trying to find a solution that won't change the html files below is helpful

 ngAfterViewChecked(){
    this.renderer.setElementStyle(targetItem.nativeElement, 'height', textHeight+"px");
}

You can import renderer from import {Renderer} from '@angular/core';

Format date as dd/MM/yyyy using pipes

I think that it's because the locale is hardcoded into the DatePipe. See this link:

And there is no way to update this locale by configuration right now.

ERROR in Cannot find module 'node-sass'

One of the cases is the post-install process fails. Right after node-sass is installed, the post-install script will be executed. It requires Python and a C++ builder for that process. The log 'gyp: No Xcode or CLT version detected!' maybe because it couldn't find any C++ builder. So try installing Python and any C++ builder then put their directories in environment variables so that npm can find them. (I come from Windows)

How do I stop a program when an exception is raised in Python?

If you don't handle an exception, it will propagate up the call stack up to the interpreter, which will then display a traceback and exit. IOW : you don't have to do anything to make your script exit when an exception happens.

How to write to files using utl_file in oracle

Here's an example of code which uses the UTL_FILE.PUT and UTL_FILE.PUT_LINE calls:

declare 
  fHandle  UTL_FILE.FILE_TYPE;
begin
  fHandle := UTL_FILE.FOPEN('my_directory', 'test_file', 'w');

  UTL_FILE.PUT(fHandle, 'This is the first line');
  UTL_FILE.PUT(fHandle, 'This is the second line');
  UTL_FILE.PUT_LINE(fHandle, 'This is the third line');

  UTL_FILE.FCLOSE(fHandle);
EXCEPTION
  WHEN OTHERS THEN
    DBMS_OUTPUT.PUT_LINE('Exception: SQLCODE=' || SQLCODE || '  SQLERRM=' || SQLERRM);
    RAISE;
end;

The output from this looks like:

This is the first lineThis is the second lineThis is the third line

Share and enjoy.

How to fix "namespace x already contains a definition for x" error? Happened after converting to VS2010

I had this problem. It was due to me renaming a folder in the App_Code directory and releasing to my iis site folder. The original named folder was still present in my target directory - hence duplicate - (I don't do a full delete of target before copying) Anyway removing the old folder fixed this.

Node.js - Find home directory in platform agnostic way

os.homedir() was added by this PR and is part of the public 4.0.0 release of nodejs.


Example usage:

const os = require('os');

console.log(os.homedir());

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

Here is a list of examples for sending cookies - https://github.com/andriichuk/php-curl-cookbook#cookies

$curlHandler = curl_init();

curl_setopt_array($curlHandler, [
CURLOPT_URL => 'https://httpbin.org/cookies',
CURLOPT_RETURNTRANSFER => true,

CURLOPT_COOKIEFILE  => $cookieFile,
CURLOPT_COOKIE => 'foo=bar;baz=foo',

/**
 * Or set header
 * CURLOPT_HTTPHEADER => [
       'Cookie: foo=bar;baz=foo',
   ]
 */
]);

$response = curl_exec($curlHandler);
curl_close($curlHandler);

echo $response;

Opening the Settings app from another app

To add to accepted answer: (from apple developer documentation) "When you open the URL built from this string (openSettingsURLString), the system launches the Settings app and displays the app’s custom settings, if it has any." So, if you want to open settings for your app, create your own Settings.bundle.

Should I use alias or alias_method?

I think there is an unwritten rule (something like a convention) that says to use 'alias' just for registering a method-name alias, means if you like to give the user of your code one method with more than one name:

class Engine
  def start
    #code goes here
  end
  alias run start
end

If you need to extend your code, use the ruby meta alternative.

class Engine
  def start
    puts "start me"
  end
end

Engine.new.start() # => start me

Engine.class_eval do
  unless method_defined?(:run)
    alias_method :run, :start
    define_method(:start) do
      puts "'before' extension"
      run()
      puts "'after' extension"
    end
  end
end

Engine.new.start
# => 'before' extension
# => start me
# => 'after' extension

Engine.new.run # => start me

Table row and column number in jQuery

Can you output that data in the cells as you are creating the table?

so your table would look like this:

<table>
  <thead>...</thead>
  <tbody>
    <tr><td data-row='1' data-column='1'>value</td>
      <td data-row='1' data-column='2'>value</td>
      <td data-row='1' data-column='3'>value</td></tr>

  <tbody>
</table>

then it would be a simple matter

$("td").click(function(event) {
   var row = $(this).attr("data-row");
   var col = $(this).attr("data-col");
}

What's the idiomatic syntax for prepending to a short python list?

The s.insert(0, x) form is the most common.

Whenever you see it though, it may be time to consider using a collections.deque instead of a list.

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

How to pass the id of an element that triggers an `onclick` event to the event handling function

Use this:

<link onclick='doWithThisElement(this.attributes["id"].value)' />

In the context of the onclick JavaScript, this refers to the current element (which in this case is the whole HTML element link).

SELECT FOR UPDATE with SQL Server

Recently I had a deadlock problem because Sql Server locks more then necessary (page). You can't really do anything against it. Now we are catching deadlock exceptions... and I wish I had Oracle instead.

Edit: We are using snapshot isolation meanwhile, which solves many, but not all of the problems. Unfortunately, to be able to use snapshot isolation it must be allowed by the database server, which may cause unnecessary problems at customers site. Now we are not only catching deadlock exceptions (which still can occur, of course) but also snapshot concurrency problems to repeat transactions from background processes (which cannot be repeated by the user). But this still performs much better than before.

Windows Batch: How to add Host-Entries?

I would do it this way, so you won't end up with duplicate entries if the script is run multiple times.

@echo off

SET NEWLINE=^& echo.

FIND /C /I "ns1.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^62.116.159.4 ns1.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns2.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^217.160.113.37 ns2.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns3.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^89.146.248.4 ns3.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

FIND /C /I "ns4.intranet.de" %WINDIR%\system32\drivers\etc\hosts
IF %ERRORLEVEL% NEQ 0 ECHO %NEWLINE%^74.208.254.4 ns4.intranet.de>>%WINDIR%\System32\drivers\etc\hosts

Java count occurrence of each item in an array

This is a simple script I used in Python but it can be easily adapted. Nothing fancy though.

def occurance(arr):
  results = []
  for n in arr:
      data = {}
      data["point"] = n
      data["count"] = 0
      for i in range(0, len(arr)):
          if n == arr[i]:
              data["count"] += 1
      results.append(data)
  return results

Toolbar overlapping below status bar

Just set this to v21/styles.xml file

 <item name="android:windowDrawsSystemBarBackgrounds">true</item>
 <item name="android:statusBarColor">@color/colorPrimaryDark</item>

and be sure

 <item name="android:windowTranslucentStatus">false</item>

How to check if a std::thread is still running?

This simple mechanism you can use for detecting finishing of a thread without blocking in join method.

std::thread thread([&thread]() {
    sleep(3);
    thread.detach();
});

while(thread.joinable())
    sleep(1);

Update a column value, replacing part of a string

UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')

Limit the output of the TOP command to a specific process name

I solved my problem using:

top -n1 -b | grep "proccess name"

in this case: -n is used to set how many times top will what proccess
and -b is used to show all pids

it's prevents errors like : top: pid limit (20) exceeded

How to remove application from app listings on Android Developer Console

The one exception worth noting is that while you can't delete apps, the folks over at Google Play Developer Support are able to on their end if the app is both unpublished and has 0 lifetime installs. So if your app has 0 lifetime installs, you might be in luck.

First you will need unpublish the app and wait 24 hours (to allow global stats to update and ensure that no last-minute installs happened). Assuming no last-minute installs happen over those 24 hours, you can contact Google Play Developer Support and check to see if they can delete it.

Please note that their requirement for 0 installs is a hard requirement. No exceptions can be made (not even if you installed the app yourself for testing purposes).

IN Clause with NULL or IS NULL

I know that is late to answer but could be useful for someone else You can use sub-query and convert the null to 0

SELECT *
FROM (SELECT CASE WHEN id_field IS NULL 
                THEN 0 
                ELSE id_field 
            END AS id_field
      FROM tbl_name) AS tbl
WHERE tbl.id_field IN ('value1', 'value2', 'value3', 0)

Setting the filter to an OpenFileDialog to allow the typical image formats?

Here's an example of the ImageCodecInfo suggestion (in VB):

   Imports System.Drawing.Imaging
        ...            

        Dim ofd as new OpenFileDialog()
        ofd.Filter = ""
        Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders()
        Dim sep As String = String.Empty
        For Each c As ImageCodecInfo In codecs
            Dim codecName As String = c.CodecName.Substring(8).Replace("Codec", "Files").Trim()
            ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, codecName, c.FilenameExtension)
            sep = "|"
        Next
        ofd.Filter = String.Format("{0}{1}{2} ({3})|{3}", ofd.Filter, sep, "All Files", "*.*")

And it looks like this:

enter image description here

Difference between Visual Basic 6.0 and VBA

VBA stands for Visual Basic For Applications and its a Visual Basic implementation intended to be used in the Office Suite.

The difference between them is that VBA is embedded inside Office documents (its an Office feature). VB is the ide/language for developing applications.

combining two string variables

you need to take out the quotes:

soda = a + b

(You want to refer to the variables a and b, not the strings "a" and "b")

Android - Pulling SQlite database android device

If your device is running Android v4 or above, you can pull app data, including it's database, without root by using adb backup command, then extract the backup file and access the sqlite database.

First backup app data to your PC via USB cable with the following command, replace app.package.name with the actual package name of the application.

adb backup -f ~/data.ab -noapk app.package.name

This will prompt you to "unlock your device and confirm the backup operation". Do not provide a password for backup encryption, so you can extract it later. Click on the "Back up my data" button on your device. The screen will display the name of the package you're backing up, then close by itself upon successful completion.

The resulting data.ab file in your home folder contains application data in android backup format. To extract it use the following command:

dd if=data.ab bs=1 skip=24 | openssl zlib -d | tar -xvf -

If the above ended with openssl:Error: 'zlib' is an invalid command. error, try the below.

dd if=data.ab bs=1 skip=24 | python -c "import zlib,sys;sys.stdout.write(zlib.decompress(sys.stdin.read()))" | tar -xvf -

The result is the apps/app.package.name/ folder containing application data, including sqlite database.

For more details you can check the original blog post.

Python Dictionary Comprehension

I really like the @mgilson comment, since if you have a two iterables, one that corresponds to the keys and the other the values, you can also do the following.

keys = ['a', 'b', 'c']
values = [1, 2, 3]
d = dict(zip(keys, values))

giving

d = {'a': 1, 'b': 2, 'c': 3}

Empty set literal?

Yes. The same notation that works for non-empty dict/set works for empty ones.

Notice the difference between non-empty dict and set literals:

{1: 'a', 2: 'b', 3: 'c'} -- a number of key-value pairs inside makes a dict
{'aaa', 'bbb', 'ccc'} -- a tuple of values inside makes a set

So:

{} == zero number of key-value pairs == empty dict
{*()} == empty tuple of values == empty set

However the fact, that you can do it, doesn't mean you should. Unless you have some strong reasons, it's better to construct an empty set explicitly, like:

a = set()

Performance:

The literal is ~15% faster than the set-constructor (CPython-3.8, 2019 PC, Intel(R) Core(TM) i7-8550U CPU @ 1.80GHz):

>>> %timeit ({*()} & {*()}) | {*()}
214 ns ± 1.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

>>> %timeit (set() & set()) | set()
252 ns ± 0.566 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

... and for completeness, Renato Garcia's frozenset proposal on the above expression is some 60% faster!

>>> ? = frozenset()

>>> %timeit (? & ?) | ?
100 ns ± 0.51 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

NB: As ctrueden noticed in comments, {()} is not an empty set. It's a set with 1 element: empty tuple.

How can I set a custom baud rate on Linux?

BOTHER appears to be available from <asm/termios.h> on Linux. Pulling the definition from there is going to be wildly non-portable, but I assume this API is non-portable anyway, so it's probably no big loss.

Get list of all input objects using JavaScript, without accessing a form object

var inputs = document.getElementsByTagName('input');
for (var i = 0; i < inputs.length; ++i) {
  // ...
}

How do I include a path to libraries in g++

In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")

Angular: conditional class with *ngClass

_x000D_
_x000D_
<div class="collapse in " [ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''" id="collapseExampleOrganization" aria-expanded="true" style="">_x000D_
 <ul>   <li class="nav-item" [ngClass]="{'active': active_tab=='manage'}">_x000D_
<a routerLink="/main/organization/manage" (click)="activemenu('manage')"> <i class="la la-building-o"></i>_x000D_
<p>Manage</p></a></li> _x000D_
<li class="nav-item" [ngClass]="{'active': active_tab=='assignservice'}"><a routerLink="/main/organization/assignservice" (click)="activemenu('assignservice')"><i class="la la-user"></i><p>Add organization</p></a></li>_x000D_
</ul></div>
_x000D_
_x000D_
_x000D_

Code is good example of ngClass if else condition.

[ngClass]="(active_tab=='assignservice' || active_tab=='manage')?'show':''"

[ngClass]="{'active': active_tab=='assignservice'}"

How to do a for loop in windows command line?

You might also consider adding ".

For example for %i in (*.wav) do opusenc "%~ni.wav" "%~ni.opus" is very good idea.

Converting a datetime string to timestamp in Javascript

Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond]) constructor signature of the Date object.

var dateString = '17-09-2013 10:08',
    dateTimeParts = dateString.split(' '),
    timeParts = dateTimeParts[1].split(':'),
    dateParts = dateTimeParts[0].split('-'),
    date;

date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);

console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400

You could also use a regular expression with capturing groups to parse the date string in one line.

var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);

console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]

How do I get the IP address into a batch-file variable?

This work even if you have a virtual network adapters or VPN connections:

FOR /F "tokens=4 delims= " %%i in ('route print ^| find " 0.0.0.0"') do set localIp=%%i
echo Your IP Address is: %localIp%

When and Why to use abstract classes/methods?

Abstract classes/methods are generally used when a class provides some high level functionality but leaves out certain details to be implemented by derived classes. Making the class/method abstract ensures that it cannot be used on its own, but must be specialized to define the details that have been left out of the high level implementation. This is most often used with the template method pattern:

http://en.wikipedia.org/wiki/Template_method_pattern

Javascript How to define multiple variables on a single line?

There is no way to do it in one line with assignment as value.

var a = b = 0;

makes b global. A correct way (without leaking variables) is the slightly longer:

var a = 0, b = a;

which is useful in the case:

var a = <someLargeExpressionHere>, b = a, c = a, d = a;

Why doesn't java.util.Set have get(int index)?

That is because Set only guarantees uniqueness, but says nothing about the optimal access or usage patterns. Ie, a Set can be a List or a Map, each of which have very different retrieval characteristics.

PHP new line break in emails

If you output to html or an html e-mail you will need to use <br> or <br /> instead of \n.

If it's just a text e-mail: Are you perhaps using ' instead of "? Although then your values would not be inserted either...

Android failed to load JS bundle

The following made it work for me on Ubuntu 14.04:

cd (App Dir)
react-native start > /dev/null 2>&1 &
adb reverse tcp:8081 tcp:8081

Update: See

Update 2: @scgough We got this error because React Native (RN) was unable to fetch JavaScript from the dev server running on our workstations. You can see why this happens here:

https://github.com/facebook/react-native/blob/42eb5464fd8a65ed84b799de5d4dc225349449be/ReactAndroid/src/main/java/com/facebook/react/devsupport/DevServerHelper.java#L116-L137

If your RN app detects that you're using Genymotion or the emulator it tries to fetch the JavaScript from GENYMOTION_LOCALHOST (10.0.3.2) or EMULATOR_LOCALHOST (10.0.2.2). Otherwise it presumes that you're using a device and it tries to fetch the JavaScript from DEVICE_LOCALHOST (localhost). The problem is that the dev server runs on your workstation's localhost, not the device's, so in order to get it to work you need to either:

Could pandas use column as index?

Yes, with set_index you can make Locality your row index.

data.set_index('Locality', inplace=True)

If inplace=True is not provided, set_index returns the modified dataframe as a result.

Example:

> import pandas as pd
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
                     ['ABERFELDIE', 534000, 600000]],
                    columns=['Locality', 2005, 2006])

> df
     Locality    2005    2006
0  ABBOTSFORD  427000  448000
1  ABERFELDIE  534000  600000

> df.set_index('Locality', inplace=True)
> df
              2005    2006
Locality                  
ABBOTSFORD  427000  448000
ABERFELDIE  534000  600000

> df.loc['ABBOTSFORD']
2005    427000
2006    448000
Name: ABBOTSFORD, dtype: int64

> df.loc['ABBOTSFORD'][2005]
427000

> df.loc['ABBOTSFORD'].values
array([427000, 448000])

> df.loc['ABBOTSFORD'].tolist()
[427000, 448000]

SQlite - Android - Foreign key syntax

As you can see in the error description your table contains the columns (_id, tast_title, notes, reminder_date_time) and you are trying to add a foreign key from a column "taskCat" but it does not exist in your table!

Android Studio Google JAR file causing GC overhead limit exceeded error

For me non of the answers worked I saw here worked. I guessed that having the CPU work extremely hard makes the computer hot. After I closed programs that consume large amounts of CPU (like chrome) and cooling down my laptop the problem disappeared.

For reference: I had the CPU on 96%-97% and Memory usage over 2,000,000K by a java.exe process (which was actually gradle related process).

Using a different font with twitter bootstrap

Hi you can create a customized build on bootstrap, just change the font name in the following pages

Bootstrap 2.3.2 http://getbootstrap.com/2.3.2/customize.html#variables

Bootstrap 3 http://getbootstrap.com/customize/#less-variables

After that, make sure to use proper @font-face in a css file and link that to your page. Or you could use font kit generators.

How do I run two commands in one line in Windows CMD?

In order to execute two commands at the same time, you must put an & (ampersand) symbol between the two commands. Like so:

color 0a & start chrome.exe

Cheers!

How to insert a large block of HTML in JavaScript?

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

NULL value for int in Update statement

Provided that your int column is nullable, you may write:

UPDATE dbo.TableName
SET TableName.IntColumn = NULL
WHERE <condition>

java.lang.NoClassDefFoundError: org/json/JSONObject

Add json jar to your classpath

or use java -classpath json.jar ClassName

refer this

Bootstrap Element 100% Width

Though people have mentioned that you will need to use .container-fluid in this case but you will also have to remove the padding from bootstrap.

What is javax.inject.Named annotation supposed to be used for?

@Inject instead of Spring’s @Autowired to inject a bean.
@Named instead of Spring’s @Component to declare a bean.

Those JSR-330 standard annotations are scanned and retrieved the same way as Spring annotation (as long as the following jar is in your classpath)

How to Convert JSON object to Custom C# object?

To keep your options open, if you're using .NET 3.5 or later, here is a wrapped up example you can use straight from the framework using Generics. As others have mentioned, if it's not just simple objects you should really use JSON.net.

public static string Serialize<T>(T obj)
{
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    MemoryStream ms = new MemoryStream();
    serializer.WriteObject(ms, obj);
    string retVal = Encoding.UTF8.GetString(ms.ToArray());
    return retVal;
}

public static T Deserialize<T>(string json)
{
    T obj = Activator.CreateInstance<T>();
    MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
    DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
    obj = (T)serializer.ReadObject(ms);
    ms.Close();
    return obj;
}

You'll need:

using System.Runtime.Serialization;

using System.Runtime.Serialization.Json;

Remove the legend on a matplotlib figure

if you call pyplot as plt

frameon=False is to remove the border around the legend

and '' is passing the information that no variable should be in the legend

import matplotlib.pyplot as plt
plt.legend('',frameon=False)

Get local href value from anchor (a) tag

In my case I had a href with a # and target.href was returning me the complete url. Target.hash did the work for me.

$(".test a").on('click', function(e) {
    console.log(e.target.href); // logs https://www.test.com/#test
    console.log(e.target.hash); // logs #test
  });

Capture Image from Camera and Display in Activity

Capture photo + Choose from Gallery:

        a = (ImageButton)findViewById(R.id.imageButton1);

        a.setOnClickListener(new View.OnClickListener() {

            @Override

            public void onClick(View v) {

                selectImage();

            }

        });
    }
    private File savebitmap(Bitmap bmp) {
      String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
      OutputStream outStream = null;
     // String temp = null;
        File file = new File(extStorageDirectory, "temp.png");
      if (file.exists()) {
       file.delete();
       file = new File(extStorageDirectory, "temp.png");

      }

      try {
       outStream = new FileOutputStream(file);
       bmp.compress(Bitmap.CompressFormat.PNG, 100, outStream);
       outStream.flush();
       outStream.close();

      } catch (Exception e) {
       e.printStackTrace();
       return null;
      }
      return file;
     }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
     private void selectImage() {



            final CharSequence[] options = { "Take Photo", "Choose from Gallery","Cancel" };



            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);

            builder.setTitle("Add Photo!");

            builder.setItems(options, new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialog, int item) {

                    if (options[item].equals("Take Photo"))

                    {

                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

                        File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");

                        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                        //pic = f;

                        startActivityForResult(intent, 1);


                    }

                    else if (options[item].equals("Choose from Gallery"))

                    {

                        Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                        startActivityForResult(intent, 2);



                    }

                    else if (options[item].equals("Cancel")) {

                        dialog.dismiss();

                    }

                }

            });

            builder.show();

        }



        @Override

        protected void onActivityResult(int requestCode, int resultCode, Intent data) {

            super.onActivityResult(requestCode, resultCode, data);

            if (resultCode == RESULT_OK) {

                if (requestCode == 1) {
                    //h=0;
                    File f = new File(Environment.getExternalStorageDirectory().toString());

                    for (File temp : f.listFiles()) {

                        if (temp.getName().equals("temp.jpg")) {

                            f = temp;
                            File photo = new File(Environment.getExternalStorageDirectory(), "temp.jpg");
                           //pic = photo;
                            break;

                        }

                    }

                    try {

                        Bitmap bitmap;

                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();



                        bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),

                                bitmapOptions); 



                        a.setImageBitmap(bitmap);




                        String path = android.os.Environment

                                .getExternalStorageDirectory()

                                + File.separator

                                + "Phoenix" + File.separator + "default";
                        //p = path;

                        f.delete();

                        OutputStream outFile = null;

                        File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");

                        try {

                            outFile = new FileOutputStream(file);

                            bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
    //pic=file;
                            outFile.flush();

                            outFile.close();


                        } catch (FileNotFoundException e) {

                            e.printStackTrace();

                        } catch (IOException e) {

                            e.printStackTrace();

                        } catch (Exception e) {

                            e.printStackTrace();

                        }

                    } catch (Exception e) {

                        e.printStackTrace();

                    }

                } else if (requestCode == 2) {



                    Uri selectedImage = data.getData();
                   // h=1;
    //imgui = selectedImage;
                    String[] filePath = { MediaStore.Images.Media.DATA };

                    Cursor c = getContentResolver().query(selectedImage,filePath, null, null, null);

                    c.moveToFirst();

                    int columnIndex = c.getColumnIndex(filePath[0]);

                    String picturePath = c.getString(columnIndex);

                    c.close();

                    Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));


                    Log.w("path of image from gallery......******************.........", picturePath+"");


                    a.setImageBitmap(thumbnail);

                }

            }

What does string::npos mean in this code?

std::string::npos is implementation defined index that is always out of bounds of any std::string instance. Various std::string functions return it or accept it to signal beyond the end of the string situation. It is usually of some unsigned integer type and its value is usually std::numeric_limits<std::string::size_type>::max () which is (thanks to the standard integer promotions) usually comparable to -1.

Truncate to three decimals in Python

Okay, this is just another approach to solve this working on the number as a string and performing a simple slice of it. This gives you a truncated output of the number instead of a rounded one.

num = str(1324343032.324325235)
i = num.index(".")
truncated = num[:i + 4]
    
print(truncated)

Output:

'1324343032.324'

Of course then you can parse:

float(truncated)

How to convert an object to a byte array in C#

To convert an object to a byte array:

// Convert an object to a byte array
public static byte[] ObjectToByteArray(Object obj)
{
    BinaryFormatter bf = new BinaryFormatter();
    using (var ms = new MemoryStream())
    {
        bf.Serialize(ms, obj);
        return ms.ToArray();
    }
}

You just need copy this function to your code and send to it the object that you need to convert to a byte array. If you need convert the byte array to an object again you can use the function below:

// Convert a byte array to an Object
public static Object ByteArrayToObject(byte[] arrBytes)
{
    using (var memStream = new MemoryStream())
    {
        var binForm = new BinaryFormatter();
        memStream.Write(arrBytes, 0, arrBytes.Length);
        memStream.Seek(0, SeekOrigin.Begin);
        var obj = binForm.Deserialize(memStream);
        return obj;
    }
}

You can use these functions with custom classes. You just need add the [Serializable] attribute in your class to enable serialization

PHP Redirect to another page after form submit

First give your input type submit a name, like this name='submitform'.

and then put this in your php file

if (isset($_POST['submitform']))
    {   
    ?>
<script type="text/javascript">
window.location = "http://www.google.com/";
</script>      
    <?php
    }

Don't forget to change the url to yours.

How to find a value in an array and remove it by using PHP array functions?

To find and remove multiple instance of value in an array, i have used the below code

$list = array(1,3,4,1,3,1,5,8);

$new_arr=array();

foreach($list as $value){

    if($value=='1')
    {
        continue;
    }
    else
    {
        $new_arr[]=$value;
    }     
}


print_r($new_arr);

How do I enable index downloads in Eclipse for Maven dependency search?

Tick 'Full Index Enabled' and then 'Rebuild Index' of the central repository in 'Global Repositories' under Window > Show View > Other > Maven > Maven Repositories, and it should work.

The rebuilding may take a long time depending on the speed of your internet connection, but eventually it works.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I use this script - it's antiquated, but effective in targeting a separate Internet Explorer 10 style sheet or JavaScript file that is included only if the browser is Internet Explorer 10, the same way you would with conditional comments. No jQuery or other plugin is required.

<script>
    /*@cc_on
      @if (@_jscript_version == 10)
          document.write(' <link type= "text/css" rel="stylesheet" href="your-ie10-styles.css" />');
      @end
    @*/
</script >

How to get margin value of a div in plain JavaScript?

The properties on the style object are only the styles applied directly to the element (e.g., via a style attribute or in code). So .style.marginTop will only have something in it if you have something specifically assigned to that element (not assigned via a style sheet, etc.).

To get the current calculated style of the object, you use either the currentStyle property (Microsoft) or the getComputedStyle function (pretty much everyone else).

Example:

var p = document.getElementById("target");
var style = p.currentStyle || window.getComputedStyle(p);

display("Current marginTop: " + style.marginTop);

Fair warning: What you get back may not be in pixels. For instance, if I run the above on a p element in IE9, I get back "1em".

Live Copy | Source

destination path already exists and is not an empty directory

This error comes up when you try to clone a repository in a folder which still contains .git folder (Hidden folder).

If the earlier answers doesn't work then you can proceed with my answer. Hope it will solve your issue.

Open terminal & change the directory to the destination folder (where you want to clone).

Now type: ls -a

You may see a folder named .git.

You have to remove that folder by the following command: rm -rf .git

Now you are ready to clone your project.

Bootstrap Datepicker - Months and Years Only

I'm using version 2(supports both bootstrap v2 and v3) and for me this works:

$("#datepicker").datepicker( {
    format: "mm/yyyy",
    startView: "year", 
    minView: "year"
});

LISTAGG function: "result of string concatenation is too long"

Thank you for advices. I had the same problem when concatenate several fields, but even xmlagg not helped me - I still got the ORA-01489. After several attempts I found the cause and solution:

  1. Cause: one of fields in my xmlagg stores large text;
  2. Solution: apply to_clob() function.

Example:

rtrim(xmlagg(xmlelement(t, t.field1 ||'|'|| 
                           t.field2 ||'|'|| 
                           t.field3 ||'|'|| 
                           to_clob(t.field4),'; ').extract('//text()')).GetClobVal(),',')

Hope this help anybody.

TypeError: only length-1 arrays can be converted to Python scalars while trying to exponentially fit data

Non-numpy functions like math.abs() or math.log10() don't play nicely with numpy arrays. Just replace the line raising an error with:

m = np.log10(np.abs(x))

Apart from that the np.polyfit() call will not work because it is missing a parameter (and you are not assigning the result for further use anyway).

Mockito verify order / sequence of method calls

Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.

Suppose I have two classes Foo and Bar:

public class Foo {
  public void first() {}
  public void second() {}
}

public class Bar {
  public void firstThenSecond(Foo foo) {
    foo.first();
    foo.second();
  }
}

I can then add a test class to test that Bar's firstThenSecond() method actually calls first(), then second(), and not second(), then first(). See the following test code:

public class BarTest {
  @Test
  public void testFirstThenSecond() {
    Bar bar = new Bar();
    Foo mockFoo = Mockito.mock(Foo.class);
    bar.firstThenSecond(mockFoo);

    InOrder orderVerifier = Mockito.inOrder(mockFoo);
    // These lines will PASS
    orderVerifier.verify(mockFoo).first();
    orderVerifier.verify(mockFoo).second();

    // These lines will FAIL
    // orderVerifier.verify(mockFoo).second();
    // orderVerifier.verify(mockFoo).first();
  }
}

java: ArrayList - how can I check if an index exists?

If your index is less than the size of your list then it does exist, possibly with null value. If index is bigger then you may call ensureCapacity() to be able to use that index.

If you want to check if a value at your index is null or not, call get()

How can I create an array with key value pairs?

No need array_push function.if you want to add multiple item it works fine. simply try this and it worked for me

class line_details {
   var $commission_one=array();
   foreach($_SESSION['commission'] as $key=>$data){
          $row=  explode('-', $key);
          $this->commission_one[$row['0']]= $row['1'];            
   }

}

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

Tools: replace not replacing in Android manifest

I fixed same issue. Solution for me:

  1. add the xmlns:tools="http://schemas.android.com/tools" line in the manifest tag
  2. add tools:replace=.. in the manifest tag
  3. move android:label=... in the manifest tag

Example:

 <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
              tools:replace="allowBackup, label"
              android:allowBackup="false"
              android:label="@string/all_app_name"/>

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

I think this is what you want, I already tested this code and works

The tools used are: (all these tools can be downloaded as Nuget packages)

http://fluentassertions.codeplex.com/

http://autofixture.codeplex.com/

http://code.google.com/p/moq/

https://nuget.org/packages/AutoFixture.AutoMoq

var fixture = new Fixture().Customize(new AutoMoqCustomization());
var myInterface = fixture.Freeze<Mock<IFileConnection>>();

var sut = fixture.CreateAnonymous<Transfer>();

myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>()))
        .Throws<System.IO.IOException>();

sut.Invoking(x => 
        x.TransferFiles(
            myInterface.Object, 
            It.IsAny<string>(), 
            It.IsAny<string>()
        ))
        .ShouldThrow<System.IO.IOException>();

Edited:

Let me explain:

When you write a test, you must know exactly what you want to test, this is called: "subject under test (SUT)", if my understanding is correctly, in this case your SUT is: Transfer

So with this in mind, you should not mock your SUT, if you substitute your SUT, then you wouldn't be actually testing the real code

When your SUT has external dependencies (very common) then you need to substitute them in order to test in isolation your SUT. When I say substitute I'm referring to use a mock, dummy, mock, etc depending on your needs

In this case your external dependency is IFileConnection so you need to create mock for this dependency and configure it to throw the exception, then just call your SUT real method and assert your method handles the exception as expected

  • var fixture = new Fixture().Customize(new AutoMoqCustomization());: This linie initializes a new Fixture object (Autofixture library), this object is used to create SUT's without having to explicitly have to worry about the constructor parameters, since they are created automatically or mocked, in this case using Moq

  • var myInterface = fixture.Freeze<Mock<IFileConnection>>();: This freezes the IFileConnection dependency. Freeze means that Autofixture will use always this dependency when asked, like a singleton for simplicity. But the interesting part is that we are creating a Mock of this dependency, you can use all the Moq methods, since this is a simple Moq object

  • var sut = fixture.CreateAnonymous<Transfer>();: Here AutoFixture is creating the SUT for us

  • myInterface.Setup(x => x.Get(It.IsAny<string>(), It.IsAny<string>())).Throws<System.IO.IOException>(); Here you are configuring the dependency to throw an exception whenever the Get method is called, the rest of the methods from this interface are not being configured, therefore if you try to access them you will get an unexpected exception

  • sut.Invoking(x => x.TransferFiles(myInterface.Object, It.IsAny<string>(), It.IsAny<string>())).ShouldThrow<System.IO.IOException>();: And finally, the time to test your SUT, this line uses the FluenAssertions library, and it just calls the TransferFiles real method from the SUT and as parameters it receives the mocked IFileConnection so whenever you call the IFileConnection.Get in the normal flow of your SUT TransferFiles method, the mocked object will be invoking throwing the configured exception and this is the time to assert that your SUT is handling correctly the exception, in this case, I am just assuring that the exception was thrown by using the ShouldThrow<System.IO.IOException>() (from the FluentAssertions library)

References recommended:

http://martinfowler.com/articles/mocksArentStubs.html

http://misko.hevery.com/code-reviewers-guide/

http://misko.hevery.com/presentations/

http://www.youtube.com/watch?v=wEhu57pih5w&feature=player_embedded

http://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=player_embedded

Task.Run with Parameter(s)?

Idea is to avoid using a Signal like above. Pumping int values into a struct prevents those values from changing (in the struct). I had the following Problem: loop var i would change before DoSomething(i) was called (i was incremented at end of loop before ()=> DoSomething(i,ii) was called). With the structs it doesn't happen anymore. Nasty bug to find: DoSomething(i, ii) looks great, but never sure if it gets called each time with a different value for i (or just a 100 times with i=100), hence -> struct

struct Job { public int P1; public int P2; }
…
for (int i = 0; i < 100; i++) {
    var job = new Job { P1 = i, P2 = i * i}; // structs immutable...
    Task.Run(() => DoSomething(job));
}

If Else in LINQ

Answer above is not suitable for complicate Linq expression. All you need is:

// set up the "main query"
var test = from p in _db.test select _db.test;
// if str1 is not null, add a where-condition
if(str1 != null)
{
    test = test.Where(p => p.test == str);
}

Download a file by jQuery.Ajax

I struggled with this issue for a long time. Finally an elegant external library suggested here helped me out.

How to increase memory limit for PHP over 2GB?

You can also try this:

ini_set("max_execution_time", "-1");
ini_set("memory_limit", "-1");
ignore_user_abort(true);
set_time_limit(0);

How to pass parameters to ThreadStart method in Thread?

How about this: (or is it ok to use like this?)

var test = "Hello";
new Thread(new ThreadStart(() =>
{
    try
    {
        //Staff to do
        Console.WriteLine(test);
    }
    catch (Exception ex)
    {
        throw;
    }
})).Start();

Add a column with a default value to an existing table in SQL Server

Add a new column to a table:

ALTER TABLE [table]
ADD Column1 Datatype

For example,

ALTER TABLE [test]
ADD ID Int

If the user wants to make it auto incremented then:

ALTER TABLE [test]
ADD ID Int IDENTITY(1,1) NOT NULL

How to implement onBackPressed() in Fragments?

Just add addToBackStack while you are transitioning between your fragments like below:

fragmentManager.beginTransaction().replace(R.id.content_frame,fragment).addToBackStack("tag").commit();

if you write addToBackStack(null) , it will handle it by itself but if you give a tag , you should handle it manually.

Create a dropdown component

This is the code to create dropdown in Angular 7, 8, 9

.html file code

<div>
<label>Summary: </label>
<select (change)="SelectItem($event.target.value)" class="select">
  <option value="0">--All--</option>
  <option *ngFor="let item of items" value="{{item.Id.Value}}">
    {{item.Name}}
  </option>
</select>
</div>

.ts file code

SelectItem(filterVal: any)
{
    var id=filterVal;
    //code
}

items is an array which should be initialized in .ts file.

selenium - chromedriver executable needs to be in PATH

Another way is download and unzip chromedriver and put 'chromedriver.exe' in C:\Python27\Scripts and then you need not to provide the path of driver, just

driver= webdriver.Chrome()

will work

pass parameter by link_to ruby on rails

You probably don't want to pass the car object as a parameter, try just passing car.id. What do you get when you inspect(params) after clicking "Add to cart"?

Manually type in a value in a "Select" / Drop-down HTML list?

Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.

http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx

But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").

CSS fixed width in a span

You can do it using a table, but it is not pure CSS.

<style>
ul{
    text-indent: 40px;
}

li{
    list-style-type: none;
    padding: 0;
}

span{
    color: #ff0000;
    position: relative;
    left: -40px;
}
</style>


<ul>
<span></span><li>The lazy dog.</li>
<span>AND</span><li>The lazy cat.</li>
<span>OR</span><li>The active goldfish.</li>
</ul>

Note that it doesn't display exactly like you want, because it switches line on each option. However, I hope that this helps you come closer to the answer.

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I have similar problems, in my case seem to be related to network connectivity:

Error Domain=NSURLErrorDomain Code=-1001 "The request timed out."

Things to check:

  • Is there any chance that your server is not able to respond within some time limit? Like 60 seconds or 4 minutes?
  • Is there a possibility that your device is switching networks (WiFi, 3G, VPN)?
  • Could someone (client vs. server) be waiting for authentication?

Sorry, no ideas how to fix. Just debugging this, trying to find out what the problem is (-1021, -1001, -1009)

Update: Google search was very kind to find this:

  • -1001 TimedOut - it took longer than the timeout which was alotted.
  • -1003 CannotFindHost - the host could not be found.
  • -1004 CannotConnectToHost - the host would not let us establish a connection.

Search for string and get count in vi editor

I suggest doing:

  1. Search either with * to do a "bounded search" for what's under the cursor, or do a standard /pattern search.
  2. Use :%s///gn to get the number of occurrences. Or you can use :%s///n to get the number of lines with occurrences.

** I really with I could find a plug-in that would giving messaging of "match N of N1 on N2 lines" with every search, but alas.

Note: Don't be confused by the tricky wording of the output. The former command might give you something like 4 matches on 3 lines where the latter might give you 3 matches on 3 lines. While technically accurate, the latter is misleading and should say '3 lines match'. So, as you can see, there really is never any need to use the latter ('n' only) form. You get the same info, more clearly, and more by using the 'gn' form.

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

How to pass query parameters with a routerLink

queryParams

queryParams is another input of routerLink where they can be passed like

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}">Somewhere</a>

fragment

<a [routerLink]="['../']" [queryParams]="{prop: 'xxx'}" [fragment]="yyy">Somewhere</a>

routerLinkActiveOptions

To also get routes active class set on parent routes:

[routerLinkActiveOptions]="{ exact: false }"

To pass query parameters to this.router.navigate(...) use

let navigationExtras: NavigationExtras = {
  queryParams: { 'session_id': sessionId },
  fragment: 'anchor'
};

// Navigate to the login page with extras
this.router.navigate(['/login'], navigationExtras);

See also https://angular.io/guide/router#query-parameters-and-fragments

How to select option in drop down using Capybara

To add yet another answer to the pile (because apparently there's so many ways of doing it depending on your setup) - I did it by selecting the literal option element and clicking it

find(".some-selector-for-dropdown option[value='1234']").select_option

It's not very pretty, but it works :/

How do I change select2 box height

Here's my take on Carpetsmoker's answer (which I liked due to it being dynamic), cleaned up and updated for select2 v4:

$('#selectField').on('select2:open', function (e) {
  var container = $(this).select('select2-container');
  var position = container.offset().top;
  var availableHeight = $(window).height() - position - container.outerHeight();
  var bottomPadding = 50; // Set as needed
  $('ul.select2-results__options').css('max-height', (availableHeight - bottomPadding) + 'px');
});

Simple regular expression for a decimal with a precision of 2

Valid regex tokens vary by implementation. A generic form is:

[0-9]+(\.[0-9][0-9]?)?

More compact:

\d+(\.\d{1,2})?

Both assume that both have at least one digit before and one after the decimal place.

To require that the whole string is a number of this form, wrap the expression in start and end tags such as (in Perl's form):

^\d+(\.\d{1,2})?$

To match numbers without a leading digit before the decimal (.12) and whole numbers having a trailing period (12.) while excluding input of a single period (.), try the following:

^(\d+(\.\d{0,2})?|\.?\d{1,2})$

Added

Wrapped the fractional portion in ()? to make it optional. Be aware that this excludes forms such as 12. Including that would be more like ^\d+\\.?\d{0,2}$.

Added

Use ^\d{1,6}(\.\d{1,2})?$ to stop repetition and give a restriction to whole part of the decimal value.

How to make a Python script run like a service or daemon in Linux

Here's a nice class that is taken from here:

#!/usr/bin/env python

import sys, os, time, atexit
from signal import SIGTERM

class Daemon:
        """
        A generic daemon class.

        Usage: subclass the Daemon class and override the run() method
        """
        def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
                self.stdin = stdin
                self.stdout = stdout
                self.stderr = stderr
                self.pidfile = pidfile

        def daemonize(self):
                """
                do the UNIX double-fork magic, see Stevens' "Advanced
                Programming in the UNIX Environment" for details (ISBN 0201563177)
                http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
                """
                try:
                        pid = os.fork()
                        if pid > 0:
                                # exit first parent
                                sys.exit(0)
                except OSError, e:
                        sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
                        sys.exit(1)

                # decouple from parent environment
                os.chdir("/")
                os.setsid()
                os.umask(0)

                # do second fork
                try:
                        pid = os.fork()
                        if pid > 0:
                                # exit from second parent
                                sys.exit(0)
                except OSError, e:
                        sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
                        sys.exit(1)

                # redirect standard file descriptors
                sys.stdout.flush()
                sys.stderr.flush()
                si = file(self.stdin, 'r')
                so = file(self.stdout, 'a+')
                se = file(self.stderr, 'a+', 0)
                os.dup2(si.fileno(), sys.stdin.fileno())
                os.dup2(so.fileno(), sys.stdout.fileno())
                os.dup2(se.fileno(), sys.stderr.fileno())

                # write pidfile
                atexit.register(self.delpid)
                pid = str(os.getpid())
                file(self.pidfile,'w+').write("%s\n" % pid)

        def delpid(self):
                os.remove(self.pidfile)

        def start(self):
                """
                Start the daemon
                """
                # Check for a pidfile to see if the daemon already runs
                try:
                        pf = file(self.pidfile,'r')
                        pid = int(pf.read().strip())
                        pf.close()
                except IOError:
                        pid = None

                if pid:
                        message = "pidfile %s already exist. Daemon already running?\n"
                        sys.stderr.write(message % self.pidfile)
                        sys.exit(1)

                # Start the daemon
                self.daemonize()
                self.run()

        def stop(self):
                """
                Stop the daemon
                """
                # Get the pid from the pidfile
                try:
                        pf = file(self.pidfile,'r')
                        pid = int(pf.read().strip())
                        pf.close()
                except IOError:
                        pid = None

                if not pid:
                        message = "pidfile %s does not exist. Daemon not running?\n"
                        sys.stderr.write(message % self.pidfile)
                        return # not an error in a restart

                # Try killing the daemon process       
                try:
                        while 1:
                                os.kill(pid, SIGTERM)
                                time.sleep(0.1)
                except OSError, err:
                        err = str(err)
                        if err.find("No such process") > 0:
                                if os.path.exists(self.pidfile):
                                        os.remove(self.pidfile)
                        else:
                                print str(err)
                                sys.exit(1)

        def restart(self):
                """
                Restart the daemon
                """
                self.stop()
                self.start()

        def run(self):
                """
                You should override this method when you subclass Daemon. It will be called after the process has been
                daemonized by start() or restart().
                """

Simple Random Samples from a Sql database

Maybe you could do

SELECT * FROM table LIMIT 10000 OFFSET FLOOR(RAND() * 190000)

How to Return partial view of another controller by controller?

Simply you could use:

PartialView("../ABC/XXX")

Should Jquery code go in header or footer?

Most jquery code executes on document ready, which doesn't happen until the end of the page anyway. Furthermore, page rendering can be delayed by javascript parsing/execution, so it's best practice to put all javascript at the bottom of the page.

case-insensitive matching in xpath?

matches() is an XPATH 2.0 function that allows for case-insensitive regex matching.

One of the flags is i for case-insensitive matching.

The following XPATH using the matches() function with the case-insensitive flag:

//CD[matches(@title,'empire burlesque','i')]

Retaining file permissions with Git

We can improve on the other answers by changing the format of the .permissions file to be executable chmod statements, and to make use of the -printf parameter to find. Here is the simpler .git/hooks/pre-commit file:

#!/usr/bin/env bash

echo -n "Backing-up file permissions... "

cd "$(git rev-parse --show-toplevel)"

find . -printf 'chmod %m "%p"\n' > .permissions

git add .permissions

echo done.

...and here is the simplified .git/hooks/post-checkout file:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

Remember that other tools might have already configured these scripts, so you may need to merge them together. For example, here's a post-checkout script that also includes the git-lfs commands:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on you
r path. If you no longer wish to use Git LFS, remove this hook by deleting .git/hooks/post-checkout.\n"; exit 2; }
git lfs post-checkout "$@"

npm install error - MSB3428: Could not load the Visual C++ component "VCBuild.exe"

For me worked install the component "VCBuild.exe", just dowload the wizard, install and them open the cmd again as administrator and try run again. Updated link to dowload the wizard here

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

AttributeError: module 'cv2.cv2' has no attribute 'createLBPHFaceRecognizer'

For me, I had to have OpenCV (3.4.2), Py-OpenCV (3.4.2), LibOpenCV (3.4.2).

My Python was version 3.5.6 with Anaconda in Windows OS 10.

Regex in JavaScript for validating decimal numbers

Numbers with at most 2 decimal places:

/^\d+(?:\.\d{1,2})?$/

This should work fine. Please try out :)

Build error, This project references NuGet

First I would check if your MusicKarma project has Microsoft.Net.Compilers in its packages.config file. If not then you could remove everything to do with that NuGet package from your MusicKarma.csproj.

If you are using the Microsoft.Net.Compilers NuGet package then my guess is that the path is incorrect. Looking at the directory name in the error message I would guess that the MusicKarma solution file (.sln) is in the same directory as the MusicKarma.csproj. If so then the packages directory is probably wrong since by default the packages directory would be inside the solution directory. So I am assuming that your packages directory is:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\MusicKarma\packages

Whilst your MusicKarma.csproj file is looking for the props file in:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\packages\Microsoft.Net.Compilers.1.1.1\build

So if that is the case then you can fix the problem by editing the path in your MusicKarma.csproj file or by reinstalling the NuGet package.

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

IE11 meta element Breaks SVG

I figured it out! The page was rendering using IE8 mode... had

<meta http-equiv="X-UA-Compatible" content="IE=8">

in the header... changed it to

<meta http-equiv="X-UA-Compatible" content="IE=9">

9 and it worked!

Neither BindingResult nor plain target object for bean name available as request attribute

You would have got this Exception while doing a GET on http://localhost:8080/projectname/login

As Vinay has correctly stated you can definitely use

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(Model model) { 
    model.addAttribute("login", new Login()); 
    return "login"; 
}

But I am going to provide some alternative syntax which I think you were trying with Spring 3.0.

You can also achieve the above functionality with

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(Login loginModel) { 
    return "login"; 
}

and it login.jsp (assuming you are using InternalResourceViewResolver) you can have

<form:form method="POST" action="login.htm" modelAttribute="login">

Notice : modelAttribute is login and not loginModel. It is as per the class name you provide in argument. But if you want to use loginModel as modelAttribute is jsp you can do the following

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(@ModelAttribute("loginModel")Login loginModel) { 
    return "login"; 
}

and jsp would have

<form:form method="POST" action="login.htm" modelAttribute="loginModel">

I know there are just different ways for doing the same thing. But the most important point to note here -

Imp Note: When you add your model class in your methods argument (like public String displayLogin(Login loginModel)) it is automatically created and added to your Model object (which is why you can directly access it in JSP without manually putting it in model). Then it will search your request if request has attributes that it can map with the new ModelObject create. If yes Spring will inject values from request parameters to your custom model object class (Login in this case).

You can test this by doing

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(Login loginModel, Model model) { 
    System.out.println(model.asMap().get("login").equals(loginModel));
    return "login"; 
}

Note : Above creating of new custom model object may not hold true if you have given @SessionAttributes({"login"}). In this case it will get from session and populate values.

Crop image in PHP

You can use imagecrop function in (PHP 5 >= 5.5.0, PHP 7)

Example:

<?php
$im = imagecreatefrompng('example.png');
$size = min(imagesx($im), imagesy($im));
$im2 = imagecrop($im, ['x' => 0, 'y' => 0, 'width' => $size, 'height' => $size]);
if ($im2 !== FALSE) {
    imagepng($im2, 'example-cropped.png');
    imagedestroy($im2);
}
imagedestroy($im);
?>

How to set an HTTP proxy in Python 2.7?

It looks like get-pip.py has been updated to use the environment variables http_proxy and https_proxy.

Windows:

set http_proxy=http://proxy.myproxy.com
set https_proxy=https://proxy.myproxy.com
python get-pip.py

Linux/OS X:

export http_proxy=http://proxy.myproxy.com
export https_proxy=https://proxy.myproxy.com
sudo -E python get-pip.py

However if this still doesn't work for you, you can always install pip through a proxy using setuptools' easy_install by setting the same environment variables.

Windows:

set http_proxy=http://proxy.myproxy.com
set https_proxy=https://proxy.myproxy.com
easy_install pip

Linux/OS X:

export http_proxy=http://proxy.myproxy.com
export https_proxy=https://proxy.myproxy.com
sudo -E easy_install pip

Then once it's installed, use:

pip install --proxy="user:password@server:port" packagename

From the pip man page:

--proxy
Have pip use a proxy server to access sites. This can be specified using "user:[email protected]:port" notation. If the password is left out, pip will ask for it.

AngularJS: factory $http.get JSON file

++ This worked for me. It's vanilla javascirpt and good for use cases such as de-cluttering when testing with ngMocks library:

<!-- specRunner.html - keep this at the top of your <script> asset loading so that it is available readily -->
<!--  Frienly tip - have all JSON files in a json-data folder for keeping things organized-->
<script src="json-data/findByIdResults.js" charset="utf-8"></script>
<script src="json-data/movieResults.js" charset="utf-8"></script>

This is your javascript file that contains the JSON data

// json-data/JSONFindByIdResults.js
var JSONFindByIdResults = {
     "Title": "Star Wars",
     "Year": "1983",
     "Rated": "N/A",
     "Released": "01 May 1983",
     "Runtime": "N/A",
     "Genre": "Action, Adventure, Sci-Fi",
     "Director": "N/A",
     "Writer": "N/A",
     "Actors": "Harrison Ford, Alec Guinness, Mark Hamill, James Earl Jones",
     "Plot": "N/A",
     "Language": "English",
     "Country": "USA",
     "Awards": "N/A",
     "Poster": "N/A",
     "Metascore": "N/A",
     "imdbRating": "7.9",
     "imdbVotes": "342",
     "imdbID": "tt0251413",
     "Type": "game",
     "Response": "True"
};

Finally, work with the JSON data anywhere in your code

// working with JSON data in code
var findByIdResults = window.JSONFindByIdResults;

Note:- This is great for testing and even karma.conf.js accepts these files for running tests as seen below. Also, I recommend this only for de-cluttering data and testing/development environment.

// extract from karma.conf.js
files: [
     'json-data/JSONSearchResultHardcodedData.js',
     'json-data/JSONFindByIdResults.js'
     ...
]

Hope this helps.

++ Built on top of this answer https://stackoverflow.com/a/24378510/4742733

UPDATE

An easier way that worked for me is just include a function at the bottom of the code returning whatever JSON.

// within test code
let movies = getMovieSearchJSON();
.....
...
...
....
// way down below in the code
function getMovieSearchJSON() {
      return {
         "Title": "Bri Squared",
         "Year": "2011",
         "Rated": "N/A",
         "Released": "N/A",
         "Runtime": "N/A",
         "Genre": "Comedy",
         "Director": "Joy Gohring",
         "Writer": "Briana Lane",
         "Actors": "Brianne Davis, Briana Lane, Jorge Garcia, Gabriel Tigerman",
         "Plot": "N/A",
         "Language": "English",
         "Country": "USA",
         "Awards": "N/A",
         "Poster": "http://ia.media-imdb.com/images/M/MV5BMjEzNDUxMDI4OV5BMl5BanBnXkFtZTcwMjE2MzczNQ@@._V1_SX300.jpg",
         "Metascore": "N/A",
         "imdbRating": "8.2",
         "imdbVotes": "5",
         "imdbID": "tt1937109",
         "Type": "movie",
         "Response": "True"
   }
}

How to fix the error "Windows SDK version 8.1" was not found?

Grep the folder tree's *.vcxproj files. Replace <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion> with <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> or whatever SDK version you get when you update one of the projects.

What is Ruby's double-colon `::`?

:: is basically a namespace resolution operator. It allows you to access items in modules, or class-level items in classes. For example, say you had this setup:

module SomeModule
    module InnerModule
        class MyClass
            CONSTANT = 4
        end
    end
end

You could access CONSTANT from outside the module as SomeModule::InnerModule::MyClass::CONSTANT.

It doesn't affect instance methods defined on a class, since you access those with a different syntax (the dot .).

Relevant note: If you want to go back to the top-level namespace, do this: ::SomeModule – Benjamin Oakes

Rename multiple files in a directory in Python

Use os.rename(src, dst) to rename or move a file or a directory.

$ ls
cheese_cheese_type.bar  cheese_cheese_type.foo
$ python
>>> import os
>>> for filename in os.listdir("."):
...  if filename.startswith("cheese_"):
...    os.rename(filename, filename[7:])
... 
>>> 
$ ls
cheese_type.bar  cheese_type.foo

How to get info on sent PHP curl request

You can also use a proxy tool like Charles to capture the outgoing request headers, data, etc. by passing the proxy details through CURLOPT_PROXY to your curl_setopt_array method.

For example:

$proxy = '127.0.0.1:8888';
$opt = array (
    CURLOPT_URL => "http://www.example.com",
    CURLOPT_PROXY => $proxy,
    CURLOPT_POST => true,
    CURLOPT_VERBOSE => true,
    );

$ch = curl_init();
curl_setopt_array($ch, $opt);
curl_exec($ch);
curl_close($ch);

javascript create array from for loop

You need to push i

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

for (var i = yearStart; i < yearEnd+1; i++) {
    arr.push(i);
}

Then, your resulting array will be:

arr = [2000, 2001, 2003, ... 2039, 2040]

Hope this helps

How to make CSS3 rounded corners hide overflow in Chrome/Opera

As for me none of the solutions worked well, only using:

-webkit-mask-image: -webkit-radial-gradient(circle, white, black);

on the wrapper element did the job.

Here the example: http://jsfiddle.net/gpawlik/qWdf6/74/

What happened to Lodash _.pluck?

Or try pure ES6 nonlodash method like this

const reducer = (array, object) => {
  array.push(object.a)
  return array
}

var objects = [{ 'a': 1 }, { 'a': 2 }];
objects.reduce(reducer, [])

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

MrOBrian's answer shows why your current code doesn't work, with the missing trailing ] and quotes, but here's an easier way to make it work:

onchange='mySelectHandler(this)'

And then:

function mySelectHandler(el){
     var mySelect = $(el)
     // get selected value
     alert ("selected " + mySelect.val())
  }

Or better still, remove the inline event handler altogether and bind the event handler with jQuery:

$('select[name="a[b]"]').change(function() {
    var mySelect = $(this);
    alert("selected " mySelect.val());
});

That last would need to be in a document.ready handler or in a script block that appears after the select element. If you want to run the same function for other selects simply change the selector to something that applies to all, e.g., all selects would be $('select'), or all with a particular class would be $('select.someClass').

Add a CSS class to <%= f.submit %>

Rails 4 and Bootstrap 3 "primary" button

<%= f.submit nil, :class => 'btn btn-primary' %>

Yields something like:

screen-2014-01-22_02.24.26.png

Why use a READ UNCOMMITTED isolation level?

I always use READ UNCOMMITTED now. It's fast with the least issues. When using other isolations you will almost always come across some Blocking issues.

As long as you use Auto Increment fields and pay a little more attention to inserts then your fine, and you can say goodbye to blocking issues.

You can make errors with READ UNCOMMITED but to be honest, it is very easy make sure your inserts are full proof. Inserts/Updates which use the results from a select are only thing you need to watch out for. (Use READ COMMITTED here, or ensure that dirty reads aren't going to cause a problem)

So go the Dirty Reads (Specially for big reports), your software will run smoother...

Accessing localhost:port from Android emulator

I resolved exact the problem when the service layer is using Visual Studio IIS Express. Just point to 10.0.2.2:port wont work. Instead of messing around the IIS Express as mentioned by other posts, I just put a proxy in front of the IIS Express. For example, apache or nginx. The nginx.conf will look like

 # Mobile API
 server { 
    listen       8090;
    server_name  default_server;

    location / {
        proxy_pass http://localhost:54722;
    }
  }

Then the android needs to points to my IP address as 192.168.x.x:8090

Running script upon login mac

tl;dr: use OSX's native process launcher and manager, launchd.

To do so, make a launchctl daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.

  1. Create a .plist file according to the instructions in the Apple Dev docs here or more detail below.
  2. Place in ~/Library/LaunchAgents
  3. Log in (or run manually via launchctl load [filename.plist])

For more on launchd, the wikipedia article is quite good and describes the system and its advantages over other older systems.


Here's the specific plist file to run a script at login.

Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
   <key>Label</key>
   <string>com.user.loginscript</string>
   <key>ProgramArguments</key>
   <array><string>/path/to/executable/script.sh</string></array>
   <key>RunAtLoad</key>
   <true/>
</dict>
</plist>

Replace the <string> after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh to ensure it is for all users).

Save as ~/Library/LaunchAgents/com.user.loginscript.plist

Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist and log out/in to test (or to test directly, run launchctl start com.user.loginscript)

Tail /var/log/system.log for error messages.

The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons) are run on boot.

If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.

XSS filtering function in PHP

All above methods don't allow to preserve some tags like <a>, <table> etc. There is an ultimate solution http://sourceforge.net/projects/kses/ Drupal uses it

How can I change the Bootstrap default font family using font from Google?

If you have a custom.css file, in there, just do something like:

font-family: "Oswald", Helvetica, Arial, sans-serif!important;

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

How to wait for a JavaScript Promise to resolve before resuming function?

You can do it manually. (I know, that that isn't great solution, but..) use while loop till the result hasn't a value

kickOff().then(function(result) {
   while(true){
       if (result === undefined) continue;
       else {
            $("#output").append(result);
            return;
       }
   }
});

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

SQL SERVER: Get total days between two dates

You can try this MSDN link

DATEDIFF ( datepart , startdate , enddate )
SELECT DATEDIFF(DAY, '1/1/2011', '3/1/2011')

Populating a data frame in R in a loop

Thanks Notable1, works for me with the tidytextr Create a dataframe with the name of files in one column and content in other.

    diretorio <- "D:/base"
    arquivos <- list.files(diretorio, pattern = "*.PDF")
    quantidade <- length(arquivos)

#
df = NULL
for (k in 1:quantidade) {

      nome = arquivos[k]
      print(nome)
      Sys.sleep(1) 
      dados = read_pdf(arquivos[k],ocr = T)
      print(dados)
      Sys.sleep(1)
      df = rbind(df, data.frame(nome,dados))
      Sys.sleep(1)
}
Encoding(df$text) <- "UTF-8"

Merging dataframes on index with pandas

You can do this with merge:

df_merged = df1.merge(df2, how='outer', left_index=True, right_index=True)

The keyword argument how='outer' keeps all indices from both frames, filling in missing indices with NaN. The left_index and right_index keyword arguments have the merge be done on the indices. If you get all NaN in a column after doing a merge, another troubleshooting step is to verify that your indices have the same dtypes.

The merge code above produces the following output for me:

                V1    V2
A 2012-01-01  12.0  15.0
  2012-02-01  14.0   NaN
  2012-03-01   NaN  21.0
B 2012-01-01  15.0  24.0
  2012-02-01   8.0   9.0
C 2012-01-01  17.0   NaN
  2012-02-01   9.0   NaN
D 2012-01-01   NaN   7.0
  2012-02-01   NaN  16.0

error TS2339: Property 'x' does not exist on type 'Y'

The correct fix is to add the property in the type definition as explained by @Nitzan Tomer. But also you can just define property as any, if you want to write code almost as in JavaScript:

arr.filter((item:any) => {
    return item.isSelected == true;
}

Creating a daemon in Linux

man 7 daemon describes how to create daemon in great detail. My answer is just excerpt from this manual.

There are at least two types of daemons:

  1. traditional SysV daemons (old-style),
  2. systemd daemons (new-style).

SysV Daemons

If you are interested in traditional SysV daemon, you should implement the following steps:

  1. Close all open file descriptors except standard input, output, and error (i.e. the first three file descriptors 0, 1, 2). This ensures that no accidentally passed file descriptor stays around in the daemon process. On Linux, this is best implemented by iterating through /proc/self/fd, with a fallback of iterating from file descriptor 3 to the value returned by getrlimit() for RLIMIT_NOFILE.
  2. Reset all signal handlers to their default. This is best done by iterating through the available signals up to the limit of _NSIG and resetting them to SIG_DFL.
  3. Reset the signal mask using sigprocmask().
  4. Sanitize the environment block, removing or resetting environment variables that might negatively impact daemon runtime.
  5. Call fork(), to create a background process.
  6. In the child, call setsid() to detach from any terminal and create an independent session.
  7. In the child, call fork() again, to ensure that the daemon can never re-acquire a terminal again.
  8. Call exit() in the first child, so that only the second child (the actual daemon process) stays around. This ensures that the daemon process is re-parented to init/PID 1, as all daemons should be.
  9. In the daemon process, connect /dev/null to standard input, output, and error.
  10. In the daemon process, reset the umask to 0, so that the file modes passed to open(), mkdir() and suchlike directly control the access mode of the created files and directories.
  11. In the daemon process, change the current directory to the root directory (/), in order to avoid that the daemon involuntarily blocks mount points from being unmounted.
  12. In the daemon process, write the daemon PID (as returned by getpid()) to a PID file, for example /run/foobar.pid (for a hypothetical daemon "foobar") to ensure that the daemon cannot be started more than once. This must be implemented in race-free fashion so that the PID file is only updated when it is verified at the same time that the PID previously stored in the PID file no longer exists or belongs to a foreign process.
  13. In the daemon process, drop privileges, if possible and applicable.
  14. From the daemon process, notify the original process started that initialization is complete. This can be implemented via an unnamed pipe or similar communication channel that is created before the first fork() and hence available in both the original and the daemon process.
  15. Call exit() in the original process. The process that invoked the daemon must be able to rely on that this exit() happens after initialization is complete and all external communication channels are established and accessible.

Note this warning:

The BSD daemon() function should not be used, as it implements only a subset of these steps.

A daemon that needs to provide compatibility with SysV systems should implement the scheme pointed out above. However, it is recommended to make this behavior optional and configurable via a command line argument to ease debugging as well as to simplify integration into systems using systemd.

Note that daemon() is not POSIX compliant.


New-Style Daemons

For new-style daemons the following steps are recommended:

  1. If SIGTERM is received, shut down the daemon and exit cleanly.
  2. If SIGHUP is received, reload the configuration files, if this applies.
  3. Provide a correct exit code from the main daemon process, as this is used by the init system to detect service errors and problems. It is recommended to follow the exit code scheme as defined in the LSB recommendations for SysV init scripts.
  4. If possible and applicable, expose the daemon's control interface via the D-Bus IPC system and grab a bus name as last step of initialization.
  5. For integration in systemd, provide a .service unit file that carries information about starting, stopping and otherwise maintaining the daemon. See systemd.service(5) for details.
  6. As much as possible, rely on the init system's functionality to limit the access of the daemon to files, services and other resources, i.e. in the case of systemd, rely on systemd's resource limit control instead of implementing your own, rely on systemd's privilege dropping code instead of implementing it in the daemon, and similar. See systemd.exec(5) for the available controls.
  7. If D-Bus is used, make your daemon bus-activatable by supplying a D-Bus service activation configuration file. This has multiple advantages: your daemon may be started lazily on-demand; it may be started in parallel to other daemons requiring it — which maximizes parallelization and boot-up speed; your daemon can be restarted on failure without losing any bus requests, as the bus queues requests for activatable services. See below for details.
  8. If your daemon provides services to other local processes or remote clients via a socket, it should be made socket-activatable following the scheme pointed out below. Like D-Bus activation, this enables on-demand starting of services as well as it allows improved parallelization of service start-up. Also, for state-less protocols (such as syslog, DNS), a daemon implementing socket-based activation can be restarted without losing a single request. See below for details.
  9. If applicable, a daemon should notify the init system about startup completion or status updates via the sd_notify(3) interface.
  10. Instead of using the syslog() call to log directly to the system syslog service, a new-style daemon may choose to simply log to standard error via fprintf(), which is then forwarded to syslog by the init system. If log levels are necessary, these can be encoded by prefixing individual log lines with strings like "<4>" (for log level 4 "WARNING" in the syslog priority scheme), following a similar style as the Linux kernel's printk() level system. For details, see sd-daemon(3) and systemd.exec(5).

To learn more read whole man 7 daemon.

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 2.3.x and later supports the dropdown-submenu..

<ul class="dropdown-menu">
            <li><a href="#">Login</a></li>
            <li class="dropdown-submenu">
                <a tabindex="-1" href="#">More options</a>
                <ul class="dropdown-menu">
                    <li><a tabindex="-1" href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                    <li><a href="#">Second level</a></li>
                </ul>
            </li>
            <li><a href="#">Logout</a></li>
</ul>

Working demo on Bootply.com

What is a magic number, and why is it bad?

Another advantage of extracting a magic number as a constant gives the possibility to clearly document the business information.

public class Foo {
    /** 
     * Max age in year to get child rate for airline tickets
     * 
     * The value of the constant is {@value}
     */
    public static final int MAX_AGE_FOR_CHILD_RATE = 2;

    public void computeRate() {
         if (person.getAge() < MAX_AGE_FOR_CHILD_RATE) {
               applyChildRate();
         }
    }
}

How to filter a data frame

You are missing a comma in your statement.

Try this:

data[data[, "Var1"]>10, ]

Or:

data[data$Var1>10, ]

Or:

subset(data, Var1>10)

As an example, try it on the built-in dataset, mtcars

data(mtcars)

mtcars[mtcars[, "mpg"]>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2


mtcars[mtcars$mpg>25, ]

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

subset(mtcars, mpg>25)

                mpg cyl  disp  hp drat    wt  qsec vs am gear carb
Fiat 128       32.4   4  78.7  66 4.08 2.200 19.47  1  1    4    1
Honda Civic    30.4   4  75.7  52 4.93 1.615 18.52  1  1    4    2
Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
Fiat X1-9      27.3   4  79.0  66 4.08 1.935 18.90  1  1    4    1
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.70  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.90  1  1    5    2

Default text which won't be shown in drop-down list

Kyle's solution worked perfectly fine for me so I made my research in order to avoid any Js and CSS, but just sticking with HTML. Adding a value of selected to the item we want to appear as a header forces it to show in the first place as a placeholder. Something like:

<option selected disabled>Choose here</option>

The complete markup should be along these lines:

<select>
    <option selected disabled>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

You can take a look at this fiddle, and here's the result:

enter image description here

If you do not want the sort of placeholder text to appear listed in the options once a user clicks on the select box just add the hidden attribute like so:

<select>
    <option selected disabled hidden>Choose here</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
    <option value="4">Four</option>
    <option value="5">Five</option>
</select>

Check the fiddle here and the screenshot below.

enter image description here


Here is the solution:

<select>
    <option style="display:none;" selected>Select language</option>
    <option>Option 1</option>
    <option>Option 2</option>
</select>

Get top n records for each group of grouped results

There is a really nice answer to this problem at MySQL - How To Get Top N Rows per Each Group

Based on the solution in the referenced link, your query would be like:

SELECT Person, Group, Age
   FROM
     (SELECT Person, Group, Age, 
                  @group_rank := IF(@group = Group, @group_rank + 1, 1) AS group_rank,
                  @current_group := Group 
       FROM `your_table`
       ORDER BY Group, Age DESC
     ) ranked
   WHERE group_rank <= `n`
   ORDER BY Group, Age DESC;

where n is the top n and your_table is the name of your table.

I think the explanation in the reference is really clear. For quick reference I will copy and paste it here:

Currently MySQL does not support ROW_NUMBER() function that can assign a sequence number within a group, but as a workaround we can use MySQL session variables.

These variables do not require declaration, and can be used in a query to do calculations and to store intermediate results.

@current_country := country This code is executed for each row and stores the value of country column to @current_country variable.

@country_rank := IF(@current_country = country, @country_rank + 1, 1) In this code, if @current_country is the same we increment rank, otherwise set it to 1. For the first row @current_country is NULL, so rank is also set to 1.

For correct ranking, we need to have ORDER BY country, population DESC

Using port number in Windows host file

What you want can be achieved by modifying the hosts file through Fiddler 2 application.

Follow these steps:

  1. Install Fiddler2

  2. Navigate to Fiddler2 menu:- Tools > HOSTS.. (Click to select)

  3. Add a line like this:-

    localhost:8080 www.mydomainname.com

  4. Save the file & then checkout www.mydomainname.com in browser.

Why did my Git repo enter a detached HEAD state?

The other way to get in a git detached head state is to try to commit to a remote branch. Something like:

git fetch
git checkout origin/foo
vi bar
git commit -a -m 'changed bar'

Note that if you do this, any further attempt to checkout origin/foo will drop you back into a detached head state!

The solution is to create your own local foo branch that tracks origin/foo, then optionally push.

This probably has nothing to do with your original problem, but this page is high on the google hits for "git detached head" and this scenario is severely under-documented.

default web page width - 1024px or 980px?

980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.

Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.

Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/

Writing .csv files from C++

Change

Morison_File << t;                                 //Printing to file
Morison_File << F;

To

Morison_File << t << ";" << F << endl;                                 //Printing to file

a , would also do instead of ;

JavaScript get child element

I'd suggest doing something similar to:

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = parent.getElementsByClassName('sub');
        if (sub[0].style.display == 'inline'){
            sub[0].style.display = 'none';
        }
        else {
            sub[0].style.display = 'inline';
        }
    }
}

document.getElementById('cat').onclick = function(){
    show_sub(this.id);
};????

JS Fiddle demo.

Though the above relies on the use of a class rather than a name attribute equal to sub.

As to why your original version "didn't work" (not, I must add, a particularly useful description of the problem), all I can suggest is that, in Chromium, the JavaScript console reported that:

Uncaught TypeError: Object # has no method 'getElementsByName'.

One approach to working around the older-IE family's limitations is to use a custom function to emulate getElementsByClassName(), albeit crudely:

function eBCN(elem,classN){
    if (!elem || !classN){
        return false;
    }
    else {
        var children = elem.childNodes;
        for (var i=0,len=children.length;i<len;i++){
            if (children[i].nodeType == 1
                &&
                children[i].className == classN){
                    var sub = children[i];
            }
        }
        return sub;
    }
}

function show_sub(cat) {
    if (!cat) {
        return false;
    }
    else if (document.getElementById(cat)) {
        var parent = document.getElementById(cat),
            sub = eBCN(parent,'sub');
        if (sub.style.display == 'inline'){
            sub.style.display = 'none';
        }
        else {
            sub.style.display = 'inline';
        }
    }
}

var D = document,
    listElems = D.getElementsByTagName('li');
for (var i=0,len=listElems.length;i<len;i++){
    listElems[i].onclick = function(){
        show_sub(this.id);
    };
}?

JS Fiddle demo.

Set Encoding of File to UTF8 With BOM in Sublime Text 3

I can't set "UTF-8 with BOM" in the corner button either, but I can change it from the menu bar.

"File"->"Save with encoding"->"UTF-8 with BOM"

Error in installation a R package

I had the same problem with e1071 package. Just close any other R sessions running parallelly and you will be good to go.

Project with path ':mypath' could not be found in root project 'myproject'

It's not enough to have just compile project("xy") dependency. You need to configure root project to include all modules (or to call them subprojects but that might not be correct word here).

Create a settings.gradle file in the root of your project and add this:

include ':progressfragment'

to that file. Then sync Gradle and it should work.

Also one interesting side note: If you add ':unexistingProject' in settings.gradle (project that you haven't created yet), Gradle will create folder for this project after sync (at least in Android studio this is how it behaves). So, to avoid errors with settings.gradle when you create project from existing files, first add that line to file, sync and then put existing code in created folder. Unwanted behavior arising from this might be that if you delete the project folder and then sync folder will come back empty because Gradle sync recreated it since it is still listed in settings.gradle.

how can I display tooltip or item information on mouse over?

The simplest way to get tooltips in most browsers is to set some text in the title attribute.

eg.

<img src="myimage.jpg" alt="a cat" title="My cat sat on a table" />

produces (hover your mouse over the image):

a cat http://www.imagechicken.com/uploads/1275939952008633500.jpg

Title attributes can be applied to most HTML elements.

How to Initialize char array from a string

I'm not sure what your problem is, but the following seems to work OK:

#include <stdio.h>

int main()
{
    const char s0[] = "ABCD";
    const char s1[] = { s0[3], s0[2], s0[1], s0[0], 0 };

    puts(s0);
    puts(s1);
    return 0;
}


Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
cl /Od /D "WIN32" /D "_CONSOLE" /Gm /EHsc /RTC1 /MLd /W3 /c /ZI /TC
   .\Tmp.c
Tmp.c
Linking...

Build Time 0:02


C:\Tmp>tmp.exe
ABCD
DCBA

C:\Tmp>

Edit 9 June 2009

If you need global access, you might need something ugly like this:

#include <stdio.h>

const char *GetString(int bMunged)
{
    static char s0[5] = "ABCD";
    static char s1[5];

    if (bMunged) {
        if (!s1[0])  {
            s1[0] = s0[3]; 
            s1[1] = s0[2];
            s1[2] = s0[1];
            s1[3] = s0[0];
            s1[4] = 0;
        }
        return s1;
    } else {
        return s0;
    }
}

#define S0 GetString(0)
#define S1 GetString(1)

int main()
{
    puts(S0);
    puts(S1);
    return 0;
}

Get table column names in MySQL?

It's also interesting to note that you can use
EXPLAIN table_name which is synonymous with DESCRIBE table_name and SHOW COLUMNS FROM table_name although EXPLAIN is more commonly used to obtain information about the query execution plan.

How to solve the “failed to lazily initialize a collection of role” Hibernate exception

From my experience, I have the following methods to solved the famous LazyInitializationException:

(1) Use Hibernate.initialize

Hibernate.initialize(topics.getComments());

(2) Use JOIN FETCH

You can use the JOIN FETCH syntax in your JPQL to explicitly fetch the child collection out. This is some how like EAGER fetching.

(3) Use OpenSessionInViewFilter

LazyInitializationException often occur in view layer. If you use Spring framework, you can use OpenSessionInViewFilter. However, I do not suggest you to do so. It may leads to performance issue if not use correctly.

VS 2012: Scroll Solution Explorer to current file

I've found the Sync with Active Document button in the solution explorer to be the the most effective (this may be a vs2013 feature!)

enter image description here

How to replace text of a cell based on condition in excel

You can use the IF statement in a new cell to replace text, such as:

=IF(A4="C", "Other", A4)

This will check and see if cell value A4 is "C", and if it is, it replaces it with the text "Other"; otherwise, it uses the contents of cell A4.

EDIT

Assuming that the Employee_Count values are in B1-B10, you can use this:

=IF(B1=LARGE($B$1:$B$10, 10), "Other", B1)

This function doesn't even require the data to be sorted; the LARGE function will find the 10th largest number in the series, and then the rest of the formula will compare against that.

Split a string by a delimiter in python

You can use the str.split method: string.split('__')

>>> "MATCHES__STRING".split("__")
['MATCHES', 'STRING']

How to use sha256 in php5.3.0

First of all, sha256 is a hashing algorithm, not a type of encryption. An encryption would require having a way to decrypt the information back to its original value (collisions aside).

Looking at your code, it seems it should work if you are providing the correct parameter.

  • Try using a literal string in your code first, and verify its validity instead of using the $_POST[] variable

  • Try moving the comparison from the database query to the code (get the hash for the given user and compare to the hash you have just calculated)

But most importantly before deploying this in any kind of public fashion, please remember to sanitize your inputs. Don't allow arbitrary SQL to be insert into the queries. The best idea here would be to use parameterized queries.

Writing outputs to log file and console

I find it very useful to append both stdout and stderr to a log file. I was glad to see a solution by alfonx with exec > >(tee -a), because I was wondering how to accomplish this using exec. I came across a creative solution using here-doc syntax and .: https://unix.stackexchange.com/questions/80707/how-to-output-text-to-both-screen-and-file-inside-a-shell-script

I discovered that in zsh, the here-doc solution can be modified using the "multios" construct to copy output to both stdout/stderr and the log file:

#!/bin/zsh
LOG=$0.log
# 8 is an arbitrary number;
# multiple redirects for the same file descriptor 
# triggers "multios"
. 8<<\EOF /dev/fd/8 2>&2 >&1 2>>$LOG >>$LOG
# some commands
date >&2
set -x
echo hi
echo bye
EOF
echo not logged

It is not as readable as the exec solution but it has the advantage of allowing you to log just part of the script. Of course, if you omit the EOF then the whole script is executed with logging. I'm not sure how zsh implements multios, but it may have less overhead than tee. Unfortunately it seems that one cannot use multios with exec.

Is there a "do ... while" loop in Ruby?

I found the following snippet while reading the source for Tempfile#initialize in the Ruby core library:

begin
  tmpname = File.join(tmpdir, make_tmpname(basename, n))
  lock = tmpname + '.lock'
  n += 1
end while @@cleanlist.include?(tmpname) or
  File.exist?(lock) or File.exist?(tmpname)

At first glance, I assumed the while modifier would be evaluated before the contents of begin...end, but that is not the case. Observe:

>> begin
?>   puts "do {} while ()" 
>> end while false
do {} while ()
=> nil

As you would expect, the loop will continue to execute while the modifier is true.

>> n = 3
=> 3
>> begin
?>   puts n
>>   n -= 1
>> end while n > 0
3
2
1
=> nil

While I would be happy to never see this idiom again, begin...end is quite powerful. The following is a common idiom to memoize a one-liner method with no params:

def expensive
  @expensive ||= 2 + 2
end

Here is an ugly, but quick way to memoize something more complex:

def expensive
  @expensive ||=
    begin
      n = 99
      buf = "" 
      begin
        buf << "#{n} bottles of beer on the wall\n" 
        # ...
        n -= 1
      end while n > 0
      buf << "no more bottles of beer" 
    end
end

Originally written by Jeremy Voorhis. The content has been copied here because it seems to have been taken down from the originating site. Copies can also be found in the Web Archive and at Ruby Buzz Forum. -Bill the Lizard

Excel- compare two cell from different sheet, if true copy value from other cell

In your destination field you want to use VLOOKUP like so:

=VLOOKUP(Sheet1!A1:A100,Sheet2!A1:F100,6,FALSE)

VLOOKUP Arguments:

  1. The set fields you want to lookup.
  2. The table range you want to lookup up your value against. The first column of your defined table should be the column you want compared against your lookup field. The table range should also contain the value you want to display (Column F).
  3. This defines what field you want to display upon a match.
  4. FALSE tells VLOOKUP to do an exact match.

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

ieshims.dll is an artefact of Vista/7 where a shim DLL is used to proxy certain calls (such as CreateProcess) to handle protected mode IE, which doesn't exist on XP, so it is unnecessary. wer.dll is related to Windows Error Reporting and again is probably unused on Windows XP which has a slightly different error reporting system than Vista and above.

I would say you shouldn't need either of them to be present on XP and would normally be delay loaded anyway.

How can I create a progress bar in Excel VBA?

I liked the Status Bar from this page:

https://wellsr.com/vba/2017/excel/vba-application-statusbar-to-mark-progress/

I updated it so it could be used as a called procedure. No credit to me.


showStatus Current, Total, "  Process Running: "

Private Sub showStatus(Current As Integer, lastrow As Integer, Topic As String)
Dim NumberOfBars As Integer
Dim pctDone As Integer

NumberOfBars = 50
'Application.StatusBar = "[" & Space(NumberOfBars) & "]"


' Display and update Status Bar
    CurrentStatus = Int((Current / lastrow) * NumberOfBars)
    pctDone = Round(CurrentStatus / NumberOfBars * 100, 0)
    Application.StatusBar = Topic & " [" & String(CurrentStatus, "|") & _
                            Space(NumberOfBars - CurrentStatus) & "]" & _
                            " " & pctDone & "% Complete"

' Clear the Status Bar when you're done
'    If Current = Total Then Application.StatusBar = ""

End Sub

enter image description here

Is there a CSS selector for text nodes?

Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span or div, for example.

onchange equivalent in angular2

In Angular you can define event listeners like in the example below:

<!-- Here you can call public methods from parental component -->
<input (change)="method_name()"> 

Sublime Text 2 - Show file navigation in sidebar

This is not exactly a solution, but for opening new files this works great:

AdvancedNewFile

https://github.com/skuroda/Sublime-AdvancedNewFile

Command + Option + n to save a file in a new or existing directory.

enter image description here

So this would place your_file.html.erb in the existing views directory in a Rails app. If you needed a new directory -you would just type that as the path and then hit enter.

You can also Tab like in terminal to autocomplete for existing directories.

This does not give the sidebar navigation I am looking for, but at least helps with one significant need that is repeated often.

Angularjs how to upload multipart form data and a file?

This is pretty must just a copy of that projects demo page and shows uploading a single file on form submit with upload progress.

(function (angular) {
'use strict';

angular.module('uploadModule', [])
    .controller('uploadCtrl', [
        '$scope',
        '$upload',
        function ($scope, $upload) {
            $scope.model = {};
            $scope.selectedFile = [];
            $scope.uploadProgress = 0;

            $scope.uploadFile = function () {
                var file = $scope.selectedFile[0];
                $scope.upload = $upload.upload({
                    url: 'api/upload',
                    method: 'POST',
                    data: angular.toJson($scope.model),
                    file: file
                }).progress(function (evt) {
                    $scope.uploadProgress = parseInt(100.0 * evt.loaded / evt.total, 10);
                }).success(function (data) {
                    //do something
                });
            };

            $scope.onFileSelect = function ($files) {
                $scope.uploadProgress = 0;
                $scope.selectedFile = $files;
            };
        }
    ])
    .directive('progressBar', [
        function () {
            return {
                link: function ($scope, el, attrs) {
                    $scope.$watch(attrs.progressBar, function (newValue) {
                        el.css('width', newValue.toString() + '%');
                    });
                }
            };
        }
    ]);
 }(angular));

HTML

<form ng-submit="uploadFile()">
   <div class="row">
         <div class="col-md-12">
                  <input type="text" ng-model="model.fileDescription" />
                  <input type="number" ng-model="model.rating" />
                  <input type="checkbox" ng-model="model.isAGoodFile" />
                  <input type="file" ng-file-select="onFileSelect($files)">
                  <div class="progress" style="margin-top: 20px;">
                    <div class="progress-bar" progress-bar="uploadProgress" role="progressbar">
                      <span ng-bind="uploadProgress"></span>
                      <span>%</span>
                    </div>
                  </div>

                  <button button type="submit" class="btn btn-default btn-lg">
                    <i class="fa fa-cloud-upload"></i>
                    &nbsp;
                    <span>Upload File</span>
                  </button>
                </div>
              </div>
            </form>

EDIT: Added passing a model up to the server in the file post.

The form data in the input elements would be sent in the data property of the post and be available as normal form values.

dropzone.js - how to do something after ALL files are uploaded

Just use queuecomplete that's what its there for and its so so simple. Check the docs http://www.dropzonejs.com/

queuecomplete > Called when all files in the queue finished uploading.

      this.on("queuecomplete", function (file) {
          alert("All files have uploaded ");
      });