Programs & Examples On #Equivalence

Elegant ways to support equivalence ("equality") in Python classes

You don't have to override both __eq__ and __ne__ you can override only __cmp__ but this will make an implication on the result of ==, !==, < , > and so on.

is tests for object identity. This means a is b will be True in the case when a and b both hold the reference to the same object. In python you always hold a reference to an object in a variable not the actual object, so essentially for a is b to be true the objects in them should be located in the same memory location. How and most importantly why would you go about overriding this behaviour?

Edit: I didn't know __cmp__ was removed from python 3 so avoid it.

How to show loading spinner in jQuery?

$('#message').load('index.php?pg=ajaxFlashcard', null, showResponse);
showLoad();

function showResponse() {
    hideLoad();
    ...
}

http://docs.jquery.com/Ajax/load#urldatacallback

How to pass prepareForSegue: an object

I've implemented a library with a category on UIViewController that simplifies this operation. Basically, you set the parameters you want to pass over in a NSDictionary associated to the UI item that is performing the segue. It works with manual segues too.

For example, you can do

[self performSegueWithIdentifier:@"yourIdentifier" parameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

for a manual segue or create a button with a segue and use

[button setSegueParameters:@{@"customParam1":customValue1, @"customValue2":customValue2}];

If destination view controller is not key-value coding compliant for a key, nothing happens. It works with key-values too (useful for unwind segues). Check it out here https://github.com/stefanomondino/SMQuickSegue

Printing out a linked list using toString

When the JVM tries to run your application, it calls your main method statically; something like this:

LinkedList.main();

That means there is no instance of your LinkedList class. In order to call your toString() method, you can create a new instance of your LinkedList class.

So the body of your main method should be like this:

public static void main(String[] args){
    // creating an instance of LinkedList class
    LinkedList ll = new LinkedList();

    // adding some data to the list
    ll.insertFront(1);
    ll.insertFront(2);
    ll.insertFront(3);
    ll.insertBack(4);

    System.out.println(ll.toString());
}

Find in Files: Search all code in Team Foundation Server

Assuming you have Notepad++, an often-missed feature is 'Find in files', which is extremely fast and comes with filters, regular expressions, replace and all the N++ goodies.

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

node.js require all files in a folder?

Using this function you can require a whole dir.

const GetAllModules = ( dirname ) => {
    if ( dirname ) {
        let dirItems = require( "fs" ).readdirSync( dirname );
        return dirItems.reduce( ( acc, value, index ) => {
            if ( PATH.extname( value ) == ".js" && value.toLowerCase() != "index.js" ) {
                let moduleName = value.replace( /.js/g, '' );
                acc[ moduleName ] = require( `${dirname}/${moduleName}` );
            }
            return acc;
        }, {} );
    }
}

// calling this function.

let dirModules = GetAllModules(__dirname);

How to decrypt an encrypted Apple iTunes iPhone backup?

Sorry, but it might even be more complicated, involving pbkdf2, or even a variation of it. Listen to the WWDC 2010 session #209, which mainly talks about the security measures in iOS 4, but also mentions briefly the separate encryption of backups and how they're related.

You can be pretty sure that without knowing the password, there's no way you can decrypt it, even by brute force.

Let's just assume you want to try to enable people who KNOW the password to get to the data of their backups.

I fear there's no way around looking at the actual code in iTunes in order to figure out which algos are employed.

Back in the Newton days, I had to decrypt data from a program and was able to call its decryption function directly (knowing the password, of course) without the need to even undersand its algorithm. It's not that easy anymore, unfortunately.

I'm sure there are skilled people around who could reverse engineer that iTunes code - you just have to get them interested.

In theory, Apple's algos should be designed in a way that makes the data still safe (i.e. practically unbreakable by brute force methods) to any attacker knowing the exact encryption method. And in WWDC session 209 they went pretty deep into details about what they do to accomplish this. Maybe you can actually get answers directly from Apple's security team if you tell them your good intentions. After all, even they should know that security by obfuscation is not really efficient. Try their security mailing list. Even if they do not repond, maybe someone else silently on the list will respond with some help.

Good luck!

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

How to deploy a Java Web Application (.war) on tomcat?

Log in :URL = "localhost:8080/" Enter username and pass word Click Manager App Scroll Down and find "WAR file to deploy" Chose file and click deploy

Done

Go to Webapp folder of you Apache tomcat you will see a folder name matching with your war file name.

Type link in your url address bar:: localhost:8080/HelloWorld/HelloWorld.html and press enter

Done

CertPathValidatorException : Trust anchor for certificate path not found - Retrofit Android

DISCLAIMER: this answer is from Jul 2015 and uses Retrofit and OkHttp from that time.
Check this link for more info on Retrofit v2 and this one for the current OkHttp methods.

Okay, I got it working using Android Developers guide.

Just as OP, I'm trying to use Retrofit and OkHttp to connect to a self-signed SSL-enabled server.

Here's the code that got things working (I've removed the try/catch blocks):

public static RestAdapter createAdapter(Context context) {
  // loading CAs from an InputStream
  CertificateFactory cf = CertificateFactory.getInstance("X.509");
  InputStream cert = context.getResources().openRawResource(R.raw.my_cert);
  Certificate ca;
  try {
    ca = cf.generateCertificate(cert);
  } finally { cert.close(); }

  // creating a KeyStore containing our trusted CAs
  String keyStoreType = KeyStore.getDefaultType();
  KeyStore keyStore = KeyStore.getInstance(keyStoreType);
  keyStore.load(null, null);
  keyStore.setCertificateEntry("ca", ca);

  // creating a TrustManager that trusts the CAs in our KeyStore
  String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
  TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
  tmf.init(keyStore);

  // creating an SSLSocketFactory that uses our TrustManager
  SSLContext sslContext = SSLContext.getInstance("TLS");
  sslContext.init(null, tmf.getTrustManagers(), null);

  // creating an OkHttpClient that uses our SSLSocketFactory
  OkHttpClient okHttpClient = new OkHttpClient();
  okHttpClient.setSslSocketFactory(sslContext.getSocketFactory());

  // creating a RestAdapter that uses this custom client
  return new RestAdapter.Builder()
              .setEndpoint(UrlRepository.API_BASE)
              .setClient(new OkClient(okHttpClient))
              .build();
}

To help in debugging, I also added .setLogLevel(RestAdapter.LogLevel.FULL) to my RestAdapter creation commands and I could see it connecting and getting the response from the server.

All it took was my original .crt file saved in main/res/raw. The .crt file, aka the certificate, is one of the two files created when you create a certificate using openssl. Generally, it is a .crt or .cert file, while the other is a .key file.

Afaik, the .crt file is your public key and the .key file is your private key.

As I can see, you already have a .cert file, which is the same, so try to use it.


PS: For those that read it in the future and only have a .pem file, according to this answer, you only need this to convert one to the other:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

PS²: For those that don't have any file at all, you can use the following command (bash) to extract the public key (aka certificate) from any server:

echo -n | openssl s_client -connect your.server.com:443 | \
  sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ~/my_cert.crt

Just replace the your.server.com and the port (if it is not standard HTTPS) and choose a valid path for your output file to be created.

How to NodeJS require inside TypeScript file?

The correct syntax is:

import sampleModule = require('modulename');

or

import * as sampleModule from 'modulename';

Then compile your TypeScript with --module commonjs.

If the package doesn't come with an index.d.ts file and its package.json doesn't have a "typings" property, tsc will bark that it doesn't know what 'modulename' refers to. For this purpose you need to find a .d.ts file for it on http://definitelytyped.org/, or write one yourself.

If you are writing code for Node.js you will also want the node.d.ts file from http://definitelytyped.org/.

Refused to load the script because it violates the following Content Security Policy directive

It was solved with:

script-src 'self' http://xxxx 'unsafe-inline' 'unsafe-eval';

How can I kill all sessions connecting to my oracle database?

I found the below snippet helpful. Taken from: http://jeromeblog-jerome.blogspot.com/2007/10/how-to-unlock-record-on-oracle.html

select
owner||'.'||object_name obj ,
oracle_username||' ('||s.status||')' oruser ,
os_user_name osuser ,
machine computer ,
l.process unix ,
s.sid||','||s.serial# ss ,
r.name rs ,
to_char(s.logon_time,'yyyy/mm/dd hh24:mi:ss') time
from v$locked_object l ,
dba_objects o ,
v$session s ,
v$transaction t ,
v$rollname r
where l.object_id = o.object_id
and s.sid=l.session_id
and s.taddr=t.addr
and t.xidusn=r.usn
order by osuser, ss, obj
;

Then ran:

Alter System Kill Session '<value from ss above>'
;

To kill individual sessions.

How to darken an image on mouseover?

Create black png with lets say 50% transparency. Overlay this on mouseover.

Load image from resources

You can add an image resource in the project then (right click on the project and choose the Properties item) access that in this way:

this.picturebox.image = projectname.properties.resources.imagename;

Finding import static statements for Mockito constructs

The problem is that static imports from Hamcrest and Mockito have similar names, but return Matchers and real values, respectively.

One work-around is to simply copy the Hamcrest and/or Mockito classes and delete/rename the static functions so they are easier to remember and less show up in the auto complete. That's what I did.

Also, when using mocks, I try to avoid assertThat in favor other other assertions and verify, e.g.

assertEquals(1, 1);
verify(someMock).someMethod(eq(1));

instead of

assertThat(1, equalTo(1));
verify(someMock).someMethod(eq(1));

If you remove the classes from your Favorites in Eclipse, and type out the long name e.g. org.hamcrest.Matchers.equalTo and do CTRL+SHIFT+M to 'Add Import' then autocomplete will only show you Hamcrest matchers, not any Mockito matchers. And you can do this the other way so long as you don't mix matchers.

How do I use the CONCAT function in SQL Server 2008 R2?

CONCAT is new to SQL Server 2012. The link you gave makes this clear, it is not a function on Previous Versions, including 2008 R2.

That it is part of SQL Server 2012 can be seen in the document tree:

SQL Server 2012  
Product Documentation  
Books Online for SQL Server 2012  
Database Engine  
  Transact-SQL Reference (Database Engine)  
    Built-in Functions (Transact-SQL)  
      String Functions (Transact-SQL)  

EDIT Martin Smith helpfully points out that SQL Server provides an implementation of ODBC's CONCAT function.

How to detect scroll direction

You can use this simple plugin to add scrollUp and scrollDown to your jQuery

https://github.com/phpust/JQueryScrollDetector

var lastScrollTop = 0;
var action = "stopped";
var timeout = 100;
// Scroll end detector:
$.fn.scrollEnd = function(callback, timeout) {    
      $(this).scroll(function(){
        // get current scroll top 
        var st = $(this).scrollTop();
        var $this = $(this);
        // fix for page loads
        if (lastScrollTop !=0 )
        {
            // if it's scroll up
            if (st < lastScrollTop){
                action = "scrollUp";
            } 
            // else if it's scroll down
            else if (st > lastScrollTop){
                action = "scrollDown";
            }
        }
        // set the current scroll as last scroll top
        lastScrollTop = st;
        // check if scrollTimeout is set then clear it
        if ($this.data('scrollTimeout')) {
          clearTimeout($this.data('scrollTimeout'));
        }
        // wait until timeout done to overwrite scrolls output
        $this.data('scrollTimeout', setTimeout(callback,timeout));
    });
};

$(window).scrollEnd(function(){
    if(action!="stopped"){
        //call the event listener attached to obj.
        $(document).trigger(action); 
    }
}, timeout);

Run AVD Emulator without Android Studio

If you are on windows then create a .bat file and just double click that .bat file which will save you some time every day. Here is my code to launch android Emulator with use of batch file:

@echo off
title Android Emulator
color 1b
echo #################################

echo Please make sure that your android path is correct for the script
echo Change this path "C:\Users\YOUR_USER_NAME\AppData\Local\Android\Sdk\emulator" to use your curret path and save it as a .bat file on your system to launch android emulator
echo #################################
c:
cd C:\Users\YOUR_USER_NAME\AppData\Local\Android\Sdk\emulator
emulator -avd Nexus_5X_API_28

pause

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

How should I set the default proxy to use default credentials?

This is the new suggested method.

WebRequest.GetSystemWebProxy();

How to get public directory?

You can use base_path() to get the base of your application - and then just add your public folder to that:

$path = base_path().'/public';
return File::put($path , $data)

Note: Be very careful about allowing people to upload files into your root of public_html. If they upload their own index.php file, they will take over your site.

Cache an HTTP 'Get' service response in AngularJS?

angularBlogServices.factory('BlogPost', ['$resource',
    function($resource) {
        return $resource("./Post/:id", {}, {
            get:    {method: 'GET',    cache: true,  isArray: false},
            save:   {method: 'POST',   cache: false, isArray: false},
            update: {method: 'PUT',    cache: false, isArray: false},
            delete: {method: 'DELETE', cache: false, isArray: false}
        });
    }]);

set cache to be true.

Why is the console window closing immediately once displayed my output?

This behaves the same for CtrlF5 or F5. Place immediately before end of Main method.

using System.Diagnostics;

private static void Main(string[] args) {

  DoWork();
  
  if (Debugger.IsAttached) {
    Console.WriteLine("Press any key to continue . . .");
    Console.ReadKey();
  }
}

Django - filtering on foreign key properties

Asset.objects.filter( project__name__contains="Foo" )

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

How do I get the value of a registry key and ONLY the value using powershell

Given a key \SQL with two properties:

enter image description here

I'd grab the "MSSQLSERVER" one with the following in-cases where I wasn't sure what the property name was going to be to use dot-notation:

$regkey_property_name = 'MSSQLSERVER'
$regkey = get-item -Path 'HKLM:\Software\Microsoft\Microsoft SQL Server\Instance Names\SQL'
$regkey.GetValue($regkey_property_name)

How to move the cursor word by word in the OS X Terminal

