Programs & Examples On #Odbc sql server driver

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

How to extract IP Address in Spring MVC Controller get call?

I use such method to do this

public class HttpReqRespUtils {

    private static final String[] IP_HEADER_CANDIDATES = {
        "X-Forwarded-For",
        "Proxy-Client-IP",
        "WL-Proxy-Client-IP",
        "HTTP_X_FORWARDED_FOR",
        "HTTP_X_FORWARDED",
        "HTTP_X_CLUSTER_CLIENT_IP",
        "HTTP_CLIENT_IP",
        "HTTP_FORWARDED_FOR",
        "HTTP_FORWARDED",
        "HTTP_VIA",
        "REMOTE_ADDR"
    };

    public static String getClientIpAddressIfServletRequestExist() {

        if (RequestContextHolder.getRequestAttributes() == null) {
            return "0.0.0.0";
        }

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        for (String header: IP_HEADER_CANDIDATES) {
            String ipList = request.getHeader(header);
            if (ipList != null && ipList.length() != 0 && !"unknown".equalsIgnoreCase(ipList)) {
                String ip = ipList.split(",")[0];
                return ip;
            }
        }

        return request.getRemoteAddr();
    }
}

Delete duplicate elements from an array

As elements are yet ordered, you don't have to build a map, there's a fast solution :

var newarr = [arr[0]];
for (var i=1; i<arr.length; i++) {
   if (arr[i]!=arr[i-1]) newarr.push(arr[i]);
}

If your array weren't sorted, you would use a map :

var newarr = (function(arr){
  var m = {}, newarr = []
  for (var i=0; i<arr.length; i++) {
    var v = arr[i];
    if (!m[v]) {
      newarr.push(v);
      m[v]=true;
    }
  }
  return newarr;
})(arr);

Note that this is, by far, much faster than the accepted answer.

Writing Unicode text to a text file?

In case of writing in python3

>>> a = u'bats\u00E0'
>>> print a
batsà
>>> f = open("/tmp/test", "w")
>>> f.write(a)
>>> f.close()
>>> data = open("/tmp/test").read()
>>> data
'batsà'

In case of writing in python2:

>>> a = u'bats\u00E0'
>>> f = open("/tmp/test", "w")
>>> f.write(a)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)

To avoid this error you would have to encode it to bytes using codecs "utf-8" like this:

>>> f.write(a.encode("utf-8"))
>>> f.close()

and decode the data while reading using the codecs "utf-8":

>>> data = open("/tmp/test").read()
>>> data.decode("utf-8")
u'bats\xe0'

And also if you try to execute print on this string it will automatically decode using the "utf-8" codecs like this

>>> print a
batsà

rails generate model

For me what happened was that I generated the app with rails new rails new chapter_2 but the RVM --default had rails 4.0.2 gem, but my chapter_2 project use a new gemset with rails 3.2.16.

So when I ran

rails generate scaffold User name:string email:string

the console showed

Usage:
   rails new APP_PATH [options]

So I fixed the RVM and the gemset with the rails 3.2.16 gem , and then generated the app again then I executed

 rails generate scaffold User name:string email:string

and it worked

How to make <input type="file"/> accept only these types?

Use accept attribute with the MIME_type as values

<input type="file" accept="image/gif, image/jpeg" />

Open Excel file for reading with VBA without display

Open them from a new instance of Excel.

Sub Test()

    Dim xl As Excel.Application
    Set xl = CreateObject("Excel.Application")

    Dim w As Workbook
    Set w = xl.Workbooks.Add()

    MsgBox "Not visible yet..."
    xl.Visible = True

    w.Close False
    Set xl = Nothing

End Sub

You need to remember to clean up after you're done.

Defining a variable with or without export

Although not explicitly mentioned in the discussion, it is NOT necessary to use export when spawning a subshell from inside bash since all the variables are copied into the child process.

How do you set CMAKE_C_COMPILER and CMAKE_CXX_COMPILER for building Assimp for iOS?

SOLUTIONS

  1. Sometimes the project is created before installing g++. So install g++ first and then recreate your project. This worked for me.
  2. Paste the following line in CMakeCache.txt: CMAKE_CXX_COMPILER:FILEPATH=/usr/bin/c++

Note the path to g++ depends on OS. I have used my fedora path obtained using which g++

Concatenate rows of two dataframes in pandas

Thanks to @EdChum I was struggling with same problem especially when indexes do not match. Unfortunatly in pandas guide this case is missed (when you for example delete some rows)

import pandas as pd
t=pd.DataFrame()
t['a']=[1,2,3,4]
t=t.loc[t['a']>1] #now index starts from 1

u=pd.DataFrame()
u['b']=[1,2,3] #index starts from 0

#option 1
#keep index of t
u.index = t.index 

#option 2
#index of t starts from 0
t.reset_index(drop=True, inplace=True)

#now concat will keep number of rows 
r=pd.concat([t,u], axis=1)

How do you share constants in NodeJS modules?

From previous project experience, this is a good way:

In the constants.js:

// constants.js

'use strict';

let constants = {
    key1: "value1",
    key2: "value2",
    key3: {
        subkey1: "subvalue1",
        subkey2: "subvalue2"
    }
};

module.exports =
        Object.freeze(constants); // freeze prevents changes by users

In main.js (or app.js, etc.), use it as below:

// main.js

let constants = require('./constants');

console.log(constants.key1);

console.dir(constants.key3);

Extracting specific columns from a data frame

You can use with :

with(df, data.frame(A, B, E))

Test if something is not undefined in JavaScript

typeof:

var foo;
if (typeof foo == "undefined"){
  //do stuff
}

How to draw checkbox or tick mark in GitHub Markdown table?

I used &#9744; (☐) for [ ] and &#9745; (☑) for [x] and it works for marked.js which says it is compatible with Github markdown. I based my solution on answers for this question. See also this informative answer.

Update: I should have mentioned that when you do it this way, you do not need the <ul>, e.g:

| Unchecked | Checked |
| --------- | ------- |
| &#9744;   | &#9745; |

CSS Change List Item Background Color with Class

This is an issue of selector specificity. (The selector .selected is less specific than ul.nav li.)

To fix, use as much specificity in the overriding rule as in the original:

ul.nav li {
 background-color:blue;
}
ul.nav li.selected {
 background-color:red;
}

You might also consider nixing the ul, unless there will be other .navs. So:

.nav li {
 background-color:blue;
}
.nav li.selected {
 background-color:red;
}

That's a bit cleaner, less typing, and fewer bits.

Calling remove in foreach loop in Java

The java design of the "enhanced for loop" was to not expose the iterator to code, but the only way to safely remove an item is to access the iterator. So in this case you have to do it old school:

 for(Iterator<String> i = names.iterator(); i.hasNext();) {
       String name = i.next();
       //Do Something
       i.remove();
 }

If in the real code the enhanced for loop is really worth it, then you could add the items to a temporary collection and call removeAll on the list after the loop.

EDIT (re addendum): No, changing the list in any way outside the iterator.remove() method while iterating will cause problems. The only way around this is to use a CopyOnWriteArrayList, but that is really intended for concurrency issues.

The cheapest (in terms of lines of code) way to remove duplicates is to dump the list into a LinkedHashSet (and then back into a List if you need). This preserves insertion order while removing duplicates.

Python Save to file

You can use this function:

def saveListToFile(listname, pathtosave):
    file1 = open(pathtosave,"w") 
    for i in listname:
        file1.writelines("{}\n".format(i))    
    file1.close() 

# to save:
saveListToFile(list, path)

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

You can set HorizontalAlignment to Left, set your MaxWidth and then bind Width to the ActualWidth of the parent element:

<Page
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  <StackPanel Name="Container">   
    <TextBox Background="Azure" 
    Width="{Binding ElementName=Container,Path=ActualWidth}"
    Text="Hello" HorizontalAlignment="Left" MaxWidth="200" />
  </StackPanel>
</Page>

How to detect scroll direction

Existing Solution

There could be 3 solution from this posting and other stackoverflow article.

Solution 1

    var lastScrollTop = 0;
    $(window).on('scroll', function() {
        st = $(this).scrollTop();
        if(st < lastScrollTop) {
            console.log('up 1');
        }
        else {
            console.log('down 1');
        }
        lastScrollTop = st;
    });

Solution 2

    $('body').on('DOMMouseScroll', function(e){
        if(e.originalEvent.detail < 0) {
            console.log('up 2');
        }
        else {
            console.log('down 2');
        }
    });

Solution 3

    $('body').on('mousewheel', function(e){
        if(e.originalEvent.wheelDelta > 0) {
            console.log('up 3');
        }
        else {
            console.log('down 3');
        }
    });

Multi Browser Test

I couldn't tested it on Safari

chrome 42 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

Firefox 37 (Win 7)

  • Solution 1
    • Up : 20 events per 1 scroll
    • Down : 20 events per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : 1 event per 1 scroll
  • Solution 3
    • Up : Not working
    • Down : Not working

IE 11 (Win 8)

  • Solution 1
    • Up : 10 events per 1 scroll (side effect : down scroll occured at last)
    • Down : 10 events per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : Not working
    • Down : 1 event per 1 scroll

IE 10 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

IE 9 (Win 7)

  • Solution 1
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

IE 8 (Win 7)

  • Solution 1
    • Up : 2 events per 1 scroll (side effect : down scroll occured at last)
    • Down : 2~4 events per 1 scroll
  • Soltion 2
    • Up : Not working
    • Down : Not working
  • Solution 3
    • Up : 1 event per 1 scroll
    • Down : 1 event per 1 scroll

Combined Solution

I checked that side effect from IE 11 and IE 8 is come from if else statement. So, I replaced it with if else if statement as following.

From the multi browser test, I decided to use Solution 3 for common browsers and Solution 1 for firefox and IE 11.

I referred this answer to detect IE 11.

    // Detect IE version
    var iev=0;
    var ieold = (/MSIE (\d+\.\d+);/.test(navigator.userAgent));
    var trident = !!navigator.userAgent.match(/Trident\/7.0/);
    var rv=navigator.userAgent.indexOf("rv:11.0");

    if (ieold) iev=new Number(RegExp.$1);
    if (navigator.appVersion.indexOf("MSIE 10") != -1) iev=10;
    if (trident&&rv!=-1) iev=11;

    // Firefox or IE 11
    if(typeof InstallTrigger !== 'undefined' || iev == 11) {
        var lastScrollTop = 0;
        $(window).on('scroll', function() {
            st = $(this).scrollTop();
            if(st < lastScrollTop) {
                console.log('Up');
            }
            else if(st > lastScrollTop) {
                console.log('Down');
            }
            lastScrollTop = st;
        });
    }
    // Other browsers
    else {
        $('body').on('mousewheel', function(e){
            if(e.originalEvent.wheelDelta > 0) {
                console.log('Up');
            }
            else if(e.originalEvent.wheelDelta < 0) {
                console.log('Down');
            }
        });
    }

MySQL wait_timeout Variable - GLOBAL vs SESSION

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

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

SHOW SESSION VARIABLES LIKE "%wait%";

Result: 300

Similarly, at any time, if you did

mysql> SET session wait_timeout=300;

You'd get

mysql> SHOW SESSION VARIABLES LIKE 'wait_timeout';

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

Resize image in PHP

private function getTempImage($url, $tempName){
  $tempPath = 'tempFilePath' . $tempName . '.png';
  $source_image = imagecreatefrompng($url); // check type depending on your necessities.
  $source_imagex = imagesx($source_image);
  $source_imagey = imagesy($source_image);
  $dest_imagex = 861; // My default value
  $dest_imagey = 96;  // My default value

  $dest_image = imagecreatetruecolor($dest_imagex, $dest_imagey);

  imagecopyresampled($dest_image, $source_image, 0, 0, 0, 0, $dest_imagex, $dest_imagey, $source_imagex, $source_imagey);

  imagejpeg($dest_image, $tempPath, 100);

  return $tempPath;

}

This is an adapted solution based on this great explanation. This guy made a step by step explanation. Hope all enjoy it.

Autocompletion of @author in Intellij

You can work around that via a Live Template. Go to Settings -> Live Template, click the "Add"-Button (green plus on the right).

In the "Abbreviation" field, enter the string that should activate the template (e.g. @a), and in the "Template Text" area enter the string to complete (e.g. @author - My Name). Set the "Applicable context" to Java (Comments only maybe) and set a key to complete (on the right).

I tested it and it works fine, however IntelliJ seems to prefer the inbuild templates, so "@a + Tab" only completes "author". Setting the completion key to Space worked however.

To change the user name that is automatically inserted via the File Templates (when creating a class for example), can be changed by adding

-Duser.name=Your name

to the idea.exe.vmoptions or idea64.exe.vmoptions (depending on your version) in the IntelliJ/bin directory.

enter image description here

Restart IntelliJ

How to return the current timestamp with Moment.js?

Get by Location:

moment.locale('pt-br')
return moment().format('DD/MM/YYYY HH:mm:ss')

Java escape JSON String?

org.json.simple.JSONObject.escape() escapes quotes,, /, \r, \n, \b, \f, \t and other control characters.

import org.json.simple.JSONValue;
JSONValue.escape("test string");

Add pom.xml when using maven

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <scope>test</scope>
</dependency>

Relative imports for the billionth time

@BrenBarn's answer says it all, but if you're like me it might take a while to understand. Here's my case and how @BrenBarn's answer applies to it, perhaps it will help you.

The case

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
    moduleA.py

Using our familiar example, and add to it that moduleX.py has a relative import to ..moduleA. Given that I tried writing a test script in the subpackage1 directory that imported moduleX, but then got the dreaded error described by the OP.

Solution

Move test script to the same level as package and import package.subpackage1.moduleX

Explanation

As explained, relative imports are made relative to the current name. When my test script imports moduleX from the same directory, then module name inside moduleX is moduleX. When it encounters a relative import the interpreter can't back up the package hierarchy because it's already at the top

When I import moduleX from above, then name inside moduleX is package.subpackage1.moduleX and the relative import can be found

How to get a Fragment to remove itself, i.e. its equivalent of finish()?

If you need to popback from the fourth fragment in the backstack history to the first, use tags!!!

When you add the first fragment you should use something like this:

getFragmentManager.beginTransaction.addToBackStack("A").add(R.id.container, FragmentA).commit() 

or

