Programs & Examples On #Business intelligence

Business intelligence(BI) refers to the process of analyzing an organization's business data, by various (often computer-aided) means, to assist in the organization's decision making. BI technologies are capable of handling large amount of unstructured data to help identify, develop and create strategic opportunities.

Installation of SQL Server Business Intelligence Development Studio

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

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

Difference between Fact table and Dimension table?

This is to answer the part:

I was trying to understand whether dimension tables can be fact table as well or not?

The short answer (INMO) is No.That is because the 2 types of tables are created for different reasons. However, from a database design perspective, a dimension table could have a parent table as the case with the fact table which always has a dimension table (or more) as a parent. Also, fact tables may be aggregated, whereas Dimension tables are not aggregated. Another reason is that fact tables are not supposed to be updated in place whereas Dimension tables could be updated in place in some cases.

More details:

Fact and dimension tables appear in a what is commonly known as a Star Schema. A primary purpose of star schema is to simplify a complex normalized set of tables and consolidate data (possibly from different systems) into one database structure that can be queried in a very efficient way.

On its simplest form, it contains a fact table (Example: StoreSales) and a one or more dimension tables. Each Dimension entry has 0,1 or more fact tables associated with it (Example of dimension tables: Geography, Item, Supplier, Customer, Time, etc.). It would be valid also for the dimension to have a parent, in which case the model is of type "Snow Flake". However, designers attempt to avoid this kind of design since it causes more joins that slow performance. In the example of StoreSales, The Geography dimension could be composed of the columns (GeoID, ContenentName, CountryName, StateProvName, CityName, StartDate, EndDate)

In a Snow Flakes model, you could have 2 normalized tables for Geo information, namely: Content Table, Country Table.

You can find plenty of examples on Star Schema. Also, check this out to see an alternative view on the star schema model Inmon vs. Kimball. Kimbal has a good forum you may also want to check out here: Kimball Forum.

Edit: To answer comment about examples for 4NF:

  • Example for a fact table violating 4NF:

Sales Fact (ID, BranchID, SalesPersonID, ItemID, Amount, TimeID)

  • Example for a fact table not violating 4NF:

AggregatedSales (BranchID, TotalAmount)

Here the relation is in 4NF

The last example is rather uncommon.

How to change pivot table data source in Excel?

In case of Excel 2007 You can change datasource in Options menu /Change Data Source

Output first 100 characters in a string

Most of previous examples will raise an exception in case your string is not long enough.

Another approach is to use 'yourstring'.ljust(100)[:100].strip().

This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

I want to add to the answers posted on above that none of the solutions proposed here worked for me. My WAMP, is working on port 3308 instead of 3306 which is what it is installed by default. I found out that when working in a local environment, if you are using mysqladmin in your computer (for testing environment), and if you are working with port other than 3306, you must define your variable DB_SERVER with the value localhost:NumberOfThePort, so it will look like the following: define("DB_SERVER", "localhost:3308"). You can obtain this value by right-clicking on the WAMP icon in your taskbar (on the hidden icons section) and select Tools. You will see the section: "Port used by MySQL: NumberOfThePort"

This will fix your connection to your database.

This was the error I got: Error: SQLSTATE[HY1045] Access denied for user 'username'@'localhost' on line X.

I hope this helps you out.

:)

onNewIntent() lifecycle and registered listeners

onNewIntent() is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate(). From activities lifecycle point of view it's therefore needed to call onPause() before onNewIntent(). I suggest you to rewrite your activity to not use these listeners inside of onNewIntent(). For example most of the time my onNewIntent() methods simply looks like this:

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    // getIntent() should always return the most recent
    setIntent(intent);
}

With all setup logic happening in onResume() by utilizing getIntent().

How to initialize a List<T> to a given size (as opposed to capacity)?

You seem to be emphasizing the need for a positional association with your data, so wouldn't an associative array be more fitting?

Dictionary<int, string> foo = new Dictionary<int, string>();
foo[2] = "string";

Check/Uncheck checkbox with JavaScript

I would like to note, that setting the 'checked' attribute to a non-empty string leads to a checked box.

So if you set the 'checked' attribute to "false", the checkbox will be checked. I had to set the value to the empty string, null or the boolean value false in order to make sure the checkbox was not checked.

Where is body in a nodejs http.get response?

The body is not fully stored as part of the response, the reason for this is because the body can contain a very large amount of data, if it was to be stored on the response object, the program's memory would be consumed quite fast.

Instead, Node.js uses a mechanism called Stream. This mechanism allows holding only a small part of the data and allows the programmer to decide if to fully consume it in memory or use each part of the data as its flowing.

There are multiple ways how to fully consume the data into memory, since HTTP Response is a readable stream, all readable methods are available on the res object

  1. listening to the "data" event and saving the chunks passed to the callback

    const chunks = []
    
    res.on("data", (chunk) => {
        chunks.push(chunk)
    });
    
    res.on("end", () => {
        const body = Buffer.concat(chunks);
    });
    

When using this approach you do not interfere with the behavior of the stream and you are only gathering the data as it is available to the application.

  1. using the "readble" event and calling res.read()

    const chunks = [];
    
    res.on("readable", () => {
       let chunk;
       while(null !== (chunk = res.read())){
           chunks.push(chunk)
       }
    });
    
    res.on("end", () => {
        const body = Buffer.concat(chunks);
    });
    

When going with this approach you are fully in charge of the stream flow and until res.read is called no more data will be passed into the stream.

  1. using an async iterator

    const chunks = [];
    
    for await (const chunk of readable) {
        chunks.push(chunk);
    } 
    
    const body = Buffer.concat(chunks);
    

This approach is similar to the "data" event approach. It will just simplify the scoping and allow the entire process to happen in the same scope.

While as described, it is possible to fully consume data from the response it is always important to keep in mind if it is actually necessary to do so. In many cases, it is possible to simply direct the data to its destination without fully saving it into memory.

Node.js read streams, including HTTP response, have a built-in method for doing this, this method is called pipe. The usage is quite simple, readStream.pipe(writeStream);.

for example:

If the final destination of your data is the file system, you can simply open a write stream to the file system and then pipe the data to ts destination.

const { createWriteStream } = require("fs");
const writeStream = createWriteStream("someFile");
res.pipe(writeStream);

How can I count the occurrences of a list item?

if you want a number of occurrences for the particular element:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> single_occurrences = Counter(z)
>>> print(single_occurrences.get("blue"))
3
>>> print(single_occurrences.values())
dict_values([3, 2, 1])

CSS: How to position two elements on top of each other, without specifying a height?

After much testing, I have verified that the original question is already right; missing just a couple of settings:

  • the container_row MUST have position: relative;
  • the children (...), MUST have position: absolute; left:0;
  • to make sure the children (...) align exactly over each other, the container_row should have additional styling:
    • height:x; line-height:x; vertical-align:middle;
    • text-align:center; could, also, help.

The project description file (.project) for my project is missing

If you only want to checkout and you delete the folder from the workspace you also need to delete the reference to it in the Java view. Then it should checkout as if it were checking out for the first time.

What is the cleanest way to ssh and run multiple commands in Bash?

For simple commands you can use:

ssh <ssh_args> command1 '&&' command2

or

ssh <ssh_args> command1 \&\& command2

Difference between spring @Controller and @RestController annotation

In the code below I'll show you the difference between @controller

@Controller
public class RestClassName{

  @RequestMapping(value={"/uri"})
  @ResponseBody
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}

and @RestController

@RestController
public class RestClassName{

  @RequestMapping(value={"/uri"})
  public ObjectResponse functionRestName(){
      //...
      return instance
   }
}

the @ResponseBody is activated by default. You don't need to add it above the function signature.

Find distance between two points on map using Google Map API V2

Coming rather late, but seeing that this is one of the top results on Google search for the topic I'll share another way:

Use a one-liner with Googles utility class SphericalUtil

SphericalUtil.computeDistanceBetween(latLngFrom, latLngTo)

You will need the utility classes.

You can simply include them in your project using gradle:

implementation 'com.google.maps.android:android-maps-utils:0.5+'

How to get the list of all database users

EXEC sp_helpuser

or

SELECT * FROM sysusers

Both of these select all the users of the current database (not the server).

.htaccess rewrite subdomain to directory

Redirect subdomain directory:

RewriteCond %{HTTP_HOST} ^([^.]+)\.(archive\.example\.com)$ [NC]
RewriteRule ^ http://%2/%1%{REQUEST_URI} [L,R=301]

did you register the component correctly? For recursive components, make sure to provide the "name" option

The high votes answer is right. You can checkout that you have applied different name for the components. But if the question is still not resolved, you can make sure that you have register the component only once.

_x000D_
_x000D_
components: {_x000D_
    IMContainer,_x000D_
    RightPanel_x000D_
},_x000D_
methods: {},_x000D_
components: {_x000D_
    IMContainer,_x000D_
    RightPanel_x000D_
}_x000D_
  
_x000D_
_x000D_
_x000D_

we always forget that we have register the component before

How to call another components function in angular2

It depends on the relation between your components (parent / child) but the best / generic way to make communicate components is to use a shared service.

See this doc for more details:

That being said, you could use the following to provide an instance of the com1 into com2:

<div>
  <com1 #com1>...</com1>
  <com2 [com1ref]="com1">...</com2>
</div>

In com2, you can use the following:

@Component({
  selector:'com2'
})
export class com2{
  @Input()
  com1ref:com1;

  function2(){
    // i want to call function 1 from com1 here
    this.com1ref.function1();
  }
}

Excel telling me my blank cells aren't blank

Goto->Special->blanks does not like merged cells. Try unmerging cells above the range in which you want to select blanks then try again.

How to check if a query string value is present via JavaScript?

This should help:

function getQueryParams(){
    try{
        url = window.location.href;
        query_str = url.substr(url.indexOf('?')+1, url.length-1);
        r_params = query_str.split('&');
        params = {}
        for( i in r_params){
            param = r_params[i].split('=');
            params[ param[0] ] = param[1];
        }
        return params;
    }
    catch(e){
       return {};
    }
}

Is there any way to return HTML in a PHP function? (without building the return value as a string)

If you don't want to have to rely on a third party tool you can use this technique:

function TestBlockHTML($replStr){
  $template = 
   '<html>
     <body>
       <h1>$str</h1>
     </body>
   </html>';
 return strtr($template, array( '$str' => $replStr));
}

How to trigger an event in input text after I stop typing/writing?

There is some simple plugin I've made that does exacly that. It requires much less code than proposed solutions and it's very light (~0,6kb)

First you create Bid object than can be bumped anytime. Every bump will delay firing Bid callback for next given ammount of time.

var searchBid = new Bid(function(inputValue){
    //your action when user will stop writing for 200ms. 
    yourSpecialAction(inputValue);
}, 200); //we set delay time of every bump to 200ms

When Bid object is ready, we need to bump it somehow. Let's attach bumping to keyup event.

$("input").keyup(function(){
    searchBid.bump( $(this).val() ); //parameters passed to bump will be accessable in Bid callback
});

What happens here is:

Everytime user presses key, bid is 'delayed' (bumped) for next 200ms. If 200ms will pass without beeing 'bumped' again, callback will be fired.

Also, you've got 2 additional functions for stopping bid (if user pressed esc or clicked outside input for example) and for finishing and firing callback immediately (for example when user press enter key):

searchBid.stop();
searchBid.finish(valueToPass);

Select elements by attribute in CSS

You can combine multiple selectors and this is so cool knowing that you can select every attribute and attribute based on their value like href based on their values with CSS only..

Attributes selectors allows you play around some extra with id and class attributes

Here is an awesome read on Attribute Selectors

Fiddle

_x000D_
_x000D_
a[href="http://aamirshahzad.net"][title="Aamir"] {_x000D_
  color: green;_x000D_
  text-decoration: none;_x000D_
}_x000D_
_x000D_
a[id*="google"] {_x000D_
  color: red;_x000D_
}_x000D_
_x000D_
a[class*="stack"] {_x000D_
  color: yellow;_x000D_
}
_x000D_
<a href="http://aamirshahzad.net" title="Aamir">Aamir</a>_x000D_
<br>_x000D_
<a href="http://google.com" id="google-link" title="Google">Google</a>_x000D_
<br>_x000D_
<a href="http://stackoverflow.com" class="stack-link" title="stack">stack</a>
_x000D_
_x000D_
_x000D_

Browser support:
IE6+, Chrome, Firefox & Safari

You can check detail here.

How to print a double with two decimals in Android?

For Displaying digit upto two decimal places there are two possibilities - 1) Firstly, you only want to display decimal digits if it's there. For example - i) 12.10 to be displayed as 12.1, ii) 12.00 to be displayed as 12. Then use-

DecimalFormat formater = new DecimalFormat("#.##"); 

2) Secondly, you want to display decimal digits irrespective of decimal present For example -i) 12.10 to be displayed as 12.10. ii) 12 to be displayed as 12.00.Then use-

DecimalFormat formater = new DecimalFormat("0.00"); 

HTML5 Local storage vs. Session storage

Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.

//Set the value in a local storage object
localStorage.setItem('name', myName);

//Get the value from storage object
localStorage.getItem('name');

//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege

Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.

//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";

Read More Click

Appending to an empty DataFrame in Pandas?

That should work:

>>> df = pd.DataFrame()
>>> data = pd.DataFrame({"A": range(3)})
>>> df.append(data)
   A
0  0
1  1
2  2

But the append doesn't happen in-place, so you'll have to store the output if you want it:

>>> df
Empty DataFrame
Columns: []
Index: []
>>> df = df.append(data)
>>> df
   A
0  0
1  1
2  2

Passing javascript variable to html textbox

instead of

_x000D_
_x000D_
document.getElementById("txtBillingGroupName").value = groupName;
_x000D_
_x000D_
_x000D_

You can use

_x000D_
_x000D_
$("#txtBillingGroupName").val(groupName);
_x000D_
_x000D_
_x000D_

instead of groupName you can pass string value like "Group1"

How to open a link in new tab (chrome) using Selenium WebDriver?

You can open multiple browser or a window by using below code:

WebDriver driver = new ChromeDriver();
driver.get("http://yahoo.com");  

WebDriver driver1 = new ChromeDriver();
driver1.get("google.com");

WebDriver driver2 = new InternetExplorerDriver();
driver2.get("google.com/gmap");

Make $JAVA_HOME easily changable in Ubuntu

Put the environment variables into the global /etc/environment file:

...
export JAVA_HOME=/usr/lib/jvm/java-1.5.0-sun
...

Execute "source /etc/environment" in every shell where you want the variables to be updated:

$ source /etc/environment

Check that it works:

$ echo $JAVA_HOME
$ /usr/lib/jvm/java-1.5.0-sun

Great, no logout needed.

If you want to set JAVA_HOME environment variable in only the terminal, set it in ~/.bashrc file.

Using "like" wildcard in prepared statement

PreparedStatement ps = cn.prepareStatement("Select * from Users where User_FirstName LIKE ?");
ps.setString(1, name + '%');

Try this out.

check for null date in CASE statement, where have I gone wrong?

Try:

select
     id,
     StartDate,
CASE WHEN StartDate IS NULL
    THEN 'Awaiting'
    ELSE 'Approved' END AS StartDateStatus
FROM myTable

You code would have been doing a When StartDate = NULL, I think.


NULL is never equal to NULL (as NULL is the absence of a value). NULL is also never not equal to NULL. The syntax noted above is ANSI SQL standard and the converse would be StartDate IS NOT NULL.

You can run the following:

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

And this returns:

EqualityCheck = 0
InEqualityCheck = 0
NullComparison = 1

For completeness, in SQL Server you can:

SET ANSI_NULLS OFF;

Which would result in your equals comparisons working differently:

SET ANSI_NULLS OFF

SELECT CASE WHEN (NULL = NULL) THEN 1 ELSE 0 END AS EqualityCheck,
CASE WHEN (NULL <> NULL) THEN 1 ELSE 0 END AS InEqualityCheck,
CASE WHEN (NULL IS NULL) THEN 1 ELSE 0 END AS NullComparison

Which returns:

EqualityCheck = 1
InEqualityCheck = 0
NullComparison = 1

But I would highly recommend against doing this. People subsequently maintaining your code might be compelled to hunt you down and hurt you...

Also, it will no longer work in upcoming versions of SQL server:

https://msdn.microsoft.com/en-GB/library/ms188048.aspx

.m2 , settings.xml in Ubuntu

Quoted from http://maven.apache.org/settings.html:

There are two locations where a settings.xml file may live:

The Maven install: $M2_HOME/conf/settings.xml

A user's install: ${user.home}/.m2/settings.xml

So, usually for a specific user you edit

/home/*username*/.m2/settings.xml

To set environment for all local users, you might think about changing the first path.

"could not find stored procedure"

Sometimes this can also happen when you have a stored procedure being called with parameters. For example, if you type something like:

