Programs & Examples On #Nsmutabledictionary

NSMutableDictionary is the mutable version of NSDictionary.

for each loop in Objective-C for accessing NSMutable dictionary

The easiest way to enumerate a dictionary is

for (NSString *key in tDictionary.keyEnumerator) 
{
    //do something here;
}

where tDictionary is the NSDictionary or NSMutableDictionary you want to iterate.

How can we store into an NSDictionary? What is the difference between NSDictionary and NSMutableDictionary?

The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...

...create an NSDictionary

NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects 
                                                       forKeys:keys];

...iterate over it

for (id key in dictionary) {
    NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}

...make it mutable

NSMutableDictionary *mutableDict = [dictionary mutableCopy];

Note: historic version before 2010: [[dictionary mutableCopy] autorelease]

...and alter it

[mutableDict setObject:@"value3" forKey:@"key3"];

...then store it to a file

[mutableDict writeToFile:@"path/to/file" atomically:YES];

...and read it back again

NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];

...read a value

NSString *x = [anotherDict objectForKey:@"key1"];

...check if a key exists

if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");

...use scary futuristic syntax

From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]

nodeJs callbacks simple example

const fs = require('fs');

fs.stat('input.txt', function (err, stats) {
    if(err){
        console.log(err);
    } else {
        console.log(stats);
        console.log('Completed Reading File');
    }
});

'fs' is a node module which helps you to read file. Callback function will make sure that your file named 'input.txt' is completely read before it gets executed. fs.stat() function is to get file information like file size, date created and date modified.

Material effect on button with background color

The @ianhanniballake's answer is absolutely correct and simple. But it took me few days to understand. For someone who don't understand his answer, here is more detail implementation

<Button
        android:id="@+id/btn"
        style="@style/MaterialButton"
        ... />


<style name="MaterialButton" parent="Widget.AppCompat.Button.Colored">
    <item name="android:theme">@style/Theme.MaterialButton</item>
   ...
</style>


<style name="Theme.MaterialButton" parent="YourTheme">
    <item name="colorAccent">@color/yourAccentColor</item>
    <item name="colorButtonNormal">@color/yourButtonNormalColor</item>
</style>

===Or===

<Button
        android:id="@+id/btn"
        style="@style/Widget.AppCompat.Button.Colored"
        android:theme="@style/Theme.MaterialButton" />

<style name="Theme.MaterialButton" parent="YourTheme">
    <item name="colorAccent">@color/yourAccentColor</item>
    <item name="colorButtonNormal">@color/yourButtonNormalColor</item>
</style>

How do I return the response from an asynchronous call?

The simplest solution is create a JavaScript function and call it for the Ajax success callback.

function callServerAsync(){
    $.ajax({
        url: '...',
        success: function(response) {

            successCallback(response);
        }
    });
}

function successCallback(responseObj){
    // Do something like read the response and show data
    alert(JSON.stringify(responseObj)); // Only applicable to JSON response
}

function foo(callback) {

    $.ajax({
        url: '...',
        success: function(response) {
           return callback(null, response);
        }
    });
}

var result = foo(function(err, result){
          if (!err)
           console.log(result);    
}); 

Detect Click into Iframe using JavaScript

Combining above answer with ability to click again and again without clicking outside iframe.

    var eventListener = window.addEventListener('blur', function() {
    if (document.activeElement === document.getElementById('contentIFrame')) {
        toFunction(); //function you want to call on click
        setTimeout(function(){ window.focus(); }, 0);
    }
    window.removeEventListener('blur', eventListener );
    });

Pass values of checkBox to controller action in asp.net mvc4

For the MVC Controller method, use a nullable boolean type:

public ActionResult Index( string responsables, bool? checkResp) { etc. }

Then if the check box is checked, checkResp will be true. If not, it will be null.

Proper MIME type for OTF fonts

Ignore the chrome warning. There is no standard MIME type for OTF fonts.

font/opentype may silence the warning, but that doesn't make it the "right" thing to do.

Arguably, you're better off making one up, e.g. with "application/x-opentype" because at least "application" is a registered content type, while "font" is not.

Update: OTF remains a problem, but WOFF grew an IANA MIME type of application/font-woff in January 2013.

Update 2: OTF has grown a MIME type: application/font-sfnt In March 2013. This type also applies to .ttf

Asyncio.gather vs asyncio.wait

A very important distinction, which is easy to miss, is the default bheavior of these two functions, when it comes to exceptions.


I'll use this example to simulate a coroutine that will raise exceptions, sometimes -

import asyncio
import random


async def a_flaky_tsk(i):
    await asyncio.sleep(i)  # bit of fuzz to simulate a real-world example

    if i % 2 == 0:
        print(i, "ok")
    else:
        print(i, "crashed!")
        raise ValueError

coros = [a_flaky_tsk(i) for i in range(10)]

await asyncio.gather(*coros) outputs -

0 ok
1 crashed!
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 20, in <module>
    asyncio.run(main())
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/runners.py", line 43, in run
    return loop.run_until_complete(main)
  File "/Users/dev/.pyenv/versions/3.8.2/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete
    return future.result()
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 17, in main
    await asyncio.gather(*coros)
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

As you can see, the coros after index 1 never got to execute.


But await asyncio.wait(coros) continues to execute tasks, even if some of them fail -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
Task exception was never retrieved
future: <Task finished name='Task-10' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-8' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-2' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-9' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError
Task exception was never retrieved
future: <Task finished name='Task-3' coro=<a_flaky_tsk() done, defined at /Users/dev/PycharmProjects/trading/xxx.py:6> exception=ValueError()>
Traceback (most recent call last):
  File "/Users/dev/PycharmProjects/trading/xxx.py", line 12, in a_flaky_tsk
    raise ValueError
ValueError

Ofcourse, this behavior can be changed for both by using -

asyncio.gather(..., return_exceptions=True)

or,

asyncio.wait([...], return_when=asyncio.FIRST_EXCEPTION)


But it doesn't end here!

Notice: Task exception was never retrieved in the logs above.

asyncio.wait() won't re-raise exceptions from the child tasks until you await them individually. (The stacktrace in the logs are just messages, they cannot be caught!)

done, pending = await asyncio.wait(coros)
for tsk in done:
    try:
        await tsk
    except Exception as e:
        print("I caught:", repr(e))

Output -

0 ok
1 crashed!
2 ok
3 crashed!
4 ok
5 crashed!
6 ok
7 crashed!
8 ok
9 crashed!
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()
I caught: ValueError()

On the other hand, to catch exceptions with asyncio.gather(), you must -

results = await asyncio.gather(*coros, return_exceptions=True)
for result_or_exc in results:
    if isinstance(result_or_exc, Exception):
        print("I caught:", repr(result_or_exc))

(Same output as before)

If using maven, usually you put log4j.properties under java or resources?

Just putting it in src/main/resources will bundle it inside the artifact. E.g. if your artifact is a JAR, you will have the log4j.properties file inside it, losing its initial point of making logging configurable.

I usually put it in src/main/resources, and set it to be output to target like so:

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${project.build.directory}</targetPath>
            <includes>
                <include>log4j.properties</include>
            </includes>
        </resource>
    </resources>
</build>

Additionally, in order for log4j to actually see it, you have to add the output directory to the class path. If your artifact is an executable JAR, you probably used the maven-assembly-plugin to create it. Inside that plugin, you can add the current folder of the JAR to the class path by adding a Class-Path manifest entry like so:

<plugin>
    <artifactId>maven-assembly-plugin</artifactId>
    <configuration>
        <archive>
            <manifest>
                <mainClass>com.your-package.Main</mainClass>
            </manifest>
            <manifestEntries>
                <Class-Path>.</Class-Path>
            </manifestEntries>
        </archive>
        <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
        </descriptorRefs>
    </configuration>
    <executions>
        <execution>
            <id>make-assembly</id> <!-- this is used for inheritance merges -->
            <phase>package</phase> <!-- bind to the packaging phase -->
            <goals>
                <goal>single</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Now the log4j.properties file will be right next to your JAR file, independently configurable.

To run your application directly from Eclipse, add the resources directory to your classpath in your run configuration: Run->Run Configurations...->Java Application->New select the Classpath tab, select Advanced and browse to your src/resources directory.

Take a full page screenshot with Firefox on the command-line

The Developer Toolbar GCLI and Shift+F2 shortcut were removed in Firefox version 60. To take a screenshot in 60 or newer:

  • press Ctrl+Shift+K to open the developer console (? Option+? Command+K on macOS)
  • type :screenshot or :screenshot --fullpage

Find out more regarding screenshots and other features


For Firefox versions < 60:

Press Shift+F2 or go to Tools > Web Developer > Developer Toolbar to open a command line. Write:

screenshot

and press Enter in order to take a screenshot.

To fully answer the question, you can even save the whole page, not only the visible part of it:

screenshot --fullpage

And to copy the screenshot to clipboard, use --clipboard option:

screenshot --clipboard --fullpage

Firefox 18 changes the way arguments are passed to commands, you have to add "--" before them.

You can find some documentation and the full list of commands here.

PS. The screenshots are saved into the downloads directory by default.

angularjs to output plain text instead of html

jQuery is about 40 times SLOWER, please do not use jQuery for that simple task.

function htmlToPlaintext(text) {
  return text ? String(text).replace(/<[^>]+>/gm, '') : '';
}

usage :

var plain_text = htmlToPlaintext( your_html );

With angular.js :

angular.module('myApp.filters', []).
  filter('htmlToPlaintext', function() {
    return function(text) {
      return  text ? String(text).replace(/<[^>]+>/gm, '') : '';
    };
  }
);

use :

<div>{{myText | htmlToPlaintext}}</div>  

Get Client Machine Name in PHP

PHP Manual says:

gethostname (PHP >= 5.3.0) gethostname — Gets the host name

Look:

<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

http://php.net/manual/en/function.gethostname.php

Enjoy

Android: How to overlay a bitmap and draw over a bitmap?

You can do something like this:

public void putOverlay(Bitmap bitmap, Bitmap overlay) {
    Canvas canvas = new Canvas(bitmap);
    Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG);
    canvas.drawBitmap(overlay, 0, 0, paint);
} 

The idea is very simple: Once you associate a bitmap with a canvas, you can call any of the canvas' methods to draw over the bitmap.

This will work for bitmaps that have transparency. A bitmap will have transparency, if it has an alpha channel. Look at Bitmap.Config. You'd probably want to use ARGB_8888.

Important: Look at this Android sample for the different ways you can perform drawing. It will help you a lot.

Performance wise (memory-wise, to be exact), Bitmaps are the best objects to use, since they simply wrap a native bitmap. An ImageView is a subclass of View, and a BitmapDrawable holds a Bitmap inside, but it holds many other things as well. But this is an over-simplification. You can suggest a performance-specific scenario for a precise answer.

What is a LAMP stack?

Lamp stack stands for Linux Apache Mysql PHP

there is also Mean Stack MongoDB ExpressJS AngularJS NodeJS

Insert string in beginning of another string

The first case is done using the insert() method:

_sb.insert(0, "Hello ");

The latter case can be done using the overloaded + operator on Strings. This uses a StringBuilder behind the scenes:

String s2 = "Hello " + _s;

Reading JSON POST using PHP

Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.

$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");

getUserLocation($ip_srv);

Function:

function getUserLocation($services) {

        $ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout

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

            // Configuring curl options
            $options = array (
                CURLOPT_RETURNTRANSFER => true, // return web page
                //CURLOPT_HEADER => false, // don't return headers
                CURLOPT_HTTPHEADER => array('Content-type: application/json'),
                CURLOPT_FOLLOWLOCATION => true, // follow redirects
                CURLOPT_ENCODING => "", // handle compressed
                CURLOPT_USERAGENT => "test", // who am i
                CURLOPT_AUTOREFERER => true, // set referer on redirect
                CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
                CURLOPT_TIMEOUT => 5, // timeout on response
                CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
            ); 

            // Initializing curl
            $ch = curl_init($services[$i]);
            curl_setopt_array ( $ch, $options );

            $content = curl_exec ( $ch );
            $err = curl_errno ( $ch );
            $errmsg = curl_error ( $ch );
            $header = curl_getinfo ( $ch );
            $httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );

            curl_close ( $ch );

            //echo 'service: ' . $services[$i] . '</br>';
            //echo 'err: '.$err.'</br>';
            //echo 'errmsg: '.$errmsg.'</br>';
            //echo 'httpCode: '.$httpCode.'</br>';
            //print_r($header);
            //print_r(json_decode($content, true));

            if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {

                return json_decode($content, true);

            } 

        }
    }

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

Another option is to use Promise.all to wait for an array of promises to resolve and then act on those.

Code below shows how to wait for all the promises to resolve and then deal with the results once they are all ready (as that seemed to be the objective of the question); Also for illustrative purposes, it shows output during execution (end finishes before middle).

_x000D_
_x000D_
function append_output(suffix, value) {
  $("#output_"+suffix).append(value)
}

function kickOff() {
  let start = new Promise((resolve, reject) => {
    append_output("now", "start")
    resolve("start")
  })
  let middle = new Promise((resolve, reject) => {
    setTimeout(() => {
      append_output("now", " middle")
      resolve(" middle")
    }, 1000)
  })
  let end = new Promise((resolve, reject) => {
    append_output("now", " end")
    resolve(" end")
  })

  Promise.all([start, middle, end]).then(results => {
    results.forEach(
      result => append_output("later", result))
  })
}

kickOff()
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Updated during execution: <div id="output_now"></div>
Updated after all have completed: <div id="output_later"></div>
_x000D_
_x000D_
_x000D_

How can I round a number in JavaScript? .toFixed() returns a string?

Here's a slightly more functional version of the answer m93a provided.

const toFixedNumber = (toFixTo = 2, base = 10) => num => {
  const pow = Math.pow(base, toFixTo)
  return +(Math.round(num * pow) / pow)
}

const oneNumber = 10.12323223

const result1 = toFixedNumber(2)(oneNumber) // 10.12
const result2 = toFixedNumber(3)(oneNumber) // 10.123

// or using pipeline-operator
const result3 = oneNumber |> toFixedNumber(2) // 10.12

How to convert base64 string to image?

Return converted image without saving:

from PIL import Image
import cv2

# Take in base64 string and return cv image
def stringToRGB(base64_string):
    imgdata = base64.b64decode(str(base64_string))
    image = Image.open(io.BytesIO(imgdata))
    return cv2.cvtColor(np.array(image), cv2.COLOR_BGR2RGB)

Stretch image to fit full container width bootstrap

This will do the same as many of the other answers, but will make sides flush with the window, so there is no scroll bars.

<div class="container-fluid">
  <div class="row">
    <div class="col" style="padding: 0;">
       <img src="example.jpg" class="img-responsive" alt="Example">  
    </div>
  </div>
