Programs & Examples On #Clistbox

How can I check if a string only contains letters in Python?

(1) Use str.isalpha() when you print the string.

(2) Please check below program for your reference:-

 str = "this";  # No space & digit in this string
 print str.isalpha() # it gives return True

 str = "this is 2";
 print str.isalpha() # it gives return False

Note:- I checked above example in Ubuntu.

Binding an Image in WPF MVVM

If you have a process that already generates and returns an Image type, you can alter the bind and not have to modify any additional image creation code.

Refer to the ".Source" of the image in the binding statement.

XAML

<Image Name="imgOpenClose" Source="{Binding ImageOpenClose.Source}"/>

View Model Field

private Image _imageOpenClose;
public Image ImageOpenClose
{
    get
    {
        return _imageOpenClose;
    }
    set
    {
        _imageOpenClose = value;
        OnPropertyChanged();
    }
}

Use of True, False, and None as return values in Python functions

For True, not None:

if foo:

For false, None:

if not foo:

Vue.js redirection to another page

can try this too ...

router.push({ name: 'myRoute' })

how to create dynamic two dimensional array in java?

simple you want to inialize a 2d array and assign a size of array then a example is

   public static void main(String args[])
   { 
    char arr[][];   //arr is 2d array name
    arr = new char[3][3]; 
    }


   //this is a way to inialize a 2d array in java....  

AngularJS Multiple ng-app within a page

_x000D_
_x000D_
         var shoppingCartModule = angular.module("shoppingCart", [])_x000D_
          shoppingCartModule.controller("ShoppingCartController",_x000D_
           function($scope) {_x000D_
             $scope.items = [{_x000D_
               product_name: "Product 1",_x000D_
               price: 50_x000D_
             }, {_x000D_
               product_name: "Product 2",_x000D_
               price: 20_x000D_
             }, {_x000D_
               product_name: "Product 3",_x000D_
               price: 180_x000D_
             }];_x000D_
             $scope.remove = function(index) {_x000D_
               $scope.items.splice(index, 1);_x000D_
             }_x000D_
           }_x000D_
         );_x000D_
         var namesModule = angular.module("namesList", [])_x000D_
          namesModule.controller("NamesController",_x000D_
           function($scope) {_x000D_
             $scope.names = [{_x000D_
               username: "Nitin"_x000D_
             }, {_x000D_
               username: "Mukesh"_x000D_
             }];_x000D_
           }_x000D_
         );_x000D_
_x000D_
_x000D_
         var namesModule = angular.module("namesList2", [])_x000D_
          namesModule.controller("NamesController",_x000D_
           function($scope) {_x000D_
             $scope.names = [{_x000D_
               username: "Nitin"_x000D_
             }, {_x000D_
               username: "Mukesh"_x000D_
             }];_x000D_
           }_x000D_
         );_x000D_
_x000D_
_x000D_
         angular.element(document).ready(function() {_x000D_
           angular.bootstrap(document.getElementById("App2"), ['namesList']);_x000D_
           angular.bootstrap(document.getElementById("App3"), ['namesList2']);_x000D_
         });
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
_x000D_
  <div id="App1" ng-app="shoppingCart" ng-controller="ShoppingCartController">_x000D_
    <h1>Your order</h1>_x000D_
    <div ng-repeat="item in items">_x000D_
      <span>{{item.product_name}}</span>_x000D_
      <span>{{item.price | currency}}</span>_x000D_
      <button ng-click="remove($index);">Remove</button>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
  <div id="App2" ng-app="namesList" ng-controller="NamesController">_x000D_
    <h1>List of Names</h1>_x000D_
    <div ng-repeat="_name in names">_x000D_
      <p>{{_name.username}}</p>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div id="App3" ng-app="namesList2" ng-controller="NamesController">_x000D_
    <h1>List of Names</h1>_x000D_
    <div ng-repeat="_name in names">_x000D_
      <p>{{_name.username}}</p>_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

$(window).width() not the same as media query

It may be due to scrollbar, use innerWidth instead of width like

if($(window).innerWidth() <= 751) {
   $("#body-container .main-content").remove()
                                .insertBefore($("#body-container .left-sidebar"));
} else {
   $("#body-container .main-content").remove()
                                .insertAfter($("#body-container .left-sidebar"));
}

Also you can get the viewport like

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };
}

Above code Source

How to sort Counter by value? - python

Yes:

>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})

Using the sorted keyword key and a lambda function:

>>> sorted(x.items(), key=lambda i: i[1])
[('b', 3), ('a', 5), ('c', 7)]
>>> sorted(x.items(), key=lambda i: i[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]

This works for all dictionaries. However Counter has a special function which already gives you the sorted items (from most frequent, to least frequent). It's called most_common():

>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
>>> list(reversed(x.most_common()))  # in order of least to most
[('b', 3), ('a', 5), ('c', 7)]

You can also specify how many items you want to see:

>>> x.most_common(2)  # specify number you want
[('c', 7), ('a', 5)]

Applying Comic Sans Ms font style

The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:

http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http

810    style = "body { background-color: white; color: black; font-family: "
811        "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812        "hr { border: 0; border-bottom: 1px dashed; }\n";

E.g., try this:

font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;

CSS Calc Viewport Units Workaround?

<div>It's working fine.....</div>

div
{
     height: calc(100vh - 8vw);
    background: #000;
    overflow:visible;
    color: red;
}

Check here this css code right now support All browser without Opera

just check this

Live

see Live preview by jsfiddle

See Live preview by codepen.io

Google Maps: How to create a custom InfoWindow?

I found InfoBox perfect for advanced styling.

An InfoBox behaves like a google.maps.InfoWindow, but it supports several additional properties for advanced styling. An InfoBox can also be used as a map label. An InfoBox also fires the same events as a google.maps.InfoWindow.

Include http://code.google.com/p/google-maps-utility-library-v3/source/browse/trunk/infobox/src/infobox.js in your page

Creating executable files in Linux

Make file executable:

chmod +x file

Find location of perl:

which perl

This should return something like

/bin/perl sometimes /usr/local/bin

Then in the first line of your script add:

#!"path"/perl with path from above e.g.

#!/bin/perl

Then you can execute the file

./file

There may be some issues with the PATH, so you may want to change that as well ...

How do you post to the wall on a facebook page (not profile)

This works for me:

try {
       $statusUpdate = $facebook->api('/me/feed', 'post',
                 array('name'=>'My APP on Facebook','message'=> 'I am here working',
                 'privacy'=> array('value'=>'CUSTOM','friends'=>'SELF'),
                 'description'=>'testing my description',
                 'picture'=>'https://fbcdn-photos-a.akamaihd.net/mypicture.gif',
                 'caption'=>'apps.facebook.com/myapp','link'=>'http://apps.facebook.com/myapp'));
 } catch (FacebookApiException $e) {
      d($e);
}

How can I copy a file on Unix using C?

sprintf( cmd, "/bin/cp -p \'%s\' \'%s\'", old, new);

system( cmd);

Add some error checks...

Otherwise, open both and loop on read/write, but probably not what you want.

...

UPDATE to address valid security concerns:

Rather than using "system()", do a fork/wait, and call execv() or execl() in the child.

execl( "/bin/cp", "-p", old, new);

How to view UTF-8 Characters in VIM or Gvim

On Microsoft Windows, gvim wouldn't allow you to select non-monospaced fonts. Unfortunately Latha is a non-monospaced font.

There is a hack way to make it happen: Using FontForge (you can download Windows binary from http://www.geocities.jp/meir000/fontforge/) to edit the Latha.ttf and mark it as a monospaced font. Doing like this:

  1. Load fontforge, select latha.ttf.
  2. Menu: Element -> Font Info
  3. Select "OS/2" from left-hand list on Font Info dialog
  4. Select "Panose" tab
  5. Set Proportion = Monospaced
  6. Save new TTF version of this font, try it out!

Good luck!

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.

create table test (
  id integer not null,
  ts datetime not null
  );

insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');

Values were chosen in such a way that for

  • id = 1, elapsed time is 1 hour
  • id = 2, elapsed time is 2 hours, and
  • id = 3, elapsed time is 3 hours.

This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.

select t.id,
       min(ts) start_time,
       max(ts) end_time,
       datediff(second, min(ts),max(ts)) elapsed_sec,
       convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;

ID  START_TIME                 END_TIME                   ELAPSED_SEC  DO_NOT_USE
1   January, 01 2012 08:00:00  January, 01 2012 09:00:00  3600         01:00:00
2   January, 01 2012 08:30:00  January, 01 2012 10:30:00  7200         02:00:00
3   January, 01 2012 09:00:00  January, 02 2012 12:00:00  97200        03:00:00

Note the misleading "03:00:00" for the 27-hour difference on id number 3.

Function to format elapsed time in SQL Server

Regex empty string or email

If you are using it within rails - activerecord validation you can set allow_blank: true

As:

validates :email, allow_blank: true, format: { with: EMAIL_REGEX }

Executing Javascript from Python

One more solution as PyV8 seems to be unmaintained and dependent on the old version of libv8.

PyMiniRacer It's a wrapper around the v8 engine and it works with the new version and is actively maintained.

pip install py-mini-racer

from py_mini_racer import py_mini_racer
ctx = py_mini_racer.MiniRacer()
ctx.eval("""
function escramble_758(){
    var a,b,c
    a='+1 '
    b='84-'
    a+='425-'
    b+='7450'
    c='9'
    return a+c+b;
}
""")
ctx.call("escramble_758")

And yes, you have to replace document.write with return as others suggested

In Git, how do I figure out what my current revision is?

below will work with any previously pushed revision, not only HEAD

for abbreviated revision hash:

git log -1 --pretty=format:%h

for long revision hash:

git log -1 --pretty=format:%H

How can I login to a website with Python?

Web page automation ? Definitely "webbot"

webbot even works web pages which have dynamically changing id and classnames and has more methods and features than selenium or mechanize.

Here's a snippet :)

from webbot import Browser 
web = Browser()
web.go_to('google.com') 
web.click('Sign in')
web.type('[email protected]' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^

The docs are also pretty straight forward and simple to use : https://webbot.readthedocs.io

if (boolean condition) in Java

Okay, so..

// As you already stated, you know that a boolean defaults to false.
boolean turnedOn;
if(turnedOn) // Here, you are saying "if turnedOn (is true, that's implicit)
{
//then do this
}
else // if it is NOT true (it is false)
{
//do this
}

Does it make more sense now?

The if statement will evaluate whatever code you put in it that returns a boolean value, and if the evaluation returns true, you enter the first block. Else (if the value is not true, it will be false, because a boolean can either be true or false) it will enter the - yep, you guessed it - the else {} block.

A more verbose example.

If I am asked "are you hungry?", the simple answer is yes (true). or no (false).

boolean isHungry = true; // I am always hungry dammit.
if(isHungry) { // Yes, I am hungry.
   // Well, you should go grab a bite to eat then!
} else { // No, not really.
   // Ah, good for you. More food for me!

   // As if this would ever happen - bad example, sorry. ;)
}

Byte Array in Python

Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray type.

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>> 

The service cannot accept control messages at this time

I killed related w3wp.exe (on a friends' advise) at task manager and it worked.

Note: Use at your own risk. Be careful picking which one to kill.

Android read text raw resource file

What if you use a character-based BufferedReader instead of byte-based InputStream?

BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line = reader.readLine();
while (line != null) { 
    ...
    line = reader.readLine();
}

Don't forget that readLine() skips the new-lines!

Checking whether a variable is an integer or not

You can use this function:

def is_int(x):    
    if type(x) == int:
       return True
    return False

Test:

print is_int('7.0') # False
print is_int(7.0) # False
print is_int(7.5) # False
print is_int(-1) # True

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use <script>'s defer attribute. It specifies that the script will be executed when the page has finished parsing.

<script defer src="path/to/yourscript.js">

A nice article about this: http://davidwalsh.name/script-defer

Browser support seems pretty good: http://caniuse.com/#search=defer

Another great article about loading JS using defer and async: https://flaviocopes.com/javascript-async-defer/

Spring Boot - How to log all requests and responses with exceptions in single place?

the code pasted below works with my tests and can be downloaded from my [github project][1], sharing after applying a solution based on that on a production project.

@Configuration
public class LoggingFilter extends GenericFilterBean {

    /**
     * It's important that you actually register your filter this way rather then just annotating it
     * as @Component as you need to be able to set for which "DispatcherType"s to enable the filter
     * (see point *1*)
     * 
     * @return
     */
    @Bean
    public FilterRegistrationBean<LoggingFilter> initFilter() {
        FilterRegistrationBean<LoggingFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(new LoggingFilter());

        // *1* make sure you sett all dispatcher types if you want the filter to log upon
        registrationBean.setDispatcherTypes(EnumSet.allOf(DispatcherType.class));

        // *2* this should put your filter above any other filter
        registrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);

        return registrationBean;
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        ContentCachingRequestWrapper wreq = 
            new ContentCachingRequestWrapper(
                (HttpServletRequest) request);

        ContentCachingResponseWrapper wres = 
            new ContentCachingResponseWrapper(
                (HttpServletResponse) response);

        try {

            // let it be ...
            chain.doFilter(wreq, wres);

            // makes sure that the input is read (e.g. in 404 it may not be)
            while (wreq.getInputStream().read() >= 0);

            System.out.printf("=== REQUEST%n%s%n=== end request%n",
                    new String(wreq.getContentAsByteArray()));

            // Do whatever logging you wish here, in this case I'm writing request 
            // and response to system out which is probably not what you wish to do
            System.out.printf("=== RESPONSE%n%s%n=== end response%n",
                    new String(wres.getContentAsByteArray()));

            // this is specific of the "ContentCachingResponseWrapper" we are relying on, 
            // make sure you call it after you read the content from the response
            wres.copyBodyToResponse();

            // One more point, in case of redirect this will be called twice! beware to handle that
            // somewhat

        } catch (Throwable t) {
            // Do whatever logging you whish here, too
            // here you should also be logging the error!!!
            throw t;
        }

    }
}

Difference between attr_accessor and attr_accessible

attr_accessor is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to

class MyModel
  def my_variable
    @my_variable
  end
  def my_variable=(value)
    @my_variable = value
  end
end

attr_accessible is a Rails method that determines what variables can be set in a mass assignment.

When you submit a form, and you have something like MyModel.new params[:my_model] then you want to have a little bit more control, so that people can't submit things that you don't want them to.

You might do attr_accessible :email so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.

That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.

So attr_accessor is about creating methods to store variables, and attr_accessible is about the security of mass assignments.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

My issue was not that I was referencing the server by the IP address instead of the URL. I had purchased a signed certificate from a CA for use inside a private network. The URL specified on the certificate does matter when referencing the server. Once I referenced the server by the URL in the certificate everything started to work.

Remove carriage return in Unix

Removing \r on any UNIX® system:

Most existing solutions in this question are GNU-specific, and wouldn't work on OS X or BSD; the solutions below should work on many more UNIX systems, and in any shell, from tcsh to sh, yet still work even on GNU/Linux, too.

Tested on OS X, OpenBSD and NetBSD in tcsh, and on Debian GNU/Linux in bash.


With sed:

In tcsh on an OS X, the following sed snippet could be used together with printf, as neither sed nor echo handle \r in the special way like the GNU does:

sed `printf 's/\r$//g'` input > output

With tr:

Another option is tr:

tr -d '\r' < input > output

Difference between sed and tr:

It would appear that tr preserves a lack of a trailing newline from the input file, whereas sed on OS X and NetBSD (but not on OpenBSD or GNU/Linux) inserts a trailing newline at the very end of the file even if the input is missing any trailing \r or \n at the very end of the file.


Testing:

Here's some sample testing that could be used to ensure this works on your system, using printf and hexdump -C; alternatively, od -c could also be used if your system is missing hexdump:

% printf 'a\r\nb\r\nc' | hexdump -C
00000000  61 0d 0a 62 0d 0a 63                              |a..b..c|
00000007
% printf 'a\r\nb\r\nc' | ( sed `printf 's/\r$//g'` /dev/stdin > /dev/stdout ) | hexdump -C
00000000  61 0a 62 0a 63 0a                                 |a.b.c.|
00000006
% printf 'a\r\nb\r\nc' | ( tr -d '\r' < /dev/stdin > /dev/stdout ) | hexdump -C
00000000  61 0a 62 0a 63                                    |a.b.c|
00000005
% 

How to find all trigger associated with a table with SQL Server?

select t.name as TriggerName,m.definition,is_disabled 
from sys.all_sql_modules m 
inner join  
sys.triggers t
on m.object_id = t.object_id 
inner join sys.objects o
on o.object_id = t.parent_id
Where o.name = 'YourTableName'

This will give you all triggers on a Specified Table

C convert floating point to int

If you want to round it to lower, just cast it.

float my_float = 42.8f;
int my_int;
my_int = (int)my_float;          // => my_int=42

For other purpose, if you want to round it to nearest, you can make a little function or a define like this:

#define FLOAT_TO_INT(x) ((x)>=0?(int)((x)+0.5):(int)((x)-0.5))

float my_float = 42.8f;
int my_int;
my_int = FLOAT_TO_INT(my_float); // => my_int=43

Be careful, ideally you should verify float is between INT_MIN and INT_MAX before casting it.

Get UTC time and local time from NSDate object

My Xcode Version 6.1.1 (6A2008a)

In playground, test like this:

// I'm in East Timezone 8
let x = NSDate() //Output:"Dec 29, 2014, 11:37 AM"
let y = NSDate.init() //Output:"Dec 29, 2014, 11:37 AM"
println(x) //Output:"2014-12-29 03:37:24 +0000"


// seconds since 2001
x.hash //Output:441,517,044
x.hashValue //Output:441,517,044
x.timeIntervalSinceReferenceDate //Output:441,517,044.875367

// seconds since 1970
x.timeIntervalSince1970 //Output:1,419,824,244.87537

How to set a bitmap from resource

If you have declare a bitmap object and you want to display it or store this bitmap object. but first you have to assign any image , and you may use the button click event, this code will only demonstrate that how to store the drawable image in bitmap Object.

Bitmap contact_pic = BitmapFactory.decodeResource(
                           v.getContext().getResources(),
                           R.drawable.android_logo
                     );

Now you can use this bitmap object, whether you want to store it, or to use it in google maps while drawing a pic on fixed latitude and longitude, or to use some where else

Android refresh current activity

This is a refresh button method, but it works well in my application. in finish() you kill the instances

public void refresh(View view){          //refresh is onClick name given to the button
    onRestart();
}

@Override
protected void onRestart() {

    // TODO Auto-generated method stub
    super.onRestart();
    Intent i = new Intent(lala.this, lala.class);  //your class
    startActivity(i);
    finish();

}

How to set 'X-Frame-Options' on iframe?

you can do it in tomcat instance level config file (web.xml) need to add the 'filter' and filter-mapping' in web.xml config file. this will add the [X-frame-options = DENY] in all the page as it is a global setting.

<filter>
        <filter-name>httpHeaderSecurity</filter-name>
        <filter-class>org.apache.catalina.filters.HttpHeaderSecurityFilter</filter-class>
        <async-supported>true</async-supported>
        <init-param>
          <param-name>antiClickJackingEnabled</param-name>
          <param-value>true</param-value>
        </init-param>
        <init-param>
          <param-name>antiClickJackingOption</param-name>
          <param-value>DENY</param-value>
        </init-param>
    </filter>

  <filter-mapping> 
    <filter-name>httpHeaderSecurity</filter-name> 
    <url-pattern>/*</url-pattern>
</filter-mapping>

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Deserializing JSON to .NET object using Newtonsoft (or LINQ to JSON maybe?)

i craeted an Extionclass for json :

 public static class JsonExtentions
    {
        public static string SerializeToJson(this object SourceObject) { return Newtonsoft.Json.JsonConvert.SerializeObject(SourceObject); }


        public static T JsonToObject<T>(this string JsonString) { return (T)Newtonsoft.Json.JsonConvert.DeserializeObject<T>(JsonString); }
}

Design-Pattern:

 public class Myobject
    {
        public Myobject(){}
        public string prop1 { get; set; }

        public static Myobject  GetObject(string JsonString){return  JsonExtentions.JsonToObject<Myobject>(JsonString);}
        public  string ToJson(string JsonString){return JsonExtentions.SerializeToJson(this);}
    }

Usage:

   Myobject dd= Myobject.GetObject(jsonstring);

                 Console.WriteLine(dd.prop1);

Is there a way to make a DIV unselectable?

Also in IOS if you want to get rid of gray semi-transparent overlays appearing ontouch, add css:

-webkit-tap-highlight-color: rgba(0,0,0,0);
-webkit-touch-callout: none;

Android: How to enable/disable option menu item on button click?

A more modern answer for an old question:

MainActivity.kt

private var myMenuIconEnabled by Delegates.observable(true) { _, old, new ->
    if (new != old) invalidateOptionsMenu()
}

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    findViewById<Button>(R.id.my_button).setOnClickListener { myMenuIconEnabled = false }
}

override fun onCreateOptionsMenu(menu: Menu?): Boolean {
    menuInflater.inflate(R.menu.menu_main_activity, menu)
    return super.onCreateOptionsMenu(menu)
}

override fun onPrepareOptionsMenu(menu: Menu): Boolean {
    menu.findItem(R.id.action_my_action).isEnabled = myMenuIconEnabled
    return super.onPrepareOptionsMenu(menu)
}

menu_main_activity.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
    android:id="@+id/action_my_action"
    android:icon="@drawable/ic_my_icon_24dp"
    app:iconTint="@drawable/menu_item_icon_selector"
    android:title="My title"
    app:showAsAction="always" />
</menu>

menu_item_icon_selector.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="?enabledMenuIconColor" android:state_enabled="true" />
<item android:color="?disabledMenuIconColor" />

attrs.xml

<resources>   
    <attr name="enabledMenuIconColor" format="reference|color"/>
    <attr name="disabledMenuIconColor" format="reference|color"/>
</resources>

styles.xml or themes.xml

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="disabledMenuIconColor">@color/white_30_alpha</item>
    <item name="enabledMenuIconColor">@android:color/white</item>

SQL Server equivalent of MySQL's NOW()?

You can also use CURRENT_TIMESTAMP, if you feel like being more ANSI compliant (though if you're porting code between database vendors, that'll be the least of your worries). It's exactly the same as GetDate() under the covers (see this question for more on that).

There's no ANSI equivalent for GetUTCDate(), however, which is probably the one you should be using if your app operates in more than a single time zone ...

How to use sed to replace only the first occurrence in a file?

A possible solution here might be to tell the compiler to include the header without it being mentioned in the source files. IN GCC there are these options:

   -include file
       Process file as if "#include "file"" appeared as the first line of
       the primary source file.  However, the first directory searched for
       file is the preprocessor's working directory instead of the
       directory containing the main source file.  If not found there, it
       is searched for in the remainder of the "#include "..."" search
       chain as normal.

       If multiple -include options are given, the files are included in
       the order they appear on the command line.

   -imacros file
       Exactly like -include, except that any output produced by scanning
       file is thrown away.  Macros it defines remain defined.  This
       allows you to acquire all the macros from a header without also
       processing its declarations.

       All files specified by -imacros are processed before all files
       specified by -include.

Microsoft's compiler has the /FI (forced include) option.

This feature can be handy for some common header, like platform configuration. The Linux kernel's Makefile uses -include for this.

Android file chooser

EDIT (02 Jan 2012):

I created a small open source Android Library Project that streamlines this process, while also providing a built-in file explorer (in case the user does not have one present). It's extremely simple to use, requiring only a few lines of code.

You can find it at GitHub: aFileChooser.


ORIGINAL

If you want the user to be able to choose any file in the system, you will need to include your own file manager, or advise the user to download one. I believe the best you can do is look for "openable" content in an Intent.createChooser() like this:

private static final int FILE_SELECT_CODE = 0;

private void showFileChooser() {
    Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
    intent.setType("*/*"); 
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    try {
        startActivityForResult(
                Intent.createChooser(intent, "Select a File to Upload"),
                FILE_SELECT_CODE);
    } catch (android.content.ActivityNotFoundException ex) {
        // Potentially direct the user to the Market with a Dialog
        Toast.makeText(this, "Please install a File Manager.", 
                Toast.LENGTH_SHORT).show();
    }
}

You would then listen for the selected file's Uri in onActivityResult() like so:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
            Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);
            Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}