Under iterm2's Preferences > Profile > Keys, you click the + below Key Mappings and record a new shortcut. For Action, select Send Escape Sequence and type b or f for backwards and forwards respectively.

When I tried to record one for (Ctrl+?), I noticed in the Keyboard Shortcut field that the arrow never showed up. Turns out I had to disable the default mac's System Preferences > Keyboard > Shortcuts > Mission Control shorcuts first to get things to work, as they'll override iterm2's default shortcuts. Should be true for the standard terminal app, too.

Keyboard system preferences

How do I launch the Android emulator from the command line?

List all your emulators:

emulator -list-avds

Run one of the listed emulators with -avd flag:

emulator -avd @name-of-your-emulator

where emulator is under:

${ANDROID_SDK}/tools/emulator

Making button go full-width?

<div class="col-md-9">
    <button class="btn btn-block btn-primary" type="button">Block level button</button>
</div>

In Bootstrap 3, this should be all you need. I believe btn-large was overriding the width of btn-block.

Should I use `import os.path` or `import os`?

Couldn't find any definitive reference, but I see that the example code for os.walk uses os.path but only imports os

Get Max value from List<myType>

thelist.Max(e => e.age);

Difference between <span> and <div> with text-align:center;?

It might be, because your span element sets is side as width as its content. if you have a div with 500px width and text-align center, and you enter a span tag it should be aligned in the center. So your problem might be a CSS one. Install Firebug at Firefox and check the style attributes your span or div object has.

Understanding Spring @Autowired usage

Yes, you can configure the Spring servlet context xml file to define your beans (i.e., classes), so that it can do the automatic injection for you. However, do note, that you have to do other configurations to have Spring up and running and the best way to do that, is to follow a tutorial ground up.

Once you have your Spring configured probably, you can do the following in your Spring servlet context xml file for Example 1 above to work (please replace the package name of com.movies to what the true package name is and if this is a 3rd party class, then be sure that the appropriate jar file is on the classpath) :

<beans:bean id="movieFinder" class="com.movies.MovieFinder" />

or if the MovieFinder class has a constructor with a primitive value, then you could something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg value="100" />
</beans:bean>

or if the MovieFinder class has a constructor expecting another class, then you could do something like this,

<beans:bean id="movieFinder" class="com.movies.MovieFinder" >
    <beans:constructor-arg ref="otherBeanRef" />
</beans:bean>

...where 'otherBeanRef' is another bean that has a reference to the expected class.

virtualenvwrapper and Python 3

On Ubuntu; using mkvirtualenv -p python3 env_name loads the virtualenv with python3.

Inside the env, use python --version to verify.

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

You could use moment.js with Postman to give you that timestamp format.

You can add this to the pre-request script:

const moment = require('moment');
pm.globals.set("today", moment().format("MM/DD/YYYY"));

Then reference {{today}} where ever you need it.

If you add this to the Collection Level Pre-request Script, it will be run for each request in the Collection. Rather than needing to add it to all the requests individually.

For more information about using moment in Postman, I wrote a short blog post: https://dannydainton.com/2018/05/21/hold-on-wait-a-moment/

What is difference between Axios and Fetch?

In addition... I was playing around with various libs in my test and noticed their different handling of 4xx requests. In this case my test returns a json object with a 400 response. This is how 3 popular libs handle the response:

// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);
console.log(res.error)


// node-fetch
const body = await fetch(url)
console.log(await body.json())


// Axios
const body = axios.get(url)
const res = await t.throws(body);
console.log(res.response.data)

Of interest is that request-promise-native and axios throw on 4xx response while node-fetch doesn't. Also fetch uses a promise for json parsing.

How to ignore the first line of data when processing CSV data?

Python 2.x

csvreader.next()

Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

csv_data = csv.reader(open('sample.csv'))
csv_data.next() # skip first row
for row in csv_data:
    print(row) # should print second row

Python 3.x

csvreader.__next__()

Return the next row of the reader’s iterable object as a list (if the object was returned from reader()) or a dict (if it is a DictReader instance), parsed according to the current dialect. Usually you should call this as next(reader).

csv_data = csv.reader(open('sample.csv'))
csv_data.__next__() # skip first row
for row in csv_data:
    print(row) # should print second row

process.waitFor() never returns

I would like to add something to the previous answers but since I don't have the rep to comment, I will just add an answer. This is directed towards android users which are programming in Java.

Per the post from RollingBoy, this code almost worked for me:

Process process = Runtime.getRuntime().exec("tasklist");
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((reader.readLine()) != null) {}
process.waitFor();

In my case, the waitFor() was not releasing because I was executing a statement with no return ("ip adddr flush eth0"). An easy way to fix this is to simply ensure you always return something in your statement. For me, that meant executing the following: "ip adddr flush eth0 && echo done". You can read the buffer all day, but if there is nothing ever returned, your thread will never release its wait.

Hope that helps someone!

Finding rows containing a value (or values) in any column

If you want to find the rows that have any of the values in a vector, one option is to loop the vector (lapply(v1,..)), create a logical index of (TRUE/FALSE) with (==). Use Reduce and OR (|) to reduce the list to a single logical matrix by checking the corresponding elements. Sum the rows (rowSums), double negate (!!) to get the rows with any matches.

indx1 <- !!rowSums(Reduce(`|`, lapply(v1, `==`, df)), na.rm=TRUE)

Or vectorise and get the row indices with which with arr.ind=TRUE

indx2 <- unique(which(Vectorize(function(x) x %in% v1)(df),
                                     arr.ind=TRUE)[,1])

Benchmarks

I didn't use @kristang's solution as it is giving me errors. Based on a 1000x500 matrix, @konvas's solution is the most efficient (so far). But, this may vary if the number of rows are increased

val <- paste0('M0', 1:1000)
set.seed(24)
df1 <- as.data.frame(matrix(sample(c(val, NA), 1000*500, 
  replace=TRUE), ncol=500), stringsAsFactors=FALSE) 
set.seed(356)
v1 <- sample(val, 200, replace=FALSE)

 konvas <- function() {apply(df1, 1, function(r) any(r %in% v1))}
 akrun1 <- function() {!!rowSums(Reduce(`|`, lapply(v1, `==`, df1)),
               na.rm=TRUE)}
 akrun2 <- function() {unique(which(Vectorize(function(x) x %in% 
              v1)(df1),arr.ind=TRUE)[,1])}


 library(microbenchmark)
 microbenchmark(konvas(), akrun1(), akrun2(), unit='relative', times=20L)
 #Unit: relative
 #   expr       min         lq       mean     median         uq      max   neval
 # konvas()   1.00000   1.000000   1.000000   1.000000   1.000000  1.00000    20
 # akrun1() 160.08749 147.642721 125.085200 134.491722 151.454441 52.22737    20
 # akrun2()   5.85611   5.641451   4.676836   5.330067   5.269937  2.22255    20
 # cld
 #  a 
 #  b
 #  a 

For ncol = 10, the results are slighjtly different:

expr       min        lq     mean    median        uq       max    neval
 konvas()  3.116722  3.081584  2.90660  2.983618  2.998343  2.394908    20
 akrun1() 27.587827 26.554422 22.91664 23.628950 21.892466 18.305376    20
 akrun2()  1.000000  1.000000  1.00000  1.000000  1.000000  1.000000    20

data

 v1 <- c('M017', 'M018')
 df <- structure(list(datetime = c("04.10.2009 01:24:51",
"04.10.2009 01:24:53", 
"04.10.2009 01:24:54", "04.10.2009 01:25:06", "04.10.2009 01:25:07", 
"04.10.2009 01:26:07", "04.10.2009 01:26:27", "04.10.2009 01:27:23", 
"04.10.2009 01:27:30", "04.10.2009 01:27:32", "04.10.2009 01:27:34"
), col1 = c("M017", "M018", "M051", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "M017", "M051"), col2 = c("<NA>", "<NA>", "<NA>", 
"M016", "M015", "M017", "M017", "M017", "M017", "<NA>", "<NA>"
), col3 = c("<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", "<NA>", 
"<NA>", "<NA>", "<NA>", "<NA>"), col4 = c(NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA)), .Names = c("datetime", "col1", "col2", 
"col3", "col4"), class = "data.frame", row.names = c("1", "2", 
"3", "4", "5", "6", "7", "8", "9", "10", "11"))

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

CREATE FUNCTION [dbo].[_ICAN_FN_IntToTime](@Num INT)
  RETURNS NVARCHAR(13)
AS
-------------------------------------------------------------------------------------------------------------------
--INVENTIVE:Keyvan ARYAEE-MOEEN
-------------------------------------------------------------------------------------------------------------------
  BEGIN
    DECLARE @Hour VARCHAR(10)=CAST(@Num/3600 AS  VARCHAR(2))
    DECLARE @Minute VARCHAR(10)=CAST((@Num-@Hour*3600)/60 AS  VARCHAR(2))
    DECLARE @Time VARCHAR(13)=CASE WHEN @Hour<10 THEN '0'+@Hour ELSE @Hour END+':'+CASE WHEN @Minute<10 THEN '0'+@Minute ELSE @Minute END+':00.000'
    RETURN @Time
  END
-------------------------------------------------------------------------------------------------------------------
--SELECT dbo._ICAN_FN_IntToTime(25500)
-------------------------------------------------------------------------------------------------------------------

What is the purpose of shuffling and sorting phase in the reducer in Map Reduce Programming?

Let's revisit key phases of Mapreduce program.

The map phase is done by mappers. Mappers run on unsorted input key/values pairs. Each mapper emits zero, one, or multiple output key/value pairs for each input key/value pairs.

The combine phase is done by combiners. The combiner should combine key/value pairs with the same key. Each combiner may run zero, once, or multiple times.

The shuffle and sort phase is done by the framework. Data from all mappers are grouped by the key, split among reducers and sorted by the key. Each reducer obtains all values associated with the same key. The programmer may supply custom compare functions for sorting and a partitioner for data split.

The partitioner decides which reducer will get a particular key value pair.

The reducer obtains sorted key/[values list] pairs, sorted by the key. The value list contains all values with the same key produced by mappers. Each reducer emits zero, one or multiple output key/value pairs for each input key/value pair.

Have a look at this javacodegeeks article by Maria Jurcovicova and mssqltips article by Datta for a better understanding

Below is the image from safaribooksonline article

enter image description here

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

In my case it happened when calling a function by passing a parameter of a Core Data managed object's property. At the time of calling the object was no longer existed, and that caused this error.

I have solved the issue by checking if the managed object exists or not before calling the function.

How to remove all files from directory without removing directory in Node.js

Building on @Waterscroll's response, if you want to use async and await in node 8+:

const fs = require('fs');
const util = require('util');
const readdir = util.promisify(fs.readdir);
const unlink = util.promisify(fs.unlink);
const directory = 'test';

async function toRun() {
  try {
    const files = await readdir(directory);
    const unlinkPromises = files.map(filename => unlink(`${directory}/${filename}`));
    return Promise.all(unlinkPromises);
  } catch(err) {
    console.log(err);
  }
}

toRun();

How to force maven update?

What maven does is, it downloads all your project's dependencies into your local repo (.m2 folder). Because of the internet causing issues with your local repo, you project is facing problems. I am not sure if this will surely help you or not but you can try deleting all the files within the repository folder inside the .m2 folder. Since there would be nothing in the local repo, maven would be forced to download the dependencies again, thus forcing an update. Generally, the .m2 folder is located at c:users:[username]:.m2

How to enable zoom controls and pinch zoom in a WebView?

To enable zoom controls in a WebView, add the following line:

webView.getSettings().setBuiltInZoomControls(true);

With this line of code, you get the zoom enabled in your WebView, if you want to remove the zoom in and zoom out buttons provided, add the following line of code:

webView.getSettings().setDisplayZoomControls(false);

Python: AttributeError: '_io.TextIOWrapper' object has no attribute 'split'

Try this:

 >>> f = open('goodlines.txt')
 >>> mylist = f.readlines()

open() function returns a file object. And for file object, there is no method like splitlines() or split(). You could use dir(f) to see all the methods of file object.

Gulp command not found after install

I got this working on Win10 using a combination of the answers from above and elsewhere. Posting here for others and future me.

I followed the instructions from here: https://gulpjs.com/docs/en/getting-started/quick-start but on the last step after typing gulp --version I got the message -bash: gulp: command not found

To fix this:

  1. I added %AppData%\npm to my Path environment variable
  2. Closed all gitbash (cmd, powershell, etc...) and restarted gitbash.
  3. Then gulp --version worked

Also, found the below for reasons why not to install gulp globally and how to remove it (not sure if this is advisable though):

what does gulp-"cli" stands for?

How to uninstall Gulp CLI from NPM globally?

Simple way to encode a string according to a password?

I'll give 4 solutions:

1) Using Fernet encryption with cryptography library

Here is a solution using the package cryptography, that you can install as usual with pip install cryptography:

import base64
from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC

def cipherFernet(password):
    key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'abcd', iterations=1000, backend=default_backend()).derive(password)
    return Fernet(base64.urlsafe_b64encode(key))

def encrypt1(plaintext, password):
    return cipherFernet(password).encrypt(plaintext)

def decrypt1(ciphertext, password):
    return cipherFernet(password).decrypt(ciphertext)

# Example:

print(encrypt1(b'John Doe', b'mypass'))  
# b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg=='
print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'mypass')) 
# b'John Doe'
try:  # test with a wrong password
    print(decrypt1(b'gAAAAABd53tHaISVxFO3MyUexUFBmE50DUV5AnIvc3LIgk5Qem1b3g_Y_hlI43DxH6CiK4YjYHCMNZ0V0ExdF10JvoDw8ejGjg==', b'wrongpass')) 
except InvalidToken:
    print('Wrong password')