getFragmentManager.beginTransaction.addToBackStack("A").replace(R.id.container, FragmentA).commit()

And when you want to show Fragments B,C and D you use this:

getFragmentManager.beginTransaction.addToBackStack("B").replace(R.id.container, FragmentB, "B").commit()

and other letters....

To return to Fragment A, just call popBackStack(0, "A"), yes, use the flag that you specified when you add it, and note that it must be the same flag in the command addToBackStack(), not the one used in command replace or add.

You're welcome ;)

How to obtain the start time and end time of a day?

tl;dr

LocalDate                       // Represents an entire day, without time-of-day and without time zone.
.now(                           // Capture the current date.
    ZoneId.of( "Asia/Tokyo" )   // Returns a `ZoneId` object.
)                               // Returns a `LocalDate` object.
.atStartOfDay(                  // Determines the first moment of the day as seen on that date in that time zone. Not all days start at 00:00!
    ZoneId.of( "Asia/Tokyo" ) 
)                               // Returns a `ZonedDateTime` object.

Start of day

Get the full length of the today as seen in a time zone.

Using Half-Open approach, where the beginning is inclusive while the ending is exclusive. This approach solves the flaw in your code that fails to account for the very last second of the day.

ZoneId zoneId = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( zoneId  ) ;

ZonedDateTime zdtStart = today.atStartOfDay( zoneId ) ;
ZonedDateTime zdtStop = today.plusDays( 1 ).atStartOfDay( zoneId ) ;

zdtStart.toString() = 2020-01-30T00:00+01:00[Africa/Tunis]

zdtStop.toString() = 2020-01-31T00:00+01:00[Africa/Tunis]

See the same moments in UTC.

Instant start = zdtStart.toInstant() ;
Instant stop = zdtStop.toInstant() ;

start.toString() = 2020-01-29T23:00:00Z

stop.toString() = 2020-01-30T23:00:00Z

If you want the entire day of a date as seen in UTC rather than in a time zone, use OffsetDateTime.

LocalDate today = LocalDate.now( ZoneOffset.UTC  ) ;

OffsetDateTime odtStart = today.atTime( OffsetTime.MIN ) ;
OffsetDateTime odtStop = today.plusDays( 1 ).atTime( OffsetTime.MIN ) ;

odtStart.toString() = 2020-01-30T00:00+18:00

odtStop.toString() = 2020-01-31T00:00+18:00

These OffsetDateTime objects will already be in UTC, but you can call toInstant if you need such objects which are always in UTC by definition.

Instant start = odtStart.toInstant() ;
Instant stop = odtStop.toInstant() ;

start.toString() = 2020-01-29T06:00:00Z

stop.toString() = 2020-01-30T06:00:00Z

Tip: You may be interested in adding the ThreeTen-Extra library to your project to use its Interval class to represent this pair of Instant objects. This class offers useful methods for comparison such as abuts, overlaps, contains, and more.

Interval interval = Interval.of( start , stop ) ;

interval.toString() = 2020-01-29T06:00:00Z/2020-01-30T06:00:00Z

Half-Open

The answer by mprivat is correct. His point is to not try to obtain end of a day, but rather compare to "before start of next day". His idea is known as the "Half-Open" approach where a span of time has a beginning that is inclusive while the ending is exclusive.

  • The current date-time frameworks of Java (java.util.Date/Calendar and Joda-Time) both use milliseconds from the epoch. But in Java 8, the new JSR 310 java.time.* classes use nanoseconds resolution. Any code you wrote based on forcing the milliseconds count of last moment of day would be incorrect if switched to the new classes.
  • Comparing data from other sources becomes faulty if they employ other resolutions. For example, Unix libraries typically employ whole seconds, and databases such as Postgres resolve date-time to microseconds.
  • Some Daylight Saving Time changes happen over midnight which might further confuse things.

enter image description here

Joda-Time 2.3 offers a method for this very purpose, to obtain first moment of the day: withTimeAtStartOfDay(). Similarly in java.time, LocalDate::atStartOfDay.

Search StackOverflow for "joda half-open" to see more discussion and examples.

See this post, Time intervals and other ranges should be half-open, by Bill Schneider.

Avoid legacy date-time classes

The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.

Use java.time classes. The java.time framework is the official successor of the highly successful Joda-Time library.

java.time

The java.time framework is built into Java 8 and later. Back-ported to Java 6 & 7 in the ThreeTen-Backport project, further adapted to Android in the ThreeTenABP project.

An Instant is a moment on the timeline in UTC with a resolution of nanoseconds.

Instant instant = Instant.now();

Apply a time zone to get the wall-clock time for some locality.

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.ofInstant( instant , zoneId );

To get the first moment of the day go through the LocalDate class and its atStartOfDay method.

ZonedDateTime zdtStart = zdt.toLocalDate().atStartOfDay( zoneId );

Using Half-Open approach, get first moment of following day.

ZonedDateTime zdtTomorrowStart = zdtStart.plusDays( 1 );

Table of all date-time types in Java, both modern and legacy

Currently the java.time framework lacks an Interval class as described below for Joda-Time. However, the ThreeTen-Extra project extends java.time with additional classes. This project is the proving ground for possible future additions to java.time. Among its classes is Interval. Construct an Interval by passing a pair of Instant objects. We can extract an Instant from our ZonedDateTime objects.

Interval today = Interval.of( zdtStart.toInstant() , zdtTomorrowStart.toInstant() );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes. Hibernate 5 & JPA 2.2 support java.time.

Where to obtain the java.time classes?


Joda-Time

UPDATE: The Joda-Time project is now in maintenance-mode, and advises migration to the java.time classes. I am leaving this section intact for history.

Joda-Time has three classes to represent a span of time in various ways: Interval, Period, and Duration. An Interval has a specific beginning and ending on the timeline of the Universe. This fits our need to represent "a day".

We call the method withTimeAtStartOfDay rather than set time of day to zeros. Because of Daylight Saving Time and other anomalies the first moment of the day may not be 00:00:00.

Example code using Joda-Time 2.3.

DateTimeZone timeZone = DateTimeZone.forID( "America/Montreal" );
DateTime now = DateTime.now( timeZone );
DateTime todayStart = now.withTimeAtStartOfDay();
DateTime tomorrowStart = now.plusDays( 1 ).withTimeAtStartOfDay();
Interval today = new Interval( todayStart, tomorrowStart );

If you must, you can convert to a java.util.Date.

java.util.Date date = todayStart.toDate();

Node.js: printing to console without a trailing newline?

In Windows console (Linux, too), you should replace '\r' with its equivalent code \033[0G:

process.stdout.write('ok\033[0G');

This uses a VT220 terminal escape sequence to send the cursor to the first column.

Uncaught Error: Unexpected module 'FormsModule' declared by the module 'AppModule'. Please add a @Pipe/@Directive/@Component annotation

Add FormsModule in Imports Array.
i.e

@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})

Or this can be done without using [(ngModel)] by using

<input [value]='hero.name' (input)='hero.name=$event.target.value' placeholder="name">

instead of

<input [(ngModel)]="hero.name" placeholder="Name">

How to compare two lists in python?

for i in arr1:
    if i in arr2:
        return 1
    return  0
arr1=[1,2,5]
arr2=[2,4,15]
q=checkarrayequalornot(arr1,arr2)
print(q)
>>0

JAX-RS / Jersey how to customize error handling?

This is the correct behavior actually. Jersey will try to find a handler for your input and will try to construct an object from the provided input. In this case it will try to create a new Date object with the value X provided to the constructor. Since this is an invalid date, by convention Jersey will return 404.

What you can do is rewrite and put birth date as a String, then try to parse and if you don't get what you want, you're free to throw any exception you want by any of the exception mapping mechanisms (there are several).

Should I Dispose() DataSet and DataTable?

You should assume it does something useful and call Dispose even if it does nothing in current .NET Framework incarnations. There's no guarantee it will stay that way in future versions leading to inefficient resource usage.

Basic Python client socket example

It looks like your client is trying to connect to a non-existent server. In a shell window, run:

$ nc -l 5000

before running your Python code. It will act as a server listening on port 5000 for you to connect to. Then you can play with typing into your Python window and seeing it appear in the other terminal and vice versa.

How to import jquery using ES6 syntax?

If you are using Webpack 4, the answer is to use the ProvidePlugin. Their documentation specifically covers angular.js with jquery use case:

new webpack.ProvidePlugin({
  'window.jQuery': 'jquery'
});

The issue is that when using import syntax angular.js and jquery will always be imported before you have a chance to assign jquery to window.jQuery (import statements will always run first no matter where they are in the code!). This means that angular will always see window.jQuery as undefined until you use ProvidePlugin.

How to select Multiple images from UIImagePickerController

You can't use UIImagePickerController, but you can use a custom image picker. I think ELCImagePickerController is the best option, but here are some other libraries you could use:

Objective-C
1. ELCImagePickerController
2. WSAssetPickerController
3. QBImagePickerController
4. ZCImagePickerController
5. CTAssetsPickerController
6. AGImagePickerController
7. UzysAssetsPickerController
8. MWPhotoBrowser
9. TSAssetsPickerController
10. CustomImagePicker
11. InstagramPhotoPicker
12. GMImagePicker
13. DLFPhotosPicker
14. CombinationPickerController
15. AssetPicker
16. BSImagePicker
17. SNImagePicker
18. DoImagePickerController
19. grabKit
20. IQMediaPickerController
21. HySideScrollingImagePicker
22. MultiImageSelector
23. TTImagePicker
24. SelectImages
25. ImageSelectAndSave
26. imagepicker-multi-select
27. MultiSelectImagePickerController
28. YangMingShan(Yahoo like image selector)
29. DBAttachmentPickerController
30. BRImagePicker
31. GLAssetGridViewController
32. CreolePhotoSelection

Swift
1. LimPicker (Similar to WhatsApp's image picker)
2. RMImagePicker
3. DKImagePickerController
4. BSImagePicker
5. Fusuma(Instagram like image selector)
6. YangMingShan(Yahoo like image selector)
7. NohanaImagePicker
8. ImagePicker
9. OpalImagePicker
10. TLPhotoPicker
11. AssetsPickerViewController
12. Alerts-and-pickers/Telegram Picker

Thanx to @androidbloke,
I have added some library that I know for multiple image picker in swift.
Will update list as I find new ones.
Thank You.

How to run a python script from IDLE interactive shell?

On Windows environment, you can execute py file on Python3 shell command line with the following syntax:

exec(open('absolute path to file_name').read())

Below explains how to execute a simple helloworld.py file from python shell command line

File Location: C:/Users/testuser/testfolder/helloworld.py

File Content: print("hello world")

We can execute this file on Python3.7 Shell as below:

>>> import os
>>> abs_path = 'C://Users/testuser/testfolder'
>>> os.chdir(abs_path)
>>> os.getcwd()
'C:\\Users\\testuser\\testfolder'

>>> exec(open("helloworld.py").read())
hello world

>>> exec(open("C:\\Users\\testuser\\testfolder\\helloworld.py").read())
hello world

>>> os.path.abspath("helloworld.py")
'C:\\Users\\testuser\\testfolder\\helloworld.py'
>>> import helloworld
hello world

How to include a font .ttf using CSS?

I know this is an old post but this solved my problem.

_x000D_
_x000D_
@font-face{_x000D_
  font-family: "Font Name";_x000D_
  src: url("../fonts/font-name.ttf") format("truetype");_x000D_
}
_x000D_
_x000D_
_x000D_

notice src:url("../fonts/font-name.ttf"); we use two periods to go back to the root directory and then into the fonts folder or wherever your file is located.

hope this helps someone down the line:) happy coding

JDK on OSX 10.7 Lion

On newer versions of OS X you should find ALL JREs (and JDKs) under

/Library/Java/JavaVirtualMachines/

/System/Library/Java/JavaVirtualMachines/

the old path

/System/Library/Frameworks/JavaVM.framework/

has been deprecated.

Here is the official deprecation note:

http://developer.apple.com/library/mac/#releasenotes/Java/JavaSnowLeopardUpdate3LeopardUpdate8RN/NewandNoteworthy/NewandNoteworthy.html#//apple_ref/doc/uid/TP40010380-CH4-SW1

Zooming MKMapView to fit annotation pins?

An iOS 7 compatible way is to use the following. First call showAnnotation in order to get a rectangle including all annotations. Afterwards create and UIEdgeInset with an top inset of the pin height. Thus you ensure to show the whole pin on the map.

[self.mapView showAnnotations:self.mapView.annotations animated:YES];
MKMapRect rect = [self.mapView visibleMapRect];
UIEdgeInsets insets = UIEdgeInsetsMake(pinHeight, 0, 0, 0);
[self.mapView setVisibleMapRect:rect edgePadding:insets animated:YES];

Multiline text in JLabel

if you want your jLabel Text to resize automaticly for example in a stretchable gridbaglayout its enough just to put its text in html tags like so:

JLabel label = new JLabel("<html>First line and maybe second line</html>");

JQuery $.ajax() post - data in a java servlet

For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

  &A2168=1&A1837=5&A8472=1&A1987=2

On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

Enumeration keys = request.getParameterNames(); 
HashMap map = new HashMap(); 
String key = null; 
while(keys.hasMoreElements()){ 
      key = keys.nextElement().toString(); 
      map.put(key, request.getParameter(key)); 
}

How to remove files and directories quickly via terminal (bash shell)

rm -rf some_dir

-r "recursive" -f "force" (suppress confirmation messages)

Be careful!

How can I get the full object in Node.js's console.log(), rather than '[Object]'?

Both of these usages can be applied:

// more compact, and colour can be applied (better for process managers logging)
console.dir(queryArgs, { depth: null, colors: true });

// get a clear list of actual values
console.log(JSON.stringify(queryArgs, undefined, 2));

How to remove the hash from window.location (URL) with JavaScript without page refresh?

$(window).on('hashchange', function (e) {
    history.replaceState('', document.title, e.oldURL);
});

Correct format specifier to print pointer or address?

Use %p, for "pointer", and don't use anything else*. You aren't guaranteed by the standard that you are allowed to treat a pointer like any particular type of integer, so you'd actually get undefined behaviour with the integral formats. (For instance, %u expects an unsigned int, but what if void* has a different size or alignment requirement than unsigned int?)