set @runProc = 'dbo.StoredProcedure'
 exec @runProc

This will work, However:

set @runProc = 'dbo.StoredProcedure ''foods'''
exec @runProc

This will throw the error "could not find stored procedure dbo.StoredProcedure 'foods'", however this can easily be overcome with parantheses like so:

set @runProc = 'exec dbo.StoredProcedure ''foods'''
exec (@runProc)

fork() child and parent processes

Start by reading the fork man page as well as the getppid / getpid man pages.

From fork's

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

So this should be something down the lines of

if ((pid=fork())==0){
    printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
    printf("Dont yada yada me, im your parent with pid %u ", getpid());
}

As to your question:

This is the child process. My pid is 22163 and my parent's id is 0.

This is the child process. My pid is 22162 and my parent's id is 22163.

fork() executes before the printf. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork() will return 0 to the child process, and the pid of the child process to the parent process.

You get two running processes, each one will execute this instruction statement:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

and

printf ("... My pid is %d and my parent's id is %d",getpid(),22163);  

~

To wrap it up, the above line is the child, specifying its pid. The second line is the parent process, specifying its id (22162) and its child's (22163).

How does BitLocker affect performance?

My current work machine came with bitlocker, and being an upgrade from the prior model. It only seemed faster to me. What I have found, however, is that bitlocker is more bullet proof than truecrypt, when it comes to accurately laying down the data. I do a lot of work in SAS which constantly writes backup copies to disk as it moves along and shoots a variety of output types to disk at the end. SAS works fine writing output from multithreaded processes back to bitlocker and doesn't seem to know it's there. This has not been the case for me with truecrypt. I'm not sure what happens or how, but I found that processes got out of synch when working with source/output data in a truecrypt container, which is what I installed on my second work computer since it had no bitlocker. The constant backups were shooting to an SSD while the truecrypt results were on a regular HD. Maybe that speed difference helped trip it up. Whatever the cause, I had to quit using truecrypt on that second computer because it made my SAS results out of synch with respect to processing order and it screwed up some of my processes and data. Scary stuff in my world.

I work with people who have successfully used Truecrypt on the exact same computer, but they weren't using a disk intensive app. like SAS.

Bitlocker to Go, the encryption which bitlocker applies to thumb-drives, does slow things down quite a bit when it comes to read/write times. It's not too hard to use as long as you remember your password on the thumbdrive, and are willing to wait for it to format/initialize the drive, but in my experience it made access to the flash drive about 4 times as slow. Don't know why it would slow down a thumb drive and not a disk but that's how it was for me and my coworker.

Based on my success with bitlocker at work, I bought Windows Pro for my home computer to get bitlocker and plan to encrypt some directories with it for things like financials.

How to get the 'height' of the screen using jquery

use with responsive website (view in mobile or ipad)

jQuery(window).height();   // return height of browser viewport
jQuery(window).width();    // return width of browser viewport

rarely use

jQuery(document).height(); // return height of HTML document
jQuery(document).width();  // return width of HTML document

How to use an image for the background in tkinter?

One simple method is to use place to use an image as a background image. This is the type of thing that place is really good at doing.

For example:

background_image=tk.PhotoImage(...)
background_label = tk.Label(parent, image=background_image)
background_label.place(x=0, y=0, relwidth=1, relheight=1)

You can then grid or pack other widgets in the parent as normal. Just make sure you create the background label first so it has a lower stacking order.

Note: if you are doing this inside a function, make sure you keep a reference to the image, otherwise the image will be destroyed by the garbage collector when the function returns. A common technique is to add a reference as an attribute of the label object:

background_label.image = background_image

"Permission Denied" trying to run Python on Windows 10

Add the path of python folder in environmental variable and it will work

1.search environmental variable

2.look for system variable section and find variable named path in it

3.double click on path and add new path which directs towards python folder and that's it.

the python folder is usually in C:\Users["user name"]\AppData\Local\Programs\Python\Python39

Can I pass parameters by reference in Java?

Java is always pass by value.

When you pass a primitive it's a copy of the value, when you pass an object it's a copy of the reference pointer.

What happened to console.log in IE8?

If you get "undefined" to all of your console.log calls, that probably means you still have an old firebuglite loaded (firebug.js). It will override all the valid functions of IE8's console.log even though they do exist. This is what happened to me anyway.

Check for other code overriding the console object.

Android check internet connection

Use this code to check the internet connection

ConnectivityManager connectivityManager = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if ((connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
                || (connectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                        .getState() == NetworkInfo.State.CONNECTED)) {
            return true;
        } else {
            return false;
        }

How to get a List<string> collection of values from app.config in WPF?

Thank for the question. But I have found my own solution to this problem. At first, I created a method

    public T GetSettingsWithDictionary<T>() where T:new()
    {
        IConfigurationRoot _configurationRoot = new ConfigurationBuilder()
        .AddXmlFile($"{Assembly.GetExecutingAssembly().Location}.config", false, true).Build();

        var instance = new T();
        foreach (var property in typeof(T).GetProperties())
        {
            if (property.PropertyType == typeof(Dictionary<string, string>))
            {
                property.SetValue(instance, _configurationRoot.GetSection(typeof(T).Name).Get<Dictionary<string, string>>());
                break;
            }

        }
        return instance;
    }

Then I used this method to produce an instance of a class

var connStrs = GetSettingsWithDictionary<AuthMongoConnectionStrings>();

I have the next declaration of class

public class AuthMongoConnectionStrings
{
    public Dictionary<string, string> ConnectionStrings { get; set; }
}

and I store my setting in App.config

<configuration>    
  <AuthMongoConnectionStrings
  First="first"
  Second="second"
  Third="33" />
</configuration> 

Save current directory in variable using Bash?

You can use shell in-build variable PWD, like this:

export PATH=$PATH:$PWD+somethingelse

How to remove tab indent from several lines in IDLE?

By default, IDLE has it on Shift-Left Bracket. However, if you want, you can customise it to be Shift-Tab by clicking Options --> Configure IDLE --> Keys --> Use a Custom Key Set --> dedent-region --> Get New Keys for Selection

Then you can choose whatever combination you want. (Don't forget to click apply otherwise all the settings would not get affected.)

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

var fs = require("fs");
var filename = "./index.html";

function start(resp) {
    resp.writeHead(200, {
        "Content-Type": "text/html"
    });
    fs.readFile(filename, "utf8", function(err, data) {
        if (err) throw err;
        resp.write(data);
        resp.end();
    });
}

What's the best way to get the last element of an array without deleting it?

Short and sweet.

I came up with solution to remove error message and preserve one-liner form and efficient performance:

$lastEl = array_values(array_slice($array, -1))[0];

-- previous solution

$lastEl = array_pop((array_slice($array, -1)));

Note: The extra parentheses are needed to avoid a PHP Strict standards: Only variables should be passed by reference.

React Native add bold or italics to single words in <Text> field

You could just nest the Text components with the required style. The style will be applied along with already defined style in the first Text component.

Example:

 <Text style={styles.paragraph}>
   Trouble singing in. <Text style={{fontWeight: "bold"}}> Resolve</Text>
 </Text>

How to set environment variables in PyCharm?

I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

The installation is pretty simple:

Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

Then, I created a file, in my project root, called environment.env which contains:

DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
DEBUG=1

Then I went to Run->Edit Configurations, and I followed the steps in the next image:

Set Environment Variables

In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

GetElementByID - Multiple IDs

document.getElementById() only supports one name at a time and only returns a single node not an array of nodes. You have several different options:

  1. You could implement your own function that takes multiple ids and returns multiple elements.
  2. You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string .
  3. You could put a common class names on all those nodes and use document.getElementsByClassName() with a single class name.

Examples of each option:

doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));

or:

// put a common class on each object
doStuff(document.getElementsByClassName("circles"));

or:

function getElementsById(ids) {
    var idList = ids.split(" ");
    var results = [], item;
    for (var i = 0; i < idList.length; i++) {
        item = document.getElementById(idList[i]);
        if (item) {
            results.push(item);
        }
    }
    return(results);
}

doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));

How does one use the onerror attribute of an img element

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

How do I get an Excel range using row and column numbers in VSTO / C#?

I found a good short method that seems to work well...

Dim x, y As Integer
x = 3: y = 5  
ActiveSheet.Cells(y, x).Select
ActiveCell.Value = "Tada"

In this example we are selecting 3 columns over and 5 rows down, then putting "Tada" in the cell.

Working with TIFFs (import, export) in Python using numpy

I recommend using the python bindings to OpenImageIO, it's the standard for dealing with various image formats in the vfx world. I've ovten found it more reliable in reading various compression types compared to PIL.

import OpenImageIO as oiio
input = oiio.ImageInput.open ("/path/to/image.tif")

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

CloseableHttpClient is the base class of the httpclient library, the one all implementations use. Other subclasses are for the most part deprecated.

The HttpClient is an interface for this class and other classes.

You should then use the CloseableHttpClient in your code, and create it using the HttpClientBuilder. If you need to wrap the client to add specific behaviour you should use request and response interceptors instead of wrapping with the HttpClient.

This answer was given in the context of httpclient-4.3.

Why do I keep getting 'SVN: Working Copy XXXX locked; try performing 'cleanup'?

This happened to me when I copied a directory from another subversion project and tried to commit. The soluction was to delete the .svn director inside the directory I wanted to commit.

Pandas sum by groupby, but exclude certain columns

If you are looking for a more generalized way to apply to many columns, what you can do is to build a list of column names and pass it as the index of the grouped dataframe. In your case, for example:

columns = ['Y'+str(i) for year in range(1967, 2011)]

df.groupby('Country')[columns].agg('sum')

Parsing PDF files (especially with tables) with PDFBox

It is not required for me to use the PDFBox library, so a solution that uses another library is fine

Camelot and Excalibur

You may want to try Python library Camelot, an open source library for Python. If you are not inclined to write code, you may use the web interface Excalibur created around Camelot. You "upload" the document to a localhost web server, and "download" the result from this localhost server.

Here is an example from using this python code:

import camelot
tables = camelot.read_pdf('foo.pdf', flavor="stream")
tables[0].to_csv('foo.csv')

The input is a pdf containing this table:

PDF-TREX sample

Sample table from the PDF-TREX set

No help is provided to camelot, it is working on its own by looking at pieces of text relative alignment. The result is returned in a csv file:

PDF table extracted from sample by camelot

PDF table extracted from sample by camelot

"Rules" can de added to help camelot identify where are fillets in sophisticated tables:

Rule added to Excalibur
Rule added in Excalibur. Source

GitHub:

The two projects are active.

Here is a comparison with other software (with test based on actual documents), Tabula, pdfplumber, pdftables, pdf-table-extract.


I want is to be able to parse the file and know what each parsed number means

You cannot do that automatically, as pdf is not semantically structured.

Book versus document

Pdf "documents" are unstructured from a semantic standpoint (it's like a notepad file), the pdf document gives instructions on where to print a text fragment, unrelated to other fragments of the same section, there is no separation between content (what to print, and whether this is a fragment of a title, a table or a footnote) and the visual representation (font, location, etc). Pdf is an extension of PostScript, which describes a Hello world! page this way:

!PS
 /Courier             % font
 20 selectfont        % size
 72 500 moveto        % current location to print at
 (Hello world!) show  % add text fragment
 showpage             % print all on the page

(Wikipedia).
One can imagine what a table looks like with the same instructions.

We could say html is not clearer, however there is a big difference: Html describes the content semantically (title, paragraph, list, table header, table cell, ...) and associates the css to produce a visual form, hence content is fully accessible. In this sense, html is a simplified descendant of sgml which puts constraints to allow data processing:

Markup should describe a document's structure and other attributes rather than specify the processing that needs to be performed, because it is less likely to conflict with future developments.

exactly the opposite of PostScript/Pdf. SGML is used in publishing. Pdf doesn't embed this semantical structure, it carries only the css-equivalent associated to plain character strings which may not be complete words or sentences. Pdf is used for closed documents and now for the so-called workflow management.

After having experimented the uncertainty and difficulty in trying to extract data from pdf, it's clear pdf is not at all a solution to preserve a document content for the future (in spite Adobe has obtained from their pairs a pdf standard).

What is actually preserved well is the printed representation, as the pdf was fully dedicated to this aspect when created. Pdf are nearly as dead as printed books.

When reusing the content matters, one must rely again on manual re-entering of data, like from a printed book (possibly trying to do some OCR on it). This is more and more true, as many pdf even prevent the use of copy-paste, introducing multiple spaces between words or produce an unordered characters gibberish when some "optimization" is done for web use.

When the content of the document, not its printed representation, is valuable, then pdf is not the correct format. Even Adobe is unable to recreate perfectly the source of a document from its pdf rendering.

So open data should never be released in pdf format, this limits their use to reading and printing (when allowed), and makes reuse harder or impossible.

Python Traceback (most recent call last)

In Python2, input is evaluated, input() is equivalent to eval(raw_input()). When you enter klj, Python tries to evaluate that name and raises an error because that name is not defined.

Use raw_input to get a string from the user in Python2.

Demo 1: klj is not defined:

>>> input()
klj
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'klj' is not defined

Demo 2: klj is defined:

>>> klj = 'hi'
>>> input()
klj
'hi'

Demo 3: getting a string with raw_input:

>>> raw_input()
klj
'klj'

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

Not sure what you meant, but you can permanently turn showing whitespaces on and off in Settings -> Editor -> General -> Appearance -> Show whitespaces.

Also, you can set it for a current file only in View -> Active Editor -> Show WhiteSpaces.

Edit:

Had some free time since it looks like a popular issue, I had written a plugin to inspect the code for such abnormalities. It is called Zero Width Characters locator and you're welcome to give it a try.

Adding iOS UITableView HeaderView (not section header)

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
    {

    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0,0,tableView.frame.size.width,30)];
    headerView.backgroundColor=[[UIColor redColor]colorWithAlphaComponent:0.5f];
    headerView.layer.borderColor=[UIColor blackColor].CGColor;
    headerView.layer.borderWidth=1.0f;

    UILabel *headerLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 5,100,20)];

    headerLabel.textAlignment = NSTextAlignmentRight;
    headerLabel.text = @"LeadCode ";
    //headerLabel.textColor=[UIColor whiteColor];
    headerLabel.backgroundColor = [UIColor clearColor];


    [headerView addSubview:headerLabel];

    UILabel *headerLabel1 = [[UILabel alloc] initWithFrame:CGRectMake(60, 0, headerView.frame.size.width-120.0, headerView.frame.size.height)];

    headerLabel1.textAlignment = NSTextAlignmentRight;
    headerLabel1.text = @"LeadName";
    headerLabel.textColor=[UIColor whiteColor];
    headerLabel1.backgroundColor = [UIColor clearColor];

    [headerView addSubview:headerLabel1];

    return headerView;

}

How to make a div center align in HTML

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
  <head>_x000D_
    <title>Center</title>_x000D_
  </head>_x000D_
  <body>_x000D_
_x000D_
    <div style="text-align: center;">_x000D_
      <div style="width: 500px; margin: 0 auto; background: #000; color: #fff;">This DIV is centered</div>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Tested and worked in IE, Firefox, Chrome, Safari and Opera. I did not test IE6. The outer text-align is needed for IE. Other browsers (and IE9?) will work when you give the DIV margin (left and right) value of auto. Margin "0 auto" is a shorthand for margin "0 auto 0 auto" (top right bottom left).

Note: the text is also centered inside the inner DIV, if you want it to remain on the left side just specify text-align: left; for the inner DIV.

Edit: IE 6, 7, 8 and 9 running on the Standards Mode will work with margins set to auto.

PHP cURL custom headers

curl_setopt($ch, CURLOPT_HTTPHEADER, array(
    'X-Apple-Tz: 0',
    'X-Apple-Store-Front: 143444,12'
));

http://www.php.net/manual/en/function.curl-setopt.php

Git Push ERROR: Repository not found

Had similar issue. The root of the problem was that I followed some online tutorial about adding a new repository to Github.

Just go to Github, create a new repo, it will ask you to add a README, don't add it. Create it, and you'll get instructions on how to push.

It's similar to the next two lines:

git remote add origin https://github.com/YOUR_USER/your-repo.git
git push -u origin master

How do I add multiple conditions to "ng-disabled"?

Actually the ng-disabled directive works with the " || " logical operator for me. The " && " evaluate only one condition.

http://jsbin.com/kuqilejesi/2/edit?html,js,output

Python 3 - Encode/Decode vs Bytes/Str

To add to Lennart Regebro's answer There is even the third way that can be used:

encoded3 = str.encode(original, 'utf-8')
print(encoded3)

Anyway, it is actually exactly the same as the first approach. It may also look that the second way is a syntactic sugar for the third approach.