You can adapt with your own salt, iteration count, etc. This code is not very far from @HCLivess's answer but the goal is here to have ready-to-use encrypt and decrypt functions. Source: https://cryptography.io/en/latest/fernet/#using-passwords-with-fernet.

Note: use .encode() and .decode() everywhere if you want strings 'John Doe' instead of bytes like b'John Doe'.


2) Simple AES encryption with Crypto library

This works with Python 3:

import base64
from Crypto import Random
from Crypto.Hash import SHA256
from Crypto.Cipher import AES

def cipherAES(password, iv):
    key = SHA256.new(password).digest()
    return AES.new(key, AES.MODE_CFB, iv)

def encrypt2(plaintext, password):
    iv = Random.new().read(AES.block_size)
    return base64.b64encode(iv + cipherAES(password, iv).encrypt(plaintext))

def decrypt2(ciphertext, password):
    d = base64.b64decode(ciphertext)
    iv, ciphertext = d[:AES.block_size], d[AES.block_size:]
    return cipherAES(password, iv).decrypt(ciphertext)

# Example:    

print(encrypt2(b'John Doe', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'mypass'))
print(decrypt2(b'B/2dGPZTD8V22cIVKfp2gD2tTJG/UfP/', b'wrongpass'))  # wrong password: no error, but garbled output

Note: you can remove base64.b64encode and .b64decode if you don't want text-readable output and/or if you want to save the ciphertext to disk as a binary file anyway.


3) AES using a better password key derivation function and the ability to test if "wrong password entered", with Crypto library

The solution 2) with AES "CFB mode" is ok, but has two drawbacks: the fact that SHA256(password) can be easily bruteforced with a lookup table, and that there is no way to test if a wrong password has been entered. This is solved here by the use of AES in "GCM mode", as discussed in AES: how to detect that a bad password has been entered? and Is this method to say “The password you entered is wrong” secure?:

import Crypto.Random, Crypto.Protocol.KDF, Crypto.Cipher.AES

def cipherAES_GCM(pwd, nonce):
    key = Crypto.Protocol.KDF.PBKDF2(pwd, nonce, count=100000)
    return Crypto.Cipher.AES.new(key, Crypto.Cipher.AES.MODE_GCM, nonce=nonce, mac_len=16)

def encrypt3(plaintext, password):
    nonce = Crypto.Random.new().read(16)
    return nonce + b''.join(cipherAES_GCM(password, nonce).encrypt_and_digest(plaintext))  # you case base64.b64encode it if needed

def decrypt3(ciphertext, password):
    nonce, ciphertext, tag = ciphertext[:16], ciphertext[16:len(ciphertext)-16], ciphertext[-16:]
    return cipherAES_GCM(password, nonce).decrypt_and_verify(ciphertext, tag)

# Example:

print(encrypt3(b'John Doe', b'mypass'))
print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'mypass'))
try:
    print(decrypt3(b'\xbaN_\x90R\xdf\xa9\xc7\xd6\x16/\xbb!\xf5Q\xa9]\xe5\xa5\xaf\x81\xc3\n2e/("I\xb4\xab5\xa6ezu\x8c%\xa50', b'wrongpass'))
except ValueError:
    print("Wrong password")

4) Using RC4 (no library needed)

Adapted from https://github.com/bozhu/RC4-Python/blob/master/rc4.py.

def PRGA(S):
    i = 0
    j = 0
    while True:
        i = (i + 1) % 256
        j = (j + S[i]) % 256
        S[i], S[j] = S[j], S[i]
        yield S[(S[i] + S[j]) % 256]

def encryptRC4(plaintext, key, hexformat=False):
    key, plaintext = bytearray(key), bytearray(plaintext)  # necessary for py2, not for py3
    S = list(range(256))
    j = 0
    for i in range(256):
        j = (j + S[i] + key[i % len(key)]) % 256
        S[i], S[j] = S[j], S[i]
    keystream = PRGA(S)
    return b''.join(b"%02X" % (c ^ next(keystream)) for c in plaintext) if hexformat else bytearray(c ^ next(keystream) for c in plaintext)

print(encryptRC4(b'John Doe', b'mypass'))                           # b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a'
print(encryptRC4(b'\x88\xaf\xc1\x04\x8b\x98\x18\x9a', b'mypass'))   # b'John Doe'

(Outdated since the latest edits, but kept for future reference): I had problems using Windows + Python 3.6 + all the answers involving pycrypto (not able to pip install pycrypto on Windows) or pycryptodome (the answers here with from Crypto.Cipher import XOR failed because XOR is not supported by this pycrypto fork ; and the solutions using ... AES failed too with TypeError: Object type <class 'str'> cannot be passed to C code). Also, the library simple-crypt has pycrypto as dependency, so it's not an option.

What are the dark corners of Vim your mom never told you about?

My favourite recipe to switch back and forth between windows:

function! SwitchPrevWin()
    let l:winnr_index = winnr()
    if l:winnr_index > 1
       let l:winnr_index -= 1
    else
       "set winnr_index to max window open
        let l:winnr_index = winnr('$')
    endif
    exe l:winnr_index . "wincmd w" 
endfunction

nmap <M-z> :call SwitchPrevWin()
imap <M-z> <ESC>:call SwitchPrevWin()

nmap <C-z> :wincmd w
imap <C-z> <ESC>:wincmd w

Add a prefix string to beginning of each line

While I don't think pierr had this concern, I needed a solution that would not delay output from the live "tail" of a file, since I wanted to monitor several alert logs simultaneously, prefixing each line with the name of its respective log.

Unfortunately, sed, cut, etc. introduced too much buffering and kept me from seeing the most current lines. Steven Penny's suggestion to use the -s option of nl was intriguing, and testing proved that it did not introduce the unwanted buffering that concerned me.

There were a couple of problems with using nl, though, related to the desire to strip out the unwanted line numbers (even if you don't care about the aesthetics of it, there may be cases where using the extra columns would be undesirable). First, using "cut" to strip out the numbers re-introduces the buffering problem, so it wrecks the solution. Second, using "-w1" doesn't help, since this does NOT restrict the line number to a single column - it just gets wider as more digits are needed.

It isn't pretty if you want to capture this elsewhere, but since that's exactly what I didn't need to do (everything was being written to log files already, I just wanted to watch several at once in real time), the best way to lose the line numbers and have only my prefix was to start the -s string with a carriage return (CR or ^M or Ctrl-M). So for example:

#!/bin/ksh

# Monitor the widget, framas, and dweezil
# log files until the operator hits <enter>
# to end monitoring.

PGRP=$$

for LOGFILE in widget framas dweezil
do
(
    tail -f $LOGFILE 2>&1 |
    nl -s"^M${LOGFILE}>  "
) &
sleep 1
done

read KILLEM

kill -- -${PGRP}

Raw SQL Query without DbSet - Entity Framework Core

It depends if you're using EF Core 2.1 or EF Core 3 and higher versions.

If you're using EF Core 2.1

If you're using EF Core 2.1 Release Candidate 1 available since 7 may 2018, you can take advantage of the proposed new feature which is Query type.

What is query type?

In addition to entity types, an EF Core model can contain query types, which can be used to carry out database queries against data that isn't mapped to entity types.

When to use query type?

Serving as the return type for ad hoc FromSql() queries.

Mapping to database views.

Mapping to tables that do not have a primary key defined.

Mapping to queries defined in the model.

So you no longer need to do all the hacks or workarounds proposed as answers to your question. Just follow these steps:

First you defined a new property of type DbQuery<T> where T is the type of the class that will carry the column values of your SQL query. So in your DbContext you'll have this:

public DbQuery<SomeModel> SomeModels { get; set; }

Secondly use FromSql method like you do with DbSet<T>:

var result = context.SomeModels.FromSql("SQL_SCRIPT").ToList();
var result = await context.SomeModels.FromSql("SQL_SCRIPT").ToListAsync();

Also note that DdContexts are partial classes, so you can create one or more separate files to organize your 'raw SQL DbQuery' definitions as best suits you.


If you're using EF Core 3.0 and higher versions

Query type is now known as Keyless entity type. As said above query types were introduced in EF Core 2.1. If you're using EF Core 3.0 or higher version you should now consider using keyless entity types because query types are now marked as obsolete.

This feature was added in EF Core 2.1 under the name of query types. In EF Core 3.0 the concept was renamed to keyless entity types. The [Keyless] Data Annotation became available in EFCore 5.0.

We still have the same scenarios as for query types for when to use keyless entity type.

So to use it you need to first mark your class SomeModel with [Keyless] data annotation or through fluent configuration with .HasNoKey() method call like below:

public DbSet<SomeModel> SomeModels { get; set; }

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeModel>().HasNoKey();
}

After that configuration, you can use one of the methods explained here to execute your SQL query. For example you can use this one:

var result = context.SomeModels.FromSqlRaw("SQL SCRIPT").ToList();

Accessing JSON elements

import json
weather = urllib2.urlopen('url')
wjson = weather.read()
wjdata = json.loads(wjson)
print wjdata['data']['current_condition'][0]['temp_C']

What you get from the url is a json string. And your can't parse it with index directly. You should convert it to a dict by json.loads and then you can parse it with index.

Instead of using .read() to intermediately save it to memory and then read it to json, allow json to load it directly from the file:

wjdata = json.load(urllib2.urlopen('url'))

Class 'ViewController' has no initializers in swift

if you lost a "!" in your code ,like this code below, you'll also get this error.

import UIKit

class MemeDetailViewController : UIViewController {

    @IBOutlet weak var memeImage: UIImageView!

    var meme:Meme! // lost"!"

    override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)
        self.memeImage!.image = meme.memedImage
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
    }

}

Catch KeyError in Python

You can also try to use get(), for example:

connection = manager.connect.get("I2Cx")

which won't raise a KeyError in case the key doesn't exist.

You may also use second argument to specify the default value, if the key is not present.

Avoid duplicates in INSERT INTO SELECT query in SQL Server

A little off topic, but if you want to migrate the data to a new table, and the possible duplicates are in the original table, and the column possibly duplicated is not an id, a GROUP BY will do:

INSERT INTO TABLE_2
(name)
  SELECT t1.name
  FROM TABLE_1 t1
  GROUP BY t1.name

How to make a JFrame Modal in Swing java

As others mentioned, you could use JDialog. If you don't have access to the parent frame or you want to freeze the hole application just pass null as a parent:

final JDialog frame = new JDialog((JFrame)null, frameTitle, true); frame.setModal(true);
frame.getContentPane().add(panel);
frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
frame.pack();
frame.setVisible(true);

Java: how do I check if a Date is within a certain range?

An easy way is to convert the dates into milliseconds after January 1, 1970 (use Date.getTime()) and then compare these values.

How to check the presence of php and apache on ubuntu server through ssh

Another way to find out if a program is installed is by using the which command. It will show the path of the program you're searching for. For example if when your searching for apache you can use the following command:

$ which apache2ctl
/usr/sbin/apache2ctl

And if you searching for PHP try this:

$ which php
/usr/bin/php

If the which command doesn't give any result it means the software is not installed (or is not in the current $PATH):

$ which php
$

Setting maxlength of textbox with JavaScript or jQuery

<head>
    <script type="text/javascript">
        function SetMaxLength () {
            var input = document.getElementById ("myInput");
            input.maxLength = 10;
        }
    </script>
</head>
<body>
    <input id="myInput" type="text" size="20" />
</body>

Problems with a PHP shell script: "Could not open input file"

Have you tried:

#!/usr/local/bin/php

I.e. without the -q part? That's what the error message "Could not open input file: -q" means. The first argument to php if it doesn't look like an option is the name of the PHP file to execute, and -q is CGI only.

EDIT: A couple of (non-related) tips:

  1. You don't need to terminate the last block of PHP with ?>. In fact, it is often better not to.
  2. When executed on the command line, PHP defines the global constant STDIN to fopen("php://stdin", "r"). You can use that instead of opening "php://stdin" a second time: $fd = STDIN;

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token