</div>

How do emulators work and how are they written?

I've never done anything so fancy as to emulate a game console but I did take a course once where the assignment was to write an emulator for the machine described in Andrew Tanenbaums Structured Computer Organization. That was fun an gave me a lot of aha moments. You might want to pick that book up before diving in to writing a real emulator.

jQuery.ajax handling continue responses: "success:" vs ".done"?

From JQuery Documentation

The jqXHR objects returned by $.ajax() as of jQuery 1.5 implement the Promise interface, giving them all the properties, methods, and behavior of a Promise (see Deferred object for more information). These methods take one or more function arguments that are called when the $.ajax() request terminates. This allows you to assign multiple callbacks on a single request, and even to assign callbacks after the request may have completed. (If the request is already complete, the callback is fired immediately.) Available Promise methods of the jqXHR object include:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {});

An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); 

(added in jQuery 1.6) An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {});

Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are removed as of jQuery 3.0. You can use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

How to encrypt String in Java

Warning

Do not use this as some kind of security measurement.

The encryption mechanism in this post is a One-time pad, which means that the secret key can be easily recovered by an attacker using 2 encrypted messages. XOR 2 encrypted messages and you get the key. That simple!

Pointed out by Moussa


I am using Sun's Base64Encoder/Decoder which is to be found in Sun's JRE, to avoid yet another JAR in lib. That's dangerous from point of using OpenJDK or some other's JRE. Besides that, is there another reason I should consider using Apache commons lib with Encoder/Decoder?

public class EncryptUtils {
    public static final String DEFAULT_ENCODING = "UTF-8"; 
    static BASE64Encoder enc = new BASE64Encoder();
    static BASE64Decoder dec = new BASE64Decoder();

    public static String base64encode(String text) {
        try {
            return enc.encode(text.getBytes(DEFAULT_ENCODING));
        } catch (UnsupportedEncodingException e) {
            return null;
        }
    }//base64encode

    public static String base64decode(String text) {
        try {
            return new String(dec.decodeBuffer(text), DEFAULT_ENCODING);
        } catch (IOException e) {
            return null;
        }
    }//base64decode

    public static void main(String[] args) {
        String txt = "some text to be encrypted";
        String key = "key phrase used for XOR-ing";
        System.out.println(txt + " XOR-ed to: " + (txt = xorMessage(txt, key)));

        String encoded = base64encode(txt);       
        System.out.println(" is encoded to: " + encoded + " and that is decoding to: " + (txt = base64decode(encoded)));
        System.out.print("XOR-ing back to original: " + xorMessage(txt, key));
    }

    public static String xorMessage(String message, String key) {
        try {
            if (message == null || key == null) return null;

            char[] keys = key.toCharArray();
            char[] mesg = message.toCharArray();

            int ml = mesg.length;
            int kl = keys.length;
            char[] newmsg = new char[ml];

            for (int i = 0; i < ml; i++) {
                newmsg[i] = (char)(mesg[i] ^ keys[i % kl]);
            }//for i

            return new String(newmsg);
        } catch (Exception e) {
            return null;
        }
    }//xorMessage
}//class

docker: Error response from daemon: Get https://registry-1.docker.io/v2/: Service Unavailable. IN DOCKER , MAC

Just to add, in case anyone else comes across this issue.

On a Mac I had to logout and log back in.

docker logout

docker login 

Then it prompts for username (NOTE: Not email) and password. (Need an account on https://hub.docker.com to pull images down)

Then it worked for me.

I want to declare an empty array in java and then I want do update it but the code is not working

You are creating an array of zero length (no slots to put anything in)

 int array[]={/*nothing in here = array with no elements*/};

and then trying to assign values to array elements (which you don't have, because there are no slots)

array[i] = number; //array[i] = element i in the array of length 0

You need to define a larger array to fit your needs

 int array[] = new int[4]; //Create an array with 4 elements [0],[1],[2] and [3] each containing an int value

Excel formula is only showing the formula rather than the value within the cell in Office 2010

Add an = at the beginning. That makes it a function rather than an entry.

How can I call a shell command in my Perl script?

From Perl HowTo, the most common ways to execute external commands from Perl are:

  • my $files = `ls -la` — captures the output of the command in $files
  • system "touch ~/foo" — if you don't want to capture the command's output
  • exec "vim ~/foo" — if you don't want to return to the script after executing the command
  • open(my $file, '|-', "grep foo"); print $file "foo\nbar" — if you want to pipe input into the command

error C2220: warning treated as error - no 'object' file generated

As a side-note, you can enable/disable individual warnings using #pragma. You can have a look at the documentation here

From the documentation:

// pragma_warning.cpp
// compile with: /W1
#pragma warning(disable:4700)
void Test() {
   int x;
   int y = x;   // no C4700 here
   #pragma warning(default:4700)   // C4700 enabled after Test ends
}

int main() {
   int x;
   int y = x;   // C4700
}

How would I get everything before a : in a string Python

Using index:

>>> string = "Username: How are you today?"
>>> string[:string.index(":")]
'Username'

The index will give you the position of : in string, then you can slice it.

If you want to use regex:

>>> import re
>>> re.match("(.*?):",string).group()
'Username'                       

match matches from the start of the string.

you can also use itertools.takewhile

>>> import itertools
>>> "".join(itertools.takewhile(lambda x: x!=":", string))
'Username'

Reading entire html file to String?

For string operations use StringBuilder or StringBuffer classes for accumulating string data blocks. Do not use += operations for string objects. String class is immutable and you will produce a large amount of string objects upon runtime and it will affect on performance.

Use .append() method of StringBuilder/StringBuffer class instance instead.

Get GMT Time in Java

From my experience, the bundled Calendar and Date classes in Java can yield undersired effect. If you wouldn't mind upgrading to Java 8, then consider using ZonedDateTime

like so:

ZonedDateTime currentDate = ZonedDateTime.now( ZoneOffset.UTC );

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

C/C++ macro string concatenation

Hint: The STRINGIZE macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include the header file - then the compiler will happily put the purported macro name into the string with no error.

If you intend that the argument to STRINGIZE is always a macro with a normal C value, then

#define STRINGIZE(A) ((A),STRINGIZE_NX(A))

will expand it once and check it for validity, discard that, and then expand it again into a string.

It took me a while to figure out why STRINGIZE(ENOENT) was ending up as "ENOENT" instead of "2"... I hadn't included errno.h.

Change color of PNG image via CSS?

_x000D_
_x000D_
body{_x000D_
  background: #333 url(/images/classy_fabric.png);_x000D_
  width: 430px;_x000D_
  margin: 0 auto;_x000D_
  padding: 30px;_x000D_
}_x000D_
.preview{_x000D_
  background: #ccc;_x000D_
  width: 415px;_x000D_
  height: 430px;_x000D_
  border: solid 10px #fff;_x000D_
}_x000D_
_x000D_
input[type='radio'] {_x000D_
  -webkit-appearance: none;_x000D_
  -moz-appearance: none;_x000D_
  width: 25px;_x000D_
  height: 25px;_x000D_
  margin: 5px 0 5px 5px;_x000D_
  background-size: 225px 70px;_x000D_
  position: relative;_x000D_
  float: left;_x000D_
  display: inline;_x000D_
  top: 0;_x000D_
  border-radius: 3px;_x000D_
  z-index: 99999;_x000D_
  cursor: pointer;_x000D_
  box-shadow: 1px 1px 1px #000;_x000D_
}_x000D_
_x000D_
input[type='radio']:hover{_x000D_
  -webkit-filter: opacity(.4);_x000D_
  filter: opacity(.4);    _x000D_
}_x000D_
_x000D_
.red{_x000D_
  background: red;_x000D_
}_x000D_
_x000D_
.red:checked{_x000D_
  background: linear-gradient(brown, red)_x000D_
}_x000D_
_x000D_
.green{_x000D_
  background: green;_x000D_
}_x000D_
_x000D_
.green:checked{_x000D_
  background: linear-gradient(green, lime);_x000D_
}_x000D_
_x000D_
.yellow{_x000D_
  background: yellow;_x000D_
}_x000D_
_x000D_
.yellow:checked{_x000D_
  background: linear-gradient(orange, yellow);_x000D_
}_x000D_
_x000D_
.purple{_x000D_
  background: purple;_x000D_
}_x000D_
_x000D_
.pink{_x000D_
  background: pink;_x000D_
}_x000D_
_x000D_
.purple:checked{_x000D_
  background: linear-gradient(purple, violet);_x000D_
}_x000D_
_x000D_
.red:checked ~ img{_x000D_
  -webkit-filter: opacity(.5) drop-shadow(0 0 0 red);_x000D_
  filter: opacity(.5) drop-shadow(0 0 0 red);_x000D_
}_x000D_
_x000D_
.green:checked ~ img{_x000D_
  -webkit-filter: opacity(.5) drop-shadow(0 0 0 green);_x000D_
  filter: opacity(.5) drop-shadow(0 0 0 green);_x000D_
}_x000D_
_x000D_
.yellow:checked ~ img{_x000D_
  -webkit-filter: opacity(.5) drop-shadow(0 0 0 yellow);_x000D_
  filter: opacity(.5) drop-shadow(0 0 0 yellow);_x000D_
}_x000D_
_x000D_
.purple:checked ~ img{_x000D_
  -webkit-filter: opacity(.5) drop-shadow(0 0 0 purple);_x000D_
  filter: opacity(.5) drop-shadow(0 0 0 purple);_x000D_
}_x000D_
_x000D_
.pink:checked ~ img{_x000D_
  -webkit-filter: opacity(.5) drop-shadow(0 0 0 pink);_x000D_
  filter: opacity(.5) drop-shadow(0 0 0 pink);_x000D_
}_x000D_
_x000D_
_x000D_
img{_x000D_
  width: 394px;_x000D_
  height: 375px;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.label{_x000D_
  width: 150px;_x000D_
  height: 75px;_x000D_
  position: absolute;_x000D_
  top: 170px;_x000D_
  margin-left: 130px;_x000D_
}_x000D_
_x000D_
::selection{_x000D_
  background: #000;_x000D_
}
_x000D_
<div class="preview">_x000D_
  <input class='red' name='color' type='radio' />_x000D_
  <input class='green' name='color' type='radio' />_x000D_
    <input class='pink' name='color' type='radio' />_x000D_
  <input checked class='yellow' name='color' type='radio' />_x000D_
  <input class='purple' name='color' type='radio' />  _x000D_
  <img src="https://i.stack.imgur.com/bd7VJ.png"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Source: https://codepen.io/taryaoui/pen/EKkcu

NuGet Package Restore Not Working

vs2015 no enable nuget restore problem. My solution:

  1. add folder .nuget, add file NuGet.Config and NuGet.targets in Directory .nuget

  2. each project file add: build

  <RestorePackages>true</RestorePackages>

  <Import Project="$(SolutionDir)\.nuget\NuGet.targets" Condition="Exists('$(SolutionDir)\.nuget\NuGet.targets')" />
  <Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
    <PropertyGroup>
      <ErrorText>This project references NuGet package(s) that are missing on this computer. Enable NuGet Package Restore to download them.  For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
    </PropertyGroup>
    <Error Condition="!Exists('$(SolutionDir)\.nuget\NuGet.targets')" Text="$([System.String]::Format('$(ErrorText)', '$(SolutionDir)\.nuget\NuGet.targets'))" />
  </Target>

Pass in an array of Deferreds to $.when()

To pass an array of values to any function that normally expects them to be separate parameters, use Function.prototype.apply, so in this case you need:

$.when.apply($, my_array).then( ___ );

See http://jsfiddle.net/YNGcm/21/

In ES6, you can use the ... spread operator instead:

$.when(...my_array).then( ___ );

In either case, since it's unlikely that you'll known in advance how many formal parameters the .then handler will require, that handler would need to process the arguments array in order to retrieve the result of each promise.

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

UPDATE table
SET A = IF(A > 0 AND A < 1, 1, IF(A > 1 AND A < 2, 2, A))
WHERE A IS NOT NULL;

you might want to use CEIL() if A is always a floating point value > 0 and <= 2

How to select all instances of a variable and edit variable name in Sublime

Despite much effort, I have not found a built-in or plugin-assisted way to do what you're trying to do. I completely agree that it should be possible, as the program can distinguish foo from buffoon when you first highlight it, but no one seems to know a way of doing it.


However, here are some useful key combos for selecting words in Sublime Text 2:

Ctrl?G - selects all occurrences of the current word (AltF3 on Windows/Linux)

?D - selects the next instance of the current word (CtrlD)

  • ?K,?D - skips the current instance and goes on to select the next one (CtrlK,CtrlD)
  • ?U - "soft undo", moves back to the previous selection (CtrlU)

?E, ?H - uses the current selection as the "Find" field in Find and Replace (CtrlE,CtrlH)

Setting up a cron job in Windows

There's pycron which I really as a Cron implementation for windows, but there's also the built in scheduler which should work just fine for what you need (Control Panel -> Scheduled Tasks -> Add Scheduled Task).

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

_x000D_
_x000D_
function kmpSearch(pattern, text) {_x000D_
  if (pattern.length == 0)_x000D_
    return 0; // Immediate match_x000D_
_x000D_
  // Compute longest suffix-prefix table_x000D_
  var lsp = [0]; // Base case_x000D_
  for (var i = 1; i < pattern.length; i++) {_x000D_
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1];_x000D_
    if (pattern.charAt(i) == pattern.charAt(j))_x000D_
      j++;_x000D_
    lsp.push(j);_x000D_
  }_x000D_
_x000D_
  // Walk through text string_x000D_
  var j = 0; // Number of chars matched in pattern_x000D_
  for (var i = 0; i < text.length; i++) {_x000D_
    while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1]; // Fall back in the pattern_x000D_
    if (text.charAt(i) == pattern.charAt(j)) {_x000D_
      j++; // Next char matched, increment position_x000D_
      if (j == pattern.length)_x000D_
        return i - (j - 1);_x000D_
    }_x000D_
  }_x000D_
  return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
_x000D_
_x000D_

CRON job to run on the last day of the month

You could set up a cron job to run on every day of the month, and have it run a shell script like the following. This script works out whether tomorrow's day number is less than today's (i.e. if tomorrow is a new month), and then does whatever you want.

TODAY=`date +%d`
TOMORROW=`date +%d -d "1 day"`

# See if tomorrow's day is less than today's
if [ $TOMORROW -lt $TODAY ]; then
echo "This is the last day of the month"
# Do stuff...
fi

CSS text-transform capitalize on all caps

JavaScript:

var links = document.getElementsByClassName("link");
for (var i = 0; i < links.length; i++) {
  links[i].innerHTML = links[i].innerHTML.toLowerCase();
}

CSS:

.link { text-transform: capitalize; }

What Khan "ended up doing" (which is cleaner and worked for me) is down in the comments of the post marked as the answer.

how to display data values on Chart.js

Edited @ajhuddy's answer a little. Only for bar charts. My version adds:

  • Fade in animation for the values.
  • Prevent clipping by positioning the value inside the bar if the bar is too high.
  • No blinking.

Example

Downside: When hovering over a bar that has value inside it the value might look a little jagged. I have not found a solution do disable hover effects. It might also need tweaking depending on your own settings.

Configuration:

bar: {
  tooltips: {
    enabled: false
  },
  hover: {
    animationDuration: 0
  },
  animation: {
    onComplete: function() {
      this.chart.controller.draw();
      drawValue(this, 1);
    },
    onProgress: function(state) {
      var animation = state.animationObject;
      drawValue(this, animation.currentStep / animation.numSteps);
    }
  }
}

Helpers:

// Font color for values inside the bar
var insideFontColor = '255,255,255';
// Font color for values above the bar
var outsideFontColor = '0,0,0';
// How close to the top edge bar can be before the value is put inside it
var topThreshold = 20;

var modifyCtx = function(ctx) {
  ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize, 'normal', Chart.defaults.global.defaultFontFamily);
  ctx.textAlign = 'center';
  ctx.textBaseline = 'bottom';
  return ctx;
};

var fadeIn = function(ctx, obj, x, y, black, step) {
  var ctx = modifyCtx(ctx);
  var alpha = 0;
  ctx.fillStyle = black ? 'rgba(' + outsideFontColor + ',' + step + ')' : 'rgba(' + insideFontColor + ',' + step + ')';
  ctx.fillText(obj, x, y);
};

var drawValue = function(context, step) {
  var ctx = context.chart.ctx;

  context.data.datasets.forEach(function (dataset) {
    for (var i = 0; i < dataset.data.length; i++) {
      var model = dataset._meta[Object.keys(dataset._meta)[0]].data[i]._model;
      var textY = (model.y > topThreshold) ? model.y - 3 : model.y + 20;
      fadeIn(ctx, dataset.data[i], model.x, textY, model.y > topThreshold, step);
    }
  });
};

How to call Stored Procedure in Entity Framework 6 (Code-First)?

Mindless passenger has a project that allows for multiple results sets to be returned from a stored proc using entity framework. One of his examples below....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

Missing visible-** and hidden-** in Bootstrap v4

The user Klaro suggested to restore the old visibility classes, which is a good idea. Unfortunately, their solution did not work in my project.

I think that it is a better idea to restore the old mixin of bootstrap, because it is covering all breakpoints which can be individually defined by the user.

Here is the code:

// Restore Bootstrap 3 "hidden" utility classes.
@each $bp in map-keys($grid-breakpoints) {
  .hidden-#{$bp}-up {
    @include media-breakpoint-up($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-down {
    @include media-breakpoint-down($bp) {
      display: none !important;
    }
  }
  .hidden-#{$bp}-only{
    @include media-breakpoint-only($bp){
      display:none !important;
    }
  }
}

In my case, I have inserted this part in a _custom.scss file which is included at this point in the bootstrap.scss:

/*!
 * Bootstrap v4.0.0-beta (https://getbootstrap.com)
 * Copyright 2011-2017 The Bootstrap Authors
 * Copyright 2011-2017 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 */

@import "functions";
@import "variables";
@import "mixins";
@import "custom"; // <-- my custom file for overwriting default vars and adding the snippet from above
@import "print";
@import "reboot";
[..]

Upload DOC or PDF using PHP

You can use

$_FILES['filename']['error'];

If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done

1 : if file size is over limit .... You can find other options by googling

Set the maximum character length of a UITextField

I give a supplementary answer based on @Frouo. I think his answer is the most beautiful way. Becuase it's a common control we can reuse.

private var kAssociationKeyMaxLength: Int = 0

extension UITextField {

    @IBInspectable var maxLength: Int {
        get {
            if let length = objc_getAssociatedObject(self, &kAssociationKeyMaxLength) as? Int {
                return length
            } else {
                return Int.max
            }
        }
        set {
            objc_setAssociatedObject(self, &kAssociationKeyMaxLength, newValue, .OBJC_ASSOCIATION_RETAIN)
            self.addTarget(self, action: #selector(checkMaxLength), for: .editingChanged)
        }
    }

    func checkMaxLength(textField: UITextField) {

        guard !self.isInputMethod(), let prospectiveText = self.text,
            prospectiveText.count > maxLength
            else {
                return
        }

        let selection = selectedTextRange
        let maxCharIndex = prospectiveText.index(prospectiveText.startIndex, offsetBy: maxLength)
        text = prospectiveText.substring(to: maxCharIndex)
        selectedTextRange = selection
    }

    //The method is used to cancel the check when use Chinese Pinyin input method.
    //Becuase the alphabet also appears in the textfield when inputting, we should cancel the check.
    func isInputMethod() -> Bool {
        if let positionRange = self.markedTextRange {
            if let _ = self.position(from: positionRange.start, offset: 0) {
                return true
            }
        }
        return false
    }

}

How do I restart nginx only after the configuration test was successful on Ubuntu?

As of nginx 1.8.0, the correct solution is

sudo nginx -t && sudo service nginx reload

Note that due to a bug, configtest always returns a zero exit code even if the config file has an error.

What are the special dollar sign shell variables?

  • $_ last argument of last command
  • $# number of arguments passed to current script
  • $* / $@ list of arguments passed to script as string / delimited list

off the top of my head. Google for bash special variables.

datetime dtypes in pandas read_csv

You might try passing actual types instead of strings.

import pandas as pd
from datetime import datetime
headers = ['col1', 'col2', 'col3', 'col4'] 
dtypes = [datetime, datetime, str, float] 
pd.read_csv(file, sep='\t', header=None, names=headers, dtype=dtypes)

But it's going to be really hard to diagnose this without any of your data to tinker with.

And really, you probably want pandas to parse the the dates into TimeStamps, so that might be:

pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=True)

Check cell for a specific letter or set of letters

Just use = IF(A1="Bla*","YES","NO"). When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.

Git push results in "Authentication Failed"

I've ran into "$ git fetch fatal: Authentication failed for 'http://...." after my windows password has expired and was changed. Multiple fetches, reboot and even reinstall of git with windows credential manager didn't help.

Surprisingly the right answer somewhere here in comments but not in answers (and some of them are really weird!). You need to go to Control panel -> Credential Manager / Windows Credentials and update you password for git:http://yourrepoaddress

How to read the post request parameters using JavaScript

function getParameterByName(name, url) {
            if (!url) url = window.location.href;
            name = name.replace(/[\[\]]/g, "\\$&");
            var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
                results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, " "));
        }
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");

