Programs & Examples On #Serverside javascript

Server-side JavaScript is a set of techniques allowing to build JavaScript applications directly on the server.

Node.js Best Practice Exception Handling

I would just like to add that Step.js library helps you handle exceptions by always passing it to the next step function. Therefore you can have as a last step a function that check for any errors in any of the previous steps. This approach can greatly simplify your error handling.

Below is a quote from the github page:

any exceptions thrown are caught and passed as the first argument to the next function. As long as you don't nest callback functions inline your main functions this prevents there from ever being any uncaught exceptions. This is very important for long running node.JS servers since a single uncaught exception can bring the whole server down.

Furthermore, you can use Step to control execution of scripts to have a clean up section as the last step. For example if you want to write a build script in Node and report how long it took to write, the last step can do that (rather than trying to dig out the last callback).

user authentication libraries for node.js?

A few years have passed and I'd like to introduce my authentication solution for Express. It's called Lockit. You can find the project on GitHub and a short intro at my blog.

So what are the differences to the existing solutions?

  • easy to use: set up your DB, npm install, require('lockit'), lockit(app), done
  • routes already built-in (/signup, /login, /forgot-password, etc.)
  • views already built-in (based on Bootstrap but you can easily use your own views)
  • it supports JSON communication for your AngularJS / Ember.js single page apps
  • it does NOT support OAuth and OpenID. Only username and password.
  • it works with several databases (CouchDB, MongoDB, SQL) out of the box
  • it has tests (I couldn't find any tests for Drywall)
  • it is actively maintained (compared to everyauth)
  • email verification and forgot password process (send email with token, not supported by Passport)
  • modularity: use only what you need
  • flexibility: customize all the things

Take a look at the examples.

nodejs vs node on ubuntu 12.04

You can execute this command to enable nodejs:

scl enable rh-nodejs8 bash

Note: Check your node version.

Source: https://developers.redhat.com/products/softwarecollections/hello-world/

How does setTimeout work in Node.JS?

The semantics of setTimeout are roughly the same as in a web browser: the timeout arg is a minimum number of ms to wait before executing, not a guarantee. Furthermore, passing 0, a non-number, or a negative number, will cause it to wait a minimum number of ms. In Node, this is 1ms, but in browsers it can be as much as 50ms.

The reason for this is that there is no preemption of JavaScript by JavaScript. Consider this example:

setTimeout(function () {
  console.log('boo')
}, 100)
var end = Date.now() + 5000
while (Date.now() < end) ;
console.log('imma let you finish but blocking the event loop is the best bug of all TIME')

The flow here is:

  1. schedule the timeout for 100ms.
  2. busywait for 5000ms.
  3. return to the event loop. check for pending timers and execute.

If this was not the case, then you could have one bit of JavaScript "interrupt" another. We'd have to set up mutexes and semaphors and such, to prevent code like this from being extremely hard to reason about:

var a = 100;
setTimeout(function () {
  a = 0;
}, 0);
var b = a; // 100 or 0?

The single-threadedness of Node's JavaScript execution makes it much simpler to work with than most other styles of concurrency. Of course, the trade-off is that it's possible for a badly-behaved part of the program to block the whole thing with an infinite loop.

Is this a better demon to battle than the complexity of preemption? That depends.

Distinct in Linq based on only one field of the table

data.Select(x=>x.Name).Distinct().Select(x => new SelectListItem { Text = x });

How to list all Git tags?

If you want to check you tag name locally, you have to go to the path where you have created tag(local path). Means where you have put your objects. Then type command:

git show --name-only <tagname>

It will show all the objects under that tag name. I am working in Teradata and object means view, table etc

Java 8 Iterable.forEach() vs foreach loop

One of most upleasing functional forEach's limitations is lack of checked exceptions support.

One possible workaround is to replace terminal forEach with plain old foreach loop:

    Stream<String> stream = Stream.of("", "1", "2", "3").filter(s -> !s.isEmpty());
    Iterable<String> iterable = stream::iterator;
    for (String s : iterable) {
        fileWriter.append(s);
    }

Here is list of most popular questions with other workarounds on checked exception handling within lambdas and streams:

Java 8 Lambda function that throws exception?

Java 8: Lambda-Streams, Filter by Method with Exception

How can I throw CHECKED exceptions from inside Java 8 streams?

Java 8: Mandatory checked exceptions handling in lambda expressions. Why mandatory, not optional?

Error:java: javacTask: source release 8 requires target release 1.8

Many answers regarding Maven are right but you don't have to configure the plugin directly.

Like described on the wiki page of the Apache Maven Compiler Plugin you can just set the 2 properties used by the plugin.

<project>
  [...]
  <properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>
  [...]
</project>

SQL/mysql - Select distinct/UNIQUE but return all columns?

SELECT  c2.field1 ,
        field2
FROM    (SELECT DISTINCT
                field1
         FROM   dbo.TABLE AS C
        ) AS c1
        JOIN dbo.TABLE AS c2 ON c1.field1 = c2.field1

Jquery: how to sleep or delay?

If you can't use the delay method as Robert Harvey suggested, you can use setTimeout.

Eg.

setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one

Android SDK location

Have you tried to find this folder via the Windows explorer? Can it been seen? Maybe the folder is hidden (by default install - it is hidden by the Windows operating system in the users folder). Just check that you can view hidden folders in Windows explorer (by the settings in the windows control panel > appearance and personalization > folder options > show hidden files and folders.

This happened to me as the Windows OS could not find the SDK folder which was required for the Android Studio SDK path, and was resolved by showing hidden files and folders, which enabled me to complete the default SDK install path location.

Checking for NULL pointer in C/C++

I'll start off with this: consistency is king, the decision is less important than the consistency in your code base.

In C++

NULL is defined as 0 or 0L in C++.

If you've read The C++ Programming Language Bjarne Stroustrup suggests using 0 explicitly to avoid the NULL macro when doing assignment, I'm not sure if he did the same with comparisons, it's been a while since I read the book, I think he just did if(some_ptr) without an explicit comparison but I am fuzzy on that.

The reason for this is that the NULL macro is deceptive (as nearly all macros are) it is actually 0 literal, not a unique type as the name suggests it might be. Avoiding macros is one of the general guidelines in C++. On the other hand, 0 looks like an integer and it is not when compared to or assigned to pointers. Personally I could go either way, but typically I skip the explicit comparison (though some people dislike this which is probably why you have a contributor suggesting a change anyway).

Regardless of personal feelings this is largely a choice of least evil as there isn't one right method.

This is clear and a common idiom and I prefer it, there is no chance of accidentally assigning a value during the comparison and it reads clearly:

if (some_ptr) {}

This is clear if you know that some_ptr is a pointer type, but it may also look like an integer comparison:

if (some_ptr != 0) {}

This is clear-ish, in common cases it makes sense... But it's a leaky abstraction, NULL is actually 0 literal and could end up being misused easily:

if (some_ptr != NULL) {}

C++11 has nullptr which is now the preferred method as it is explicit and accurate, just be careful about accidental assignment:

if (some_ptr != nullptr) {}

Until you are able to migrate to C++0x I would argue it's a waste of time worrying about which of these methods you use, they are all insufficient which is why nullptr was invented (along with generic programming issues which came up with perfect forwarding.) The most important thing is to maintain consistency.

In C

C is a different beast.

In C NULL can be defined as 0 or as ((void *)0), C99 allows for implementation defined null pointer constants. So it actually comes down to the implementation's definition of NULL and you will have to inspect it in your standard library.

Macros are very common and in general they are used a lot to make up for deficiencies in generic programming support in the language and other things as well. The language is much simpler and reliance on the preprocessor more common.

From this perspective I'd probably recommend using the NULL macro definition in C.

"use database_name" command in PostgreSQL

Use this commad when first connect to psql

=# psql <databaseName> <usernamePostgresql>

Ternary operator in AngularJS templates

There it is : ternary operator got added to angular parser in 1.1.5! see the changelog

Here is a fiddle showing new ternary operator used in ng-class directive.

ng-class="boolForTernary ? 'blue' : 'red'"

Linq filter List<string> where it contains a string value from another List<string>

Try the following:

var filteredFileSet = fileList.Where(item => filterList.Contains(item));

When you iterate over filteredFileSet (See LINQ Execution) it will consist of a set of IEnumberable values. This is based on the Where Operator checking to ensure that items within the fileList data set are contained within the filterList set.

As fileList is an IEnumerable set of string values, you can pass the 'item' value directly into the Contains method.

ASP.NET / C#: DropDownList SelectedIndexChanged in server control not firing

First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?

I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.

For the second case (event handler never fires even though request made), you may want to try the following suggestions:

  1. Query the Request.Params[ddlCountries.UniqueID] and see if it has value. If it has, manually fire the event handler.
  2. As long as view state is on, only bind the list data when it is not a post back.
  3. If view state has to be off, then put the list data bind in OnInit instead of OnLoad.

Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.

In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.

Thanks for your time reading this, and welcome everyone to correct if I am wrong.

Hibernate problem - "Use of @OneToMany or @ManyToMany targeting an unmapped class"

In my case a has to add my classes, when building the SessionFactory, with addAnnotationClass

Configuration configuration.configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration
            .addAnnotatedClass(MyEntity1.class)
            .addAnnotatedClass(MyEntity2.class)
            .buildSessionFactory(builder.build());

Replace comma with newline in sed on MacOS?

FWIW, the following line works in windows and replaces semicolons in my path variables with a newline. I'm using the tools installed under my git bin directory.

echo %path% | sed -e $'s/;/\\n/g' | less

List of standard lengths for database fields

Some probably correct column lengths

                            Min Max

Hostname                    1   255
Domain Name                 4   253
Email Address               7   254
Email Address [1]           3   254
Telephone Number            10  15      
Telephone Number [2]        3   26  
HTTP(S) URL w domain name   11  2083        
URL [3]                     6   2083    
Postal Code [4]             2   11
IP Address (incl ipv6)      7   45
Longitude                   numeric 9,6
Latitude                    numeric 8,6
Money[5]                    numeric 19,4

[1] Allow local domains or TLD-only domains
[2] Allow short numbers like 911 and extensions like 16045551212x12345
[3] Allow local domains, tv:// scheme
[4] http://en.wikipedia.org/wiki/List_of_postal_codes. Use max 12 if storing dash or space
[5] http://stackoverflow.com/questions/224462/storing-money-in-a-decimal-column-what-precision-and-scale

A long rant on personal names

A personal name is either a Polynym (a name with multiple sortable components), a Mononym (a name with only one component), or a Pictonym (a name represented by a picture - this exists due to people like Prince).

A person can have multiple names, playing roles, such as LEGAL, MARITAL, MAIDEN, PREFERRED, SOBRIQUET, PSEUDONYM, etc. You might have business rules, such as "a person can only have one legal name at a time, but multiple pseudonyms at a time".

Some examples:

names: [
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"George",
    middle:"Herman",
    moniker:"Babe",
    surname:"Ruth",
    generation:"JUNIOR"
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"The Bambino" /* mononyms can be more than one word, but only one component */
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"The Sultan of Swat"
  }
]

or

names: [
  {
    type:"POLYNYM",
    role:"PREFERRED",
    given:"Malcolm",
    surname:"X"
  },
  {
    type:"POLYNYM",
    role:"BIRTH",
    given:"Malcolm",
    surname:"Little"
  },
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Malik",
    surname:"El-Shabazz"
  }
]

or

names:[
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Prince",
    middle:"Rogers",
    surname:"Nelson"
  },
  {
    type:"MONONYM",
    role:"SOBRIQUET",
    mononym:"Prince"
  },
  {
    type:"PICTONYM",
    role:"LEGAL",
    url:"http://upload.wikimedia.org/wikipedia/en/thumb/a/af/Prince_logo.svg/130px-Prince_logo.svg.png"
  }
]

or

names:[
  {
    type:"POLYNYM",
    role:"LEGAL",
    given:"Juan Pablo",
    surname:"Fernández de Calderón",
    secondarySurname:"García-Iglesias" /* hispanic people often have two surnames. it can be impolite to use the wrong one. Portuguese and Spaniards differ as to which surname is important */
  }
]

Given names, middle names, surnames can be multiple words such as "Billy Bob" Thornton, or Ralph "Vaughn Williams".

How to get Wikipedia content using Wikipedia's API?

You can download the Wikipedia database directly and parse all pages to XML with Wiki Parser, which is a standalone application. The first paragraph is a separate node in the resulting XML.

Alternatively, you can extract the first paragraph from its plain-text output.

How to "EXPIRE" the "HSET" child key in redis?

Regarding a NodeJS implementation, I have added a custom expiryTime field in the object I save in the HASH. Then after a specific period time, I clear the expired HASH entries by using the following code:

client.hgetall(HASH_NAME, function(err, reply) {
    if (reply) {
        Object.keys(reply).forEach(key => {
            if (reply[key] && JSON.parse(reply[key]).expiryTime < (new Date).getTime()) {
                client.hdel(HASH_NAME, key);
            }
        })
    }
});

What is the best way to seed a database in Rails?

The best way is to use fixtures.

Note: Keep in mind that fixtures do direct inserts and don't use your model so if you have callbacks that populate data you will need to find a workaround.

Opening Chrome From Command Line

C:\>start chrome "http://site1.com" works on Windows Vista.

How to properly create an SVN tag from trunk?

Just use this:

svn  copy  http://svn.example.com/project/trunk  
           http://svn.example.com/project/branches/release-1
           -m  "branch for release 1.0"

(all on one line, of course.) You should always make a branch of the entire trunk folder and contents. It is of course possible to branch sub-parts of the trunk, but this will almost never be a good practice. You want the branch to behave exactly like the trunk does now, and for that to happen you have to branch the entire trunk.

See a better summary of SVN usage at my blog: SVN Essentials, and SVN Essentials 2

How to hide status bar in Android

If you need this in one activity, you have to put in onCreate, before setContentView:

requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

setContentView(R.layout.your_screen);

Pandas DataFrame: replace all values in a column, based on condition

A bit late to the party but still - I prefer using numpy where:

import numpy as np
df['First Season'] = np.where(df['First Season'] > 1990, 1, df['First Season'])

Is floating point math broken?

Most answers here address this question in very dry, technical terms. I'd like to address this in terms that normal human beings can understand.

Imagine that you are trying to slice up pizzas. You have a robotic pizza cutter that can cut pizza slices exactly in half. It can halve a whole pizza, or it can halve an existing slice, but in any case, the halving is always exact.

That pizza cutter has very fine movements, and if you start with a whole pizza, then halve that, and continue halving the smallest slice each time, you can do the halving 53 times before the slice is too small for even its high-precision abilities. At that point, you can no longer halve that very thin slice, but must either include or exclude it as is.

Now, how would you piece all the slices in such a way that would add up to one-tenth (0.1) or one-fifth (0.2) of a pizza? Really think about it, and try working it out. You can even try to use a real pizza, if you have a mythical precision pizza cutter at hand. :-)


Most experienced programmers, of course, know the real answer, which is that there is no way to piece together an exact tenth or fifth of the pizza using those slices, no matter how finely you slice them. You can do a pretty good approximation, and if you add up the approximation of 0.1 with the approximation of 0.2, you get a pretty good approximation of 0.3, but it's still just that, an approximation.

For double-precision numbers (which is the precision that allows you to halve your pizza 53 times), the numbers immediately less and greater than 0.1 are 0.09999999999999999167332731531132594682276248931884765625 and 0.1000000000000000055511151231257827021181583404541015625. The latter is quite a bit closer to 0.1 than the former, so a numeric parser will, given an input of 0.1, favour the latter.

(The difference between those two numbers is the "smallest slice" that we must decide to either include, which introduces an upward bias, or exclude, which introduces a downward bias. The technical term for that smallest slice is an ulp.)

In the case of 0.2, the numbers are all the same, just scaled up by a factor of 2. Again, we favour the value that's slightly higher than 0.2.

Notice that in both cases, the approximations for 0.1 and 0.2 have a slight upward bias. If we add enough of these biases in, they will push the number further and further away from what we want, and in fact, in the case of 0.1 + 0.2, the bias is high enough that the resulting number is no longer the closest number to 0.3.

In particular, 0.1 + 0.2 is really 0.1000000000000000055511151231257827021181583404541015625 + 0.200000000000000011102230246251565404236316680908203125 = 0.3000000000000000444089209850062616169452667236328125, whereas the number closest to 0.3 is actually 0.299999999999999988897769753748434595763683319091796875.


P.S. Some programming languages also provide pizza cutters that can split slices into exact tenths. Although such pizza cutters are uncommon, if you do have access to one, you should use it when it's important to be able to get exactly one-tenth or one-fifth of a slice.

(Originally posted on Quora.)

Child inside parent with min-height: 100% not inheriting height

Another JS solution, that is easy and can be used to avoid a non-easy CSS-only or extra markup / hacky solution.

function minHeight(elm, percent) {
  var windowHeight = isNaN(window.innerHeight) ? 
                     window.clientHeight : window.innerHeight;
  var height = windowHeight * percent / 100;
  elm.style.minHeight = height + 'px';
}

W/ jQuery :

function minHeight($elm, percent) {
  var windowHeight = $(window).height();
  var height = windowHeight * percent / 100;
  $elm.css('min-height', height + 'px');
}

Angular directive :

myModule.directive('minHeight', ['$window', function($window) {
  return {
    restrict: 'A',
    link: function(scope, elm, attrs) {
      var windowHeight = isNaN($window.innerHeight) ? 
               $window.clientHeight : $window.innerHeight;
      var height = windowHeight * attrs.minHeight / 100;
      elm.css('min-height', height + 'px');
    }
  };
}]);

To be used like this :

<div>
  <!-- height auto here -->
  <div min-height="100">
    <!-- This guy is at least 100% of window height but grows if needed -->
  </div>
</div>

Excel formula to search if all cells in a range read "True", if not, then show "False"

=COUNTIFS(1:1,FALSE)=0

This will return TRUE or FALSE (Looks for FALSE, if count isn't 0 (all True) it will be false

How can one check to see if a remote file exists using PHP?

This can be done by obtaining the HTTP Status code (404 = not found) which is possible with file_get_contentsDocs making use of context options. The following code takes redirects into account and will return the status code of the final destination (Demo):

$url = 'http://example.com/';
$code = FALSE;

$options['http'] = array(
    'method' => "HEAD",
    'ignore_errors' => 1
);

$body = file_get_contents($url, NULL, stream_context_create($options));

foreach($http_response_header as $header)
    sscanf($header, 'HTTP/%*d.%*d %d', $code);

echo "Status code: $code";

If you don't want to follow redirects, you can do it similar (Demo):

$url = 'http://example.com/';
$code = FALSE;

$options['http'] = array(
    'method' => "HEAD",
    'ignore_errors' => 1,
    'max_redirects' => 0
);

$body = file_get_contents($url, NULL, stream_context_create($options));

sscanf($http_response_header[0], 'HTTP/%*d.%*d %d', $code);

echo "Status code: $code";

Some of the functions, options and variables in use are explained with more detail on a blog post I've written: HEAD first with PHP Streams.

how to get the selected index of a drop down

the actual index is available as a property of the select element.

var sel = document.getElementById('CCards');
alert(sel.selectedIndex);

you can use the index to get to the selection option, where you can pull the text and value.

var opt = sel.options[sel.selectedIndex];
alert(opt.text);
alert(opt.value);

Return current date plus 7 days

$date = strtotime("+7 day", strtotime("M d, Y"));
$date =  date('j M, Y', $date);

This will work as well

vba: get unique values from array

No, VBA does not have this functionality. You can use the technique of adding each item to a collection using the item as the key. Since a collection does not allow duplicate keys, the result is distinct values that you can copy to an array, if needed.

You may also want something more robust. See Distinct Values Function at http://www.cpearson.com/excel/distinctvalues.aspx

Distinct Values Function

A VBA Function that will return an array of the distinct values in a range or array of input values.

Excel has some manual methods, such as Advanced Filter, for getting a list of distinct items from an input range. The drawback of using such methods is that you must manually refresh the results when the input data changes. Moreover, these methods work only with ranges, not arrays of values, and, not being functions, cannot be called from worksheet cells or incorporated into array formulas. This page describes a VBA function called DistinctValues that accepts as input either a range or an array of data and returns as its result an array containing the distinct items from the input list. That is, the elements with all duplicates removed. The order of the input elements is preserved. The order of the elements in the output array is the same as the order in the input values. The function can be called from an array entered range on a worksheet (see this page for information about array formulas), or from in an array formula in a single worksheet cell, or from another VB function.

Calculating moving average

One can use runner package for moving functions. In this case mean_run function. Problem with cummean is that it doesn't handle NA values, but mean_run does. runner package also supports irregular time series and windows can depend on date:

library(runner)
set.seed(11)
x1 <- rnorm(15)
x2 <- sample(c(rep(NA,5), rnorm(15)), 15, replace = TRUE)
date <- Sys.Date() + cumsum(sample(1:3, 15, replace = TRUE))

mean_run(x1)
#>  [1] -0.5910311 -0.2822184 -0.6936633 -0.8609108 -0.4530308 -0.5332176
#>  [7] -0.2679571 -0.1563477 -0.1440561 -0.2300625 -0.2844599 -0.2897842
#> [13] -0.3858234 -0.3765192 -0.4280809

mean_run(x2, na_rm = TRUE)
#>  [1] -0.18760011 -0.09022066 -0.06543317  0.03906450 -0.12188853 -0.13873536
#>  [7] -0.13873536 -0.14571604 -0.12596067 -0.11116961 -0.09881996 -0.08871569
#> [13] -0.05194292 -0.04699909 -0.05704202

mean_run(x2, na_rm = FALSE )
#>  [1] -0.18760011 -0.09022066 -0.06543317  0.03906450 -0.12188853 -0.13873536
#>  [7]          NA          NA          NA          NA          NA          NA
#> [13]          NA          NA          NA

mean_run(x2, na_rm = TRUE, k = 4)
#>  [1] -0.18760011 -0.09022066 -0.06543317  0.03906450 -0.10546063 -0.16299272
#>  [7] -0.21203756 -0.39209010 -0.13274756 -0.05603811 -0.03894684  0.01103493
#> [13]  0.09609256  0.09738460  0.04740283

mean_run(x2, na_rm = TRUE, k = 4, idx = date)
#> [1] -0.187600111 -0.090220655 -0.004349696  0.168349653 -0.206571573 -0.494335093
#> [7] -0.222969541 -0.187600111 -0.087636571  0.009742884  0.009742884  0.012326968
#> [13]  0.182442234  0.125737145  0.059094786

One can also specify other options like lag, and roll only at specific indexes. More in package and function documentation.

How to Export-CSV of Active Directory Objects?

HI you can try this...

Try..

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation

Or

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer

Hope it works for you.

How do I install a JRE or JDK to run the Android Developer Tools on Windows 7?

Your problem is that you have 64-bit eclipse running but you have 32 bit JRE.So please download JRE for 64 bit windows and let it install on the default location. Finally add that path till bin in your PATH variable. Try it should work.

fatal error: Python.h: No such file or directory

on Fedora run this for Python 2:

sudo dnf install python2-devel

and for Python 3:

sudo dnf install python3-devel

Split varchar into separate columns in Oracle

With REGEXP_SUBSTR is as simple as:

SELECT REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 1) col_one,
       REGEXP_SUBSTR(t.column_one, '[^ ]+', 1, 2) col_two
FROM YOUR_TABLE t;

Can I store images in MySQL

Yes, you can store images in the database, but it's not advisable in my opinion, and it's not general practice.

A general practice is to store images in directories on the file system and store references to the images in the database. e.g. path to the image,the image name, etc.. Or alternatively, you may even store images on a content delivery network (CDN) or numerous hosts across some great expanse of physical territory, and store references to access those resources in the database.

Images can get quite large, greater than 1MB. And so storing images in a database can potentially put unnecessary load on your database and the network between your database and your web server if they're on different hosts.

I've worked at startups, mid-size companies and large technology companies with 400K+ employees. In my 13 years of professional experience, I've never seen anyone store images in a database. I say this to support the statement it is an uncommon practice.

Renaming a directory in C#

One already exists. If you cannot get over the "Move" syntax of the System.IO namespace. There is a static class FileSystem within the Microsoft.VisualBasic.FileIO namespace that has both a RenameDirectory and RenameFile already within it.

As mentioned by SLaks, this is just a wrapper for Directory.Move and File.Move.

how to loop through rows columns in excel VBA Macro

Try this:

Create A Macro with the following thing inside:

Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(-1, 1).Select
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
ActiveCell.Offset(0, -1).Select

That particular macro will copy the current cell (place your cursor in the VOL cell you wish to copy) down one row and then copy the CAP cell also.

This is only a single loop so you can automate copying VOL and CAP of where your current active cell (where your cursor is) to down 1 row.

Just put it inside a For loop statement to do it x number of times. like:

For i = 1 to 100 'Do this 100 times
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(-1, 1).Select
    Selection.Copy
    ActiveCell.Offset(1, 0).Select
    ActiveSheet.Paste
    ActiveCell.Offset(0, -1).Select
Next i

How can I find an element by CSS class with XPath?

XPath has a contains-token function, specifically designed for this situation:

//div[contains-token(@class, 'Test')]

It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.

LINQ to Entities how to update a record

They both track your changes to the collection, just call the SaveChanges() method that should update the DB.

How do I get countifs to select all non-blank cells in Excel?

Use a criteria of "<>". It will count anything which isn't an empty cell, including #NAME? or #DIV/0!. As to why it works, damned if I know, but Excel seems to understand it.

Note: works nicely in Google Spreadsheet too

How to set a DateTime variable in SQL Server 2008?

Check This:

DECLARE
    @_month TINYINT         = 5,
    @_year SMALLINT         = 2020,
    @date_ref DATETIME      = NULL 


    IF @_year IS NULL
        SET @date_ref = GETDATE() - 430
    ELSE
    BEGIN
        SELECT @date_ref = CAST ( CAST ( @_year AS VARCHAR (4)) 
            + 
            CASE 
                WHEN @_month < 10 THEN '0' + CAST ( @_month AS VARCHAR(1)) 
                ELSE CAST ( @_month AS VARCHAR(2)) 
            END 
            + 
            '01' AS DATETIME )
    END

MAX function in where clause mysql

Some Mysql versions disallow 'limit' inside of a sub select. My answer to you (and me in the future) would be to use groups

select firstName,Lastname,id 
where {whatever}
group by id
having max(id)

This allows you to return whatever you want in the select area, without having an aggregate field.

What are the different NameID format used for?