The getPath() method in my FileUtils.java is:

public static String getPath(Context context, Uri uri) throws URISyntaxException {
    if ("content".equalsIgnoreCase(uri.getScheme())) {
        String[] projection = { "_data" };
        Cursor cursor = null;

        try {
            cursor = context.getContentResolver().query(uri, projection, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow("_data");
            if (cursor.moveToFirst()) {
                return cursor.getString(column_index);
            }
        } catch (Exception e) {
            // Eat it
        }
    }
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
} 

sorting dictionary python 3

Python's ordinary dicts cannot be made to provide the keys/elements in any specific order. For that, you could use the OrderedDict type from the collections module. Note that the OrderedDict type merely keeps a record of insertion order. You would have to sort the entries prior to initializing the dictionary if you want subsequent views/iterators to return the elements in order every time. For example:

>>> myDic={10: 'b', 3:'a', 5:'c'}
>>> sorted_list=sorted(myDic.items(), key=lambda x: x[0])
>>> myOrdDic = OrderedDict(sorted_list)
>>> myOrdDic.items()
[(3, 'a'), (5, 'c'), (10, 'b')]
>>> myOrdDic[7] = 'd'
>>> myOrdDic.items()
[(3, 'a'), (5, 'c'), (10, 'b'), (7, 'd')]

If you want to maintain proper ordering for newly added items, you really need to use a different data structure, e.g., a binary tree/heap. This approach of building a sorted list and using it to initialize a new OrderedDict() instance is just woefully inefficient unless your data is completely static.

Edit: So, if the object of sorting the data is merely to print it in order, in a format resembling a python dict object, something like the following should suffice:

def pprint_dict(d):
    strings = []
    for k in sorted(d.iterkeys()):
        strings.append("%d: '%s'" % (k, d[k]))
    return '{' + ', '.join(strings) + '}'

Note that this function is not flexible w/r/t the types of the key, value pairs (i.e., it expects the keys to be integers and the corresponding values to be strings). If you need more flexibility, use something like strings.append("%s: %s" % (repr(k), repr(d[k]))) instead.

Importing CSV with line breaks in Excel 2007

This is for Excel 2016:

Just had the same problem with line breaks inside a csv file with the Excel Wizard.

Afterwards I was trying it with the "New Query" Feature: Data -> New Query -> From File -> From CSV -> Choose the File -> Import -> Load

It was working perfectly and a very quick workaround for all of you that have the same problem.

Get a timestamp in C in microseconds?

But this returns some nonsense value that if I get two timestamps, the second one can be smaller or bigger than the first (second one should always be bigger).

What makes you think that? The value is probably OK. It’s the same situation as with seconds and minutes – when you measure time in minutes and seconds, the number of seconds rolls over to zero when it gets to sixty.

To convert the returned value into a “linear” number you could multiply the number of seconds and add the microseconds. But if I count correctly, one year is about 1e6*60*60*24*360 µsec and that means you’ll need more than 32 bits to store the result:

$ perl -E '$_=1e6*60*60*24*360; say int log($_)/log(2)'
44

That’s probably one of the reasons to split the original returned value into two pieces.

Validating parameters to a Bash script

Old post but I figured i could contribute anyway.

A script is arguably not necessary and with some tolerance to wild cards could be carried out from the command line.

  1. wild anywhere matching. Lets remove any occurrence of sub "folder"

    $ rm -rf ~/*/folder/*
    
  2. Shell iterated. Lets remove the specific pre and post folders with one line

    $ rm -rf ~/foo{1,2,3}/folder/{ab,cd,ef}
    
  3. Shell iterated + var (BASH tested).

    $ var=bar rm -rf ~/foo{1,2,3}/${var}/{ab,cd,ef}
    

UILabel text margin

Maybe later for the party, but the following just works. Just subclass UILabel.

#import "UITagLabel.h"

#define padding UIEdgeInsetsMake(5, 10, 5, 10)

@implementation UITagLabel

- (void)drawTextInRect:(CGRect)rect {
    [super drawTextInRect:UIEdgeInsetsInsetRect(rect, padding)];
}

- (CGSize) intrinsicContentSize {
    CGSize superContentSize = [super intrinsicContentSize];
    CGFloat width = superContentSize.width + padding.left + padding.right;
    CGFloat height = superContentSize.height + padding.top + padding.bottom;
    return CGSizeMake(width, height);
}

- (CGSize) sizeThatFits:(CGSize)size {
    CGSize superSizeThatFits = [super sizeThatFits:size];
    CGFloat width = superSizeThatFits.width + padding.left + padding.right;
    CGFloat height = superSizeThatFits.height + padding.top + padding.bottom;
    return CGSizeMake(width, height);
}

@end

Increase max_execution_time in PHP?

For increasing execution time and file size, you need to mention below values in your .htaccess file. It will work.

php_value upload_max_filesize 80M
php_value post_max_size 80M
php_value max_input_time 18000
php_value max_execution_time 18000

How do I align a label and a textarea?

Just wrap the textarea with the label and set the textarea style to

vertical-align: middle;

Here is some magic for all textareas on the page:)

<style>
    label textarea{
        vertical-align: middle;
    }
</style>

<label>Blah blah blah Description: <textarea>dura bura</textarea></label>

jQuery each loop in table row

Just a recommendation:

I'd recommend using the DOM table implementation, it's very straight forward and easy to use, you really don't need jQuery for this task.

var table = document.getElementById('tblOne');

var rowLength = table.rows.length;

for(var i=0; i<rowLength; i+=1){
  var row = table.rows[i];

  //your code goes here, looping over every row.
  //cells are accessed as easy

  var cellLength = row.cells.length;
  for(var y=0; y<cellLength; y+=1){
    var cell = row.cells[y];

    //do something with every cell here
  }
}

jquery-ui-dialog - How to hook into dialog close event

I have found it!

You can catch the close event using the following code:

 $('div#popup_content').on('dialogclose', function(event) {
     alert('closed');
 });

Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()

How to resolve "must be an instance of string, string given" prior to PHP 7?

As others have already said, type hinting currently only works for object types. But I think the particular error you've triggered might be in preparation of the upcoming string type SplString.

In theory it behaves like a string, but since it is an object would pass the object type verification. Unfortunately it's not yet in PHP 5.3, might come in 5.4, so haven't tested this.

Make .gitignore ignore everything except a few files

I also had some issues with the negation of single files. I was able to commit them, but my IDE (IntelliJ) always complained about ignored files, which are tracked.

git ls-files -i --exclude-from .gitignore

Displayed the two files, which I've excluded this way:

public/
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

In the end, this worked for me:

public/*
!public/typo3conf/
public/typo3conf/*
!public/typo3conf/LocalConfiguration.php
!public/typo3conf/PackageStates.php

The key was the negation of the folder typo3conf/ first.

Also, it seems that the order of the statements doesn't matter. Instead, you need to explicitly negate all subfolders, before you can negate single files in it.

The folder !public/typo3conf/ and the folder contents public/typo3conf/* are two different things for .gitignore.

Great thread! This issue bothered me for a while ;)

How can I strip all punctuation from a string in JavaScript using regex?

For en-US ( American English ) strings this should suffice:

"This., -/ is #! an $ % ^ & * example ;: {} of a = -_ string with `~)() punctuation".replace( /[^a-zA-Z ]/g, '').replace( /\s\s+/g, ' ' )

Be aware that if you support UTF-8 and characters like chinese/russian and all, this will replace them as well, so you really have to specify what you want.

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

How to convert int to float in C?

This Should work Making it Round to 2 Point

       int a=53214
       parseFloat(Math.round(a* 100) / 100).toFixed(2);

How to search a list of tuples in Python

tl;dr

A generator expression is probably the most performant and simple solution to your problem:

l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

result = next((i for i, v in enumerate(l) if v[0] == 53), None)
# 2

Explanation

There are several answers that provide a simple solution to this question with list comprehensions. While these answers are perfectly correct, they are not optimal. Depending on your use case, there may be significant benefits to making a few simple modifications.

The main problem I see with using a list comprehension for this use case is that the entire list will be processed, although you only want to find 1 element.

Python provides a simple construct which is ideal here. It is called the generator expression. Here is an example:

# Our input list, same as before
l = [(1,"juca"),(22,"james"),(53,"xuxa"),(44,"delicia")]

# Call next on our generator expression.
next((i for i, v in enumerate(l) if v[0] == 53), None)

We can expect this method to perform basically the same as list comprehensions in our trivial example, but what if we're working with a larger data set? That's where the advantage of using the generator method comes into play. Rather than constructing a new list, we'll use your existing list as our iterable, and use next() to get the first item from our generator.

Lets look at how these methods perform differently on some larger data sets. These are large lists, made of 10000000 + 1 elements, with our target at the beginning (best) or end (worst). We can verify that both of these lists will perform equally using the following list comprehension:

List comprehensions

"Worst case"

worst_case = ([(False, 'F')] * 10000000) + [(True, 'T')]
print [i for i, v in enumerate(worst_case) if v[0] is True]

# [10000000]
#          2 function calls in 3.885 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.885    3.885    3.885    3.885 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

"Best case"

best_case = [(True, 'T')] + ([(False, 'F')] * 10000000)
print [i for i, v in enumerate(best_case) if v[0] is True]

# [0]
#          2 function calls in 3.864 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    3.864    3.864    3.864    3.864 so_lc.py:1(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

Generator expressions

Here's my hypothesis for generators: we'll see that generators will significantly perform better in the best case, but similarly in the worst case. This performance gain is mostly due to the fact that the generator is evaluated lazily, meaning it will only compute what is required to yield a value.

Worst case

# 10000000
#          5 function calls in 1.733 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         2    1.455    0.727    1.455    0.727 so_lc.py:10(<genexpr>)
#         1    0.278    0.278    1.733    1.733 so_lc.py:9(<module>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    1.455    1.455 {next}

Best case

best_case  = [(True, 'T')] + ([(False, 'F')] * 10000000)
print next((i for i, v in enumerate(best_case) if v[0] == True), None)

# 0
#          5 function calls in 0.316 seconds
#
#    Ordered by: standard name
#
#    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
#         1    0.316    0.316    0.316    0.316 so_lc.py:6(<module>)
#         2    0.000    0.000    0.000    0.000 so_lc.py:7(<genexpr>)
#         1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}
#         1    0.000    0.000    0.000    0.000 {next}

WHAT?! The best case blows away the list comprehensions, but I wasn't expecting the our worst case to outperform the list comprehensions to such an extent. How is that? Frankly, I could only speculate without further research.

Take all of this with a grain of salt, I have not run any robust profiling here, just some very basic testing. This should be sufficient to appreciate that a generator expression is more performant for this type of list searching.

Note that this is all basic, built-in python. We don't need to import anything or use any libraries.

I first saw this technique for searching in the Udacity cs212 course with Peter Norvig.

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

Using Jasmine to spy on a function without an object

My answer differs slightly to @FlavorScape in that I had a single (default export) function in the imported module, I did the following:

import * as functionToTest from 'whatever-lib';

const fooSpy = spyOn(functionToTest, 'default');

Cancel a UIView animation?

When I work with UIStackView animation, besides removeAllAnimations() I need to set some values to initial one because removeAllAnimations() can set them to unpredictable state. I have stackView with view1 and view2 inside, and one view should be visible and one hidden:

public func configureStackView(hideView1: Bool, hideView2: Bool) {
    let oldHideView1 = view1.isHidden
    let oldHideView2 = view2.isHidden
    view1.layer.removeAllAnimations()
    view2.layer.removeAllAnimations()
    view.layer.removeAllAnimations()
    stackView.layer.removeAllAnimations()
    // after stopping animation the values are unpredictable, so set values to old
    view1.isHidden = oldHideView1 //    <- Solution is here
    view2.isHidden = oldHideView2 //    <- Solution is here

    UIView.animate(withDuration: 0.3,
                   delay: 0.0,
                   usingSpringWithDamping: 0.9,
                   initialSpringVelocity: 1,
                   options: [],
                   animations: {
                    view1.isHidden = hideView1
                    view2.isHidden = hideView2
                    stackView.layoutIfNeeded()
    },
                   completion: nil)
}

What is the difference between Trap and Interrupt?

A Trap can be identified as a transfer of control, which is initiated by the programmer. The term Trap is used interchangeably with the term Exception (which is an automatically occurring software interrupt). But some may argue that a trap is simply a special subroutine call. So they fall in to the category of software-invoked interrupts. For example, in 80×86 machines, a programmer can use the int instruction to initiate a trap. Because a trap is always unconditional the control will always be transferred to the subroutine associated with the trap. The exact instruction, which invokes the routine for handling the trap is easily identified because an explicit instruction is used to specify a trap.

Regular expression to limit number of characters to 10

You can use curly braces to control the number of occurrences. For example, this means 0 to 10:

/^[a-z]{0,10}$/

The options are:

  • {3} Exactly 3 occurrences;
  • {6,} At least 6 occurrences;
  • {2,5} 2 to 5 occurrences.

See the regular expression reference.

Your expression had a + after the closing curly brace, hence the error.

How to open select file dialog via js?

For the sake of completeness, Ron van der Heijden's solution in pure JavaScript:

<button onclick="document.querySelector('.inputFile').click();">Select File ...</button>
<input class="inputFile" type="file" style="display: none;">

SQL query to select distinct row with minimum value

SELECT * from room
INNER JOIN
  (
  select DISTINCT hotelNo, MIN(price) MinPrice
  from room
 Group by hotelNo
  ) NewT   
 on room.hotelNo = NewT.hotelNo and room.price = NewT.MinPrice;

"The system cannot find the file C:\ProgramData\Oracle\Java\javapath\java.exe"

For New version of Java JavaPath folder is located

64 bit OS

"C:\Program Files \Common Files\Oracle\Java\javapath\"

X86

"C:\Program Files(x86) \Common Files\Oracle\Java\javapath\"

How to set default value to all keys of a dict object in python?

defaultdict can do something like that for you.

Example:

>>> from collections import defaultdict
>>> d = defaultdict(list)
>>> d
defaultdict(<class 'list'>, {})
>>> d['new'].append(10)
>>> d
defaultdict(<class 'list'>, {'new': [10]})

How can I loop through a List<T> and grab each item?

Just like any other collection. With the addition of the List<T>.ForEach method.

foreach (var item in myMoney)
    Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type);

for (int i = 0; i < myMoney.Count; i++)
    Console.WriteLine("amount is {0}, and type is {1}", myMoney[i].amount, myMoney[i].type);

myMoney.ForEach(item => Console.WriteLine("amount is {0}, and type is {1}", item.amount, item.type));

How can one see content of stack with GDB?

You need to use gdb's memory-display commands. The basic one is x, for examine. There's an example on the linked-to page that uses

gdb> x/4xw $sp

to print "four words (w ) of memory above the stack pointer (here, $sp) in hexadecimal (x)". The quotation is slightly paraphrased.

Make flex items take content width, not width of parent container

In addtion to align-self you can also consider auto margin which will do almost the same thing

_x000D_
_x000D_
.container {_x000D_
  background: red;_x000D_
  height: 200px;_x000D_
  flex-direction: column;_x000D_
  padding: 10px;_x000D_
  display: flex;_x000D_
}_x000D_
a {_x000D_
  margin-right:auto;_x000D_
  padding: 10px 40px;_x000D_
  background: pink;_x000D_
}
_x000D_
<div class="container">_x000D_
  <a href="#">Test</a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

To get an access token: facebook Graph API Explorer

You can customize specific access permissions, basic permissions are included by default.

Save attachments to a folder and rename them

This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"

' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection

    ' This code only strips attachments from mail items.
    ' If objMsg.class=olMail Then
    ' Get the Attachments collection of the item.
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""

    If lngCount > 0 Then

        ' We need to use a count down loop for removing items
        ' from a collection. Otherwise, the loop counter gets
        ' confused and only every other item is removed.

        For i = lngCount To 1 Step -1

            ' Save attachment before deleting from item.
            ' Get the file name.
            strFile = objAttachments.Item(i).FileName

            ' Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            ' Save the attachment as a file.
            objAttachments.Item(i).SaveAsFile strFile

            ' Delete the attachment.
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the message
            'check for html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'Use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        ' Adds the filename string to the message body and save it
        ' Check for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
        Else
            objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
        End If
        objMsg.Save
    End If
Next

ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

Call a VBA Function into a Sub Procedure

Calling a Sub Procedure – 3 Way technique

Once you have a procedure, whether you created it or it is part of the Visual Basic language, you can use it. Using a procedure is also referred to as calling it.

Before calling a procedure, you should first locate the section of code in which you want to use it. To call a simple procedure, type its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"

msgbox strFullName
End Sub

Sub Exercise()
    CreateCustomer
End Sub

Besides using the name of a procedure to call it, you can also precede it with the Call keyword. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    Call CreateCustomer
End Sub

When calling a procedure, without or without the Call keyword, you can optionally type an opening and a closing parentheses on the right side of its name. Here is an example:

Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

Sub Exercise()
    CreateCustomer()
End Sub

Procedures and Access Levels

Like a variable access, the access to a procedure can be controlled by an access level. A procedure can be made private or public. To specify the access level of a procedure, precede it with the Private or the Public keyword. Here is an example:

Private Sub CreateCustomer()
    Dim strFullName As String

    strFullName = "Paul Bertrand Yamaguchi"
End Sub

The rules that were applied to global variables are the same:

Private: If a procedure is made private, it can be called by other procedures of the same module. Procedures of outside modules cannot access such a procedure.

Also, when a procedure is private, its name does not appear in the Macros dialog box

Public: A procedure created as public can be called by procedures of the same module and by procedures of other modules.

Also, if a procedure was created as public, when you access the Macros dialog box, its name appears and you can run it from there

store return json value in input hidden field

If you use the JSON Serializer, you can simply store your object in string format as such

myHiddenText.value = JSON.stringify( myObject );

You can then get the value back with

myObject = JSON.parse( myHiddenText.value );

However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.

Wget output document and headers to STDOUT

It works here:

    $ wget -S -O - http://google.com
HTTP request sent, awaiting response... 
  HTTP/1.1 301 Moved Permanently
  Location: http://www.google.com/
  Content-Type: text/html; charset=UTF-8
  Date: Sat, 25 Aug 2012 10:15:38 GMT
  Expires: Mon, 24 Sep 2012 10:15:38 GMT
  Cache-Control: public, max-age=2592000
  Server: gws
  Content-Length: 219
  X-XSS-Protection: 1; mode=block
  X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29--  http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...

  ...skipped a few more redirections ...

    [<=>                                                                                                                                     ] 0           --.-K/s              
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti 

... skipped ...

perhaps you need to update your wget (~$ wget --version GNU Wget 1.14 built on linux-gnu.)

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Redirect to new Page in AngularJS using $location

If you want to change ng-view you'll have to use the '#'

$window.location.href= "#operation";

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

Android Center text on canvas

In my case, I didn't have to put the text in the middle of a canvas, but in a wheel that spins. Though I had to use this code to succeed:

fun getTextRect(textSize: Float, textPaint: TextPaint, string: String) : PointF {
    val rect = RectF(left, top, right, bottom)
    val rectHeight = Rect()
    val cx = rect.centerX()
    val cy = rect.centerY()

    textPaint.getTextBounds(string, 0, string.length, rectHeight)
    val y = cy + rectHeight.height()/2
    val x = cx - textPaint.measureText(string)/2

    return PointF(x, y)
}

Then I call this method from the View class:

private fun drawText(canvas: Canvas, paint: TextPaint, text: String, string: String) {
    val pointF = getTextRect(paint.textSize, textPaint, string)
    canvas.drawText(text, pointF!!.x, pointF.y, paint)
}

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

Linux Script to check if process is running and act on the result

If you changed awk '{print $1}' to '{ $1=""; print $0}' you will get all processes except for the first as a result. It will start with the field separator (a space generally) but I don't recall killall caring. So:

#! /bin/bash

logfile="/var/oscamlog/oscam1check.log"

case "$(pidof oscam1 | wc -w)" in

0)  echo "oscam1 not running, restarting oscam1:     $(date)" >> $logfile
    /usr/local/bin/oscam1 -b -c /usr/local/etc/oscam1 -t /usr/local/tmp.oscam1 &
    ;;
2)  echo "oscam1 running, all OK:     $(date)" >> $logfile
    ;;
*)  echo "multiple instances of oscam1 running. Stopping & restarting oscam1:     $(date)" >> $logfile
    kill $(pidof oscam1 | awk '{ $1=""; print $0}')
    ;;
esac

It is worth noting that the pidof route seems to work fine for commands that have no spaces, but you would probably want to go back to a ps-based string if you were looking for, say, a python script named myscript that showed up under ps like

root 22415 54.0 0.4 89116 79076 pts/1 S 16:40 0:00 /usr/bin/python /usr/bin/myscript

Just an FYI

Python error "ImportError: No module named"

In my case, I was using sys.path.insert() to import a local module and was getting module not found from a different library. I had to put sys.path.insert() below the imports that reported module not found. I guess the best practice is to put sys.path.insert() at the bottom of your imports.

Difference between Method and Function?

Both are same, there is no difference its just a different term for the same thing in C#.

Method:

In object-oriented programming, a method is a subroutine (or procedure or function) associated with a class.

With respect to Object Oriented programming the term "Method" is used, not functions.

Apply .gitignore on an existing repository already tracking large number of files

Here is one way to “untrack” any files that are would otherwise be ignored under the current set of exclude patterns:

(GIT_INDEX_FILE=some-non-existent-file \
git ls-files --exclude-standard --others --directory --ignored -z) |
xargs -0 git rm --cached -r --ignore-unmatch --

This leaves the files in your working directory but removes them from the index.

The trick used here is to provide a non-existent index file to git ls-files so that it thinks there are no tracked files. The shell code above asks for all the files that would be ignored if the index were empty and then removes them from the actual index with git rm.

After the files have been “untracked”, use git status to verify that nothing important was removed (if so adjust your exclude patterns and use git reset -- path to restore the removed index entry). Then make a new commit that leaves out the “crud”.

The “crud” will still be in any old commits. You can use git filter-branch to produce clean versions of the old commits if you really need a clean history (n.b. using git filter-branch will “rewrite history”, so it should not be undertaken lightly if you have any collaborators that have pulled any of your historical commits after the “crud” was first introduced).

Java Could not reserve enough space for object heap error

I had this problem. I solved it with downloading 64x of the Java. Here is the link: http://javadl.sun.com/webapps/download/AutoDL?BundleId=87443

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

I understand the accepted answer, and have up-voted it but thought I'd dump my laymen's answer here...

Creating a hash

  1. The salt is randomly generated using the function Rfc2898DeriveBytes which generates a hash and a salt. Inputs to Rfc2898DeriveBytes are the password, the size of the salt to generate and the number of hashing iterations to perform. https://msdn.microsoft.com/en-us/library/h83s4e12(v=vs.110).aspx
  2. The salt and the hash are then mashed together(salt first followed by the hash) and encoded as a string (so the salt is encoded in the hash). This encoded hash (which contains the salt and hash) is then stored (typically) in the database against the user.

Checking a password against a hash

To check a password that a user inputs.

  1. The salt is extracted from the stored hashed password.
  2. The salt is used to hash the users input password using an overload of Rfc2898DeriveBytes which takes a salt instead of generating one. https://msdn.microsoft.com/en-us/library/yx129kfs(v=vs.110).aspx
  3. The stored hash and the test hash are then compared.

The Hash

Under the covers the hash is generated using the SHA1 hash function (https://en.wikipedia.org/wiki/SHA-1). This function is iteratively called 1000 times (In the default Identity implementation)

Why is this secure

  • Random salts means that an attacker can’t use a pre-generated table of hashs to try and break passwords. They would need to generate a hash table for every salt. (Assuming here that the hacker has also compromised your salt)
  • If 2 passwords are identical they will have different hashes. (meaning attackers can’t infer ‘common’ passwords)
  • Iteratively calling SHA1 1000 times means that the attacker also needs to do this. The idea being that unless they have time on a supercomputer they won’t have enough resource to brute force the password from the hash. It would massively slow down the time to generate a hash table for a given salt.

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

I solved it by writing

[self.navigationController presentViewController:viewController 
                                        animated:TRUE 
                                      completion:NULL];

Add border-bottom to table row <tr>

No CSS border bottom:

<table>
    <thead>
        <tr>
            <th>Title</th>
        </tr>
        <tr>
            <th>
                <hr>
            </th>
        </tr>
    </thead>
</table>

Does Typescript support the ?. operator? (And, what's it called?)

Edit Nov. 13, 2019!

As of November 5, 2019 TypeScript 3.7 has shipped and it now supports ?. the optional chaining operator !!!

https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-7.html#optional-chaining


For Historical Purposes Only:

Edit: I have updated the answer thanks to fracz comment.

TypeScript 2.0 released !. It's not the same as ?.(Safe Navigator in C#)

See this answer for more details:

https://stackoverflow.com/a/38875179/1057052

This will only tell the compiler that the value is not null or undefined. This will not check if the value is null or undefined.

TypeScript Non-null assertion operator

// Compiled with --strictNullChecks
function validateEntity(e?: Entity) {
    // Throw exception if e is null or invalid entity
}

function processEntity(e?: Entity) {
    validateEntity(e);
    let s = e!.name;  // Assert that e is non-null and access name
}

Class method decorator with self arguments?

A more concise example might be as follows:

#/usr/bin/env python3
from functools import wraps

def wrapper(method):
    @wraps(method)
    def _impl(self, *method_args, **method_kwargs):
        method_output = method(self, *method_args, **method_kwargs)
        return method_output + "!"
    return _impl

class Foo:
    @wrapper
    def bar(self, word):
        return word

f = Foo()
result = f.bar("kitty")
print(result)

Which will print:

kitty!

How to write a cron that will run a script every day at midnight?

Here's a good tutorial on what crontab is and how to use it on Ubuntu. Your crontab line will look something like this:

00 00 * * * ruby path/to/your/script.rb

(00 00 indicates midnight--0 minutes and 0 hours--and the *s mean every day of every month.)

Syntax: 
  mm hh dd mt wd  command

  mm minute 0-59
  hh hour 0-23
  dd day of month 1-31
  mt month 1-12
  wd day of week 0-7 (Sunday = 0 or 7)
  command: what you want to run
  all numeric values can be replaced by * which means all

How can I send large messages with Kafka (over 15MB)?

The idea is to have equal size of message being sent from Kafka Producer to Kafka Broker and then received by Kafka Consumer i.e.

Kafka producer --> Kafka Broker --> Kafka Consumer

Suppose if the requirement is to send 15MB of message, then the Producer, the Broker and the Consumer, all three, needs to be in sync.

Kafka Producer sends 15 MB --> Kafka Broker Allows/Stores 15 MB --> Kafka Consumer receives 15 MB

The setting therefore should be:

a) on Broker:

message.max.bytes=15728640 
replica.fetch.max.bytes=15728640

b) on Consumer:

fetch.message.max.bytes=15728640

Python, add items from txt file into a list

f = open('file.txt','r')

for line in f:
    myNames.append(line.strip()) # We don't want newlines in our list, do we?

Updating Python on Mac

I wanted to achieve the same today. The Mac with Snow Leopard comes with Python 2.6.1 version.

Since multiple Python versions can coexist, I downloaded Python 3.2.3 from: http://www.python.org/getit/

After installation the newer Python will be available under the Application folder and the IDE there uses 3.2.3 version of Python.

From the shell, python3 works with the newer version. That serves the purpose :)

How to get memory usage at runtime using C++?

The existing answers are better for how to get the correct value, but I can at least explain why getrusage isn't working for you.

man 2 getrusage:

The above struct [rusage] was taken from BSD 4.3 Reno. Not all fields are meaningful under Linux. Right now (Linux 2.4, 2.6) only the fields ru_utime, ru_stime, ru_minflt, ru_majflt, and ru_nswap are maintained.

Getting a list of files in a directory with a glob

Swift 5 for cocoa

        // Getting the Contents of a Directory in a Single Batch Operation

        let bundleRoot = Bundle.main.bundlePath
        let url = URL(string: bundleRoot)
        let properties: [URLResourceKey] = [ URLResourceKey.localizedNameKey, URLResourceKey.creationDateKey, URLResourceKey.localizedTypeDescriptionKey]
        if let src = url{
            do {
                let paths = try FileManager.default.contentsOfDirectory(at: src, includingPropertiesForKeys: properties, options: [])

                for p in paths {
                     if p.hasSuffix(".data"){
                           print("File Path is: \(p)")
                     }
                }

            } catch  {  }
        }

Removing object properties with Lodash

This is my solution to deep remove empty properties with Lodash:

const compactDeep = obj => {
    const emptyFields = [];

    function calculateEmpty(prefix, source) {
        _.each(source, (val, key) => {
           if (_.isObject(val) && !_.isEmpty(val)) {
                calculateEmpty(`${prefix}${key}.`, val);
            } else if ((!_.isBoolean(val) && !_.isNumber(val) && !val) || (_.isObject(val) && _.isEmpty(val))) {
                emptyFields.push(`${prefix}${key}`);
            }
        });
    }

    calculateEmpty('', obj);

    return _.omit(obj, emptyFields);
};

How to add hyperlink in JLabel?

Update I've tidied up the SwingLink class further and added more features; an up-to-date copy of it can be found here: https://bitbucket.org/dimo414/jgrep/src/tip/src/grep/SwingLink.java


@McDowell's answer is great, but there's several things that could be improved upon. Notably text other than the hyperlink is clickable and it still looks like a button even though some of the styling has been changed/hidden. While accessibility is important, a coherent UI is as well.

So I put together a class extending JLabel based on McDowell's code. It's self-contained, handles errors properly, and feels more like a link:

public class SwingLink extends JLabel {
  private static final long serialVersionUID = 8273875024682878518L;
  private String text;
  private URI uri;

  public SwingLink(String text, URI uri){
    super();
    setup(text,uri);
  }

  public SwingLink(String text, String uri){
    super();
    setup(text,URI.create(uri));
  }

  public void setup(String t, URI u){
    text = t;
    uri = u;
    setText(text);
    setToolTipText(uri.toString());
    addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        open(uri);
      }
      public void mouseEntered(MouseEvent e) {
        setText(text,false);
      }
      public void mouseExited(MouseEvent e) {
        setText(text,true);
      }
    });
  }

  @Override
  public void setText(String text){
    setText(text,true);
  }

  public void setText(String text, boolean ul){
    String link = ul ? "<u>"+text+"</u>" : text;
    super.setText("<html><span style=\"color: #000099;\">"+
    link+"</span></html>");
    this.text = text;
  }

  public String getRawText(){
    return text;
  }

  private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      Desktop desktop = Desktop.getDesktop();
      try {
        desktop.browse(uri);
      } catch (IOException e) {
        JOptionPane.showMessageDialog(null,
            "Failed to launch the link, your computer is likely misconfigured.",
            "Cannot Launch Link",JOptionPane.WARNING_MESSAGE);
      }
    } else {
      JOptionPane.showMessageDialog(null,
          "Java is not able to launch links on your computer.",
          "Cannot Launch Link", JOptionPane.WARNING_MESSAGE);
    }
  }
}

You could also, for instance, change the link color to purple after being clicked, if that seemed useful. It's all self contained, you simply call:

SwingLink link = new SwingLink("Java", "http://java.sun.com");
mainPanel.add(link);

Calling a Javascript Function from Console

This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].

I wasn't able to run functions from the Developer Tools console, but I then found this

https://developer.mozilla.org/en-US/docs/Tools/Scratchpad

and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.

I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).

https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn

Image 1 (Firefox): http://imgur.com/a/ofkOp

enter image description here

Image 2 (Chrome): http://imgur.com/a/dLnRX

enter image description here

What is a "web service" in plain English?

A web service differs from a web site in that a web service provides information consumable by software rather than humans. As a result, we are usually talking about exposed JSON, XML, or SOAP services.

Web services are a key component in "mashups". Mashups are when information from many websites is automatically aggregated into a new and useful service. For example, there are sites that aggregate Google Maps with information about police reports to give you a graphical representation of crime in your area. Another type of mashup would be to take real stock data provided by another site and combine it with a fake trading application to create a stock-market "game".

Web services are also used to provide news (see RSS), latest items added to a site, information on new products, podcasts, and other great features that make the modern web turn.

Hope this helps!

Angular 5 - Copy to clipboard

The best way to do this in Angular and keep the code simple is to use this project.

https://www.npmjs.com/package/ngx-clipboard

    <fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true" 
    ngxClipboard [cbContent]="target value here" 
    (cbOnSuccess)="copied($event)"></fa-icon>

jQuery - Redirect with post data

why not just use a button instead of submit. clicking the button will let you construct a proper url for your browser to redirect to.

$("#button").click(function() {
   var url = 'site.com/process.php?';
   $('form input').each(function() {
       url += 'key=' + $(this).val() + "&";
   });
   // handle removal of last &.

   window.location.replace(url);
});

React.js: How to append a component on click?

As @Alex McMillan mentioned, use state to dictate what should be rendered in the dom.

In the example below I have an input field and I want to add a second one when the user clicks the button, the onClick event handler calls handleAddSecondInput( ) which changes inputLinkClicked to true. I am using a ternary operator to check for the truthy state, which renders the second input field

class HealthConditions extends React.Component {
  constructor(props) {
    super(props);


    this.state = {
      inputLinkClicked: false
    }
  }

  handleAddSecondInput() {
    this.setState({
      inputLinkClicked: true
    })
  }


  render() {
    return(
      <main id="wrapper" className="" data-reset-cookie-tab>
        <div id="content" role="main">
          <div className="inner-block">

            <H1Heading title="Tell us about any disabilities, illnesses or ongoing conditions"/>

            <InputField label="Name of condition"
              InputType="text"
              InputId="id-condition"
              InputName="condition"
            />

            {
              this.state.inputLinkClicked?

              <InputField label=""
                InputType="text"
                InputId="id-condition2"
                InputName="condition2"
              />

              :

              <div></div>
            }

            <button
              type="button"
              className="make-button-link"
              data-add-button=""
              href="#"
              onClick={this.handleAddSecondInput}
            >
              Add a condition
            </button>

            <FormButton buttonLabel="Next"
              handleSubmit={this.handleSubmit}
              linkto={
                this.state.illnessOrDisability === 'true' ?
                "/404"
                :
                "/add-your-details"
              }
            />

            <BackLink backLink="/add-your-details" />

          </div>
         </div>
      </main>
    );
  }
}

Possible cases for Javascript error: "Expected identifier, string or number"

IE7 is much less forgiving than newer browsers, especially Chrome. I like to use JSLint to find these bugs. It will find these improperly placed commas, among other things. You will probably want to activate the option to ignore improper whitespace.

In addition to improperly placed commas, at this blog in the comments someone reported:

I've been hunting down an error that only said "Expected identifier" only in IE (7). My research led me to this page. After some frustration, it turned out that the problem that I used a reserved word as a function name ("switch"). THe error wasn't clear and it pointed to the wrong line number.

hexadecimal string to byte array in python

Suppose your hex string is something like

>>> hex_string = "deadbeef"

Convert it to a string (Python = 2.7):

>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"

or since Python 2.7 and Python 3.0:

>>> bytes.fromhex(hex_string)  # Python = 3
b'\xde\xad\xbe\xef'

>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')

Note that bytes is an immutable version of bytearray.

Remove accents/diacritics in a string in JavaScript

tested fastest way to remove diacritics from the string that covers almost all characters is this. found highest performance among all the other methods

Diacritics Map

var diacriticsMap = {
'\u0041': 'A','\u24B6': 'A','\uFF21': 'A','\u00C0': 'A','\u00C1': 'A','\u00C2': 'A','\u1EA6': 'A','\u1EA4': 'A','\u1EAA': 'A','\u1EA8': 'A',
'\u00C3': 'A','\u0100': 'A','\u0102': 'A','\u1EB0': 'A','\u1EAE': 'A','\u1EB4': 'A','\u1EB2': 'A','\u0226': 'A','\u01E0': 'A','\u00C4': 'A',
'\u01DE': 'A','\u1EA2': 'A','\u00C5': 'A','\u01FA': 'A','\u01CD': 'A','\u0200': 'A','\u0202': 'A','\u1EA0': 'A','\u1EAC': 'A','\u1EB6': 'A',
'\u1E00': 'A','\u0104': 'A','\u023A': 'A','\u2C6F': 'A',

'\uA732': 'AA',
'\u00C6': 'AE','\u01FC': 'AE','\u01E2': 'AE',
'\uA734': 'AO',
'\uA736': 'AU',
'\uA738': 'AV','\uA73A': 'AV',
'\uA73C': 'AY',
'\u0042': 'B','\u24B7': 'B','\uFF22': 'B','\u1E02': 'B','\u1E04': 'B','\u1E06': 'B','\u0243': 'B','\u0182': 'B','\u0181': 'B',

'\u0043': 'C','\u24B8': 'C','\uFF23': 'C','\u0106': 'C','\u0108': 'C','\u010A': 'C','\u010C': 'C','\u00C7': 'C','\u1E08': 'C','\u0187': 'C',
'\u023B': 'C','\uA73E': 'C',

'\u0044': 'D','\u24B9': 'D','\uFF24': 'D','\u1E0A': 'D','\u010E': 'D','\u1E0C': 'D','\u1E10': 'D','\u1E12': 'D','\u1E0E': 'D','\u0110': 'D',
'\u018B': 'D','\u018A': 'D','\u0189': 'D','\uA779': 'D',

'\u01F1': 'DZ','\u01C4': 'DZ',
'\u01F2': 'Dz','\u01C5': 'Dz',

'\u0045': 'E','\u24BA': 'E','\uFF25': 'E','\u00C8': 'E','\u00C9': 'E','\u00CA': 'E','\u1EC0': 'E','\u1EBE': 'E','\u1EC4': 'E','\u1EC2': 'E',
'\u1EBC': 'E','\u0112': 'E','\u1E14': 'E','\u1E16': 'E','\u0114': 'E','\u0116': 'E','\u00CB': 'E','\u1EBA': 'E','\u011A': 'E','\u0204': 'E',
'\u0206': 'E','\u1EB8': 'E','\u1EC6': 'E','\u0228': 'E','\u1E1C': 'E','\u0118': 'E','\u1E18': 'E','\u1E1A': 'E','\u0190': 'E','\u018E': 'E',

'\u0046': 'F','\u24BB': 'F','\uFF26': 'F','\u1E1E': 'F','\u0191': 'F','\uA77B': 'F',

'\u0047': 'G','\u24BC': 'G','\uFF27': 'G','\u01F4': 'G','\u011C': 'G','\u1E20': 'G','\u011E': 'G','\u0120': 'G','\u01E6': 'G','\u0122': 'G',
'\u01E4': 'G','\u0193': 'G','\uA7A0': 'G','\uA77D': 'G','\uA77E': 'G',

'\u0048': 'H','\u24BD': 'H','\uFF28': 'H','\u0124': 'H','\u1E22': 'H','\u1E26': 'H','\u021E': 'H','\u1E24': 'H','\u1E28': 'H','\u1E2A': 'H',
'\u0126': 'H','\u2C67': 'H','\u2C75': 'H','\uA78D': 'H',

'\u0049': 'I','\u24BE': 'I','\uFF29': 'I','\u00CC': 'I','\u00CD': 'I','\u00CE': 'I','\u0128': 'I','\u012A': 'I','\u012C': 'I','\u0130': 'I',
'\u00CF': 'I','\u1E2E': 'I','\u1EC8': 'I','\u01CF': 'I','\u0208': 'I','\u020A': 'I','\u1ECA': 'I','\u012E': 'I','\u1E2C': 'I','\u0197': 'I',

'\u004A': 'J','\u24BF': 'J','\uFF2A': 'J','\u0134': 'J','\u0248': 'J',

'\u004B': 'K','\u24C0': 'K','\uFF2B': 'K','\u1E30': 'K','\u01E8': 'K','\u1E32': 'K','\u0136': 'K','\u1E34': 'K','\u0198': 'K','\u2C69': 'K',
'\uA740': 'K','\uA742': 'K','\uA744': 'K','\uA7A2': 'K',

'\u004C': 'L','\u24C1': 'L','\uFF2C': 'L','\u013F': 'L','\u0139': 'L','\u013D': 'L','\u1E36': 'L','\u1E38': 'L','\u013B': 'L','\u1E3C': 'L',
'\u1E3A': 'L','\u0141': 'L','\u023D': 'L','\u2C62': 'L','\u2C60': 'L','\uA748': 'L','\uA746': 'L','\uA780': 'L',

'\u01C7': 'LJ',
'\u01C8': 'Lj',
'\u004D': 'M','\u24C2': 'M','\uFF2D': 'M','\u1E3E': 'M','\u1E40': 'M','\u1E42': 'M','\u2C6E': 'M','\u019C': 'M',

'\u004E': 'N','\u24C3': 'N','\uFF2E': 'N','\u01F8': 'N','\u0143': 'N','\u00D1': 'N','\u1E44': 'N','\u0147': 'N','\u1E46': 'N','\u0145': 'N',
'\u1E4A': 'N','\u1E48': 'N','\u0220': 'N','\u019D': 'N','\uA790': 'N','\uA7A4': 'N',

'\u01CA': 'NJ',
'\u01CB': 'Nj',

'\u004F': 'O','\u24C4': 'O','\uFF2F': 'O','\u00D2': 'O','\u00D3': 'O','\u00D4': 'O','\u1ED2': 'O','\u1ED0': 'O','\u1ED6': 'O','\u1ED4': 'O',
'\u00D5': 'O','\u1E4C': 'O','\u022C': 'O','\u1E4E': 'O','\u014C': 'O','\u1E50': 'O','\u1E52': 'O','\u014E': 'O','\u022E': 'O','\u0230': 'O',
'\u00D6': 'O','\u022A': 'O','\u1ECE': 'O','\u0150': 'O','\u01D1': 'O','\u020C': 'O','\u020E': 'O','\u01A0': 'O','\u1EDC': 'O','\u1EDA': 'O',
'\u1EE0': 'O','\u1EDE': 'O','\u1EE2': 'O','\u1ECC': 'O','\u1ED8': 'O','\u01EA': 'O','\u01EC': 'O','\u00D8': 'O','\u01FE': 'O','\u0186': 'O',
'\u019F': 'O','\uA74A': 'O','\uA74C': 'O',

'\u01A2': 'OI',
'\uA74E': 'OO',
'\u0222': 'OU',
'\u0050': 'P','\u24C5': 'P','\uFF30': 'P','\u1E54': 'P','\u1E56': 'P','\u01A4': 'P','\u2C63': 'P','\uA750': 'P','\uA752': 'P','\uA754': 'P',
'\u0051': 'Q','\u24C6': 'Q','\uFF31': 'Q','\uA756': 'Q','\uA758': 'Q','\u024A': 'Q',

'\u0052': 'R','\u24C7': 'R','\uFF32': 'R','\u0154': 'R','\u1E58': 'R','\u0158': 'R','\u0210': 'R','\u0212': 'R','\u1E5A': 'R','\u1E5C': 'R',
'\u0156': 'R','\u1E5E': 'R','\u024C': 'R','\u2C64': 'R','\uA75A': 'R','\uA7A6': 'R','\uA782': 'R',

'\u0053': 'S','\u24C8': 'S','\uFF33': 'S','\u1E9E': 'S','\u015A': 'S','\u1E64': 'S','\u015C': 'S','\u1E60': 'S','\u0160': 'S','\u1E66': 'S',
'\u1E62': 'S','\u1E68': 'S','\u0218': 'S','\u015E': 'S','\u2C7E': 'S','\uA7A8': 'S','\uA784': 'S',

'\u0054': 'T','\u24C9': 'T','\uFF34': 'T','\u1E6A': 'T','\u0164': 'T','\u1E6C': 'T','\u021A': 'T','\u0162': 'T','\u1E70': 'T','\u1E6E': 'T',
'\u0166': 'T','\u01AC': 'T','\u01AE': 'T','\u023E': 'T','\uA786': 'T',

'\uA728': 'TZ',

'\u0055': 'U','\u24CA': 'U','\uFF35': 'U','\u00D9': 'U','\u00DA': 'U','\u00DB': 'U','\u0168': 'U','\u1E78': 'U','\u016A': 'U','\u1E7A': 'U',
'\u016C': 'U','\u00DC': 'U','\u01DB': 'U','\u01D7': 'U','\u01D5': 'U','\u01D9': 'U','\u1EE6': 'U','\u016E': 'U','\u0170': 'U','\u01D3': 'U',
'\u0214': 'U','\u0216': 'U','\u01AF': 'U','\u1EEA': 'U','\u1EE8': 'U','\u1EEE': 'U','\u1EEC': 'U','\u1EF0': 'U','\u1EE4': 'U','\u1E72': 'U',
'\u0172': 'U','\u1E76': 'U','\u1E74': 'U','\u0244': 'U',

'\u0056': 'V','\u24CB': 'V','\uFF36': 'V','\u1E7C': 'V','\u1E7E': 'V','\u01B2': 'V','\uA75E': 'V','\u0245': 'V',
'\uA760': 'VY',
'\u0057': 'W','\u24CC': 'W','\uFF37': 'W','\u1E80': 'W','\u1E82': 'W','\u0174': 'W','\u1E86': 'W','\u1E84': 'W','\u1E88': 'W','\u2C72': 'W',
'\u0058': 'X','\u24CD': 'X','\uFF38': 'X','\u1E8A': 'X','\u1E8C': 'X',

'\u0059': 'Y','\u24CE': 'Y','\uFF39': 'Y','\u1EF2': 'Y','\u00DD': 'Y','\u0176': 'Y','\u1EF8': 'Y','\u0232': 'Y','\u1E8E': 'Y','\u0178': 'Y',
'\u1EF6': 'Y','\u1EF4': 'Y','\u01B3': 'Y','\u024E': 'Y','\u1EFE': 'Y',

'\u005A': 'Z','\u24CF': 'Z','\uFF3A': 'Z','\u0179': 'Z','\u1E90': 'Z','\u017B': 'Z','\u017D': 'Z','\u1E92': 'Z','\u1E94': 'Z','\u01B5': 'Z',
'\u0224': 'Z','\u2C7F': 'Z','\u2C6B': 'Z','\uA762': 'Z',

'\u0061': 'a','\u24D0': 'a','\uFF41': 'a','\u1E9A': 'a','\u00E0': 'a','\u00E1': 'a','\u00E2': 'a','\u1EA7': 'a','\u1EA5': 'a','\u1EAB': 'a',
'\u1EA9': 'a','\u00E3': 'a','\u0101': 'a','\u0103': 'a','\u1EB1': 'a','\u1EAF': 'a','\u1EB5': 'a','\u1EB3': 'a','\u0227': 'a','\u01E1': 'a',
'\u00E4': 'a','\u01DF': 'a','\u1EA3': 'a','\u00E5': 'a','\u01FB': 'a','\u01CE': 'a','\u0201': 'a','\u0203': 'a','\u1EA1': 'a','\u1EAD': 'a',
'\u1EB7': 'a','\u1E01': 'a','\u0105': 'a','\u2C65': 'a','\u0250': 'a',

'\uA733': 'aa',
'\u00E6': 'ae','\u01FD': 'ae','\u01E3': 'ae',
'\uA735': 'ao',
'\uA737': 'au',
'\uA739': 'av','\uA73B': 'av',
'\uA73D': 'ay',
'\u0062': 'b','\u24D1': 'b','\uFF42': 'b','\u1E03': 'b','\u1E05': 'b','\u1E07': 'b','\u0180': 'b','\u0183': 'b','\u0253': 'b',

'\u0063': 'c','\u24D2': 'c','\uFF43': 'c','\u0107': 'c','\u0109': 'c','\u010B': 'c','\u010D': 'c','\u00E7': 'c','\u1E09': 'c','\u0188': 'c',
'\u023C': 'c','\uA73F': 'c','\u2184': 'c',

'\u0064': 'd','\u24D3': 'd','\uFF44': 'd','\u1E0B': 'd','\u010F': 'd','\u1E0D': 'd','\u1E11': 'd','\u1E13': 'd','\u1E0F': 'd','\u0111': 'd',
'\u018C': 'd','\u0256': 'd','\u0257': 'd','\uA77A': 'd',

'\u01F3': 'dz','\u01C6': 'dz',

'\u0065': 'e','\u24D4': 'e','\uFF45': 'e','\u00E8': 'e','\u00E9': 'e','\u00EA': 'e','\u1EC1': 'e','\u1EBF': 'e','\u1EC5': 'e','\u1EC3': 'e',
'\u1EBD': 'e','\u0113': 'e','\u1E15': 'e','\u1E17': 'e','\u0115': 'e','\u0117': 'e','\u00EB': 'e','\u1EBB': 'e','\u011B': 'e','\u0205': 'e',
'\u0207': 'e','\u1EB9': 'e','\u1EC7': 'e','\u0229': 'e','\u1E1D': 'e','\u0119': 'e','\u1E19': 'e','\u1E1B': 'e','\u0247': 'e','\u025B': 'e',
'\u01DD': 'e',

'\u0066': 'f','\u24D5': 'f','\uFF46': 'f','\u1E1F': 'f','\u0192': 'f','\uA77C': 'f',

'\u0067': 'g','\u24D6': 'g','\uFF47': 'g','\u01F5': 'g','\u011D': 'g','\u1E21': 'g','\u011F': 'g','\u0121': 'g','\u01E7': 'g','\u0123': 'g',
'\u01E5': 'g','\u0260': 'g','\uA7A1': 'g','\u1D79': 'g','\uA77F': 'g',

'\u0068': 'h','\u24D7': 'h','\uFF48': 'h','\u0125': 'h','\u1E23': 'h','\u1E27': 'h','\u021F': 'h','\u1E25': 'h','\u1E29': 'h','\u1E2B': 'h',
'\u1E96': 'h','\u0127': 'h','\u2C68': 'h','\u2C76': 'h','\u0265': 'h',

'\u0195': 'hv',

'\u0069': 'i','\u24D8': 'i','\uFF49': 'i','\u00EC': 'i','\u00ED': 'i','\u00EE': 'i','\u0129': 'i','\u012B': 'i','\u012D': 'i','\u00EF': 'i',
'\u1E2F': 'i','\u1EC9': 'i','\u01D0': 'i','\u0209': 'i','\u020B': 'i','\u1ECB': 'i','\u012F': 'i','\u1E2D': 'i','\u0268': 'i','\u0131': 'i',

'\u006A': 'j','\u24D9': 'j','\uFF4A': 'j','\u0135': 'j','\u01F0': 'j','\u0249': 'j',

'\u006B': 'k','\u24DA': 'k','\uFF4B': 'k','\u1E31': 'k','\u01E9': 'k','\u1E33': 'k','\u0137': 'k','\u1E35': 'k','\u0199': 'k','\u2C6A': 'k',
'\uA741': 'k','\uA743': 'k','\uA745': 'k','\uA7A3': 'k',

'\u006C': 'l','\u24DB': 'l','\uFF4C': 'l','\u0140': 'l','\u013A': 'l','\u013E': 'l','\u1E37': 'l','\u1E39': 'l','\u013C': 'l','\u1E3D': 'l',
'\u1E3B': 'l','\u017F': 'l','\u0142': 'l','\u019A': 'l','\u026B': 'l','\u2C61': 'l','\uA749': 'l','\uA781': 'l','\uA747': 'l',

'\u01C9': 'lj',
'\u006D': 'm','\u24DC': 'm','\uFF4D': 'm','\u1E3F': 'm','\u1E41': 'm','\u1E43': 'm','\u0271': 'm','\u026F': 'm',

'\u006E': 'n','\u24DD': 'n','\uFF4E': 'n','\u01F9': 'n','\u0144': 'n','\u00F1': 'n','\u1E45': 'n','\u0148': 'n','\u1E47': 'n','\u0146': 'n',
'\u1E4B': 'n','\u1E49': 'n','\u019E': 'n','\u0272': 'n','\u0149': 'n','\uA791': 'n','\uA7A5': 'n',

'\u01CC': 'nj',

'\u006F': 'o','\u24DE': 'o','\uFF4F': 'o','\u00F2': 'o','\u00F3': 'o','\u00F4': 'o','\u1ED3': 'o','\u1ED1': 'o','\u1ED7': 'o','\u1ED5': 'o',
'\u00F5': 'o','\u1E4D': 'o','\u022D': 'o','\u1E4F': 'o','\u014D': 'o','\u1E51': 'o','\u1E53': 'o','\u014F': 'o','\u022F': 'o','\u0231': 'o',
'\u00F6': 'o','\u022B': 'o','\u1ECF': 'o','\u0151': 'o','\u01D2': 'o','\u020D': 'o','\u020F': 'o','\u01A1': 'o','\u1EDD': 'o','\u1EDB': 'o',
'\u1EE1': 'o','\u1EDF': 'o','\u1EE3': 'o','\u1ECD': 'o','\u1ED9': 'o','\u01EB': 'o','\u01ED': 'o','\u00F8': 'o','\u01FF': 'o','\u0254': 'o',
'\uA74B': 'o','\uA74D': 'o','\u0275': 'o',

'\u01A3': 'oi',
'\u0223': 'ou',
'\uA74F': 'oo',
'\u0070': 'p','\u24DF': 'p','\uFF50': 'p','\u1E55': 'p','\u1E57': 'p','\u01A5': 'p','\u1D7D': 'p','\uA751': 'p','\uA753': 'p','\uA755': 'p',
'\u0071': 'q','\u24E0': 'q','\uFF51': 'q','\u024B': 'q','\uA757': 'q','\uA759': 'q',

'\u0072': 'r','\u24E1': 'r','\uFF52': 'r','\u0155': 'r','\u1E59': 'r','\u0159': 'r','\u0211': 'r','\u0213': 'r','\u1E5B': 'r','\u1E5D': 'r',
'\u0157': 'r','\u1E5F': 'r','\u024D': 'r','\u027D': 'r','\uA75B': 'r','\uA7A7': 'r','\uA783': 'r',

'\u0073': 's','\u24E2': 's','\uFF53': 's','\u00DF': 's','\u015B': 's','\u1E65': 's','\u015D': 's','\u1E61': 's','\u0161': 's','\u1E67': 's',
'\u1E63': 's','\u1E69': 's','\u0219': 's','\u015F': 's','\u023F': 's','\uA7A9': 's','\uA785': 's','\u1E9B': 's',

'\u0074': 't','\u24E3': 't','\uFF54': 't','\u1E6B': 't','\u1E97': 't','\u0165': 't','\u1E6D': 't','\u021B': 't','\u0163': 't','\u1E71': 't',
'\u1E6F': 't','\u0167': 't','\u01AD': 't','\u0288': 't','\u2C66': 't','\uA787': 't',

'\uA729': 'tz',

'\u0075': 'u','\u24E4': 'u','\uFF55': 'u','\u00F9': 'u','\u00FA': 'u','\u00FB': 'u','\u0169': 'u','\u1E79': 'u','\u016B': 'u','\u1E7B': 'u',
'\u016D': 'u','\u00FC': 'u','\u01DC': 'u','\u01D8': 'u','\u01D6': 'u','\u01DA': 'u','\u1EE7': 'u','\u016F': 'u','\u0171': 'u','\u01D4': 'u',
'\u0215': 'u','\u0217': 'u','\u01B0': 'u','\u1EEB': 'u','\u1EE9': 'u','\u1EEF': 'u','\u1EED': 'u','\u1EF1': 'u','\u1EE5': 'u','\u1E73': 'u',
'\u0173': 'u','\u1E77': 'u','\u1E75': 'u','\u0289': 'u',

'\u0076': 'v','\u24E5': 'v','\uFF56': 'v','\u1E7D': 'v','\u1E7F': 'v','\u028B': 'v','\uA75F': 'v','\u028C': 'v',
'\uA761': 'vy',
'\u0077': 'w','\u24E6': 'w','\uFF57': 'w','\u1E81': 'w','\u1E83': 'w','\u0175': 'w','\u1E87': 'w','\u1E85': 'w','\u1E98': 'w','\u1E89': 'w',
'\u2C73': 'w',
'\u0078': 'x','\u24E7': 'x','\uFF58': 'x','\u1E8B': 'x','\u1E8D': 'x',

'\u0079': 'y','\u24E8': 'y','\uFF59': 'y','\u1EF3': 'y','\u00FD': 'y','\u0177': 'y','\u1EF9': 'y','\u0233': 'y','\u1E8F': 'y','\u00FF': 'y',
'\u1EF7': 'y','\u1E99': 'y','\u1EF5': 'y','\u01B4': 'y','\u024F': 'y','\u1EFF': 'y',

'\u007A': 'z','\u24E9': 'z','\uFF5A': 'z','\u017A': 'z','\u1E91': 'z','\u017C': 'z','\u017E': 'z','\u1E93': 'z','\u1E95': 'z','\u01B6': 'z',
'\u0225': 'z','\u0240': 'z','\u2C6C': 'z','\uA763': 'z',
};

Use

function removeDicretics(str) {
    return str.replace(/[^\u0000-\u007E]/g, function (weirdo) {
        return diacriticsMap[weirdo] || weirdo;
    });
}
// Call
var cleanStr = removeDicretics("bullshìt"); // bullshit

How to update SQLAlchemy row entry?

Examples to clarify the important issue in accepted answer's comments

I didn't understand it until I played around with it myself, so I figured there would be others who were confused as well. Say you are working on the user whose id == 6 and whose no_of_logins == 30 when you start.

# 1 (bad)
user.no_of_logins += 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 2 (bad)
user.no_of_logins = user.no_of_logins + 1
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 3 (bad)
setattr(user, 'no_of_logins', user.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = 31 WHERE user.id = 6

# 4 (ok)
user.no_of_logins = User.no_of_logins + 1
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 5 (ok)
setattr(user, 'no_of_logins', User.no_of_logins + 1)
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

The point

By referencing the class instead of the instance, you can get SQLAlchemy to be smarter about incrementing, getting it to happen on the database side instead of the Python side. Doing it within the database is better since it's less vulnerable to data corruption (e.g. two clients attempt to increment at the same time with a net result of only one increment instead of two). I assume it's possible to do the incrementing in Python if you set locks or bump up the isolation level, but why bother if you don't have to?

A caveat

If you are going to increment twice via code that produces SQL like SET no_of_logins = no_of_logins + 1, then you will need to commit or at least flush in between increments, or else you will only get one increment in total:

# 6 (bad)
user.no_of_logins = User.no_of_logins + 1
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

# 7 (ok)
user.no_of_logins = User.no_of_logins + 1
session.flush()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6
user.no_of_logins = User.no_of_logins + 1
session.commit()
# result: UPDATE user SET no_of_logins = no_of_logins + 1 WHERE user.id = 6

Java String split removed empty values

From the documentation of String.split(String regex):

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

So you will have to use the two argument version String.split(String regex, int limit) with a negative value:

String[] split = data.split("\\|",-1);

Doc:

If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.

This will not leave out any empty elements, including the trailing ones.

Hide header in stack navigator React navigation

if you want remove the header from all screen goto app.js and add this code to Stack.Navigator

screenOptions={ { headerShown: false } }

How do I time a method's execution in Java?

I go with the simple answer. Works for me.

long startTime = System.currentTimeMillis();

doReallyLongThing();

long endTime = System.currentTimeMillis();

System.out.println("That took " + (endTime - startTime) + " milliseconds");

It works quite well. The resolution is obviously only to the millisecond, you can do better with System.nanoTime(). There are some limitations to both (operating system schedule slices, etc.) but this works pretty well.

Average across a couple of runs (the more the better) and you'll get a decent idea.

How to create an empty file at the command line in Windows?

Try this:

type NUL > 1.txt

this will definitely create an empty file.

How do I fix the multiple-step OLE DB operation errors in SSIS?

This query should identify columns that are potential problems...

SELECT * 
FROM [source].INFORMATION_SCHEMA.COLUMNS src
    INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst 
        ON dst.COLUMN_NAME = src.COLUMN_NAME
WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH 

afxwin.h file is missing in VC++ Express Edition

Found this post that may help: http://social.msdn.microsoft.com/forums/en-US/Vsexpressvc/thread/7c274008-80eb-42a0-a79b-95f5afbf6528/

Or shortly, afxwin.h is MFC and MFC is not included in the free version of VC++ (Express Edition).

Checking Maven Version

Type the command mvn -version directly in your maven directory, you probably haven't added it to your PATH. Here are explained details of how to add maven to your PATH variable (I guess you use Windows because you are talking about CMD).

gitignore all files of extension in directory

I believe the simplest solution would be to use find. I do not like to have multiple .gitignore hanging around in sub-directories and I prefer to manage a unique, top-level .gitignore. To do so you could simply append the found files to your .gitignore. Supposing that /public/static/ is your project/git home I would use something like:

find . -type f -name *.js | cut -c 3- >> .gitignore

I found that cutting out the ./ at the beginning is often necessary for git to understand which files to avoid. Therefore the cut -c 3-.

Resizing an iframe based on content

I'm implementing ConroyP's frame-in-frame solution to replace a solution based on setting document.domain, but found it to be quite hard determining the height of the iframe's content correctly in different browsers (testing with FF11, Ch17 and IE9 right now).

ConroyP uses:

var height = document.body.scrollHeight;

But that only works on the initial page load. My iframe has dynamic content and I need to resize the iframe on certain events.

What I ended up doing was using different JS properties for the different browsers.

function getDim () {
    var body = document.body,
        html = document.documentElement;

    var bc = body.clientHeight;
    var bo = body.offsetHeight;
    var bs = body.scrollHeight;
    var hc = html.clientHeight;
    var ho = html.offsetHeight;
    var hs = html.scrollHeight;

    var h = Math.max(bc, bo, bs, hc, hs, ho);

    var bd = getBrowserData();

    // Select height property to use depending on browser
    if (bd.isGecko) {
        // FF 11
        h = hc;
    } else if (bd.isChrome) {
        // CH 17
        h = hc;
    } else if (bd.isIE) {
        // IE 9
        h = bs;
    }

    return h;
}

getBrowserData() is browser detect function "inspired" by Ext Core's http://docs.sencha.com/core/source/Ext.html#method-Ext-apply

That worked well for FF and IE but then there were issues with Chrome. One of the was a timing issue, apparently it takes Chrome a while to set/detect the hight of the iframe. And then Chrome also never returned the height of the content in the iframe correctly if the iframe was higher than the content. This wouldn't work with dynamic content when the height is reduced.

To solve this I always set the iframe to a low height before detecting the content's height and then setting the iframe height to it's correct value.

function resize () {
    // Reset the iframes height to a low value.
    // Otherwise Chrome won't detect the content height of the iframe.
    setIframeHeight(150);

    // Delay getting the dimensions because Chrome needs
    // a few moments to get the correct height.
    setTimeout("getDimAndResize()", 100);
}

The code is not optimized, it's from my devel testing :)

Hope someone finds this helpful!

How do I write good/correct package __init__.py files

Your __init__.py should have a docstring.

Although all the functionality is implemented in modules and subpackages, your package docstring is the place to document where to start. For example, consider the python email package. The package documentation is an introduction describing the purpose, background, and how the various components within the package work together. If you automatically generate documentation from docstrings using sphinx or another package, the package docstring is exactly the right place to describe such an introduction.

For any other content, see the excellent answers by firecrow and Alex Martelli.

How do I disable TextBox using JavaScript?

You can use disabled attribute to disable the textbox.

document.getElementById('color').disabled = true;

How come I can't remove the blue textarea border in Twitter Bootstrap?

Your best bet is to right click > inspect the element.

I am using Bootstrap 4 and none of the suggestions worked until I did this.

Once I found where the relevant code was in the inspect window, I copied and pasted the relevant code that was causing the :focus to be outlined blue and changed it accordingly.

This is the code that worked in my css

.btn.focus, .btn:focus
{
outline: 0;
box-shadow: 0 0 0 0;
}

Compare two dates with JavaScript

In order to create dates from free text in Javascript you need to parse it into the Date() object.

You could use Date.parse() which takes free text tries to convert it into a new date but if you have control over the page I would recommend using HTML select boxes instead or a date picker such as the YUI calendar control or the jQuery UI Datepicker.

Once you have a date as other people have pointed out you can use simple arithmetic to subtract the dates and convert it back into a number of days by dividing the number (in seconds) by the number of seconds in a day (60*60*24 = 86400).

How can I get the value of a registry key from within a batch script?

set regVar_LocalPrjPath="LocalPrjPath"
set regVar_Path="HKEY_CURRENT_USER\Software\xyz\KeyPath"

:: ### Retrieve VAR1 ###
FOR /F "skip=2 tokens=2,*" %%A IN ('reg.exe query %regVar_Path% /v %regVar_LocalPrjPath%') DO set "VAR1=%%B"

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

After reading several suggestions here and combining the ideas, for me following changes in /etc/ImageMagick-6/policy.xml were necessary:

<policy domain="coder" rights="read|write" pattern="PDF" />

... rights="none" did not help. ...pattern="LABEL" was not neccessary. Although I do not work with big png files (only ~1 Mb) some changes in memory limits were also necessary:

<policy domain="resource" name="memory" value="2GiB"/>

(instead of 256Mib), and

<policy domain="resource" name="area" value="2GB"/>

(instead of 128 MB)

Absolute vs relative URLs

I'm going to have to disagree with the majority here.

I think the relative URL scheme is "fine" when you want to quickly get something up and running and not think outside the box, particularly if your project is small with few developers (or just yourself).

However, once you start working on big, fatty systems where you switch domains and protocols all the time, I believe that a more elegant approach is in order.

When you compare absolute and relative URLs in essence, Absolute wins. Why? Because it won't ever break. Ever. An absolute URL is exactly what it says it is. The catch is when you have to MAINTAIN your absolute URLs.

The weak approach to absolute URL linking is actually hard coding the entire URL. Not a great idea, and probably the culprit of why people see them as dangerous/evil/annoying to maintain. A better approach is to write yourself an easy to use URL generator. These are easy to write, and can be incredibly powerful- automatically detecting your protocol, easy to config (literally set the url once for the whole app), etc, and it injects your domain all by itself. The nice thing about that: You go on coding using relative URLs, and at run time the application inserts your URLs as full absolutes on the fly. Awesome.

Seeing as how practically all modern sites use some sort of dynamic back-end, it's in the best interest of said site to do it that way. Absolute URLs do more than just make you certain of where they point to- they also can improve SEO performance.

I might add that the argument that absolute URLs is somehow going to change the load time of the page is a myth. If your domain weighs more than a few bytes and you're on a dialup modem in the 1980s, sure. But that's just not the case anymore. https://stackoverflow.com/ is 25 bytes, whereas the "topbar-sprite.png" file that they use for the nav area of the site weighs in at 9+ kb. That means that the additional URL data is .2% of the loaded data in comparison to the sprite file, and that file is not even considered a big performance hit.

That big, unoptimized, full-page background image is much more likely to slow your load times.

An interesting post about why relative URLs shouldn't be used is here: Why relative URLs should be forbidden for web developers

An issue that can arise with relatives, for instance, is that sometimes server mappings (mind you on big, messed up projects) don't line up with file names and the developer may make an assumption about a relative URL that just isn't true. I just saw that today on a project that I'm on and it brought an entire page down.

Or perhaps a developer forgot to switch a pointer and all of a sudden google indexed your entire test environment. Whoops- duplicate content (bad for SEO!).

Absolutes can be dangerous, but when used properly and in a way that can't break your build they are proven to be more reliable. Look at the article above which gives a bunch of reasons why the Wordpress url generator is super awesome.

:)

Importing a long list of constants to a Python file

Sure, you can put your constants into a separate module. For example:

const.py:

A = 12
B = 'abc'
C = 1.2

main.py:

import const

print const.A, const.B, const.C

Note that as declared above, A, B and C are variables, i.e. can be changed at run time.

How to test if a string is basically an integer in quotes using Ruby

"12".match(/^(\d)+$/)      # true
"1.2".match(/^(\d)+$/)     # false
"dfs2".match(/^(\d)+$/)    # false
"13422".match(/^(\d)+$/)   # true

Save ArrayList to SharedPreferences

This method is used to store/save array list:-

 public static void saveSharedPreferencesLogList(Context context, List<String> collageList) {
            SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
            SharedPreferences.Editor prefsEditor = mPrefs.edit();
            Gson gson = new Gson();
            String json = gson.toJson(collageList);
            prefsEditor.putString("myJson", json);
            prefsEditor.commit();
        }

This method is used to retrieve array list:-

public static List<String> loadSharedPreferencesLogList(Context context) {
        List<String> savedCollage = new ArrayList<String>();
        SharedPreferences mPrefs = context.getSharedPreferences("PhotoCollage", context.MODE_PRIVATE);
        Gson gson = new Gson();
        String json = mPrefs.getString("myJson", "");
        if (json.isEmpty()) {
            savedCollage = new ArrayList<String>();
        } else {
            Type type = new TypeToken<List<String>>() {
            }.getType();
            savedCollage = gson.fromJson(json, type);
        }

        return savedCollage;
    }

Extracting date from a string in Python

If you know the position of the date object in the string (for example in a log file), you can use .split()[index] to extract the date without fully knowing the format.

For example:

>>> string = 'monkey 2010-07-10 love banana'
>>> date = string.split()[1]
>>> date
'2010-07-10'

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

Make sure you add following line in your top level build.gradle and that should fix it.

maven { url 'https://maven.google.com' }

I got exact same error you mentioned above, once I added this entry everything worked.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

In addition to accepted answer, if you're using Entity Migrations for updating database, you should add this line at the beggining of the Up() function in your migration file:

Sql("alter table dbo.CompanyTransactions drop constraint [df__CompanyTr__Creat__0cdae408];");

You can find the constraint name in the error at nuget packet manager console which starts with FK_dbo.

How to initialize/instantiate a custom UIView class with a XIB file in Swift

And this is the answer of Frederik on Swift 3.0

/*
 Usage:
 - make your CustomeView class and inherit from this one
 - in your Xib file make the file owner is your CustomeView class
 - *Important* the root view in your Xib file must be of type UIView
 - link all outlets to the file owner
 */
@IBDesignable
class NibLoadingView: UIView {

    @IBOutlet weak var view: UIView!

    override init(frame: CGRect) {
        super.init(frame: frame)
        nibSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        nibSetup()
    }

    private func nibSetup() {
        backgroundColor = .clear

        view = loadViewFromNib()
        view.frame = bounds
        view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        view.translatesAutoresizingMaskIntoConstraints = true

        addSubview(view)
    }

    private func loadViewFromNib() -> UIView {
        let bundle = Bundle(for: type(of: self))
        let nib = UINib(nibName: String(describing: type(of: self)), bundle: bundle)
        let nibView = nib.instantiate(withOwner: self, options: nil).first as! UIView

        return nibView
    }
}

Python csv string to array

https://docs.python.org/2/library/csv.html?highlight=csv#csv.reader

csvfile can be any object which supports the iterator protocol and returns a string each time its next() method is called

Thus, a StringIO.StringIO(), str.splitlines() or even a generator are all good.

Set element focus in angular way

About this solution, we could just create a directive and attach it to the DOM element that has to get the focus when a given condition is satisfied. By following this approach we avoid coupling controller to DOM element ID's.

Sample code directive:

gbndirectives.directive('focusOnCondition', ['$timeout',
    function ($timeout) {
        var checkDirectivePrerequisites = function (attrs) {
          if (!attrs.focusOnCondition && attrs.focusOnCondition != "") {
                throw "FocusOnCondition missing attribute to evaluate";
          }
        }

        return {            
            restrict: "A",
            link: function (scope, element, attrs, ctrls) {
                checkDirectivePrerequisites(attrs);

                scope.$watch(attrs.focusOnCondition, function (currentValue, lastValue) {
                    if(currentValue == true) {
                        $timeout(function () {                                                
                            element.focus();
                        });
                    }
                });
            }
        };
    }
]);

A possible usage

.controller('Ctrl', function($scope) {
   $scope.myCondition = false;
   // you can just add this to a radiobutton click value
   // or just watch for a value to change...
   $scope.doSomething = function(newMyConditionValue) {
       // do something awesome
       $scope.myCondition = newMyConditionValue;
  };

});

HTML

<input focus-on-condition="myCondition">

Limiting number of displayed results when using ngRepeat

Another (and I think better) way to achieve this is to actually intercept the data. limitTo is okay but what if you're limiting to 10 when your array actually contains thousands?

When calling my service I simply did this:

TaskService.getTasks(function(data){
    $scope.tasks = data.slice(0,10);
});

This limits what is sent to the view, so should be much better for performance than doing this on the front-end.

How To Accept a File POST

I used Mike Wasson's answer before I updated all the NuGets in my webapi mvc4 project. Once I did, I had to re-write the file upload action:

    public Task<HttpResponseMessage> Upload(int id)
    {
        HttpRequestMessage request = this.Request;
        if (!request.Content.IsMimeMultipartContent())
        {
            throw new HttpResponseException(new HttpResponseMessage(HttpStatusCode.UnsupportedMediaType));
        }

        string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads");
        var provider = new MultipartFormDataStreamProvider(root);

        var task = request.Content.ReadAsMultipartAsync(provider).
            ContinueWith<HttpResponseMessage>(o =>
            {
                FileInfo finfo = new FileInfo(provider.FileData.First().LocalFileName);

                string guid = Guid.NewGuid().ToString();

                File.Move(finfo.FullName, Path.Combine(root, guid + "_" + provider.FileData.First().Headers.ContentDisposition.FileName.Replace("\"", "")));

                return new HttpResponseMessage()
                {
                    Content = new StringContent("File uploaded.")
                };
            }
        );
        return task;
    }

Apparently BodyPartFileNames is no longer available within the MultipartFormDataStreamProvider.

What is a plain English explanation of "Big O" notation?

Big O is a means to represent the upper bounds of any function. We generally use it for expressing the upper bounds of a function that tells the running time of an Algorithm.

Ex : f(n) = 2(n^2) +3n be a function representing the running time of a hypothetical algorithm, Big-O notation essentially gives the upper limit for this function which is O(n^2)

This notation basically tells us that, for any input 'n' the running time won't be greater than the value expressed by Big-O notation.

Also, agree with all the above detailed answers. Hope this helps !!

How to get all keys with their values in redis

Yes, you can do print all keys using below bash script,

for key in $(redis-cli -p 6379 keys \*);
  do echo "Key : '$key'" 
     redis-cli -p 6379 GET $key;
done

where, 6379 is a port on which redis is running.

Download data url file

There are several solutions but they depend on HTML5 and haven't been implemented completely in some browsers yet. Examples below were tested in Chrome and Firefox (partly works).

  1. Canvas example with save to file support. Just set your document.location.href to the data URI.
  2. Anchor download example. It uses <a href="your-data-uri" download="filename.txt"> to specify file name.

Set width of a "Position: fixed" div relative to parent div

Use this CSS:

#container {
    width: 400px;
    border: 1px solid red;
}