SMTP Connect() failed. Message was not sent.Mailer error: SMTP Connect() failed

Here is a list of this you should look into when dealing with PHPMailer:

  1. Enable openSSL by un-commenting extension=php_openssl.dll in your PHP.ini
  2. Use $mail->SMTPSecure = 'tls'; and $mail->Port = 587;
  3. Enable debugging for if you are going wrong somewhere else like incorrect username and password etc.

jQuery Ajax calls and the Html.AntiForgeryToken()

I was just implementing this actual problem in my current project. i did it for all ajax-POSTs that needed an authenticated user.

First off i decided to hook my jquery ajax calls so i do not to repeat myself too often. this javascript snippet ensures all ajax (post) calls will add my request validation token to the request. Note: the name __RequestVerificationToken is used by the .Net framework so i can utilize the standard Anti-CSRF features as shown below.

$(document).ready(function () {
    var securityToken = $('[name=__RequestVerificationToken]').val();
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

In your Views where you need the token to be available to the above javascript just use the common HTML-Helper. You can basically add this code whereever you want. I placed it within a if(Request.IsAuthenticated) statement:

@Html.AntiForgeryToken() // you can provide a string as salt when needed which needs to match the one on the controller

In your controller simply use the standard ASP.Net MVC Anti-CSRF mechanism. I did it like this (though i actually used Salt).

[HttpPost]
[Authorize]
[ValidateAntiForgeryToken]
public JsonResult SomeMethod(string param)
{
    // do something
    return Json(true);
}

With Firebug or a similar tool you can easily see how your POST requests now have a __RequestVerificationToken parameter appended.

Python error: AttributeError: 'module' object has no attribute

When you import lib, you're importing the package. The only file to get evaluated and run in this case is the 0 byte __init__.py in the lib directory.

If you want access to your function, you can do something like this from lib.mod1 import mod1 and then run the mod12 function like so mod1.mod12().

If you want to be able to access mod1 when you import lib, you need to put an import mod1 inside the __init__.py file inside the lib directory.

iText - add content to existing PDF file

This is the most complicated scenario I can imagine: I have a PDF file created with Ilustrator and modified with Acrobat to have AcroFields (AcroForm) that I'm going to fill with data with this Java code, the result of that PDF file with the data in the fields is modified adding a Document.

Actually in this case I'm dynamically generating a background that is added to a PDF that is also dynamically generated with a Document with an unknown amount of data or pages.

I'm using JBoss and this code is inside a JSP file (should work in any JSP webserver).

Note: if you are using IExplorer you must submit a HTTP form with POST method to be able to download the file. If not you are going to see the PDF code in the screen. This does not happen in Chrome or Firefox.

<%@ page import="java.io.*, com.lowagie.text.*, com.lowagie.text.pdf.*" %><%

response.setContentType("application/download");
response.setHeader("Content-disposition","attachment;filename=listaPrecios.pdf" );  

// -------- FIRST THE PDF WITH THE INFO ----------
String str = "";
// lots of words
for(int i = 0; i < 800; i++) str += "Hello" + i + " ";
// the document
Document doc = new Document( PageSize.A4, 25, 25, 200, 70 );
ByteArrayOutputStream streamDoc = new ByteArrayOutputStream();
PdfWriter.getInstance( doc, streamDoc );
// lets start filling with info
doc.open();
doc.add(new Paragraph(str));
doc.close();
// the beauty of this is the PDF will have all the pages it needs
PdfReader frente = new PdfReader(streamDoc.toByteArray());
PdfStamper stamperDoc = new PdfStamper( frente, response.getOutputStream());

// -------- THE BACKGROUND PDF FILE -------
// in JBoss the file has to be in webinf/classes to be readed this way
PdfReader fondo = new PdfReader("listaPrecios.pdf");
ByteArrayOutputStream streamFondo = new ByteArrayOutputStream();
PdfStamper stamperFondo = new PdfStamper( fondo, streamFondo);
// the acroform
AcroFields form = stamperFondo.getAcroFields();
// the fields 
form.setField("nombre","Avicultura");
form.setField("descripcion","Esto describe para que sirve la lista ");
stamperFondo.setFormFlattening(true);
stamperFondo.close();
// our background is ready
PdfReader fondoEstampado = new PdfReader( streamFondo.toByteArray() );

// ---- ADDING THE BACKGROUND TO EACH DATA PAGE ---------
PdfImportedPage pagina = stamperDoc.getImportedPage(fondoEstampado,1);
int n = frente.getNumberOfPages();
PdfContentByte background;
for (int i = 1; i <= n; i++) {
    background = stamperDoc.getUnderContent(i);
    background.addTemplate(pagina, 0, 0);
}
// after this everithing will be written in response.getOutputStream()
stamperDoc.close(); 
%>

There is another solution much simpler, and solves your problem. It depends the amount of text you want to add.

// read the file
PdfReader fondo = new PdfReader("listaPrecios.pdf");
PdfStamper stamper = new PdfStamper( fondo, response.getOutputStream());
PdfContentByte content = stamper.getOverContent(1);
// add text
ColumnText ct = new ColumnText( content );
// this are the coordinates where you want to add text
// if the text does not fit inside it will be cropped
ct.setSimpleColumn(50,500,500,50);
ct.setText(new Phrase(str, titulo1));
ct.go();

Fatal error: Class 'SoapClient' not found

I solved this issue on PHP 7.0.22-0ubuntu0.16.04.1 nginx

sudo apt-get install php7.0-soap

sudo systemctl restart php7.0-fpm
sudo systemctl restart nginx

What is a C++ delegate?

Windows Runtime equivalent of a function object in standard C++. One can use the whole function as a parameter (actually that is a function pointer). It is mostly used in conjunction with events. The delegate represents a contract that event handlers much fulfill. It facilitate how a function pointer can work for.

Dynamic type languages versus static type languages

It is all about the right tool for the job. Neither is better 100% of the time. Both systems were created by man and have flaws. Sorry, but we suck and making perfect stuff.

I like dynamic typing because it gets out of my way, but yes runtime errors can creep up that I didn't plan for. Where as static typing may fix the aforementioned errors, but drive a novice(in typed languages) programmer crazy trying to cast between a constant char and a string.

How to copy a file along with directory structure/path using python?

take a look at shutil. shutil.copyfile(src, dst) will copy a file to another file.

Note that shutil.copyfile will not create directories that do not already exist. for that, use os.makedirs

Toolbar navigation icon never set

work for me...

<android.support.v7.widget.Toolbar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/toolBar"
        android:background="@color/colorGreen"
        app:title="Title"
        app:titleTextColor="@color/colorBlack"
        app:navigationIcon="@drawable/ic_action_back"/>

Python datetime strptime() and strftime(): how to preserve the timezone information

Part of the problem here is that the strings usually used to represent timezones are not actually unique. "EST" only means "America/New_York" to people in North America. This is a limitation in the C time API, and the Python solution is… to add full tz features in some future version any day now, if anyone is willing to write the PEP.

You can format and parse a timezone as an offset, but that loses daylight savings/summer time information (e.g., you can't distinguish "America/Phoenix" from "America/Los_Angeles" in the summer). You can format a timezone as a 3-letter abbreviation, but you can't parse it back from that.

If you want something that's fuzzy and ambiguous but usually what you want, you need a third-party library like dateutil.

If you want something that's actually unambiguous, just append the actual tz name to the local datetime string yourself, and split it back off on the other end:

d = datetime.datetime.now(pytz.timezone("America/New_York"))
dtz_string = d.strftime(fmt) + ' ' + "America/New_York"

d_string, tz_string = dtz_string.rsplit(' ', 1)
d2 = datetime.datetime.strptime(d_string, fmt)
tz2 = pytz.timezone(tz_string)

print dtz_string 
print d2.strftime(fmt) + ' ' + tz_string

Or… halfway between those two, you're already using the pytz library, which can parse (according to some arbitrary but well-defined disambiguation rules) formats like "EST". So, if you really want to, you can leave the %Z in on the formatting side, then pull it off and parse it with pytz.timezone() before passing the rest to strptime.

Implementation difference between Aggregation and Composition in Java

First we must talk about what actually the difference between Aggregation and Composition is to be on the same page.

Aggregation is an association where the associated entity may exist independent of the association. For example, a Person may be associated to an Organisation but he/she may have independent existence in the system.

whereas

Composition refers to a situation when one of the associated entities is strongly related to the other and cannot exist without the other's existence. In fact the identity of that entity is always associated with the identity of the other object. For example, wheels in a car.

Now, aggregation can simply be achieved by holding a property of one entity in another as below:

class Person {
    Organisation worksFor;
}

class Organisation {
    String name;
}

class Main {
    public static void main(String args[]) {

        //Create Person object independently
        Person p = new Person();

        //Create the Organisation independently
        Organisation o = new Organisation();
        o.name = "XYZ Corporation";

        /*
          At this point both person and organisation 
          exist without any association  
        */
        p.worksFor = o;

    }
}

For Composition it is necessary that the dependent object is always created with the identity of its associated object. You can use an inner class for the same.

class Car {
    class Wheel {
        Car associatedWith;
    }
}

class Main {
    public static void main() {
        //Create Car object independently
        Car car = new Car();

        //Cannot create Wheel instance independently
        //need a reference of a Car for the same.
        Car.Wheel wheel = car.new Wheel();
    }
}

Please note that the same use case may fall under aggregation/composition depending on the application scenario. For example, the Person-Organisation case may become composition if you are developing an application for people working in some organisation and the reference to organisation is must for sign up. Similarly, if you are maintaining inventory for parts of a Car, Car-Wheel relationship can be aggregation.

How to paste text to end of every line? Sublime 2

Here's the workflow I use all the time, using the keyboard only

  1. Ctrl/Cmd + A Select All
  2. Ctrl/Cmd + Shift + L Split into Lines
  3. ' Surround every line with quotes

Note that this doesn't work if there are blank lines in the selection.

install / uninstall APKs programmatically (PackageManager vs Intents)

If you have Device Owner (or profile owner, I haven't tried) permission you can silently install/uninstall packages using device owner API.

for uninstalling:

public boolean uninstallPackage(Context context, String packageName) {
    ComponentName name = new ComponentName(MyAppName, MyDeviceAdminReceiver.class.getCanonicalName());
    PackageManager packageManger = context.getPackageManager();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageInstaller packageInstaller = packageManger.getPackageInstaller();
        PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        params.setAppPackageName(packageName);
        int sessionId = 0;
        try {
            sessionId = packageInstaller.createSession(params);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
        packageInstaller.uninstall(packageName, PendingIntent.getBroadcast(context, sessionId,
                new Intent("android.intent.action.MAIN"), 0).getIntentSender());
        return true;
    }
    System.err.println("old sdk");
    return false;
}

and to install package:

public boolean installPackage(Context context,
                                     String packageName, String packagePath) {
    ComponentName name = new ComponentName(MyAppName, MyDeviceAdminReceiver.class.getCanonicalName());
    PackageManager packageManger = context.getPackageManager();
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        PackageInstaller packageInstaller = packageManger.getPackageInstaller();
        PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
                PackageInstaller.SessionParams.MODE_FULL_INSTALL);
        params.setAppPackageName(packageName);
        try {
            int sessionId = packageInstaller.createSession(params);
            PackageInstaller.Session session = packageInstaller.openSession(sessionId);
            OutputStream out = session.openWrite(packageName + ".apk", 0, -1);
            readTo(packagePath, out); //read the apk content and write it to out
            session.fsync(out);
            out.close();
            System.out.println("installing...");
            session.commit(PendingIntent.getBroadcast(context, sessionId,
                    new Intent("android.intent.action.MAIN"), 0).getIntentSender());
            System.out.println("install request sent");
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    System.err.println("old sdk");
    return false;
}

Fully change package name including company domain

Four steps are given below:

  1. Click on app folder below:

enter image description here

com.new25.impro. press Shift + F6 {Refactor->Rename...} to rename the package and press refactor.

  1. After that one, see the android monitor. That show change everywhere that packagename. Click refactor.

  2. Go to module app:change the application id for you like that name put it. and click sync now.

  3. Now you can change the package name to what you like.

How do I open an .exe from another C++ .exe?

You should always avoid using system() because

  • It is resource heavy
  • It defeats security -- you don't know you it's a valid command or does the same thing on every system, you could even start up programs you didn't intend to start up. The danger is that when you directly execute a program, it gets the same privileges as your program -- meaning that if, for example, you are running as system administrator then the malicious program you just inadvertently executed is also running as system administrator. If that doesn't scare you silly, check your pulse.
  • Anti virus programs hate it, your program could get flagged as a virus.

You should use CreateProcess().

You can use Createprocess() to just start up an .exe and creating a new process for it. The application will run independent from the calling application.

Here's an example I used in one of my projects:

#include <windows.h>

VOID startup(LPCTSTR lpApplicationName)
{
   // additional information
   STARTUPINFO si;     
   PROCESS_INFORMATION pi;

   // set the size of the structures
   ZeroMemory( &si, sizeof(si) );
   si.cb = sizeof(si);
   ZeroMemory( &pi, sizeof(pi) );

  // start the program up
  CreateProcess( lpApplicationName,   // the path
    argv[1],        // Command line
    NULL,           // Process handle not inheritable
    NULL,           // Thread handle not inheritable
    FALSE,          // Set handle inheritance to FALSE
    0,              // No creation flags
    NULL,           // Use parent's environment block
    NULL,           // Use parent's starting directory 
    &si,            // Pointer to STARTUPINFO structure
    &pi             // Pointer to PROCESS_INFORMATION structure (removed extra parentheses)
    );
    // Close process and thread handles. 
    CloseHandle( pi.hProcess );
    CloseHandle( pi.hThread );
}

EDIT: The error you are getting is because you need to specify the path of the .exe file not just the name. Openfile.exe probably doesn't exist.

How to convert "0" and "1" to false and true

My solution (vb.net):

Private Function ConvertToBoolean(p1 As Object) As Boolean
    If p1 Is Nothing Then Return False
    If IsDBNull(p1) Then Return False
    If p1.ToString = "1" Then Return True
    If p1.ToString.ToLower = "true" Then Return True
    Return False
End Function

How to call another controller Action From a controller in Mvc

As @mxmissile says in the comments to the accepted answer, you shouldn't new up the controller because it will be missing dependencies set up for IoC and won't have the HttpContext.

Instead, you should get an instance of your controller like this:

var controller = DependencyResolver.Current.GetService<ControllerB>();
controller.ControllerContext = new ControllerContext(this.Request.RequestContext, controller);

Getting value of HTML text input

Depends on where you want to use the email. If it's on the client side, without sending it to a PHP script, JQuery (or javascript) can do the trick.

I've created a fiddle to explain the same - http://jsfiddle.net/qHcpR/

It has an alert which goes off on load and when you click the textbox itself.

Add property to an array of objects

  Object.defineProperty(Results, "Active", {value : 'true',
                       writable : true,
                       enumerable : true,
                       configurable : true});

How to include Javascript file in Asp.Net page

add like

<head runat="server">
<script src="Registration.js" type="text/javascript"></script>
</head>

OR can add in code behind.

Page.ClientScript.RegisterClientScriptInclude("Registration", ResolveUrl("~/js/Registration.js"));

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

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

Styling a disabled input with css only

A space in a CSS selector selects child elements.

.btn input

This is basically what you wrote and it would select <input> elements within any element that has the btn class.

I think you're looking for

input[disabled].btn:hover, input[disabled].btn:active, input[disabled].btn:focus

This would select <input> elements with the disabled attribute and the btn class in the three different states of hover, active and focus.

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

Try This:

It'll give you a temporary path not the accurate path, you can use this script if you want to show selected images as in this jsfiddle example(Try it by selectng images as well as other files):-

JSFIDDLE

Here is the code :-

HTML:-

<input type="file" id="i_file" value=""> 
<input type="button" id="i_submit" value="Submit">
<br>
<img src="" width="200" style="display:none;" />
<br>
<div id="disp_tmp_path"></div>

JS:-

$('#i_file').change( function(event) {
    var tmppath = URL.createObjectURL(event.target.files[0]);
    $("img").fadeIn("fast").attr('src',URL.createObjectURL(event.target.files[0]));

    $("#disp_tmp_path").html("Temporary Path(Copy it and try pasting it in browser address bar) --> <strong>["+tmppath+"]</strong>");
});

Its not exactly what you were looking for, but may be it can help you somewhere.

Input type DateTime - Value format?

with momentjs i use

moment(value).format("YYYY-MM-DDTHH:mm:ss")

Difference between logical addresses, and physical addresses?

I found a article about Logical vs Physical Address in Operating System, which clearly explains about this.

Logical Address is generated by CPU while a program is running. The logical address is virtual address as it does not exist physically therefore it is also known as Virtual Address. This address is used as a reference to access the physical memory location by CPU. The term Logical Address Space is used for the set of all logical addresses generated by a programs perspective. The hardware device called Memory-Management Unit is used for mapping logical address to its corresponding physical address.

Physical Address identifies a physical location of required data in a memory. The user never directly deals with the physical address but can access by its corresponding logical address. The user program generates the logical address and thinks that the program is running in this logical address but the program needs physical memory for its execution therefore the logical address must be mapped to the physical address bu MMU before they are used. The term Physical Address Space is used for all physical addresses corresponding to the logical addresses in a Logical address space.

Logical and Physical Address comparision

Source: www.geeksforgeeks.org

Programmatically saving image to Django ImageField

What I did was to create my own storage that will just not save the file to the disk:

from django.core.files.storage import FileSystemStorage

class CustomStorage(FileSystemStorage):

    def _open(self, name, mode='rb'):
        return File(open(self.path(name), mode))

    def _save(self, name, content):
        # here, you should implement how the file is to be saved
        # like on other machines or something, and return the name of the file.
        # In our case, we just return the name, and disable any kind of save
        return name

    def get_available_name(self, name):
        return name

Then, in my models, for my ImageField, I've used the new custom storage:

from custom_storage import CustomStorage

custom_store = CustomStorage()

class Image(models.Model):
    thumb = models.ImageField(storage=custom_store, upload_to='/some/path')

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

How to use Angular2 templates with *ngFor to create a table out of nested arrays?

Here is a basic approach - it sure can be improved - of what I understood to be your requirement.

This will display 2 columns, one with the groups name, and one with the list of items associated to the group.

The trick is simply to include a list within the items cell.

<table>
  <thead>
    <th>Groups Name</th>
    <th>Groups Items</th>
  </thead>
  <tbody>
    <tr *ngFor="let group of groups">
      <td>{{group.name}}</td>
      <td>
        <ul>
          <li *ngFor="let item of group.items">{{item}}</li>
        </ul>
      </td>
    </tr>
  </tbody>
</table>

Loop until a specific user input

As an alternative to @Mark Byers' approach, you can use while True:

guess = 50     # this should be outside the loop, I think
while True:    # infinite loop
    n = raw_input("\n\nTrue, False or Correct?: ")
    if n == "Correct":
        break  # stops the loop
    elif n == "True":
        # etc.

What exactly is \r in C language?

It's Carriage Return. Source: http://msdn.microsoft.com/en-us/library/6aw8xdf2(v=vs.80).aspx

The following repeats the loop until the user has pressed the Return key.

while(ch!='\r')
{
  ch=getche();
}

Is there a numpy builtin to reject outliers from a list

Something important when dealing with outliers is that one should try to use estimators as robust as possible. The mean of a distribution will be biased by outliers but e.g. the median will be much less.

Building on eumiro's answer:

def reject_outliers(data, m = 2.):
    d = np.abs(data - np.median(data))
    mdev = np.median(d)
    s = d/mdev if mdev else 0.
    return data[s<m]

Here I have replace the mean with the more robust median and the standard deviation with the median absolute distance to the median. I then scaled the distances by their (again) median value so that m is on a reasonable relative scale.

Note that for the data[s<m] syntax to work, data must be a numpy array.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

On Windows 7 setting the proxy to global config will resolve this issue

git config --global http.proxy http://user:password@proxy_addr:port

but the problem here is your password will not be encrypted.. Hopefully that should not be much problem as most of time you will be sole owner of your PC.

TestNG ERROR Cannot find class in classpath

I just had this problem and was because the skip test option in the run configuration was checked. made that unchecked and build, then run the testNg, worked.

How to copy files from 'assets' folder to sdcard?

Based on Rohith Nandakumar's solution, I did something of my own to copy files from a subfolder of assets (i.e. "assets/MyFolder"). Also, I'm checking if the file already exists in sdcard before trying to copy again.

private void copyAssets() {
    AssetManager assetManager = getAssets();
    String[] files = null;
    try {
        files = assetManager.list("MyFolder");
    } catch (IOException e) {
        Log.e("tag", "Failed to get asset file list.", e);
    }
    if (files != null) for (String filename : files) {
        InputStream in = null;
        OutputStream out = null;
        try {
          in = assetManager.open("MyFolder/"+filename);
          File outFile = new File(getExternalFilesDir(null), filename);
          if (!(outFile.exists())) {// File does not exist...
                out = new FileOutputStream(outFile);
                copyFile(in, out);
          }
        } catch(IOException e) {
            Log.e("tag", "Failed to copy asset file: " + filename, e);
        }     
        finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    // NOOP
                }
            }
        }  
    }
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
    byte[] buffer = new byte[1024];
    int read;
    while((read = in.read(buffer)) != -1){
      out.write(buffer, 0, read);
    }
}

Why std::cout instead of simply cout?

You probably had using namespace std; before in your code you did in class. That explicitly tells the precompiler to look for the symbols in std, which means you don't need to std::. Though it is good practice to std::cout instead of cout so you explicitly invoke std::cout every time. That way if you are using another library that redefines cout, you still have the std::cout behavior instead of some other custom behavior.

Replace only text inside a div using jquery

Another approach is keep that element, change the text, then append that element back

const star_icon = $(li).find('.stars svg')
$(li).find('.stars').text(repo.stargazers_count).append(star_icon)

Multiline TextView in Android?

What I learned was to add "\n" in between the words where you want it to brake into the next line. For example...

<TextView
    android:id="@+id/time"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAlignment="center"
    android:text="M-F 9am-5pm \n By Appointment Only" />

The \n between 5pm and By allowed me more control of where I wanted my my next line to begin and end.

How to draw text using only OpenGL methods?

Load an image with characters as texture and draw the part of that texture depending on what character you want. You can create that texture using a paint program, hardcode it or use a window component to draw to an image and retrieve that image for an exact copy of system fonts.

No need to use Glut or any other extension, just basic OpenGL operability. It gets the job done, not to mention that its been done like this for decades by professional programmers in very succesfull games and other applications.

Append an object to a list in R in amortized constant time, O(1)?

I have made a small comparison of methods mentioned here.

n = 1e+4
library(microbenchmark)
### Using environment as a container
lPtrAppend <- function(lstptr, lab, obj) {lstptr[[deparse(substitute(lab))]] <- obj}
### Store list inside new environment
envAppendList <- function(lstptr, obj) {lstptr$list[[length(lstptr$list)+1]] <- obj} 

microbenchmark(times = 5,  
        env_with_list_ = {
            listptr <- new.env(parent=globalenv())
            listptr$list <- NULL
            for(i in 1:n) {envAppendList(listptr, i)}
            listptr$list
        },
        c_ = {
            a <- list(0)
            for(i in 1:n) {a = c(a, list(i))}
        },
        list_ = {
            a <- list(0)
            for(i in 1:n) {a <- list(a, list(i))}
        },
        by_index = {
            a <- list(0)
            for(i in 1:n) {a[length(a) + 1] <- i}
            a
        },
        append_ = { 
            a <- list(0)    
            for(i in 1:n) {a <- append(a, i)} 
            a
        },
        env_as_container_ = {
            listptr <- new.env(parent=globalenv())
            for(i in 1:n) {lPtrAppend(listptr, i, i)} 
            listptr
        }   
)

Results:

Unit: milliseconds
              expr       min        lq       mean    median        uq       max neval cld
    env_with_list_  188.9023  198.7560  224.57632  223.2520  229.3854  282.5859     5  a 
                c_ 1275.3424 1869.1064 2022.20984 2191.7745 2283.1199 2491.7060     5   b
             list_   17.4916   18.1142   22.56752   19.8546   20.8191   36.5581     5  a 
          by_index  445.2970  479.9670  540.20398  576.9037  591.2366  607.6156     5  a 
           append_ 1140.8975 1316.3031 1794.10472 1620.1212 1855.3602 3037.8416     5   b
 env_as_container_  355.9655  360.1738  399.69186  376.8588  391.7945  513.6667     5  a 

How to get previous month and year relative to today, using strtotime and date?

function getOnemonthBefore($date){
    $day = intval(date("t", strtotime("$date")));//get the last day of the month
    $month_date = date("y-m-d",strtotime("$date -$day days"));//get the day 1 month before
    return $month_date;
}

The resulting date is dependent to the number of days the input month is consist of. If input month is february (28 days), 28 days before february 5 is january 8. If input is may 17, 31 days before is april 16. Likewise, if input is may 31, resulting date will be april 30.

NOTE: the input takes complete date ('y-m-d') and outputs ('y-m-d') you can modify this code to suit your needs.

Python dictionary get multiple values

If the fallback keys are not too many you can do something like this

value = my_dict.get('first_key') or my_dict.get('second_key')

Limiting floats to two decimal points

Use combination of Decimal object and round() method.

Python 3.7.3
>>> from decimal import Decimal
>>> d1 = Decimal (13.949999999999999) # define a Decimal
>>> d1 
Decimal('13.949999999999999289457264239899814128875732421875')
>>> d2 = round(d1, 2) # round to 2 decimals
>>> d2
Decimal('13.95')

Recursively add the entire folder to a repository

In my case, there was a .git folder in the subdirectory because I had previously initialized a git repo there. When I added the subdirectory it simply added it as a subproject without adding any of the contained files.

I solved the issue by removing the git repository from the subdirectory and then re-adding the folder.

Delete specified file from document directory

Instead of having the error set to NULL, have it set to

NSError *error;
[fileManager removeItemAtPath:filePath error:&error];
if (error){
NSLog(@"%@", error);
}

this will tell you if it's actually deleting the file

How to initialize a vector with fixed length in R

The initialization method easiest to remember is

vec = vector(,10); #the same as "vec = vector(length = 10);"

The values of vec are: "[1] FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE FALSE" (logical mode) by default.

But after setting a character value, like

vec[2] = 'abc'

vec becomes: "FALSE" "abc" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE" "FALSE"", which is of the character mode.

concatenate char array in C

First copy the current string to a larger array with strcpy, then use strcat.

For example you can do:

char* str = "Hello";
char dest[12];

strcpy( dest, str );
strcat( dest, ".txt" );

Convert file to byte array and vice versa

Otherwise Try this :

Converting File To Bytes

  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.IOException;


   public class Temp {

        public static void main(String[] args) {

         File file = new File("c:/EventItemBroker.java");

         byte[] b = new byte[(int) file.length()];
         try {
               FileInputStream fileInputStream = new FileInputStream(file);
               fileInputStream.read(b);
               for (int i = 0; i < b.length; i++) {
                           System.out.print((char)b[i]);
                }
          } catch (FileNotFoundException e) {
                      System.out.println("File Not Found.");
                      e.printStackTrace();
          }
          catch (IOException e1) {
                   System.out.println("Error Reading The File.");
                    e1.printStackTrace();
          }

       }
    }

Converting Bytes to File

      public class WriteByteArrayToFile {

         public static void main(String[] args) {

            String strFilePath = "Your path";
            try {
                 FileOutputStream fos = new FileOutputStream(strFilePath);
                 String strContent = "Write File using Java ";

                 fos.write(strContent.getBytes());
                 fos.close();
           }
          catch(FileNotFoundException ex)   {
                 System.out.println("FileNotFoundException : " + ex);
          }
         catch(IOException ioe)  {
                 System.out.println("IOException : " + ioe);
          }

       }
     }

Group by with union mysql select query

select sum(qty), name
from (
    select count(m.owner_id) as qty, o.name
    from transport t,owner o,motorbike m
    where t.type='motobike' and o.owner_id=m.owner_id
        and t.type_id=m.motorbike_id
    group by m.owner_id

    union all

    select count(c.owner_id) as qty, o.name,
    from transport t,owner o,car c
    where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
    group by c.owner_id
) t
group by name

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

d3.select("#element") not working when code above the html element

<script>$(function(){var svg = d3.select("#chart").append("svg:svg");});</script>
<div id="chart"></div>

In other words, it's not happening because you can't query against something that doesn't exist yet-- so just do it after the page loads (here via jquery).

Btw, its recommended that you place your JS files before the close of your body tag.

How to implement class constants?

Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("my.config");

export interface MyAppConfig {
    apiEndpoint: string;
}

export const AppConfig: MyAppConfig = {    
    apiEndpoint: "http://localhost:8080/api/"    
};

Inject it in providers in app.module.ts

You will be able to use it across every components.

EDIT for Angular 4 :

For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.

Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject

Example Code

Angular 2 Using Opaque Tokens

const API_URL = new OpaqueToken('apiUrl'); //no Type Check


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      new Inject(API_URL) //notice the new Inject
    ]
  }
]