1 and 2 are SAML 1.1 because those URIs were part of the OASIS SAML 1.1 standard. Section 8.3 of the linked PDF for the OASIS SAML 2.0 standard explains this:

Where possible an existing URN is used to specify a protocol. In the case of IETF protocols, the URN of the most current RFC that specifies the protocol is used. URI references created specifically for SAML have one of the following stems, according to the specification set version in which they were first introduced:

urn:oasis:names:tc:SAML:1.0:
urn:oasis:names:tc:SAML:1.1:
urn:oasis:names:tc:SAML:2.0:

Min/Max-value validators in asp.net mvc

Here is how I would write a validator for MaxValue

public class MaxValueAttribute : ValidationAttribute
    {
        private readonly int _maxValue;

        public MaxValueAttribute(int maxValue)
        {
            _maxValue = maxValue;
        }

        public override bool IsValid(object value)
        {
            return (int) value <= _maxValue;
        }
    }

The MinValue Attribute should be fairly the same

How to use a decimal range() step value?

more_itertools is a third-party library that implements a numeric_range tool:

import more_itertools as mit


for x in mit.numeric_range(0, 1, 0.1):
    print("{:.1f}".format(x))

Output

0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9

This tool also works for Decimal and Fraction.

alternative to "!is.null()" in R

I have also seen:

if(length(obj)) {
  # do this if object has length
  # NULL has no length
}

I don't think it's great though. Because some vectors can be of length 0. character(0), logical(0), integer(0) and that might be treated as a NULL instead of an error.

Classes vs. Functions

i know it is a controversial topic, and likely i get burned now. but here are my thoughts.

For myself i figured that it is best to avoid classes as long as possible. If i need a complex datatype I use simple struct (C/C++), dict (python), JSON (js), or similar, i.e. no constructor, no class methods, no operator overloading, no inheritance, etc. When using class, you can get carried away by OOP itself (What Design pattern, what should be private, bla bla), and loose focus on the essential stuff you wanted to code in the first place.

If your project grows big and messy, then OOP starts to make sense because some sort of helicopter-view system architecture is needed. "function vs class" also depends on the task ahead of you.

function

  • purpose: process data, manipulate data, create result sets.
  • when to use: always code a function if you want to do this: “y=f(x)”

struct/dict/json/etc (instead of class)

  • purpose: store attr./param., maintain attr./param., reuse attr./param., use attr./param. later.
  • when to use: if you deal with a set of attributes/params (preferably not mutable)
  • different languages same thing: struct (C/C++), JSON (js), dict (python), etc.
  • always prefer simple struct/dict/json/etc over complicated classes (keep it simple!)

class (if it is a new data type)

  • a simple perspective: is a struct (C), dict (python), json (js), etc. with methods attached.
  • The method should only make sense in combination with the data/param stored in the class.
  • my advice: never code complex stuff inside class methods (call an external function instead)
  • warning: do not misuse classes as fake namespace for functions! (this happens very often!)
  • other use cases: if you want to do a lot of operator overloading then use classes (e.g. your own matrix/vector multiplication class)
  • ask yourself: is it really a new “data type”? (Yes => class | No => can you avoid using a class)

array/vector/list (to store a lot of data)

  • purpose: store a lot of homogeneous data of the same data type, e.g. time series
  • advice#1: just use what your programming language already have. do not reinvent it
  • advice#2: if you really want your “class mysupercooldatacontainer”, then overload an existing array/vector/list/etc class (e.g. “class mycontainer : public std::vector…”)

enum (enum class)

  • i just mention it
  • advice#1: use enum plus switch-case instead of overcomplicated OOP design patterns
  • advice#2: use finite state machines

How can I put an icon inside a TextInput in React Native?

You can use combination of View, Icon and TextInput like so:

<View style={styles.searchSection}>
    <Icon style={styles.searchIcon} name="ios-search" size={20} color="#000"/>
    <TextInput
        style={styles.input}
        placeholder="User Nickname"
        onChangeText={(searchString) => {this.setState({searchString})}}
        underlineColorAndroid="transparent"
    />
</View>

and use flex-direction for styling

searchSection: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
},
searchIcon: {
    padding: 10,
},
input: {
    flex: 1,
    paddingTop: 10,
    paddingRight: 10,
    paddingBottom: 10,
    paddingLeft: 0,
    backgroundColor: '#fff',
    color: '#424242',
},

Icons were taken from "react-native-vector-icons"

T-SQL split string

here is a version that can split on a pattern using patindex, a simple adaptation of the post above. I had a case where I needed to split a string that contained multiple separator chars.


alter FUNCTION dbo.splitstring ( @stringToSplit VARCHAR(1000), @splitPattern varchar(10) )
RETURNS
 @returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN

 DECLARE @name NVARCHAR(255)
 DECLARE @pos INT

 WHILE PATINDEX(@splitPattern, @stringToSplit) > 0
 BEGIN
  SELECT @pos  = PATINDEX(@splitPattern, @stringToSplit)  
  SELECT @name = SUBSTRING(@stringToSplit, 1, @pos-1)

  INSERT INTO @returnList 
  SELECT @name

  SELECT @stringToSplit = SUBSTRING(@stringToSplit, @pos+1, LEN(@stringToSplit)-@pos)
 END

 INSERT INTO @returnList
 SELECT @stringToSplit

 RETURN
END
select * from dbo.splitstring('stringa/stringb/x,y,z','%[/,]%');

result looks like this

stringa stringb x y z

How to abort makefile if variable not set?

You can use an IF to test:

check:
        @[ "${var}" ] || ( echo ">> var is not set"; exit 1 )

Result:

$ make check
>> var is not set
Makefile:2: recipe for target 'check' failed
make: *** [check] Error 1

How to call Oracle MD5 hash function?

In Oracle 12c you can use the function STANDARD_HASH. It does not require any additional privileges.

select standard_hash('foo', 'MD5') from dual;

The dbms_obfuscation_toolkit is deprecated (see Note here). You can use DBMS_CRYPTO directly:

select rawtohex(
    DBMS_CRYPTO.Hash (
        UTL_I18N.STRING_TO_RAW ('foo', 'AL32UTF8'),
        2)
    ) from dual;

Output:

ACBD18DB4CC2F85CEDEF654FCCC4A4D8

Add a lower function call if needed. More on DBMS_CRYPTO.

getting the X/Y coordinates of a mouse click on an image with jQuery

Take a look at http://jsfiddle.net/TroyAlford/ZZEk8/ for a working example of the below:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset();
            var x = ev.clientX - offset.left;
            var y = ev.clientY - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Note that the above will get you the x and the y relative to the image's box - but will not correctly take into account margin, border and padding. These elements aren't actually part of the image, in your case - but they might be part of the element that you would want to take into account.

In this case, you should also use $div.outerWidth(true) - $div.width() and $div.outerHeight(true) - $div.height() to calculate the amount of margin / border / etc.

Your new code might look more like:

<img id='myImg' src='/my/img/link.gif' />

<script type="text/javascript">
    $(document).bind('click', function () {
        // Add a click-handler to the image.
        $('#myImg').bind('click', function (ev) {
            var $img = $(ev.target);

            var offset = $img.offset(); // Offset from the corner of the page.
            var xMargin = ($img.outerWidth() - $img.width()) / 2;
            var yMargin = ($img.outerHeight() - $img.height()) / 2;
            // Note that the above calculations assume your left margin is 
            // equal to your right margin, top to bottom, etc. and the same 
            // for borders.

            var x = (ev.clientX + xMargin) - offset.left;
            var y = (ev.clientY + yMargin) - offset.top;

            alert('clicked at x: ' + x + ', y: ' + y);
        });
    });
</script>

Eclipse: stop code from running (java)

For Eclipse: menu bar-> window -> show view then find "debug" option if not in list then select other ...

new window will open and then search using keyword "debug" -> select debug from list

it will added near console tab. use debug tab to terminate and remove previous executions. ( right clicking on executing process will show you many option including terminate)

How can I iterate over the elements in Hashmap?

Need Key & Value in Iteration

Use entrySet() to iterate through Map and need to access value and key:

Map<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

Need Key in Iteration

If you want just to iterate over keys of map you can use keySet()

for(String key: map.keySet()) {
     Person value = map.get(key); 
}

Need Value in Iteration

If you just want to iterate over values of map you can use values()

for(Person person: map.values()) {

}

How to serialize a JObject without the formatting?

you can use JsonConvert.SerializeObject()

JsonConvert.SerializeObject(myObject) // myObject is returned by JObject.Parse() method

JsonConvert.SerializeObject()

JObject.Parse()

How to add buttons dynamically to my form?

use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3

private void button1_Click(object sender, EventArgs e)
{
int h =3;


Button[] buttonArray = new Button[8];

for (int i = 0; i <= h-1; i++)
{
   buttonArray[i] = new Button();
   buttonArray[i].Size = new Size(20, 43);
   buttonArray[i].Name= ""+i+"";
   buttonArray[i].Click += button_Click;//function
   buttonArray[i].Location = new Point(40, 20 + (i * 20));
    panel1.Controls.Add(buttonArray[i]);

}  }

Laravel - Session store not set on request

I'm using laravel 7.x and this problem arose.. the following fixed it:

go to kernel.php and add these 2 classes to protected $middleware

\Illuminate\Session\Middleware\StartSession::class, \Illuminate\View\Middleware\ShareErrorsFromSession::class,

Adding gif image in an ImageView in android

In your build.gradle(Module:app), add android-gif-drawable as a dependency by adding the following code:

allprojects {
    repositories {
       mavenCentral()
    }
}

dependencies {
    compile 'pl.droidsonroids.gif:android-gif-drawable:1.2.+'
}


UPDATE: As of Android Gradle Plugin 3.0.0, the new command for compiling is implementation, so the above line might have to be changed to:

dependencies {
    implementation 'pl.droidsonroids.gif:android-gif-drawable:1.2.17'
}

Then sync your project. When synchronization ends, go to your layout file and add the following code:

<pl.droidsonroids.gif.GifImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:src="@drawable/gif_file"
/>

And that's it, you can manage it with a simple ImageView.

Server is already running in Rails

If you are on Windows, you just need to do only one step as 'rails restart' and then again type 'rails s' You are good to go.

Pandas convert dataframe to array of tuples

The most efficient and easy way:

list(data_set.to_records())

You can filter the columns you need before this call.

The POM for project is missing, no dependency information available

The scope <scope>provided</scope> gives you an opportunity to tell that the jar would be available at runtime, so do not bundle it. It does not mean that you do not need it at compile time, hence maven would try to download that.

Now I think, the below maven artifact do not exist at all. I tries searching google, but not able to find. Hence you are getting this issue.

Change groupId to <groupId>net.sourceforge.ant4x</groupId> to get the latest jar.

<dependency>
  <groupId>net.sourceforge.ant4x</groupId>
  <artifactId>ant4x</artifactId>
  <version>${net.sourceforge.ant4x-version}</version>
  <scope>provided</scope>
</dependency>

Another solution for this problem is:

  1. Run your own maven repo.
  2. download the jar
  3. Install the jar into the repository.
  4. Add a code in your pom.xml something like:

Where http://localhost/repo is your local repo URL:

<repositories>
    <repository>
        <id>wmc-central</id>
        <url>http://localhost/repo</url>
    </repository>
    <-- Other repository config ... -->
</repositories>

How can I create a copy of an Oracle table without copying the data?

Just use a where clause that won't select any rows:

create table xyz_new as select * from xyz where 1=0;

Limitations

The following things will not be copied to the new table:

  • sequences
  • triggers
  • indexes
  • some constraints may not be copied
  • materialized view logs

This also does not handle partitions


javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

How to make HTML open a hyperlink in another window or tab?

the target = _blank is will open in new tab or windows based on browser setting.

To force a new window use javascript onclick all three parts are needed. url, a name, and window width and height size or it will just open in a new tab.

<a onclick="window.open('http://www.starfall.com/','name','width=600,height=400')">Starfall</a>

How to convert index of a pandas dataframe into a column?

df1 = pd.DataFrame({"gi":[232,66,34,43],"ptt":[342,56,662,123]})
p = df1.index.values
df1.insert( 0, column="new",value = p)
df1

    new     gi     ptt
0    0      232    342
1    1      66     56 
2    2      34     662
3    3      43     123

Copy data from another Workbook through VBA

I had the same question but applying the provided solutions changed the file to write in. Once I selected the new excel file, I was also writing in that file and not in my original file. My solution for this issue is below:

Sub GetData()

    Dim excelapp As Application
    Dim source As Workbook
    Dim srcSH1 As Worksheet
    Dim sh As Worksheet
    Dim path As String
    Dim nmr As Long
    Dim i As Long

    nmr = 20

    Set excelapp = New Application

    With Application.FileDialog(msoFileDialogOpen)
        .AllowMultiSelect = False
        .Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1
        .Show
        path = .SelectedItems.Item(1)
    End With

    Set source = excelapp.Workbooks.Open(path)
    Set srcSH1 = source.Worksheets("Sheet1")
    Set sh = Sheets("Sheet1")

    For i = 1 To nmr
        sh.Cells(i, "A").Value = srcSH1.Cells(i, "A").Value
    Next i

End Sub

With excelapp a new application will be called. The with block sets the path for the external file. Finally, I set the external Workbook with source and srcSH1 as a Worksheet within the external sheet.

Pass variables from servlet to jsp

Use

request.setAttribute("attributeName");

and then

getServletContext().getRequestDispatcher("/file.jsp").forward();