A programming language is a means to express abstract ideas formally, to be executed by the machine. A programming language is considered good if it contains constructs that one needs. Python is a hybrid language -- i.e. more natural and more versatile than pure OO or pure procedural languages. Sometimes functions are more appropriate than the object methods, sometimes the reverse is true. It depends on mental picture of the solved problem.

Anyway, the feature mentioned in the question is probably a by-product of the language implementation/design. In my opinion, this is a nice example that show the alternative thinking about technically the same thing.

In other words, calling an object method means thinking in terms "let the object gives me the wanted result". Calling a function as the alternative means "let the outer code processes the passed argument and extracts the wanted value".

The first approach emphasizes the ability of the object to do the task on its own, the second approach emphasizes the ability of an separate algoritm to extract the data. Sometimes, the separate code may be that much special that it is not wise to add it as a general method to the class of the object.

org.hibernate.MappingException: Unknown entity

My issue was resolved After adding
sessionFactory.setPackagesToScan( new String[] { "com.springhibernate.model" }); Tested this Functionality in spring boot latest version 2.1.2.

Full Method:

 @Bean( name="sessionFactoryConfig")
    public LocalSessionFactoryBean sessionFactoryConfig() {

        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

        sessionFactory.setDataSource(dataSourceConfig());
        sessionFactory.setPackagesToScan(
                new String[] { "com.springhibernate.model" });

        sessionFactory.setHibernateProperties(hibernatePropertiesConfig());

        return sessionFactory;
    }

Python list iterator behavior and next(iterator)

It behaves the way you want if called as a function:

>>> def test():
...     a = iter(list(range(10)))
...     for i in a:
...         print(i)
...         next(a)
... 
>>> test()
0
2
4
6
8

JPA and Hibernate - Criteria vs. JPQL or HQL

Most the answers here are misleading and mention that Criteria Queries are slower than HQL, which is actually not the case.

If you delve deep and perform some tests you will see Criteria Queries perform much better that regular HQL.

And also with Criteria Query you get Object Oriented control which is not there with HQL.

For more information read this answer here.

Illegal Escape Character "\"

I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")

NameError: name 'datetime' is not defined

You need to import the module datetime first:

>>> import datetime

After that it works:

>>> import datetime
>>> date = datetime.date.today()
>>> date
datetime.date(2013, 11, 12)

Replace multiple strings at once

For the tags, you should be able to just set the content with .text() instead of .html().

Example: http://jsfiddle.net/Phf4u/1/

var textarea = $('textarea').val().replace(/<br\s?\/?>/, '\n');

$("#output").text(textarea);

...or if you just wanted to remove the <br> elements, you could get rid of the .replace(), and temporarily make them DOM elements.

Example: http://jsfiddle.net/Phf4u/2/

var textarea = $('textarea').val();

textarea = $('<div>').html(textarea).find('br').remove().end().html();

$("#output").text(textarea);

XSS filtering function in PHP

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

Get paragraph text inside an element

If you use eg. "id" you can do it this way:

_x000D_
_x000D_
   (function() {_x000D_
    let x = document.getElementById("idName");_x000D_
    let y = document.getElementById("liName");_x000D_
    _x000D_
    y.addEventListener('click', function(e) {_x000D_
        y.appendChild(x);_x000D_
    });_x000D_
_x000D_
  _x000D_
})();
_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
    <title></title>_x000D_
    <meta charset="UTF-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1.0">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <p id="idName">TEXT</p>_x000D_
    <ul>_x000D_
        <li id="liName">_x000D_
_x000D_
        </li>_x000D_
    </ul>_x000D_
</body>_x000D_
<script src="js/scripts/script.js"></script>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Sticky and NON-Sticky sessions

When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.

However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.

Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.

If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.

To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.

As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html

Convert a float64 to an int in Go

Correct rounding is likely desired.

Therefore math.Round() is your quick(!) friend. Approaches with fmt.Sprintf and strconv.Atois() were 2 orders of magnitude slower according to my tests with a matrix of float64 values that were intended to become correctly rounded int values.

package main
import (
    "fmt"
    "math"
)
func main() {
    var x float64 = 5.51
    var y float64 = 5.50
    var z float64 = 5.49
    fmt.Println(int(math.Round(x)))  // outputs "6"
    fmt.Println(int(math.Round(y)))  // outputs "6"
    fmt.Println(int(math.Round(z)))  // outputs "5"
}

math.Round() does return a float64 value but with int() applied afterwards, I couldn't find any mismatches so far.

Storing an object in state of a React component?

Easier way to do it in one line of code

this.setState({ object: { ...this.state.object, objectVarToChange: newData } })

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

For me changing the Jenkins version helped.

  <parent>
    <groupId>org.jenkins-ci.plugins</groupId>
    <artifactId>plugin</artifactId>
    <version>1.642.4</version><!-- which version of Jenkins is this plugin built against? -->
  </parent>

How can I make a div stick to the top of the screen once it's been scrolled to?

sticky till the footer hits the div:

function stickyCostSummary() {
    var stickySummary = $('.sticky-cost-summary');
    var scrollCostSummaryDivPosition = $(window).scrollTop();
    var footerHeight = $('#footer').height();
    var documentHeight = $(document).height();
    var costSummaryHeight = stickySummary.height();
    var headerHeight = 83;
    var footerMargin = 10;
    var scrollHeight = 252;
    var footerPosition = $('#footer').offset().top;

    if (scrollCostSummaryDivPosition > scrollHeight && scrollCostSummaryDivPosition <= (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
        stickySummary.removeAttr('style');
        stickySummary.addClass('fixed');

    } else if (scrollCostSummaryDivPosition > (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin)) {
        stickySummary.removeClass('fixed');
        stickySummary.css({
          "position" : "absolute",
          "top" : (documentHeight - footerHeight - costSummaryHeight - headerHeight - footerMargin - scrollHeight) + "px"
      });
    } else {
        stickySummary.removeClass('fixed');
        stickySummary.css({
            "position" : "absolute",
            "top" : "0"
        });
    }
}

$window.scroll(stickyCostSummary);

How should I pass an int into stringWithFormat?

Do this:

label.text = [NSString stringWithFormat:@"%d", count];

Is there any simple way to convert .xls file to .csv file? (Excel)

I integrate the @mattmc3 aswer. If you want to convert a xlsx file you should use this connection string (the string provided by matt works for xls formats, not xlsx):

var cnnStr = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO\"", excelFilePath);

Postgres Error: More than one row returned by a subquery used as an expression

This means your nested SELECT returns more than one rows.

You need to add a proper WHERE clause to it.

What does it mean to have an index to scalar variable error? python

exponent is a 1D array. This means that exponent[0] is a scalar, and exponent[0][i] is trying to access it as if it were an array.

Did you mean to say:

L = identity(len(l))
for i in xrange(len(l)):
    L[i][i] = exponent[i]

or even

L = diag(exponent)

?

Is Android using NTP to sync time?

i wanted to ask if Android Devices uses the network time protocol (ntp) to synchronize the time.

For general time synchronization, devices with telephony capability, where the wireless provider provides NITZ information, will use NITZ. My understanding is that NTP is used in other circumstances: NITZ-free wireless providers, WiFi-only, etc.

Your cited blog post suggests another circumstance: on-demand time synchronization in support of GPS. That is certainly conceivable, though I do not know whether it is used or not.

How to change the display name for LabelFor in razor in mvc3?

This was an old question, but existing answers ignore the serious issue of throwing away any custom attributes when you regenerate the model. I am adding a more detailed answer to cover the current options available.

You have 3 options:

  • Add a [DisplayName("Name goes here")] attribute to the data model class. The downside is that this is thrown away whenever you regenerate the data models.
  • Add a string parameter to your Html.LabelFor. e.g. @Html.LabelFor(model => model.SomekingStatus, "My New Label", new { @class = "control-label"}) Reference: https://msdn.microsoft.com/en-us/library/system.web.mvc.html.labelextensions.labelfor(v=vs.118).aspx The downside to this is that you must repeat the label in every view.
  • Third option. Use a meta-data class attached to the data class (details follow).

Option 3 - Add a Meta-Data Class:

Microsoft allows for decorating properties on an Entity Framework class, without modifying the existing class! This by having meta-data classes that attach to your database classes (effectively a sideways extension of your EF class). This allow attributes to be added to the associated class and not to the class itself so the changes are not lost when you regenerate the data models.

For example, if your data class is MyModel with a SomekingStatus property, you could do it like this:

First declare a partial class of the same name (and using the same namespace), which allows you to add a class attribute without being overridden:

[MetadataType(typeof(MyModelMetaData))]
public partial class MyModel
{
}

All generated data model classes are partial classes, which allow you to add extra properties and methods by simply creating more classes of the same name (this is very handy and I often use it e.g. to provide formatted string versions of other field types in the model).

Step 2: add a metatadata class referenced by your new partial class:

public class MyModelMetaData
{
    // Apply DisplayNameAttribute (or any other attributes)
    [DisplayName("My New Label")]
    public string SomekingStatus;
}

Reference: https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.metadatatypeattribute(v=vs.110).aspx

Notes:

  • From memory, if you start using a metadata class, it may ignore existing attributes on the actual class ([required] etc) so you may need to duplicate those in the Meta-data class.
  • This does not operate by magic and will not just work with any classes. The code that looks for UI decoration attributes is designed to look for a meta-data class first.

Spring MVC How take the parameter value of a GET HTTP Request in my controller method?

As explained in the documentation, by using an @RequestParam annotation:

public @ResponseBody String byParameter(@RequestParam("foo") String foo) {
    return "Mapped by path + method + presence of query parameter! (MappingController) - foo = "
           + foo;
}

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Adding a Button to a WPF DataGrid

XAML :

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False"  ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="Button_Click_dgvs">Text</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>

Code Behind :

       private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ //IQueryable 
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row & row.IsSelected) yield return row;
    }
}

void Button_Click_dgvs(object sender, RoutedEventArgs e)
{

    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
           // var row = (DataGrid)vis;

            var rows = GetDataGridRowsForButtons(dgv_Students);
            string id;
            foreach (DataGridRow dr in rows)
            {
                id = (dr.Item as tbl_student).Identification_code;
                MessageBox.Show(id);
                 break;
            }
            break;
        }
}

After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.

How to check a boolean condition in EL?

You can have a look at the EL (expression language) description here.

Both your code are correct, but I prefer the second one, as comparing a boolean to true or false is redundant.

For better readibility, you can also use the not operator:

<c:if test="${not theBooleanVariable}">It's false!</c:if>

Convert a number into a Roman Numeral in javaScript

I wrote this from scratch for freecodecamp challenge. I hope this will help someone.

_x000D_
_x000D_
function convertToRoman(num) {_x000D_
_x000D_
    var nums = [0, 0, 0, 0];_x000D_
_x000D_
    var numsRom = ["", "", "", ""];_x000D_
_x000D_
    var nRom = {_x000D_
        I: "I",_x000D_
        V: "V",_x000D_
        X: "X",_x000D_
        L: "L",_x000D_
        C: "C",_x000D_
        D: "D",_x000D_
        M: "M"_x000D_
    };_x000D_
    /*_x000D_
    1,_x000D_
    5,_x000D_
    10,_x000D_
    50,_x000D_
    100,_x000D_
    500,_x000D_
    1000_x000D_
    */_x000D_
_x000D_
    var i;_x000D_
_x000D_
    nums[0] = Math.floor(num / 1000);_x000D_
    nums[1] = Math.floor((num - nums[0] * 1000) / 100);_x000D_
    nums[2] = Math.floor((num - nums[0] * 1000 - nums[1] * 100) / 10);_x000D_
    nums[3] = num - nums[0] * 1000 - nums[1] * 100 - nums[2] * 10;_x000D_
_x000D_
    //1000_x000D_
    for (i = 0; i < nums[0]; i++) {_x000D_
        numsRom[0] += nRom.M;_x000D_
    }_x000D_
_x000D_
    //100_x000D_
    switch (nums[1]) {_x000D_
        case 1:_x000D_
        case 2:_x000D_
        case 3:_x000D_
            for (i = 0; i < nums[1]; i++) {_x000D_
                numsRom[1] += nRom.C;_x000D_
            }_x000D_
            break;_x000D_
        case 4:_x000D_
            numsRom[1] += nRom.C + nRom.D;_x000D_
            break;_x000D_
        case 5:_x000D_
            numsRom[1] += nRom.D;_x000D_
            break;_x000D_
        case 6:_x000D_
        case 7:_x000D_
        case 8:_x000D_
            numsRom[1] += nRom.D;_x000D_
            for (i = 0; i < nums[1] - 5; i++) {_x000D_
                numsRom[1] += nRom.C;_x000D_
            }_x000D_
            break;_x000D_
        case 9:_x000D_
            numsRom[1] += nRom.C + nRom.M;_x000D_
    }_x000D_
_x000D_
    //10_x000D_
    switch (nums[2]) {_x000D_
        case 1:_x000D_
        case 2:_x000D_
        case 3:_x000D_
            for (i = 0; i < nums[2]; i++) {_x000D_
                numsRom[2] += nRom.X;_x000D_
            }_x000D_
            break;_x000D_
        case 4:_x000D_
            numsRom[2] += nRom.X + nRom.L;_x000D_
            break;_x000D_
        case 5:_x000D_
            numsRom[2] += nRom.L;_x000D_
            break;_x000D_
        case 6:_x000D_
        case 7:_x000D_
        case 8:_x000D_
            numsRom[2] += nRom.L;_x000D_
            for (i = 0; i < nums[2] - 5; i++) {_x000D_
                numsRom[2] += nRom.X;_x000D_
            }_x000D_
            break;_x000D_
        case 9:_x000D_
            numsRom[2] += nRom.X + nRom.C;_x000D_
    }_x000D_
_x000D_
    //1_x000D_
    switch (nums[3]) {_x000D_
        case 1:_x000D_
        case 2:_x000D_
        case 3:_x000D_
            for (i = 0; i < nums[3]; i++) {_x000D_
                numsRom[3] += nRom.I;_x000D_
            }_x000D_
            break;_x000D_
        case 4:_x000D_
            numsRom[3] += nRom.I + nRom.V;_x000D_
            break;_x000D_
        case 5:_x000D_
            numsRom[3] += nRom.V;_x000D_
            break;_x000D_
        case 6:_x000D_
        case 7:_x000D_
        case 8:_x000D_
            numsRom[3] += nRom.V;_x000D_
            for (i = 0; i < nums[3] - 5; i++) {_x000D_
                numsRom[3] += nRom.I;_x000D_
            }_x000D_
            break;_x000D_
        case 9:_x000D_
            numsRom[2] += nRom.I + nRom.X;_x000D_
    }_x000D_
_x000D_
    return numsRom.join("");_x000D_
}_x000D_
_x000D_
console.log("Number: " + 1234 + " is " + convertToRoman(1234));
_x000D_
_x000D_
_x000D_

What are the differences between virtual memory and physical memory?

See here: Physical Vs Virtual Memory

Virtual memory is stored on the hard drive and is used when the RAM is filled. Physical memory is limited to the size of the RAM chips installed in the computer. Virtual memory is limited by the size of the hard drive, so virtual memory has the capability for more storage.

CSS: Creating textured backgrounds

You should try slicing the image if possible into a smaller piece which could be repeated. I have sliced that image to a 101x101px image.

BG Tile

CSS:

body{
  background-image: url(SO_texture_bg.jpg);
  background-repeat:repeat;
}

But in some cases, we wouldn't be able to slice the image to a smaller one. In that case, I would use the whole image. But you could also use the CSS3 methods like what Mustafa Kamal had mentioned.

Wish you good luck.

Is there a CSS parent selector?

There is no parent selector; just the way there is no previous sibling selector. One good reason for not having these selectors is because the browser has to traverse through all children of an element to determine whether or not a class should be applied. For example, if you wrote:

body:contains-selector(a.active) { background: red; }

Then the browser will have to wait until it has loaded and parsed everything until the </body> to determine if the page should be red or not.

The article Why we don't have a parent selector explains it in detail.

Extract month and year from a zoo::yearmon object

I know the OP is using zoo here, but I found this thread googling for a standard ts solution for the same problem. So I thought I'd add a zoo-free answer for ts as well.

# create an example Date 
date_1 <- as.Date("1990-01-01")
# extract year
as.numeric(format(date_1, "%Y"))
# extract month
as.numeric(format(date_1, "%m"))

How to get last key in an array?

Since PHP 7.3 (2018) there is (finally) function for this: http://php.net/manual/en/function.array-key-last.php

$array = ['apple'=>10,'grape'=>15,'orange'=>20];
echo array_key_last ( $array )

will output

orange

Storage permission error in Marshmallow