Angular 4 Using Injection Tokens

const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      API_URL // no `new Inject()` needed!
    ]
  }
]

Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.

How do DATETIME values work in SQLite?

Store it in a field of type long. See Date.getTime() and new Date(long)

how to check if string contains '+' character

[+]is simpler

    String s = "ddjdjdj+kfkfkf";

    if(s.contains ("+"))
    {
        String parts[] = s.split("[+]");
        s =  parts[0]; // i want to strip part after  +
    }
    System.out.println(s);

Excel to JSON javascript code?

The answers are working fine with xls format but, in my case, it didn't work for xlsx format. Thus I added some code here. it works both xls and xlsx format.

I took the sample from the official sample link.

Hope it may help !

function fileReader(oEvent) {
        var oFile = oEvent.target.files[0];
        var sFilename = oFile.name;

        var reader = new FileReader();
        var result = {};

        reader.onload = function (e) {
            var data = e.target.result;
            data = new Uint8Array(data);
            var workbook = XLSX.read(data, {type: 'array'});
            console.log(workbook);
            var result = {};
            workbook.SheetNames.forEach(function (sheetName) {
                var roa = XLSX.utils.sheet_to_json(workbook.Sheets[sheetName], {header: 1});
                if (roa.length) result[sheetName] = roa;
            });
            // see the result, caution: it works after reader event is done.
            console.log(result);
        };
        reader.readAsArrayBuffer(oFile);
}