#fixed {
    position: fixed;
    width: inherit;
    border: 1px solid green;
}

The #fixed element will inherit it's parent width, so it will be 100% of that.

Are multiple `.gitignore`s frowned on?

Pro single

  • Easy to find.

  • Hunting down exclusion rules can be quite difficult if I have multiple gitignore, at several levels in the repo.

  • With multiple files, you also typically wind up with a fair bit of duplication.

Pro multiple

  • Scopes "knowledge" to the part of the file tree where it is needed.

  • Since Git only tracks files, an empty .gitignore is the only way to commit an "empty" directory.

    (And before Git 1.8, the only way to exclude a pattern like my/**.example was to create my/.gitignore in with the pattern **.foo. This reason doesn't apply now, as you can do /my/**/*.example.)


I much prefer a single file, where I can find all the exclusions. I've never missed per-directory .svn, and I won't miss per-directory .gitignore either.

That said, multiple gitignores are quite common. If you do use them, at least be consistent in their use to make them reasonable to work with. For example, you may put them in directories only one level from the root.

What is a practical, real world example of the Linked List?

If you think about it, a "Link" is simply a way of identifying a "Next", "Previous", "Child" or "Parent" relationship among data instances. So, among real world applications you'll find a broad variety of applications. Think of a simple List (e.g. Grocery List) for basic Linked Lists. But consider too the uses to which we can place Graphs (plotting distances between cities on a map, interactions among species in biology) or Trees (hierarchies in an organization or data in an index of a database for two very diverse examples).