Check multiple Permission in API level 23 Step 1:

 String[] permissions = new String[]{
        Manifest.permission.INTERNET,
        Manifest.permission.READ_PHONE_STATE,
        Manifest.permission.READ_EXTERNAL_STORAGE,
        Manifest.permission.WRITE_EXTERNAL_STORAGE,
        Manifest.permission.VIBRATE,
        Manifest.permission.RECORD_AUDIO,
};

Step 2:

 private boolean checkPermissions() {
    int result;
    List<String> listPermissionsNeeded = new ArrayList<>();
    for (String p : permissions) {
        result = ContextCompat.checkSelfPermission(this, p);
        if (result != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(p);
        }
    }
    if (!listPermissionsNeeded.isEmpty()) {
        ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), 100);
        return false;
    }
    return true;
}

Step 3:

 @Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    if (requestCode == 100) {
        if (grantResults.length > 0
                && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // do something
        }
        return;
    }
}

Step 4: in onCreate of Activity checkPermissions();

In STL maps, is it better to use map::insert than []?

If your application is speed critical i will advice using [] operator because it creates total 3 copies of the original object out of which 2 are temporary objects and sooner or later destroyed as.

But in insert(), 4 copies of the original object are created out of which 3 are temporary objects( not necessarily "temporaries") and are destroyed.

Which means extra time for: 1. One objects memory allocation 2. One extra constructor call 3. One extra destructor call 4. One objects memory deallocation

If your objects are large, constructors are typical, destructors do a lot of resource freeing, above points count even more. Regarding readability, i think both are fair enough.

The same question came into my mind but not over readability but speed. Here is a sample code through which I came to know about the point i mentioned.

class Sample
{
    static int _noOfObjects;

    int _objectNo;
public:
    Sample() :
        _objectNo( _noOfObjects++ )
    {
        std::cout<<"Inside default constructor of object "<<_objectNo<<std::endl;
    }

    Sample( const Sample& sample) :
    _objectNo( _noOfObjects++ )
    {
        std::cout<<"Inside copy constructor of object "<<_objectNo<<std::endl;
    }

    ~Sample()
    {
        std::cout<<"Destroying object "<<_objectNo<<std::endl;
    }
};
int Sample::_noOfObjects = 0;


int main(int argc, char* argv[])
{
    Sample sample;
    std::map<int,Sample> map;

    map.insert( std::make_pair<int,Sample>( 1, sample) );
    //map[1] = sample;
    return 0;
}

Output when insert() is used Output when [] operator is used

how to execute a scp command with the user name and password in one line

Thanks for your feed back got it to work I used the sshpass tool.

sshpass -p 'password' scp [email protected]:sys_config /var/www/dev/

How to create hyperlink to call phone number on mobile devices?

Dashes (-) have no significance other than making the number more readable, so you might as well include them.

Since we never know where our website visitors are coming from, we need to make phone numbers callable from anywhere in the world. For this reason the + sign is always necessary. The + sign is automatically converted by your mobile carrier to your international dialing prefix, also known as "exit code". This code varies by region, country, and sometimes a single country can use multiple codes, depending on the carrier. Fortunately, when it is a local call, dialing it with the international format will still work.

Using your example number, when calling from China, people would need to dial:

00-1-555-555-1212

And from Russia, they would dial

810-1-555-555-1212

The + sign solves this issue by allowing you to omit the international dialing prefix.

After the international dialing prefix comes the country code(pdf), followed by the geographic code (area code), finally the local phone number.

Therefore either of the last two of your examples would work, but my recommendation is to use this format for readability:

<a href="tel:+1-555-555-1212">+1-555-555-1212</a>

Note: For numbers that contain a trunk prefix different from the country code (e.g. if you write it locally with brackets around a 0), you need to omit it because the number must be in international format.

downcast and upcast

Upcasting (using (Employee)someInstance) is generally easy as the compiler can tell you at compile time if a type is derived from another.

Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.

To test if an employee is a manager:

Employee m = new Manager();
Employee e = new Employee();

if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");

You can also use this

Employee someEmployee = e  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (e) is a manager");

Employee someEmployee = m  as Manager;
    if(someEmployee  != null) Console.WriteLine("someEmployee (m) is a manager");

How do you initialise a dynamic array in C++?

No internal means, AFAIK. Use this: memset(c, 0, length);

How remove border around image in css?

I do believe you need to add the border: none style to your icon element as well.

sudo echo "something" >> /etc/privilegedFile doesn't work

In bash you can use tee in combination with > /dev/null to keep stdout clean.

 echo "# comment" |  sudo tee -a /etc/hosts > /dev/null

How does true/false work in PHP?

think of operator as unary function: is_false(type value) which returns true or false, depending on the exact implementation for specific type and value. Consider if statement to invoke such function implicitly, via syntactic sugar.

other possibility is that type has cast operator, which turns type into another type implicitly, in this case string to Boolean.

PHP does not expose such details, but C++ allows operator overloading which exposes fine details of operator implementation.

This application has no explicit mapping for /error

I need to mention this way and give the reference to packages and it worked out. You may exclude @EnableAutoConfiguration this annotation but required for me to bypass any DB related depenencies.

@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
@ComponentScan(basePackages = {"your package 1", "your package2"})

public class CommentStoreApplication {

    public static void main(String[] args) {
        SpringApplication.run(CommentStoreApplication.class, args);

    }
}

How to calculate UILabel width based on text length?

Swift 4 Answer who are using Constraint

label.text = "Hello World"

var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(attributes: [NSFontAttributeName: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet

Swift 5 Answer who are using Constraint

label.text = "Hello World"

var rect: CGRect = label.frame //get frame of label
rect.size = (label.text?.size(withAttributes: [NSAttributedString.Key.font: UIFont(name: label.font.fontName , size: label.font.pointSize)!]))! //Calculate as per label font
labelWidth.constant = rect.width // set width to Constraint outlet

Cannot load properties file from resources directory

If it is simple application then getSystemResourceAsStream can also be used.

try (InputStream inputStream = ClassLoader.getSystemResourceAsStream("config.properties"))..

How do I remove a library from the arduino environment?

In Elegoo Super Starter Kit, Part 2, Lesson 2.12, IR Receiver Module, I hit the problem that the lesson's IRremote library has a hard conflict with the built-in Arduino RobotIRremote library. I am using the Win10 IDE App, and it was non-trivial to "move the RobotIRremote" folder like the pre-Win10 instructions said. The built-in Libraries are saved at a path like: C:\Program Files\WindowsApps\ArduinoLLC.ArduinoIDE_1.8.42.0_x86__mdqgnx93n4wtt\libraries You won't be able to see WindowsApps unless you show hidden files, and you can't do anything in that folder structure until you are the owner. Carefully follow these directions to make that happen: https://www.youtube.com/watch?v=PmrOzBDZTzw
After hours of frustration, the process above finally resulted in success for me. Elegoo gets an F+ for modern instructions on this lesson.

How to wait in a batch script?

I used this

:top
cls
type G:\empty.txt
type I:\empty.txt
timeout /T 500
goto top

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

I think jQuery cannot find the element.

First of all find the element

var rowTemplate= document.getElementsByName("rowTemplate");

or

var rowTemplate = document.getElementById("rowTemplate"); 

or

var rowTemplate = $('#rowTemplate');

Then try your code again

rowTemplate.html().replace(....)

How do you add an action to a button programmatically in xcode

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];   

Can lambda functions be templated?

Here is one solution that involves wrapping the lamba in a structure:

template <typename T>                                                   
struct LamT                                                             
{                                                                       
   static void Go()                                                     
   {                                                                    
      auto lam = []()                                                   
      {                                                                 
         T var;                                                         
         std::cout << "lam, type = " << typeid(var).name() << std::endl;
      };                                                                

      lam();                                                            
   }                                                                    
};   

To use do:

LamT<int>::Go();  
LamT<char>::Go(); 
#This prints 
lam, type = i
lam, type = c

The main issue with this (besides the extra typing) you cannot embed this structure definition inside another method or you get (gcc 4.9)

error: a template declaration cannot appear at block scope

I also tried doing this:

template <typename T> using LamdaT = decltype(                          
   [](void)                                                          
   {                                                                 
       std::cout << "LambT type = " << typeid(T).name() << std::endl;  
   });

With the hope that I could use it like this:

LamdaT<int>();      
LamdaT<char>();

But I get the compiler error:

error: lambda-expression in unevaluated context

So this doesn't work ... but even if it did compile it would be of limited use because we would still have to put the "using LamdaT" at file scope (because it is a template) which sort of defeats the purpose of lambdas.

Passing variable number of arguments around

Variadic Functions can be dangerous. Here's a safer trick:

   void func(type* values) {
        while(*values) {
            x = *values++;
            /* do whatever with x */
        }
    }

func((type[]){val1,val2,val3,val4,0});

How to create a unique index on a NULL column?

It is possible to use filter predicates to specify which rows to include in the index.

From the documentation:

WHERE <filter_predicate> Creates a filtered index by specifying which rows to include in the index. The filtered index must be a nonclustered index on a table. Creates filtered statistics for the data rows in the filtered index.

Example:

CREATE TABLE Table1 (
  NullableCol int NULL
)

CREATE UNIQUE INDEX IX_Table1 ON Table1 (NullableCol) WHERE NullableCol IS NOT NULL;

Excel column number from column name

Based on Anastasiya's answer. I think this is the shortest vba command:

Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

Return only string message from Spring MVC 3 Controller

This is just a note for those who might find this question later, but you don't have to pull in the response to change the content type. Here's an example below to do just that:

@RequestMapping(method = RequestMethod.GET, value="/controller")
public ResponseEntity<byte[]> displayUploadedFile()
{
  HttpHeaders headers = new HttpHeaders();
  String disposition = INLINE;
  String fileName = "";
  headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

  //Load your attachment here

  if (Arrays.equals(Constants.HEADER_BYTES_PDF, contentBytes)) {
    headers.setContentType(MediaType.valueOf("application/pdf"));
    fileName += ".pdf";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_TIFF_BIG_ENDIAN, contentBytes)
      || Arrays.equals(Constantsr.HEADER_BYTES_TIFF_LITTLE_ENDIAN, contentBytes)) {
    headers.setContentType(MediaType.valueOf("image/tiff"));
    fileName += ".tif";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_JPEG, contentBytes)) {
    headers.setContentType(MediaType.IMAGE_JPEG);
    fileName += ".jpg";
  }

  //Handle other types if necessary

  headers.add("Content-Disposition", , disposition + ";filename=" + fileName);
  return new ResponseEntity<byte[]>(uploadedBytes, headers, HttpStatus.OK);
}

Redis: Show database size/size for keys

Perhaps you can do some introspection on the db file. The protocol is relatively simple (yet not well documented), so you could write a parser for it to determine which individual keys are taking up a lot of space.


New suggestions:

Have you tried using MONITOR to see what is being written, live? Perhaps you can find the issue with the data in motion.

Eclipse Java error: This selection cannot be launched and there are no recent launches

When you create a new class file, try to mark the check box near

public static void main(String[] args) {

this will help you to fix the problem.

Facebook Open Graph Error - Inferred Property

UPD 2020: "Open Graph Object Debugger" has been discontinued. Use Sharing Debugger to refresh Facebook cache.


There is some confusion about tons of Facebook Tools and Documentation. So many people probably use the Sharing Debugger tool to check their OpenGraph markup: https://developers.facebook.com/tools/debug/sharing/

But it only retrieves the information about your site from the Facebook cache. This means that after you change the ogp-markup on your site, the Sharing Debugger will still be using the old cached data. Moreover, if there is no cached data on the Facebook server then the Sharing Debugger will show you the error: This URL hasn't been shared on Facebook before.

So, the solution is to use another tool – Open Graph Object Debugger: https://developers.facebook.com/tools/debug/og/object/

It allows you to Fetch new scrape information and refresh the Facebook cache:

Open Graph Object Debugger

Honestly, I don't know how to find this tool exploring the Tools & Support section of developers.facebook.com – I cannot find any links and mentions. I only have this tool in my bookmarks. That's Facebook :)


Use 'property'-attrs

I also noted that some developers use the name attribute instead of property. Many parsers probably will process such tags properly, but according to The Open Graph protocol, we should use property, not name:

<meta property="og:url" content="http://www.mywebaddress.com"/>

Use full URLs

The last recommendation is to specify full URLs. For example, Facebook complains when you use relative URL in og:image. So use the full one:

<meta property="og:image" content="http://www.mywebaddress.com/myimage.jpg"/>

Exporting PDF with jspdf not rendering CSS

You can get the example of css implemented html to pdf conversion using jspdf on following link: JSFiddle Link

This is sample code for the jspdf html to pdf download.

$('#print-btn').click(() => {
    var pdf = new jsPDF('p','pt','a4');
    pdf.addHTML(document.body,function() {
        pdf.save('web.pdf');
    });
})

VirtualBox Cannot register the hard disk already exists

I really appreciate the suggestions here. The Impaler's and Oleg's comments helped me to piece my solution together.

Use the VBoxManage CLI. There's a modifymedium command with a --setlocation option.

I suggest opening the VBox GUI (on VM VirtualBox Manager 6.0)
- select "Virtual Media Manager" (I used the File menu)
- select the "Information" button for the disk giving you this error
- copy the UUID
Note: I removed the controller from the "Storage" setting before the next step.
- open your command prompt and navigate to the location of the .vdi file
It's a good idea to type VBoxMange to see a list of options, but this is the command to run:

VBoxManage modifymedium [insert medium type here] [UUID] --setlocation [full path to .vdi file]

Finally, reattach the controller to any VM--preferably the one you'd like to fix.

json.net has key method?

Just use x["error_msg"]. If the property doesn't exist, it returns null.

How to change the font and font size of an HTML input tag?

<input type ="text" id="txtComputer">

css

input[type="text"]
{
    font-size:24px;
}

Angular2 If ngModel is used within a form tag, either the name attribute must be set or the form

For me, the solution was very simple. I changed the <form> tag into a <div> and the error goes away.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

I was parsing JSON from a REST API call and got this error. It turns out the API had become "fussier" (eg about order of parameters etc) and so was returning malformed results. Check that you are getting what you expect :)

What is the equivalent of "none" in django templates?

Look at the yesno helper

Eg:

{{ myValue|yesno:"itwasTrue,itWasFalse,itWasNone" }}

how to remove multiple columns in r dataframe?

If you only want to remove columns 5 and 7 but not 6 try:

album2 <- album2[,-c(5,7)] #deletes columns 5 and 7

PermGen elimination in JDK 8

The Permanent Generation (PermGen) space has completely been removed and is kind of replaced by a new space called Metaspace.The consequences of the PermGen removal is that obviously the PermSize and MaxPermSize JVM arguments are ignored and you will never get a java.lang.OutOfMemoryError: PermGen error. The JDK 8 HotSpot JVM is now using native memory for the representation of class metadata and is called Metaspace. Read More>>

Coding Conventions - Naming Enums

This will probably not make me a lot of new friends, but it should be added that the C# people have a different guideline: The enum instances are "Pascal case" (upper/lower case mixed). See stackoverflow discussion and MSDN Enumeration Type Naming Guidelines.

As we are exchanging data with a C# system, I am tempted to copy their enums exactly, ignoring Java's "constants have uppercase names" convention. Thinking about it, I don't see much value in being restricted to uppercase for enum instances. For some purposes .name() is a handy shortcut to get a readable representation of an enum constant and a mixed case name would look nicer.

So, yes, I dare question the value of the Java enum naming convention. The fact that "the other half of the programming world" does indeed use a different style makes me think it is legitimate to doubt our own religion.

How do I get a background location update every n minutes in my iOS application?

To someone else having nightmare figure out this one. I have a simple solution.

  1. look this example from raywenderlich.com-> have sample code, this works perfectly, but unfortunately no timer during background location. this will run indefinitely.
  2. Add timer by using :

    -(void)applicationDidEnterBackground {
    [self.locationManager stopUpdatingLocation];
    
    UIApplication*    app = [UIApplication sharedApplication];
    
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        [app endBackgroundTask:bgTask];
        bgTask = UIBackgroundTaskInvalid;
    }];
    
     self.timer = [NSTimer scheduledTimerWithTimeInterval:intervalBackgroundUpdate
                                                  target:self.locationManager
                                                selector:@selector(startUpdatingLocation)
                                                userInfo:nil
                                                 repeats:YES];
    
    }
    
  3. Just don't forget to add "App registers for location updates" in info.plist.

CSS Equivalent of the "if" statement

CSS itself doesn't have conditional statements, but here's a hack involving custom properties (a.k.a. "css variables").

In this trivial example, you want to apply a padding based on a certain condition—like an "if" statement.

:root   { --is-big: 0; }

.is-big { --is-big: 1; }

.block {
  padding: calc(
    4rem * var(--is-big) +
    1rem * (1 - var(--is-big))
  );
}

So any .block that's an .is-big or that's a descendant of one will have a padding of 4rem, while all other blocks will only have 1rem. Now I call this a "trivial" example because it can be done without the hack.