// Add your id of "File Input" 
$('#fileUpload').change(function(ev) {
        // Do something 
        fileReader(ev);
}

clear cache of browser by command line

Here is how to clear all trash & caches (without other private data in browsers) by a command line. This is a command line batch script that takes care of all trash (as of April 2014):

erase "%TEMP%\*.*" /f /s /q
for /D %%i in ("%TEMP%\*") do RD /S /Q "%%i"

erase "%TMP%\*.*" /f /s /q
for /D %%i in ("%TMP%\*") do RD /S /Q "%%i"

erase "%ALLUSERSPROFILE%\TEMP\*.*" /f /s /q
for /D %%i in ("%ALLUSERSPROFILE%\TEMP\*") do RD /S /Q "%%i"

erase "%SystemRoot%\TEMP\*.*" /f /s /q
for /D %%i in ("%SystemRoot%\TEMP\*") do RD /S /Q "%%i"


@rem Clear IE cache -  (Deletes Temporary Internet Files Only)
RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8
erase "%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Microsoft\Windows\Tempor~1\*") do RD /S /Q "%%i"

@rem Clear Google Chrome cache
erase "%LOCALAPPDATA%\Google\Chrome\User Data\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Google\Chrome\User Data\*") do RD /S /Q "%%i"


@rem Clear Firefox cache
erase "%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*.*" /f /s /q
for /D %%i in ("%LOCALAPPDATA%\Mozilla\Firefox\Profiles\*") do RD /S /Q "%%i"

pause

I am pretty sure it will run for some time when you first run it :) Enjoy!

How to calculate the difference between two dates using PHP?

Try this very simple answer using date_diff(), this is tested.

$date1 = date_create("2017-11-27");
$date2 = date_create("2018-12-29");
$diff=date_diff($date1,$date2);
$months = $diff->format("%m months");
$years = $diff->format("%y years");
$days = $diff->format("%d days");

echo $years .' '.$months.' '.$days;

the output is:

1 years 1 months 2 days

Creating a "logical exclusive or" operator in Java

What you're asking for wouldn't make much sense. Unless I'm incorrect you're suggesting that you want to use XOR to perform Logical operations the same way AND and OR do. Your provided code actually shows what I'm reffering to:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}

Your function has boolean inputs, and when bitwise XOR is used on booleans the result is the same as the code you've provided. In other words, bitwise XOR is already efficient when comparing individual bits(booleans) or comparing the individual bits in larger values. To put this into context, in terms of binary values any non-zero value is TRUE and only ZERO is false.

So for XOR to be applied the same way Logical AND is applied, you would either only use binary values with just one bit(giving the same result and efficiency) or the binary value would have to be evaluated as a whole instead of per bit. In other words the expression ( 010 ^^ 110 ) = FALSE instead of ( 010 ^^ 110 ) = 100. This would remove most of the semantic meaning from the operation, and represents a logical test you shouldn't be using anyway.

Change limit for "Mysql Row size too large"

After spending hours I have found the solution: just run the following SQL in your MySQL admin to convert the table to MyISAM:

USE db_name;
ALTER TABLE table_name ENGINE=MYISAM;

Avoid synchronized(this) in Java?

As already said here synchronized block can use user-defined variable as lock object, when synchronized function uses only "this". And of course you can manipulate with areas of your function which should be synchronized and so on.

But everyone says that no difference between synchronized function and block which covers whole function using "this" as lock object. That is not true, difference is in byte code which will be generated in both situations. In case of synchronized block usage should be allocated local variable which holds reference to "this". And as result we will have a little bit larger size of function (not relevant if you have only few number of functions).

More detailed explanation of the difference you can find here: http://www.artima.com/insidejvm/ed2/threadsynchP.html

Also usage of synchronized block is not good due to following point of view:

The synchronized keyword is very limited in one area: when exiting a synchronized block, all threads that are waiting for that lock must be unblocked, but only one of those threads gets to take the lock; all the others see that the lock is taken and go back to the blocked state. That's not just a lot of wasted processing cycles: often the context switch to unblock a thread also involves paging memory off the disk, and that's very, very, expensive.

For more details in this area I would recommend you read this article: http://java.dzone.com/articles/synchronized-considered

SQL Server SELECT LAST N Rows

I tested JonVD's code, but found it was very slow, 6s.

This code took 0s.

SELECT TOP(5) ORDERID, CUSTOMERID, OrderDate    
FROM Orders where EmployeeID=5    
Order By OrderDate DESC

How to convert these strange characters? (ë, Ã, ì, ù, Ã)

I actually found something that worked for me. It converts the text to binary and then to UTF8.

Source Text that has encoding issues: If ‘Yes’, what was your last