Are list-comprehensions and functional functions faster than "for loops"?

I wrote a simple script that test the speed and this is what I found out. Actually for loop was fastest in my case. That really suprised me, check out bellow (was calculating sum of squares).

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        i = i**2
        a += i
    return a

def square_sum3(numbers):
    sqrt = lambda x: x**2
    return sum(map(sqrt, numbers))

def square_sum4(numbers):
    return(sum([int(i)**2 for i in numbers]))


time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.302000 #Reduce
0:00:00.144000 #For loop
0:00:00.318000 #Map
0:00:00.390000 #List comprehension

Validate phone number using angular js

Use ng-pattern, in this example you can validate a simple patern with 10 numbers, when the patern is not matched ,the message is show and the button is disabled.

 <form  name="phoneNumber">

        <label for="numCell" class="text-strong">Phone number</label>

        <input id="numCell" type="text" name="inputCelular"  ng-model="phoneNumber" 
            class="form-control" required  ng-pattern="/^[0-9]{10,10}$/"></input>
        <div class="alert-warning" ng-show="phoneNumber.inputCelular.$error.pattern">
            <p> write a phone number</p>
        </div>

    <button id="button"  class="btn btn-success" click-once ng-disabled="!phoneNumber.$valid" ng-click="callDigitaliza()">Buscar</button>