Then it will be accessible in the JSP.

As a side note - in your jsp avoid using java code. Use JSTL.

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

Vim clear last search highlighting

This will clear the search highlight after updatetime milliseconds of inactivity.

updatetime defaults to 4000ms or 4s but I set mine to 10s. It is important to note that updatetime does more than just this so read the docs before you change it.

function! SearchHlClear()
    let @/ = ''
endfunction
augroup searchhighlight
    autocmd!
    autocmd CursorHold,CursorHoldI * call SearchHlClear()
augroup END

Get img thumbnails from Vimeo?

Actually the guy who asked that question posted his own answer.

"Vimeo seem to want me to make a HTTP request, and extract the thumbnail URL from the XML they return..."

The Vimeo API docs are here: http://vimeo.com/api/docs/simple-api

In short, your app needs to make a GET request to an URL like the following:

http://vimeo.com/api/v2/video/video_id.output

and parse the returned data to get the thumbnail URL that you require, then download the file at that URL.

Can I perform a DNS lookup (hostname to IP address) using client-side Javascript?

Edit: This question gave me an itch, so I put up a JSONP webservice on Google App Engine that returns the clients ip address. Usage:

<script type="application/javascript">
function getip(json){
  alert(json.ip); // alerts the ip address
}
</script>

<script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"> </script>

Yay, no server proxies needed.


Pure JS can't. If you have a server script under the same domain that prints it out you could send a XMLHttpRequest to read it.

find_spec_for_exe': can't find gem bundler (>= 0.a) (Gem::GemNotFoundException)

The reason is your current ruby environment, you got a different version of bundler with the version in Gemfile.lock.

  • Safe way, install bundler with the same version in Gemfile.lock, this won't break anything if there is some incampatibly thing happened.
  • Hard way, just remove Gemfile.lock, and run bundle install.

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

You need to add a COM reference in your project to the "Microsoft Excel 11.0 Object Library" - or whatever version is appropriate.

This code works for me:

private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
    Microsoft.Office.Interop.Excel.Application xlApp = null;
    Workbook xlWorkbook = null;
    Sheets xlSheets = null;
    Worksheet xlNewSheet = null;

    try {
        xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
            return;

        // Uncomment the line below if you want to see what's happening in Excel
        // xlApp.Visible = true;

        xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
                false, XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);

        xlSheets = xlWorkbook.Sheets as Sheets;

        // The first argument below inserts the new worksheet as the first one
        xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
        xlNewSheet.Name = worksheetName;

        xlWorkbook.Save();
        xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
        xlApp.Quit();
    }
    finally {
        Marshal.ReleaseComObject(xlNewSheet);
        Marshal.ReleaseComObject(xlSheets);
        Marshal.ReleaseComObject(xlWorkbook);
        Marshal.ReleaseComObject(xlApp);
        xlApp = null;
    }
}

Note that you want to be very careful about properly cleaning up and releasing your COM object references. Included in that StackOverflow question is a useful rule of thumb: "Never use 2 dots with COM objects". In your code; you're going to have real trouble with that. My demo code above does NOT properly clean up the Excel app, but it's a start!

Some other links that I found useful when looking into this question:

According to MSDN

To use COM interop, you must have administrator or Power User security permissions.

Hope that helps.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Here is a possible solution:

From your first script, call your second script with the following line:

wscript.exe invis.vbs run.bat %*

Actually, you are calling a vbs script with:

  • the [path]\name of your script
  • all the other arguments needed by your script (%*)

Then, invis.vbs will call your script with the Windows Script Host Run() method, which takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

C++: Converting Hexadecimal to Decimal

Well, the C way might be something like ...

#include <stdlib.h>
#include <stdio.h>

int main()
{
        int n;
        scanf("%d", &n);
        printf("%X", n);

        exit(0);
}

How do I combine 2 javascript variables into a string

You can use the JavaScript String concat() Method,

var str1 = "Hello ";
var str2 = "world!";
var res = str1.concat(str2); //will return "Hello world!"

Its syntax is:

string.concat(string1, string2, ..., stringX)

How to sum a variable by group

You can also use the by() function:

x2 <- by(x$Frequency, x$Category, sum)
do.call(rbind,as.list(x2))

Those other packages (plyr, reshape) have the benefit of returning a data.frame, but it's worth being familiar with by() since it's a base function.

How to get an Instagram Access Token

This worked just fine for me:

http://jelled.com/instagram/access-token

FYI, I used it in combination with the jQuery Instagram plugin which you'll find here; http://potomak.github.com/jquery-instagram

How to show loading spinner in jQuery?

There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.

$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

The ajaxStart/Stop functions will fire whenever you do any Ajax calls.

Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop should only be attached to document. This would transform the above snippet to:

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });

How do I put an image into my picturebox using ImageLocation?

Setting the image using picture.ImageLocation() works fine, but you are using a relative path. Check your path against the location of the .exe after it is built.

For example, if your .exe is located at:

<project folder>/bin/Debug/app.exe

The image would have to be at:

<project folder>/bin/Image/1.jpg


Of course, you could just set the image at design-time (the Image property on the PictureBox property sheet).

If you must set it at run-time, one way to make sure you know the location of the image is to add the image file to your project. For example, add a new folder to your project, name it Image. Right-click the folder, choose "Add existing item" and browse to your image (be sure the file filter is set to show image files). After adding the image, in the property sheet set the Copy to Output Directory to Copy if newer.

At this point the image file will be copied when you build the application and you can use

picture.ImageLocation = @"Image\1.jpg"; 

Difference between PCDATA and CDATA in DTD

PCDATA - Parsed Character Data

XML parsers normally parse all the text in an XML document.

CDATA - (Unparsed) Character Data

The term CDATA is used about text data that should not be parsed by the XML parser.

Characters like "<" and "&" are illegal in XML elements.

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

Django DateField default options

This is why you should always import the base datetime module: import datetime, rather than the datetime class within that module: from datetime import datetime.

The other mistake you have made is to actually call the function in the default, with the (). This means that all models will get the date at the time the class is first defined - so if your server stays up for days or weeks without restarting Apache, all elements will get same the initial date.

So the field should be:

import datetime
date = models.DateField(_("Date"), default=datetime.date.today)

Managing SSH keys within Jenkins for Git

This works for me if you have config and the private key file in the /Jenkins/.ssh/ you need to chown (change owner) for these 2 files then restart jenkins in order for the jenkins instance to read these 2 files.

CSS display:table-row does not expand when width is set to 100%

give on .view-type class float:left; or delete the float:right; of .view-name

edit: Wrap your div <div class="view-row"> with another div for example <div class="table">

and set the following css :

.table {
    display:table;
    width:100%;}

You have to use the table structure for correct results.

How can I delete all Git branches which have been merged?

My Bash script contribution is based loosely on mmrobin's answer.

It takes some useful parameters specifying includes and excludes, or to examine/remove only local or remote branches instead of both.

#!/bin/bash

# exclude branches regex, configure as "(branch1|branch2|etc)$"
excludes_default="(master|next|ag/doc-updates)$"
excludes="__NOTHING__"
includes=
merged="--merged"
local=1
remote=1

while [ $# -gt 0 ]; do
  case "$1" in
  -i) shift; includes="$includes $1" ;;
  -e) shift; excludes="$1" ;;
  --no-local) local=0 ;;
  --no-remote) remote=0 ;;
  --all) merged= ;;
  *) echo "Unknown argument $1"; exit 1 ;;
  esac
  shift   # next option
done

if [ "$includes" == "" ]; then
  includes=".*"
else
  includes="($(echo $includes | sed -e 's/ /|/g'))"
fi