Same issue:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.UUID` out of START_OBJECT token

What caused it was the following:

ResponseEntity<UUID> response = restTemplate.postForEntity("/example/", null, UUID.class);

In my test I purposely set the request as null (no content POST). As previously mentioned, the cause for the OP was the same because the request didn't contain a valid JSON, so it couldn't be automatically identified as an application/json request which was the limitation on the server (consumes = "application/json"). A valid JSON request would be. What fixed it was populating an entity with null body and json headers explicitly.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity request = new HttpEntity<>(null, headers);
ResponseEntity<UUID> response = restTemplate.postForEntity("/example/", request, UUID.class);

background: fixed no repeat not working on mobile

I have found a great solution for fixed backgrounds on mobile devices requiring no JavaScript at all.

body:before {
  content: "";
  display: block;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  z-index: -10;
  background: url(photos/2452.jpg) no-repeat center center;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}

Please be aware of the negative z-index value of -10. html root element default z-index is 0. This value must be the smallest z-index to have it as background.

How to enable TLS 1.2 support in an Android application (running on Android 4.1 JB)

You should use

 SSLContext.getInstance("TLSv1.2"); 

for specific protocol version.

The second exception occured because default socketFactory used fallback SSLv3 protocol for failures.

You can use NoSSLFactory from main answer here for its suppression How to disable SSLv3 in android for HttpsUrlConnection?

Also you should init SSLContext with all your certificates(client and trusted ones if you need them)

But all of that is useless without using

ProviderInstaller.installIfNeeded(getContext())

Here is more information with proper usage scenario https://developer.android.com/training/articles/security-gms-provider.html

Hope it helps.

Simple working Example of json.net in VB.net

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

How to backup MySQL database in PHP?

I would recommend using mysqldump and from php use the system command as suggested in the article you found.

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

How do I parse JSON with Objective-C?

Don't reinvent the wheel. Use json-framework or something similar.

If you do decide to use json-framework, here's how you would parse a JSON string into an NSDictionary:

SBJsonParser* parser = [[[SBJsonParser alloc] init] autorelease];
// assuming jsonString is your JSON string...
NSDictionary* myDict = [parser objectWithString:jsonString];

// now you can grab data out of the dictionary using objectForKey or another dictionary method

Reversing a String with Recursion in Java

Because this is recursive your output at each step would be something like this:

  1. "Hello" is entered. The method then calls itself with "ello" and will return the result + "H"
  2. "ello" is entered. The method calls itself with "llo" and will return the result + "e"
  3. "llo" is entered. The method calls itself with "lo" and will return the result + "l"
  4. "lo" is entered. The method calls itself with "o" and will return the result + "l"
  5. "o" is entered. The method will hit the if condition and return "o"

So now on to the results:

The total return value will give you the result of the recursive call's plus the first char

To the return from 5 will be: "o"

The return from 4 will be: "o" + "l"

The return from 3 will be: "ol" + "l"

The return from 2 will be: "oll" + "e"

The return from 1 will be: "olle" + "H"

This will give you the result of "olleH"

PHP sessions that have already been started

I encountered this issue while trying to fix $_SESSION's blocking behavior.

http://konrness.com/php5/how-to-prevent-blocking-php-requests/

The session file remains locked until the script completes or the session is manually closed.

So, by default, a page should open a session in read-only mode. But once it's open in read-only, it has to be closed-and-reopened in to get it into write mode.

const SESSION_DEFAULT_COOKIE_LIFETIME = 86400;

/**
 * Open _SESSION read-only
 */
function OpenSessionReadOnly() {
    session_start([
                      'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME,
                      'read_and_close'  => true,    // READ ACCESS FAST
                  ]);
    // $_SESSION is now defined. Call WriteSessionValues() to write out values
}

/**
 * _SESSION is read-only by default. Call this function to save a new value
 * call this function like `WriteSessionValues(["username"=>$login_user]);`
 * to set $_SESSION["username"]
 *
 * @param array $values_assoc_array
 */
function WriteSessionValues($values_assoc_array) {
    // this is required to close the read-only session and 
    // not get a warning on the next line.
    session_abort();

    // now open the session with write access
    session_start([ 'cookie_lifetime' => SESSION_DEFAULT_COOKIE_LIFETIME ]);

    foreach ($values_assoc_array as $key => $value) {
        $_SESSION[ $key ] = $value;
    }
    session_write_close();  // Write session data and end session

    OpenSessionReadOnly(); // now reopen the session in read-only mode.
}

OpenSessionReadOnly();  // start the session for this page

Then when you go to write some value:

WriteSessionValues(["username"=>$login_user]);

The function takes an array of key=>value pairs to make it even more efficient.

Open directory using C

Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).

How do I vertical center text next to an image in html/css?

That's a fun one. If you know ahead of time the height of the container of the text, you can use line-height equal to that height, and it should center the text vertically.

new DateTime() vs default(DateTime)

The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min

Therefore there is no difference between default(DateTime) and new DateTime() and DateTime.Min

How to add leading zeros for for-loop in shell?

why not printf '%02d' $num? See help printf for this internal bash command.

Firefox Add-on RESTclient - How to input POST parameters?

If you want to submit a POST request

  1. You have to set the “request header” section of the Firefox plugin to have a “name” = “Content-Type” and “value” = “application/x-www-form-urlencoded
  2. Now, you are able to submit parameter like “name=mynamehere&title=TA” in the “request body” text area field

How to get unique device hardware id in Android?

Please read this official blog entry on Google developer blog: http://android-developers.blogspot.be/2011/03/identifying-app-installations.html

Conclusion For the vast majority of applications, the requirement is to identify a particular installation, not a physical device. Fortunately, doing so is straightforward.

There are many good reasons for avoiding the attempt to identify a particular device. For those who want to try, the best approach is probably the use of ANDROID_ID on anything reasonably modern, with some fallback heuristics for legacy devices

.

How to format x-axis time scale values in Chart.js v2

as per the Chart js documentation page tick configuration section. you can format the value of each tick using the callback function. for example I wanted to change locale of displayed dates to be always German. in the ticks parts of the axis options

ticks: {
    callback: function(value) { 
        return new Date(value).toLocaleDateString('de-DE', {month:'short', year:'numeric'}); 
    },
},

Adding up BigDecimals using Streams

Original answer

Yes, this is possible:

List<BigDecimal> bdList = new ArrayList<>();
//populate list
BigDecimal result = bdList.stream()
        .reduce(BigDecimal.ZERO, BigDecimal::add);

What it does is:

  1. Obtain a List<BigDecimal>.
  2. Turn it into a Stream<BigDecimal>
  3. Call the reduce method.

    3.1. We supply an identity value for addition, namely BigDecimal.ZERO.

    3.2. We specify the BinaryOperator<BigDecimal>, which adds two BigDecimal's, via a method reference BigDecimal::add.

Updated answer, after edit

I see that you have added new data, therefore the new answer will become:

List<Invoice> invoiceList = new ArrayList<>();
//populate
Function<Invoice, BigDecimal> totalMapper = invoice -> invoice.getUnit_price().multiply(invoice.getQuantity());
BigDecimal result = invoiceList.stream()
        .map(totalMapper)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

It is mostly the same, except that I have added a totalMapper variable, that has a function from Invoice to BigDecimal and returns the total price of that invoice.

Then I obtain a Stream<Invoice>, map it to a Stream<BigDecimal> and then reduce it to a BigDecimal.

Now, from an OOP design point I would advice you to also actually use the total() method, which you have already defined, then it even becomes easier:

List<Invoice> invoiceList = new ArrayList<>();
//populate
BigDecimal result = invoiceList.stream()
        .map(Invoice::total)
        .reduce(BigDecimal.ZERO, BigDecimal::add);

Here we directly use the method reference in the map method.

RegEx - Match Numbers of Variable Length

{[0-9]+:[0-9]+}

try adding plus(es)

IIS7 Cache-Control

That's not true Jeff.

You simply have to select a folder within your IIS 7 Manager UI (e.g. Images or event the Default Web Application folder) and then click on "HTTP Response Headers". Then you have to click on "Set Common Header.." in the right pane and select the "Expire Web content". There you can easily configure a max-age of 24 hours by choosing "After:", entering "24" in the Textbox and choose "Hours" in the combobox.

Your first paragraph regarding the web.config entry is right. I'd add the cacheControlCustom-attribute to set the cache control header to "public" or whatever is needed in that case.

You can, of course, achieve the same by providing web.config entries (or files) as needed.

Edit: removed a confusing sentence :)

Accessing dict keys like an attribute?

This doesn't address the original question, but should be useful for people that, like me, end up here when looking for a lib that provides this functionality.

Addict it's a great lib for this: https://github.com/mewwts/addict it takes care of many concerns mentioned in previous answers.

An example from the docs:

body = {
    'query': {
        'filtered': {
            'query': {
                'match': {'description': 'addictive'}
            },
            'filter': {
                'term': {'created_by': 'Mats'}
            }
        }
    }
}

With addict:

from addict import Dict
body = Dict()
body.query.filtered.query.match.description = 'addictive'
body.query.filtered.filter.term.created_by = 'Mats'

How to find the lowest common ancestor of two nodes in any binary tree?

If someone interested in pseudo code(for university home works) here is one.

GETLCA(BINARYTREE BT, NODE A, NODE  B)
IF Root==NIL
    return NIL
ENDIF

IF Root==A OR root==B
    return Root
ENDIF

Left = GETLCA (Root.Left, A, B)
Right = GETLCA (Root.Right, A, B)

IF Left! = NIL AND Right! = NIL
    return root
ELSEIF Left! = NIL
    Return Left
ELSE
    Return Right
ENDIF

How do I change the figure size for a seaborn plot?

You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set method:

import seaborn as sns

sns.set(rc={'figure.figsize':(11.7,8.27)})

Other alternative may be to use figure.figsize of rcParams to set figure size as below:

from matplotlib import rcParams

# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27

More details can be found in matplotlib documentation

How can I check if a var is a string in JavaScript?

My personal approach, which seems to work for all cases, is testing for the presence of members that will all only be present for strings.

function isString(x) {
    return (typeof x == 'string' || typeof x == 'object' && x.toUpperCase && x.substr && x.charAt && x.trim && x.replace ? true : false);
}

See: http://jsfiddle.net/x75uy0o6/

I'd like to know if this method has flaws, but it has served me well for years.

The controller for path was not found or does not implement IController

Also, for those who the solution above didn't work, here's is what worked for me:

I have a solution with multiple projects. All projects were in MVC3. I installed Visual Studio 2012 in my machine and it seems that some projects were automatically upgraded to MVC4.

I got this problem

The controller for path '/etc/etc' was not found or does not implement IController

because the project that handled that route was pointing to MVC4.

I had to manually update their references to use MVC3. You can also do that by opening the .csproj file with a text editor. Find the reference to MVC3 and remove this line:

<SpecificVersion>False</SpecificVersion>

How do I get the domain originating the request in express.js?

You have to retrieve it from the HOST header.

var host = req.get('host');

It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.


If this is for supporting cross-origin requests, you would instead use the Origin header.

var origin = req.get('origin');

Note that some cross-origin requests require validation through a "preflight" request:

req.options('/route', function (req, res) {
    var origin = req.get('origin');
    // ...
});

If you're looking for the client's IP, you can retrieve that with:

var userIP = req.socket.remoteAddress;

Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.

Get most recent file in a directory on Linux

Finding the most current file in every directory according to a pattern, e.g. the sub directories of the working directory that have name ending with "tmp" (case insensitive):

find . -iname \*tmp -type d -exec sh -c "ls -lArt {} | tail -n 1" \;

How to implement a binary tree?

This implementation supports insert, find and delete operations without destroy the structure of the tree. This is not a banlanced tree.

# Class for construct the nodes of the tree. (Subtrees)
class Node:
def __init__(self, key, parent_node = None):
    self.left = None
    self.right = None
    self.key = key
    if parent_node == None:
        self.parent = self
    else:
        self.parent = parent_node

# Class with the  structure of the tree. 
# This Tree is not balanced.
class Tree:
def __init__(self):
    self.root = None

# Insert a single element
def insert(self, x):
    if(self.root == None):
        self.root = Node(x)
    else:
        self._insert(x, self.root)

def _insert(self, x, node):
    if(x < node.key):
        if(node.left == None):
            node.left = Node(x, node)
        else:
            self._insert(x, node.left)
    else:
        if(node.right == None):
            node.right = Node(x, node)
        else:
            self._insert(x, node.right)

# Given a element, return a node in the tree with key x. 
def find(self, x):
    if(self.root == None):
        return None
    else:
        return self._find(x, self.root)
def _find(self, x, node):
    if(x == node.key):
        return node
    elif(x < node.key):
        if(node.left == None):
            return None
        else:
            return self._find(x, node.left)
    elif(x > node.key):
        if(node.right == None):
            return None
        else:
            return self._find(x, node.right)

# Given a node, return the node in the tree with the next largest element.
def next(self, node):
    if node.right != None:
        return self._left_descendant(node.right)
    else:
        return self._right_ancestor(node)

def _left_descendant(self, node):
    if node.left == None:
        return node
    else:
        return self._left_descendant(node.left)

def _right_ancestor(self, node):
    if node.key <= node.parent.key:
        return node.parent
    else:
        return self._right_ancestor(node.parent)

# Delete an element of the tree
def delete(self, x):
    node = self.find(x)
    if node == None:
        print(x, "isn't in the tree")
    else:
        if node.right == None:
            if node.left == None:
                if node.key < node.parent.key:
                    node.parent.left = None
                    del node # Clean garbage
                else:
                    node.parent.right = None
                    del Node # Clean garbage
            else:
                node.key = node.left.key
                node.left = None
        else:
            x = self.next(node)
            node.key = x.key
            x = None


# tests
t = Tree()
t.insert(5)
t.insert(8)
t.insert(3)
t.insert(4)
t.insert(6)
t.insert(2)

t.delete(8)
t.delete(5)

t.insert(9)
t.insert(1)

t.delete(2)
t.delete(100)

# Remember: Find method return the node object. 
# To return a number use t.find(nº).key
# But it will cause an error if the number is not in the tree.
print(t.find(5)) 
print(t.find(8))
print(t.find(4))
print(t.find(6))
print(t.find(9))

html select only one checkbox in a group

While JS is probably the way to go, it could be done with HTML and CSS only.

Here you have a fake radio button which is really a label for a real hidden radio button. By doing that, you get exactly the effect you need.

<style>
   #uncheck>input { display: none }
   input:checked + label { display: none }
   input:not(:checked) + label + label{ display: none } 
</style>

<div id='uncheck'>
  <input type="radio" name='food' id="box1" /> 
  Pizza 
    <label for='box1'>&#9678;</label> 
    <label for='box0'>&#9673;</label>
  <input type="radio" name='food' id="box2" /> 
  Ice cream 
    <label for='box2'>&#9678;</label> 
    <label for='box0'>&#9673;</label>
  <input type="radio" name='food' id="box0" checked />
</div>

See it here: https://jsfiddle.net/tn70yxL8/2/

Now, that assumes you need non-selectable labels.

If you were willing to include the labels, you can technically avoid repeating the "uncheck" label by changing its text in CSS, see here: https://jsfiddle.net/7tdb6quy/2/

JAX-RS — How to return JSON and HTTP status code together?

Expanding on the answer of Nthalk with Microprofile OpenAPI you can align the return code with your documentation using @APIResponse annotation.

This allows tagging a JAX-RS method like

@GET
@APIResponse(responseCode = "204")
public Resource getResource(ResourceRequest request) 

You can parse this standardized annotation with a ContainerResponseFilter

@Provider
public class StatusFilter implements ContainerResponseFilter {

    @Override
    public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
        if (responseContext.getStatus() == 200) {
            for (final var annotation : responseContext.getEntityAnnotations()) {
                if (annotation instanceof APIResponse response) {
                    final var rawCode = response.responseCode();
                    final var statusCode = Integer.parseInt(rawCode);

                    responseContext.setStatus(statusCode);
                }
            }
        }
    }

}

A caveat occurs when you put multiple annotations on your method like

@APIResponse(responseCode = "201", description = "first use case")
@APIResponse(responseCode = "204", description = "because you can")
public Resource getResource(ResourceRequest request) 

How to tell if a file is git tracked (by shell exit code)?

using git log will give info about this. If the file is tracked in git the command shows some results(logs). Else it is empty.

For example if the file is git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
commit ad9180b772d5c64dcd79a6cbb9487bd2ef08cbfc
Author: User <[email protected]>
Date:   Mon Feb 20 07:45:04 2017 -0600

    fix eslint indentation errors
....
....

If the file is not git tracked,

root@user-ubuntu:~/project-repo-directory# git log src/../somefile.js
root@user-ubuntu:~/project-repo-directory#

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

It is possible to solve the problem by updating the 'Newtonsoft' version.

In Visual Studio 2015 it is possible to right click on the "Solution" and select "Manage Nuget packages for solution", search for "Newtonsoft" select a more current version and click update.

How to find whether MySQL is installed in Red Hat?

yum list installed | grep mysql

Then if it's not installed you can do (as root)

yum install mysql -y

Converting BigDecimal to Integer

TL;DR

Use one of these for universal conversion needs

//Java 7 or below
bigDecimal.setScale(0, RoundingMode.DOWN).intValueExact()
//Java 8    
bigDecimal.toBigInteger().intValueExact()

Reasoning

The answer depends on what the requirements are and how you answer these question.

  • Will the BigDecimal potentially have a non-zero fractional part?
  • Will the BigDecimal potentially not fit into the Integer range?
  • Would you like non-zero fractional parts rounded or truncated?
  • How would you like non-zero fractional parts rounded?

If you answered no to the first 2 questions, you could just use BigDecimal.intValueExact() as others have suggested and let it blow up when something unexpected happens.

If you are not absolutely 100% confident about question number 2, then intValue() is always the wrong answer.

Making it better

Let's use the following assumptions based on the other answers.

  • We are okay with losing precision and truncating the value because that's what intValueExact() and auto-boxing do
  • We want an exception thrown when the BigDecimal is larger than the Integer range because anything else would be crazy unless you have a very specific need for the wrap around that happens when you drop the high-order bits.

Given those params, intValueExact() throws an exception when we don't want it to if our fractional part is non-zero. On the other hand, intValue() doesn't throw an exception when it should if our BigDecimal is too large.

To get the best of both worlds, round off the BigDecimal first, then convert. This also has the benefit of giving you more control over the rounding process.

Spock Groovy Test

void 'test BigDecimal rounding'() {
    given:
    BigDecimal decimal = new BigDecimal(Integer.MAX_VALUE - 1.99)
    BigDecimal hugeDecimal = new BigDecimal(Integer.MAX_VALUE + 1.99)
    BigDecimal reallyHuge = new BigDecimal("10000000000000000000000000000000000000000000000")
    String decimalAsBigIntString = decimal.toBigInteger().toString()
    String hugeDecimalAsBigIntString = hugeDecimal.toBigInteger().toString()
    String reallyHugeAsBigIntString = reallyHuge.toBigInteger().toString()

    expect: 'decimals that can be truncated within Integer range to do so without exception'
    //GOOD: Truncates without exception
    '' + decimal.intValue() == decimalAsBigIntString
    //BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
    // decimal.intValueExact() == decimalAsBigIntString
    //GOOD: Truncates without exception
    '' + decimal.setScale(0, RoundingMode.DOWN).intValueExact() == decimalAsBigIntString

    and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
    //BAD: hugeDecimal.intValue() is -2147483648 instead of 2147483648
    //'' + hugeDecimal.intValue() == hugeDecimalAsBigIntString
    //BAD: Throws ArithmeticException 'Non-zero decimal digits' because we lose information
    //'' + hugeDecimal.intValueExact() == hugeDecimalAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + hugeDecimal.setScale(0, RoundingMode.DOWN).intValueExact() == hugeDecimalAsBigIntString

    and: 'truncated decimal that cannot be truncated within Integer range throw conversionOverflow exception'
    //BAD: hugeDecimal.intValue() is 0
    //'' + reallyHuge.intValue() == reallyHugeAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + reallyHuge.intValueExact() == reallyHugeAsBigIntString
    //GOOD: Throws conversionOverflow ArithmeticException because to large
    //'' + reallyHuge.setScale(0, RoundingMode.DOWN).intValueExact() == reallyHugeAsBigIntString

    and: 'if using Java 8, BigInteger has intValueExact() just like BigDecimal'
    //decimal.toBigInteger().intValueExact() == decimal.setScale(0, RoundingMode.DOWN).intValueExact()
}

"This SqlTransaction has completed; it is no longer usable."... configuration error?

I have the same problem. This error occurs because conection pooling. When exists two or more users acess the system the connetion pooling reuse a connetion and the transation too. If the first user execute commit ou rollback the transaction is no longe usable.

ImportError: No module named Image

On a system with both Python 2 and 3 installed and with pip2-installed Pillow failing to provide Image, it is possible to install PIL for Python 2 in a way that will solve ImportError: No module named Image:

easy_install-2.7 --user PIL

or

sudo easy_install-2.7 PIL

convert double to int

Here is a complete example

class Example 
{    
  public static void Main() 
  {    
    double x, y; 
    int i; 

    x = 10.0; 
    y = 3.0; 

    // cast double to int, fractional component lost (Line to be replaced) 
    i = (int) (x / y); 
    Console.WriteLine("Integer outcome of x / y: " + i); 
  }    
}

If you want to round the number to the closer integer do the following:

i = (int) Math.Round(x / y); // Line replaced

move column in pandas dataframe

You can use pd.Index.difference with np.hstack, then reindex or use label-based indexing. In general, it's a good idea to avoid list comprehensions or other explicit loops with NumPy / Pandas objects.

cols_to_move = ['b', 'x']
new_cols = np.hstack((df.columns.difference(cols_to_move), cols_to_move))

# OPTION 1: reindex
df = df.reindex(columns=new_cols)

# OPTION 2: direct label-based indexing
df = df[new_cols]

# OPTION 3: loc label-based indexing
df = df.loc[:, new_cols]

print(df)

#    a  y  b   x
# 0  1 -1  2   3
# 1  2 -2  4   6
# 2  3 -3  6   9
# 3  4 -4  8  12

Read specific columns from a csv file with csv module?

SAMPLE.CSV
a, 1, +
b, 2, -
c, 3, *
d, 4, /
column_names = ["Letter", "Number", "Symbol"]
df = pd.read_csv("sample.csv", names=column_names)
print(df)
OUTPUT
  Letter  Number Symbol
0      a       1      +
1      b       2      -
2      c       3      *
3      d       4      /

letters = df.Letter.to_list()
print(letters)
OUTPUT
['a', 'b', 'c', 'd']

How do I find the index of a character within a string in C?

Just subtract the string address from what strchr returns:

char *string = "qwerty";
char *e;
int index;

e = strchr(string, 'e');
index = (int)(e - string);

Note that the result is zero based, so in above example it will be 2.

Get Row Index on Asp.net Rowcommand event

I was able to use @rahularyansharma's answer above in my own project, with one minor modification. I needed to get the value of particular cells on the row on which the user clicks a LinkButton. The second line can be modified to get the value of as many cells as you wish.

Here is my solution:

GridViewRow gvr = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
string typecore = gvr.Cells[3].Text.ToString().Trim();

Vue Js - Loop via v-for X times (in a range)

The same goes for v-for in range:

<li v-for="n in 20 " :key="n">{{n}}</li>

Pass parameter to EventHandler

Timer.Elapsed expects method of specific signature (with arguments object and EventArgs). If you want to use your PlayMusicEvent method with additional argument evaluated during event registration, you can use lambda expression as an adapter:

myTimer.Elapsed += new ElapsedEventHandler((sender, e) => PlayMusicEvent(sender, e, musicNote));

Edit: you can also use shorter version:

myTimer.Elapsed += (sender, e) => PlayMusicEvent(sender, e, musicNote);

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Does it make sense to use Require.js with Angular.js?

It makes sense to use requirejs with angularjs if you plan on lazy loading controllers and directives etc, while also combining multiple lazy dependencies into single script files for much faster lazy loading. RequireJS has an optimisation tool that makes the combining easy. See http://ify.io/using-requirejs-with-optimisation-for-lazy-loading-angularjs-artefacts/

Join a list of items with different types as string in Python

There are three ways of doing this.

let say you have a list of integers

my_list = [100,200,300]
  1. "-".join(str(n) for n in my_list)
  2. "-".join([str(n) for n in my_list])
  3. "-".join(map(str, my_list))

However as stated in the example of timeit on python website at https://docs.python.org/2/library/timeit.html using a map is faster. So I would recommend you using "-".join(map(str, my_list))

"The following SDK components were not installed: sys-img-x86-addon-google_apis-google-22 and addon-google_apis-google-22"

I just run: C:\Users[Username]\AppData\Local\Android\sdk\SDK Manager.exe

Install SDK Platform Android M Preview

enter image description here

And run Android Studio again.

It's working for me :D

Read whole ASCII file into C++ std::string

I think best way is to use string stream. simple and quick !!!

#include <fstream>
#include <iostream>
#include <sstream> //std::stringstream
int main() {
    std::ifstream inFile;
    inFile.open("inFileName"); //open the input file

    std::stringstream strStream;
    strStream << inFile.rdbuf(); //read the file
    std::string str = strStream.str(); //str holds the content of the file

    std::cout << str << "\n"; //you can do anything with the string!!!
}

C++, copy set to vector

std::copy cannot be used to insert into an empty container. To do that, you need to use an insert_iterator like so:

std::set<double> input;
input.insert(5);
input.insert(6);

std::vector<double> output;
std::copy(input.begin(), input.end(), inserter(output, output.begin())); 

submitting a GET form with query string params and hidden params disappear

I had a very similar problem where for the form action, I had something like:

<form action="http://www.example.com/?q=content/something" method="GET">
   <input type="submit" value="Go away..." />&nbsp;
</form>

The button would get the user to the site, but the query info disappeared so the user landed on the home page rather than the desired content page. The solution in my case was to find out how to code the URL without the query that would get the user to the desired page. In this case my target was a Drupal site, so as it turned out /content/something also worked. I also could have used a node number (i.e. /node/123).

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

ERROR in Cannot find module 'node-sass'

It worked for me...

sudo npm rebuild node-sass --force

List of all special characters that need to be escaped in a regex

  • Java characters that have to be escaped in regular expressions are:
    \.[]{}()<>*+-=!?^$|
  • Two of the closing brackets (] and }) are only need to be escaped after opening the same type of bracket.
  • In []-brackets some characters (like + and -) do sometimes work without escape.

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

Creating a dictionary from a CSV file

I believe the syntax you were looking for is as follows:

import csv

with open('coors.csv', mode='r') as infile:
    reader = csv.reader(infile)
    with open('coors_new.csv', mode='w') as outfile:
        writer = csv.writer(outfile)
        mydict = {rows[0]:rows[1] for rows in reader}

Alternately, for python <= 2.7.1, you want:

mydict = dict((rows[0],rows[1]) for rows in reader)

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

I like to do this witch i think is cleaner :

1 - Add the model to namespace:

use App\Employee;

2 - then you can do :

$employees = Employee::get();

or maybe somthing like this:

$employee = Employee::where('name', 'John')->first();

How to delete a localStorage item when the browser window/tab is closed?

you can try following code to delete local storage:

delete localStorage.myPageDataArr;

Finding length of char array

If you are expecting 4 as output then try this:

char a[]={0x00,0xdc,0x01,0x04};

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

CSS transition between left -> right and top -> bottom positions

In more modern browsers (including IE 10+) you can now use calc():

.moveto {
  top: 0px;
  left: calc(100% - 50px);
}

How to combine two vectors into a data frame

x <-c(1,2,3)
y <-c(100,200,300)
x_name <- "cond"
y_name <- "rating"

require(reshape2)
df <- melt(data.frame(x,y))
colnames(df) <- c(x_name, y_name)
print(df)

UPDATE (2017-02-07): As an answer to @cdaringe comment - there are multiple solutions possible, one of them is below.

library(dplyr)
library(magrittr)

x <- c(1, 2, 3)
y <- c(100, 200, 300)
z <- c(1, 2, 3, 4, 5)
x_name <- "cond"
y_name <- "rating"

# Helper function to create data.frame for the chunk of the data
prepare <- function(name, value, xname = x_name, yname = y_name) {
  data_frame(rep(name, length(value)), value) %>%
    set_colnames(c(xname, yname))
}

bind_rows(
  prepare("x", x),
  prepare("y", y),
  prepare("z", z)
)

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

You can't create a new branch with this command

git checkout --track origin/branch

if you have changes that are not staged.

Here is example:

$ git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

        modified:   src/App.js

no changes added to commit (use "git add" and/or "git commit -a")

// TRY TO CREATE:

$ git checkout --track origin/new-branch
fatal: 'origin/new-branch' is not a commit and a branch 'new-branch' cannot be created from it

However you can easily create a new branch with un-staged changes with git checkout -b command:

$ git checkout -b new-branch
Switched to a new branch 'new-branch'
M       src/App.js

MySQL wait_timeout Variable - GLOBAL vs SESSION

Your session status are set once you start a session, and by default, take the current GLOBAL value.

If you disconnected after you did SET @@GLOBAL.wait_timeout=300, then subsequently reconnected, you'd see

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

+---------------+-------+
| Variable_name | Value |
+---------------+-------+
| wait_timeout  | 300   |
+---------------+-------+

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

On delete cascade with doctrine2

Here is simple example. A contact has one to many associated phone numbers. When a contact is deleted, I want all its associated phone numbers to also be deleted, so I use ON DELETE CASCADE. The one-to-many/many-to-one relationship is implemented with by the foreign key in the phone_numbers.

CREATE TABLE contacts
 (contact_id BIGINT AUTO_INCREMENT NOT NULL,
 name VARCHAR(75) NOT NULL,
 PRIMARY KEY(contact_id)) ENGINE = InnoDB;

CREATE TABLE phone_numbers
 (phone_id BIGINT AUTO_INCREMENT NOT NULL,
  phone_number CHAR(10) NOT NULL,
 contact_id BIGINT NOT NULL,
 PRIMARY KEY(phone_id),
 UNIQUE(phone_number)) ENGINE = InnoDB;

ALTER TABLE phone_numbers ADD FOREIGN KEY (contact_id) REFERENCES \
contacts(contact_id) ) ON DELETE CASCADE;

By adding "ON DELETE CASCADE" to the foreign key constraint, phone_numbers will automatically be deleted when their associated contact is deleted.

INSERT INTO table contacts(name) VALUES('Robert Smith');
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8963333333', 1);
INSERT INTO table phone_numbers(phone_number, contact_id) VALUES('8964444444', 1);

Now when a row in the contacts table is deleted, all its associated phone_numbers rows will automatically be deleted.

DELETE TABLE contacts as c WHERE c.id=1; /* delete cascades to phone_numbers */

To achieve the same thing in Doctrine, to get the same DB-level "ON DELETE CASCADE" behavoir, you configure the @JoinColumn with the onDelete="CASCADE" option.

<?php
namespace Entities;

use Doctrine\Common\Collections\ArrayCollection;

/**
 * @Entity
 * @Table(name="contacts")
 */
class Contact 
{

    /**
     *  @Id
     *  @Column(type="integer", name="contact_id") 
     *  @GeneratedValue
     */
    protected $id;  

    /** 
     * @Column(type="string", length="75", unique="true") 
     */ 
    protected $name; 

    /** 
     * @OneToMany(targetEntity="Phonenumber", mappedBy="contact")
     */ 
    protected $phonenumbers; 

    public function __construct($name=null)
    {
        $this->phonenumbers = new ArrayCollection();

        if (!is_null($name)) {

            $this->name = $name;
        }
    }

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function addPhonenumber(Phonenumber $p)
    {
        if (!$this->phonenumbers->contains($p)) {

            $this->phonenumbers[] = $p;
            $p->setContact($this);
        }
    }

    public function removePhonenumber(Phonenumber $p)
    {
        $this->phonenumbers->remove($p);
    }
}

<?php
namespace Entities;

/**
 * @Entity
 * @Table(name="phonenumbers")
 */
class Phonenumber 
{

    /**
    * @Id
    * @Column(type="integer", name="phone_id") 
    * @GeneratedValue
    */
    protected $id; 

    /**
     * @Column(type="string", length="10", unique="true") 
     */  
    protected $number;

    /** 
     * @ManyToOne(targetEntity="Contact", inversedBy="phonenumbers")
     * @JoinColumn(name="contact_id", referencedColumnName="contact_id", onDelete="CASCADE")
     */ 
    protected $contact; 

    public function __construct($number=null)
    {
        if (!is_null($number)) {

            $this->number = $number;
        }
    }

    public function setPhonenumber($number)
    {
        $this->number = $number;
    }

    public function setContact(Contact $c)
    {
        $this->contact = $c;
    }
} 
?>

<?php

$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);

$contact = new Contact("John Doe"); 

$phone1 = new Phonenumber("8173333333");
$phone2 = new Phonenumber("8174444444");
$em->persist($phone1);
$em->persist($phone2);
$contact->addPhonenumber($phone1); 
$contact->addPhonenumber($phone2); 

$em->persist($contact);
try {

    $em->flush();
} catch(Exception $e) {

    $m = $e->getMessage();
    echo $m . "<br />\n";
}

If you now do

# doctrine orm:schema-tool:create --dump-sql

you will see that the same SQL will be generated as in the first, raw-SQL example

Find a pair of elements from an array whose sum equals a given number

 public static int[] f (final int[] nums, int target) {
    int[] r = new int[2];
    r[0] = -1;
    r[1] = -1;
    int[] vIndex = new int[0Xfff];
    for (int i = 0; i < nums.length; i++) {
        int delta = 0Xff;
        int gapIndex = target - nums[i] + delta;
        if (vIndex[gapIndex] != 0) {
            r[0] = vIndex[gapIndex];
            r[1] = i + 1;
            return r;
        } else {
            vIndex[nums[i] + delta] = i + 1;
        }
    }
    return r;
}

Error Dropping Database (Can't rmdir '.test\', errno: 17)

Go to the datadir for your mysql installation and rm the databases manually. It can be

/usr/local/var/mysql

Then,

rm -R <Your DB name>

To check datadir for your installation,

vim the mysql.server file and find it there.

How to get datetime in JavaScript?

Semantically, you're probably looking for the one-liner

new Date().toLocaleString()

which formats the date in the locale of the user.

If you're really looking for a specific way to format dates, I recommend the moment.js library.

How to make lists contain only distinct element in Python?

If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster. Python Programming FAQ

d = {}
for x in mylist:
    d[x] = 1
mylist = list(d.keys())

iPhone App Icons - Exact Radius?

You don't need to apply corner radius to your app icon, you can just apply square icons. The device is automatically applying corner radius.

What's the meaning of exception code "EXC_I386_GPFLT"?

I could get this error working with UnsafeMutablePointer

let ptr = rawptr.assumingMemoryBound(to: A.self) //<-- wrong A.self Change it to B.Self
ptr.pointee = B()

How to stop a setTimeout loop?

You need to use a variable to track "doneness" and then test it on every iteration of the loop. If done == true then return.

var done = false;

function setBgPosition() {
    if ( done ) return;
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
        if ( done ) return;
        Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length)
        {
            setTimeout(run, 200);
        }else
        {
            setBgPosition();
        }
    }
    setTimeout(run, 200);
}

setBgPosition(); // start the loop

setTimeout( function(){ done = true; }, 5000 ); // external event to stop loop

How to determine the current shell I'm working on

If you just want to ensure the user is invoking a script with Bash:

if [ ! -n "$BASH" ] ;then echo Please run this script $0 with bash; exit 1; fi

Create table using Javascript

Might not solve the problem described in this particular question, but might be useful to people looking to create tables out of array of objects:

_x000D_
_x000D_
function createTable(objectArray, fields, fieldTitles) {_x000D_
  let body = document.getElementsByTagName('body')[0];_x000D_
  let tbl = document.createElement('table');_x000D_
  let thead = document.createElement('thead');_x000D_
  let thr = document.createElement('tr');_x000D_
  fieldTitles.forEach((fieldTitle) => {_x000D_
    let th = document.createElement('th');_x000D_
    th.appendChild(document.createTextNode(fieldTitle));_x000D_
    thr.appendChild(th);_x000D_
  });_x000D_
  thead.appendChild(thr);_x000D_
  tbl.appendChild(thead);_x000D_
_x000D_
  let tbdy = document.createElement('tbody');_x000D_
  let tr = document.createElement('tr');_x000D_
  objectArray.forEach((object) => {_x000D_
    let tr = document.createElement('tr');_x000D_
    fields.forEach((field) => {_x000D_
      var td = document.createElement('td');_x000D_
      td.appendChild(document.createTextNode(object[field]));_x000D_
      tr.appendChild(td);_x000D_
    });_x000D_
    tbdy.appendChild(tr);    _x000D_
  });_x000D_
  tbl.appendChild(tbdy);_x000D_
  body.appendChild(tbl)_x000D_
  return tbl;_x000D_
}_x000D_
_x000D_
createTable([_x000D_
  {name: 'Banana', price: '3.04'},_x000D_
  {name: 'Orange', price: '2.56'},_x000D_
  {name: 'Apple', price: '1.45'}_x000D_
],_x000D_
['name', 'price'], ['Name', 'Price']);
_x000D_
_x000D_
_x000D_

IntelliJ does not show project folders

OS:Mac && IDE: IntelliJ && Project: Maven build

  1. Navigate to File>Project Structure>Modules.
  2. In right-hand area; list of modules would be present.
  3. Delete the default one selected and close IntelliJ.
  4. Next Open again; IntelliJ will ask if you want to treat the project as Maven project.
  5. Accept that popup and you are good to go.

Escaping quotes and double quotes

In Powershell 5 escaping double quotes can be done by backtick (`). But sometimes you need to provide your double quotes escaped which can be done by backslash + backtick (\`). Eg in this curl call:

C:\Windows\System32\curl.exe -s -k -H "Content-Type: application/json" -XPOST localhost:9200/index_name/inded_type -d"{\`"velocity\`":3.14}"

C pointers and arrays: [Warning] assignment makes pointer from integer without a cast

int[] and int* are represented the same way, except int[] allocates (IIRC).

ap is a pointer, therefore giving it the value of an integer is dangerous, as you have no idea what's at address 45.

when you try to access it (x = *ap), you try to access address 45, which causes the crash, as it probably is not a part of the memory you can access.

Change Spinner dropdown icon

Try applying following style to your spinner using

style="@style/SpinnerTheme"

//Spinner Style:

<style name="SpinnerTheme" parent="android:Widget.Spinner">
    <item name="android:background">@drawable/bg_spinner</item>
</style>

//bg_spinner.xml Replace the arrow_down_gray with your arrow

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item>

        <layer-list>

            <item>
                <shape>
                    <gradient android:angle="90" android:endColor="#ffffff" android:startColor="#ffffff" android:type="linear" />

                    <stroke android:width="0.33dp" android:color="#0fb1fa" />

                    <corners android:radius="0dp" />

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
                </shape>
            </item>

            <item android:right="5dp">

                <bitmap android:gravity="center_vertical|right" android:src="@drawable/arrow_down_gray" />

            </item>

        </layer-list>

    </item>

</selector>

Magento: Set LIMIT on collection

There are several ways to do this:

$collection = Mage::getModel('...')
            ->getCollection()
            ->setPageSize(20)
            ->setCurPage(1);

Will get first 20 records.

Here is the alternative and maybe more readable way:

$collection = Mage::getModel('...')->getCollection();
$collection->getSelect()->limit(20);

This will call Zend Db limit. You can set offset as second parameter.

Ajax Upload image

Image upload using ajax and check image format and upload max size   

<form class='form-horizontal' method="POST"  id='document_form' enctype="multipart/form-data">
                                    <div class='optionBox1'>
                                        <div class='row inviteInputWrap1 block1'>
                                            <div class='col-3'>
                                                <label class='col-form-label'>Name</label>
                                                <input type='text' class='form-control form-control-sm' name='name[]' id='name' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <label class='col-form-label'>File</label>
                                                <input type='file' class='form-control form-control-sm' name='file[]' id='file' Value=''>
                                            </div>
                                            <div class='col-3'>
                                                <span class='deleteInviteWrap1 remove1 d-none'>
                                                    <i class='fas fa-trash'></i>
                                                </span>
                                            </div>
                                        </div>
                                        <div class='row'>
                                             <div class='col-8 pl-3 pb-4 mt-4'>
                                                <span class='btn btn-info add1 pr-3'>+ Add More</span>
                                                 <button class='btn btn-primary'>Submit</button> 
                                            </div>
                                        </div>
                                    </div>
                                    </form>     
                                    
                                    </div>  
                      
    
      $.validator.setDefaults({
       submitHandler: function (form) 
         {
               $.ajax({
                    url : "action1.php",
                    type : "POST",
                    data : new FormData(form),
                    mimeType: "multipart/form-data",
                    contentType: false,
                    cache: false,
                    dataType:'json',
                    processData: false,
                    success: function(data)
                    {
                        if(data.status =='success')
                            {
                                 swal("Document has been successfully uploaded!", {
                                    icon: "success",
                                 });
                                 setTimeout(function(){
                                    window.location.reload(); 
                                },1200);
                            }
                            else
                            {
                                swal('Oh noes!', "Error in document upload. Please contact to administrator", "error");
                            }   
                    },
                    error:function(data)
                    {
                        swal ( "Ops!" ,  "error in document upload." ,  "error" );
                    }
                });
            }
      });
    
      $('#document_form').validate({
        rules: {
            "name[]": {
              required: true
          },
          "file[]": {
              required: true,
              extension: "jpg,jpeg,png,pdf,doc",
              filesize :2000000 
          }
        },
        messages: {
            "name[]": {
            required: "Please enter name"
          },
          "file[]": {
            required: "Please enter file",
            extension :'Please upload only jpg,jpeg,png,pdf,doc'
          }
        },
        errorElement: 'span',
        errorPlacement: function (error, element) {
          error.addClass('invalid-feedback');
          element.closest('.col-3').append(error);
        },
        highlight: function (element, errorClass, validClass) {
          $(element).addClass('is-invalid');
        },
        unhighlight: function (element, errorClass, validClass) {
          $(element).removeClass('is-invalid');
        }
      });
    
      $.validator.addMethod('filesize', function(value, element, param) {
         return this.optional(element) || (element.files[0].size <= param)
        }, 'File size must be less than 2 MB');

Push items into mongo array via mongoose

The $push operator appends a specified value to an array.

{ $push: { <field1>: <value1>, ... } }

$push adds the array field with the value as its element.

Above answer fulfils all the requirements, but I got it working by doing the following

var objFriends = { fname:"fname",lname:"lname",surname:"surname" };
Friend.findOneAndUpdate(
   { _id: req.body.id }, 
   { $push: { friends: objFriends  } },
  function (error, success) {
        if (error) {
            console.log(error);
        } else {
            console.log(success);
        }
    });
)

How do I find the authoritative name-server for a domain name?

I found that the best way it to add always the +trace option:

dig SOA +trace stackoverflow.com

It works also with recursive CNAME hosted in different provider. +trace trace imply +norecurse so the result is just for the domain you specify.

Why won't my PHP app send a 404 error?

Load default server 404 page, if you have one, e.g. defined for apache:

if(strstr($_SERVER['REQUEST_URI'],'index.php')){
  header('HTTP/1.0 404 Not Found');
  readfile('404missing.html');
  exit();
}

No tests found with test runner 'JUnit 4'

Very late but what solved the problem for me was that my test method names all started with captial letters: "public void Test". Making the t lower case worked.

Is there a way to access the "previous row" value in a SELECT statement?

WITH CTE AS (
  SELECT
    rownum = ROW_NUMBER() OVER (ORDER BY columns_to_order_by),
    value
  FROM table
)
SELECT
  curr.value - prev.value
FROM CTE cur
INNER JOIN CTE prev on prev.rownum = cur.rownum - 1

Is it possible to embed animated GIFs in PDFs?

It's not really possible. You could, but if you're going to it would be useless without appropriate plugins. You'd be better using some other form. PDF's are used to have a consolidated output to printers and the screen, so animations won't work without other resources, and then it's not really a PDF.

How to unpack an .asar file?

From the asar documentation

(the use of npx here is to avoid to install the asar tool globally with npm install -g asar)

Extract the whole archive:

npx asar extract app.asar destfolder 

Extract a particular file:

npx asar extract-file app.asar main.js

How to use glOrtho() in OpenGL?

glOrtho describes a transformation that produces a parallel projection. The current matrix (see glMatrixMode) is multiplied by this matrix and the result replaces the current matrix, as if glMultMatrix were called with the following matrix as its argument:

OpenGL documentation (my bold)

The numbers define the locations of the clipping planes (left, right, bottom, top, near and far).

The "normal" projection is a perspective projection that provides the illusion of depth. Wikipedia defines a parallel projection as:

Parallel projections have lines of projection that are parallel both in reality and in the projection plane.

Parallel projection corresponds to a perspective projection with a hypothetical viewpoint—e.g., one where the camera lies an infinite distance away from the object and has an infinite focal length, or "zoom".

What's the difference between IFrame and Frame?

The only reasons I can think of are actually in the wiki article you referenced to mention a couple...

"The "Verified by Visa" system has drawn some criticism, since it is hard for users to differentiate between the legitimate Verified by Visa pop-up window or inline frame, and a fraudulent phishing site."

"as of 2008, most web browsers do not provide a simple way to check the security certificate for the contents of an iframe"

If you read the Criticism section in the article it details all the potential security flaws.

Otherwise the only difference is the fact that an IFrame is an inline frame and a Frame is part of a Frameset. Which means more layout problems than anything else!

Proper way to get page content

The wp_trim_words function can limit the characters too by changing the $num_words variable. For anyone who might find useful.

<?php 
$id=58; 
$post = get_post($id); 
$content = apply_filters('the_content', $post->post_content); 

$customExcerpt = wp_trim_words( $content, $num_words = 26, $more = '' );
echo $customExcerpt;  
?>

jQuery selector for inputs with square brackets in the name attribute

Just separate it with different quotes:

<input name="myName[1][data]" value="myValue">

JQuery:

var value = $('input[name="myName[1][data]"]').val();

How to launch another aspx web page upon button click?

Edited and fixed (thanks to Shredder)

If you mean you want to open a new tab, try the below:

protected void Page_Load(object sender, EventArgs e)
{
    this.Form.Target = "_blank";
}

protected void Button1_Click(object sender, EventArgs e)
{

    Response.Redirect("Otherpage.aspx");
}

This will keep the original page to stay open and cause the redirects on the current page to affect the new tab only.

-J

Insert string at specified position

Use the stringInsert function rather than the putinplace function. I was using the later function to parse a mysql query. Although the output looked alright, the query resulted in a error which took me a while to track down. The following is my version of the stringInsert function requiring only one parameter.

function stringInsert($str,$insertstr,$pos)
{
    $str = substr($str, 0, $pos) . $insertstr . substr($str, $pos);
    return $str;
}  

How do I center a window onscreen in C#?

Use Location property of the form. Set it to the desired top left point

desired x = (desktop_width - form_witdh)/2

desired y = (desktop_height - from_height)/2

How to convert int to string on Arduino?

Use like this:

String myString = String(n);

You can find more examples here.

Difference between subprocess.Popen and os.system

When running python (cpython) on windows the <built-in function system> os.system will execute under the curtains _wsystem while if you're using a non-windows os, it'll use system.

On contrary, Popen should use CreateProcess on windows and _posixsubprocess.fork_exec in posix-based operating-systems.

That said, an important piece of advice comes from os.system docs, which says:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

How to get names of enum entries?

I wrote a helper function to enumerate an enum:

static getEnumValues<T extends number>(enumType: {}): T[] {
  const values: T[] = [];
  const keys = Object.keys(enumType);
  for (const key of keys.slice(0, keys.length / 2)) {
    values.push(<T>+key);
  }
  return values;
}

Usage:

for (const enumValue of getEnumValues<myEnum>(myEnum)) {
  // do the thing
}

The function returns something that can be easily enumerated, and also casts to the enum type.

TypeScript: casting HTMLElement

We could type our variable with an explicit return type:

const script: HTMLScriptElement = document.getElementsByName(id).item(0);

Or assert as (needed with TSX):

const script = document.getElementsByName(id).item(0) as HTMLScriptElement;

Or in simpler cases assert with angle-bracket syntax.


A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler.

Documentation:

TypeScript - Basic Types - Type assertions

How to click a browser button with JavaScript automatically?

This will give you some control over the clicking, and looks tidy

<script>
var timeOut = 0;
function onClick(but)
{
    //code
    clearTimeout(timeOut);
    timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>

Find maximum value of a column and return the corresponding row values using Pandas

In order to print the Country and Place with maximum value, use the following line of code.

print(df[['Country', 'Place']][df.Value == df.Value.max()])

Html.fromHtml deprecated in Android N

From official doc :

fromHtml(String) method was deprecated in API level 24. use fromHtml(String, int) instead.

  1. TO_HTML_PARAGRAPH_LINES_CONSECUTIVE Option for toHtml(Spanned, int): Wrap consecutive lines of text delimited by '\n' inside <p> elements.

  2. TO_HTML_PARAGRAPH_LINES_INDIVIDUAL Option for toHtml(Spanned, int): Wrap each line of text delimited by '\n' inside a <p> or a <li> element.

https://developer.android.com/reference/android/text/Html.html

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

For me it was different from any of the above,

The activity was declared as abstract, That is why giving the error. Once it removed it worked.

Earlier

     public abstract class SampleActivity extends AppcompatActivity{
     }

After removal

     public class SampleActivity extends AppcompatActivity{
     }

Excel - Sum column if condition is met by checking other column in same table

This should work, but there is a little trick. After you enter the formula, you need to hold down Ctrl+Shift while you press Enter. When you do, you'll see that the formula bar has curly-braces around your formula. This is called an array formula.

For example, if the Months are in cells A2:A100 and the amounts are in cells B2:B100, your formula would look like {=SUM(If(A2:A100="January",B2:B100))}. You don't actually type the curly-braces though.

You could also do something like =SUM((A2:A100="January")*B2:B100). You'd still need to use the trick to get it to work correctly.

Android Studio Emulator and "Process finished with exit code 0"

You can try to delete the emulator and reinstall it this usually does the trick for me. Sometimes you also run into hiccups on your computer so try restarting your computer. Your computer may not be able to handle android studio if so there is nothing you can do. Consequently, you may not have the right ram requirements. Finally, If all else fails you can try to delete then reinstall android studio.

JSON Parse File Path

Loading local JSON file

Use something like this

$.getJSON("../../data/file.json", function(json) {
    console.log(json); // this will show the info in firebug console 
    alert(json);
});

Determine a user's timezone

A simple way to do it is by using:

new Date().getTimezoneOffset();

Changing java platform on which netbeans runs

In my Windows 7 box I found netbeans.conf in <Drive>:\<Program Files folder>\<NetBeans installation folder>\etc . Thanks all.

What is a 'NoneType' object?

NoneType is simply the type of the None singleton:

>>> type(None)
<type 'NoneType'>

From the latter link above:

None

The sole value of the type NoneType. None is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments to None are illegal and raise a SyntaxError.

In your case, it looks like one of the items you are trying to concatenate is None, hence your error.

Could not install packages due to an EnvironmentError: [Errno 13]

try this command line below for MacOS to check user's permission.

$ sudo python -m pip install --user --upgrade pip

Function stoi not declared

stoi is a C++11 function. If you aren't using a compiler that understands C++11, this simply won't compile.

You can use a stringstream instead to read the input:

stringstream ss(hours0);
ss >> hours;

Working with Enums in android

There has been some debate around this point of contention, but even in the most recent documents android suggests that it's not such a good idea to use enums in an android application. The reason why is because they use up more memory than a static constants variable. Here is a document from a page of 2014 that advises against the use of enums in an android application. http://developer.android.com/training/articles/memory.html#Overhead

I quote:

Be aware of memory overhead

Be knowledgeable about the cost and overhead of the language and libraries you are using, and keep this information in mind when you design your app, from start to finish. Often, things on the surface that look innocuous may in fact have a large amount of overhead. Examples include:

  • Enums often require more than twice as much memory as static constants. You should strictly avoid using enums on Android.

  • Every class in Java (including anonymous inner classes) uses about 500 bytes of code.

  • Every class instance has 12-16 bytes of RAM overhead.

  • Putting a single entry into a HashMap requires the allocation of an additional entry object that takes 32 bytes (see the previous section about optimized data containers).

A few bytes here and there quickly add up—app designs that are class- or object-heavy will suffer from this overhead. That can leave you in the difficult position of looking at a heap analysis and realizing your problem is a lot of small objects using up your RAM.

There has been some places where they say that these tips are outdated and no longer valuable, but the reason they keep repeating it, must be there is some truth to it. Writing an android application is something you should keep as lightweight as possible for a smooth user experience. And every little inch of performance counts!

Select and trigger click event of a radio button in jquery

You are triggering the event before the event is even bound.

Just move the triggering of the event to after attaching the event.

$(document).ready(function() {
  $("#checkbox_div input:radio").click(function() {

    alert("clicked");

   });

  $("input:radio:first").prop("checked", true).trigger("click");

});

Check Fiddle

How does a PreparedStatement avoid or prevent SQL injection?

The problem with SQL injection is, that a user input is used as part of the SQL statement. By using prepared statements you can force the user input to be handled as the content of a parameter (and not as a part of the SQL command).

But if you don't use the user input as a parameter for your prepared statement but instead build your SQL command by joining strings together, you are still vulnerable to SQL injections even when using prepared statements.

How to specify line breaks in a multi-line flexbox layout?

Another possible solution that doesn't require to add any extra markup is to add some dynamic margin to separate the elements.

In the case of the example, this can be done with the help of calc(), just adding margin-left and margin-right to the 3n+2 element (2, 5, 8)

.item:nth-child(3n+2) {
  background: silver;
  margin: 10px calc(50% - 175px);
}

Snippet Example

_x000D_
_x000D_
.container {_x000D_
  background: tomato;_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  align-content: space-between;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.item {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: gold;_x000D_
  border: 1px solid black;_x000D_
  font-size: 30px;_x000D_
  line-height: 100px;_x000D_
  text-align: center;_x000D_
  margin: 10px;_x000D_
}_x000D_
.item:nth-child(3n+2) {_x000D_
  background: silver;_x000D_
  margin: 10px calc(50% - 175px);_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="item">1</div>_x000D_
  <div class="item">2</div>_x000D_
  <div class="item">3</div>_x000D_
  <div class="item">4</div>_x000D_
  <div class="item">5</div>_x000D_
  <div class="item">6</div>_x000D_
  <div class="item">7</div>_x000D_
  <div class="item">8</div>_x000D_
  <div class="item">9</div>_x000D_
  <div class="item">10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is *.o file?

You've gotten some answers, and most of them are correct, but miss what (I think) is probably the point here.

My guess is that you have a makefile you're trying to use to create an executable. In case you're not familiar with them, makefiles list dependencies between files. For a really simple case, it might have something like:

myprogram.exe: myprogram.o
    $(CC) -o myprogram.exe myprogram.o

myprogram.o: myprogram.cpp
    $(CC) -c myprogram.cpp

The first line says that myprogram.exe depends on myprogram.o. The second line tells how to create myprogram.exe from myprogram.o. The third and fourth lines say myprogram.o depends on myprogram.cpp, and how to create myprogram.o from myprogram.cpp` respectively.

My guess is that in your case, you have a makefile like the one above that was created for gcc. The problem you're running into is that you're using it with MS VC instead of gcc. As it happens, MS VC uses ".obj" as the extension for its object files instead of ".o".

That means when make (or its equivalent built into the IDE in your case) tries to build the program, it looks at those lines to try to figure out how to build myprogram.exe. To do that, it sees that it needs to build myprogram.o, so it looks for the rule that tells it how to build myprogram.o. That says it should compile the .cpp file, so it does that.

Then things break down -- the VC++ compiler produces myprogram.obj instead of myprogram.o as the object file, so when it tries to go to the next step to produce myprogram.exe from myprogram.o, it finds that its attempt at creating myprogram.o simply failed. It did what the rule said to do, but that didn't produce myprogram.o as promised. It doesn't know what to do, so it quits and give you an error message.

The cure for that specific problem is probably pretty simple: edit the make file so all the object files have an extension of .obj instead of .o. There's room for a lot of question whether that will fix everything though -- that may be all you need, or it may simply lead to other (probably more difficult) problems.

Why do you need ./ (dot-slash) before executable or script name to run it in bash?

When you include the '.' you are essentially giving the "full path" to the executable bash script, so your shell does not need to check your PATH variable. Without the '.' your shell will look in your PATH variable (which you can see by running echo $PATH to see if the command you typed lives in any of the folders on your PATH. If it doesn't (as is the case with manage.py) it says it can't find the file. It is considered bad practice to include the current directory on your PATH, which is explained reasonably well here: http://www.faqs.org/faqs/unix-faq/faq/part2/section-13.html

How to downgrade to older version of Gradle

Got to

gradle-wrapper.properties

Change the version of the below mentioned distribution (gradle-5.6.4-bin.zip)

distributionUrl=https://services.gradle.org/distributions/gradle-5.6.4-bin.zip

HTML img tag: title attribute vs. alt attribute?

ALT Attribute

The alt attribute is defined in a set of tags (namely, img, area and optionally for input and applet) to allow you to provide a text equivalent for the object.

A text equivalent brings the following benefits to your web site and its visitors in the following common situations:

  • nowadays, Web browsers are available in a very wide variety of platforms with very different capacities; some cannot display images at all or only a restricted set of type of images; some can be configured to not load images. If your code has the alt attribute set in its images, most of these browsers will display the description you gave instead of the images
  • some of your visitors cannot see images, be they blind, color-blind, low-sighted; the alt attribute is of great help for those people that can rely on it to have a good idea of what's on your page
  • search engine bots belong to the two above categories: if you want your website to be indexed as well as it deserves, use the alt attribute to make sure that they won't miss important sections of your pages.

Title Attribute

The objective of this technique is to provide context sensitive help for users as they enter data in forms by providing the help information in a title attribute. The help may include format information or examples of input.

Example 1: A pulldown menu that limits the scope of a search
A search form uses a pulldown menu to limit the scope of the search. The pulldown menu is immediately adjacent to the text field used to enter the search term. The relationship between the search field and the pulldown menu is clear to users who can see the visual design, which does not have room for a visible label. The title attribute is used to identify the select menu. The title attribute can be spoken by screen readers or displayed as a tool tip for people using screen magnifiers.

<label for="searchTerm">Search for:</label>
<input id="searchTerm" type="text" size="30" value="" name="searchTerm">
<select title="Search in" id="scope">
    ...
</select> 

Example 2: Input fields for a phone number
A Web page contains controls for entering a phone number in the United States, with three fields for area code, exchange, and last four digits.

<fieldset>
    <legend>Phone number</legend>
    <input id="areaCode" name="areaCode" title="Area Code" type="text" size="3" value="" >
    <input id="exchange" name="exchange" title="First three digits of phone number" type="text" size="3" value="" >
    <input id="lastDigits" name="lastDigits" title="Last four digits of phone number" type="text" size="4" value="" >
</fieldset> 

Example 3: A Search Function A Web page contains a text field where the user can enter search terms and a button labeled "Search" for performing the search. The title attribute is used to identify the form control and the button is positioned right after the text field so that it is clear to the user that the text field is where the search term should be entered.

<input type="text" title="Type search term here"/> <input type="submit" value="Search"/>

Example 4: A data table of form controls
A data table of form controls needs to associate each control with the column and row headers for that cell. Without a title (or off-screen LABEL) it is difficult for non-visual users to pause and interrogate for corresponding row/column header values using their assistive technology while tabbing through the form.

For example, a survey form has four column headers in first row: Question, Agree, Undecided, Disagree. Each following row contains a question and a radio button in each cell corresponding to answer choice in the three columns. The title attribute for every radio button is a concatenation of the answer choice (column header) and the text of the question (row header) with a hyphen or colon as a separator.

Img Element

Allowed attributes mentioned at MDN.

  • alt
  • crossorigin
  • decoding
  • height
  • importance (experimental api)
  • intrinsicsize (experimental api)
  • ismap
  • referrerpolicy (experimental api)
  • src
  • srcset
  • width
  • usemap

As you can see title attribute is not allowed inside img element. I would use alt attribute and if requires I would use CSS (Example: pseudo class :hover) instead of title attribute.

cleanest way to skip a foreach if array is empty

foreach((array)$items as $item) {}

Html helper for <input type="file" />

You can also use:

@using (Html.BeginForm("Upload", "File", FormMethod.Post, new { enctype = "multipart/form-data" }))
{ 
    <p>
        <input type="file" id="fileUpload" name="fileUpload" size="23" />
    </p>
    <p>
        <input type="submit" value="Upload file" /></p> 
}

JavaScript listener, "keypress" doesn't detect backspace?

Something I wrote up incase anyone comes across an issue with people hitting backspace while thinking they are in a form field

window.addEventListener("keydown", function(e){
    /*
     * keyCode: 8
     * keyIdentifier: "U+0008"
    */
    if(e.keyCode === 8 && document.activeElement !== 'text') {
        e.preventDefault();
        alert('Prevent page from going back');
    }
});

How to write a JSON file in C#?

Update 2020: It's been 7 years since I wrote this answer. It still seems to be getting a lot of attention. In 2013 Newtonsoft Json.Net was THE answer to this problem. Now it's still a good answer to this problem but it's no longer the the only viable option. To add some up-to-date caveats to this answer:

  • .Net Core now has the spookily similar System.Text.Json serialiser (see below)
  • The days of the JavaScriptSerializer have thankfully passed and this class isn't even in .Net Core. This invalidates a lot of the comparisons ran by Newtonsoft.
  • It's also recently come to my attention, via some vulnerability scanning software we use in work that Json.Net hasn't had an update in some time. Updates in 2020 have dried up and the latest version, 12.0.3, is over a year old.
  • The speed tests quoted below are comparing an older version of Json.Nt (version 6.0 and like I said the latest is 12.0.3) with an outdated .Net Framework serialiser.

Are Json.Net's days numbered? It's still used a LOT and it's still used by MS librarties. So probably not. But this does feel like the beginning of the end for this library that may well of just run it's course.


Update since .Net Core 3.0

A new kid on the block since writing this is System.Text.Json which has been added to .Net Core 3.0. Microsoft makes several claims to how this is, now, better than Newtonsoft. Including that it is faster than Newtonsoft. as below, I'd advise you to test this yourself .


I would recommend Json.Net, see example below:

List<data> _data = new List<data>();
_data.Add(new data()
{
    Id = 1,
    SSN = 2,
    Message = "A Message"
});

string json = JsonConvert.SerializeObject(_data.ToArray());

//write string to file
System.IO.File.WriteAllText(@"D:\path.txt", json);

Or the slightly more efficient version of the above code (doesn't use a string as a buffer):

//open file stream
using (StreamWriter file = File.CreateText(@"D:\path.txt"))
{
     JsonSerializer serializer = new JsonSerializer();
     //serialize object directly into file stream
     serializer.Serialize(file, _data);
}

Documentation: Serialize JSON to a file


Why? Here's a feature comparison between common serialisers as well as benchmark tests .

Below is a graph of performance taken from the linked article:

enter image description here

This separate post, states that:

Json.NET has always been memory efficient, streaming the reading and writing large documents rather than loading them entirely into memory, but I was able to find a couple of key places where object allocations could be reduced...... (now) Json.Net (6.0) allocates 8 times less memory than JavaScriptSerializer


Benchmarks appear to be Json.Net 5, the current version (on writing) is 10. What version of standard .Net serialisers used is not mentioned

These tests are obviously from the developers who maintain the library. I have not verified their claims. If in doubt test them yourself.

Configure DataSource programmatically in Spring Boot

My project of spring-boot has run normally according to your assistance. The yaml datasource configuration is:

spring:
  # (DataSourceAutoConfiguration & DataSourceProperties)
  datasource:
    name: ds-h2
    url: jdbc:h2:D:/work/workspace/fdata;DATABASE_TO_UPPER=false
    username: h2
    password: h2
    driver-class: org.h2.Driver

Custom DataSource

@Configuration
@Component
public class DataSourceBean {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    @Primary
    public DataSource getDataSource() {
        return DataSourceBuilder
                .create()
//                .url("jdbc:h2:D:/work/workspace/fork/gs-serving-web-content/initial/data/fdata;DATABASE_TO_UPPER=false")
//                .username("h2")
//                .password("h2")
//                .driverClassName("org.h2.Driver")
                .build();
    }
}

How to find index of list item in Swift?

Swift 4

For reference types:

extension Array where Array.Element: AnyObject {

    func index(ofElement element: Element) -> Int? {
        for (currentIndex, currentElement) in self.enumerated() {
            if currentElement === element {
                return currentIndex
            }
        }
        return nil
    }
}

Display an array in a readable/hierarchical format

print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.

foreach($data as $d){
  foreach($d as $v){
    echo $v."\n";
  }
}

It is more efficient to use if-return-return or if-else-return?

Since the return statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).

The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if condition is false anyway.

Note that Python supports a syntax that allows you to use only one return statement in your case:

return A+1 if A > B else A-1

(grep) Regex to match non-ASCII characters?

This turned out to be very flexible and extensible. $field =~ s/[^\x00-\x7F]//g ; # thus all non ASCII or specific items in question could be cleaned. Very nice either in selection or pre-processing of items that will eventually become hash keys.

Git Extensions: Win32 error 487: Couldn't reserve space for cygwin's heap, Win32 error 0

I ran into this today. Led by Greg Hewgill's answer, I looked at running processes on my system to see if anything was "stuck" or if other users were logged into the machine doing anything with git. I then launched cygwin (installed separately) on this particular machine. It launched ok. I closed it and then tried the Git Extensions again (I was trying a pull operation) and it worked. Not sure if the launching of cygwin cleared something that was shared but this is the first time I ran into this error and this seemed to fix it for me.

What is the difference between "long", "long long", "long int", and "long long int" in C++?

long is equivalent to long int, just as short is equivalent to short int. A long int is a signed integral type that is at least 32 bits, while a long long or long long int is a signed integral type is at least 64 bits.

This doesn't necessarily mean that a long long is wider than a long. Many platforms / ABIs use the LP64 model - where long (and pointers) are 64 bits wide. Win64 uses the LLP64, where long is still 32 bits, and long long (and pointers) are 64 bits wide.

There's a good summary of 64-bit data models here.

long double doesn't guarantee much other than it will be at least as wide as a double.

How do I specify unique constraint for multiple columns in MySQL?

If You are creating table in mysql then use following :

create table package_template_mapping (
mapping_id  int(10) not null auto_increment  ,
template_id int(10) NOT NULL ,
package_id  int(10) NOT NULL ,
remark      varchar(100),
primary key (mapping_id) ,
UNIQUE KEY template_fun_id (template_id , package_id)
);

Encode html entities in javascript

You can use regex to replace any character in a given unicode range with its html entity equivalent. The code would look something like this:

var encodedStr = rawStr.replace(/[\u00A0-\u9999<>\&]/g, function(i) {
   return '&#'+i.charCodeAt(0)+';';
});

This code will replace all characters in the given range (unicode 00A0 - 9999, as well as ampersand, greater & less than) with their html entity equivalents, which is simply &#nnn; where nnn is the unicode value we get from charCodeAt.

See it in action here: http://jsfiddle.net/E3EqX/13/ (this example uses jQuery for element selectors used in the example. The base code itself, above, does not use jQuery)

Making these conversions does not solve all the problems -- make sure you're using UTF8 character encoding, make sure your database is storing the strings in UTF8. You still may see instances where the characters do not display correctly, depending on system font configuration and other issues out of your control.

Documentation

Regex to get the words after matching string

This is a Python solution.

import re

line ="""Subject:
    Security ID:        S-1-5-21-3368353891-1012177287-890106238-22451
    Account Name:       ChamaraKer
    Account Domain:     JIC
    Logon ID:       0x1fffb

Object:
    Object Server:  Security
    Object Type:    File
    Object Name:    D:\ApacheTomcat\apache-tomcat-6.0.36\logs\localhost.2013-07-01.log
    Handle ID:  0x11dc"""



regex = (r'Object Name:\s+(.*)')
match1= re.findall(regex,line)
print (match1)

*** Remote Interpreter Reinitialized  ***
>>> 
['D:\\ApacheTomcat\x07pache-tomcat-6.0.36\\logs\\localhost.2013-07-01.log']
>>> 

"Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project

This error is often caused by incompatible jQuery versions. I encountered the same error with a foundation 6 repository. My repository was using jQuery 3, but foundation requires an earlier version. I then changed it and it worked.

If you look at the version of jQuery required by the foundation 5 dependencies it states "jquery": "~2.1.0".

Can you confirm that you are loading the correct version of jQuery?

I hope this helps.

Importing csv file into R - numeric values read as characters

Including this in the read.csv command worked for me: strip.white = TRUE

(I found this solution here.)

save a pandas.Series histogram plot to file

You can use ax.figure.savefig():

import pandas as pd

s = pd.Series([0, 1])
ax = s.plot.hist()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in Philip Cloud's answer, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

Yes, it is, you will want to use the static Load method on the Assembly class, and then call then call the CreateInstance method on the Assembly instance returned to you from the call to Load.

Also, you can call one of the other static methods starting with "Load" on the Assembly class, depending on your needs.

Converting String to Int using try/except in Python

Firstly, try / except are not functions, but statements.

To convert a string (or any other type that can be converted) to an integer in Python, simply call the int() built-in function. int() will raise a ValueError if it fails and you should catch this specifically:

In Python 2.x:

>>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print '%s as an int is %d' % (str(value), int(value))
...     except ValueError as ex:
...         print '"%s" cannot be converted to an int: %s' % (value, ex)
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'

In Python 3.x

the syntax has changed slightly:

>>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
...     try:
...         print('%s as an int is %d' % (str(value), int(value)))
...     except ValueError as ex:
...         print('"%s" cannot be converted to an int: %s' % (value, ex))
...
12345 as an int is 12345
67890 as an int is 67890
3.14 as an int is 3
42 as an int is 42
21 as an int is 21
254 as an int is 254
"Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'