Also you can use another complex patern like

^+?\d{1,3}?[- .]?(?(?:\d{2,3}))?[- .]?\d\d\d[- .]?\d\d\d\d$

, for more complex phone numbers

How to set the first option on a select box using jQuery?

I created a new option in the select tag that has a value of empty string ("") and used:

$("form.query").find('select#topic').val("");

Combine Multiple child rows into one row MYSQL

Joe Edel's answer to himself is actually the right approach to resolve the pivot problem.

Basically the idea is to list out the columns in the base table firstly, and then any number of options.value from the joint option table. Just left join the same option table multiple times in order to get all the options.

What needs to be done by the programming language is to build this query dynamically according to a list of options needs to be queried.

PHP, getting variable from another php-file

using include 'page1.php' in second page is one option but it can generate warnings and errors of undefined variables.
Three methods by which you can use variables of one php file in another php file:

  • use session to pass variable from one page to another
    method:
    first you have to start the session in both the files using php command

    sesssion_start();
    then in first file consider you have one variable
    $x='var1';

    now assign value of $x to a session variable using this:
    $_SESSION['var']=$x;
    now getting value in any another php file:
    $y=$_SESSION['var'];//$y is any declared variable

  • using get method and getting variables on clicking a link
    method

    <a href="page2.php?variable1=value1&variable2=value2">clickme</a>
    getting values in page2.php file by $_GET function:
    $x=$_GET['variable1'];//value1 be stored in $x
    $y=$_GET['variable2'];//vale2 be stored in $y

  • if you want to pass variable value using button then u can use it by following method:

    $x='value1'
    <input type="submit" name='btn1' value='.$x.'/>
    in second php
    $var=$_POST['btn1'];