.block {
  padding: 1rem;
}

.is-big .block,
.block.is-big {
  padding: 4rem;
}

But I will leave its applications to your imagination.

What's the difference between a mock & stub?

following is my understanding...

  • if you create test objects locally and feed your local service with that, you are using mock object. this will give a test for the method you implemented in your local service. it is used to verify behaviors

  • when you get the test data from the real service provider, though from a test version of interface and get a test version of the object, you are working with stubs the stub can have logic to accept certain input and give corresponding output to help you perform state verification...

bash echo number of lines of file given in a bash variable without the file name

I normally use the 'back tick' feature of bash

export NUM_LINES=`wc -l filename`

Note the 'tick' is the 'back tick' e.g. ` not the normal single quote

Extract the first word of a string in a SQL Server query

Enhancement of Ben Brandt's answer to compensate even if the string starts with space by applying LTRIM(). Tried to edit his answer but rejected, so I am now posting it here separately.

DECLARE @test NVARCHAR(255)
SET @test = 'First Second'

SELECT SUBSTRING(LTRIM(@test),1,(CHARINDEX(' ',LTRIM(@test) + ' ')-1))

Determine Pixel Length of String in Javascript/jQuery?

Put it in an absolutely-positioned div then use clientWidth to get the displayed width of the tag. You can even set the visibility to "hidden" to hide the div:

<div id="text" style="position:absolute;visibility:hidden" >This is some text</div>
<input type="button" onclick="getWidth()" value="Go" />
<script type="text/javascript" >
    function getWidth() {
        var width = document.getElementById("text").clientWidth;
        alert(" Width :"+  width);
    }
</script>

TypeError: unhashable type: 'dict', when dict used as a key for another dict

From the error, I infer that referenceElement is a dictionary (see repro below). A dictionary cannot be hashed and therefore cannot be used as a key to another dictionary (or itself for that matter!).

>>> d1, d2 = {}, {}
>>> d1[d2] = 1
Traceback (most recent call last):
  File "<input>", line 1, in <module>
TypeError: unhashable type: 'dict'

You probably meant either for element in referenceElement.keys() or for element in json['referenceElement'].keys(). With more context on what types json and referenceElement are and what they contain, we will be able to better help you if neither solution works.

How to determine if OpenSSL and mod_ssl are installed on Apache2

You should install this Apache mod, http://httpd.apache.org/docs/2.0/mod/mod_info.html, it basically gives you a run down of the mods you're using and the Apache settings. I have this enabled on my Apache and it gives me this info for my website,

Server Version: Apache/2.2.3 (Debian) mod_jk/1.2.18 PHP/5.2.0-8+etch13 mod_ssl/2.2.3 OpenSSL/0.9.8c mod_perl/2.0.2 Perl/v5.8.8

Using PHP with Socket.io

If you really want to use PHP as your backend for socket.io ,here are what I found. Two socket.io php server side alternative.

https://github.com/walkor/phpsocket.io

https://github.com/RickySu/phpsocket.io

Exmaple codes for the first repository like this.

use PHPSocketIO\SocketIO;

// listen port 2021 for socket.io client
$io = new SocketIO(2021);
$io->on('connection', function($socket)use($io){
  $socket->on('chat message', function($msg)use($io){
    $io->emit('chat message', $msg);
  });
});

is there a function in lodash to replace matched item

Came across this as well and did it simply that way.

const persons = [{id: 1, name: "Person 1"}, {id:2, name:"Person 2"}];
const updatedPerson = {id: 1, name: "new Person Name"}
const updatedPersons = persons.map(person => (
  person.id === updated.id
    ? updatedPerson
    : person
))

If wanted we can generalize it

const replaceWhere = (list, predicate, replacement) => {
  return list.map(item => predicate(item) ? replacement : item)
}

replaceWhere(persons, person => person.id === updatedPerson.id, updatedPerson)

sql how to cast a select query

I interpreted the question as using cast on a subquery. Yes, you can do that:

select cast((<subquery>) as <newtype>)

If you do so, then you need to be sure that the returns one row and one value. And, since it returns one value, you could put the cast in the subquery instead:

select (select cast(<val> as <newtype>) . . .)

How to change line color in EditText

The best approach is to use an AppCompatEditText with backgroundTint attribute of app namespace. i.e.

    <android.support.v7.widget.AppCompatEditText
    android:layout_width="match_parent"      
    app:backgroundTint="YOUR COLOR"
    android:layout_height="wrap_content" />

when we use android:backgroundTint it will only work in API21 or more but app:backgroundTint works on all API levels your app does.

Multiple markers Google Map API v3 from array of addresses and avoid OVER_QUERY_LIMIT while geocoding on pageLoad

Here is my solution:

dependencies: Gmaps.js, jQuery

var Maps = function($) {
   var lost_addresses = [],
       geocode_count  = 0;

   var addMarker = function() { console.log('Marker Added!') };

   return {
     getGecodeFor: function(addresses) {
        var latlng;
        lost_addresses = [];
        for(i=0;i<addresses.length;i++) {
          GMaps.geocode({
            address: addresses[i],
            callback: function(response, status) {
              if(status == google.maps.GeocoderStatus.OK) {
                addMarker();
              } else if(status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
                lost_addresses.push(addresses[i]);
              }

               geocode_count++;
               // notify listeners when the geocode is done
               if(geocode_count == addresses.length) {
                 $.event.trigger({ type: 'done:geocoder' });
               }
            }
          });
        }
     },
     processLostAddresses: function() {
       if(lost_addresses.length > 0) {
         this.getGeocodeFor(lost_addresses);
       }
     }
   };
}(jQuery);

Maps.getGeocodeFor(address);

// listen to done:geocode event and process the lost addresses after 1.5s
$(document).on('done:geocode', function() {
  setTimeout(function() {
    Maps.processLostAddresses();
  }, 1500);
});

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

VBA: Convert Text to Number

''Convert text to Number with ZERO Digits and Number convert ZERO Digits  

Sub ZERO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0"
 Set rSelection = Nothing
End Sub

''Convert text to Number with TWO Digits and Number convert TWO Digits  

Sub TWO_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.00"
 Set rSelection = Nothing
End Sub

''Convert text to Number with SIX Digits and Number convert SIX Digits  


Sub SIX_DIGIT()
 On Error Resume Next
 Dim rSelection As Range
 Set rSelection = rSelection
 rSelection.Select
 With Selection
  Selection.NumberFormat = "General"
  .Value = .Value
 End With
 rSelection.Select
  Selection.NumberFormat = "0.000000"
 Set rSelection = Nothing
End Sub



Send file using POST from a Python script

Yes. You'd use the urllib2 module, and encode using the multipart/form-data content type. Here is some sample code to get you started -- it's a bit more than just file uploading, but you should be able to read through it and see how it works:

user_agent = "image uploader"
default_message = "Image $current of $total"

import logging
import os
from os.path import abspath, isabs, isdir, isfile, join
import random
import string
import sys
import mimetypes
import urllib2
import httplib
import time
import re

def random_string (length):
    return ''.join (random.choice (string.letters) for ii in range (length + 1))

def encode_multipart_data (data, files):
    boundary = random_string (30)

    def get_content_type (filename):
        return mimetypes.guess_type (filename)[0] or 'application/octet-stream'

    def encode_field (field_name):
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"' % field_name,
                '', str (data [field_name]))

    def encode_file (field_name):
        filename = files [field_name]
        return ('--' + boundary,
                'Content-Disposition: form-data; name="%s"; filename="%s"' % (field_name, filename),
                'Content-Type: %s' % get_content_type(filename),
                '', open (filename, 'rb').read ())

    lines = []
    for name in data:
        lines.extend (encode_field (name))
    for name in files:
        lines.extend (encode_file (name))
    lines.extend (('--%s--' % boundary, ''))
    body = '\r\n'.join (lines)

    headers = {'content-type': 'multipart/form-data; boundary=' + boundary,
               'content-length': str (len (body))}

    return body, headers

def send_post (url, data, files):
    req = urllib2.Request (url)
    connection = httplib.HTTPConnection (req.get_host ())
    connection.request ('POST', req.get_selector (),
                        *encode_multipart_data (data, files))
    response = connection.getresponse ()
    logging.debug ('response = %s', response.read ())
    logging.debug ('Code: %s %s', response.status, response.reason)

def make_upload_file (server, thread, delay = 15, message = None,
                      username = None, email = None, password = None):

    delay = max (int (delay or '0'), 15)

    def upload_file (path, current, total):
        assert isabs (path)
        assert isfile (path)

        logging.debug ('Uploading %r to %r', path, server)
        message_template = string.Template (message or default_message)

        data = {'MAX_FILE_SIZE': '3145728',
                'sub': '',
                'mode': 'regist',
                'com': message_template.safe_substitute (current = current, total = total),
                'resto': thread,
                'name': username or '',
                'email': email or '',
                'pwd': password or random_string (20),}
        files = {'upfile': path}

        send_post (server, data, files)

        logging.info ('Uploaded %r', path)
        rand_delay = random.randint (delay, delay + 5)
        logging.debug ('Sleeping for %.2f seconds------------------------------\n\n', rand_delay)
        time.sleep (rand_delay)

    return upload_file

def upload_directory (path, upload_file):
    assert isabs (path)
    assert isdir (path)

    matching_filenames = []
    file_matcher = re.compile (r'\.(?:jpe?g|gif|png)$', re.IGNORECASE)

    for dirpath, dirnames, filenames in os.walk (path):
        for name in filenames:
            file_path = join (dirpath, name)
            logging.debug ('Testing file_path %r', file_path)
            if file_matcher.search (file_path):
                matching_filenames.append (file_path)
            else:
                logging.info ('Ignoring non-image file %r', path)

    total_count = len (matching_filenames)
    for index, file_path in enumerate (matching_filenames):
        upload_file (file_path, index + 1, total_count)

def run_upload (options, paths):
    upload_file = make_upload_file (**options)

    for arg in paths:
        path = abspath (arg)
        if isdir (path):
            upload_directory (path, upload_file)
        elif isfile (path):
            upload_file (path)
        else:
            logging.error ('No such path: %r' % path)

    logging.info ('Done!')

Get first line of a shell command's output

I would use:

awk 'FNR <= 1' file_*.txt

As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1 may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i' to 'FNR <= i' allows to obtain the first i lines.

For example, if you have n files named file_1.txt, ... file_n.txt:

awk 'FNR <= 1' file_*.txt

hello
...
bye

But with head wildcards print the name of the file:

head -1 file_*.txt

==> file_1.csv <==
hello
...
==> file_n.csv <==
bye

Commands out of sync; you can't run this command now

I call this function every time before using $mysqli->query Works with stored procedures as well.

function clearStoredResults(){
    global $mysqli;

    do {
         if ($res = $mysqli->store_result()) {
           $res->free();
         }
        } while ($mysqli->more_results() && $mysqli->next_result());        

}

Initialize 2D array

How about something like this:

for (int row = 0; row < 3; row ++)
    for (int col = 0; col < 3; col++)
        table[row][col] = (char) ('1' + row * 3 + col);

The following complete Java program:

class Test {
    public static void main(String[] args) {
        char[][] table = new char[3][3];
        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                table[row][col] = (char) ('1' + row * 3 + col);

        for (int row = 0; row < 3; row ++)
            for (int col = 0; col < 3; col++)
                System.out.println (table[row][col]);
    }
}

outputs:

1
2
3
4
5
6
7
8
9

This works because the digits in Unicode are consecutive starting at \u0030 (which is what you get from '0').

The expression '1' + row * 3 + col (where you vary row and col between 0 and 2 inclusive) simply gives you a character from 1 to 9.

Obviously, this won't give you the character 10 (since that's two characters) if you go further but it works just fine for the 3x3 case. You would have to change the method of generating the array contents at that point such as with something like:

String[][] table = new String[5][5];
for (int row = 0; row < 5; row ++)
    for (int col = 0; col < 5; col++)
        table[row][col] = String.format("%d", row * 5 + col + 1);

How to switch back to 'master' with git?

I'm trying to sort of get my head around what's going on over there. Is there anything IN your "example" folder? Git doesn't track empty folders.

If you branched and switched to your new branch then made a new folder and left it empty, and then did "git commit -a", you wouldn't get that new folder in the commit.

Which means it's untracked, which means checking out a different branch wouldn't remove it.

fastest MD5 Implementation in JavaScript

I wrote tests to compare several JavaScript hash implementations, including most MD5 implementations mentioned here. To run the tests, go to http://brillout.github.io/test-javascript-hash-implementations/ and wait a bit.

It seems that the YaMD5 implementation of R. Hill's answer is the fastest.

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

SQL Server: Difference between PARTITION BY and GROUP BY

PARTITION BY is analytic, while GROUP BY is aggregate. In order to use PARTITION BY, you have to contain it with an OVER clause.

After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

Configure Two DataSources in Spring Boot 2.0.* or above

If you need to configure multiple data sources, you have to mark one of the DataSource instances as @Primary, because various auto-configurations down the road expect to be able to get one by type.

If you create your own DataSource, the auto-configuration backs off. In the following example, we provide the exact same feature set as the auto-configuration provides on the primary data source:

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSourceProperties firstDataSourceProperties() {
    return new DataSourceProperties();
}

@Bean
@Primary
@ConfigurationProperties("app.datasource.first")
public DataSource firstDataSource() {
    return firstDataSourceProperties().initializeDataSourceBuilder().build();
}

@Bean
@ConfigurationProperties("app.datasource.second")
public BasicDataSource secondDataSource() {
    return DataSourceBuilder.create().type(BasicDataSource.class).build();
}

firstDataSourceProperties has to be flagged as @Primary so that the database initializer feature uses your copy (if you use the initializer).

And your application.propoerties will look something like this:

app.datasource.first.url=jdbc:oracle:thin:@localhost/first
app.datasource.first.username=dbuser
app.datasource.first.password=dbpass
app.datasource.first.driver-class-name=oracle.jdbc.OracleDriver

app.datasource.second.url=jdbc:mariadb://localhost:3306/springboot_mariadb
app.datasource.second.username=dbuser
app.datasource.second.password=dbpass
app.datasource.second.driver-class-name=org.mariadb.jdbc.Driver

The above method is the correct to way to init multiple database in spring boot 2.0 migration and above. More read can be found here.

How do I timestamp every ping result?

The simpler option is just using ts(1) from moreutils (fairly standard on most distros).

$ ping 1.1.1.1 | ts 

Feb 13 12:49:17 PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data. 
Feb 13 12:49:17 64 bytes from 1.1.1.1: icmp_seq=1 ttl=57 time=5.92 ms
Feb 13 12:49:18 64 bytes from 1.1.1.1: icmp_seq=2 ttl=57 time=5.30 ms
Feb 13 12:49:19 64 bytes from 1.1.1.1: icmp_seq=3 ttl=57 time=5.71 ms
Feb 13 12:49:20 64 bytes from 1.1.1.1: icmp_seq=4 ttl=57 time=5.86 ms

or

 ping 1.1.1.1 -I eth0 | ts "[%FT%X]"

Allows for the same strftime format strings as the shell/date workaround.

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

An implementation of the fast Fourier transform (FFT) in C#

The guy that did AForge did a fairly good job but it's not commercial quality. It's great to learn from but you can tell he was learning too so he has some pretty serious mistakes like assuming the size of an image instead of using the correct bits per pixel.

I'm not knocking the guy, I respect the heck out of him for learning all that and show us how to do it. I think he's a Ph.D now or at least he's about to be so he's really smart it's just not a commercially usable library.

The Math.Net library has its own weirdness when working with Fourier transforms and complex images/numbers. Like, if I'm not mistaken, it outputs the Fourier transform in human viewable format which is nice for humans if you want to look at a picture of the transform but it's not so good when you are expecting the data to be in a certain format (the normal format). I could be mistaken about that but I just remember there was some weirdness so I actually went to the original code they used for the Fourier stuff and it worked much better. (ExocortexDSP v1.2 http://www.exocortex.org/dsp/)

Math.net also had some other funkyness I didn't like when dealing with the data from the FFT, I can't remember what it was I just know it was much easier to get what I wanted out of the ExoCortex DSP library. I'm not a mathematician or engineer though; to those guys it might make perfect sense.

So! I use the FFT code yanked from ExoCortex, which Math.Net is based on, without anything else and it works great.

And finally, I know it's not C#, but I've started looking at using FFTW (http://www.fftw.org/). And this guy already made a C# wrapper so I was going to check it out but haven't actually used it yet. (http://www.sdss.jhu.edu/~tamas/bytes/fftwcsharp.html)

OH! I don't know if you are doing this for school or work but either way there is a GREAT free lecture series given by a Stanford professor on iTunes University.

https://podcasts.apple.com/us/podcast/the-fourier-transforms-and-its-applications/id384232849

Generate Java class from JSON?

Try http://www.jsonschema2pojo.org

Or the jsonschema2pojo plug-in for Maven:

        <plugin>
            <groupId>org.jsonschema2pojo</groupId>
            <artifactId>jsonschema2pojo-maven-plugin</artifactId>
            <version>1.0.2</version>
            <configuration>
                <sourceDirectory>${basedir}/src/main/resources/schemas</sourceDirectory>
                <targetPackage>com.myproject.jsonschemas</targetPackage>
                <sourceType>json</sourceType>
            </configuration>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

The <sourceType>json</sourceType> covers the case where the sources are json (like the OP). If you have actual json schemas, remove this line.

Updated in 2014: Two things have happened since Dec '09 when this question was asked:

  • The JSON Schema spec has moved on a lot. It's still in draft (not finalised) but it's close to completion and is now a viable tool specifying your structural rules

  • I've recently started a new open source project specifically intended to solve your problem: jsonschema2pojo. The jsonschema2pojo tool takes a json schema document and generates DTO-style Java classes (in the form of .java source files). The project is not yet mature but already provides coverage of the most useful parts of json schema. I'm looking for more feedback from users to help drive the development. Right now you can use the tool from the command line or as a Maven plugin.

Hope this helps!

Determine which MySQL configuration file is being used

I installed mysql use brew install mysql

mysqld --verbose --help | less

And it shows:

enter image description here

Sending GET request with Authentication headers using restTemplate

These days something like the following will suffice:

HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(accessToken);
restTemplate.exchange(RequestEntity.get(new URI(url)).headers(headers).build(), returnType);

getMinutes() 0-9 - How to display two digit numbers?

how about this? it works for me! :)

var d = new Date();
var minutes = d.getMinutes().toString().replace(/^(\d)$/, '0$1');

Is there an easy way to check the .NET Framework version?

public class DA
{
    public static class VersionNetFramework
    {
        public static string GetVersion()
        {
            return Environment.Version.ToString();
        }
        public static string GetVersionDicription()
        {
            int Major = Environment.Version.Major;
            int Minor = Environment.Version.Minor;
            int Build = Environment.Version.Build;
            int Revision = Environment.Version.Revision;

            //http://dzaebel.net/NetVersionen.htm
            //http://stackoverflow.com/questions/12971881/how-to-reliably-detect-the-actual-net-4-5-version-installed

            //4.0.30319.42000 = .NET 4.6 on Windows 8.1 64 - bit
            if ((Major >=4) && (Minor >=0) && (Build >= 30319) && (Revision >= 42000))
                return @".NET 4.6 on Windows 8.1 64 - bit or later";
            //4.0.30319.34209 = .NET 4.5.2 on Windows 8.1 64 - bit
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 34209))
                return @".NET 4.5.2 on Windows 8.1 64 - bit or later";
            //4.0.30319.34209 = .NET 4.5.2 on Windows 7 SP1 64 - bit
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 34209))
                return @".NET 4.5.2 on Windows 7 SP1 64 - bit or later";
            //4.0.30319.34014 = .NET 4.5.1 on Windows 8.1 64 - bit
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 34014))
                return @".NET 4.5.1 on Windows 8.1 64 - bit or later";
            //4.0.30319.18444 = .NET 4.5.1 on Windows 7 SP1 64 - bit(with MS14 - 009 security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 18444))
                return @".NET 4.5.1 on Windows 7 SP1 64 - bit(with MS14 - 009 security update) or later";
            //4.0.30319.18408 = .NET 4.5.1 on Windows 7 SP1 64 - bit
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 18408))
                return @".NET 4.5.1 on Windows 7 SP1 64 - bit or later";
            //4.0.30319.18063 = .NET 4.5 on Windows 7 SP1 64 - bit(with MS14 - 009 security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 18063))
                return @".NET 4.5 on Windows 7 SP1 64 - bit(with MS14 - 009 security update) or later";
            //4.0.30319.18052 = .NET 4.5 on Windows 7 SP1 64 - bit
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 18052))
                return @".NET 4.5 on Windows 7 SP1 64 - bit or later";
            //4.0.30319.18010 = .NET 4.5 on Windows 8
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 18010))
                return @".NET 4.5 on Windows 8 or later";
            //4.0.30319.17929 = .NET 4.5 RTM
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 17929))
                return @".NET 4.5 RTM or later";
            //4.0.30319.17626 = .NET 4.5 RC
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 17626))
                return @".NET 4.5 RC or later";
            //4.0.30319.17020.NET 4.5 Preview, September 2011
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 17020))
                return @".NET 4.5 Preview, September 2011 or later";
            //4.0.30319.2034 = .NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS14 - 009 LDR security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 2034))
                return @".NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS14 - 009 LDR security update) or later";
            //4.0.30319.1026 = .NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS14 - 057 GDR security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 1026))
                return @".NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS14 - 057 GDR security update) or later";
            //4.0.30319.1022 = .NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS14 - 009 GDR security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 1022))
                return @".NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS14 - 009 GDR security update) or later";
            //4.0.30319.1008 = .NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS13 - 052 GDR security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 1008))
                return @".NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS13 - 052 GDR security update) or later";
            //4.0.30319.544 = .NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS12 - 035 LDR security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 544))
                return @".NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS12 - 035 LDR security update) or later";
            //4.0.30319.447   yes built by: RTMLDR, .NET 4.0 Platform Update 1, April 2011
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 447))
                return @"built by: RTMLDR, .NET 4.0 Platform Update 1, April 2011 or later";
            //4.0.30319.431   yes built by: RTMLDR, .NET 4.0 GDR Update, March 2011 / with VS 2010 SP1 / or.NET 4.0 Update
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 431))
                return @"built by: RTMLDR, .NET 4.0 GDR Update, March 2011 / with VS 2010 SP1 / or.NET 4.0 Update or later";
            //4.0.30319.296 = .NET 4.0 on Windows XP SP3, 7(with MS12 - 074 GDR security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 296))
                return @".NET 4.0 on Windows XP SP3, 7(with MS12 - 074 GDR security update) or later";
            //4.0.30319.276 = .NET 4.0 on Windows XP SP3 (4.0.3 Runtime update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 276))
                return @".NET 4.0 on Windows XP SP3 (4.0.3 Runtime update) or later";
            //4.0.30319.269 = .NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS12 - 035 GDR security update)
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 269))
                return @".NET 4.0 on Windows XP SP3, 7, 7 SP1(with MS12 - 035 GDR security update) or later";
            //4.0.30319.1 yes built by: RTMRel, .NET 4.0 RTM Release, April 2010
            if ((Major >= 4) && (Minor >= 0) && (Build >= 30319) && (Revision >= 1))
                return @"built by: RTMRel, .NET 4.0 RTM Release, April 2010 or later";

            //4.0.30128.1     built by: RC1Rel, .NET 4.0 Release Candidate, Feb 2010
            if ((Major >=4) && (Minor >=0) && (Build >= 30128) && (Revision >= 1))
                return @"built by: RC1Rel, .NET 4.0 Release Candidate, Feb 2010 or later";
            //4.0.21006.1     built by: B2Rel, .NET 4.0 Beta2, Oct 2009
            if ((Major >=4) && (Minor >=0) && (Build >= 21006) && (Revision >=1))
                return @"built by: B2Rel, .NET 4.0 Beta2, Oct 2009 or later";
            //4.0.20506.1     built by: Beta1, .NET 4.0 Beta1, May 2009
            if ((Major >=4) && (Minor >=0) && (Build >= 20506) && (Revision >=1))
                return @"built by: Beta1, .NET 4.0 Beta1, May 2009 or later";
            //4.0.11001.1     built by: CTP2 VPC, .NET 4.0 CTP, October 2008
            if ((Major >=4) && (Minor >=0) && (Build >= 11001) && (Revision >=1))
                return @"built by: CTP2 VPC, .NET 4.0 CTP, October 2008 or later";

            //3.5.30729.5420  yes built by: Win7SP1, .NET 3.5.1 Sicherheits - Update, 12 April 2011
            if ((Major >=3) && (Minor >=5) && (Build >= 30729) && (Revision >= 5420))
                return @"built by: Win7SP1, .NET 3.5.1 Sicherheits - Update, 12 April 2011 or later";
            //3.5.30729.5004  yes built by: NetFXw7 / Windows 7..Rel., Jan 2010 / +Data functions KB976127 .NET 3.5 SP1
            if ((Major >=3) && (Minor >=5) && (Build >= 30729) && (Revision >= 5004))
                return @"built by: NetFXw7 / Windows 7..Rel., Jan 2010 / +Data functions KB976127 .NET 3.5 SP1 or later";
            //3.5.30729.4466  yes built by: NetFXw7 / Windows XP..Rel. , Jan 2010 / +Data functions KB976127 .NET 3.5 SP1
            if ((Major >=3) && (Minor >=5) && (Build >= 30729) && (Revision >= 4466))
                return @"built by: NetFXw7 / Windows XP..Rel. , Jan 2010 / +Data functions KB976127 .NET 3.5 SP1 or later";
            //3.5.30729.4926  yes built by: NetFXw7 / Windows 7 Release, Oct 2009 / .NET 3.5 SP1 + Hotfixes
            if ((Major >=3) && (Minor >=5) && (Build >= 30729) && (Revision >= 4926))
                return @"built by: NetFXw7 / Windows 7 Release, Oct 2009 / .NET 3.5 SP1 + Hotfixes or later";
            //3.5.30729.4918      built by: NetFXw7 / Windows 7 Release Candidate, June 2009
            if ((Major >=3) && (Minor >=5) && (Build >= 30729) && (Revision >= 4918))
                return @"built by: NetFXw7 / Windows 7 Release Candidate, June 2009 or later";
            //3.5.30729.196   yes built by: QFE, .NET 3.5 Family Update Vista / W2008, Dec 2008
            if ((Major >= 3) && (Minor >= 5) && (Build >= 30729) && (Revision >=196))
                return @"built by: QFE, .NET 3.5 Family Update Vista / W2008, Dec 2008 or later";
            //3.5.30729.1 yes built by: SP, .NET 3.5 SP1, Aug 2008
            if ((Major >= 3) && (Minor >= 5) && (Build >= 30729) && (Revision >=1))
                return @"built by: SP, .NET 3.5 SP1, Aug 2008 or later";

            //3.5.30428.1         built by: SP1Beta1, .NET 3.5 SP1 BETA1, May 2008
            if ((Major >=3) && (Minor >=5) && (Build >= 30428) && (Revision >=1))
                return @"built by: SP1Beta1, .NET 3.5 SP1 BETA1, May 2008 or later";
            //3.5.21022.8 yes built by: RTM, Jan 2008
            if ((Major >=3) && (Minor >=5) && (Build >= 21022) && (Revision >= 8))
                return @"built by: RTM, Jan 2008 or later";
            //3.5.20706.1     built by: Beta2, Orcas Beta2, Oct 2007
            if ((Major >=3) && (Minor >=5) && (Build >= 20706) && (Revision >= 1))
                return @"built by: Beta2, Orcas Beta2, Oct 2007 or later";
            //3.5.20526.0     built by: MCritCTP, Orcas Beta1, Mar 2007
            if ((Major >=3) && (Minor >=5) && (Build >= 20526) && (Revision >=0))
                return @"built by: MCritCTP, Orcas Beta1, Mar 2007 or later";

            //3.0.6920.1500   yes built by: QFE, Family Update Vista / W2008, Dez 2008, KB958483
            if ((Major >=3) && (Minor >=0) && (Build >= 6920) && (Revision >= 1500))
                return @"built by: QFE, Family Update Vista / W2008, Dez 2008, KB958483 or later";
            //3.0.4506.4926   yes(NetFXw7.030729 - 4900) / Windows 7 Release, Oct 2009
            if ((Major >=3) && (Minor >=0) && (Build >= 4506) && (Revision >= 4926))
                return @"(NetFXw7.030729 - 4900) / Windows 7 Release, Oct 2009 or later";
            //3.0.4506.4918(NetFXw7.030729 - 4900) / Windows 7 Release Candidate, June 2009
            if ((Major >=3) && (Minor >=5) && (Build >= 4506) && (Revision >= 4918))
                return @"(NetFXw7.030729 - 4900) / Windows 7 Release Candidate, June 2009 or later";
            //3.0.4506.2152       3.0.4506.2152(SP.030729 - 0100) / .NET 4.0 Beta1 / May 2009
            if ((Major >= 3) && (Minor >= 5) && (Build >= 4506) && (Revision >= 2152))
                return @"3.0.4506.2152(SP.030729 - 0100) / .NET 4.0 Beta1 / May 2009 or later";
            //3.0.4506.2123   yes(NetFX.030618 - 0000).NET 3.0 SP2, Aug 2008
            if ((Major >= 3) && (Minor >= 5) && (Build >= 4506) && (Revision >= 2123))
                return @"s(NetFX.030618 - 0000).NET 3.0 SP2, Aug 2008 or later";
            //3.0.4506.2062(SP1Beta1.030428 - 0100), .NET 3.0 SP1 BETA1, May 2008
            if ((Major >= 3) && (Minor >= 5) && (Build >= 4506) && (Revision >= 2062))
                return @"(SP1Beta1.030428 - 0100), .NET 3.0 SP1 BETA1, May 2008 or later";
            //3.0.4506.590(winfxredb2.004506 - 0590), Orcas Beta2, Oct 2007
            if ((Major >= 3) && (Minor >= 5) && (Build >= 4506) && (Revision >= 590))
                return @"(winfxredb2.004506 - 0590), Orcas Beta2, Oct 2007 or later";
            //3.0.4506.577(winfxred.004506 - 0577), Orcas Beta1, Mar 2007
            if ((Major >= 3) && (Minor >= 5) && (Build >= 4506) && (Revision >= 577))
                return @"(winfxred.004506 - 0577), Orcas Beta1, Mar 2007 or later";
            //3.0.4506.30 yes Release (.NET Framework 3.0) Nov 2006
            if ((Major >= 3) && (Minor >= 5) && (Build >= 4506) && (Revision >= 30))
                return @"Release (.NET Framework 3.0) Nov 2006 or later";
            //3.0.4506.25 yes(WAPRTM.004506 - 0026) Vista Ultimate, Jan 2007
            if ((Major >= 3) && (Minor >= 5) && (Build >= 4506) && (Revision >= 25))
                return @"(WAPRTM.004506 - 0026) Vista Ultimate, Jan 2007 or later";

            //2.0.50727.4927  yes(NetFXspW7.050727 - 4900) / Windows 7 Release, Oct 2009
            if ((Major >=2) && (Minor >=0) && (Build >= 50727) && (Revision >= 4927))
                return @"(NetFXspW7.050727 - 4900) / Windows 7 Release, Oct 2009 or later";
            //2.0.50727.4918(NetFXspW7.050727 - 4900) / Windows 7 Release Candidate, June 2009
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 4918))
                return @"(NetFXspW7.050727 - 4900) / Windows 7 Release Candidate, June 2009 or later";
            //2.0.50727.4200  yes(NetFxQFE.050727 - 4200).NET 2.0 SP2, KB974470, Securityupdate, Oct 2009
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 4200))
                return @"(NetFxQFE.050727 - 4200).NET 2.0 SP2, KB974470, Securityupdate, Oct 2009 or later";
            //2.0.50727.3603(GDR.050727 - 3600).NET 4.0 Beta 2, Oct 2009
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 3603))
                return @"(GDR.050727 - 3600).NET 4.0 Beta 2, Oct 2009 or later";
            //2.0.50727.3082  yes(QFE.050727 - 3000), .NET 3.5 Family Update XP / W2003, Dez 2008, KB958481
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 3082))
                return @"(QFE.050727 - 3000), .NET 3.5 Family Update XP / W2003, Dez 2008, KB958481 or later";
            //2.0.50727.3074  yes(QFE.050727 - 3000), .NET 3.5 Family Update Vista / W2008, Dez 2008, KB958481
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 3074))
                return @"(QFE.050727 - 3000), .NET 3.5 Family Update Vista / W2008, Dez 2008, KB958481 or later";
            //2.0.50727.3053  yes(netfxsp.050727 - 3000), .NET 2.0 SP2, Aug 2008
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 3053))
                return @"yes(netfxsp.050727 - 3000), .NET 2.0 SP2, Aug 2008 or later";
            //2.0.50727.3031(netfxsp.050727 - 3000), .NET 2.0 SP2 Beta 1, May 2008
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 3031))
                return @"(netfxsp.050727 - 3000), .NET 2.0 SP2 Beta 1, May 2008 or later";
            //2.0.50727.1434  yes(REDBITS.050727 - 1400), Windows Server 2008 and Windows Vista SP1, Dez 2007
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 1434))
                return @"(REDBITS.050727 - 1400), Windows Server 2008 and Windows Vista SP1, Dez 2007 or later";
            //2.0.50727.1433  yes(REDBITS.050727 - 1400), .NET 2.0 SP1 Release, Nov 2007, http://www.microsoft.com/downloads/details.aspx?FamilyID=79bc3b77-e02c-4ad3-aacf-a7633f706ba5
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 1433))
                return @"(REDBITS.050727 - 1400), .NET 2.0 SP1 Release, Nov 2007 or later";
            //2.0.50727.1378(REDBITSB2.050727 - 1300), Orcas Beta2, Oct 2007
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 1378))
                return @"(REDBITSB2.050727 - 1300), Orcas Beta2, Oct 2007 or later";
            //2.0.50727.1366(REDBITS.050727 - 1300), Orcas Beta1, Mar 2007
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 1366))
                return @"(REDBITS.050727 - 1300), Orcas Beta1, Mar 2007 or later";
            //2.0.50727.867   yes(VS Express Edition 2005 SP1), Apr 2007, http://www.microsoft.com/downloads/details.aspx?FamilyId=7B0B0339-613A-46E6-AB4D-080D4D4A8C4E
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 867))
                return @"(VS Express Edition 2005 SP1), Apr 2007 or later";
            //2.0.50727.832(Fix x86 VC++2005), Apr 2007, http://support.microsoft.com/kb/934586/en-us
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 832))
                return @"(Fix x86 VC++2005), Apr 2007 or later";
            //2.0.50727.762   yes(VS TeamSuite SP1), http://www.microsoft.com/downloads/details.aspx?FamilyId=BB4A75AB-E2D4-4C96-B39D-37BAF6B5B1DC
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 762))
                return @"(VS TeamSuite SP1) or later";
            //2.0.50727.312   yes(rtmLHS.050727 - 3100) Vista Ultimate, Jan 2007
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 312))
                return @"(rtmLHS.050727 - 3100) Vista Ultimate, Jan 2007 or later";
            //2.0.50727.42    yes Release (.NET Framework 2.0) Oct 2005
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 42))
                return @"Release (.NET Framework 2.0) Oct 2005 or later";
            //2.0.50727.26        Version 2.0(Visual Studio Team System 2005 Release Candidate) Oct 2005
            if ((Major >= 2) && (Minor >= 0) && (Build >= 50727) && (Revision >= 26))
                return @"Version 2.0(Visual Studio Team System 2005 Release Candidate) Oct 2005 or later";

            //2.0.50712       Version 2.0(Visual Studio Team System 2005(Drop3) CTP) July 2005
            if ((Major >=2) && (Minor >=0) && (Build >= 50712))
                return @"Version 2.0(Visual Studio Team System 2005(Drop3) CTP) July 2005 or later";
            //2.0.50215       Version 2.0(WinFX SDK for Indigo / Avalon 2005 CTP) July 2005
            if ((Major >=2) && (Minor >=0) && (Build >= 50215))
                return @"Version 2.0(WinFX SDK for Indigo / Avalon 2005 CTP) July 2005 or later";
            //2.0.50601.0     Version 2.0(Visual Studio.NET 2005 CTP) June 2005
            if ((Major >=2) && (Minor >=0) && (Build >= 50601) && (Revision >=0))
                return @"Version 2.0(Visual Studio.NET 2005 CTP) June 2005 or later";
            //2.0.50215.44        Version 2.0(Visual Studio.NET 2005 Beta 2, Visual Studio Express Beta 2) Apr 2005
            if ((Major >=2) && (Minor >=0) && (Build >= 50215) && (Revision >= 44))
                return @"Version 2.0(Visual Studio.NET 2005 Beta 2, Visual Studio Express Beta 2) Apr 2005 or later";
            //2.0.50110.28        Version 2.0(Visual Studio.NET 2005 CTP, Professional Edition) Feb 2005
            if ((Major >=2) && (Minor >=0) && (Build >= 50110) && (Revision >=28))
                return @"Version 2.0(Visual Studio.NET 2005 CTP, Professional Edition) Feb 2005 or later";
            //2.0.41115.19        Version 2.0(Visual Studio.NET 2005 Beta 1, Team System Refresh) Dec 2004
            if ((Major >=2 ) && (Minor >=0 ) && (Build >= 41115) && (Revision >= 19))
                return @"Version 2.0(Visual Studio.NET 2005 Beta 1, Team System Refresh) Dec 2004 or later";
            //2.0.40903.0         Version 2.0(Whidbey CTP, Visual Studio Express) Oct 2004
            if ((Major >=2) && (Minor >=0) && (Build >= 40903) && (Revision >=0))
                return @"Version 2.0(Whidbey CTP, Visual Studio Express) Oct 2004 or later";
            //2.0.40607.85        Version 2.0(Visual Studio.NET 2005 Beta 1, Team System Refresh) Aug 2004 *
            if ((Major >=2) && (Minor >=0) && (Build >= 40607) && (Revision >= 85))
                return @"Version 2.0(Visual Studio.NET 2005 Beta 1, Team System Refresh) Aug 2004 * or later";
            //2.0.40607.42        Version 2.0(SQL Server Yukon Beta 2) July 2004
            if ((Major >=2) && (Minor >=0) && (Build >= 40607) && (Revision >= 42))
                return @"Version 2.0(SQL Server Yukon Beta 2) July 2004 or later";
            //2.0.40607.16        Version 2.0(Visual Studio.NET 2005 Beta 1, TechEd Europe 2004) June 2004
            if ((Major >=2) && (Minor >=0) && (Build >= 40607) && (Revision >= 16))
                return @"Version 2.0(Visual Studio.NET 2005 Beta 1, TechEd Europe 2004) June 2004 or later";
            //2.0.40301.9         Version 2.0(Whidbey CTP, WinHEC 2004) March 2004 *
            if ((Major >=0) && (Minor >=0) && (Build >= 40301) && (Revision >=9))
                return @"Version 2.0(Whidbey CTP, WinHEC 2004) March 2004 * or later";

            //1.2.30703.27        Version 1.2(Whidbey Alpha, PDC 2004) Nov 2003 *
            if ((Major >=1) && (Minor >=2) && (Build >= 30703) && (Revision >= 27))
                return @"Version 1.2(Whidbey Alpha, PDC 2004) Nov 2003 * or later";
            //1.2.21213.1     Version 1.2(Whidbey pre - Alpha build) *
            if ((Major >=1) && (Minor >=2) && (Build >= 21213) && (Revision >=1))
                return @"Version 1.2(Whidbey pre - Alpha build) * or later";

            //1.1.4322.2443   yes Version 1.1 Servicepack 1, KB953297, Oct 2009
            if ((Major >=1) && (Minor >=1) && (Build >= 4322) && (Revision >=2443))
                return @"Version 1.1 Servicepack 1, KB953297, Oct 2009 or later";
            //1.1.4322.2407   yes Version 1.1 RTM
            if ((Major >=1) && (Minor >=1) && (Build >= 4322) && (Revision >= 2407))
                return @"Version 1.1 RTM or later";
            //1.1.4322.2407       Version 1.1 Orcas Beta2, Oct 2007
            if ((Major >=1) && (Minor >=1) && (Build >= 4322) && (Revision >= 2407))
                return @"Version 1.1 Orcas Beta2, Oct 2007 or later";
            //1.1.4322.2379       Version 1.1 Orcas Beta1, Mar 2007
            if ((Major >=1) && (Minor >=1) && (Build >= 4322) && (Revision >= 2379))
                return @"Version 1.1 Orcas Beta1, Mar 2007 or later";
            //1.1.4322.2032   yes Version 1.1 SP1 Aug 2004
            if ((Major >=1) && (Minor >=1) && (Build >= 4322) && (Revision >= 2032))
                return @"Version 1.1 SP1 Aug 2004 or later";
            //1.1.4322.573    yes Version 1.1 RTM(Visual Studio.NET 2003 / Windows Server 2003) Feb 2003 *
            if ((Major >=1) && (Minor >=1) && (Build >= 4322) && (Revision >= 573))
                return @"Version 1.1 RTM(Visual Studio.NET 2003 / Windows Server 2003) Feb 2003 * or later";
            //1.1.4322.510        Version 1.1 Final Beta Oct 2002 *
            if ((Major >=1) && (Minor >=1) && (Build >= 4322) && (Revision >= 510))
                return @"Version 1.1 Final Beta Oct 2002 * or later";

            //1.0.3705.6018   yes Version 1.0 SP3 Aug 2004
            if ((Major >=1) && (Minor >=0) && (Build >= 3705) && (Revision >= 6018))
                return @"Version 1.0 SP3 Aug 2004 or later";
            //1.0.3705.288    yes Version 1.0 SP2 Aug 2002 *
            if ((Major >=1) && (Minor >=0) && (Build >= 3705) && (Revision >= 288))
                return @"Version 1.0 SP2 Aug 2002 * or later";
            //1.0.3705.209    yes Version 1.0 SP1 Mar 2002 *
            if ((Major >=1) && (Minor >=0) && (Build >= 3705) && (Revision >=209))
                return @"Version 1.0 SP1 Mar 2002 * or later";
            //1.0.3705.0  yes Version 1.0 RTM(Visual Studio.NET 2002) Feb 2002 *
            if ((Major >=1) && (Minor >=0) && (Build >= 3705) && (Revision >=0))
                return @"Version 1.0 RTM(Visual Studio.NET 2002) Feb 2002 * or later";
            //1.0.3512.0      Version 1.0 Pre - release RC3(Visual Studio.NET 2002 RC3)
            if ((Major >=1) && (Minor >=0) && (Build >= 3512) && (Revision >=0))
                return @"Version 1.0 Pre - release RC3(Visual Studio.NET 2002 RC3) or later";
            //1.0.2914.16     Version 1.0 Public Beta 2 Jun 2001 *
            if ((Major >=1) && (Minor >=0) && (Build >= 2914) && (Revision >= 16))
                return @"Version 1.0 Public Beta 2 Jun 2001 * or later";
            //1.0.2204.21         Version 1.0 Public Beta 1 Nov 2000 *
            if ((Major >=1) && (Minor >=0) && (Build >= 2204) && (Revision >=21))
                return @"Version 1.0 Public Beta 1 Nov 2000 * or later";

            return @"Unknown .NET version";
        }
    }
}

How to import an existing X.509 certificate and private key in Java keystore to use in SSL?

Keytool in Java 6 does have this capability: Importing private keys into a Java keystore using keytool

Here are the basic details from that post.

  1. Convert the existing cert to a PKCS12 using OpenSSL. A password is required when asked or the 2nd step will complain.

    openssl pkcs12 -export -in [my_certificate.crt] -inkey [my_key.key] -out [keystore.p12] -name [new_alias] -CAfile [my_ca_bundle.crt] -caname root
    
  2. Convert the PKCS12 to a Java Keystore File.

    keytool -importkeystore -deststorepass [new_keystore_pass] -destkeypass [new_key_pass] -destkeystore [keystore.jks] -srckeystore [keystore.p12] -srcstoretype PKCS12 -srcstorepass [pass_used_in_p12_keystore] -alias [alias_used_in_p12_keystore]
    

Get the element with the highest occurrence in an array

Try it too, this does not take in account browser version.

function mode(arr){
var a = [],b = 0,occurrence;
    for(var i = 0; i < arr.length;i++){
    if(a[arr[i]] != undefined){
        a[arr[i]]++;
    }else{
        a[arr[i]] = 1;
    }
    }
    for(var key in a){
    if(a[key] > b){
        b = a[key];
        occurrence = key;
    }
    }
return occurrence;
}
alert(mode(['segunda','terça','terca','segunda','terça','segunda']));

Please note that this function returns latest occurence in the array when 2 or more entries appear same number of times!

no target device found android studio 2.1.1

go to "Run>edit configuration>" and select "Open select deployment target dialog" from deployment target option then run your app it will show you a dialog box you can choose your target device from there, enjoy it.

Is there a way to pass javascript variables in url?

Do you mean include javascript variable values in the query string of the URL?

Yes:

 window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;

Input size vs width

You can use both. The css style will override the size attribute in browsers that support CSS and make the field the correct width, and for those that don't, it will fall back to the specified number of characters.

Edit: I should have mentioned that the size attribute isn't a precise method of sizing: according to the HTML specification, it should refer to the number of characters of the current font the input will be able to display at once.

However, unless the font specified is a fixed-width/monospace font, this is not a guarantee that the specified number of characters will actually be visible; in most fonts, different characters will be different widths. This question has some good answers relating to this issue.

The snippet below demonstrates both approaches.

_x000D_
_x000D_
@font-face {_x000D_
    font-family: 'Diplomata';_x000D_
    font-style: normal;_x000D_
    font-weight: 400;_x000D_
    src: local('Diplomata'), local('Diplomata-Regular'), url(https://fonts.gstatic.com/s/diplomata/v8/8UgOK_RUxkBbV-q561I6kFtXRa8TVwTICgirnJhmVJw.woff2) format('woff2');_x000D_
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
@font-face {_x000D_
    font-family: 'Open Sans Condensed';_x000D_
    font-style: normal;_x000D_
    font-weight: 300;_x000D_
    src: local('Open Sans Condensed Light'), local('OpenSansCondensed-Light'), url(https://fonts.gstatic.com/s/opensanscondensed/v11/gk5FxslNkTTHtojXrkp-xBEur64QvLD-0IbiAdTUNXE.woff2) format('woff2');_x000D_
    unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02C6, U+02DA, U+02DC, U+2000-206F, U+2074, U+20AC, U+2212, U+2215;_x000D_
}_x000D_
p {_x000D_
  margin: 0 0 10px 0;_x000D_
}_x000D_
input {_x000D_
  font-size: 20px;_x000D_
}_x000D_
.narrow-font {_x000D_
  font-family: 'Open Sans Condensed', sans-serif;_x000D_
}_x000D_
.wide-font {_x000D_
  font-family: 'Diplomata', cursive;_x000D_
}_x000D_
.set-width {_x000D_
  width: 220px;_x000D_
}
_x000D_
<p>_x000D_
  <input type="text" size="10" class="narrow-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="wide-font" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="narrow-font set-width" value="0123456789" />_x000D_
</p>_x000D_
<p>_x000D_
  <input type="text" size="10" class="wide-font set-width" value="0123456789" />_x000D_
</p>
_x000D_
_x000D_
_x000D_

System.Timers.Timer vs System.Threading.Timer

Information from Microsoft about this (see Remarks on MSDN):

  • System.Timers.Timer, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Threading.Timer, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
  • System.Windows.Forms.Timer (.NET Framework only), a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment; it executes on the UI thread.
  • System.Web.UI.Timer (.NET Framework only), an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.

It is interesting to mention that System.Timers.Timer was deprecated with .NET Core 1.0, but was implemented again in .NET Core 2.0 (/ .NET Standard 2.0). The goal with .NET Standard 2.0 was that it should be as easy as possible to switch from the .NET Framework which is probably the reason it came back.

When it was deprecated, the .NET Portability Analyzer Visual Studio Add-In recommended to use System.Threading.Timer instead.

Looks like that Microsoft favors System.Threading.Timer before System.Timers.Timer.

EDIT NOTE 2018-11-15: I hand to change my answer since the old information about .NET Core 1.0 was not valid anymore.

How do I check if a C++ string is an int?

Since C++11 you can make use of std::all_of and ::isdigit:

#include <algorithm>
#include <cctype>
#include <iostream>
#include <string_view>

int main([[maybe_unused]] int argc, [[maybe_unused]] char *argv[])
{
    auto isInt = [](std::string_view str) -> bool {
        return std::all_of(str.cbegin(), str.cend(), ::isdigit);
    };

    for(auto &test : {"abc", "123abc", "123.0", "+123", "-123", "123"}) {
        std::cout << "Is '" << test << "' numeric? " 
            << (isInt(test) ? "true" : "false") << std::endl;
    }

    return 0;
}

Check out the result with Godbolt.

Find when a file was deleted in Git

Short answer:

git log --full-history -- your_file

will show you all commits in your repo's history, including merge commits, that touched your_file. The last (top) one is the one that deleted the file.

Some explanation:

The --full-history flag here is important. Without it, Git performs "history simplification" when you ask it for the log of a file. The docs are light on details about exactly how this works and I lack the grit and courage required to try to figure it out from the source code, but the git-log docs have this much to say:

Default mode

Simplifies the history to the simplest history explaining the final state of the tree. Simplest because it prunes some side branches if the end result is the same (i.e. merging branches with the same content)

This is obviously concerning when the file whose history we want is deleted, since the simplest history explaining the final state of a deleted file is no history. Is there a risk that git log without --full-history will simply claim that the file was never created? Unfortunately, yes. Here's a demonstration:

mark@lunchbox:~/example$ git init
Initialised empty Git repository in /home/mark/example/.git/
mark@lunchbox:~/example$ touch foo && git add foo && git commit -m "Added foo"
[master (root-commit) ddff7a7] Added foo
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 foo
mark@lunchbox:~/example$ git checkout -b newbranch
Switched to a new branch 'newbranch'
mark@lunchbox:~/example$ touch bar && git add bar && git commit -m "Added bar"
[newbranch 7f9299a] Added bar
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 bar
mark@lunchbox:~/example$ git checkout master
Switched to branch 'master'
mark@lunchbox:~/example$ git rm foo && git commit -m "Deleted foo"
rm 'foo'
[master 7740344] Deleted foo
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 foo
mark@lunchbox:~/example$ git checkout newbranch
Switched to branch 'newbranch'
mark@lunchbox:~/example$ git rm bar && git commit -m "Deleted bar"
rm 'bar'
[newbranch 873ed35] Deleted bar
 1 file changed, 0 insertions(+), 0 deletions(-)
 delete mode 100644 bar
mark@lunchbox:~/example$ git checkout master
Switched to branch 'master'
mark@lunchbox:~/example$ git merge newbranch
Already up-to-date!
Merge made by the 'recursive' strategy.
mark@lunchbox:~/example$ git log -- foo
commit 77403443a13a93073289f95a782307b1ebc21162
Author: Mark Amery 
Date:   Tue Jan 12 22:50:50 2016 +0000

    Deleted foo

commit ddff7a78068aefb7a4d19c82e718099cf57be694
Author: Mark Amery 
Date:   Tue Jan 12 22:50:19 2016 +0000

    Added foo
mark@lunchbox:~/example$ git log -- bar
mark@lunchbox:~/example$ git log --full-history -- foo
commit 2463e56a21e8ee529a59b63f2c6fcc9914a2b37c
Merge: 7740344 873ed35
Author: Mark Amery 
Date:   Tue Jan 12 22:51:36 2016 +0000

    Merge branch 'newbranch'

commit 77403443a13a93073289f95a782307b1ebc21162
Author: Mark Amery 
Date:   Tue Jan 12 22:50:50 2016 +0000

    Deleted foo

commit ddff7a78068aefb7a4d19c82e718099cf57be694
Author: Mark Amery 
Date:   Tue Jan 12 22:50:19 2016 +0000

    Added foo
mark@lunchbox:~/example$ git log --full-history -- bar
commit 873ed352c5e0f296b26d1582b3b0b2d99e40d37c
Author: Mark Amery 
Date:   Tue Jan 12 22:51:29 2016 +0000

    Deleted bar

commit 7f9299a80cc9114bf9f415e1e9a849f5d02f94ec
Author: Mark Amery 
Date:   Tue Jan 12 22:50:38 2016 +0000

    Added bar

Notice how git log -- bar in the terminal dump above resulted in literally no output; Git is "simplifying" history down into a fiction where bar never existed. git log --full-history -- bar, on the other hand, gives us the commit that created bar and the commit that deleted it.

To be clear: this issue isn't merely theoretical. I only looked into the docs and discovered the --full-history flag because git log -- some_file was failing for me in a real repository where I was trying to track a deleted file down. History simplification might sometimes be helpful when you're trying to understand how a currently-existing file came to be in its current state, but when trying to track down a file deletion it's more likely to screw you over by hiding the commit you care about. Always use the --full-history flag for this use case.

Add content to a new open window

in parent.html:

<script type="text/javascript">
    $(document).ready(function () {
        var output = "data";
        var OpenWindow = window.open("child.html", "mywin", '');
        OpenWindow.dataFromParent = output; // dataFromParent is a variable in child.html
        OpenWindow.init();
    });
</script>

in child.html:

<script type="text/javascript">
    var dataFromParent;    
    function init() {
        document.write(dataFromParent);
    }
</script>

How to sort an ArrayList?

You can use Collections.sort(list) to sort list if your list contains Comparable elements. Otherwise I would recommend you to implement that interface like here:

public class Circle implements Comparable<Circle> {}

and of course provide your own realization of compareTo method like here:

@Override
    public int compareTo(Circle another) {
        if (this.getD()<another.getD()){
            return -1;
        }else{
            return 1;
        }
    }

And then you can again use Colection.sort(list) as now list contains objects of Comparable type and can be sorted. Order depends on compareTo method. Check this https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html for more detailed information.

Replacing few values in a pandas dataframe column with another value

loc function can be used to replace multiple values, Documentation for it : loc

df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'

Sending HTML email using Python

for python3, improve @taltman 's answer:

  • use email.message.EmailMessage instead of email.message.Message to construct email.
  • use email.set_content func, assign subtype='html' argument. instead of low level func set_payload and add header manually.
  • use SMTP.send_message func instead of SMTP.sendmail func to send email.
  • use with block to auto close connection.
from email.message import EmailMessage
from smtplib import SMTP

# construct email
email = EmailMessage()
email['Subject'] = 'foo'
email['From'] = '[email protected]'
email['To'] = '[email protected]'
email.set_content('<font color="red">red color text</font>', subtype='html')

# Send the message via local SMTP server.
with smtplib.SMTP('localhost') as s:
    s.login('foo_user', 'bar_password')
    s.send_message(email)

HTTP client timeout and server timeout

go to the url about:config and paste each line:

network.http.keep-alive.timeout;10
network.http.connection-retry-timeout;10
network.http.pipelining.read-timeout;5
network.http.connection-timeout;10

<strong> vs. font-weight:bold & <em> vs. font-style:italic

HTML represents meaning; CSS represents appearance. How you mark up text in a document is not determined by how that text appears on screen, but simply what it means. As another example, some other HTML elements, like headings, are styled font-weight: bold by default, but they are marked up using <h1><h6>, not <strong> or <b>.

In HTML5, you use <strong> to indicate important parts of a sentence, for example:

<p><strong>Do not touch.</strong> Contains <strong>hazardous</strong> materials.

And you use <em> to indicate linguistic stress, for example:

<p>A Gentleman: I suppose he does. But there's no point in asking.
<p>A Lady: Why not?
<p>A Gentleman: Because he doesn't row.
<p>A Lady: He doesn't <em>row</em>?
<p>A Gentleman: No. He <em>doesn't</em> row.
<p>A Lady: Ah. I see what you mean.

These elements are semantic elements that just happen to have bold and italic representations by default, but you can style them however you like. For example, in the <em> sample above, you could represent stress emphasis in uppercase instead of italics, but the functional purpose of the <em> element remains the same — to change the context of a sentence by emphasizing specific words or phrases over others:

em {
    font-style: normal;
    text-transform: uppercase;
}

Note that the original answer (below) applied to HTML standards prior to HTML5, in which <strong> and <em> had somewhat different meanings, <b> and <i> were purely presentational and had no semantic meaning whatsoever. Like <strong> and <em> respectively, they have similar presentational defaults but may be styled differently.


You use <strong> and <em> to indicate intense emphasis and normal emphasis respectively.

Or think of it this way: font-weight: bold is closer to <b> than <strong>, and font-style: italic is closer to <i> than <em>. These visual styles are purely visual: tools like screen readers aren't going to understand what bold and italic mean, but some screen readers are able to read <strong> and <em> text in a more emphasized tone.

Is there a way to specify which pytest tests to run from a file?

According to the doc about Run tests by node ids

since you have all node ids in foo.txt, just run

pytest `cat foo.txt | tr '\n' ' '`

this is same with below command (with file content in the question)

pytest tests_directory/foo.py::test_001 tests_directory/bar.py::test_some_other_test

Programmatically select a row in JTable

It is an old post, but I came across this recently

Selecting a specific interval

As @aleroot already mentioned, by using

table.setRowSelectionInterval(index0, index1);

You can specify an interval, which should be selected.

Adding an interval to the existing selection

You can also keep the current selection, and simply add additional rows by using this here

table.getSelectionModel().addSelectionInterval(index0, index1);

This line of code additionally selects the specified interval. It doesn't matter if that interval already is selected, of parts of it are selected.

What's the difference between a 302 and a 307 redirect?

Originally there was just 302

Response What browsers should do
302 Found Redo request with new url

The idea is that:

  • if you were doing a GET at some location, you would redo your GET to the new URL
  • if you were doing a POST at some location, you would redo your POST to the new URL
  • if you were doing a PUT at some location, you would redo your PUT to the new URL
  • if you were doing a DELETE at some location, you would redo your DELETE to the new URL
  • etc

Unfortunately every browser did it wrong. When getting a 302, they would always switch to GET at the new URL, rather than retrying the request with the same verb (e.g., POST):

  • Mosaic did it wrong
  • Netscape copied the bugs in Mosaic; so they got it wrong
  • Internet Explorer copied the bugs in Netscape; so they got it wrong

It became de-facto wrong.

All browsers got 302 wrong. So 303 and 307 were created.

Response What browsers should do What browsers actually do
302 Found Redo request with new url GET with new url
303 See Other GET with new url GET with new url
307 Temporary Redirect Redo request with new url Redo request with new url

In chart form

The 5 different kinds of redirects:

+------------------------------------------------------------+
¦           ¦                Switch to GET?                  ¦
¦           ¦------------------------------------------------¦
¦ Temporary ¦          No            ¦         Yes           ¦
¦-----------+------------------------+-----------------------¦
¦ No        ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes       ¦ 307 Temporary Redirect ¦ 303 See Other         ¦
¦           ¦ 302 Found (intended)   ¦ 302 Found (actual)    ¦
+------------------------------------------------------------+

Alternatively:

Response Switch to get? Temporary?
301 Moved Permanently No No
302 Found (intended) No Yes
302 Found (actual) Yes Yes
303 See Other Yes Yes
307 Temporary Redirect No Yes
308 Permanent Redirect No No

Run .jar from batch-file

cd "Your File Location without inverted commas"

example : cd C:\Users*****\Desktop\directory\target

java -jar myjar.jar

example bat file looks like this:

@echo OFF
cd C:\Users\****\Desktop\directory\target
java -jar myjar.jar

This will work fine.

Format numbers to strings in Python

I've tried this in Python 3.6.9

>>> hours, minutes, seconds = 9, 33, 35
>>> time = f'{hours:02}:{minutes:02}:{seconds:02} {"pm" if hours > 12 else "am"}'
>>> print (time)
09:33:35 am
>>> type(time)

<class 'str'>

jQuery UI - Close Dialog When Clicked Outside

This doesn't use jQuery UI, but does use jQuery, and may be useful for those who aren't using jQuery UI for whatever reason. Do it like so:

function showDialog(){
  $('#dialog').show();
  $('*').on('click',function(e){
    $('#zoomer').hide();
  });
}

$(document).ready(function(){

  showDialog();    

});

So, once I've shown a dialog, I add a click handler that only looks for the first click on anything.

Now, it would be nicer if I could get it to ignore clicks on anything on #dialog and its contents, but when I tried switching $('*') with $(':not("#dialog,#dialog *")'), it still detected #dialog clicks.

Anyway, I was using this purely for a photo lightbox, so it worked okay for that purpose.

How to access Spring MVC model object in javascript file?

I recently faced the same need. So I tried Aurand's way but it seems the code is missing ${}. So the code inside SomeJsp.jsp <head></head>is:

<script>
  var model=[];
  model.paramOne="${model.paramOne}";
  model.paramTwo="${model.paramTwo}";
  model.paramThree="${model.paramThree}";
</script>

Note that you can't asssign using var model = ${model} as it will assign a java object reference. So to access this in external JS:

$(document).ready(function() {
   alert(model.paramOne);
});

Generate insert script for selected records?

In SSMS execute your sql query. From the result window select all cells and copy the values. Goto below website and there you can paste the copied data and generate sql scripts. You can also save results of query from SSMS as CSV file and import the csv file in this website.

http://www.convertcsv.com/csv-to-sql.htm

mongoError: Topology was destroyed

You need to restart mongo to solve the topology error, then just change some options of mongoose or mongoclient to overcome this problem:

var mongoOptions = {
    useMongoClient: true,
    keepAlive: 1,
    connectTimeoutMS: 30000,
    reconnectTries: Number.MAX_VALUE,
    reconnectInterval: 5000,
    useNewUrlParser: true
}

mongoose.connect(mongoDevString,mongoOptions);

how to show lines in common (reverse diff)?

Was asked here before: Unix command to find lines common in two files

You could also try with perl (credit goes here)

perl -ne 'print if ($seen{$_} .= @ARGV) =~ /10$/'  file1 file2

Java and unlimited decimal places?

I believe that you are looking for the java.lang.BigDecimal class.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

enter image description here

I want to change or update my ContactNo to 8018070999 where there is 8018070777 using Case statement

update [Contacts] set contactNo=(case 
when contactNo=8018070777 then 8018070999
else
contactNo
end)

enter image description here

Make docker use IPv4 for port binding

By default, docker uses AF_INET6 sockets which can be used for both IPv4 and IPv6 connections. This causes netstat to report an IPv6 address for the listening address.

From RedHat https://access.redhat.com/solutions/3114021

running a command as a super user from a python script

Try:

subprocess.call(['sudo', 'apach2ctl', 'restart'])

The subprocess needs to access the real stdin/out/err for it to be able to prompt you, and read in your password. If you set them up as pipes, you need to feed the password into that pipe yourself.

If you don't define them, then it grabs sys.stdout, etc...

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

How do I check if a list is empty?

I prefer it explicitly:

if len(li) == 0:
    print('the list is empty')

This way it's 100% clear that li is a sequence (list) and we want to test its size. My problem with if not li: ... is that it gives the false impression that li is a boolean variable.

Fastest way to convert JavaScript NodeList to Array?

In ES6 you can either use:

  • Array.from

    let array = Array.from(nodelist)

  • Spread operator

    let array = [...nodelist]

How to convert datatype:object to float64 in python?

I had this problem in a DataFrame (df) created from an Excel-sheet with several internal header rows.

After cleaning out the internal header rows from df, the columns' values were of "non-null object" type (DataFrame.info()).

This code converted all numerical values of multiple columns to int64 and float64 in one go:

for i in range(0, len(df.columns)):
    df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
    # errors='ignore' lets strings remain as 'non-null objects'

How can I generate an INSERT script for an existing SQL Server table that includes all stored rows?

Yes, but you'll need to run it at the database level.

Right-click the database in SSMS, select "Tasks", "Generate Scripts...". As you work through, you'll get to a "Scripting Options" section. Click on "Advanced", and in the list that pops up, where it says "Types of data to script", you've got the option to select Data and/or Schema.

Screen shot of Advanced Scripting Options

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

Can we rely on String.isEmpty for checking null condition on a String in Java?

Use StringUtils.isEmpty instead, it will also check for null.

Examples are:

 StringUtils.isEmpty(null)      = true
 StringUtils.isEmpty("")        = true
 StringUtils.isEmpty(" ")       = false
 StringUtils.isEmpty("bob")     = false
 StringUtils.isEmpty("  bob  ") = false

See more on official Documentation on String Utils.

How to do error logging in CodeIgniter (PHP)

To simply put a line in the server's error log, use PHP's error_log() function. However, that method will not send an e-mail.

First, to trigger an error:

trigger_error("Error message here", E_USER_ERROR);

By default, this will go in the server's error log file. See the ErrorLog directive for Apache. To set your own log file:

ini_set('error_log', 'path/to/log/file');

Note that the log file you choose must already exist and be writable by the server process. The simplest way to make the file writable is to make the server user the owner of the file. (The server user may be nobody, _www, apache, or something else, depending on your OS distribution.)

To e-mail the error, you need to set up a custom error handler:

function mail_error($errno, $errstr, $errfile, $errline) {
  $message = "[Error $errno] $errstr - Error on line $errline in file $errfile";
  error_log($message); // writes the error to the log file
  mail('[email protected]', 'I have an error', $message);
}
set_error_handler('mail_error', E_ALL^E_NOTICE);

Please see the relevant PHP documentation for more info.

MySQL Trigger after update only if row has changed

You can do this by comparing each field using the NULL-safe equals operator <=> and then negating the result using NOT.

The complete trigger would become:

DROP TRIGGER IF EXISTS `my_trigger_name`;

DELIMITER $$

CREATE TRIGGER `my_trigger_name` AFTER UPDATE ON `my_table_name` FOR EACH ROW 
    BEGIN
        /*Add any fields you want to compare here*/
        IF !(OLD.a <=> NEW.a AND OLD.b <=> NEW.b) THEN
            INSERT INTO `my_other_table` (
                `a`,
                 `b`
            ) VALUES (
                NEW.`a`,
                NEW.`b`
            );
        END IF;
    END;$$

DELIMITER ;

(Based on a different answer of mine.)

How do I delete from multiple tables using INNER JOIN in SQL server

DELETE     TABLE1 LIN
FROM TABLE1 LIN
INNER JOIN TABLE2 LCS ON  CONDITION
WHERE CONDITION