SELECT CONVERT(CAST(CONVERT(
    (SELECT CONVERT(CAST(CONVERT(english_text USING LATIN1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865) 
USING LATIN1) AS BINARY) USING UTF8) AS 'result';

Corrected Result text: If ‘Yes’, what was your last

My source was wrongly encoded twice so I had two do it twice. For one time you can use:

SELECT CONVERT(CAST(CONVERT(column_name USING latin1) AS BINARY) USING UTF8) AS res FROM m_translation WHERE id = 865;

Please excuse me for any formatting mistakes

Pass react component as props

Using this.props.children is the idiomatic way to pass instantiated components to a react component

const Label = props => <span>{props.children}</span>
const Tab = props => <div>{props.children}</div>
const Page = () => <Tab><Label>Foo</Label></Tab>

When you pass a component as a parameter directly, you pass it uninstantiated and instantiate it by retrieving it from the props. This is an idiomatic way of passing down component classes which will then be instantiated by the components down the tree (e.g. if a component uses custom styles on a tag, but it wants to let the consumer choose whether that tag is a div or span):

const Label = props => <span>{props.children}</span>
const Button = props => {
    const Inner = props.inner; // Note: variable name _must_ start with a capital letter 
    return <button><Inner>Foo</Inner></button>
}
const Page = () => <Button inner={Label}/>

If what you want to do is to pass a children-like parameter as a prop, you can do that:

const Label = props => <span>{props.content}</span>
const Tab = props => <div>{props.content}</div>
const Page = () => <Tab content={<Label content='Foo' />} />

After all, properties in React are just regular JavaScript object properties and can hold any value - be it a string, function or a complex object.

LINQ select one field from list of DTO objects to array

You can select all Sku elements of your myLines list and then convert the result to an array.

string[] mySKUsArray = myLines.Select(x=>x.Sku).ToArray();

Getting or changing CSS class property with Javascript using DOM style

If you are looking for sending color data from backend

def color():
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    return color

Excluding directory when creating a .tar.gz file

Try removing the last / at the end of the directory path to exclude

tar -pczf MyBackup.tar.gz /home/user/public_html/ --exclude "/home/user/public_html/tmp" 

On postback, how can I check which control cause postback in Page_Init event

If you need to check which control caused the postback, then you could just directly compare ["__EVENTTARGET"] to the control you are interested in:

if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"])
{
    /*do special stuff*/
}

This assumes you're just going to be comparing the result from any GetPostBackControl(...) extension method anyway. It may not handle EVERY situation, but if it works it is simpler. Plus, you won't scour the page looking for a control you didn't care about to begin with.

When to use malloc for char pointers

Use malloc() when you don't know the amount of memory needed during compile time. In case if you have read-only strings then you can use const char* str = "something"; . Note that the string is most probably be stored in a read-only memory location and you'll not be able to modify it. On the other hand if you know the string during compiler time then you can do something like: char str[10]; strcpy(str, "Something"); Here the memory is allocated from stack and you will be able to modify the str. Third case is allocating using malloc. Lets say you don'r know the length of the string during compile time. Then you can do char* str = malloc(requiredMem); strcpy(str, "Something"); free(str);

Count number of times value appears in particular column in MySQL

Take a look at the Group by function.

What the group by function does is pretuty much grouping the similar value for a given field. You can then show the number of number of time that this value was groupped using the COUNT function.

MySQL Documentation

You can also use the group by function with a good number of other function define by MySQL (see the above link).

mysql> SELECT student_name, AVG(test_score)
    ->        FROM student
    ->        GROUP BY student_name;

How do I draw a set of vertical lines in gnuplot?

You can use the grid feature for the second unused axis x2, which is the most natural way of drawing a set of regular spaced lines.

set grid x2tics
set x2tics 10 format "" scale 0

In general, the grid is drawn at the same position as the tics on the axis. In case the position of the lines does not correspond to the tics position, gnuplot provides an additional set of tics, called x2tics. format "" and scale 0 hides the x2tics so you only see the grid lines.

You can style the lines as usual with linewith, linecolor.

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Check your connection first.

Then if you want to fetch the exact value from the database then you should write:

$username = $_POST['username'];
$password = $_POST['password'];
$result = mysql_query("SELECT * FROM Users WHERE UserName =`$usernam`");

Or you want to fetch the LIKE type of value then you should write:

$result = mysql_query("SELECT * FROM Users WHERE UserName LIKE '%$username%'");

How to get the instance id from within an ec2 instance?

You can also install awscli and use it to get all the info you wish:

AWS_DEFAULT_REGION=your-region aws ec2 describe-instances

You'll get lots of output so be sure to grep by your idetifier such as ip and print some more lines:

AWS_DEFAULT_REGION=your-region aws ec2 describe-instances | grep your-ip -A 10 | grep InstanceId

How to prepend a string to a column value in MySQL?

That's a simple one

UPDATE YourTable SET YourColumn = CONCAT('prependedString', YourColumn);

React / JSX Dynamic Component Name

I figured out a new solution. Do note that I am using ES6 modules so I am requiring the class. You could also define a new React class instead.

var components = {
    example: React.createFactory( require('./ExampleComponent') )
};

var type = "example";

newComponent() {
    return components[type]({ attribute: "value" });
}

How does Trello access the user's clipboard?

Something very similar can be seen on http://goo.gl when you shorten the URL.

There is a readonly input element that gets programmatically focused, with tooltip press CTRL-C to copy.

When you hit that shortcut, the input content effectively gets into the clipboard. Really nice :)

Link to "pin it" on pinterest without generating a button

You can create a custom link as described here using a small jQuery script

$('.linkPinIt').click(function(){
    var url = $(this).attr('href');
    var media = $(this).attr('data-image');
    var desc = $(this).attr('data-desc');
    window.open("//www.pinterest.com/pin/create/button/"+
    "?url="+url+
    "&media="+media+
    "&description="+desc,"_blank","top=0,right=0,width=750,height=320");
    return false; 
});

this will work for all links with class linkPinItwhich have the image and the description stored in the HTML 5 data attributes data-image and data-desc

<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F" 
   data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg" 
   data-desc="Title for Pinterest Photo" class="linkPinIt">
    Pin it!
</a> 

see this jfiddle example

How to Disable landscape mode in Android?

You can do this for your entire application without having to make all your activities extend a common base class.

The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.

And do not forget to add app:name=".MyApp" in your manifest file.

class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();  

        // register to be informed of activities starting up
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, 
                                          Bundle savedInstanceState) {

                // new activity created; force its orientation to portrait
                activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            ....
        });
    }
}

Where does the .gitignore file belong?

When in doubt just place it in the root of your repository. See https://help.github.com/articles/ignoring-files/ for more information.

Ignore 'Security Warning' running script from command line

This is touched in "PowerShell Execution Policies in Standard Images" on Lee Holmes' Blog and "PowerShell’s Security Guiding Principles" on the Windows Power Shell Blog .

Summary Some machines treat UNC paths as the big bad internet, so PowerShell treats them as remote files. You can either disable this feature on those servers (UncAsIntranet = 0,) or add the remote machines to your trusted hosts.

If you want to do neither, PowerShell v2 supports an -ExecutionPolicy parameter that does exactly what your pseudocode wants. PowerShell -ExecutionPolicy Bypass -File (...).

Play audio as microphone input

Just as there are printer drivers that do not connect to a printer at all but rather write to a PDF file, analogously there are virtual audio drivers available that do not connect to a physical microphone at all but can pipe input from other sources such as files or other programs.

I hope I'm not breaking any rules by recommending free/donation software, but VB-Audio Virtual Cable should let you create a pair of virtual input and output audio devices. Then you could play an MP3 into the virtual output device and then set the virtual input device as your "microphone". In theory I think that should work.

If all else fails, you could always roll your own virtual audio driver. Microsoft provides some sample code but unfortunately it is not applicable to the older Windows XP audio model. There is probably sample code available for XP too.

insert a NOT NULL column to an existing table

If you aren't allowing the column to be Null you need to provide a default to populate existing rows. e.g.

ALTER TABLE dbo.YourTbl ADD
    newcol int NOT NULL CONSTRAINT DF_YourTbl_newcol DEFAULT 0

On Enterprise Edition this is a metadata only change since 2012

Uploading an Excel sheet and importing the data into SQL Server database

A proposed solution will be:   


protected void Button1_Click(object sender, EventArgs e)
{
        try
        {
            CreateXMLFile();



        SqlConnection con = new SqlConnection(constring);
        con.Open();

        SqlCommand cmd = new SqlCommand("bulk_in", con);

        cmd.CommandType = CommandType.StoredProcedure;

        cmd.Parameters.AddWithValue("@account_det", sw_XmlString.ToString ());

       int i= cmd.ExecuteNonQuery();
            if(i>0)
            {
                Label1.Text = "File Upload successfully";
            }
            else
            {
                Label1.Text = "File Upload unsuccessfully";
                return;

            }


        con.Close();
            }
        catch(SqlException ex)
        {
            Label1.Text = ex.Message.ToString();
        }




    }
     public void CreateXMLFile()
        {

          try
            {
                M_Filepath = System.IO.Path.GetFileName(FileUpload1.PostedFile.FileName);
                fileExtn = Path.GetExtension(M_Filepath);
                strGuid = System.Guid.NewGuid().ToString();
                fNameArray = M_Filepath.Split('.');
                fName = fNameArray[0];

                xlRptName = fName + "_" + strGuid + "_" + DateTime.Now.ToShortDateString ().Replace ('/','-');
                 fileName =  xlRptName.Trim()  + fileExtn.Trim() ;



                 FileUpload1.PostedFile.SaveAs(ConfigurationManager.AppSettings["ImportFilePath"]+ fileName);



                strFileName = Path.GetFileName(FileUpload1.PostedFile.FileName).ToUpper() ;
                if (((strFileName) != "DEMO.XLS") && ((strFileName) != "DEMO.XLSX"))
                {
                    Label1.Text = "Excel File Must be DEMO.XLS or DEMO.XLSX";
                }
               FileUpload1.PostedFile.SaveAs(System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName);
               lstrFilePath = System.Configuration.ConfigurationManager.AppSettings["ImportFilePath"] + fileName;
               if (strFileName == "DEMO.XLS")
                {

                    strConn = "Provider=Microsoft.JET.OLEDB.4.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 8.0;HDR=YES;'";

                } 

                if (strFileName == "DEMO.XLSX")
                {
                    strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + lstrFilePath + ";" + "Extended Properties='Excel 12.0;HDR=YES;'";

                }

                strSQL = " Select [Name],[Mobile_num],[Account_number],[Amount],[date_a2] FROM [Sheet1$]";



                OleDbDataAdapter mydata = new OleDbDataAdapter(strSQL, strConn);

                mydata.TableMappings.Add("Table", "arul");
                mydata.Fill(dsExcl);
                dsExcl.DataSetName = "DocumentElement";
                intRowCnt = dsExcl.Tables[0].Rows.Count;
                intColCnt = dsExcl.Tables[0].Rows.Count;

                if(intRowCnt <1)
                {

                    Label1.Text = "No records in Excel File";
                    return;
                }
                if  (dsExcl==null)
                {

                }
                else
                    if(dsExcl.Tables[0].Rows.Count >= 1000 )
                    {

                        Label1.Text = "Excel data must be in less than 1000  ";
                    }


                for (intCtr = 0; intCtr <= dsExcl.Tables[0].Rows.Count - 1; intCtr++)
                {

                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Name"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Name"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Name should not be empty";
                        return;

                    }
                    else
                    {
                        strValid = "";
                    }



                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Mobile_num"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Mobile_num"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Mobile_num should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }

                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Account_number"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Account_number"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Account_number should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }





                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["Amount"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["Amount"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "Amount should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }



                    if (Convert.IsDBNull(dsExcl.Tables[0].Rows[intCtr]["date_a2"]))
                    {
                        strValid = "";

                    }
                    else
                    {
                        strValid = dsExcl.Tables[0].Rows[intCtr]["date_a2"].ToString();
                    }
                    if (strValid == "")
                    {
                        Label1.Text = "date_a2 should not be empty";

                    }
                    else
                    {
                        strValid = "";
                    }
                }


            }
         catch 
            {

            }

         try
         {
             if(dsExcl.Tables[0].Rows.Count >0)
             {

                 dr = dsExcl.Tables[0].Rows[0];
             }
             dsExcl.Tables[0].TableName = "arul";
             dsExcl.WriteXml(sw_XmlString, XmlWriteMode.IgnoreSchema);

         }
         catch
         {

         }
}`enter code here`

Sleep for milliseconds

Note that there is no standard C API for milliseconds, so (on Unix) you will have to settle for usleep, which accepts microseconds:

#include <unistd.h>

unsigned int microseconds;
...
usleep(microseconds);

Cannot truncate table because it is being referenced by a FOREIGN KEY constraint?

I write the following ways and tried to parameterized them, so you can Run them in a Query document Or Make a useful SP with them easily.

A) Delete

If your table has not millions of records this works good and hasn't any Alter commands:

---------------------------------------------------------------
------------------- Just Fill Parameters Value ----------------
---------------------------------------------------------------
DECLARE @DbName AS NVARCHAR(30) = 'MyDb'         --< Db Name
DECLARE @Schema AS NVARCHAR(30) = 'dbo'          --< Schema
DECLARE @TableName AS NVARCHAR(30) = 'Book'      --< Table Name
------------------ /Just Fill Parameters Value ----------------

DECLARE @Query AS NVARCHAR(500) = 'Delete FROM ' + @TableName

EXECUTE sp_executesql @Query
SET @Query=@DbName+'.'+@Schema+'.'+@TableName
DBCC CHECKIDENT (@Query,RESEED, 0)
  • In above answer of mine the method of resolve the mentioned problem in the question is based on @s15199d answer.

B) Truncate

If your table has millions of records or you hasn't any problem with Alter command in your codes, then use this one:

--   Book                               Student
--
--   |  BookId  | Field1 |              | StudentId |  BookId  |
--   ---------------------              ------------------------ 
--   |    1     |    A   |              |     2     |    1     |  
--   |    2     |    B   |              |     1     |    1     |
--   |    3     |    C   |              |     2     |    3     |  

---------------------------------------------------------------
------------------- Just Fill Parameters Value ----------------
---------------------------------------------------------------
DECLARE @DbName AS NVARCHAR(30) = 'MyDb'
DECLARE @Schema AS NVARCHAR(30) = 'dbo'
DECLARE @TableName_ToTruncate AS NVARCHAR(30) = 'Book'

DECLARE @TableName_OfOwnerOfConstraint AS NVARCHAR(30) = 'Student' --< Decelations About FK_Book_Constraint
DECLARE @Ref_ColumnName_In_TableName_ToTruncate AS NVARCHAR(30) = 'BookId' --< Decelations About FK_Book_Constraint
DECLARE @FK_ColumnName_In_TableOfOwnerOfConstraint AS NVARCHAR(30) = 'Fk_BookId' --< Decelations About FK_Book_Constraint
DECLARE @FK_ConstraintName AS NVARCHAR(30) = 'FK_Book_Constraint'                --< Decelations About FK_Book_Constraint
------------------ /Just Fill Parameters Value ----------------

DECLARE @Query AS NVARCHAR(2000)

SET @Query= 'ALTER TABLE '+@TableName_OfOwnerOfConstraint+' DROP CONSTRAINT '+@FK_ConstraintName
EXECUTE sp_executesql @Query

SET @Query= 'Truncate Table '+ @TableName_ToTruncate
EXECUTE sp_executesql @Query

SET @Query= 'ALTER TABLE '+@TableName_OfOwnerOfConstraint+' ADD CONSTRAINT '+@FK_ConstraintName+' FOREIGN KEY('+@FK_ColumnName_In_TableOfOwnerOfConstraint+') REFERENCES '+@TableName_ToTruncate+'('+@Ref_ColumnName_In_TableName_ToTruncate+')'
EXECUTE sp_executesql @Query
  • In above answer of mine the method of resolve the mentioned problem in the question is based on @LauroWolffValenteSobrinho answer.

  • If you have more than one CONSTRAINT then you should append its codes like me to the above query

  • Also you can change the above code base @SerjSagan answer to disable an enable the constraint

Jaxb, Class has two properties of the same name

"Class has two properties of the same name exception" can happen when you have a class member x with a public access level and a getter/setter for the same member.

As a java rule of thumb, it is not recommended to use a public access level together with getters and setters.

Check this for more details: Public property VS Private property with getter?

To fix that:

  1. Change your member's access level to private and keep your getter/setter
  2. Remove the member's getter and setter

Objective-C for Windows

If you just want to experiment, there's an Objective-C compiler for .NET (Windows) here: qckapp

PDO get the last ID inserted

That's because that's an SQL function, not PHP. You can use PDO::lastInsertId().

Like:

$stmt = $db->prepare("...");
$stmt->execute();
$id = $db->lastInsertId();

If you want to do it with SQL instead of the PDO API, you would do it like a normal select query:

$stmt = $db->query("SELECT LAST_INSERT_ID()");
$lastId = $stmt->fetchColumn();

Python: How to create a unique file name?

You can use the datetime module

import datetime
uniq_filename = str(datetime.datetime.now().date()) + '_' + str(datetime.datetime.now().time()).replace(':', '.')

Note that: I am using replace since the colons are not allowed in filenames in many operating systems.

That's it, this will give you a unique filename every single time.

Resolving LNK4098: defaultlib 'MSVCRT' conflicts with

It means that one of the dependent dlls is compiled with a different run-time library.

Project -> Properties -> C/C++ -> Code Generation -> Runtime Library

Go over all the libraries and see that they are compiled in the same way.

More about this error in this link:

warning LNK4098: defaultlib "LIBCD" conflicts with use of other libs

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

Non-const and const reference binding follow different rules

These are the rules of the C++ language:

  • an expression consisting of a literal number (12) is a "rvalue"
  • it is not permitted to create a non-const reference with a rvalue: int &ri = 12; is ill-formed
  • it is permitted to create a const reference with a rvalue: in this case, an unnamed object is created by the compiler; this object will persist as long as the reference itself exist.

You have to understand that these are C++ rules. They just are.

It is easy to invent a different language, say C++', with slightly different rules. In C++', it would be permitted to create a non-const reference with a rvalue. There is nothing inconsistent or impossible here.

But it would allow some risky code where the programmer might not get what he intended, and C++ designers rightly decided to avoid that risk.

How to make node.js require absolute? (instead of relative)

What I like to do is leverage how node loads from the node_module directory for this.

If one tries to load the module "thing", one would do something like

require('thing');

Node will then look for the 'thing' directory in the 'node_module' directory.

Since the node_module is normally at the root of the project, we can leverage this consistency. (If node_module is not at the root, then you have other self induced headaches to deal with.)

If we go into the directory and then back out of it, we can get a consistent path to the root of the node project.

require('thing/../../');

Then if we want to access the /happy directory, we would do this.

require('thing/../../happy');

Though it is quite a bit hacky, however I feel if the functionality of how node_modules load changes, there will be bigger problems to deal with. This behavior should remain consistent.

To make things clear, I do this, because the name of module does not matter.

require('root/../../happy');

I used it recently for angular2. I want to load a service from the root.

import {MyService} from 'root/../../app/services/http/my.service';

String.Format for Hex

More generally.

byte[] buf = new byte[] { 123, 2, 233 };

string s = String.Concat(buf.Select(b => b.ToString("X2")));

Using HeapDumpOnOutOfMemoryError parameter for heap dump for JBoss

If you are not using "-XX:HeapDumpPath" option then in case of JBoss EAP/As by default the heap dump file will be generated in "JBOSS_HOME/bin" directory.

Converting a character code to char (VB.NET)

You could use the Chr(int) function

Execute command on all files in a directory

I'm doing this on my raspberry pi from the command line by running:

for i in *;do omxplayer "$i";done

How do I populate a JComboBox with an ArrayList?

DefaultComboBoxModel dml= new DefaultComboBoxModel();
for (int i = 0; i < <ArrayList>.size(); i++) {
  dml.addElement(<ArrayList>.get(i).getField());
}

<ComboBoxName>.setModel(dml);

Understandable code.Edit<> with type as required.

Vlookup referring to table data in a different sheet

There might be something wrong with your formula if you are looking from another sheet maybe you have to change Sheet1 to Sheet2 ---> =VLOOKUP(M3,Sheet2!$A$2:$Q$47,13,FALSE) --- Where Sheet2 is your table array

MySQL - SELECT * INTO OUTFILE LOCAL ?

You can achieve what you want with the mysql console with the -s (--silent) option passed in.

It's probably a good idea to also pass in the -r (--raw) option so that special characters don't get escaped. You can use this to pipe queries like you're wanting.

mysql -u username -h hostname -p -s -r -e "select concat('this',' ','works')"

EDIT: Also, if you want to remove the column name from your output, just add another -s (mysql -ss -r etc.)

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

'<option value=''.$key.'">'

should be

'<option value="'.$key.'">'

jQuery Selector: Id Ends With?

It's safer to add the underscore or $ to the term you're searching for so it's less likely to match other elements which end in the same ID:

$("element[id$=_txtTitle]")

(where element is the type of element you're trying to find - eg div, input etc.

(Note, you're suggesting your IDs tend to have $ signs in them, but I think .NET 2 now tends to use underscores in the ID instead, so my example uses an underscore).

What is the right way to debug in iPython notebook?

Use ipdb

Install it via

pip install ipdb

Usage:

In[1]: def fun1(a):
   def fun2(a):
       import ipdb; ipdb.set_trace() # debugging starts here
       return do_some_thing_about(b)
   return fun2(a)
In[2]: fun1(1)

For executing line by line use n and for step into a function use s and to exit from debugging prompt use c.

For complete list of available commands: https://appletree.or.kr/quick_reference_cards/Python/Python%20Debugger%20Cheatsheet.pdf

How to save Excel Workbook to Desktop regardless of user?

I think this is the most reliable way to get the desktop path which isn't always the same as the username.

MsgBox CreateObject("WScript.Shell").specialfolders("Desktop")

Bootstrap Align Image with text

i am a new bee ;p . And i faced the same problem. And the solution is BS Media objects. please see the code..

<div class="media">
   <div class="media-left media-top">
    <img src="something.png" alt="@l!" class="media-object" width="20" height="50"/>
    </div>
   <div class="media-body">
      <h2 class="media-heading">Beside Image</h2>
   </div>
</div>

What is the difference between supervised learning and unsupervised learning?

For instance, very often training a neural network is supervised learning: you're telling the network to which class corresponds the feature vector you're feeding.

Clustering is unsupervised learning: you let the algorithm decide how to group samples into classes that share common properties.

Another example of unsupervised learning is Kohonen's self organizing maps.

How do you clear Apache Maven's cache?

As some answers have pointed out, sometimes you really want to delete the local repository entirely, for example, there might be some artifacts that can't be purged as they are not anymore referenced by the pom.

If you want to have this deletion embedded in a maven phase, as for example clean you can use the maven-clean-plugin and access the repository through the settings, for example:

 <plugin>
    <inherited>false</inherited>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-antrun-plugin</artifactId>
    <version>1.1</version>
    <executions>
        <execution>
            <phase>clean</phase>
            <goals>
                <goal>run</goal>
            </goals>
            <configuration>
                <tasks>
                    <echo>Base clean is attached to deleting local maven cache</echo>
                    <echo>${settings.localRepository}</echo>
                </tasks>
            </configuration>
        </execution>
    </executions>
</plugin>

<plugin>
    <inherited>false</inherited>
    <artifactId>maven-clean-plugin</artifactId>
    <version>3.1.0</version>
    <configuration>
        <filesets>
            <fileset>
                <directory>${settings.localRepository}</directory>
            </fileset>
        </filesets>
    </configuration>
</plugin>

How can I find a specific element in a List<T>?

You can create a search variable to hold your searching criteria. Here is an example using database.

 var query = from o in this.mJDBDataset.Products 
             where o.ProductStatus == textBox1.Text || o.Karrot == textBox1.Text 
             || o.ProductDetails == textBox1.Text || o.DepositDate == textBox1.Text 
             || o.SellDate == textBox1.Text
             select o;

 dataGridView1.DataSource = query.ToList();

 //Search and Calculate
 search = textBox1.Text;
 cnn.Open();
 string query1 = string.Format("select * from Products where ProductStatus='"
               + search +"'");
 SqlDataAdapter da = new SqlDataAdapter(query1, cnn);
 DataSet ds = new DataSet();
 da.Fill(ds, "Products");
 SqlDataReader reader;
 reader = new SqlCommand(query1, cnn).ExecuteReader();

 List<double> DuePayment = new List<double>();

 if (reader.HasRows)
 {

  while (reader.Read())
  {

   foreach (DataRow row in ds.Tables["Products"].Rows)
   {

     DuePaymentstring.Add(row["DuePayment"].ToString());
     DuePayment = DuePaymentstring.Select(x => double.Parse(x)).ToList();

   }
  }

  tdp = 0;
  tdp = DuePayment.Sum();                        
  DuePaymentstring.Remove(Convert.ToString(DuePaymentstring.Count));
  DuePayment.Clear();
 }
 cnn.Close();
 label3.Text = Convert.ToString(tdp + " Due Payment Count: " + 
 DuePayment.Count + " Due Payment string Count: " + DuePaymentstring.Count);
 tdp = 0;
 //DuePaymentstring.RemoveRange(0,DuePaymentstring.Count);
 //DuePayment.RemoveRange(0, DuePayment.Count);
 //Search and Calculate

Here "var query" is generating the search criteria you are giving through the search variable. Then "DuePaymentstring.Select" is selecting the data matching your given criteria. Feel free to ask if you have problem understanding.

LEFT function in Oracle

LEFT is not a function in Oracle. This probably came from someone familiar with SQL Server:

Returns the left part of a character string with the specified number of characters.

-- Syntax for SQL Server, Azure SQL Database, Azure SQL Data Warehouse, Parallel Data Warehouse  
LEFT ( character_expression , integer_expression )  

Creating a dictionary from a CSV file

For simple csv files, such as the following

id,col1,col2,col3
row1,r1c1,r1c2,r1c3
row2,r2c1,r2c2,r2c3
row3,r3c1,r3c2,r3c3
row4,r4c1,r4c2,r4c3

You can convert it to a Python dictionary using only built-ins

with open(csv_file) as f:
    csv_list = [[val.strip() for val in r.split(",")] for r in f.readlines()]

(_, *header), *data = csv_list
csv_dict = {}
for row in data:
    key, *values = row   
    csv_dict[key] = {key: value for key, value in zip(header, values)}

This should yield the following dictionary

{'row1': {'col1': 'r1c1', 'col2': 'r1c2', 'col3': 'r1c3'},
 'row2': {'col1': 'r2c1', 'col2': 'r2c2', 'col3': 'r2c3'},
 'row3': {'col1': 'r3c1', 'col2': 'r3c2', 'col3': 'r3c3'},
 'row4': {'col1': 'r4c1', 'col2': 'r4c2', 'col3': 'r4c3'}}

Note: Python dictionaries have unique keys, so if your csv file has duplicate ids you should append each row to a list.

for row in data:
    key, *values = row

    if key not in csv_dict:
            csv_dict[key] = []

    csv_dict[key].append({key: value for key, value in zip(header, values)})

How can I convert radians to degrees with Python?

Python convert radians to degrees or degrees to radians:

What are Radians and what problem does it solve?:

Radians and degrees are two separate units of measure that help people express and communicate precise changes in direction. Wikipedia has some great intuition with their infographics on how one Radian is defined relative to degrees:

https://en.wikipedia.org/wiki/Radian

Conversion from radians to degrees

Python examples using libraries calculating degrees from radians:

>>> import math
>>> math.degrees(0)                       #0 radians == 0 degrees
0.0
>>> math.degrees(math.pi/2)               #pi/2 radians is 90 degrees
90.0
>>> math.degrees(math.pi)                 #pi radians is 180 degrees
180.0      
>>> math.degrees(math.pi+(math.pi/2))     #pi+pi/2 radians is 270 degrees
270.0 
>>> math.degrees(math.pi+math.pi)         #2*pi radians is 360 degrees
360.0      

Python examples using libraries calculating radians from degrees:

>>> import math
>>> math.radians(0)           #0 degrees == 0 radians
0.0
>>> math.radians(90)          #90 degrees is pi/2 radians
1.5707963267948966
>>> math.radians(180)         #180 degrees is pi radians
3.141592653589793
>>> math.radians(270)         #270 degrees is pi+(pi/2) radians
4.71238898038469
>>> math.radians(360)         #360 degrees is 2*pi radians
6.283185307179586

Source: https://docs.python.org/3/library/math.html#angular-conversion

The mathematical notation:

Mathematical notation of degrees and radians

You can do degree/radian conversion without libraries:

If you roll your own degree/radian converter, you have to write your own code to handle edge cases.

Mistakes here are easy to make, and will hurt just like it hurt the developers of the 1999 mars orbiter who sunk $125m dollars crashing it into Mars because of non intuitive edge cases here.

Lets crash that orbiter and Roll our own Radians to Degrees:

Invalid radians as input return garbage output.

>>> 0 * 180.0 / math.pi                         #0 radians is 0 degrees
0.0
>>> (math.pi/2) * 180.0 / math.pi               #pi/2 radians is 90 degrees
90.0
>>> (math.pi) * 180.0 / math.pi                 #pi radians is 180 degrees
180.0
>>> (math.pi+(math.pi/2)) * 180.0 / math.pi     #pi+(pi/2) radians is 270 degrees
270.0
>>> (2 * math.pi) * 180.0 / math.pi             #2*pi radians is 360 degrees
360.0

Degrees to radians:

>>> 0 * math.pi / 180.0              #0 degrees in radians
0.0
>>> 90 * math.pi / 180.0             #90 degrees in radians
1.5707963267948966
>>> 180 * math.pi / 180.0            #180 degrees in radians
3.141592653589793
>>> 270 * math.pi / 180.0            #270 degrees in radians
4.71238898038469
>>> 360 * math.pi / 180.0            #360 degrees in radians
6.283185307179586

Expressing multiple rotations with degrees and radians

Single rotation valid radian values are between 0 and 2*pi. Single rotation degree values are between 0 and 360. However if you want to express multiple rotations, valid radian and degree values are between 0 and infinity.

>>> import math
>>> math.radians(360)                 #one complete rotation
6.283185307179586
>>> math.radians(360+360)             #two rotations
12.566370614359172
>>> math.degrees(12.566370614359172)  #math.degrees and math.radians preserve the
720.0                                 #number of rotations

Collapsing multiple rotations:

You can collapse multiple degree/radian rotations into a single rotation by modding against the value of one rotation. For degrees you mod by 360, for radians you modulus by 2*pi.

>>> import math
>>> math.radians(720+90)        #2 whole rotations plus 90 is 14.14 radians
14.137166941154069
>>> math.radians((720+90)%360)  #14.1 radians brings you to 
1.5707963267948966              #the end point as 1.57 radians.

>>> math.degrees((2*math.pi)+(math.pi/2))            #one rotation plus a quarter 
450.0                                                #rotation is 450 degrees.
>>> math.degrees(((2*math.pi)+(math.pi/2))%(2*math.pi)) #one rotation plus a quarter
90.0                                                    #rotation brings you to 90.

Protip

Khan academy has some excellent content to solidify intuition around trigonometry and angular mathematics: https://www.khanacademy.org/math/algebra2/trig-functions/intro-to-radians-alg2/v/introduction-to-radians

Trying to create a file in Android: open failed: EROFS (Read-only file system)

I have tried this with and without the WRITE_INTERNAL_STORAGE permission.

There is no WRITE_INTERNAL_STORAGE permission in Android.

How do I create this file for writing?

You don't, except perhaps on a rooted device, if your app is running with superuser privileges. You are trying to write to the root of internal storage, which apps do not have access to.

Please use the version of the FileOutputStream constructor that takes a File object. Create that File object based off of some location that you can write to, such as:

  • getFilesDir() (called on your Activity or other Context)
  • getExternalFilesDir() (called on your Activity or other Context)

The latter will require WRITE_EXTERNAL_STORAGE as a permission.

Is there an easier way than writing it to a file then reading from it again?

You can temporarily put it in a static data member.

because many people don't have SD card slots

"SD card slots" are irrelevant, by and large. 99% of Android device users will have external storage -- the exception will be 4+ year old devices where the user removed their SD card. Devices manufactured since mid-2010 have external storage as part of on-board flash, not as removable media.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

You should set property file name without .properties extension, it works correctly for me:)

How to undo last commit

Warning: Don't do this if you've already pushed

You want to do:

git reset HEAD~

If you don't want the changes and blow everything away:

git reset --hard HEAD~

Generate a sequence of numbers in Python

In python 3.1 you can produce a list in a way

     lst=list(range(100))
     for i in range(100)
        print (lst[i],',',end='')

In python 2.7 you can do it as

     lst=range(100)
     for i in range(100)
        print lst[i]+',' 

How to change indentation in Visual Studio Code?

To change the indentation based on programming language:

  1. Open the Command Palette (CtrlShiftP | macOS: ??P)

  2. Preferences: Configure language specific settings... (command id: workbench.action.configureLanguageBasedSettings)

  3. Select programming language (for example TypeScript)

  4. Add this code:

    "[typescript]": {
        "editor.tabSize": 2
    }
    

See also: VS Code Docs

Unit testing with Spring Security

I asked the same question myself over here, and just posted an answer that I recently found. Short answer is: inject a SecurityContext, and refer to SecurityContextHolder only in your Spring config to obtain the SecurityContext

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

Setting format and value in input type="date"

function getDefaultDate(curDate){
var dt = new Date(curDate);`enter code here`
var date = dt.getDate();
var month = dt.getMonth();
var year = dt.getFullYear();
if (month.toString().length == 1) {
    month = "0" + month
}
if (date.toString().length == 1) {
    date = "0" + date
}
return year.toString() + "-" + month.toString() + "-" + date.toString();
}

In function pass your date string.

Visual Studio 2017: Display method references

CodeLens is not available in the Community editions. You need Professional or higher to switch it on.

In VS2015, one way to "get" CodeLens was to install the SQL Server Developer Tools (SSDT) but I believe this has been rectified in VS2017.

Still you can get all method reference by right clicking on the method and "Find All references"

enter image description here

How to adjust layout when soft keyboard appears

In my case it helped.

main_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main2"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context="com.livewallpaper.profileview.loginact.Main2Activity">

<TextView
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:text="Title"
    android:gravity="center"
    android:layout_height="0dp" />
<LinearLayout
    android:layout_weight="1"
    android:layout_width="match_parent"
    android:layout_height="0dp">
    <EditText
        android:hint="enter here"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>
<TextView
    android:layout_weight="1"
    android:text="signup for App"
    android:gravity="bottom|center_horizontal"
    android:layout_width="match_parent"
    android:layout_height="0dp" />
</LinearLayout>

Use this in manifest file

<activity android:name=".MainActivity"
        android:screenOrientation="portrait"
        android:windowSoftInputMode="adjustResize"/>

Now the most important part! Use theme like this in either Activity or Application tag.

android:theme="@style/AppTheme"

And the theme tooks like this

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="windowActionModeOverlay">true</item>
</style>

So I was missing the theme. Which made me frustrated all day.

Get current URL from IFRAME

If your iframe is from another domain, (cross domain), the other answers are not going to help you... you will simply need to use this:

var currentUrl = document.referrer;

and - here you've got the main url!

How to fix 'Microsoft Excel cannot open or save any more documents'

If none of the above worked, try these as well:

  • In Component services >Computes >My Computer>Dcom config>Microsoft Excel Application>Properties, go to security tab, click on customize on all three sections and add the user that want to run the application, and give full permissions to the user.

  • Go to C:\Windows\Temp make sure it exists and it doesn't prompt you for entering.

Changing width property of a :before css selector using JQuery

You may try to inherit property from the base class:

_x000D_
_x000D_
var width = 2;_x000D_
var interval = setInterval(function () {_x000D_
    var element = document.getElementById('box');_x000D_
    width += 0.0625;_x000D_
    element.style.width = width + 'em';_x000D_
    if (width >= 7) clearInterval(interval);_x000D_
}, 50);
_x000D_
.box {_x000D_
    /* Set property */_x000D_
    width:4em;_x000D_
    height:2em;_x000D_
    background-color:#d42;_x000D_
    position:relative;_x000D_
}_x000D_
.box:after {_x000D_
    /* Inherit property */_x000D_
    width:inherit;_x000D_
    content:"";_x000D_
    height:1em;_x000D_
    background-color:#2b4;_x000D_
    position:absolute;_x000D_
    top:100%;_x000D_
}
_x000D_
<div id="box" class="box"></div>
_x000D_
_x000D_
_x000D_

How to parse JSON without JSON.NET library?

For those who do not have 4.5, Here is my library function that reads json. It requires a project reference to System.Web.Extensions.

using System.Web.Script.Serialization;

public object DeserializeJson<T>(string Json)
{
    JavaScriptSerializer JavaScriptSerializer = new JavaScriptSerializer();
    return JavaScriptSerializer.Deserialize<T>(Json);
}

Usually, json is written out based on a contract. That contract can and usually will be codified in a class (T). Sometimes you can take a word from the json and search the object browser to find that type.

Example usage:

Given the json

{"logEntries":[],"value":"My Code","text":"My Text","enabled":true,"checkedIndices":[],"checkedItemsTextOverflows":false}

You could parse it into a RadComboBoxClientState object like this:

string ClientStateJson = Page.Request.Form("ReportGrid1_cboReportType_ClientState");
RadComboBoxClientState RadComboBoxClientState = DeserializeJson<RadComboBoxClientState>(ClientStateJson);
return RadComboBoxClientState.Value;

How to convert a multipart file to File?

You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

The source for the MultipartFile save to disk.

File file = new File(directory, filename);

// Create the file using the touch method of the FileUtils class.
// FileUtils.touch(file);

// Write bytes from the multipart file to disk.
FileUtils.writeByteArrayToFile(file, multipartFile.getBytes());

Correct way to try/except using Python requests module?

One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)

Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah

vs

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)     

OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah

Python wildcard search in string

You could try the fnmatch module, it's got a shell-like wildcard syntax

or can use regular expressions

import re

Run "mvn clean install" in Eclipse

Right click on pom.xml, Run As, you should see the list of m2 options if you have Maven installed, you can select Maven Clean from there

How to give a pandas/matplotlib bar graph custom colors

I found the easiest way is to use the colormap parameter in .plot() with one of the preset color gradients:

df.plot(kind='bar', stacked=True, colormap='Paired')

enter image description here

You can find a large list of preset colormaps here.

colormaps

open link in iframe

Assuming the iFrame has a name attribute of "myIframe":

<a href="http://www.google.com" target="myIframe">Link Text</a> 

You can also accomplish this with the use of Javascript. The iFrame has a src attribute which specifies the location it shows. As such, it's a simple matter of binding the click of a link to changing that src attribute.

How to create websockets server in PHP

I was in your shoes for a while and finally ended up using node.js, because it can do hybrid solutions like having web and socket server in one. So php backend can submit requests thru http to node web server and then broadcast it with websocket. Very efficiant way to go.

Bootstrap NavBar with left, center or right aligned items

I found the following was a better solution depending on the content of your left, center and right items. A width of 100% without a margin caused overlapping of divs and was preventing anchor tags to work correctly - that is without the messy use of z-indexes.

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    margin: auto;
    margin-left: 48%;
}

Getting datarow values into a string?

You can get a columns value by doing this

 rows["ColumnName"]

You will also have to cast to the appropriate type.

 output += (string)rows["ColumnName"]

Error: request entity too large

If someone tried all the answers, but hadn't had any success yet and uses NGINX to host the site add this line to /etc/nginx/sites-available

client_max_body_size 100M; #100mb

What's the main difference between Java SE and Java EE?

Java SE refers to the standard version of Java and its libraries. Java EE refers to the Enterprise edition of Java which is used to deploy web applications.

SQL Data Reader - handling Null column values

This method is dependent on indexFirstName which should be the zero-based column ordinal.

if(!sqlReader.IsDBNull(indexFirstName))
{
  employee.FirstName = sqlreader.GetString(indexFirstName);
}

If you don't know the column index but wan't to check a name you can use this extension method instead:

public static class DataRecordExtensions
{
    public static bool HasColumn(this IDataRecord dr, string columnName)
    {
        for (int i=0; i < dr.FieldCount; i++)
        {
            if (dr.GetName(i).Equals(columnName, StringComparison.InvariantCultureIgnoreCase))
                return true;
        }
        return false;
    }
}

And use the method like this:

if(sqlReader.HasColumn("FirstName"))
{
  employee.FirstName = sqlreader["FirstName"];
}

how to check if string value is in the Enum list?

You can use the Enum.TryParse method:

Age age;
if (Enum.TryParse<Age>("New_Born", out age))
{
    // You now have the value in age 
}

Pandas: Subtracting two date columns and the result being an integer

You can divide column of dtype timedelta by np.timedelta64(1, 'D'), but output is not int, but float, because NaN values:

df_test['Difference'] = df_test['Difference'] / np.timedelta64(1, 'D')
print (df_test)
  First_Date Second Date  Difference
0 2016-02-09  2015-11-19        82.0
1 2016-01-06  2015-11-30        37.0
2        NaT  2015-12-04         NaN
3 2016-01-06  2015-12-08        29.0
4        NaT  2015-12-09         NaN
5 2016-01-07  2015-12-11        27.0
6        NaT  2015-12-12         NaN
7        NaT  2015-12-14         NaN
8 2016-01-06  2015-12-14        23.0
9        NaT  2015-12-15         NaN

Frequency conversion.

SQL update fields of one table from fields of another one

Not necessarily what you asked, but maybe using postgres inheritance might help?

CREATE TABLE A (
    ID            int,
    column1       text,
    column2       text,
    column3       text
);

CREATE TABLE B (
    column4       text
) INHERITS (A);

This avoids the need to update B.

But be sure to read all the details.

Otherwise, what you ask for is not considered a good practice - dynamic stuff such as views with SELECT * ... are discouraged (as such slight convenience might break more things than help things), and what you ask for would be equivalent for the UPDATE ... SET command.

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

How to dynamically allocate memory space for a string and get that string from user?

This is a function snippet I wrote to scan the user input for a string and then store that string on an array of the same size as the user input. Note that I initialize j to the value of 2 to be able to store the '\0' character.

char* dynamicstring() {
    char *str = NULL;
    int i = 0, j = 2, c;
    str = (char*)malloc(sizeof(char));
    //error checking
    if (str == NULL) {
        printf("Error allocating memory\n");
        exit(EXIT_FAILURE);
    }

    while((c = getc(stdin)) && c != '\n')
    {
        str[i] = c;
        str = realloc(str,j*sizeof(char));
        //error checking
        if (str == NULL) {
            printf("Error allocating memory\n");
            free(str);
            exit(EXIT_FAILURE);
        }

        i++;
        j++;
    }
    str[i] = '\0';
    return str;
}

In main(), you can declare another char* variable to store the return value of dynamicstring() and then free that char* variable when you're done using it.

What does "restore purchases" in In-App purchases mean?

Is it as optional functionality.

If you won't provide it when user will try to purchase non-consumable product AppStore will restore old transaction. But your app will think that this is new transaction.

If you will provide restore mechanism then your purchase manager will see restored transaction.

If app should distinguish this options then you should provide functionality for restoring previously purchased products.

Adding header to all request with Retrofit 2

The Latest Retrofit Version HERE -> 2.1.0.

lambda version:

  builder.addInterceptor(chain -> {
    Request request = chain.request().newBuilder().addHeader("key", "value").build();
    return chain.proceed(request);
  });

ugly long version:

  builder.addInterceptor(new Interceptor() {
    @Override public Response intercept(Chain chain) throws IOException {
      Request request = chain.request().newBuilder().addHeader("key", "value").build();
      return chain.proceed(request);
    }
  });

full version:

class Factory {

public static APIService create(Context context) {

  OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
  builder.readTimeout(10, TimeUnit.SECONDS);
  builder.connectTimeout(5, TimeUnit.SECONDS);

  if (BuildConfig.DEBUG) {
    HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
    interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
    builder.addInterceptor(interceptor);
  }

  builder.addInterceptor(chain -> {
    Request request = chain.request().newBuilder().addHeader("key", "value").build();
    return chain.proceed(request);
  });

  builder.addInterceptor(new UnauthorisedInterceptor(context));
  OkHttpClient client = builder.build();

  Retrofit retrofit =
      new Retrofit.Builder().baseUrl(APIService.ENDPOINT).client(client).addConverterFactory(GsonConverterFactory.create()).addCallAdapterFactory(RxJavaCallAdapterFactory.create()).build();

  return retrofit.create(APIService.class);
  }
}

gradle file (you need to add the logging interceptor if you plan to use it):

  //----- Retrofit
  compile 'com.squareup.retrofit2:retrofit:2.1.0'
  compile "com.squareup.retrofit2:converter-gson:2.1.0"
  compile "com.squareup.retrofit2:adapter-rxjava:2.1.0"
  compile 'com.squareup.okhttp3:logging-interceptor:3.4.0'

How to click a href link using Selenium

Use

driver.findElement(By.linkText("App Configuration")).click()

Other Approaches will be

JavascriptLibrary jsLib = new JavascriptLibrary(); 
jsLib.callEmbeddedSelenium(selenium, "triggerMouseEventAt", elementToClick,"click", "0,0");

or

((JavascriptExecutor) driver).executeScript("arguments[0].click();", elementToClick);

For detailed answer, View this post

How can I set / change DNS using the command-prompt at windows 8

Here is your new friend: QuickSetDNS, by NirSoft, amazing as usual.

screenshot

It also can be used in command line :) with these advantages over netsh:

  • easier syntax, in particular for setting the alternate server
  • automatically asks for privilege elevation


Just a few caveats:

  • supports only setting of IPv4, not of IPv6
  • in command line, the adapter UUID should be used, not the friendly name (e.g. "Local Area Connection") since QuickSetDNS 1.21, connection names are also supported ;)