When do I need to use a semicolon vs a slash in Oracle SQL?

I wanted to clarify some more use between the ; and the /

In SQLPLUS:

  1. ; means "terminate the current statement, execute it and store it to the SQLPLUS buffer"
  2. <newline> after a D.M.L. (SELECT, UPDATE, INSERT,...) statement or some types of D.D.L (Creating Tables and Views) statements (that contain no ;), it means, store the statement to the buffer but do not run it.
  3. / after entering a statement into the buffer (with a blank <newline>) means "run the D.M.L. or D.D.L. or PL/SQL in the buffer.
  4. RUN or R is a sqlsplus command to show/output the SQL in the buffer and run it. It will not terminate a SQL Statement.
  5. / during the entering of a D.M.L. or D.D.L. or PL/SQL means "terminate the current statement, execute it and store it to the SQLPLUS buffer"

NOTE: Because ; are used for PL/SQL to end a statement ; cannot be used by SQLPLUS to mean "terminate the current statement, execute it and store it to the SQLPLUS buffer" because we want the whole PL/SQL block to be completely in the buffer, then execute it. PL/SQL blocks must end with:

END;
/

how to compare the Java Byte[] array?

You can also use org.apache.commons.lang.ArrayUtils.isEquals()

Select a row from html table and send values onclick of a button