current_branch=$(git branch --no-color 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/')
if [ "$current_branch" != "master" ]; then
  echo "WARNING: You are on branch $current_branch, NOT master."
fi
echo -e "Fetching branches...\n"

git remote update --prune
remote_branches=$(git branch -r $merged | grep -v "/$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
local_branches=$(git branch $merged | grep -v "$current_branch$" | grep -v -E "$excludes" | grep -v -E "$excludes_default" | grep -E "$includes")
if [ -z "$remote_branches" ] && [ -z "$local_branches" ]; then
  echo "No existing branches have been merged into $current_branch."
else
  echo "This will remove the following branches:"
  if [ "$remote" == 1 -a -n "$remote_branches" ]; then
    echo "$remote_branches"
  fi
  if [ "$local" == 1 -a -n "$local_branches" ]; then
    echo "$local_branches"
  fi
  read -p "Continue? (y/n): " -n 1 choice
  echo
  if [ "$choice" == "y" ] || [ "$choice" == "Y" ]; then
    if [ "$remote" == 1 ]; then
      remotes=$(git remote)
      # Remove remote branches
      for remote in $remotes
      do
        branches=$(echo "$remote_branches" | grep "$remote/" | sed "s/$remote\/\(.*\)/:\1 /g" | tr -d '\n')
        git push $remote $branches
      done
    fi

    if [ "$local" == 1 ]; then
      # Remove local branches
      locals=$(echo "$local_branches" | sed 's/origin\///g' | tr -d '\n')
      if [ -z "$locals" ]; then
        echo "No branches removed."
      else
        git branch -d $(echo "$locals" | tr -d '\n')
      fi
    fi
  fi
fi

Python : List of dict, if exists increment a dict value, if not append a new dict

To do it exactly your way? You could use the for...else structure

for url in list_of_urls:
    for url_dict in urls:
        if url_dict['url'] == url:
            url_dict['nbr'] += 1
            break
    else:
        urls.append(dict(url=url, nbr=1))

But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:

urls = {'http://www.google.fr/': dict(url='http://www.google.fr/', nbr=1)}

for url in list_of_urls:
    if url in urls:
        urls[url]['nbr'] += 1
    else:
        urls[url] = dict(url=url, nbr=1)

A few things to note in that second example:

  • see how using a dict for urls removes the need for going through the whole urls list when testing for one single url. This approach will be faster.
  • Using dict( ) instead of braces makes your code shorter
  • using list_of_urls, urls and url as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit, urls_already_visited and current_url. I know, it's longer. But it's clearer.

And of course I'm assuming that dict(url='http://www.google.fr', nbr=1) is a simplification of your own data structure, because otherwise, urls could simply be:

urls = {'http://www.google.fr':1}

for url in list_of_urls:
    if url in urls:
        urls[url] += 1
    else:
        urls[url] = 1

Which can get very elegant with the defaultdict stance:

urls = collections.defaultdict(int)
for url in list_of_urls:
    urls[url] += 1

Android: I am unable to have ViewPager WRAP_CONTENT

I just bumped into the same issue. I had a ViewPager and I wanted to display an ad at the button of it. The solution I found was to get the pager into a RelativeView and set it's layout_above to the view id i want to see below it. that worked for me.

here is my layout XML:

  <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <LinearLayout
        android:id="@+id/AdLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:orientation="vertical" >
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/mainpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@+id/AdLayout" >
    </android.support.v4.view.ViewPager>
</RelativeLayout>

Woocommerce, get current product id

Save the current product id before entering your loop:

$current_product = $product->id;

Then in your loop for your sidebar, use $product->id again to compare:

 <li><a <? if ($product->id == $current_product) { echo "class='on'"; }?> href="<?=get_permalink();?>"><?=the_title();?></a></li>

UL has margin on the left

The <ul> element has browser inherent padding & margin by default. In your case, Use

#footer ul {
    margin: 0; /* To remove default bottom margin */ 
    padding: 0; /* To remove default left padding */
}

or a CSS browser reset ( https://cssreset.com/ ) to deal with this.

How to "properly" print a list?

This is simple code, so if you are new you should understand it easily enough.

    mylist = ["x", 3, "b"]
    for items in mylist:
        print(items)

It prints all of them without quotes, like you wanted.

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

Toggle Checkboxes on/off

Assuming that it's an image that has to toggle the checkbox, this works for me

<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">

How to increment datetime by custom months in python without using library

This is short and sweet method to add a month to a date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

date_after_month = datetime.today()+ relativedelta(months=1)
print 'Today: ',datetime.today().strftime('%d/%m/%Y')
print 'After Month:', date_after_month.strftime('%d/%m/%Y')

Output:

Today: 01/03/2013

After Month: 01/04/2013

A word of warning: relativedelta(months=1) and relativedelta(month=1) have different meanings. Passing month=1 will replace the month in original date to January whereas passing months=1 will add one month to original date.

Note: this will requires python-dateutil. To install it you need to run in Linux terminal.

sudo apt-get update && sudo apt-get install python-dateutil

Explanation : Add month value in python

HTML5 Form Input Pattern Currency Format

The best we could come up with is this:

^\\$?(([1-9](\\d*|\\d{0,2}(,\\d{3})*))|0)(\\.\\d{1,2})?$

I realize it might seem too much, but as far as I can test it matches anything that a human eye would accept as valid currency value and weeds out everything else.

It matches these:

1 => true
1.00 => true
$1 => true
$1000 => true
0.1 => true
1,000.00 => true
$1,000,000 => true
5678 => true

And weeds out these:

1.001 => false
02.0 => false
22,42 => false
001 => false
192.168.1.2 => false
, => false
.55 => false
2000,000 => false

How to get the last char of a string in PHP?

substr("testers", -1); // returns "s"

Or, for multibytes strings :

substr("multibyte string…", -1); // returns "…"

Displaying better error message than "No JSON object could be decoded"

You could try the rson library found here: http://code.google.com/p/rson/ . I it also up on PYPI: https://pypi.python.org/pypi/rson/0.9 so you can use easy_install or pip to get it.

for the example given by tom:

>>> rson.loads('[1,2,]')
...
rson.base.tokenizer.RSONDecodeError: Unexpected trailing comma: line 1, column 6, text ']'

RSON is a designed to be a superset of JSON, so it can parse JSON files. It also has an alternate syntax which is much nicer for humans to look at and edit. I use it quite a bit for input files.

As for the capitalizing of boolean values: it appears that rson reads incorrectly capitalized booleans as strings.

>>> rson.loads('[true,False]')
[True, u'False']

Difference between binary semaphore and mutex

In windows the difference is as below. MUTEX: process which successfully executes wait has to execute a signal and vice versa. BINARY SEMAPHORES: Different processes can execute wait or signal operation on a semaphore.

jQuery get the name of a select option

The Code is very Simple, Lets Put This Code

var name = $("#band_type_choices  option:selected").text();

Here You don't want to use $(this).find().text(), directly you can put your id name and add option:selected along with text().

This will return the result option name. Better Try this...

How do I format a number to a dollar amount in PHP

/*     Just Do the following, */

echo money_format("%(#10n","123.45"); //Output $ 123.45

/*    If Negative Number -123.45 */

echo money_format("%(#10n","-123.45"); //Output ($ 123.45)

How to pause / sleep thread or process in Android?

Or you could use:

android.os.SystemClock.sleep(checkEvery)

which has the advantage of not requiring a wrapping try ... catch.

Using R to list all files with a specified extension

Peg the pattern to find "\\.dbf" at the end of the string using the $ character:

list.files(pattern = "\\.dbf$")

How do you find the first key in a dictionary?

easiest way is:

first_key = my_dict.keys()[0]

but some times you should be more careful and assure that your entity is a valuable list so:

first_key = list(my_dict.keys())[0]

iPhone UILabel text soft shadow

To keep things up to date: Creating the shadow in Swift is as easy as that:

Import the QuartzCore Framework

import QuartzCore

And set the shadow attributes to your label

titleLabel.shadowColor = UIColor.blackColor()
titleLabel.shadowOffset = CGSizeMake(0.0, 0.0)
titleLabel.layer.shadowRadius = 5.0
titleLabel.layer.shadowOpacity = 0.8
titleLabel.layer.masksToBounds = false
titleLabel.layer.shouldRasterize = true

Ellipsis for overflow text in dropdown boxes

You can use this:

select {
    width:100px; 
    overflow:hidden; 
    white-space:nowrap; 
    text-overflow:ellipsis;
}
select option {
    width:100px;
    text-overflow:ellipsis;
    overflow:hidden;
}
div {
    border-style:solid; 
    width:100px; 
    overflow:hidden; 
    white-space:nowrap; 
    text-overflow:ellipsis;
}

What is going wrong when Visual Studio tells me "xcopy exited with code 4"

I had a post build command that worked just fine before I did an update on VS 2017. It turned out that the SDK tools updated and were under a new path so it couldn't find the tool I was using to sign my assemblies.

This changed from this....

call "%VS140COMNTOOLS%vsvars32"
    "C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6 Tools\x64\sn.exe" -Ra "$(TargetPath)" "$(ProjectDir)Key.snk"

To This...

"C:\Program Files (x86)\Microsoft SDKs\Windows\v10.0A\bin\NETFX 4.6.1 Tools\x64\sn.exe" -Ra "$(TargetPath)" "$(ProjectDir)Key.snk"

Very subtle but breaking change, so check your paths after an update if you see this error.

How can I commit a single file using SVN over a network?

cd myapp/trunk
svn commit -m "commit message" page1.html

For more information, see:

svn commit --help

I also recommend this free book, if you're just getting started with Subversion.

How to add number of days in postgresql datetime

This will give you the deadline :

select id,  
       title,
       created_at + interval '1' day * claim_window as deadline
from projects

Alternatively the function make_interval can be used:

select id,  
       title,
       created_at + make_interval(days => claim_window) as deadline
from projects

To get all projects where the deadline is over, use:

select *
from (
  select id, 
         created_at + interval '1' day * claim_window as deadline
  from projects
) t
where localtimestamp at time zone 'UTC' > deadline

Select multiple columns from a table, but group by one

I just wanted to add a more effective and generic way to solve this kind of problems. The main idea is about working with sub queries.

do your group by and join the same table on the ID of the table.

your case is more specific since your productId is not unique so there is 2 ways to solve this.

I will begin by the more specific solution: Since your productId is not unique we will need an extra step which is to select DISCTINCT product ids after grouping and doing the sub query like following:

WITH CTE_TEST AS (SELECT productId, SUM(OrderQuantity) Total
                    FROM OrderDetails
                    GROUP BY productId)
SELECT DISTINCT(OrderDetails.ProductID), OrderDetails.ProductName, CTE_TEST.Total
FROM OrderDetails 
INNER JOIN CTE_TEST ON CTE_TEST.ProductID = OrderDetails.ProductID

this returns exactly what is expected

 ProductID     ProductName         Total
    1001          abc               12    
    1002          abc               23
    2002          xyz               8
    3004          ytp               15
    4001          aze               19

But there a cleaner way to do this. I guess that ProductId is a foreign key to products table and i guess that there should be and OrderId primary key (unique) in this table.

in this case there are few steps to do to include extra columns while grouping on only one. It will be the same solution as following

Let's take this t_Value table for example:

enter image description here

If i want to group by description and also display all columns.

All i have to do is:

  1. create WITH CTE_Name subquery with your GroupBy column and COUNT condition
  2. select all(or whatever you want to display) from value table and the total from the CTE
  3. INNER JOIN with CTE on the ID(primary key or unique constraint) column

and that's it!

Here is the query

WITH CTE_TEST AS (SELECT Description, MAX(Id) specID, COUNT(Description) quantity 
                    FROM sch_dta.t_value
                    GROUP BY Description)
SELECT sch_dta.t_Value.*, CTE_TEST.quantity 
FROM sch_dta.t_Value 
INNER JOIN CTE_TEST ON CTE_TEST.specID = sch_dta.t_Value.Id

And here is the result:

enter image description here

Set default time in bootstrap-datetimepicker

This Works for me. I have to use specially date format like this 'YY-MM-dd hh:mm' or 'YYYY-MM-dd hh:mm'

$('#datetimepicker1').datetimepicker({
            format: 'YYYY-MM-dd hh:mm',
            defaultDate: new Date()
        });

Removing Spaces from a String in C?

Easiest and most efficient don't usually go together...

Here's a possible solution:

void remove_spaces(char* s) {
    const char* d = s;
    do {
        while (*d == ' ') {
            ++d;
        }
    } while (*s++ = *d++);
}

MySQL Workbench not opening on Windows

I have uninstalled 8.0.19 (64) and installed 8.0.18 (64 bit) and now it Opens.

AngularJS - value attribute for select

You can't really do this unless you build them yourself in an ng-repeat.

<select ng-model="foo">
   <option ng-repeat="item in items" value="{{item.code}}">{{item.name}}</option>
</select>

BUT... it's probably not worth it. It's better to leave it function as designed and let Angular handle the inner workings. Angular uses the index this way so you can actually use an entire object as a value. So you can use a drop down binding to select a whole value rather than just a string, which is pretty awesome:

<select ng-model="foo" ng-options="item as item.name for item in items"></select>

{{foo | json}}

programmatically add column & rows to WPF Datagrid

To Bind the DataTable into the DataGridTextColumn in CodeBehind xaml

<DataGrid
  Name="TrkDataGrid"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>

xaml.cs

  foreach (DataColumn col in dt.Columns)
  {
    TrkDataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  TrkDataGrid.ItemsSource= dt.DefaultView;

How to completely remove node.js from Windows

In my case, the above alone didn't work. I had installed and uninstalled several versions of nodejs to fix this error: npm in windows Error: EISDIR, read at Error (native) that I kept getting on any npm command I tried to run, including getting the npm version with: npm -v.

So the npm directory was deleted in the nodejs folder and the latest npm version was copied over from the npm dist: and then everything started working.

How can I remount my Android/system as read-write in a bash script using adb?

I could not get the mount command to work without specifying the dev block to mount as /system

#cat /proc/mounts returns ( only the system line here )
/dev/stl12 /system rfs ro,relatime,vfat,log_off,check=no,gid/uid/rwx,iocharset=utf8 0 0

so my working command is
mount -o rw,remount -t rfs /dev/stl12 /system

TCP: can two different sockets share a port?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all ip addresses". An easy mistake to make is to only listen on port 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/quickweb) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

How can a Javascript object refer to values in itself?

This is not JSON. JSON was designed to be simple; allowing arbitrary expressions is not simple.

In full JavaScript, I don't think you can do this directly. You cannot refer to this until the object called obj is fully constructed. So you need a workaround, that someone with more JavaScript-fu than I will provide.

ClassNotFoundException: org.slf4j.LoggerFactory

Better to always download as your first try, the most recent version from the developer's site

I had the same error message you had, and by downloading the jar from the above (slf4j-1.7.2.tar.gz most recent version as of 2012OCT13), untarring, uncompressing, adding 2 jars to build path in eclipse (or adding to classpath in comand line):

  1. slf4j-api-1.7.2.jar
  2. slf4j-simple-1.7.2.jar

I was able to run my program.

Android: failed to convert @drawable/picture into a drawable

It can be even more trivial than what the other posters suggested: if you have multiple projects make sure you did not create the xml layout file in the wrong project.

After creation, the file will open automatically so this might go unnoticed and you assume it is in the correct project. Obviously any references to drawables or other resources will be invalid.

And yes, I am that stupid. I'll close any unused projects from now on :)

Is there a foreach loop in Go?

Yes, Range :

The range form of the for loop iterates over a slice or map.

When ranging over a slice, two values are returned for each iteration. The first is the index, and the second is a copy of the element at that index.

Example :

package main

import "fmt"

var pow = []int{1, 2, 4, 8, 16, 32, 64, 128}

func main() {
    for i, v := range pow {
        fmt.Printf("2**%d = %d\n", i, v)
    }

    for i := range pow {
        pow[i] = 1 << uint(i) // == 2**i
    }
    for _, value := range pow {
        fmt.Printf("%d\n", value)
    }
}
  • You can skip the index or value by assigning to _.
  • If you only want the index, drop the , value entirely.

Powershell v3 Invoke-WebRequest HTTPS error

Lee's answer is great, but I also had issues with which protocols the web server supported.
After also adding the following lines, I could get the https request through. As pointed out in this answer https://stackoverflow.com/a/36266735

$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols

My full solution with Lee's code.

add-type @"
using System.Net;
using System.Security.Cryptography.X509Certificates;
public class TrustAllCertsPolicy : ICertificatePolicy {
    public bool CheckValidationResult(
        ServicePoint srvPoint, X509Certificate certificate,
        WebRequest request, int certificateProblem) {
        return true;
    }
}
"@
$AllProtocols = [System.Net.SecurityProtocolType]'Ssl3,Tls,Tls11,Tls12'
[System.Net.ServicePointManager]::SecurityProtocol = $AllProtocols
[System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

Where can I set path to make.exe on Windows?

here I'm providing solution to setup terraform enviroment variable in windows to beginners.

  1. Download the terraform package from portal either 32/64 bit version.
  2. make a folder in C drive in program files if its 32 bit package you have to create folder inside on programs(x86) folder or else inside programs(64 bit) folder.
  3. Extract a downloaded file in this location or copy terraform.exe file into this folder. copy this path location like C:\Programfile\terraform\
  4. Then got to Control Panel -> System -> System settings -> Environment Variables

Open system variables, select the path > edit > new > place the terraform.exe file location like > C:\Programfile\terraform\

and Save it.

  1. Open new terminal and now check the terraform.

How to install VS2015 Community Edition offline

It seems there are direct links and anyone could get it with a download manager.

http://download.microsoft.com/download/1/6/d/16dc7044-cd36-49b4-bdba-30166e07c786/vs2015.2.com_deu.iso

http://download.microsoft.com/download/f/d/c/fdce5d40-87d3-4bd6-9139-2a7638b96174/vs2015.2.com_enu.iso

http://download.microsoft.com/download/4/1/5/415ec933-31ee-443d-8bd6-55268d472331/vs2015.2.com_esn.iso

http://download.microsoft.com/download/7/7/4/77471e13-cfac-43c2-b76e-459238142bd5/vs2015.2.com_fra.iso

http://download.microsoft.com/download/5/9/9/5991bfbe-21d0-430a-ad1c-2aa8328a2d3e/vs2015.2.com_ita.iso

http://download.microsoft.com/download/c/a/1/ca188bdc-fead-4933-a699-4da31a4b04db/vs2015.2.com_rus.iso

http://download.microsoft.com/download/3/4/a/34a0480a-effd-4e12-878b-d243bdbb4d2c/vs2015.2.com_kor.iso

http://download.microsoft.com/download/0/f/8/0f89c8af-9430-4c13-bf6a-d75b7513ac29/vs2015.2.com_chs.iso

http://download.microsoft.com/download/1/2/c/12c9f1b7-71e2-46fc-a07b-e53b2a954c4c/vs2015.2.com_jpn.iso

http://download.microsoft.com/download/7/1/8/7186591d-7877-4461-9b49-7e236846f526/vs2015.2.com_cht.iso

References from here

How to pass form input value to php function

You can write your php file to the action attr of form element.
At the php side you can get the form value by $_POST['element_name'].

Hashmap does not work with int, char

You cannot put primitive types into collections. However, you can declare them using their corresponding object wrappers and still add the primitive values, as long as the boxing allows you.

Preventing multiple clicks on button

After hours of searching i fixed it in this way:

    old_timestamp == null;

    $('#productivity_table').on('click', function(event) {

    // code executed at first load
    // not working if you press too many clicks, it waits 1 second
    if(old_timestamp == null || old_timestamp + 1000 < event.timeStamp)
    {
         // write the code / slide / fade / whatever
         old_timestamp = event.timeStamp;
    }
    });

Convert blob URL to normal URL

For those who came here looking for a way to download a blob url video / audio, this answer worked for me. In short, you would need to find an *.m3u8 file on the desired web page through Chrome -> Network tab and paste it into a VLC player.

Another guide shows you how to save a stream with the VLC Player.

Get div height with plain JavaScript

jsFiddle

var element = document.getElementById('element');
alert(element.offsetHeight);

How to specify table's height such that a vertical scroll bar appears?

This CSS also shows a fixed height HTML table. It sets the height of the HTML tbody to 400 pixels and the HTML tbody scrolls when the it is larger, retaining the HTML thead as a non-scrolling element.

In addition, each th cell in the heading and each td cell the body should be styled for the desired fixed width.

#the-table {
  display: block;
  background: white; /* optional */
}

#the-table thead {
  text-align: left; /* optional */
}

#the-table tbody {
  display: block;
  max-height: 400px;
  overflow-y: scroll;
}

How to run vbs as administrator from vbs?

Nice article for elevation options - http://www.novell.com/support/kb/doc.php?id=7010269

Configuring Applications to Always Request Elevated Rights:

Programs can be configured to always request elevation on the user level via registry settings under HKCU. These registry settings are effective on the fly, so they can be set immediately prior to launching a particular application and even removed as soon as the application is launched, if so desired. Simply create a "String Value" under "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers" for the full path to an executable with a value of "RUN AS ADMIN". Below is an example for CMD.

Windows Registry Editor Version 5.00
[HKEY_Current_User\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"c:\\windows\\system32\\cmd.exe"="RUNASADMIN"

How do I ignore files in a directory in Git?

Both examples in the question are actually very bad examples that can lead to data loss!

My advice: never append /* to directories in .gitignore files, unless you have a good reason!

A good reason would be for example what Jefromi wrote: "if you intend to subsequently un-ignore something in the directory".

The reason why it otherwise shouldn't be done is that appending /* to directories does on the one hand work in the manner that it properly ignores all contents of the directory, but on the other hand it has a dangerous side effect:

If you execute git stash -u (to temporarily stash tracked and untracked files) or git clean -df (to delete untracked but keep ignored files) in your repository, all directories that are ignored with an appended /* will be irreversibly deleted!

Some background

I had to learn this the hard way. Somebody in my team was appending /* to some directories in our .gitignore. Over the time I had occasions where certain directories would suddenly disappear. Directories with gigabytes of local data needed by our application. Nobody could explain it and I always hat to re-download all data. After a while I got a notion that it might have to do with git stash. One day I wanted to clean my local repo (while keeping ignored files) and I was using git clean -df and again my data was gone. This time I had enough and investigated the issue. I finally figured that the reason is the appended /*.

I assume it can be explained somehow by the fact that directory/* does ignore all contents of the directory but not the directory itself. Thus it's neither considered tracked nor ignored when things get deleted. Even though git status and git status --ignored give a slightly different picture on it.

How to reproduce

Here is how to reproduce the behaviour. I'm currently using Git 2.8.4.

A directory called localdata/ with a dummy file in it (important.dat) will be created in a local git repository and the contents will be ignored by putting /localdata/* into the .gitignore file. When one of the two mentioned git commands is executed now, the directory will be (unexpectedly) lost.

mkdir test
cd test
git init
echo "/localdata/*" >.gitignore
git add .gitignore
git commit -m "Add .gitignore."
mkdir localdata
echo "Important data" >localdata/important.dat
touch untracked-file

If you do a git status --ignored here, you'll get:

On branch master
Untracked files:
  (use "git add <file>..." to include in what will be committed)

  untracked-file

Ignored files:
  (use "git add -f <file>..." to include in what will be committed)

  localdata/

Now either do

git stash -u
git stash pop

or

git clean -df

In both cases the allegedly ignored directory localdata will be gone!

Not sure if this can be considered a bug, but I guess it's at least a feature that nobody needs.

I'll report that to the git development list and see what they think about it.

How can I pass a member function where a free function is expected?

Not sure why this incredibly simple solution has been passed up:

#include <stdio.h>

class aClass
{
public:
    void aTest(int a, int b)
    {
        printf("%d + %d = %d\n", a, b, a + b);
    }
};

template<class C>
void function1(void (C::*function)(int, int), C& c)
{
    (c.*function)(1, 1);
}
void function1(void (*function)(int, int)) {
  function(1, 1);
}

void test(int a,int b)
{
    printf("%d - %d = %d\n", a , b , a - b);
}

int main (int argc, const char* argv[])
{
    aClass a;

    function1(&test);
    function1<aClass>(&aClass::aTest, a);
    return 0;
}

Output:

1 - 1 = 0
1 + 1 = 2

Graph implementation C++

Below is a implementation of Graph Data Structure in C++ as Adjacency List.

I have used STL vector for representation of vertices and STL pair for denoting edge and destination vertex.

#include <iostream>
#include <vector>
#include <map>
#include <string>

using namespace std;

struct vertex {
    typedef pair<int, vertex*> ve;
    vector<ve> adj; //cost of edge, destination vertex
    string name;
    vertex(string s) : name(s) {}
};

class graph
{
public:
    typedef map<string, vertex *> vmap;
    vmap work;
    void addvertex(const string&);
    void addedge(const string& from, const string& to, double cost);
};

void graph::addvertex(const string &name)
{
    vmap::iterator itr = work.find(name);
    if (itr == work.end())
    {
        vertex *v;
        v = new vertex(name);
        work[name] = v;
        return;
    }
    cout << "\nVertex already exists!";
}

void graph::addedge(const string& from, const string& to, double cost)
{
    vertex *f = (work.find(from)->second);
    vertex *t = (work.find(to)->second);
    pair<int, vertex *> edge = make_pair(cost, t);
    f->adj.push_back(edge);
}

Resize to fit image in div, and center horizontally and vertically

SOLUTION

<style>
.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
    background-image: url("http://i.imgur.com/H9lpVkZ.jpg");
    background-repeat: no-repeat;
    background-position: center;
    background-size: contain;

}

</style>

<div class='container'>
</div>

<div class='container' style='width:50px;height:100px;line-height:100px'>
</div>

<div class='container' style='width:140px;height:70px;line-height:70px'>
</div>

Regex to replace everything except numbers and a decimal point

Check the link Regular Expression Demo

use the below reg exp

[a-z] + [^0-9\s.]+|.(?!\d)

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

Basically:

Use IncludeErrorDetailPolicy instead if CustomErrors doesn't solve it for you (e.g. if you're ASP.NET stack is >2012):

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy 
= IncludeErrorDetailPolicy.Always;

Note: Be careful returning detailed error info can reveal sensitive information to 'hackers'. See Simon's comment on this answer below.

TL;DR version

For me CustomErrors didn't really help. It was already set to Off, but I still only got a measly an error has occurred message. I guess the accepted answer is from 3 years ago which is a long time in the web word nowadays. I'm using Web API 2 and ASP.NET 5 (MVC 5) and Microsoft has moved away from an IIS-only strategy, while CustomErrors is old skool IIS ;).

Anyway, I had an issue on production that I didn't have locally. And then found I couldn't see the errors in Chrome's Network tab like I could on my dev machine. In the end I managed to solve it by installing Chrome on my production server and then browsing to the app there on the server itself (e.g. on 'localhost'). Then more detailed errors appeared with stack traces and all.

Only afterwards I found this article from Jimmy Bogard (Note: Jimmy is mr. AutoMapper!). The funny thing is that his article is also from 2012, but in it he already explains that CustomErrors doesn't help for this anymore, but that you CAN change the 'Error detail' by setting a different IncludeErrorDetailPolicy in the global WebApi configuration (e.g. WebApiConfig.cs):

GlobalConfiguration.Configuration.IncludeErrorDetailPolicy 
= IncludeErrorDetailPolicy.Always;

Luckily he also explains how to set it up that webapi (2) DOES listen to your CustomErrors settings. That's a pretty sensible approach, and this allows you to go back to 2012 :P.

Note: The default value is 'LocalOnly', which explains why I was able to solve the problem the way I described, before finding this post. But I understand that not everybody can just remote to production and startup a browser (I know I mostly couldn't until I decided to go freelance AND DevOps).

How to window.scrollTo() with a smooth effect

$('html, body').animate({scrollTop:1200},'50');

You can do this!

Laravel - Eloquent or Fluent random row

I prefer to specify first or fail:

$collection = YourModelName::inRandomOrder()
  ->firstOrFail();

Programmatically create a UIView with color gradient

Since I only needed one type of gradient throughout my app I created a subclass of UIView and preconfigured the gradient layer on initialization with fixed colors. The initializers of UIView call the configureGradientLayer-method, which configures the CAGradientLayer:

DDGradientView.h:

#import <UIKit/UIKit.h>

@interface DDGradientView : UIView {

}
@end

DDGradientView.m:

#import "DDGradientView.h"

@implementation DDGradientView

// Change the views layer class to CAGradientLayer class
+ (Class)layerClass
{
    return [CAGradientLayer class];
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super initWithCoder:aDecoder];
    if(self) {
        [self configureGradientLayer];
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if(self) {
        [self configureGradientLayer];
    }
    return self;
}

// Make custom configuration of your gradient here   
- (void)configureGradientLayer {
    CAGradientLayer *gLayer = (CAGradientLayer *)self.layer;
    gLayer.colors = [NSArray arrayWithObjects:(id)[[UIColor whiteColor] CGColor], (id)[[UIColor lightGrayColor] CGColor], nil];
}
@end

Comparison of DES, Triple DES, AES, blowfish encryption for data

enter image description here

DES is the old "data encryption standard" from the seventies.

When to use IList and when to use List

You are most often better of using the most general usable type, in this case the IList or even better the IEnumerable interface, so that you can switch the implementation conveniently at a later time.

However, in .NET 2.0, there is an annoying thing - IList does not have a Sort() method. You can use a supplied adapter instead:

ArrayList.Adapter(list).Sort()

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Upgrading protobuf-gradle-plugin to version 0.8.10 solved my problem. Replace your existing protobuf with

classpath 'gradle.plugin.com.google.protobuf:protobuf-gradle-plugin:0.8.10'

Convert list of dictionaries to a pandas DataFrame

Pyhton3: Most of the solutions listed previously work. However, there are instances when row_number of the dataframe is not required and the each row (record) has to be written individually.

The following method is useful in that case.

import csv

my file= 'C:\Users\John\Desktop\export_dataframe.csv'

records_to_save = data2 #used as in the thread. 


colnames = list[records_to_save[0].keys()] 
# remember colnames is a list of all keys. All values are written corresponding
# to the keys and "None" is specified in case of missing value 

with open(myfile, 'w', newline="",encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerow(colnames)
    for d in records_to_save:
        writer.writerow([d.get(r, "None") for r in colnames])

syntax error near unexpected token `('

Since you've got both the shell that you're typing into and the shell that sudo -s runs, you need to quote or escape twice. (EDITED fixed quoting)

sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'

or

sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)

Out of curiosity, why do you need -s? Can't you just do this:

sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)

Default fetch type for one-to-one, many-to-one and one-to-many in Hibernate

To answer your question, Hibernate is an implementation of the JPA standard. Hibernate has its own quirks of operation, but as per the Hibernate docs

By default, Hibernate uses lazy select fetching for collections and lazy proxy fetching for single-valued associations. These defaults make sense for most associations in the majority of applications.

So Hibernate will always load any object using a lazy fetching strategy, no matter what type of relationship you have declared. It will use a lazy proxy (which should be uninitialized but not null) for a single object in a one-to-one or many-to-one relationship, and a null collection that it will hydrate with values when you attempt to access it.

It should be understood that Hibernate will only attempt to fill these objects with values when you attempt to access the object, unless you specify fetchType.EAGER.

How to group subarrays by a column value?

In a more functional programming style, you could use array_reduce

$groupedById = array_reduce($data, function (array $accumulator, array $element) {
  $accumulator[$element['id']][] = $element;

  return $accumulator;
}, []);

How do I activate a Spring Boot profile when running from IntelliJ?

Replace your profile name with BE

You can try the above way to activate a profile

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

Compiling/Executing a C# Source File in Command Prompt

Here is how to install MSBuild with standalone C# 7.0 compiler which is no longer bundled in the latest .Net Framework 4.7:

Is it possible to install a C# compiler without Visual Studio?

Then just run

"C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\MSBuild\15.0\Bin\Roslyn\csc.exe" MyApplication.cs

to compile single source file to executable.

Also note that .Net Core doesn't support compiling single source file without preconfigured project.

Java GC (Allocation Failure)

"Allocation Failure" is a cause of GC cycle to kick in.

"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.

Older JVM were not printing GC cause for minor GC cycles.

"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark is enabled).

Fitting polynomial model to data in R

Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:

polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)

Notes

  • The validity of this approach will depend on your objectives, the assumptions of optimize() and AIC() and if AIC is the criterion that you want to use,

  • polyfit() may not have a single minimum. check this with something like:

    for (i in 2:length(x)-1) print(polyfit(i))
    
  • I used the as.integer() function because it is not clear to me how I would interpret a non-integer polynomial.

  • for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here

Update

Also see the stepAIC function (in the MASS package) to automate model selection.

format a number with commas and decimals in C# (asp.net MVC3)

Your question is not very clear but this should achieve what you are trying to do:

decimal numericValue = 3494309432324.00m;
string formatted = numericValue.ToString("#,##0.00");

Then formatted will contain: 3,494,309,432,324.00

Why is the jquery script not working?

This works fine. just insert your jquery code in document.ready function.

 $(document).ready(function(e) {   
    // your code here
 });

example:

jquery

    $(document).ready(function(e) {   

      $('[id^=\"btnRight\"]').click(function (e) {    
        $(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');    
      });

      $('[id^=\"btnLeft\"]').click(function (e) {
        $(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
      });

    });

html

    <div>
        <select id='canselect_code' name='canselect_code' multiple class='fl'>
            <option value='1'>toto</option>
            <option value='2'>titi</option>
        </select>
        <input type='button' id='btnRight_code' value='  >  ' />
        <br>
        <input type='button' id='btnLeft_code' value='  <  ' />
        <select id='isselect_code' name='isselect_code' multiple class='fr'>
            <option value='3'>tata</option>
            <option value='4'>tutu</option>
        </select>
    </div>

How to use JavaScript source maps (.map files)?

Just to add to how to use map files. I use chrome for ubuntu and if I go to sources and click on a file, if there is a map file a message comes up telling me that I can view the original file and how to do it.

For the Angular files that I worked with today I click

Ctrl-P and a list of original files comes up in a small window.

I can then browse through the list to view the file that I would like to inspect and check where the issue might be.

What are the differences between git remote prune, git prune, git fetch --prune, etc

git remote prune and git fetch --prune do the same thing: deleting the refs to the branches that don't exist on the remote, as you said. The second command connects to the remote and fetches its current branches before pruning.

However it doesn't touch the local branches you have checked out, that you can simply delete with

git branch -d  random_branch_I_want_deleted

Replace -d by -D if the branch is not merged elsewhere

git prune does something different, it purges unreachable objects, those commits that aren't reachable in any branch or tag, and thus not needed anymore.

Circular gradient in android

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:padding="10dp"
    android:shape="rectangle">

    <gradient
        android:endColor="@color/color1"
        android:gradientRadius="250dp"
        android:startColor="#8F15DA"
        android:type="radial" />

    <corners
        android:bottomLeftRadius="50dp"
        android:bottomRightRadius="50dp"
        android:radius="3dp"
        android:topLeftRadius="0dp"
        android:topRightRadius="50dp" />
</shape>

How to run Node.js as a background process and never die?

Try this for a simple solution

cmd & exit

Add error bars to show standard deviation on a plot in R

You can use arrows:

arrows(x,y-sd,x,y+sd, code=3, length=0.02, angle = 90)

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

Responsive css styles on mobile devices ONLY

Why not use a media query range.

I'm currently working on a responsive layout for my employer and the ranges I'm using are as follows:

You have your main desktop styles in the body of the CSS file (1024px and above) and then for specific screen sizes I'm using:

@media all and (min-width:960px) and (max-width: 1024px) {
  /* put your css styles in here */
}

@media all and (min-width:801px) and (max-width: 959px) {
  /* put your css styles in here */
}

@media all and (min-width:769px) and (max-width: 800px) {
  /* put your css styles in here */
}

@media all and (min-width:569px) and (max-width: 768px) {
  /* put your css styles in here */
}

@media all and (min-width:481px) and (max-width: 568px) {
  /* put your css styles in here */
}

@media all and (min-width:321px) and (max-width: 480px) {
  /* put your css styles in here */
}

@media all and (min-width:0px) and (max-width: 320px) {
  /* put your css styles in here */
}

This will cover pretty much all devices being used - I would concentrate on getting the styling correct for the sizes at the end of the range (i.e. 320, 480, 568, 768, 800, 1024) as for all the others they will just be responsive to the size available.

Also, don't use px anywhere - use em's or %.

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

You need to specify all of the columns that you're not using for an aggregation function in your GROUP BY clause like this:

select libelle,credit_initial,disponible_v,sum(montant) as montant 
FROM fiche,annee,type where type.id_type=annee.id_type and annee.id_annee=fiche.id_annee 
and annee = year(current_timestamp) GROUP BY libelle,credit_initial,disponible_v order by libelle asc

The full_group_by mode basically makes you write more idiomatic SQL. You can turn off this setting if you'd like. There are different ways to do this that are outlined in the MySQL Documentation. Here's MySQL's definition of what I said above:

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)