*) [See Jonathan's fine answer!] Alternatively to %p, you can use pointer-specific macros from <inttypes.h>, added in C99.

All object pointers are implicitly convertible to void* in C, but in order to pass the pointer as a variadic argument, you have to cast it explicitly (since arbitrary object pointers are only convertible, but not identical to void pointers):

printf("x lives at %p.\n", (void*)&x);

How can I get a list of all values in select box?

You had two problems:

1) The order in which you included the HTML. Try changing the dropdown from "onLoad" to "no wrap - head" in the JavaScript settings of your fiddle.

2) Your function prints the values. What you're actually after is the text

x.options[i].text; instead of x.options[i].value;

http://jsfiddle.net/WfBRr/5/

how to check for datatype in node js- specifically for integer

I think of two ways to test for the type of a value:

Method 1:

You can use the isNaN javascript method, which determines if a value is NaN or not. But because in your case you are testing a numerical value converted to string, Javascript is trying to guess the type of the value and converts it to the number 5 which is not NaN. That's why if you console.log out the result, you will be surprised that the code:

if (isNaN(i)) {
    console.log('This is not number');
}

will not return anything. For this reason a better alternative would be the method 2.

Method 2:

You may use javascript typeof method to test the type of a variable or value

if (typeof i != "number") {
    console.log('This is not number');
}

Notice that i'm using double equal operator, because in this case the type of the value is a string but Javascript internally will convert to Number.

A more robust method to force the value to numerical type is to use Number.isNaN which is part of new Ecmascript 6 (Harmony) proposal, hence not widespread and fully supported by different vendors.

AngularJS view not updating on model change

Just use $interval

Here is your code modified. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope, $interval) {
   $scope.testValue = 0;

    $interval(function() {
        $scope.testValue++;
    }, 500);
});

How can I write output from a unit test?

Try using TestContext.WriteLine() which outputs text in test results.

Example:

[TestClass]
public class UnitTest1
{
    private TestContext testContextInstance;

    /// <summary>
    /// Gets or sets the test context which provides
    /// information about and functionality for the current test run.
    /// </summary>
    public TestContext TestContext
    {
        get { return testContextInstance; }
        set { testContextInstance = value; }
    }

    [TestMethod]
    public void TestMethod1()
    {
        TestContext.WriteLine("Message...");
    }
}

The "magic" is described in MSDN:

To use TestContext, create a member and property within your test class [...] The test framework automatically sets the property, which you can then use in unit tests.

Could not load file or assembly 'Newtonsoft.Json' or one of its dependencies. Manifest definition does not match the assembly reference

I have tried the steps by Oleg, and they worked for my same situation.

Steps:

  1. Run update-package Newtonsoft.Json -reinstall in Package Manager.

  2. Delete your bin by enabling viewing the hidden files and deleting the bin folder.

  3. Close your Visual Studio and re-open it.

  4. Now run your project again. I believe it should be ok!

How to use SVG markers in Google Maps API v3

As mentioned by others in this thread, don't forget to explicitly set the width and height attributes in the svg like so:

<svg id="some_id" data-name="some_name" xmlns="http://www.w3.org/2000/svg"
     viewBox="0 0 26 42"
     width="26px" height="42px">

if you don't do that no js manipulation can help you as gmaps will not have a frame of reference and always use a standard size.

(i know it has been mentioned in some comments, but they are easy to miss. This information helped me in various cases)

PHP How to find the time elapsed since a date time?

Convert [saved_date] to timestamp. Get current timestamp.

current timestamp - [saved_date] timestamp.

Then you can format it with date();

You can normally convert most date formats to timestamps with the strtotime() function.

PYTHONPATH on Linux

PYTHONPATH is an environment variable those content is added to the sys.path where Python looks for modules. You can set it to whatever you like.

However, do not mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble in the long run. For example, virtual environments could do strange things…

I would suggest you learned how to package a Python module properly, maybe using this easy setup. If you are especially lazy, you could use cookiecutter to do all the hard work for you.

Adding Image to xCode by dragging it from File

You can't add image from desktop to UIimageView, you only can add image (dragging) into project folders and then select the name image into UIimageView properties (inspector).

Tutorial on how to do that: http://conecode.com/news/2011/06/ios-tutorial-creating-an-image-view-uiimageview/

How to fetch JSON file in Angular 2

Keep the json file in Assets (parallel to app dir) directory

Note that if you would have generated with ng new YourAppname- this assets directory exists same line with 'app' directory, and services should be child directory of app directory. May look like as below:

::app/services/myservice.ts

getOrderSummary(): Observable {
    // get users from api
    return this.http.get('assets/ordersummary.json')//, options)
        .map((response: Response) => {
            console.log("mock data" + response.json());
            return response.json();
        }
    )
    .catch(this.handleError);
} 

Can I use a case/switch statement with two variables?

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

Explicitly select items from a list or tuple

list( myBigList[i] for i in [87, 342, 217, 998, 500] )

I compared the answers with python 2.5.2:

  • 19.7 usec: [ myBigList[i] for i in [87, 342, 217, 998, 500] ]

  • 20.6 usec: map(myBigList.__getitem__, (87, 342, 217, 998, 500))

  • 22.7 usec: itemgetter(87, 342, 217, 998, 500)(myBigList)

  • 24.6 usec: list( myBigList[i] for i in [87, 342, 217, 998, 500] )

Note that in Python 3, the 1st was changed to be the same as the 4th.


Another option would be to start out with a numpy.array which allows indexing via a list or a numpy.array:

>>> import numpy
>>> myBigList = numpy.array(range(1000))
>>> myBigList[(87, 342, 217, 998, 500)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index
>>> myBigList[[87, 342, 217, 998, 500]]
array([ 87, 342, 217, 998, 500])
>>> myBigList[numpy.array([87, 342, 217, 998, 500])]
array([ 87, 342, 217, 998, 500])

The tuple doesn't work the same way as those are slices.

How do you know if Tomcat Server is installed on your PC

The port 8005 is used as service port. You can send a shutdown command (a configurable password) to that port. It will not "speak" HTTP, so you cannot use your browser to connect.

The default port for delivering web-content is 8080.

But there may be other applications listen to that port. So your tomcat may not start, if the port is not available.

You asked "How do you know, if tomcat server is installed on your PC?". The answer to that question is: You can't

You can't determine, if it is installed, because it may be only extracted from a ZIP archive or packaged within another application (Like JBoss AS (I think)).

Visual Studio opens the default browser instead of Internet Explorer

Another way is to do the following in Visual Studio:

  1. Select Debug
  2. Options and Settings
  3. Expand Environment
  4. Select Web Browser
  5. Click the 'Internet Explorer Options' button
  6. Select the 'Programs' tab
  7. Select 'Make Default' button for Internet Explorer

Android Studio error: "Environment variable does not point to a valid JVM installation"

In my case, the problem was that a line feed had gotten into the setting of the JAVA_HOME variable. I'm not sure how, but I was mucking with it earlier because I had had an issue with an unrelated ant build that was using JAVA_HOME, and I copied the path in.

I noticed the problem partially when I did a "set" command from the command line, and it showed "JAVA_HOME" on one line and the path on the next line, and a blank line after it.

But what really helped was running the gradle command. It gave the same error message. That gave me confidence that the problem really was the JAVA_HOME variable, and not the Android Studio install.

To solve the problem, I deleted the JAVA_HOME variable first. Then, when setting up the command to set the variable, I keyed in the path manually in Textpad, to make sure there were no linefeeds or carriage returns.

Then I ran the command:

setx JAVA_HOME "C:\Program Files\Java\jdk1.7.0_71"

How to fix date format in ASP .NET BoundField (DataFormatString)?

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 


In The above link you will find the answer

**C or c**

    Displays numeric values in currency format. You can specify the number of decimal places.
    Example:

Format: {0:C}
123.456 -> $123.46

**D or d**

    Displays integer values in decimal format. You can specify the number of digits. (Although the type is referred to as "decimal", the numbers are formatted as integers.)
    Example:
        Format: {0:D}
    1234 -> 1234
    Format: {0:D6}
    1234 -> 001234

    **E or e**
    Displays numeric values in scientific (exponential) format. You can specify the number of decimal places.
    Example:
    Format: {0:E}
    1052.0329112756 -> 1.052033E+003
    Format: {0:E2}
    -1052.0329112756 -> -1.05e+003

**F or f**
Displays numeric values in fixed format. You can specify the number of decimal places.
Example:
Format: {0:F}
1234.567 -> 1234.57
Format: {0:F3}
1234.567 -> 1234.567

**G or g**
Displays numeric values in general format (the most compact of either fixed-point or scientific notation). You can specify the number of significant digits.
Example:
Format: {0:G}
-123.456 -> -123.456
Format: {0:G2}
-123.456 -> -120

F or f
Displays numeric values in fixed format. You can specify the number of decimal places.
Format: {0:F}
1234.567 -> 1234.57
Format: {0:F3}
1234.567 -> 1234.567

G or g
Displays numeric values in general format (the most compact of either fixed-point or scientific notation). You can specify the number of significant digits.
Format: {0:G}
-123.456 -> -123.456
Format: {0:G2}
-123.456 -> -120

N or n
Displays numeric values in number format (including group separators and optional negative sign). You can specify the number of decimal places.
Format: {0:N}
1234.567 -> 1,234.57
Format: {0:N4}
1234.567 -> 1,234.5670

P or p
Displays numeric values in percent format. You can specify the number of decimal places.
Format: {0:P}
1 -> 100.00%
Format: {0:P1}
.5 -> 50.0%

R or r
Displays Single, Double, or BigInteger values in round-trip format.
Format: {0:R}
123456789.12345678 -> 123456789.12345678

X or x
Displays integer values in hexadecimal format. You can specify the number of digits.
Format: {0:X}
255 -> FF
Format: {0:x4}
255 -> 00ff

What should every programmer know about security?

Principles to keep in mind if you want your applications to be secure:

  • Never trust any input!
  • Validate input from all untrusted sources - use whitelists not blacklists
  • Plan for security from the start - it's not something you can bolt on at the end
  • Keep it simple - complexity increases the likelihood of security holes
  • Keep your attack surface to a minimum
  • Make sure you fail securely
  • Use defence in depth
  • Adhere to the principle of least privilege
  • Use threat modelling
  • Compartmentalize - so your system is not all or nothing
  • Hiding secrets is hard - and secrets hidden in code won't stay secret for long
  • Don't write your own crypto
  • Using crypto doesn't mean you're secure (attackers will look for a weaker link)
  • Be aware of buffer overflows and how to protect against them

There are some excellent books and articles online about making your applications secure:

Train your developers on application security best pratices

Codebashing (paid)

Security Innovation(paid)

Security Compass (paid)

OWASP WebGoat (free)

A transport-level error has occurred when receiving results from the server

The database connection is closed by the database server. The connection remains valid in the connection pool of your app; as a result, when you pickup the shared connection string and try to execute it's not able to reach the database. If you are developing Visual Studio, simply close the temporary web server on your task bar.

If it happens in production, resetting your application pool for your web site should recycle the connection pool.

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

How to install pip for Python 3 on Mac OS X?

On MacOS 10.12

download pip: pip as get-pip.py

download python3: python3

  1. install python3
  2. open terminal: python3 get-pip.py
  3. pip3 is available

Java logical operator short-circuiting

Logical OR :- returns true if at least one of the operands evaluate to true. Both operands are evaluated before apply the OR operator.

Short Circuit OR :- if left hand side operand returns true, it returns true without evaluating the right hand side operand.

cancelling a handler.postdelayed process

Another way is to handle the Runnable itself:

Runnable r = new Runnable {
    public void run() {
        if (booleanCancelMember != false) {
            //do what you need
        }
    }
}

import module from string variable

Apart from using the importlib one can also use exec method to import a module from a string variable.

Here I am showing an example of importing the combinations method from itertools package using the exec method:

MODULES = [
    ['itertools','combinations'],
]

for ITEM in MODULES:
    import_str = "from {0} import {1}".format(ITEM[0],', '.join(str(i) for i in ITEM[1:]))
    exec(import_str)

ar = list(combinations([1, 2, 3, 4], 2))
for elements in ar:
    print(elements)

Output:

(1, 2)
(1, 3)
(1, 4)
(2, 3)
(2, 4)
(3, 4)

Upload file to SFTP using PowerShell

Using PuTTY's pscp.exe (which I have in an $env:path directory):

pscp -sftp -pw passwd c:\filedump\* user@host:/Outbox/
mv c:\filedump\* c:\backup\*

How to set a background image in Xcode using swift?

Swift 5.3 in XCode 12.2 Playgrounds

Place the cursor wherever in the code the #insertLiteral would have been in earlier versions. Select from the top-menu Editor->Insert Image Literal... and navigate to the file. Click Open.

The file is added to a playground Resource folder and will then appear when the playground is run in whichever view it was positioned when selected.

If a file is already in the playground Bundle, e.g. in /Resources, it can be dragged directly to the required position in the code (where it will be represented by an icon).

cf. Apple help docs give details of this and how to place other colour and file literals.

What does it mean if a Python object is "subscriptable" or not?

Off the top of my head, the following are the only built-ins that are subscriptable:

string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

But mipadi's answer is correct - any class that implements __getitem__ is subscriptable

ECONNREFUSED error when connecting to mongodb from node.js

I had the same issue. What I did is to run mongodb command in another terminal. Then, run my application in another tab. This resolved my problem. Though, I am trying other solution such as creating a script to run mongodb before connection is made.

Temporary table in SQL server causing ' There is already an object named' error

You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

DROP TABLE #TMPGUARDIAN
CREATE TABLE #TMPGUARDIAN(
LAST_NAME NVARCHAR(30),
FRST_NAME NVARCHAR(30))  

INSERT INTO #TMPGUARDIAN 
SELECT LAST_NAME,FRST_NAME  
FROM TBL_PEOPLE

In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

Single line sftp from terminal

SCP answer

The OP mentioned SCP, so here's that.

As others have pointed out, SFTP is a confusing since the upload syntax is completely different from the download syntax. It gets marginally easier to remember if you use the same form:

echo 'put LOCALPATH REMOTEPATH' | sftp USER@HOST
echo 'get REMOTEPATH LOCALPATH' | sftp USER@HOST

In reality, this is still a mess, and is why people still use "outdated" commands such as SCP:

scp USER@HOST:REMOTEPATH LOCALPATH
scp LOCALPATH USER@HOST:REMOTEPATH

SCP is secure but dated. It has some bugs that will never be fixed, namely crashing if the server's .bash_profile emits a message. However, in terms of usability, the devs were years ahead.

How to check if the request is an AJAX request with PHP

Set a session variable for every page on your site (actual pages not includes or rpcs) that contains the current page name, then in your Ajax call pass a nonce salted with the $_SERVER['SCRIPT_NAME'];

<?php
function create_nonce($optional_salt='')
{
    return hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']);
}
$_SESSION['current_page'] = $_SERVER['SCRIPT_NAME'];
?>

<form>
  <input name="formNonce" id="formNonce" type="hidden" value="<?=create_nonce($_SERVER['SCRIPT_NAME']);?>">
  <label class="form-group">
    Login<br />
    <input name="userName" id="userName" type="text" />
  </label>
  <label class="form-group">
    Password<br />
    <input name="userPassword" id="userPassword" type="password" />
  </label>
  <button type="button" class="btnLogin">Sign in</button>
</form>
<script type="text/javascript">
    $("form.login button").on("click", function() {
        authorize($("#userName").val(),$("#userPassword").val(),$("#formNonce").val());
    });

    function authorize (authUser, authPassword, authNonce) {
        $.ajax({
          type: "POST",
          url: "/inc/rpc.php",
          dataType: "json",
          data: "userID="+authUser+"&password="+authPassword+"&nonce="+authNonce
        })
        .success(function( msg ) {
            //some successful stuff
        });
    }
</script>

Then in the rpc you are calling test the nonce you passed, if it is good then odds are pretty great that your rpc was legitimately called:

<?php
function check_nonce($nonce, $optional_salt='')
{
    $lasthour = date("G")-1<0 ? date('Ymd').'23' : date("YmdG")-1;
    if (hash_hmac('sha256', session_id().$optional_salt, date("YmdG").'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce || 
        hash_hmac('sha256', session_id().$optional_salt, $lasthour.'someSalt'.$_SERVER['REMOTE_ADDR']) == $nonce)
    {
        return true;
    } else {
        return false;
    }
}

$ret = array();
header('Content-Type: application/json');
if (check_nonce($_POST['nonce'], $_SESSION['current_page']))
{
    $ret['nonce_check'] = 'passed';
} else {
    $ret['nonce_check'] = 'failed';
}
echo json_encode($ret);
exit;
?>

edit: FYI the way I have it set the nonce is only good for an hour and change, so if they have not refreshed the page doing the ajax call in the last hour or 2 the ajax request will fail.

How to change button color with tkinter

Another way to change color of a button if you want to do multiple operations along with color change. Using the Tk().after method and binding a change method allows you to change color and do other operations.

Label.destroy is another example of the after method.

    def export_win():
        //Some Operation
        orig_color = export_finding_graph.cget("background")
        export_finding_graph.configure(background = "green")

        tt = "Exported"
        label = Label(tab1_closed_observations, text=tt, font=("Helvetica", 12))
        label.grid(row=0,column=0,padx=10,pady=5,columnspan=3)

        def change(orig_color):
            export_finding_graph.configure(background = orig_color)

        tab1_closed_observations.after(1000, lambda: change(orig_color))
        tab1_closed_observations.after(500, label.destroy)


    export_finding_graph = Button(tab1_closed_observations, text='Export', command=export_win)
    export_finding_graph.grid(row=6,column=4,padx=70,pady=20,sticky='we',columnspan=3)

You can also revert to the original color.

Folder structure for a Node.js project

Concerning the folders you mentioned:

  • /libs is usually used for custom classes/functions/modules
  • /vendor or /support contains 3rd party libraries (added as git sub-module when using git as source control)
  • /spec contains specifications for BDD tests.
  • /tests contains the unit-tests for an application (using a testing framework, see here)

NOTE: both /vendor and /support are deprecated since NPM introduced a clean package management. It's recommended to handle all 3rd-party dependencies using NPM and a package.json file

When building a rather large application, I recommend the following additional folders (especially if you are using some kind of MVC- / ORM-Framework like express or mongoose):

  • /models contains all your ORM models (called Schemas in mongoose)
  • /views contains your view-templates (using any templating language supported in express)
  • /public contains all static content (images, style-sheets, client-side JavaScript)
    • /assets/images contains image files
    • /assets/pdf contains static pdf files
    • /css contains style sheets (or compiled output by a css engine)
    • /js contains client side JavaScript
  • /controllers contain all your express routes, separated by module/area of your application (note: when using the bootstrapping functionality of express, this folder is called /routes)

I got used to organize my projects this way and i think it works out pretty well.

Update for CoffeeScript-based Express applications (using connect-assets):

  • /app contains your compiled JavaScript
  • /assets/ contains all client-side assets that require compilation
    • /assets/js contains your client-side CoffeeScript files
    • /assets/css contains all your LESS/Stylus style-sheets
  • /public/(js|css|img) contains your static files that are not handled by any compilers
  • /src contains all your server-side specific CoffeeScript files
  • /test contains all unit testing scripts (implemented using a testing-framework of your choice)
  • /views contains all your express views (be it jade, ejs or any other templating engine)

How to turn off word wrapping in HTML?

white-space: nowrap;: Will never break text, will keep other defaults

white-space: pre;: Will never break text, will keep multiple spaces after one another as multiple spaces, will break if explicitly written to break(pressing enter in html etc)

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

IntelliJ IDEA JDK configuration on Mac OS

The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.

/Library/Java/JavaVirtualMachines/

Next, say JDK version that you find is jdk1.8.0_151.jdk, the path to home directory within it is the JDK home path.

In my case it was :

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

You can configure it by going to File -> Project Structure -> SDKs.

enter image description here enter image description here

Placing an image to the top right corner - CSS

Position the div relatively, and position the ribbon absolutely inside it. Something like:

#content {
  position:relative;
}

.ribbon {
  position:absolute;
  top:0;
  right:0;
}

How can I clear an HTML file input with JavaScript?

What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked. Here is the code.

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.

Why is this error, 'Sequence contains no elements', happening?

If this is the offending line:

db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).First();

Then it's because there is no object in Responses for which the ResponseId == item.ResponseId, and you can't get the First() record if there are no matches.

Try this instead:

var response
  = db.Responses.Where(y => y.ResponseId.Equals(item.ResponseId)).FirstOrDefault();

if (response != null)
{
    // take some alternative action
}
else
    temp.Response = response;

The FirstOrDefault() extension returns an objects default value if no match is found. For most objects (other than primitive types), this is null.

Node Express sending image files as API response

a proper solution with streams and error handling is below:

const fs = require('fs')
const stream = require('stream')

app.get('/report/:chart_id/:user_id',(req, res) => {
  const r = fs.createReadStream('path to file') // or any other way to get a readable stream
  const ps = new stream.PassThrough() // <---- this makes a trick with stream error handling
  stream.pipeline(
   r,
   ps, // <---- this makes a trick with stream error handling
   (err) => {
    if (err) {
      console.log(err) // No such file or any other kind of error
      return res.sendStatus(400); 
    }
  })
  ps.pipe(res) // <---- this makes a trick with stream error handling
})

with Node older then 10 you will need to use pump instead of pipeline.

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

How can I use JQuery to post JSON data?

Using Promise and checking if the body object is a valid JSON. If not a Promise reject will be returned.

var DoPost = function(url, body) {
    try {
        body = JSON.stringify(body);
    } catch (error) {
        return reject(error);
    }
    return new Promise((resolve, reject) => {
        $.ajax({
                type: 'POST',
                url: url,
                data: body,
                contentType: "application/json",
                dataType: 'json'
            })
            .done(function(data) {
                return resolve(data);
            })
            .fail(function(error) {
                console.error(error);
                return reject(error);
            })
            .always(function() {
                // called after done or fail
            });
    });
}

Select objects based on value of variable in object using jq

Adapted from this post on Processing JSON with jq, you can use the select(bool) like this:

$ jq '.[] | select(.location=="Stockholm")' json
{
  "location": "Stockholm",
  "name": "Walt"
}
{
  "location": "Stockholm",
  "name": "Donald"
}

Handling InterruptedException in Java

I just wanted to add one last option to what most people and articles mention. As mR_fr0g has stated, it's important to handle the interrupt correctly either by:

  • Propagating the InterruptException

  • Restore Interrupt state on Thread

Or additionally:

  • Custom handling of Interrupt

There is nothing wrong with handling the interrupt in a custom way depending on your circumstances. As an interrupt is a request for termination, as opposed to a forceful command, it is perfectly valid to complete additional work to allow the application to handle the request gracefully. For example, if a Thread is Sleeping, waiting on IO or a hardware response, when it receives the Interrupt, then it is perfectly valid to gracefully close any connections before terminating the thread.

I highly recommend understanding the topic, but this article is a good source of information: http://www.ibm.com/developerworks/java/library/j-jtp05236/

How to format a java.sql Timestamp for displaying?

java.time

I am providing the modern answer. The Timestamp class is a hack on top of the already poorly designed java.util.Date class and is long outdated. I am assuming, though, that you are getting a Timestamp from a legacy API that you cannot afford to upgrade to java.time just now. When you do that, convert it to a modern Instant and do further processing from there.

    DateTimeFormatter formatter = DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM)
            .withLocale(Locale.GERMAN);
    
    Timestamp oldfashionedTimestamp = new Timestamp(1_567_890_123_456L);
    
    ZonedDateTime dateTime = oldfashionedTimestamp.toInstant()
            .atZone(ZoneId.systemDefault());
    String desiredFormat = dateTime.format(formatter);
    
    System.out.println(desiredFormat);

Output in my time zone:

07.09.2019 23:02:03

Pick how long or short of a format you want by specifying FormatStyle.SHORT, .MEDIUM, .LONG or .FULL. Pick your own locale where I put Locale.GERMAN. And pick your desired time zone, for example ZoneId.of("Europe/Oslo"). A Timestamp is a point in time without time zone, so we need a time zone to be able to convert it into year, month, day, hour, minute, etc. If your Timestamp comes from a database value of type timestamp without time zone (generally not recommended, but unfortunately often seen), ZoneId.systemDefault() is likely to give you the correct result. Another and slightly simpler option in this case is instead to convert to a LocalDateTime using oldfashionedTimestamp.toLocalDateTime() and then format the LocalDateTime in the same way as I did with the ZonedDateTime.

Which command do I use to generate the build of a Vue app?

To deploy your application to prod environment add

"build": "vue-cli-service build --mode prod"

in your scripts in package.json file.

Open your main.js and add

Vue.config.productionTip = false;

right after your imports. Then open your cli in the project folder and run this command

npm run build

This will make a dist folder in your project directory you may upload that dist folder in your host and your website will be live

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

How to print variables in Perl

print "Number of lines: $nids\n";
print "Content: $ids\n";

How did Perl complain? print $ids should work, though you probably want a newline at the end, either explicitly with print as above or implicitly by using say or -l/$\.

If you want to interpolate a variable in a string and have something immediately after it that would looks like part of the variable but isn't, enclose the variable name in {}:

print "foo${ids}bar";

Python sockets error TypeError: a bytes-like object is required, not 'str' with send function

The reason for this error is that in Python 3, strings are Unicode, but when transmitting on the network, the data needs to be bytes instead. So... a couple of suggestions:

  1. Suggest using c.sendall() instead of c.send() to prevent possible issues where you may not have sent the entire msg with one call (see docs).
  2. For literals, add a 'b' for bytes string: c.sendall(b'Thank you for connecting')
  3. For variables, you need to encode Unicode strings to byte strings (see below)

Best solution (should work w/both 2.x & 3.x):

output = 'Thank you for connecting'
c.sendall(output.encode('utf-8'))

Epilogue/background: this isn't an issue in Python 2 because strings are bytes strings already -- your OP code would work perfectly in that environment. Unicode strings were added to Python in releases 1.6 & 2.0 but took a back seat until 3.0 when they became the default string type. Also see this similar question as well as this one.

How to open a new tab in GNOME Terminal from command line?

You can also have each tab run a set command.

gnome-terminal --tab -e "tail -f somefile" --tab -e "some_other_command"

Angular JS break ForEach

If you use jQuery (hence not jqLite) in conjunction with AngularJS you can iterate with $.each - which allows breaking and continuing based on boolean return value expression.

JSFiddle:

http://jsfiddle.net/JEcD2/1/

Javascript:

var array = ['foo', 'bar', 'yay'];
$.each(array, function(index, element){
    if (element === 'foo') {
        return true; // continue
    }
    console.log(this);
    if (element === 'bar') {
        return false; // break
    }
});

Note:

Though using jQuery is not bad, both native Array.some or Array.every functions are recommended by MDN as you can read at native forEach documentation:

"There is no way to stop or break a forEach loop. The solution is to use Array.every or Array.some"

Following examples are provided by MDN:

Array.some:

function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true

Array.every:

function isBigEnough(element, index, array){
    return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true

How can I remove 3 characters at the end of a string in php?

Just do:

echo substr($string, 0, -3);

You don't need to use a strlen call, since, as noted in the substr docs:

If length is given and is negative, then that many characters will be omitted from the end of string

How to check if a column exists in a SQL Server table?

SQL Server 2005 onwards:

IF EXISTS(SELECT 1 FROM sys.columns 
          WHERE Name = N'columnName'
          AND Object_ID = Object_ID(N'schemaName.tableName'))
BEGIN
    -- Column Exists
END

Martin Smith's version is shorter:

IF COL_LENGTH('schemaName.tableName', 'columnName') IS NOT NULL
BEGIN
    -- Column Exists
END

List and kill at jobs on UNIX

First

ps -ef

to list all processes. Note the the process number of the one you want to kill. Then

kill 1234

were you replace 1234 with the process number that you want.

Alternatively, if you are absolutely certain that there is only one process with a particular name, or you want to kill multiple processes which share the same name

killall processname

What is Node.js?

Also, do not forget to mention that Google's V8 is VERY fast. It actually converts the JavaScript code to machine code with the matched performance of compiled binary. So along with all the other great things, it's INSANELY fast.

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

Example:

perfdb-# \df information_schema.*;

List of functions
        Schema      |        Name        | Result data type | Argument data types |  Type  
 information_schema | _pg_char_max_length   | integer | typid oid, typmod integer | normal
 information_schema | _pg_char_octet_length | integer | typid oid, typmod integer | normal
 information_schema | _pg_datetime_precision| integer | typid oid, typmod integer | normal
 .....
 information_schema | _pg_numeric_scale     | integer | typid oid, typmod integer | normal
 information_schema | _pg_truetypid         | oid     | pg_attribute, pg_type     | normal
 information_schema | _pg_truetypmod        | integer | pg_attribute, pg_type     | normal
(11 rows)

Difference between ${} and $() in Bash

The syntax is token-level, so the meaning of the dollar sign depends on the token it's in. The expression $(command) is a modern synonym for `command` which stands for command substitution; it means run command and put its output here. So

echo "Today is $(date). A fine day."

will run the date command and include its output in the argument to echo. The parentheses are unrelated to the syntax for running a command in a subshell, although they have something in common (the command substitution also runs in a separate subshell).

By contrast, ${variable} is just a disambiguation mechanism, so you can say ${var}text when you mean the contents of the variable var, followed by text (as opposed to $vartext which means the contents of the variable vartext).

The while loop expects a single argument which should evaluate to true or false (or actually multiple, where the last one's truth value is examined -- thanks Jonathan Leffler for pointing this out); when it's false, the loop is no longer executed. The for loop iterates over a list of items and binds each to a loop variable in turn; the syntax you refer to is one (rather generalized) way to express a loop over a range of arithmetic values.

A for loop like that can be rephrased as a while loop. The expression

for ((init; check; step)); do
    body
done

is equivalent to

init
while check; do
    body
    step
done

It makes sense to keep all the loop control in one place for legibility; but as you can see when it's expressed like this, the for loop does quite a bit more than the while loop.

Of course, this syntax is Bash-specific; classic Bourne shell only has

for variable in token1 token2 ...; do

(Somewhat more elegantly, you could avoid the echo in the first example as long as you are sure that your argument string doesn't contain any % format codes:

date +'Today is %c. A fine day.'

Avoiding a process where you can is an important consideration, even though it doesn't make a lot of difference in this isolated example.)

changing the language of error message in required field in html5 contact form

<input type="text" id="inputName"  placeholder="Enter name"  required  oninvalid="this.setCustomValidity('Your Message')" oninput="this.setCustomValidity('') />

this can help you even more better, Fast, Convenient & Easiest.

Split a large pandas dataframe

You can use groupby, assuming you have an integer enumerated index:

import math
df = pd.DataFrame(dict(sample=np.arange(99)))
rows_per_subframe = math.ceil(len(df) / 4.)

subframes = [i[1] for i in df.groupby(np.arange(len(df))//rows_per_subframe)]

Note: groupby returns a tuple in which the 2nd element is the dataframe, thus the slightly complicated extraction.

>>> len(subframes), [len(i) for i in subframes]
(4, [25, 25, 25, 24])

SqlException: DB2 SQL error: SQLCODE: -302, SQLSTATE: 22001, SQLERRMC: null

You can find the codes in the DB2 Information Center. Here's a definition of the -302 from the z/OS Information Center:

THE VALUE OF INPUT VARIABLE OR PARAMETER NUMBER position-number IS INVALID OR TOO LARGE FOR THE TARGET COLUMN OR THE TARGET VALUE

On Linux/Unix/Windows DB2, you'll look under SQL Messages to find your error message. If the code is positive, you'll look for SQLxxxxW, if it's negative, you'll look for SQLxxxxN, where xxxx is the code you're looking up.

Why does make think the target is up to date?

EDIT: This only applies to some versions of make - you should check your man page.

You can also pass the -B flag to make. As per the man page, this does:

-B, --always-make Unconditionally make all targets.

So make -B test would solve your problem if you were in a situation where you don't want to edit the Makefile or change the name of your test folder.

Ruby Array find_first object?

Do you need the object itself or do you just need to know if there is an object that satisfies. If the former then yes: use find:

found_object = my_array.find { |e| e.satisfies_condition? }

otherwise you can use any?

found_it = my_array.any?  { |e| e.satisfies_condition? }

The latter will bail with "true" when it finds one that satisfies the condition. The former will do the same, but return the object.

Use YAML with variables

Rails / ruby frameworks are able to do some templating ... it's frequently used to load env variables ...

# fooz.yml
  foo:
    bar: <%= $ENV[:some_var] %>

No idea if this works for javascript frameworks as I think that YML format is superset of json and it depends on what reads the yml file for you.

If you can use the template like that or the << >> or the {{ }} styles depending on your reader, after that you just ...

In another yml file ...

# boo.yml

development:
  fooz: foo

Which allows you to basically insert a variable as your reference that original file each time which is dynamically set. When reading I was also seeing you can create or open YML files as objects on the fly for several languages which allows you to create a file & chain write a series of YML files or just have them all statically pointing to the dynamically created one.

413 Request Entity Too Large - File Upload Issue

-in php.ini (inside /etc/php.ini)

 max_input_time = 24000
 max_execution_time = 24000
 upload_max_filesize = 12000M
 post_max_size = 24000M
 memory_limit = 12000M

-in nginx.conf(inside /opt/nginx/conf)

client_max_body_size 24000M

Its working for my case

Setting POST variable without using form

you can do it using ajax or by sending http headers+content like:

POST /xyz.php HTTP/1.1
Host: www.mysite.com
User-Agent: Mozilla/4.0
Content-Length: 27
Content-Type: application/x-www-form-urlencoded

userid=joe&password=guessme

Why does using from __future__ import print_function breaks Python2-style print?

First of all, from __future__ import print_function needs to be the first line of code in your script (aside from some exceptions mentioned below). Second of all, as other answers have said, you have to use print as a function now. That's the whole point of from __future__ import print_function; to bring the print function from Python 3 into Python 2.6+.

from __future__ import print_function

import sys, os, time

for x in range(0,10):
    print(x, sep=' ', end='')  # No need for sep here, but okay :)
    time.sleep(1)

__future__ statements need to be near the top of the file because they change fundamental things about the language, and so the compiler needs to know about them from the beginning. From the documentation:

A future statement is recognized and treated specially at compile time: Changes to the semantics of core constructs are often implemented by generating different code. It may even be the case that a new feature introduces new incompatible syntax (such as a new reserved word), in which case the compiler may need to parse the module differently. Such decisions cannot be pushed off until runtime.

The documentation also mentions that the only things that can precede a __future__ statement are the module docstring, comments, blank lines, and other future statements.

How to check if memcache or memcached is installed for PHP?

Use this code to not only check if the memcache extension is enabled, but also whether the daemon is running and able to store and retrieve data successfully:

<?php
if (class_exists('Memcache')) {
    $server = 'localhost';
    if (!empty($_REQUEST['server'])) {
        $server = $_REQUEST['server'];
    }
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect($server);

    if ($isMemcacheAvailable) {
        $aData = $memcache->get('data');
        echo '<pre>';
        if ($aData) {
            echo '<h2>Data from Cache:</h2>';
            print_r($aData);
        } else {
            $aData = array(
                'me' => 'you',
                'us' => 'them',
            );
            echo '<h2>Fresh Data:</h2>';
            print_r($aData);
            $memcache->set('data', $aData, 0, 300);
        }
        $aData = $memcache->get('data');
        if ($aData) {
            echo '<h3>Memcache seem to be working fine!</h3>';
        } else {
            echo '<h3>Memcache DOES NOT seem to be working!</h3>';
        }
        echo '</pre>';
    }
}
if (!$isMemcacheAvailable) {
    echo 'Memcache not available';
}

?>

The model backing the 'ApplicationDbContext' context has changed since the database was created

remove all tables identity

Delete _MigrationHistory
Delete AspNetRoles
Delete AspNetUserClaims
Delete AspNetUserLogins
Delete AspNetRoles
Delete AspNetUser

Change the Blank Cells to "NA"

You can use gsub to replace multiple mutations of empty, like "" or a space, to be NA:

data= data.frame(cats=c('', ' ', 'meow'), dogs=c("woof", " ", NA))
apply(data, 2, function(x) gsub("^$|^ $", NA, x))

Clear History and Reload Page on Login/Logout Using Ionic Framework

I tried many methods, but found this method is absolutely correct:

$window.location.reload();

Hope this help others stuck for days like me with version: angular 1.5.5, ionic 1.2.4, angular-ui-router 1.0.0

Sum function in VBA

Range("A1").Function="=SUM(Range(Cells(2,1),Cells(3,2)))"

won't work because worksheet functions (when actually used on a worksheet) don't understand Range or Cell

Try

Range("A1").Formula="=SUM(" & Range(Cells(2,1),Cells(3,2)).Address(False,False) & ")"

What is a View in Oracle?

A view is a virtual table, which provides access to a subset of column from one or more table. A view can derive its data from one or more table. An output of query can be stored as a view. View act like small a table but it does not physically take any space. View is good way to present data in particular users from accessing the table directly. A view in oracle is nothing but a stored sql scripts. Views itself contain no data.

How to make a list of n numbers in Python and randomly select any number?

You can create the enumeration of the elements by something like this:

mylist = list(xrange(10))

Then you can use the random.choice function to select your items:

import random
...
random.choice(mylist)

As Asim Ihsan correctly stated, my answer did not address the full problem of the OP. To remove the values from the list, simply list.remove() can be called:

import random
...
value = random.choice(mylist)
mylist.remove(value)

As takataka pointed out, the xrange builtin function was renamed to range in Python 3.

Call parent method from child class c#

Found the solution.

In the parent I declare a new instance of the ChildClass() then bind the event handler in that class to the local method in the parent

In the child class I add a public event handler:

public EventHandler UpdateProgress;

In the parent I create a new instance of this child class then bind the local parent event to the public eventhandler in the child

ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);

Then in the LoadData() of the child class I can call

private LoadData() {
    this.OnMyMethod();
}

Where OnMyMethod is:

public void OnMyMethod()
{
     // has the event handler been assigned?
     if (this.UpdateProgress!= null)
     {
         // raise the event
         this.UpdateProgress(this, new EventArgs());
     }
}

This runs the event in the parent class

Excel: Creating a dropdown using a list in another sheet?

Yes it is. Use Data Validation from the Data panel. Select Allow: List and pick those cells on the other sheet as your source.

Creating a very simple 1 username/password login in php

Here is a simple php script for login and a page that can only be accessed by logged in users.

login.php

<?php
    session_start();
    echo isset($_SESSION['login']);
    if(isset($_SESSION['login'])) {
      header('LOCATION:index.php'); die();
    }
?>
<!DOCTYPE html>
<html>
   <head>
     <meta http-equiv='content-type' content='text/html;charset=utf-8' />
     <title>Login</title>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
   </head>
<body>
  <div class="container">
    <h3 class="text-center">Login</h3>
    <?php
      if(isset($_POST['submit'])){
        $username = $_POST['username']; $password = $_POST['password'];
        if($username === 'admin' && $password === 'password'){
          $_SESSION['login'] = true; header('LOCATION:admin.php'); die();
        } {
          echo "<div class='alert alert-danger'>Username and Password do not match.</div>";
        }

      }
    ?>
    <form action="" method="post">
      <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" class="form-control" id="username" name="username" required>
      </div>
      <div class="form-group">
        <label for="pwd">Password:</label>
        <input type="password" class="form-control" id="pwd" name="password" required>
      </div>
      <button type="submit" name="submit" class="btn btn-default">Login</button>
    </form>
  </div>
</body>
</html>

admin.php ( only logged in users can access it )

<?php
    session_start();
    if(!isset($_SESSION['login'])) {
        header('LOCATION:login.php'); die();
    }
?>
<html>
    <head>
        <title>Admin Page</title>
    </head>
    <body>
        This is admin page view able only by logged in users.
    </body> 
</html>

Use jQuery to get the file input's selected filename without the path

How about something like this?

var pathArray = $('input[type=file]').val().split('\\');
alert(pathArray[pathArray.length - 1]);

How to use onBlur event on Angular2?

You can also use (focusout) event:

Use (eventName) for while binding event to DOM, basically () is used for event binding. Also you can use ngModel to get two way binding for your model. With the help of ngModel you can manipulate model variable value inside your component.

Do this in HTML file

<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">

And in your (component) .ts file

export class AppComponent { 
 model: any;
 constructor(){ }
 someMethodWithFocusOutEvent(){
   console.log('Your method called');
   // Do something here
 }
}

Global variables in R

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

Proxy Error 502 : The proxy server received an invalid response from an upstream server

The java application takes too long to respond(maybe due start-up/jvm being cold) thus you get the proxy error.

Proxy Error

The proxy server received an invalid response from an upstream server.
 The proxy server could not handle the request GET /lin/Campaignn.jsp.

As Albert Maclang said amending the http timeout configuration may fix the issue. I suspect the java application throws a 500+ error thus the apache gateway error too. You should look in the logs.

IntelliJ can't recognize JavaFX 11 with OpenJDK 11

Quick summary, you can do either:

  1. Include the JavaFX modules via --module-path and --add-modules like in José's answer.

    OR

  2. Once you have JavaFX libraries added to your project (either manually or via maven/gradle import), add the module-info.java file similar to the one specified in this answer. (Note that this solution makes your app modular, so if you use other libraries, you will also need to add statements to require their modules inside the module-info.java file).


This answer is a supplement to Jose's answer.

The situation is this:

  1. You are using a recent Java version, e.g. 13.
  2. You have a JavaFX application as a Maven project.
  3. In your Maven project you have the JavaFX plugin configured and JavaFX dependencies setup as per Jose's answer.
  4. You go to the source code of your main class which extends Application, you right-click on it and try to run it.
  5. You get an IllegalAccessError involving an "unnamed module" when trying to launch the app.

Excerpt for a stack trace generating an IllegalAccessError when trying to run a JavaFX app from Intellij Idea:

Exception in Application start method
java.lang.reflect.InvocationTargetException
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplicationWithArgs(LauncherImpl.java:464)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication(LauncherImpl.java:363)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:567)
    at java.base/sun.launcher.LauncherHelper$FXHelper.main(LauncherHelper.java:1051)
Caused by: java.lang.RuntimeException: Exception in Application start method
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:900)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication$2(LauncherImpl.java:195)
    at java.base/java.lang.Thread.run(Thread.java:830)
Caused by: java.lang.IllegalAccessError: class com.sun.javafx.fxml.FXMLLoaderHelper (in unnamed module @0x45069d0e) cannot access class com.sun.javafx.util.Utils (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.util to unnamed module @0x45069d0e
    at com.sun.javafx.fxml.FXMLLoaderHelper.<clinit>(FXMLLoaderHelper.java:38)
    at javafx.fxml.FXMLLoader.<clinit>(FXMLLoader.java:2056)
    at org.jewelsea.demo.javafx.springboot.Main.start(Main.java:13)
    at javafx.graphics/com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$9(LauncherImpl.java:846)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runAndWait$12(PlatformImpl.java:455)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$10(PlatformImpl.java:428)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
    at javafx.graphics/com.sun.javafx.application.PlatformImpl.lambda$runLater$11(PlatformImpl.java:427)
    at javafx.graphics/com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:96)
Exception running application org.jewelsea.demo.javafx.springboot.Main

OK, now you are kind of stuck and have no clue what is going on.

What has actually happened is this:

  1. Maven has successfully downloaded the JavaFX dependencies for your application, so you don't need to separately download the dependencies or install a JavaFX SDK or module distribution or anything like that.
  2. Idea has successfully imported the modules as dependencies to your project, so everything compiles OK and all of the code completion and everything works fine.

So it seems everything should be OK. BUT, when you run your application, the code in the JavaFX modules is failing when trying to use reflection to instantiate instances of your application class (when you invoke launch) and your FXML controller classes (when you load FXML). Without some help, this use of reflection can fail in some cases, generating the obscure IllegalAccessError. This is due to a Java module system security feature which does not allow code from other modules to use reflection on your classes unless you explicitly allow it (and the JavaFX application launcher and FXMLLoader both require reflection in their current implementation in order for them to function correctly).

This is where some of the other answers to this question, which reference module-info.java, come into the picture.

So let's take a crash course in Java modules:

The key part is this:

4.9. Opens

If we need to allow reflection of private types, but we don't want all of our code exposed, we can use the opens directive to expose specific packages.

But remember, this will open the package up to the entire world, so make sure that is what you want:

module my.module { opens com.my.package; }

So, perhaps you don't want to open your package to the entire world, then you can do:

4.10. Opens … To

Okay, so reflection is great sometimes, but we still want as much security as we can get from encapsulation. We can selectively open our packages to a pre-approved list of modules, in this case, using the opens…to directive:

module my.module { opens com.my.package to moduleOne, moduleTwo, etc.; }

So, you end up creating a src/main/java/module-info.java class which looks like this:

module org.jewelsea.demo.javafx.springboot {
    requires javafx.fxml;
    requires javafx.controls;
    requires javafx.graphics;
    opens org.jewelsea.demo.javafx.springboot to javafx.graphics,javafx.fxml;
}

Where, org.jewelsea.demo.javafx.springboot is the name of the package which contains the JavaFX Application class and JavaFX Controller classes (replace this with the appropriate package name for your application). This tells the Java runtime that it is OK for classes in the javafx.graphics and javafx.fxml to invoke reflection on the classes in your org.jewelsea.demo.javafx.springboot package. Once this is done, and the application is compiled and re-run things will work fine and the IllegalAccessError generated by JavaFX's use of reflection will no longer occur.

But what if you don't want to create a module-info.java file

If instead of using the the Run button in the top toolbar of IDE to run your application class directly, you instead:

  1. Went to the Maven window in the side of the IDE.
  2. Chose the javafx maven plugin target javafx.run.
  3. Right-clicked on that and chose either Run Maven Build or Debug....

Then the app will run without the module-info.java file. I guess this is because the maven plugin is smart enough to dynamically include some kind of settings which allows the app to be reflected on by the JavaFX classes even without a module-info.java file, though I don't know how this is accomplished.

To get that setting transferred to the Run button in the top toolbar, right-click on the javafx.run Maven target and choose the option to Create Run/Debug Configuration for the target. Then you can just choose Run from the top toolbar to execute the Maven target.

What, why or when it is better to choose cshtml vs aspx?

As other people have answered, .cshtml (or .vbhtml if that's your flavor) provides a handler-mapping to load the MVC engine. The .aspx extension simply loads the aspnet_isapi.dll that performs the compile and serves up web forms. The difference in the handler mapping is simply a method of allowing the two to co-exist on the same server allowing both MVC applications and WebForms applications to live under a common root.

This allows http://www.mydomain.com/MyMVCApplication to be valid and served with MVC rules along with http://www.mydomain.com/MyWebFormsApplication to be valid as a standard web form.

Edit:
As for the difference in the technologies, the MVC (Razor) templating framework is intended to return .Net pages to a more RESTful "web-based" platform of templated views separating the code logic between the model (business/data objects), the view (what the user sees) and the controllers (the connection between the two). The WebForms model (aspx) was an attempt by Microsoft to use complex javascript embedding to simulate a more stateful application similar to a WinForms application complete with events and a page lifecycle that would be capable of retaining its own state from page to page.

The choice to use one or the other is always going to be a contentious one because there are arguments for and against both systems. I for one like the simplicity in the MVC architecture (though routing is anything but simple) and the ease of the Razor syntax. I feel the WebForms architecture is just too heavy to be an effective web platform. That being said, there are a lot of instances where the WebForms framework provides a very succinct and usable model with a rich event structure that is well defined. It all boils down to the needs of the application and the preferences of those building it.

open cv error: (-215) scn == 3 || scn == 4 in function cvtColor

Please Set As Below

img = cv2.imread('2015-05-27-191152.jpg',1)     // Change Flag As 1 For Color Image
                                                //or O for Gray Image So It image is 
                                                //already gray

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Check the target definition if you are working with an RCP-SWT project.

Open the target editor of and navigate to the environent definition. There you can set the architecture. The idea is that by starting up your RCP application then only the 32 bit SWT libraries/bundles will be loaded. If you have already a runtime configuration it is advisable to create a new one as well.

Target Editor in Eclipse

Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies

it is too late I know, howewer there is no succesfully answer. I found the answer from another website. I fixed the issue when I delete the System.Runtime assemblydependency. I deleted this.

<dependentAssembly> <assemblyIdentity name="System.Runtime" publicKeyToken="b03f5f7f11d50a3a" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-4.1.2.0" newVersion="4.1.2.0"/> </dependentAssembly>

Best Regards

How can I create a "Please Wait, Loading..." animation using jQuery?

This would make the buttons disappear, then an animation of "loading" would appear in their place and finally just display a success message.

$(function(){
    $('#submit').click(function(){
        $('#submit').hide();
        $("#form .buttons").append('<img src="assets/img/loading.gif" alt="Loading..." id="loading" />');
        $.post("sendmail.php",
                {emailFrom: nameVal, subject: subjectVal, message: messageVal},
                function(data){
                    jQuery("#form").slideUp("normal", function() {                 
                        $("#form").before('<h1>Success</h1><p>Your email was sent.</p>');
                    });
                }
        );
    });
});

Adding a public key to ~/.ssh/authorized_keys does not log me in automatically

My problem was a modified AuthorizedKeysFile, when the automation to populate /etc/ssh/authorized_keys had not yet been run.

$sudo grep AuthorizedKeysFile /etc/ssh/sshd_config
#AuthorizedKeysFile .ssh/authorized_keys
AuthorizedKeysFile  /etc/ssh/authorized_keys/%u

Tooltip on image

You can use the standard HTML title attribute of image for this:

<img src="source of image" alt="alternative text" title="this will be displayed as a tooltip"/>

creating list of objects in Javascript

So, I'm used to use

var nameOfList = new List("objectName", "objectName", "objectName")

This is how it works for me but might be different for you, I recommend to watch some Unity Tutorials on the Scripting API.

How to get current route in react-router 2.0.0-rc5

You could use the 'isActive' prop like so:

const { router } = this.context;
if (router.isActive('/login')) {
    router.push('/');
}

isActive will return a true or false.

Tested with react-router 2.7

Why can't I push to this bare repository?

I use SourceTree git client, and I see that their initial commit/push command is:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v --tags --set-upstream origin master:master

generating variable names on fly in python

On an object, you can achieve this with setattr

>>> class A(object): pass
>>> a=A()
>>> setattr(a, "hello1", 5)
>>> a.hello1
5

Cropping an UIImage

Update 2014-05-28: I wrote this when iOS 3 or so was the hot new thing, I'm certain there are better ways to do this by now, possibly built-in. As many people have mentioned, this method doesn't take rotation into account; read some additional answers and spread some upvote love around to keep the responses to this question helpful for everyone.

Original response:

I'm going to copy/paste my response to the same question elsewhere:

There isn't a simple class method to do this, but there is a function that you can use to get the desired results: CGImageCreateWithImageInRect(CGImageRef, CGRect) will help you out.

Here's a short example using it:

CGImageRef imageRef = CGImageCreateWithImageInRect([largeImage CGImage], cropRect);
// or use the UIImage wherever you like
[UIImageView setImage:[UIImage imageWithCGImage:imageRef]]; 
CGImageRelease(imageRef);

Firebase: how to generate a unique numeric ID for key?

Adding to the @htafoya answer. The code snippet will be

const getTimeEpoch = () => {
    return new Date().getTime().toString();                             
}

Git resolve conflict using --ours/--theirs for all files

git diff --name-only --diff-filter=U | xargs git checkout --theirs

Seems to do the job. Note that you have to be cd'ed to the root directory of the git repo to achieve this.

Decimal or numeric values in regular expression validation

Here is my regex for validating numbers:

^(-?[1-9]+\\d*([.]\\d+)?)$|^(-?0[.]\\d*[1-9]+)$|^0$

Valid numbers:

String []validNumbers={"3","-3","0","0.0","1.0","0.1","0.0001","-555","94549870965"};

Invalid numbers:

String []invalidNumbers={"a",""," ","-","001","-00.2","000.5",".3","3."," -1","--1","-.1","-0"};

How can I install a .ipa file to my iPhone simulator

You can run the application file of project in simulator - not .ipa file.

You can get it from:

Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->then u can see many files like 0CD04F.... find out your application file through open it.

You can copy the file to your system(which system simulator u need run ) location Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->

Then open the simulator 4.3 (its your simulator version where you pasted). You can see the application installed there.


Getting from other people:

Please tell them to find out Libraries-->Applicationsupport-->iphone simulator-->4.3(its ur simulator version)-->applications-->then you can see many files like 0CD04F.... from their system and receive that file from them.

After they have got the file, please copy and paste the file in to your system `Libraries-->Applicationsupport-->iphone simulator-->4.3(its your simulator version)-->applications-->(paste the file here).

Then you can see the app is installed in your system simulator and you can run it after clicking the file.

How do I accomplish an if/else in mustache.js?

You can define a helper in the view. However, the conditional logic is somewhat limited. Moxy-Stencil (https://github.com/dcmox/moxyscript-stencil) seems to address this with "parameterized" helpers, eg:

{{isActive param}}

and in the view:

view.isActive = function (path: string){ return path === this.path ? "class='active'" : '' }

How do you create vectors with specific intervals in R?

Use the code

x = seq(0,100,5) #this means (starting number, ending number, interval)

the output will be

[1]   0   5  10  15  20  25  30  35  40  45  50  55  60  65  70  75
[17]  80  85  90  95 100

How do you set the EditText keyboard to only consist of numbers on Android?

android:inputType="number" or android:inputType="phone". You can keep this. You will get the keyboard containing numbers. For further details on different types of keyboard, check this link.

I think it is possible only if you create your own soft keyboard. Or try this android:inputType="number|textVisiblePassword. But it still shows other characters. Besides you can keep android:digits="0123456789" to allow only numbers in your edittext. Or if you still want the same as in image, try combining two or more features with | separator and check your luck, but as per my knowledge you have to create your own keypad to get exactly like that..

PermissionError: [Errno 13] Permission denied

EDIT

I am seeing a bit of activity on my answer so I decided to improve it a bit for those with this issue still

There are basically three main methods of achieving administrator execution privileges on Windows.

  1. Running as admin from cmd.exe
  2. Creating a shortcut to execute the file with elevated privileges
  3. Changing the permissions on the python executable (Not recommended)

1) Running cmd.exe as and admin

Since in Windows there is no sudo command you have to run the terminal (cmd.exe) as an administrator to achieve to level of permissions equivalent to sudo. You can do this two ways:

  1. Manually

    • Find cmd.exe in C:\Windows\system32
    • Right-click on it
    • Select Run as Administrator
    • It will then open the command prompt in the directory C:\Windows\system32
    • Travel to your project directory
    • Run your program
  2. Via key shortcuts

    • Press the windows key (between alt and ctrl usually) + X.
    • A small pop-up list containing various administrator tasks will appear.
    • Select Command Prompt (Admin)
    • Travel to your project directory
    • Run your program

By doing that you are running as Admin so this problem should not persist

2) Creating shortcut with elevated privileges

  1. Create a shortcut for python.exe
  2. Righ-click the shortcut and select Properties
  3. Change the shortcut target into something like "C:\path_to\python.exe" C:\path_to\your_script.py"
  4. Click "advanced" in the property panel of the shortcut, and click the option "run as administrator"

Answer contributed by delphifirst in this question

3) Changing the permissions on the python executable (Not recommended)

This is a possibility but I highly discourage you from doing so.

It just involves finding the python executable and setting it to run as administrator every time. Can and probably will cause problems with things like file creation (they will be admin only) or possibly modules that require NOT being an admin to run.

jQuery Call to WebService returns "No Transport" error

For me it is an entirely different story.
Since this page has a good search engine ranking, I should add my case and the solution here too.

I built jquery myself with webpack picking only the modules I use. The ajax is always failed with "No Transport" message as the only clue.

After a long debugging, the problem turns out to be XMLHttpRequest is pluggable in jquery and it not include by default.

You have to explicitly include jquery/src/ajax/xhr file in order to make the ajax working in browsers.

Edit In Place Content Editing

I've modified your plunker to get it working via angular-xeditable:

http://plnkr.co/edit/xUDrOS?p=preview

It is common solution for inline editing - you creale hyperlinks with editable-text directive that toggles into <input type="text"> tag:

<a href="#" editable-text="bday.name" ng-click="myform.$show()" e-placeholder="Name">
    {{bday.name || 'empty'}}
</a>

For date I used editable-date directive that toggles into html5 <input type="date">.

Set the location in iPhone Simulator

in iOS Simulator menu, go to Debug -> Location -> Custom Location. There you can set the latitude and longitude and test the app accordingly. This works with mapkit and also with CLLocationManager.

Create a asmx web service in C# using visual studio 2013

Short answer: Don't do it.

Longer answer: Use WCF. It's here to replace Asmx.

see this answer for example, or the first comment on this one.

John Saunders: ASMX is a legacy technology, and should not be used for new development. WCF or ASP.NET Web API should be used for all new development of web service clients and servers. One hint: Microsoft has retired the ASMX Forum on MSDN.


As for comment ... well, if you have to, you have to. I'll leave you in the competent hands of the other answers then. (Even though it's funny it has issues, and if it does, why are you doing it in VS2013 to begin with ?)

Installing a plain plugin jar in Eclipse 3.5

Simplest way - just put in the Eclipse plugins folder. You can start Eclipse with the -clean option to make sure Eclipse cleans its' plugins cache and sees the new plugin.

In general, it is far more recommended to install plugins using proper update sites.

Python extending with - using super() Python 3 vs Python 2

In a single inheritance case (when you subclass one class only), your new class inherits methods of the base class. This includes __init__. So if you don't define it in your class, you will get the one from the base.

Things start being complicated if you introduce multiple inheritance (subclassing more than one class at a time). This is because if more than one base class has __init__, your class will inherit the first one only.

In such cases, you should really use super if you can, I'll explain why. But not always you can. The problem is that all your base classes must also use it (and their base classes as well -- the whole tree).

If that is the case, then this will also work correctly (in Python 3 but you could rework it into Python 2 -- it also has super):

class A:
    def __init__(self):
        print('A')
        super().__init__()

class B:
    def __init__(self):
        print('B')
        super().__init__()

class C(A, B):
    pass

C()
#prints:
#A
#B

Notice how both base classes use super even though they don't have their own base classes.

What super does is: it calls the method from the next class in MRO (method resolution order). The MRO for C is: (C, A, B, object). You can print C.__mro__ to see it.

So, C inherits __init__ from A and super in A.__init__ calls B.__init__ (B follows A in MRO).

So by doing nothing in C, you end up calling both, which is what you want.

Now if you were not using super, you would end up inheriting A.__init__ (as before) but this time there's nothing that would call B.__init__ for you.

class A:
    def __init__(self):
        print('A')

class B:
    def __init__(self):
        print('B')

class C(A, B):
    pass

C()
#prints:
#A

To fix that you have to define C.__init__:

class C(A, B):
    def __init__(self):
        A.__init__(self)
        B.__init__(self)

The problem with that is that in more complicated MI trees, __init__ methods of some classes may end up being called more than once whereas super/MRO guarantee that they're called just once.

Prevent nginx 504 Gateway timeout using PHP set_time_limit()

 sudo nano /etc/nginx/nginx.conf

Add these variables to nginx.conf file:

http {  
  # .....
  proxy_connect_timeout       600;
  proxy_send_timeout          600;
  proxy_read_timeout          600;
  send_timeout                600;
}

And then restart:

service nginx reload

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

Copy to Clipboard for all Browsers using javascript

For security reasons most browsers do not allow to modify the clipboard (except IE, of course...).

The only way to make a copy-to-clipboard function cross-browser compatible is to use Flash.

What does 'synchronized' mean?

Synchronized simply means that multiple threads if associated with single object can prevent dirty read and write if synchronized block is used on particular object. To give you more clarity , lets take an example :

class MyRunnable implements Runnable {
    int var = 10;
    @Override
    public void run() {
        call();
    }

    public void call() {
        synchronized (this) {
            for (int i = 0; i < 4; i++) {
                var++;
                System.out.println("Current Thread " + Thread.currentThread().getName() + " var value "+var);
            }
        }
    }
}

public class MutlipleThreadsRunnable {
    public static void main(String[] args) {
        MyRunnable runnable1 = new MyRunnable();
        MyRunnable runnable2 = new MyRunnable();
        Thread t1 = new Thread(runnable1);
        t1.setName("Thread -1");
        Thread t2 = new Thread(runnable2);
        t2.setName("Thread -2");
        Thread t3 = new Thread(runnable1);
        t3.setName("Thread -3");
        t1.start();
        t2.start();
        t3.start();
    }
}

We've created two MyRunnable class objects , runnable1 being shared with thread 1 and thread 3 & runnable2 being shared with thread 2 only. Now when t1 and t3 starts without synchronized being used , PFB output which suggest that both threads 1 and 3 simultaneously affecting var value where for thread 2 , var has its own memory.

Without Synchronized keyword

    Current Thread Thread -1 var value 11
    Current Thread Thread -2 var value 11
    Current Thread Thread -2 var value 12
    Current Thread Thread -2 var value 13
    Current Thread Thread -2 var value 14
    Current Thread Thread -1 var value 12
    Current Thread Thread -3 var value 13
    Current Thread Thread -3 var value 15
    Current Thread Thread -1 var value 14
    Current Thread Thread -1 var value 17
    Current Thread Thread -3 var value 16
    Current Thread Thread -3 var value 18

Using Synchronzied, thread 3 waiting for thread 1 to complete in all scenarios. There are two locks acquired , one on runnable1 shared by thread 1 and thread 3 and another on runnable2 shared by thread 2 only.

Current Thread Thread -1 var value 11
Current Thread Thread -2 var value 11
Current Thread Thread -1 var value 12
Current Thread Thread -2 var value 12
Current Thread Thread -1 var value 13
Current Thread Thread -2 var value 13
Current Thread Thread -1 var value 14
Current Thread Thread -2 var value 14
Current Thread Thread -3 var value 15
Current Thread Thread -3 var value 16
Current Thread Thread -3 var value 17
Current Thread Thread -3 var value 18

How do I find the data directory for a SQL Server instance?

You can find default Data and Log locations for the current SQL Server instance by using the following T-SQL:

DECLARE @defaultDataLocation nvarchar(4000)
DECLARE @defaultLogLocation nvarchar(4000)

EXEC master.dbo.xp_instance_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\MSSQLServer',
    N'DefaultData', 
    @defaultDataLocation OUTPUT

EXEC master.dbo.xp_instance_regread
    N'HKEY_LOCAL_MACHINE',
    N'Software\Microsoft\MSSQLServer\MSSQLServer',
    N'DefaultLog', 
    @defaultLogLocation OUTPUT

SELECT @defaultDataLocation AS 'Default Data Location',
       @defaultLogLocation AS 'Default Log Location'

CSS media query to target only iOS devices

Short answer No. CSS is not specific to brands.

Below are the articles to implement for iOS using media only.

https://css-tricks.com/snippets/css/media-queries-for-standard-devices/

http://stephen.io/mediaqueries/

Infact you can use PHP, Javascript to detect the iOS browser and according to that you can call CSS file. For instance

http://www.kevinleary.net/php-detect-ios-mobile-users/

How can I connect to MySQL on a WAMP server?

Just Change the Connection mysql string to 127.0.0.1 and it will work

In a URL, should spaces be encoded using %20 or +?

This confusion is because URL is still 'broken' to this day

Take "http://www.google.com" for instance. This is a URL. A URL is a Uniform Resource Locator and is really a pointer to a web page (in most cases). URLs actually have a very well-defined structure since the first specification in 1994.

We can extract detailed information about the "http://www.google.com" URL:

+---------------+-------------------+   
|      Part     |      Data         |   
+---------------+-------------------+   
|  Scheme       | http              |   
|  Host address | www.google.com    |   
+---------------+-------------------+  

If we look at a more complex URL such as "https://bob:[email protected]:8080/file;p=1?q=2#third" we can extract the following information:

+-------------------+---------------------+
|        Part       |       Data          |
+-------------------+---------------------+
|  Scheme           | https               |
|  User             | bob                 |
|  Password         | bobby               |
|  Host address     | www.lunatech.com    |
|  Port             | 8080                |
|  Path             | /file               |
|  Path parameters  | p=1                 |
|  Query parameters | q=2                 |
|  Fragment         | third               |
+-------------------+---------------------+

The reserved characters are different for each part

For HTTP URLs, a space in a path fragment part has to be encoded to "%20" (not, absolutely not "+"), while the "+" character in the path fragment part can be left unencoded.

Now in the query part, spaces may be encoded to either "+" (for backwards compatibility: do not try to search for it in the URI standard) or "%20" while the "+" character (as a result of this ambiguity) has to be escaped to "%2B".

This means that the "blue+light blue" string has to be encoded differently in the path and query parts: "http://example.com/blue+light%20blue?blue%2Blight+blue". From there you can deduce that encoding a fully constructed URL is impossible without a syntactical awareness of the URL structure.

What this boils down to is

you should have %20 before the ? and + after

Source

TypeError: can only concatenate list (not "str") to list

That's not how to add an item to a string. This:

newinv=inventory+str(add)

Means you're trying to concatenate a list and a string. To add an item to a list, use the list.append() method.

inventory.append(add) #adds a new item to inventory
print(inventory) #prints the new inventory

Hope this helps!

How to send characters in PuTTY serial communication only when pressing enter?

The settings you need are "Local echo" and "Line editing" under the "Terminal" category on the left.

To get the characters to display on the screen as you enter them, set "Local echo" to "Force on".

To get the terminal to not send the command until you press Enter, set "Local line editing" to "Force on".

PuTTY Line discipline options

Explanation:

From the PuTTY User Manual (Found by clicking on the "Help" button in PuTTY):

4.3.8 ‘Local echo’

With local echo disabled, characters you type into the PuTTY window are not echoed in the window by PuTTY. They are simply sent to the server. (The server might choose to echo them back to you; this can't be controlled from the PuTTY control panel.)

Some types of session need local echo, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local echo is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local echo to be turned on, or force it to be turned off, instead of relying on the automatic detection.

4.3.9 ‘Local line editing’ Normally, every character you type into the PuTTY window is sent immediately to the server the moment you type it.

If you enable local line editing, this changes. PuTTY will let you edit a whole line at a time locally, and the line will only be sent to the server when you press Return. If you make a mistake, you can use the Backspace key to correct it before you press Return, and the server will never see the mistake.

Since it is hard to edit a line locally without being able to see it, local line editing is mostly used in conjunction with local echo (section 4.3.8). This makes it ideal for use in raw mode or when connecting to MUDs or talkers. (Although some more advanced MUDs do occasionally turn local line editing on and turn local echo off, in order to accept a password from the user.)

Some types of session need local line editing, and many do not. In its default mode, PuTTY will automatically attempt to deduce whether or not local line editing is appropriate for the session you are working in. If you find it has made the wrong decision, you can use this configuration option to override its choice: you can force local line editing to be turned on, or force it to be turned off, instead of relying on the automatic detection.

Putty sometimes makes wrong choices when "Auto" is enabled for these options because it tries to detect the connection configuration. Applied to serial line, this is a bit trickier to do.

How to view user privileges using windows cmd?

Use whoami /priv command to list all the user privileges.

Swift addsubview and remove it

Thanks for help. This is the solution: I created the subview and i add a gesture to remove it

@IBAction func infoView(sender: UIButton) {
    var testView: UIView = UIView(frame: CGRectMake(0, 0, 320, 568))
    testView.backgroundColor = UIColor.blueColor()
    testView.alpha = 0.5
    testView.tag = 100
    testView.userInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = "removeSubview"
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    println("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        println("No!")
    }
}

Update:

Swift 3+

@IBAction func infoView(sender: UIButton) {
    let testView: UIView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
    testView.backgroundColor = .blue
    testView.alpha = 0.5
    testView.tag = 100
    testView.isUserInteractionEnabled = true
    self.view.addSubview(testView)

    let aSelector : Selector = #selector(GasMapViewController.removeSubview)
    let tapGesture = UITapGestureRecognizer(target:self, action: aSelector)
    testView.addGestureRecognizer(tapGesture)
}

func removeSubview(){
    print("Start remove sibview")
    if let viewWithTag = self.view.viewWithTag(100) {
        viewWithTag.removeFromSuperview()
    }else{
        print("No!")
    }
}

Converting dictionary to JSON

Defining r as a dictionary should do the trick:

>>> r: dict = {'is_claimed': 'True', 'rating': 3.5}
>>> print(r['rating'])
3.5
>>> type(r)
<class 'dict'>

How to remove elements from a generic list while iterating over it?

Just wanted to add my 2 cents to this in case this helps anyone, I had a similar problem but needed to remove multiple elements from an array list while it was being iterated over. the highest upvoted answer did it for me for the most part until I ran into errors and realized that the index was greater than the size of the array list in some instances because multiple elements were being removed but the index of the loop didn't keep track of that. I fixed this with a simple check:

ArrayList place_holder = new ArrayList();
place_holder.Add("1");
place_holder.Add("2");
place_holder.Add("3");
place_holder.Add("4");

for(int i = place_holder.Count-1; i>= 0; i--){
    if(i>= place_holder.Count){
        i = place_holder.Count-1; 
    }

// some method that removes multiple elements here
}

Injection of autowired dependencies failed;

public class Organization {

    @Id
    @Column(name="org_id")
    @GeneratedValue
    private int id;

    @Column(name="org_name")
    private String name;

    @Column(name="org_office_address1")
    private String address1;

    @Column(name="org_office_addres2")
    private String address2;

    @Column(name="city")
    private String city;

    @Column(name="state")
    private String state;

    @Column(name="country")
    private String country;

    @JsonIgnore
    @OneToOne
    @JoinColumn(name="pkg_id")
    private int pkgId;

    public int getPkgId() {
        return pkgId;
    }

    public void setPkgId(int pkgId) {
        this.pkgId = pkgId;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    @Column(name="pincode")
    private String pincode;

    @OneToMany(mappedBy = "organization", cascade=CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<OrganizationBranch> organizationBranch = new HashSet<OrganizationBranch>(0);

    @Column(name="status")
    private String status = "ACTIVE";

    @Column(name="project_id")
    private int redmineProjectId;

    public int getRedmineProjectId() {
        return redmineProjectId;
    }

    public void setRedmineProjectId(int redmineProjectId) {
        this.redmineProjectId = redmineProjectId;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public Set<OrganizationBranch> getOrganizationBranch() {
        return organizationBranch;
    }

    public void setOrganizationBranch(Set<OrganizationBranch> organizationBranch) {
        this.organizationBranch = organizationBranch;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress1() {
        return address1;
    }

    public void setAddress1(String address1) {
        this.address1 = address1;
    }

    public String getAddress2() {
        return address2;
    }

    public void setAddress2(String address2) {
        this.address2 = address2;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getState() {
        return state;
    }

    public void setState(String state) {
        this.state = state;
    }

    public String getPincode() {
        return pincode;
    }

    public void setPincode(String pincode) {
        this.pincode = pincode;
    }
}

You change the private int pkgId line in change datatype int to primitive class name or add annotation @autowired

How to pass parameters to ThreadStart method in Thread?

Look at this example:

public void RunWorker()
{
    Thread newThread = new Thread(WorkerMethod);
    newThread.Start(new Parameter());
}

public void WorkerMethod(object parameterObj)
{
    var parameter = (Parameter)parameterObj;
    // do your job!
}

You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.

So in your case you should use it like this:

    Thread thread = new Thread(download);
    thread.Start(filename);

But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

JSLint is suddenly reporting: Use the function form of "use strict"

I'd suggest to use jshint instead.

It allows to suppress this warning via /*jshint globalstrict: true*/.

If you are writing a library, I would only suggest using global strict if your code is encapsulated into modules as is the case with nodejs.

Otherwise you'd force everyone who is using your library into strict mode.

Adding Python Path on Windows 7

For anyone trying to achieve this with Python 3.3+, the Windows installer now includes an option to add python.exe to the system search path. Read more in the docs.

href="tel:" and mobile numbers

The BlackBerry browser and Safari for iOS (iPhone/iPod/iPad) automatically detect phone numbers and email addresses and convert them to links. If you don’t want this feature, you should use the following meta tags.

For Safari:

<meta name="format-detection" content="telephone=no">

For BlackBerry:

<meta http-equiv="x-rim-auto-match" content="none">

Source: mobilexweb.com

Git add all subdirectories

You can also face problems if a subdirectory itself is a git repository - ie .has a .git directory - check with ls -a.

To remove go to the subdirectory and rm .git -rf.

How do I calculate the MD5 checksum of a file in Python?

You can calculate the checksum of a file by reading the binary data and using hashlib.md5().hexdigest(). A function to do this would look like the following:

def File_Checksum_Dis(dirname):
    
    if not os.path.exists(dirname):
        print(dirname+" directory is not existing");
    
    for fname in os.listdir(dirname):
        if not fname.endswith('~'):
            fnaav = os.path.join(dirname, fname);
            fd = open(fnaav, 'rb');
            data = fd.read();
            fd.close();
        
            print("-"*70);
            print("File Name is: ",fname);          
            print(hashlib.md5(data).hexdigest())
            print("-"*70);
                

Make an existing Git branch track a remote branch?

In a somewhat related way I was trying to add a remote tracking branch to an existing branch, but did not have access to that remote repository on the system where I wanted to add that remote tracking branch on (because I frequently export a copy of this repo via sneakernet to another system that has the access to push to that remote). I found that there was no way to force adding a remote branch on the local that hadn't been fetched yet (so local did not know that the branch existed on the remote and I would get the error: the requested upstream branch 'origin/remotebranchname' does not exist).

In the end I managed to add the new, previously unknown remote branch (without fetching) by adding a new head file at .git/refs/remotes/origin/remotebranchname and then copying the ref (eyeballing was quickest, lame as it was ;-) from the system with access to the origin repo to the workstation (with the local repo where I was adding the remote branch on).

Once that was done, I could then use git branch --set-upstream-to=origin/remotebranchname

Java - Check if input is a positive integer, negative integer, natural number and so on.

If you really have to avoid operators then use Math.signum()

Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.

EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:

Integer.signum(int i)

mysql datatype for telephone number and address

I usually store phone numbers as a BIGINT in E164 format.

E164 never start with a 0, with the first few digits being the country code.

+441234567890
+44 (0)1234 567890
01234 567890

etc. would be stored as 441234567890.

PHP Get all subdirectories of a given directory

The following recursive function returns an array with the full list of sub directories

function getSubDirectories($dir)
{
    $subDir = array();
    $directories = array_filter(glob($dir), 'is_dir');
    $subDir = array_merge($subDir, $directories);
    foreach ($directories as $directory) $subDir = array_merge($subDir, getSubDirectories($directory.'/*'));
    return $subDir;
}

Source: https://www.lucidar.me/en/web-dev/how-to-get-subdirectories-in-php/

Contain an image within a div?

Since you don't want stretching (all of the other answers ignore that) you can simply set max-width and max-height like in my jsFiddle edit.

#container img {
    max-height: 250px;
    max-width: 250px;
} 

See my example with an image that isn't a square, it doesn't stretch

How can I turn a string into a list in Python?

The list() function [docs] will convert a string into a list of single-character strings.

>>> list('hello')
['h', 'e', 'l', 'l', 'o']

Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:

>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'

You can also loop over the characters in the string as you can loop over the elements of a list:

>>> for c in 'hello':
...     print c + c,
... 
hh ee ll ll oo

How to add label in chart.js for pie chart

It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.

var optionsPie = {
    tooltipTemplate: "<%= label %> - <%= value %>"
}

If you want the tooltip to be always shown you can make some other edits to the options:

 var optionsPie = {
        tooltipEvents: [],
        showTooltips: true,
        onAnimationComplete: function() {
            this.showTooltip(this.segments, true);
        },
        tooltipTemplate: "<%= label %> - <%= value %>"
    }

In your data items, you have to add the desired label property and value and that's all.

data = [
    {
        value: 480000,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Tobacco"
    }
];

Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie) and you are done.

This probably works best for pies which are not very small in size.

Pie chart with labels

Controller 'ngModel', required by directive '...', can't be found

You can also remove the line

  require: 'ngModel',

if you don't need ngModel in this directive. Removing ngModel will allow you to make a directive without thatngModel error.

Execute a large SQL script (with GO commands)

I hit this same issue and eventually just solved it by a simple string replace, replacing the word GO with a semi-colon (;)

All seems to be working fine while executing scripts with in-line comments, block comments, and GO commands

public static bool ExecuteExternalScript(string filePath)
{
    using (StreamReader file = new StreamReader(filePath))
    using (SqlConnection conn = new SqlConnection(dbConnStr))
    {
        StringBuilder sql = new StringBuilder();

        string line;
        while ((line = file.ReadLine()) != null)
        {
            // replace GO with semi-colon
            if (line == "GO")
                sql.Append(";");
            // remove inline comments
            else if (line.IndexOf("--") > -1)
                sql.AppendFormat(" {0} ", line.Split(new string[] { "--" }, StringSplitOptions.None)[0]);
            // just the line as it is
            else
                sql.AppendFormat(" {0} ", line);
        }
        conn.Open();

        SqlCommand cmd = new SqlCommand(sql.ToString(), conn);
        cmd.ExecuteNonQuery();
    }

    return true;
}

How do I provide a username and password when running "git clone [email protected]"?

In the comments of @Bassetassen's answer, @plosco mentioned that you can use git clone https://<token>@github.com/username/repository.git to clone from GitHub at the very least. I thought I would expand on how to do that, in case anyone comes across this answer like I did while trying to automate some cloning.

GitHub has a very handy guide on how to do this, but it doesn't cover what to do if you want to include it all in one line for automation purposes. It warns that adding the token to the clone URL will store it in plaintext in .git/config. This is obviously a security risk for almost every use case, but since I plan on deleting the repo and revoking the token when I'm done, I don't care.

1. Create a Token

GitHub has a whole guide here on how to get a token, but here's the TL;DR.

  1. Go to Settings > Developer Settings > Personal Access Tokens (here's a direct link)
  2. Click "Generate a New Token" and enter your password again. (here's another direct link)
  3. Set a description/name for it, check the "repo" permission and hit the "Generate token" button at the bottom of the page.
  4. Copy your new token before you leave the page

2. Clone the Repo

Same as the command @plosco gave, git clone https://<token>@github.com/<username>/<repository>.git, just replace <token>, <username> and <repository> with whatever your info is.

If you want to clone it to a specific folder, just insert the folder address at the end like so: git clone https://<token>@github.com/<username>/<repository.git> <folder>, where <folder> is, you guessed it, the folder to clone it to! You can of course use ., .., ~, etc. here like you can elsewhere.

3. Leave No Trace

Not all of this may be necessary, depending on how sensitive what you're doing is.

  • You probably don't want to leave that token hanging around if you have no intentions of using it for some time, so go back to the tokens page and hit the delete button next to it.
  • If you don't need the repo again, delete it rm -rf <folder>.
  • If do need the repo again, but don't need to automate it again, you can remove the remote by doing git remote remove origin or just remove the token by running git remote set-url origin https://github.com/<username>/<repository.git>.
  • Clear your bash history to make sure the token doesn't stay logged there. There are many ways to do this, see this question and this question. However, it may be easier to just prepend all the above commands with a space in order to prevent them being stored to begin with.

Note that I'm no pro, so the above may not be secure in the sense that no trace would be left for any sort of forensic work.

How to subtract hours from a date in Oracle so it affects the day also

date - n will subtract n days form given date. In order to subtract hrs you need to convert it into day buy dividing it with 24. In your case it should be to_char(sysdate - (2 + 2/24), 'MM-DD-YYYY HH24'). This will subract 2 days and 2 hrs from sysdate.

Simulating Key Press C#

Simple one, add before Main

[DllImport("USER32.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);
[DllImport("USER32.DLL")]
public static extern bool SetForegroundWindow(IntPtr hWnd);

Code inside Main/Method:

string className = "IEFrame";
string windowName = "New Tab - Windows Internet Explorer";
IntPtr IE = FindWindow(className, windowName);
if (IE == IntPtr.Zero)
{
   return;
}
SetForegroundWindow(IE);
InputSimulator.SimulateKeyPress(VirtualKeyCode.F5);

Note:

  1. Add InputSimulator as reference. To download Click here

  2. To find Class & Window name, use WinSpy++. To download Click here

Check if character is number?

function is_numeric(mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') &&
        mixed_var !== '' && !isNaN(mixed_var);
}

Source code

No Main class found in NetBeans

In the toolbar search for press the arrow and select Customize... It will open project properties.In the categories select RUN. Look for Main Class. Clear all the Main Class character and type your class name. Click on OK. And run again. The problem is solved.

How to install beautiful soup 4 with python 2.7 on windows

I feel most people have pip installed already with Python. On Windows, one way to check for pip is to open Command Prompt and typing in:

python -m pip

If you get Usage and Commands instructions then you have it installed. If python was not found though, then it needs to be added to the path. Alternatively you can run the same command from within the installation directory of python.

If all is good, then this command will install BeautifulSoup easily:

python -m pip install BeautifulSoup4

Screenshot:

Installing very very beautiful soup

N' now I see I need to upgrade my pip, which I just did :)

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Try this in the .htaccess of the external root folder

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Be careful on : Header add Access-Control-Allow-Origin "*" This is not judicious at all to grant access to everybody. I think you should user:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://example.com"
</IfModule>

How to insert multiple rows from array using CodeIgniter framework?

I have created this simple function which you guys can use easily. You will need to pass the table-name ($tbl), table-field ($insertFieldsArr) against your inserting data, data array ($arr).

insert_batch('table',array('field1','field2'),$dataArray);

    function insert_batch($tbl,$insertFieldsArr,$arr){ $sql = array(); 
    foreach( $arr as $row ) {
        $strVals='';
        $cnt=0;
        foreach($insertFieldsArr as $key=>$val){
            if(is_array($row)){
                $strVals.="'".mysql_real_escape_string($row[$cnt]).'\',';
            }
            else{
                $strVals.="'".mysql_real_escape_string($row).'\',';
            }
            $cnt++;
        }
        $strVals=rtrim($strVals,',');
        $sql[] = '('.$strVals.')';
    }

    $fields=implode(',',$insertFieldsArr);
    mysql_query('INSERT INTO `'.$tbl.'` ('.$fields.') VALUES '.implode(',', $sql));
}

How to get cumulative sum

Once the table is created -

select 
    A.id, A.SomeNumt, SUM(B.SomeNumt) as sum
    from @t A, @t B where A.id >= B.id
    group by A.id, A.SomeNumt

order by A.id

Auto refresh page every 30 seconds

Use setInterval instead of setTimeout. Though in this case either will be fine but setTimeout inherently triggers only once setInterval continues indefinitely.

<script language="javascript">
setInterval(function(){
   window.location.reload(1);
}, 30000);
</script>

Replace given value in vector

Another simpler option is to do:

 > x = c(1, 1, 2, 4, 5, 2, 1, 3, 2)
 > x[x==1] <- 0
 > x
 [1] 0 0 2 4 5 2 0 3 2

Can't use modulus on doubles?

Use fmod() from <cmath>. If you do not want to include the C header file:

template<typename T, typename U>
constexpr double dmod (T x, U mod)
{
    return !mod ? x : x - mod * static_cast<long long>(x / mod);
}

//Usage:
double z = dmod<double, unsigned int>(14.3, 4);
double z = dmod<long, float>(14, 4.6);
//This also works:
double z = dmod(14.7, 0.3);
double z = dmod(14.7, 0);
double z = dmod(0, 0.3f);
double z = dmod(myFirstVariable, someOtherVariable);

PL/SQL block problem: No data found error

Might be worth checking online for the errata section for your book.

There's an example of handling this exception here http://www.dba-oracle.com/sf_ora_01403_no_data_found.htm

Entity framework left join

If UserGroups has a one to many relationship with UserGroupPrices table, then in EF, once the relationship is defined in code like:

//In UserGroups Model
public List<UserGroupPrices> UserGrpPriceList {get;set;}

//In UserGroupPrices model
public UserGroups UserGrps {get;set;}

You can pull the left joined result set by simply this:

var list = db.UserGroupDbSet.ToList();

assuming your DbSet for the left table is UserGroupDbSet, which will include the UserGrpPriceList, which is a list of all associated records from the right table.

C compile : collect2: error: ld returned 1 exit status

This issue appears when you have a running console at the time you try to run other (or the same) program.

I had this problem during executing a program on Sublime Text while I had another one running on DevC++ already.