$("#table tr").click(function(){
   $(this).addClass('selected').siblings().removeClass('selected');    
   var value=$(this).find('td:first').html();
   alert(value);    
});

$('.ok').on('click', function(e){
    alert($("#table tr.selected td:first").html());
});

Demo:

http://jsfiddle.net/65JPw/2/

CSS container div not getting height

The best and the most bulletproof solution is to add ::before and ::after pseudoelements to the container. So if you have for example a list like:

<ul class="clearfix">
    <li></li>
    <li></li>
    <li></li>
</ul>

And every elements in the list has float:left property, then you should add to your css:

.clearfix::after, .clearfix::before {
     content: '';
     clear: both;
     display: table;
}

Or you could try display:inline-block; property, then you don't need to add any clearfix.

How to run only one unit test class using Gradle

You should try to add asteriks (*) to the end.

gradle test --tests "com.a.b.c.*"

How to check if a string contains a substring in Bash

The generic needle haystack example is following with variables

#!/bin/bash

needle="a_needle"
haystack="a_needle another_needle a_third_needle"
if [[ $haystack == *"$needle"* ]]; then
    echo "needle found"
else
    echo "needle NOT found"
fi

How get an apostrophe in a string in javascript

You can use double quotes instead of single quotes:

theAnchorText = "I'm home";

Alternatively, escape the apostrophe:

theAnchorText = 'I\'m home';

The backslash tells JavaScript (this has nothing to do with jQuery, by the way) that the next character should be interpreted as "special". In this case, an apostrophe after a backslash means to use a literal apostrophe but not to end the string.

There are also other characters you can put after a backslash to indicate other special characters. For example, you can use \n for a new line, or \t for a tab.

java.lang.NoClassDefFoundError: com/sun/mail/util/MailLogger for JUnit test case for Java mail

It happens also if your code is expecting Java Mail 1.4 and your jars are Java Mail 1.3. Happened to me when upgraded Pentaho Kettle

Regards

pthread function from a class

C++ : How to pass class member function to pthread_create()?

http://thispointer.com/c-how-to-pass-class-member-function-to-pthread_create/

typedef void * (*THREADFUNCPTR)(void *);

class C { 
   // ...
   void *print(void *) { cout << "Hello"; }
}

pthread_create(&threadId, NULL, (THREADFUNCPTR) &C::print, NULL);

How can I enter latitude and longitude in Google Maps?

You don't need to convert to decimal; you can also enter 46 23S, 115 22E. You can add seconds after the minutes, also separated by a space.

How to use OUTPUT parameter in Stored Procedure

The SQL in your SP is wrong. You probably want

Select @code = RecItemCode from Receipt where RecTransaction = @id

In your statement, you are not setting @code, you are trying to use it for the value of RecItemCode. This would explain your NullReferenceException when you try to use the output parameter, because a value is never assigned to it and you're getting a default null.

The other issue is that your SQL statement if rewritten as

Select @code = RecItemCode, RecUsername from Receipt where RecTransaction = @id

It is mixing variable assignment and data retrieval. This highlights a couple of points. If you need the data that is driving @code in addition to other parts of the data, forget the output parameter and just select the data.

Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

If you just need the code, use the first SQL statement I showed you. On the offhand chance you actually need the output and the data, use two different statements

Select @code = RecItemCode from Receipt where RecTransaction = @id
Select RecItemCode, RecUsername from Receipt where RecTransaction = @id

This should assign your value to the output parameter as well as return two columns of data in a row. However, this strikes me as terribly redundant.

If you write your SP as I have shown at the very top, simply invoke cmd.ExecuteNonQuery(); and then read the output parameter value.


Another issue with your SP and code. In your SP, you have declared @code as varchar. In your code, you specify the parameter type as Int. Either change your SP or your code to make the types consistent.


Also note: If all you are doing is returning a single value, there's another way to do it that does not involve output parameters at all. You could write

 Select RecItemCode from Receipt where RecTransaction = @id

And then use object obj = cmd.ExecuteScalar(); to get the result, no need for an output parameter in the SP or in your code.

How to get the jQuery $.ajax error response text?

If you're not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == 'error'

Using logging in multiple modules

There are several answers. i ended up with a similar yet different solution that makes sense to me, maybe it will make sense to you as well. My main objective was to be able to pass logs to handlers by their level (debug level logs to the console, warnings and above to files):

from flask import Flask
import logging
from logging.handlers import RotatingFileHandler

app = Flask(__name__)

# make default logger output everything to the console
logging.basicConfig(level=logging.DEBUG)

rotating_file_handler = RotatingFileHandler(filename="logs.log")
rotating_file_handler.setLevel(logging.INFO)

app.logger.addHandler(rotating_file_handler)

created a nice util file named logger.py:

import logging

def get_logger(name):
    return logging.getLogger("flask.app." + name)

the flask.app is a hardcoded value in flask. the application logger is always starting with flask.app as its the module's name.

now, in each module, i'm able to use it in the following mode:

from logger import get_logger
logger = get_logger(__name__)

logger.info("new log")

This will create a new log for "app.flask.MODULE_NAME" with minimum effort.

Set a default font for whole iOS app?

Developing from Hugues BR answer but using method swizzling I've arrived to a solution that is successfully changing all the fonts to a desired font in my app.

An approach with Dynamic Type should be what you should look for on iOS 7. The following solution is not using Dynamic Type.


Notes:

  • the code below, in its presented state, was never submitted to Apple approval;
  • there is a shorter version of it that passed Apple submission, that is without the - initWithCoder: override. However that won't cover all the cases;
  • the following code is present in a class I use to set the style of my app which is included by my AppDelegate class thus being available everywhere and to all UIFont instances;
  • I'm using Zapfino here just to make the changes much more visible;
  • any improvement you may find to this code is welcome.

This solution uses two different methods to achieve the final result. The first is override the UIFont class methods + systemFontWithSize: and similar with ones that use my alternatives (here I use "Zapfino" to leave no doubts that the replacement was successful).

The other method is to override - initWithCoder: method on UIFont to replace any occurrence of CTFontRegularUsage and similar by my alternatives. This last method was necessary because I've found that UILabel objects encoded in NIB files don't check the + systemFontWithSize: methods to get their system font and instead encode them as UICTFontDescriptor objects. I've tried to override - awakeAfterUsingCoder: but somehow it was getting called for every encoded object in my storyboard and causing crashes. Overriding - awakeFromNib wouldn't allow me to read the NSCoder object.

#import <objc/runtime.h>

NSString *const FORegularFontName = @"Zapfino";
NSString *const FOBoldFontName = @"Zapfino";
NSString *const FOItalicFontName = @"Zapfino";

#pragma mark - UIFont category
@implementation UIFont (CustomFonts)

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
+ (void)replaceClassSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
    Method originalMethod = class_getClassMethod(self, originalSelector);
    Method modifiedMethod = class_getClassMethod(self, modifiedSelector);
    method_exchangeImplementations(originalMethod, modifiedMethod);
}

+ (void)replaceInstanceSelector:(SEL)originalSelector withSelector:(SEL)modifiedSelector {
    Method originalDecoderMethod = class_getInstanceMethod(self, originalSelector);
    Method modifiedDecoderMethod = class_getInstanceMethod(self, modifiedSelector);
    method_exchangeImplementations(originalDecoderMethod, modifiedDecoderMethod);
}

+ (UIFont *)regularFontWithSize:(CGFloat)size
{
    return [UIFont fontWithName:FORegularFontName size:size];
}

+ (UIFont *)boldFontWithSize:(CGFloat)size
{
    return [UIFont fontWithName:FOBoldFontName size:size];
}

+ (UIFont *)italicFontOfSize:(CGFloat)fontSize
{
    return [UIFont fontWithName:FOItalicFontName size:fontSize];
}

- (id)initCustomWithCoder:(NSCoder *)aDecoder {
    BOOL result = [aDecoder containsValueForKey:@"UIFontDescriptor"];

    if (result) {
        UIFontDescriptor *descriptor = [aDecoder decodeObjectForKey:@"UIFontDescriptor"];

        NSString *fontName;
        if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontRegularUsage"]) {
            fontName = FORegularFontName;
        }
        else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontEmphasizedUsage"]) {
            fontName = FOBoldFontName;
        }
        else if ([descriptor.fontAttributes[@"NSCTFontUIUsageAttribute"] isEqualToString:@"CTFontObliqueUsage"]) {
            fontName = FOItalicFontName;
        }
        else {
            fontName = descriptor.fontAttributes[@"NSFontNameAttribute"];
        }

        return [UIFont fontWithName:fontName size:descriptor.pointSize];
    }

    self = [self initCustomWithCoder:aDecoder];

    return self;
}