You're getting the error because you're on a version < 5.7.5

Creating a SearchView that looks like the material design guidelines

It is actually quite easy to do this, if you are using android.support.v7 library.

Step - 1

Declare a menu item

<item android:id="@+id/action_search"
    android:title="Search"
    android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" />

Step - 2

Extend AppCompatActivity and in the onCreateOptionsMenu setup the SearchView.

import android.support.v7.widget.SearchView;

...

public class YourActivity extends AppCompatActivity {

    ...

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        // Retrieve the SearchView and plug it into SearchManager
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    ... 

}

Result

enter image description here

enter image description here

Best way to make WPF ListView/GridView sort on column-header clicking?

Solution that summarizes all working parts of existing answers and comments including column header templates:

View:

<ListView x:Class="MyNamspace.MyListView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300"
             ItemsSource="{Binding Items}"
             GridViewColumnHeader.Click="ListViewColumnHeaderClick">
    <ListView.Resources>

        <Style TargetType="Grid" x:Key="HeaderGridStyle">
            <Setter Property="Height" Value="20" />
        </Style>

        <Style TargetType="TextBlock" x:Key="HeaderTextBlockStyle">
            <Setter Property="Margin" Value="5,0,0,0" />
            <Setter Property="VerticalAlignment" Value="Center" />
        </Style>

        <Style TargetType="Path" x:Key="HeaderPathStyle">
            <Setter Property="StrokeThickness" Value="1" />
            <Setter Property="Fill" Value="Gray" />
            <Setter Property="Width" Value="20" />
            <Setter Property="HorizontalAlignment" Value="Center" />
            <Setter Property="Margin" Value="5,0,5,0" />
            <Setter Property="SnapsToDevicePixels" Value="True" />
        </Style>

        <DataTemplate x:Key="HeaderTemplateDefault">
            <Grid Style="{StaticResource HeaderGridStyle}">
                <TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
            </Grid>
        </DataTemplate>

        <DataTemplate x:Key="HeaderTemplateArrowUp">
            <Grid Style="{StaticResource HeaderGridStyle}">
                <Path Data="M 7,3 L 13,3 L 10,0 L 7,3" Style="{StaticResource HeaderPathStyle}" />
                <TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
            </Grid>
        </DataTemplate>

        <DataTemplate x:Key="HeaderTemplateArrowDown">
            <Grid Style="{StaticResource HeaderGridStyle}">
                <Path Data="M 7,0 L 10,3 L 13,0 L 7,0"  Style="{StaticResource HeaderPathStyle}" />
                <TextBlock Text="{Binding }" Style="{StaticResource HeaderTextBlockStyle}" />
            </Grid>
        </DataTemplate>

    </ListView.Resources>

    <ListView.View>
        <GridView ColumnHeaderTemplate="{StaticResource HeaderTemplateDefault}">

            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding NameProperty}" />
            <GridViewColumn Header="Type" Width="45" DisplayMemberBinding="{Binding TypeProperty}"/>

            <!-- ... -->

        </GridView>
    </ListView.View>
</ListView>

Code Behinde:

public partial class MyListView : ListView
{
    GridViewColumnHeader _lastHeaderClicked = null;

    public MyListView()
    {
        InitializeComponent();
    }

    private void ListViewColumnHeaderClick(object sender, RoutedEventArgs e)
    {
        GridViewColumnHeader headerClicked = e.OriginalSource as GridViewColumnHeader;

        if (headerClicked == null)
            return;

        if (headerClicked.Role == GridViewColumnHeaderRole.Padding)
            return;

        var sortingColumn = (headerClicked.Column.DisplayMemberBinding as Binding)?.Path?.Path;
        if (sortingColumn == null)
            return;

        var direction = ApplySort(Items, sortingColumn);

        if (direction == ListSortDirection.Ascending)
        {
            headerClicked.Column.HeaderTemplate =
                Resources["HeaderTemplateArrowUp"] as DataTemplate;
        }
        else
        {
            headerClicked.Column.HeaderTemplate =
                Resources["HeaderTemplateArrowDown"] as DataTemplate;
        }

        // Remove arrow from previously sorted header
        if (_lastHeaderClicked != null && _lastHeaderClicked != headerClicked)
        {
            _lastHeaderClicked.Column.HeaderTemplate =
                Resources["HeaderTemplateDefault"] as DataTemplate;
        }

        _lastHeaderClicked = headerClicked;
    }


    public static ListSortDirection ApplySort(ICollectionView view, string propertyName)
    {
        ListSortDirection direction = ListSortDirection.Ascending;
        if (view.SortDescriptions.Count > 0)
        {
            SortDescription currentSort = view.SortDescriptions[0];
            if (currentSort.PropertyName == propertyName)
            {
                if (currentSort.Direction == ListSortDirection.Ascending)
                    direction = ListSortDirection.Descending;
                else
                    direction = ListSortDirection.Ascending;
            }
            view.SortDescriptions.Clear();
        }
        if (!string.IsNullOrEmpty(propertyName))
        {
            view.SortDescriptions.Add(new SortDescription(propertyName, direction));
        }
        return direction;
    }
}

How to pass object from one component to another in Angular 2?

you could also store your data in an service with an setter and get it over a getter

import { Injectable } from '@angular/core';

@Injectable()
export class StorageService {

    public scope: Array<any> | boolean = false;

    constructor() {
    }

    public getScope(): Array<any> | boolean {
        return this.scope;
    }

    public setScope(scope: any): void {
        this.scope = scope;
    }
}

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Forget trying to decipher the example .ts - as others have said it is often incomplete.

Instead just click on the 'pop-out' icon circled here and you'll get a fully working StackBlitz example.

enter image description here

You can quickly confirm the required modules:

enter image description here

Comment out any instances of ReactiveFormsModule, and sure enough you'll get the error:

Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. 

numpy.where() detailed, step-by-step explanation / examples

Here is a little more fun. I've found that very often NumPy does exactly what I wish it would do - sometimes it's faster for me to just try things than it is to read the docs. Actually a mixture of both is best.