+ (void)load
{
    [self replaceClassSelector:@selector(systemFontOfSize:) withSelector:@selector(regularFontWithSize:)];
    [self replaceClassSelector:@selector(boldSystemFontOfSize:) withSelector:@selector(boldFontWithSize:)];
    [self replaceClassSelector:@selector(italicSystemFontOfSize:) withSelector:@selector(italicFontOfSize:)];

    [self replaceInstanceSelector:@selector(initWithCoder:) withSelector:@selector(initCustomWithCoder:)];
}
#pragma clang diagnostic pop

@end

How to make rpm auto install dependencies

Process of generating RPM from source file: 1) download source file with.gz extention. 2) install rpm-build and rpmdevtools from yum install. (rpmbuild folder will be generated...SPECS,SOURCES,RPMS.. folders will should be generated inside the rpmbuild folder). 3) copy the source code.gz to SOURCES folder.(rpmbuild/SOURCES) 4)Untar the tar ball by using the following command. go to SOURCES folder :rpmbuild/SOURCES where tar file is present. command: e.g tar -xvzf httpd-2.22.tar.gz httpd-2.22 folder will be generated in the same path. Check if apr and apr-util and there in httpd-2.22/srclib folder. If apr and apr-util doesnt exist download latest version from apache site ,untar it and put it inside httpd-2.22/srclib folder. Also make sure you have pcre install in your system .

5)go to extracted folder and then type below command: ./configure --prefix=/usr/local/apache2 --with-included-apr --enable-proxy --enable-proxy-balancer --with-mpm=worker --enable-mods-static=all 6)run below command once the configure is successful: make 7)after successfull execution od make command run: checkinstall in tha same folder. (if you dont have checkinstall software please download latest version from site) Also checkinstall software has bug which can be solved by following way::::: locate checkinstallrc and then replace TRANSLATE = 1 to TRANSLATE=0 using vim command. Also check for exclude package: EXCLUDE="/selinux" 8)checkinstall will ask for option (type R if you want tp build rpm for source file) 9)Done .rpm file will be built in RPMS folder inside rpmbuild/RPMS file... ALL the BEST ....

Regards, Prerana

How to copy std::string into std::vector<char>?

std::vector has a constructor that takes two iterators. You can use that:

std::string str = "hello";
std::vector<char> data(str.begin(), str.end());

If you already have a vector and want to add the characters at the end, you need a back inserter:

std::string str = "hello";
std::vector<char> data = /* ... */;
std::copy(str.begin(), str.end(), std::back_inserter(data));

How to define custom configuration variables in rails

I just wanted to update this for the latest cool stuff in Rails 4.2, you can now do this inside any of your config/**/*.rb files:

config.x.whatever.you.want = 42

...and this will be available in your app as:

Rails.configuration.x.whatever.you.want

See more here: http://guides.rubyonrails.org/configuring.html#custom-configuration

Python: Convert timedelta to int in a dataframe

The Series class has a pandas.Series.dt accessor object with several useful datetime attributes, including dt.days. Access this attribute via:

timedelta_series.dt.days

You can also get the seconds and microseconds attributes in the same way.

Execute another jar in a Java program

Hope this helps:

public class JarExecutor {

private BufferedReader error;
private BufferedReader op;
private int exitVal;

public void executeJar(String jarFilePath, List<String> args) throws JarExecutorException {
    // Create run arguments for the

    final List<String> actualArgs = new ArrayList<String>();
    actualArgs.add(0, "java");
    actualArgs.add(1, "-jar");
    actualArgs.add(2, jarFilePath);
    actualArgs.addAll(args);
    try {
        final Runtime re = Runtime.getRuntime();
        //final Process command = re.exec(cmdString, args.toArray(new String[0]));
        final Process command = re.exec(actualArgs.toArray(new String[0]));
        this.error = new BufferedReader(new InputStreamReader(command.getErrorStream()));
        this.op = new BufferedReader(new InputStreamReader(command.getInputStream()));
        // Wait for the application to Finish
        command.waitFor();
        this.exitVal = command.exitValue();
        if (this.exitVal != 0) {
            throw new IOException("Failed to execure jar, " + this.getExecutionLog());
        }

    } catch (final IOException | InterruptedException e) {
        throw new JarExecutorException(e);
    }
}

public String getExecutionLog() {
    String error = "";
    String line;
    try {
        while((line = this.error.readLine()) != null) {
            error = error + "\n" + line;
        }
    } catch (final IOException e) {
    }
    String output = "";
    try {
        while((line = this.op.readLine()) != null) {
            output = output + "\n" + line;
        }
    } catch (final IOException e) {
    }
    try {
        this.error.close();
        this.op.close();
    } catch (final IOException e) {
    }
    return "exitVal: " + this.exitVal + ", error: " + error + ", output: " + output;
}
}

CSS property to pad text inside of div

I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:

<div id="container">
    <p id="text">Find Agents</p>
</div>

All you need to do is apply this CSS:

#text {
    padding: 10px;
}

Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/

Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:

.container * {
    padding: 5px 10px;
}

Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/

How to create directory automatically on SD card

Just completing the Vijay's post...


Manifest

uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"

Function

public static boolean createDirIfNotExists(String path) {
    boolean ret = true;

    File file = new File(Environment.getExternalStorageDirectory(), path);
    if (!file.exists()) {
        if (!file.mkdirs()) {
            Log.e("TravellerLog :: ", "Problem creating Image folder");
            ret = false;
        }
    }
    return ret;
}

Usage

createDirIfNotExists("mydir/"); //Create a directory sdcard/mydir
createDirIfNotExists("mydir/myfile") //Create a directory and a file in sdcard/mydir/myfile.txt

You could check for errors

if(createDirIfNotExists("mydir/")){
     //Directory Created Success
}
else{
    //Error
}

Press Keyboard keys using a batch file

Just to be clear, you are wanting to launch a program from a batch file and then have the batch file press keys (in your example, the arrow keys) within that launched program?

If that is the case, you aren't going to be able to do that with simply a ".bat" file as the launched would stop the batch file from continuing until it terminated--

My first recommendation would be to use something like AutoHotkey or AutoIt if possible, simply because they both have active forums where you'd find countless examples of people launching applications and sending key presses not to mention tools to simply "record" what you want to do. However you said this is a work computer and you may not be able to load a 3rd party program.. but you aren't without options.

You can use Windows Scripting Host from something like a .vbs file to launch a program and send keys to that process. If you're running a version of Windows that includes PowerShell 2.0 (Windows XP with Service Pack 3, Windows Vista with Service Pack 1, Windows 7, etc.) you can use Windows Scripting Host as a COM object from your PS script or use VB's Intereact class.

The specifics of how to do it are outside the scope of this answer but you can find numerous examples using the methods I just described by searching on SO or Google.

edit: Just to help you get started you can look here:

  1. Automate tasks with Windows Script Host's SendKeys method
  2. A useful thread about SendKeys

How to get the correct range to set the value to a cell?

Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')

Explanation :

Setting value in a cell in spreadsheet to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in sheet which is open currently and to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)

SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)

SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);

These are constants, you must define them yourself

SHEET_ID

SHEET_NAME

POSITION

VALUE

RANGE

By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.

HTML how to clear input using javascript?

For me this is the best way:

<form id="myForm">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset form">
</form>

<script>
function myFunction() {
    document.getElementById("myForm").reset();
}
</script>

How to work offline with TFS

See this reference for information on how to bind/unbind your solution or project from source control. NOTE: this doesn't apply if you are using GIT and may not apply to versions later than VS2008.

Quoting from the reference:

To disconnect a solution or project from source control

  1. In Visual Studio, open Solution Explorer and select the item(s) to disconnect.

  2. On the File menu, click Source Control, then Change Source Control.

  3. In the Change Source Control dialog box, click Disconnect.

  4. Click OK.

An attempt was made to access a socket in a way forbidden by its access permissions

Just Restart-Service hns can change the port occupier by Hyper-V. It might release the port you need.

What is the meaning of # in URL and how can I use that?

It specifies an "Anchor", or a position on the page, and allows you to "jump" or "scroll" to that position on the page.

Please see this page for more details.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

Search and destroy (or move cautiously) any my.ini files (windows or program files), which is affecting the mysql service failure. also check port 3306 is used by using either netstat or portqry tool. this should help. Also if there is a file system issue you can run check disk.

How to set all elements of an array to zero or any same value?

You could use memset, if you sure about the length.

memset(ptr, 0x00, length)

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

Why do I need to override the equals and hashCode methods in Java?

Both the methods are defined in Object class. And both are in its simplest implementation. So when you need you want add some more implementation to these methods then you have override in your class.

For Ex: equals() method in object only checks its equality on the reference. So if you need compare its state as well then you can override that as it is done in String class.

HTML meta tag for content language

You asked for differences, but you can’t quite compare those two.

Note that <meta http-equiv="content-language" content="es"> is obsolete and removed in HTML5. It was used to specify “a document-wide default language”, with its http-equiv attribute making it a pragma directive (which simulates an HTTP response header like Content-Language that hasn’t been sent from the server, since it cannot override a real one).

Regarding <meta name="language" content="Spanish">, you hardly find any reliable information. It’s non-standard and was probably invented as a SEO makeshift.

However, the HTML5 W3C Recommendation encourages authors to use the lang attribute on html root elements (attribute values must be valid BCP 47 language tags):

<!DOCTYPE html>
<html lang="es-ES">
    <head>
        …

Anyway, if you want to specify the content language to instruct search engine robots, you should consider this quote from Google Search Console Help on multilingual sites:

Google uses only the visible content of your page to determine its language. We don’t use any code-level language information such as lang attributes.

How to define the basic HTTP authentication using cURL correctly?

as header

AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)

curl \
  --header "Content-Type: application/json" \
  --header "Authorization: Basic $AUTH" \
  --request POST \
  --data  '{"key1":"value1", "key2":"value2"}' \
  https://example.com/

How to launch an application from a browser?

I achieved the same thing using a local web server and PHP. I used a script containing shell_exec to launch an application locally.

Alternatively, you could do something like this:

<a href="file://C:/Windows/notepad.exe">Notepad</a>

What's the difference between a Future and a Promise?

For client code, Promise is for observing or attaching callback when a result is available, whereas Future is to wait for result and then continue. Theoretically anything which is possible to do with futures what can done with promises, but due to the style difference, the resultant API for promises in different languages make chaining easier.

How to ping a server only once from within a batch file?

I know why, you are using the file name "ping" and you are using the code "ping", it just keeps trying to run itself because its selected directory in where that file is, if you want it to actually ping, put this before the ping command: "cd C:\Windows\system32", the actual file that pings the server is in there!

Specifying a custom DateTime format when serializing with Json.Net

public static JsonSerializerSettings JsonSerializer { get; set; } = new JsonSerializerSettings()
        {
            DateFormatString= "yyyy-MM-dd HH:mm:ss",
            NullValueHandling = NullValueHandling.Ignore,
            ContractResolver = new LowercaseContractResolver()
        };

Hello,

I'm using this property when I need set JsonSerializerSettings

How can I undo a mysql statement that I just executed?

in case you do not only need to undo your last query (although your question actually only points on that, I know) and therefore if a transaction might not help you out, you need to implement a workaround for this:

copy the original data before commiting your query and write it back on demand based on the unique id that must be the same in both tables; your rollback-table (with the copies of the unchanged data) and your actual table (containing the data that should be "undone" than). for databases having many tables, one single "rollback-table" containing structured dumps/copies of the original data would be better to use then one for each actual table. it would contain the name of the actual table, the unique id of the row, and in a third field the content in any desired format that represents the data structure and values clearly (e.g. XML). based on the first two fields this third one would be parsed and written back to the actual table. a fourth field with a timestamp would help cleaning up this rollback-table.

since there is no real undo in SQL-dialects despite "rollback" in a transaction (please correct me if I'm wrong - maybe there now is one), this is the only way, I guess, and you have to write the code for it on your own.

Create a symbolic link of directory in Ubuntu

That's what ln is documented to do when the target already exists and is a directory. If you want /etc/nginx to be a symlink rather than contain a symlink, you had better not create it as a directory first!

Center div on the middle of screen

The best way to align a div in center both horizontally and vertically will be

HTML

<div></div>

CSS:

div {
    position: absolute;
    top:0;
    bottom: 0;
    left: 0;
    right: 0;
    margin: auto;
    width: 100px;
    height: 100px;
    background-color: blue;
}

FIDDLE

How do I install the OpenSSL libraries on Ubuntu?

You want to install the development package, which is libssl-dev:

sudo apt-get install libssl-dev

How can I pass a parameter to a setTimeout() callback?

I think you want:

setTimeout("postinsql(" + topicId + ")", 4000);

How can I get the source code of a Python function?

Please mind that the accepted answers work only if the lambda is given on a separate line. If you pass it in as an argument to a function and would like to retrieve the code of the lambda as object, the problem gets a bit tricky since inspect will give you the whole line.

For example, consider a file test.py:

import inspect

def main():
    x, f = 3, lambda a: a + 1
    print(inspect.getsource(f))

if __name__ == "__main__":
    main()

Executing it gives you (mind the indention!):

    x, f = 3, lambda a: a + 1

To retrieve the source code of the lambda, your best bet, in my opinion, is to re-parse the whole source file (by using f.__code__.co_filename) and match the lambda AST node by the line number and its context.

We had to do precisely that in our design-by-contract library icontract since we had to parse the lambda functions we pass in as arguments to decorators. It is too much code to paste here, so have a look at the implementation of this function.

html div onclick event

Try out this example, the onclick is still called from your HTML, and event bubbling is stopped.

<div class="expandable-panel-heading">
<h2>
  <a id="ancherComplaint" href="#addComplaint" onclick="markActiveLink(this);event.stopPropagation();">ABC</a>
</h2>
</div>

http://jsfiddle.net/NXML7/1/

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

No you can't since IEnumerable is an interface.

You should be able to create an empty instance of most non-interface types which implement IEnumerable, e.g.:-

IEnumerable<object> a = new object[] { };

or

IEnumerable<object> a = new List<object>();

A beginner's guide to SQL database design

It's been a while since I read it (so, I'm not sure how much of it is still relevant), but my recollection is that Joe Celko's SQL for Smarties book provides a lot of info on writing elegant, effective, and efficient queries.

How to calculate sum of a formula field in crystal Reports?

(Assuming you are looking at the reports in the Crystal Report Designer...)

Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:

  • Make a summary field: Right-click on the desired formula field in your detail section and choose "Insert Summary". Choose "sum" from the drop-down box and verify that the correct account grouping is selected, then click OK. You will then have a simple sum field in your group footer section.
  • Make a running total field: Click on the "Insert" menu and choose "Running Total Field..."*** Click on the New button and give your new running total field a name. Choose your formula field under "Field to summarize" and choose "sum" under "Type of Summary". Here you can also change when the total is evaluated and reset, leave these at their default if you're wanting a sum on each record. You can also use a formula to determine when a certain field should be counted in the total. (Evaluate: Use Formula)

Showing line numbers in IPython/Jupyter Notebooks

1.press esc to enter the command mode 2.perss l(it L in lowcase) to show the line number

Oracle Error ORA-06512

The variable pCv is of type VARCHAR2 so when you concat the insert you aren't putting it inside single quotes:

 EXECUTE IMMEDIATE  'INSERT INTO M'||pNum||'GR (CV, SUP, IDM'||pNum||') VALUES('''||pCv||''', '||pSup||', '||pIdM||')';

Additionally the error ORA-06512 raise when you are trying to insert a value too large in a column. Check the definiton of the table M_pNum_GR and the parameters that you are sending. Just for clarify if you try to insert the value 100 on a NUMERIC(2) field the error will raise.

What's a decent SFTP command-line client for windows?

WinSCP has the command line functionality:

c:\>winscp.exe /console /script=example.txt

where scripting is done in example.txt.

See http://winscp.net/eng/docs/guide_automation

Refer to http://winscp.net/eng/docs/guide_automation_advanced for details on how to use a scripting language such as Windows command interpreter/php/perl.

FileZilla does have a command line but it is limited to only opening the GUI with a pre-defined server that is in the Site Manager.

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

npm check and update package if needed

To check if any module in a project is 'old':

npm outdated

'outdated' will check every module defined in package.json and see if there is a newer version in the NPM registry.

For example, say xml2js 0.2.6 (located in node_modules in the current project) is outdated because a newer version exists (0.2.7). You would see:

[email protected] node_modules/xml2js current=0.2.6

To update all dependencies, if you are confident this is desirable:

npm update

Or, to update a single dependency such as xml2js:

npm update xml2js