I think your answer is fine (and it's OK to accept it if you like). This is just "extra".

import numpy as np

a = np.arange(4,10).reshape(2,3)

wh = np.where(a>7)
gt = a>7
x  = np.where(gt)

print "wh: ", wh
print "gt: ", gt
print "x:  ", x

gives:

wh:  (array([1, 1]), array([1, 2]))
gt:  [[False False False]
      [False  True  True]]
x:   (array([1, 1]), array([1, 2]))

... but:

print "a[wh]: ", a[wh]
print "a[gt]  ", a[gt]
print "a[x]:  ", a[x]

gives:

a[wh]:  [8 9]
a[gt]   [8 9]
a[x]:   [8 9]

How do I UPDATE from a SELECT in SQL Server?

Use:

drop table uno
drop table dos

create table uno
(
    uid int,
    col1 char(1),
    col2 char(2)
)
create table dos
(
    did int,
    col1 char(1),
    col2 char(2),
    [sql] char(4)
)
insert into uno(uid) values (1)
insert into uno(uid) values (2)
insert into dos values (1,'a','b',null)
insert into dos values (2,'c','d','cool')

select * from uno 
select * from dos

EITHER:

update uno set col1 = (select col1 from dos where uid = did and [sql]='cool'), 
col2 = (select col2 from dos where uid = did and [sql]='cool')

OR:

update uno set col1=d.col1,col2=d.col2 from uno 
inner join dos d on uid=did where [sql]='cool'

select * from uno 
select * from dos

If the ID column name is the same in both tables then just put the table name before the table to be updated and use an alias for the selected table, i.e.:

update uno set col1 = (select col1 from dos d where uno.[id] = d.[id] and [sql]='cool'),
col2  = (select col2 from dos d where uno.[id] = d.[id] and [sql]='cool')

Completely Remove MySQL Ubuntu 14.04 LTS

I experienced a similar issue on Ubuntu 14.04 LTS after a MySQL update.

I started getting error: "Fatal error: Can't open and lock privilege tables: Incorrect file format 'user'" in /var/log/mysql/error.log

MySQL could not start.

I resolved it by removing the following directory: /var/lib/mysql/mysql

sudo rm -rf /var/lib/mysql/mysql

This leaves your other DB related files in place, only removing the mysql related files.

After running these:

sudo apt-get remove --purge mysql-server mysql-client mysql-common
sudo apt-get autoremove
sudo apt-get autoclean

Then reinstalling mysql:

sudo apt-get install mysql-server

It worked perfectly.

Serving favicon.ico in ASP.NET MVC

All you need to do is to add app.UseStaticFiles(); in your startup.cs -> public void Configure(IApplicationBuilder app, IHostingEnvironment env).

ASP.net core provides an excellent way to get static files. That is using the wwwroot folder. Please read Static files in ASP.NET Core.

Using the <Link /> is not a very good idea. Why would someone add the link tag on each HTML or cshtml for the favicon.ico?

Delegates in swift?

The solutions above seemed a little coupled and at the same time avoid reuse the same protocol in other controllers, that's why I've come with the solution that is more strong typed using generic type-erasure.

@noreturn public func notImplemented(){
    fatalError("not implemented yet")
}


public protocol DataChangedProtocol: class{
    typealias DataType

    func onChange(t:DataType)
}

class AbstractDataChangedWrapper<DataType> : DataChangedProtocol{

    func onChange(t: DataType) {
        notImplemented()
    }
}


class AnyDataChangedWrapper<T: DataChangedProtocol> : AbstractDataChangedWrapper<T.DataType>{

    var base: T

    init(_ base: T ){
        self.base = base
    }

    override func onChange(t: T.DataType) {
        base.onChange(t)
    }
}


class AnyDataChangedProtocol<DataType> : DataChangedProtocol{

    var base: AbstractDataChangedWrapper<DataType>

    init<S: DataChangedProtocol where S.DataType == DataType>(_ s: S){
        self.base = AnyDataChangedWrapper(s)
    }

    func onChange(t: DataType) {
        base.onChange(t)
    }
}



class Source : DataChangedProtocol {
    func onChange(data: String) {
        print( "got new value \(data)" )
    }
}


class Target {
    var delegate: AnyDataChangedProtocol<String>?

    func reportChange(data:String ){
        delegate?.onChange(data)
    }
}


var source = Source()
var target = Target()

target.delegate = AnyDataChangedProtocol(source)
target.reportChange("newValue")    

output: got new value newValue

Convert a string into an int

Yet another way: if you are working with a C string, e.g. const char *, C native atoi() is more convenient.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

Boolean.parseBoolean("1") = false...?

Thomas, I think your wrapper code, or just the condition itself, is the cleanest way to do what you want to do in java, which is convert "1" to the Boolean True value. Actually, comparing to "0" and taking the inverse would match the C behavior of treating 0 as false and everything else as true.

Boolean intStringToBoolean(numericBooleanValueString) {
  return !"0".equals(numericBooleanValueString);
}

Replacing spaces with underscores in JavaScript?

Try .replace(/ /g,"_");

Edit: or .split(' ').join('_') if you have an aversion to REs

Edit: John Resig said:

If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers. (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)

Self Join to get employee manager name

create view as 
(select 
e1.empno as PersonID,
e1.ename as PersonName,
e2.empno MANAGER_ID,
e2.ename MANAGER_NAME 
from 
employees e1 , employees e2 
where 
e2.empno=e1.mgr)

Can I use a :before or :after pseudo-element on an input field?

:before and :after are applied inside a container, which means you can use it for elements with an end tag.

It doesn't apply for self-closing elements.

On a side note, elements which are self-closing (such as img/hr/input) are also known as 'Replaced Elements', as they are replaced with their respective content. "External Objects" for the lack of a better term. A better read here

javascript compare strings without being case sensitive

You can make both arguments lower case, and that way you will always end up with a case insensitive search.

var string1 = "aBc";
var string2 = "AbC";

if (string1.toLowerCase() === string2.toLowerCase())
{
    #stuff
}

How to set Sqlite3 to be case insensitive when string comparing?

you can use the like query for comparing the respective string with table vales.

select column name from table_name where column name like 'respective comparing value';

How do I change the font size of a UILabel in Swift?

If you want just change size of your font i create this extension

// Add extension

extension UILabel {
    func setSizeFont (sizeFont: Double) {
        self.font =  UIFont(name: self.font.fontName, size: sizeFont)!
        self.sizeToFit()
    }
}

// Use

myLabel.setSizeFont(60)

How can I auto hide alert box after it showing it?

You can't close an alert box with Javascript.

You could, however, use a window instead:

var w = window.open('','','width=100,height=100')
w.document.write('Message')
w.focus()
setTimeout(function() {w.close();}, 5000)

Using Mysql in the command line in osx - command not found?

You can just modified the .bash_profile by adding the MySQL $PATH as the following:
export PATH=$PATH:/usr/local/mysql/bin.

I did the following:

1- Open Terminal then $ nano .bash_profile or $ vim .bash_profile

2- Add the following PATH code to the .bash_profile

# Set architecture flags
export ARCHFLAGS="-arch x86_64"
# Ensure user-installed binaries take precedence
export PATH=/usr/local/mysql/bin:$PATH
# Load .bashrc if it exists
test -f ~/.bashrc && source ~/.bashrc 

3- Save the file.

4- Refresh Terminal using $ source ~/.bash_profile

5- To verify, type in Terminal $ mysql --version

6- It should print the output something like this:

$ mysql Ver 14.14 Distrib 5.7.17, for macos10.12 (x86_64)

The Terminal is now configured to read the MySQL commands from $PATH which is placed in the .bash_profile .

How to disassemble a memory range with GDB?

You don't have to use gdb. GCC will do it.

 gcc -S foo.c

This will create foo.s which is the assembly.

gcc -m32 -c -g -Wa,-a,-ad foo.c > foo.lst

The above version will create a listing file that has both the C and the assembly generated by it. GCC FAQ

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!

How can I add the sqlite3 module to Python?

I have python 2.7.3 and this solved my problem:

pip install pysqlite

Get timezone from DateTime

No.

A developer is responsible for keeping track of time-zone information associated with a DateTime value via some external mechanism.

A quote from an excellent article here. A must read for every .Net developer.

So my advice is to write a little wrapper class that suits your needs.

Read and write a text file in typescript

First you will need to install node definitions for Typescript. You can find the definitions file here:

https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/node/node.d.ts

Once you've got file, just add the reference to your .ts file like this:

/// <reference path="path/to/node.d.ts" />

Then you can code your typescript class that read/writes, using the Node File System module. Your typescript class myClass.ts can look like this:

/// <reference path="path/to/node.d.ts" />

class MyClass {

    // Here we import the File System module of node
    private fs = require('fs');

    constructor() { }

    createFile() {

        this.fs.writeFile('file.txt', 'I am cool!',  function(err) {
            if (err) {
                return console.error(err);
            }
            console.log("File created!");
        });
    }

    showFile() {

        this.fs.readFile('file.txt', function (err, data) {
            if (err) {
                return console.error(err);
            }
            console.log("Asynchronous read: " + data.toString());
        });
    }
}

// Usage
// var obj = new MyClass();
// obj.createFile();
// obj.showFile();

Once you transpile your .ts file to a javascript (check out here if you don't know how to do it), you can run your javascript file with node and let the magic work:

> node myClass.js

Should I set max pool size in database connection string? What happens if I don't?

Currently your application support 100 connections in pool. Here is what conn string will look like if you want to increase it to 200:

public static string srConnectionString = 
                "server=localhost;database=mydb;uid=sa;pwd=mypw;Max Pool Size=200;";

You can investigate how many connections with database your application use, by executing sp_who procedure in your database. In most cases default connection pool size will be enough.

Set language for syntax highlighting in Visual Studio Code

Note that for "Untitled" editor ("Untitled-1", "Untitled-2"), you now can set the language in the settings.

The previous setting was:

"files.associations": {
        "untitled-*": "javascript"
 }

This will not always work anymore, because with VSCode 1.42 (Q1 2020) will change the title of those untitled editors.
The title will now be the first line of the document for the editor title, along the generic name as part of the description.
It won't start anymore with "untitled-"

See "Untitled editor improvements"

Regarding the associated language for those "Untitled" editors:

By default, untitled files do not have a specific language mode configured.

VS Code has a setting, files.defaultLanguage, to configure a default language for untitled files.

With this release, the setting can take a new value {activeEditorLanguage} that will dynamically use the language mode of the currently active editor instead of a fixed default.

In addition, when you copy and paste text into an untitled editor, VS Code will now automatically change the language mode of the untitled editor if the text was copied from a VS Code editor:

https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_42/untitled-copy2.gif

And see workbench.editor.untitled.labelFormat in VSCode 1.43.

What is the iPhone 4 user-agent?

iOS 4.3.2's User Agent, which came out this week, is:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5

Delete item from array and shrink array

Arrays are fixed in size, you cannot resize them after creating them. You can remove an existing item by setting it to null:

objects[4] = null;

But you won't be able to delete that entire slot off the array and reduce its size by 1.

If you need a dynamically-sized array, you can use an ArrayList. With it, you can add() and remove() objects, and it will grow and shrink as needed.

How to send email to multiple recipients with addresses stored in Excel?

You have to loop through every cell in the range "D3:D6" and construct your To string. Simply assigning it to a variant will not solve the purpose. EmailTo becomes an array if you assign the range directly to it. You can do this as well but then you will have to loop through the array to create your To string

Is this what you are trying? (TRIED AND TESTED)

Option Explicit

Sub Mail_workbook_Outlook_1()
     'Working in 2000-2010
     'This example send the last saved version of the Activeworkbook
    Dim OutApp As Object
    Dim OutMail As Object
    Dim emailRng As Range, cl As Range
    Dim sTo As String

    Set emailRng = Worksheets("Selections").Range("D3:D6")

    For Each cl In emailRng 
        sTo = sTo & ";" & cl.Value
    Next

    sTo = Mid(sTo, 2)

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    On Error Resume Next
    With OutMail
        .To = sTo
        .CC = "[email protected];[email protected]"
        .BCC = ""
        .Subject = "RMA #" & Worksheets("RMA").Range("E1")
        .Body = "Attached to this email is RMA #" & _
        Worksheets("RMA").Range("E1") & _
        ". Please follow the instructions for your department included in this form."
        .Attachments.Add ActiveWorkbook.FullName
         'You can add other files also like this
         '.Attachments.Add ("C:\test.txt")

        .Display
    End With
    On Error GoTo 0

    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

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

1· Do I need these DLL's?

It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.

  1. Where can I get them?

most dlls can be found at https://www.dll-files.com

I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll

For me leshims.dll can be placed at C:\Windows\System32\. Context: windows 7 64bit.

flow 2 columns of text automatically with CSS

Use CSS3

.container {
   -webkit-column-count: 2;
      -moz-column-count: 2;
           column-count: 2;

   -webkit-column-gap: 20px;
      -moz-column-gap: 20px;
           column-gap: 20px;
}

Browser Support

  • Chrome 4.0+ (-webkit-)
  • IE 10.0+
  • Firefox 2.0+ (-moz-)
  • Safari 3.1+ (-webkit-)
  • Opera 15.0+ (-webkit-)

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

Business logic in MVC

Fist of all:
I believe that you are mixing up the MVC pattern and n-tier-based design principles.

Using an MVC approach does not mean that you shouldn't layer your application.
It might help if you see MVC more like an extension of the presentation layer.

If you put non-presentation code inside the MVC pattern you might very soon end up in a complicated design.
Therefore I would suggest that you put your business logic into a separate business layer.

Just have a look at this: Wikipedia article about multitier architecture

It says:

Today, MVC and similar model-view-presenter (MVP) are Separation of Concerns design patterns that apply exclusively to the presentation layer of a larger system.

Anyway ... when talking about an enterprise web application the calls from the UI to the business logic layer should be placed inside the (presentation) controller.

That is because the controller actually handles the calls to a specific resource, queries the data by making calls to the business logic and links the data (model) to the appropriate view.

Mud told you that the business rules go into the model.
That is also true, but he mixed up the (presentation) model (the 'M' in MVC) and the data layer model of a tier-based application design.
So it is valid to place your database related business rules in the model (data layer) of your application.
But you should not place them in the model of your MVC-structured presentation layer as this only applies to a specific UI.

This technique is independent of whether you use a domain driven design or a transaction script based approach.

Let me visualize that for you:


Presentation layer: Model - View - Controller


Business layer: Domain logic - Application logic


Data layer: Data repositories - Data access layer


The model that you see above means that you have an application that uses MVC, DDD and a database-independed data layer.
This is a common approach to design a larger enterprise web application.

But you can also shrink it down to use a simple non-DDD business layer (a business layer without domain logic) and a simple data layer that writes directly to a specific database.
You could even drop the whole data-layer and access the database directly from the business layer, though I do not recommend it.

Thats' the trick...I hope this helps...

[Note:] You should also be aware of the fact that nowadays there is more than just one "model" in an application. Commonly, each layer of an application has it's own model. The model of the presentation layer is view specific but often independent of the used controls. The business layer can also have a model, called the "domain-model". This is typically the case when you decide to take a domain-driven approach. This "domain-model" contains of data as well as business logic (the main logic of your program) and is usually independent of the presentation layer. The presentation layer usually calls the business layer on a certain "event" (button pressed etc.) to read data from or write data to the data layer. The data layer might also have it's own model, which is typically database related. It often contains a set of entity classes as well as data-access-objects (DAOs).

The question is: how does this fit into the MVC concept?

Answer -> It doesn't!
Well - it kinda does, but not completely.
This is because MVC is an approach that was developed in the late 1970's for the Smalltalk-80 programming language. At that time GUIs and personal computers were quite uncommon and the world wide web was not even invented! Most of today's programming languages and IDEs were developed in the 1990s. At that time computers and user interfaces were completely different from those in the 1970s.
You should keep that in mind when you talk about MVC.
Martin Fowler has written a very good article about MVC, MVP and today's GUIs.