Programs & Examples On #Visual studio 6

Visual Studio 6.0 is a Microsoft IDE released in 1998

Visual Studio 6 Windows Common Controls 6.0 (sp6) Windows 7, 64 bit

I had the same problem running windows 7-64 with VB6. I tried the unregister and re-register solutions above but it did not solve the problem. Then I noticed that in my VB6 Components I had references to both the Microsoft Windows Common Controls -2 6.0(SP6) and Microsoft Windows Common Controls -3 6.0(SP5). I removed the SP5 reference and all now works OK. It seems that -2 6.0 SP6 supersedes -3 6.0 (SP5) and when both are present there are two references to the same control. Hope this helps. Steve

Error: ANDROID_HOME is not set and "android" command not in your PATH. You must fulfill at least one of these conditions.

For Windows I just had to add an env variable pointing to the SDK folder. Done! (The accepted answer didn´t work for me)

enter image description here

Prevent HTML5 video from being downloaded (right-click saved)?

Short Answer: Encrypt the link like youtube does, don't know how than ask youtube/google of how they do it. (Just in case you want to get straight into the point.)

I would like to point out to anyone that this is possible because youtube does it and if they can so can any other website and it isn't from the browser either because I tested it on a couple browsers such as microsoft edge and internet explorer and so there is a way to disable it and seen that people still say it...I tries looking for an answer because if youtube can than there has to be a way and the only way to see how they do it is if someone looked into the scripts of youtube which I am doing now. I also checked to see if it was a custom context menu as well and it isn't because the context menu is over flowing the inspect element and I mean like it is over it and I looked and it never creates a new class and also it is impossible to actually access inspect element with javascript so it can't be. You can tell when it double right-click a youtube video that it pops up the context menu for chrome. Besides...youtube wouldn't add that function in. I am doing research and looking through the source of youtube so I will be back if I find the answer...if anyone says you can't than, well they didn't do research like I have. The only way to download youtube videos is through a video download.

Okay...I did research and my research stays that you can disable it except there is no javascript to it...you have to be able to encrypt the links to the video for you to be able to disable it because I think any browser won't show it if it can't find it and when I opened a youtube video link it showed as this "blob:https://www.youtube.com/e5c4808e-297e-451f-80da-3e838caa1275" without quotes so it is encrypting it so it cannot be saved...you need to know php for that but like the answer you picked out of making it harder, youtube makes it the hardest of heavy encrypting it, you need to be an advance php programmer but if you don't know that than take the person you picked as best answer of making it hard to download it...but if you know php than heavy encrypt the video link so it only is able to be read on yours...I don't know how to explain how they do it but they did and there is a way. The way youtube Encrypts there videos is quite smart so if you want to know how to than just ask youtube/google of how they do it...hope this helps for you although you already picked a best answer. So encrypting the link is best in short terms.

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

Media Queries - In between two widths

_x000D_
_x000D_
.class {_x000D_
    display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
    .class {_x000D_
        display: block; /* just an example display property */_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

How can git be installed on CENTOS 5.5?

I've tried few methods from this question and they all failed on my CentOs, either because of the wrong repos or missing files.

Here is the method which works for me (when installing version 1.7.8):

    yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel
    wget http://git-core.googlecode.com/files/git-1.7.8.tar.gz
    tar -xzvf ./git-1.7.8.tar.gz
    cd ./git-1.7.8
    ./configure
    make
    make install 

You may want to download a different version from here: http://code.google.com/p/git-core/downloads/list

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

  1. you can go in File Manager check logs folder.
  2. check Log file in public_html folder.
  3. check "php phpinfo()" file where log store.

Fragment MyFragment not attached to Activity

If you extend the Application class and maintain a static 'global' Context object, as follows, then you can use that instead of the activity to load a String resource.

public class MyApplication extends Application {
    public static Context GLOBAL_APP_CONTEXT;

    @Override
    public void onCreate() {
        super.onCreate();
        GLOBAL_APP_CONTEXT = this;
    }
}

If you use this, you can get away with Toast and resource loading without worrying about lifecycles.

<select> HTML element with height

You can also "center" the text with:

vertical-align: middle;

How to check Elasticsearch cluster health?

To check on elasticsearch cluster health you need to use

curl localhost:9200/_cat/health

More on the cat APIs here.

I usually use elasticsearch-head plugin to visualize that.

You can find it's github project here.

It's easy to install sudo $ES_HOME/bin/plugin -i mobz/elasticsearch-head and then you can open localhost:9200/_plugin/head/ in your web brower.

You should have something that looks like this :

enter image description here

error_reporting(E_ALL) does not produce error

In your php.ini file check for display_errors. If it is off, then make it on as below:

display_errors = On

It should display warnings/notices/errors .

Please read this

http://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting

How to upload (FTP) files to server in a bash script?

No need to complicate stuff - this should work:

#/bin/bash
echo "
 verbose
 open ftp.mydomain.net
 user myusername mypassword
 ascii
 put textfile1
 put textfile2
 bin
 put binaryfile1
 put binaryfile2
 bye
" | ftp -n > ftp_$$.log

or you can use mput if you have many files ...

Changing project port number in Visual Studio 2013

This has proved to be elusive for me (WebSite Project) until I figured out the following procedure, which combines the solution provided by @Jimmy, with the added step of checking out the solution from Source Control

Steps: (if using VS2013+ with website project and SourceControl)

  1. Check out the Solution file only (from sourceControl) (this can be tricky. the easiest way to do this is to make a small change in the Solution file properties/settings and then undo if necessary)
  2. Locate the solution file (e.g. solution.sln) in exploer, and open in text editor.
  3. Locate the entry: VWDPort = ...... and change to desired port: (example: "60000" - depends on your IISExpress Settings)
  4. save the change (will prompt to reload solution)

Mapping many-to-many association table with extra column(s)

As said before, with JPA, in order to have the chance to have extra columns, you need to use two OneToMany associations, instead of a single ManyToMany relationship. You can also add a column with autogenerated values; this way, it can work as the primary key of the table, if useful.

For instance, the implementation code of the extra class should look like that:

@Entity
@Table(name = "USER_SERVICES")
public class UserService{

    // example of auto-generated ID
    @Id
    @Column(name = "USER_SERVICES_ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long userServiceID;



    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "USER_ID")
    private User user;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SERVICE_ID")
    private Service service;



    // example of extra column
    @Column(name="VISIBILITY")    
    private boolean visibility;



    public long getUserServiceID() {
        return userServiceID;
    }


    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Service getService() {
        return service;
    }

    public void setService(Service service) {
        this.service = service;
    }

    public boolean getVisibility() {
        return visibility;
    }

    public void setVisibility(boolean visibility) {
        this.visibility = visibility;
    }

}

Characters allowed in a URL

From here

Thus, only alphanumerics, the special characters $-_.+!*'(), and reserved characters used for their reserved purposes may be used unencoded within a URL.

What is an Endpoint?

It's one end of a communication channel, so often this would be represented as the URL of a server or service.

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

How to access a mobile's camera from a web app?

In iPhone iOS6 and from Android ICS onwards, HTML5 has the following tag which allows you to take pictures from your device:

 <input type="file" accept="image/*" capture="camera">

Capture can take values like camera, camcorder and audio.

I think this tag will definitely not work in iOS5, not sure about it.

Changing the sign of a number in PHP?

I think Gumbo's answer is just fine. Some people prefer this fancy expression that does the same thing:

$int = (($int > 0) ? -$int : $int);

EDIT: Apparently you are looking for a function that will make negatives positive as well. I think these answers are the simplest:

/* I am not proposing you actually use functions called
   "makeNegative" and "makePositive"; I am just presenting
   the most direct solution in the form of two clearly named
   functions. */
function makeNegative($num) { return -abs($num); }
function makePositive($num) { return abs($num); }

Get UTC time and local time from NSDate object

I found an easier way to get UTC in Swift4. Put this code in playground

let date = Date() 
*//"Mar 15, 2018 at 4:01 PM"*

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss ZZZ"
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)

let newDate = dateFormatter.string(from: date) 
*//"2018-03-15 21:05:04 +0000"*

ImportError in importing from sklearn: cannot import name check_build

If you use Anaconda 2.7 64 bit, try

conda upgrade scikit-learn

and restart the python shell, that works for me.

Second edit when I faced the same problem and solved it:

conda upgrade scikit-learn

also works for me

How to convert float number to Binary?

void transfer(double x) {
unsigned long long* p = (unsigned long long*)&x;
for (int i = sizeof(unsigned long long) * 8 - 1; i >= 0; i--) {cout<< ((*p) >>i & 1);}}

How can I mock an ES6 module import using Jest?

Adding more to Andreas' answer. I had the same problem with ES6 code, but I did not want to mutate the imports. That looked hacky. So I did this:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency');

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
  });
});

And added file dependency.js in the " __ mocks __" folder parallel to file dependency.js. This worked for me. Also, this gave me the option to return suitable data from the mock implementation. Make sure you give the correct path to the module you want to mock.

SQLite3 database or disk is full / the database disk image is malformed

During app development I found that the messages come from the frequent and massive INSERT and UPDATE operations. Make sure to INSERT and UPDATE multiple rows or data in one single operation.

var updateStatementString : String! = ""

for item in cardids {
    let newstring = "UPDATE "+TABLE_NAME+" SET pendingImages = '\(pendingImage)\' WHERE cardId = '\(item)\';"
    updateStatementString.append(newstring)
}

print(updateStatementString)

let results = dbManager.sharedInstance.update(updateStatementString: updateStatementString)

return Int64(results)

No newline after div?

<div style="display: inline">Is this what you meant?</div>

Vue 2 - Mutating props vue-warn

This has to do with the fact that mutating a prop locally is considered an anti-pattern in Vue 2

What you should do now, in case you want to mutate a prop locally, is to declare a field in your data that uses the props value as its initial value and then mutate the copy:

Vue.component('task', {
    template: '#task-template',
    props: ['list'],
    data: function () {
        return {
            mutableList: JSON.parse(this.list);
        }
    }
});

You can read more about this on Vue.js official guide


Note 1: Please note that you should not use the same name for your prop and data, i.e.:

data: function () { return { list: JSON.parse(this.list) } // WRONG!!

Note 2: Since I feel there is some confusion regarding props and reactivity, I suggest you to have a look on this thread

Quickly create a large file on a Linux system

One approach: if you can guarantee unrelated applications won't use the files in a conflicting manner, just create a pool of files of varying sizes in a specific directory, then create links to them when needed.

For example, have a pool of files called:

  • /home/bigfiles/512M-A
  • /home/bigfiles/512M-B
  • /home/bigfiles/1024M-A
  • /home/bigfiles/1024M-B

Then, if you have an application that needs a 1G file called /home/oracle/logfile, execute a "ln /home/bigfiles/1024M-A /home/oracle/logfile".

If it's on a separate filesystem, you will have to use a symbolic link.

The A/B/etc files can be used to ensure there's no conflicting use between unrelated applications.

The link operation is about as fast as you can get.

Create a SQL query to retrieve most recent records

Add an auto incrementing Primary Key to each record, for example, UserStatusId.

Then your query could look like this:

select * from UserStatus where UserStatusId in
(
    select max(UserStatusId) from UserStatus group by User
)

Date User Status Notes

Maven with Eclipse Juno

This is what I was getting when tried to install m2e from Eclipse Market place. I am using Eclipse Juno.

Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) To: org.eclipse.m2e.core [1.5.0.20140606-0033]

However, the below links is perfect, it works for me.

http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-juno-0

Regards, Bilal

How to check if a process is in hang state (Linux)

Is there any command in Linux through which i can know if the process is in hang state.

There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):

  • run ps to find list of PIDs of the watched processes (along with exec time, etc)
  • loop over the PIDs
  • start gdb attaching to the process using its PID, dumping stack trace from it using thread apply all where, detaching from the process
  • a process was declared hung if:
    • its stack trace didn't change and time didn't change after 3 checks
    • its stack trace didn't change and time was indicating 100% CPU load after 3 checks
  • hung process was killed to give a chance for a monitoring application to restart the hung instance.

But that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.

Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.

The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".

How to make a Python script run like a service or daemon in Linux

Use whatever service manager your system offers - for example under Ubuntu use upstart. This will handle all the details for you such as start on boot, restart on crash, etc.

[ :Unexpected operator in shell programming

POSIX sh doesn't understand == for string equality, as that is a bash-ism. Use = instead.

The other people saying that brackets aren't supported by sh are wrong, btw.

How to model type-safe enum types?

There are many ways of doing.

1) Use symbols. It won't give you any type safety, though, aside from not accepting non-symbols where a symbol is expected. I'm only mentioning it here for completeness. Here's an example of usage:

def update(what: Symbol, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case 'row => replaceRow(where, newValue)
    case 'col | 'column => replaceCol(where, newValue)
    case _ => throw new IllegalArgumentException
  }

// At REPL:   
scala> val a = unitMatrixInt(3)
a: teste7.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a('row, 1) = a.row(0)
res41: teste7.MatrixInt =
/ 1 0 0 \
| 1 0 0 |
\ 0 0 1 /

scala> a('column, 2) = a.row(0)
res42: teste7.MatrixInt =
/ 1 0 1 \
| 0 1 0 |
\ 0 0 0 /

2) Using class Enumeration:

object Dimension extends Enumeration {
  type Dimension = Value
  val Row, Column = Value
}

or, if you need to serialize or display it:

object Dimension extends Enumeration("Row", "Column") {
  type Dimension = Value
  val Row, Column = Value
}

This can be used like this:

def update(what: Dimension, where: Int, newValue: Array[Int]): MatrixInt =
  what match {
    case Row => replaceRow(where, newValue)
    case Column => replaceCol(where, newValue)
  }

// At REPL:
scala> a(Row, 2) = a.row(1)
<console>:13: error: not found: value Row
       a(Row, 2) = a.row(1)
         ^

scala> a(Dimension.Row, 2) = a.row(1)
res1: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

scala> import Dimension._
import Dimension._

scala> a(Row, 2) = a.row(1)
res2: teste.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 1 0 /

Unfortunately, it doesn't ensure that all matches are accounted for. If I forgot to put Row or Column in the match, the Scala compiler wouldn't have warned me. So it gives me some type safety, but not as much as can be gained.

3) Case objects:

sealed abstract class Dimension
case object Row extends Dimension
case object Column extends Dimension

Now, if I leave out a case on a match, the compiler will warn me:

MatrixInt.scala:70: warning: match is not exhaustive!
missing combination         Column

    what match {
    ^
one warning found

It's used pretty much the same way, and doesn't even need an import:

scala> val a = unitMatrixInt(3)
a: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 0 0 1 /

scala> a(Row,2) = a.row(0)
res15: teste3.MatrixInt =
/ 1 0 0 \
| 0 1 0 |
\ 1 0 0 /

You might wonder, then, why ever use an Enumeration instead of case objects. As a matter of fact, case objects do have advantages many times, such as here. The Enumeration class, though, has many Collection methods, such as elements (iterator on Scala 2.8), which returns an Iterator, map, flatMap, filter, etc.

This answer is essentially a selected parts from this article in my blog.

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

Is there a link to the "latest" jQuery library on Google APIs?

DO NOT USE THIS ANSWER. The URL is pointing at jQuery 1.11 (and always will).

Credits to Basic for above snippet

http://code.jquery.com/jquery-latest.min.js is the minified version, always up-to-date.

How to deal with floating point number precision in JavaScript?

You can use parseFloat() and toFixed() if you want to bypass this issue for a small operation:

a = 0.1;
b = 0.2;

a + b = 0.30000000000000004;

c = parseFloat((a+b).toFixed(2));

c = 0.3;

a = 0.3;
b = 0.2;

a - b = 0.09999999999999998;

c = parseFloat((a-b).toFixed(2));

c = 0.1;

?: ?? Operators Instead Of IF|ELSE

For [1], you can't: these operators are made to return a value, not perform operations.

The expression

a ? b : c

evaluates to b if a is true and evaluates to c if a is false.

The expression

b ?? c

evaluates to b if b is not null and evaluates to c if b is null.

If you write

return a ? b : c;

or

return b ?? c;

they will always return something.

For [2], you can write a function that returns the right value that performs your "multiple operations", but that's probably worse than just using if/else.

How to check if two arrays are equal with JavaScript?

It handle all possible stuff and even reference itself in structure of object. You can see the example at the end of code.

var deepCompare = (function() {
    function internalDeepCompare (obj1, obj2, objects) {
        var i, objPair;

        if (obj1 === obj2) {
            return true;
        }

        i = objects.length;
        while (i--) {
            objPair = objects[i];
            if (  (objPair.obj1 === obj1 && objPair.obj2 === obj2) ||
                  (objPair.obj1 === obj2 && objPair.obj2 === obj1)  ) {                          
                return true;
            }                    
        }
        objects.push({obj1: obj1, obj2: obj2});

        if (obj1 instanceof Array) {
            if (!(obj2 instanceof Array)) {
                return false;
            }

            i = obj1.length;

            if (i !== obj2.length) {
               return false; 
            }

            while (i--) {
                if (!internalDeepCompare(obj1[i], obj2[i], objects)) {
                    return false;
                }
            }
        }
        else {
            switch (typeof obj1) {
                case "object":                
                    // deal with null
                    if (!(obj2 && obj1.constructor === obj2.constructor)) {
                        return false;
                    }

                    if (obj1 instanceof RegExp) {
                        if (!(obj2 instanceof RegExp && obj1.source === obj2.source)) {
                            return false;
                        }
                    }                 
                    else if (obj1 instanceof Date) {
                        if (!(obj2 instanceof Date && obj1.getTime() === obj2.getTime())) {
                            return false;
                        }
                    } 
                    else {    
                        for (i in obj1) {
                            if (obj1.hasOwnProperty(i)) {       
                                if (!(obj2.hasOwnProperty(i) && internalDeepCompare(obj1[i], obj2[i], objects))) {
                                    return false;
                                }
                            }
                        }         
                    }
                    break;
                case "function": 
                    if (!(typeof obj2 === "function" && obj1+"" === obj2+"")) {
                        return false;
                    }
                    break;
                default:                 //deal with NaN 
                    if (obj1 !== obj2 && obj1 === obj1 && obj2 === obj2) {
                        return false;            
                    }
            }
        }

        return true;
    }

    return function (obj1, obj2) {
        return internalDeepCompare(obj1, obj2, []);    
    };
}());

/*    
var a = [a, undefined, new Date(10), /.+/, {a:2}, function(){}, Infinity, -Infinity, NaN, 0, -0, 1, [4,5], "1", "-1", "a", null],
    b = [b, undefined, new Date(10), /.+/, {a:2}, function(){}, Infinity, -Infinity, NaN, 0, -0, 1, [4,5], "1", "-1", "a", null];
deepCompare(a, b);
*/

dropping rows from dataframe based on a "not in" condition

You can use pandas.Dataframe.isin.

pandas.Dateframe.isin will return boolean values depending on whether each element is inside the list a or not. You then invert this with the ~ to convert True to False and vice versa.

import pandas as pd

a = ['2015-01-01' , '2015-02-01']

df = pd.DataFrame(data={'date':['2015-01-01' , '2015-02-01', '2015-03-01' , '2015-04-01', '2015-05-01' , '2015-06-01']})

print(df)
#         date
#0  2015-01-01
#1  2015-02-01
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

df = df[~df['date'].isin(a)]

print(df)
#         date
#2  2015-03-01
#3  2015-04-01
#4  2015-05-01
#5  2015-06-01

Changing width property of a :before css selector using JQuery

Pseudo-elements are not part of the DOM, so they can't be manipulated using jQuery or Javascript.

But as pointed out in the accepted answer, you can use the JS to append a style block which ends of styling the pseudo-elements.

QUERY syntax using cell reference

Here is working code: =QUERY(Sheet1!$A1:$B581, "select B where A = '"&A1&"'")

In this scenario I needed the interval to stay fixed and the reference value to change when I drag it.

delete word after or around cursor in VIM

The below works for Normal mode: I agree with Dan Olson's answer that you should probably be in normal mode for most deletions. More details below.

If the cursor is inside the word:
diw to delete in the word (doesn't include spaces)
daw to delete around the word (includes spaces before the next word).

If the cursor is at the start of the word, just press dw.

This can be multiplied by adding the usual numbers for movement, e.g. 2w to move forward 2 words, so d2w deletes two words.

Insert Mode ^w
The idea of using hjkl for movement in Vim is that it's more productive to keep your hands on the home row. At the end of a word ^w works great to quickly delete the word. If you've gone into insert mode, entered some text and used the arrow keys to end up in the middle of the word you've gone against the home-row philosophy.
If you're in normal mode and want to change the word you can simply use the c (change) rather than d (delete) if you'd like to completely change the word, and re-enter insert mode without having to press i to get back to typing.

How to Export-CSV of Active Directory Objects?

HI you can try this...

Try..

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation

Or

$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com"  -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer

Hope it works for you.

How to get difference between two rows for a column field?

SQL Server 2012 and up support LAG / LEAD functions to access the previous or subsequent row. SQL Server 2005 does not support this (in SQL2005 you need a join or something else).

A SQL 2012 example on this data

/* Prepare */
select * into #tmp
from
(
    select 2  as rowint,      23 as Value
    union select 3,       45
    union select 17,      10
    union select 9,       0
) x


/* The SQL 2012 query */
select rowInt, Value, LEAD(value) over (order by rowInt) - Value  
from #tmp

LEAD(value) will return the value of the next row in respect to the given order in "over" clause.

The easiest way to transform collection to array?

Alternative solution to the updated question using Java 8:

Bar[] result = foos.stream()
    .map(x -> new Bar(x))
    .toArray(size -> new Bar[size]);

"Faceted Project Problem (Java Version Mismatch)" error message

In Spring STS, Right click the project & select "Open Project", This provision do the necessary action on the background & bring the project back to work space.

Thanks & Regards Vengat Maran

Angular JS break ForEach

As far as I know, Angular doesn't provide such a function. You may want to use underscore's find() function for this (it's basically a forEach which breaks out of the loop once the function returns true).

http://underscorejs.org/#find

What does a just-in-time (JIT) compiler do?

Just In Time Compiler (JIT) :
It compiles the java bytecodes into machine instructions of that specific CPU.

For example, if we have a loop statement in our java code :

while(i<10){
    // ...
    a=a+i;
    // ...
 }

The above loop code runs for 10 times if the value of i is 0.

It is not necessary to compile the bytecode for 10 times again and again as the same instruction is going to execute for 10 times. In that case, it is necessary to compile that code only once and the value can be changed for the required number of times. So, Just In Time (JIT) Compiler keeps track of such statements and methods (as said above before) and compiles such pieces of byte code into machine code for better performance.

Another similar example , is that a search for a pattern using "Regular Expression" in a list of strings/sentences.

JIT Compiler doesn't compile all the code to machine code. It compiles code that have a similar pattern at run time.

See this Oracle documentation on Understand JIT to read more.

Blocking device rotation on mobile web pages

Simple Javascript code to make mobile browser display either in portrait or landscape..

(Even though you have to enter html code twice in the two DIVs (one for each mode), arguably this will load faster than using javascript to change the stylesheet...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Mobile Device</title>
<script type="text/javascript">
// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    if(window.orientation==0)
    {
      document.getElementById('portrait').style.display = '';
      document.getElementById('landscape').style.display = 'none';
    }
    else if(window.orientation==90)
    {
      document.getElementById('portrait').style.display = 'none';
      document.getElementById('landscape').style.display = '';
    }
}, false);
</script>
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />
</head>
<body>
<div id="portrait" style="width:100%;height:100%;font-size:20px;">Portrait</div>
<div id="landscape" style="width:100%;height:100%;font-size:20px;">Landscape</div>

<script type="text/javascript">
if(window.orientation==0)
{
  document.getElementById('portrait').style.display = '';
  document.getElementById('landscape').style.display = 'none';
}
else if(window.orientation==90)
{
  document.getElementById('portrait').style.display = 'none';
  document.getElementById('landscape').style.display = '';
}
</script>
</body>
</html>

Tested and works on Android HTC Sense and Apple iPad.

Drawing circles with System.Drawing

You should use DrawEllipse:

//
// Summary:
//     Draws an ellipse defined by a bounding rectangle specified by coordinates
//     for the upper-left corner of the rectangle, a height, and a width.
//
// Parameters:
//   pen:
//     System.Drawing.Pen that determines the color, width,
//      and style of the ellipse.
//
//   x:
//     The x-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   y:
//     The y-coordinate of the upper-left corner of the bounding rectangle that
//     defines the ellipse.
//
//   width:
//     Width of the bounding rectangle that defines the ellipse.
//
//   height:
//     Height of the bounding rectangle that defines the ellipse.
//
// Exceptions:
//   System.ArgumentNullException:
//     pen is null.
public void DrawEllipse(Pen pen, int x, int y, int width, int height);

Remove the last three characters from a string

Remove the last characters from a string

TXTB_DateofReiumbursement.Text = (gvFinance.SelectedRow.FindControl("lblDate_of_Reimbursement") as Label).Text.Remove(10)

.Text.Remove(10)// used to remove text starting from index 10 to end

ImportError: No module named - Python

from ..gen_py.lib import MyService

or

from main.gen_py.lib import MyService

Make sure you have a (at least empty) __init__.py file on each directory.

How to iterate over rows in a DataFrame in Pandas

 for ind in df.index:
     print df['c1'][ind], df['c2'][ind]

Uninstalling Android ADT

I found a solution by myself after doing some research:

  • Go to Eclipse home folder.
  • Search for 'android' => In Windows 7 you can use search bar.
  • Delete all the file related to android, which is shown in the results.
  • Restart Eclipse.
  • Install the ADT plugin again and Restart plugin.

Now everything works fine.

Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)

@GetMapping is a composed annotation that acts as a shortcut for @RequestMapping(method = RequestMethod.GET).

@GetMapping is the newer annotaion. It supports consumes

Consume options are :

consumes = "text/plain"
consumes = {"text/plain", "application/*"}

For Further details see: GetMapping Annotation

or read: request mapping variants

RequestMapping supports consumes as well

GetMapping we can apply only on method level and RequestMapping annotation we can apply on class level and as well as on method level

Loading/Downloading image from URL on Swift

For Swift-3 and above:

extension UIImageView {
  public func imageFromUrl(urlString: String) {
    if let url = URL(string: urlString) {
        let request = URLRequest(url: url)
        NSURLConnection.sendAsynchronousRequest(request as URLRequest, queue: .main, completionHandler: { (response, data, error) in
            if let imageData = data as NSData? {
                self.image = UIImage(data: imageData as Data)
            }
        })
    }
  }
}

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

For me, on Windows 7, killing the ADB server and restarting it via command line did not help. It would not start up successfully.

>adb kill-server

>adb start-server
* daemon not running. starting it now on port 5037 *
ADB server didn't ACK
* failed to start daemon *

So killing the adb.exe process via Task Manager was actually the easiest solution that case.

How can I stop redis-server?

Redis has configuration parameter pidfile (e.g. /etc/redis.conf - check redis source code), for example:

# If a pid file is specified, Redis writes it where specified at startup
# and removes it at exit.
#
# When the server runs non daemonized, no pid file is created if none is
# specified in the configuration. When the server is daemonized, the pid file
# is used even if not specified, defaulting to "/var/run/redis.pid".
#
pidfile /var/run/redis.pid

If it is set or could be set, instead of searching for process id (pid) by using ps + grep something like this could be used:

kill $(cat /var/run/redis.pid)

If required one can make redis stop script like this (adapted default redis 5.0 init.d script in redis source code):

PIDFILE=/var/run/redis.pid
if [ ! -f $PIDFILE ]
then
    echo "$PIDFILE does not exist, process is not running"
else
    PID=$(cat $PIDFILE)
    echo "Stopping ..."
    kill $PID
    while [ -x /proc/${PID} ]
    do
        echo "Waiting for Redis to shutdown ..."
        sleep 1
    done
    echo "Redis stopped"
fi

Adding Git-Bash to the new Windows Terminal

There are below things to do.

  1. Make sure your git command can be run successfully in CMD

That means you need to add git to path when install git or add it to system environment later.

enter image description here

  1. Update the config file profile.json

Open Settings, add following snippet inside the word profiles:

        { 
            "tabTitle": "Git Bash",
            "acrylicOpacity" : 0.75, 
            "closeOnExit" : true, 
            "colorScheme" : "Campbell", 
            "commandline" : "C:/Program Files/Git/bin/bash.exe --login", 
            "cursorColor" : "#FFFFFF", 
            "cursorShape" : "bar", 
            "fontFace" : "Consolas", 
            "fontSize" : 12, 
            "guid" : "{14ad203f-52cc-4110-90d6-d96e0f41b64d}", 
            "historySize" : 9001, 
            "icon": "ms-appdata:///roaming/git-bash_32px.ico",
            "name" : "Git Bash", 
            "padding" : "0, 0, 0, 0", 
            "snapOnInput" : true, 
            "useAcrylic" : true 
        }

The icon can be obtained here: git-bash_32px.ico

You can add icons for Tab to this location:

%LOCALAPPDATA%\packages\Microsoft.WindowsTerminal_8wekyb3d8bbwe\RoamingState

Put 32x32 PNG/icons in this folder, and then in profile.json you can reference the image resource with the path starting with ms-appdata:// .

Note that, please make sure the Guidis correct and it matches the corresponding correct configs.

  1. Test git bash works well in Windows Terminal

The final result is below: enter image description here

jQuery change URL of form submit

Send the data from the form:

$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
  type: "PUT"
  url: url
  dataType: "script"
  data: postData

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

I had this error when trying to use the dreadful Business Objects 4 for .Net SDK.

They ship five BusinessObjects*.dll files, but all of them are 64-bit.

To get my webpage to load, I needed to click on Tools\Options, then change this setting in VS2013:

enter image description here

What's the difference between JavaScript and JScript?

There are some code differences to be aware of.

A negative first parameter to subtr is not supported, e.g. in Javascript: "string".substr(-1) returns "g", whereas in JScript: "string".substr(-1) returns "string"

It's possible to do "string"[0] to get "s" in Javascript, but JScript doesn't support such a construct. (Actually, only modern browsers appear to support the "string"[0] construct.

How do you use $sce.trustAsHtml(string) to replicate ng-bind-html-unsafe in Angular 1.2+

JavaScript

$scope.get_pre = function(x) {
    return $sce.trustAsHtml(x);
};

HTML

<pre ng-bind-html="get_pre(html)"></pre>

Compiling and Running Java Code in Sublime Text 2

This version of JavaC.sublime-build which is edited from vijay's answer works for me on both Windows 7 and Mac for Sublime Text 3.

I edited it so Ctrl+b or command+b is sufficient for both build + run.

{
"shell_cmd": "javac -Xlint $file && java $file_base_name",
"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
"selector": "source.java",
"shell": true
}

'&&' ensures that the second part runs only when first part succeeds ie only when the class file is generated. You can find more related info here: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/ntcmds_shelloverview.mspx?mfr=true

New line in Sql Query

-- Access: 
SELECT CHR(13) & CHR(10) 

-- SQL Server: 
SELECT CHAR(13) + CHAR(10)

how to do file upload using jquery serialization

Use FormData object.It works for any type of form

$(document).on("submit", "form", function(event)
{
    event.preventDefault();
    $.ajax({
        url: $(this).attr("action"),
        type: $(this).attr("method"),
        dataType: "JSON",
        data: new FormData(this),
        processData: false,
        contentType: false,
        success: function (data, status)
        {

        },
        error: function (xhr, desc, err)
        {
            

        }
    });        

});

SQL search multiple values in same field

Yes, you can use SQL IN operator to search multiple absolute values:

SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );

If you want to use LIKE you will need to use OR instead:

SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';

Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.

How to resize image automatically on browser width resize but keep same height?

The website you linked doesn't changes the image's width but it actually cuts it off. For that it needs to be set as a background-image.

For more info about background-image look it at http://www.w3schools.com/cssref/pr_background-image.asp

Usage:

#divID {
    background-image:url(image_url);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

Match groups in Python

You could create a helper function:

def re_match_group(pattern, str, out_groups):
    del out_groups[:]
    result = re.match(pattern, str)
    if result:
        out_groups[:len(result.groups())] = result.groups()
    return result

And then use it like this:

groups = []
if re_match_group("I love (\w+)", statement, groups):
    print "He loves", groups[0]
elif re_match_group("Ich liebe (\w+)", statement, groups):
    print "Er liebt", groups[0]
elif re_match_group("Je t'aime (\w+)", statement, groups):
    print "Il aime", groups[0]

It's a little clunky, but it gets the job done.

Android Linear Layout - How to Keep Element At Bottom Of View?

DO LIKE THIS

 <LinearLayout
android:id="@+id/LinearLayouts02"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="bottom|end">

<TextView
    android:id="@+id/texts1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:layout_weight="2"
    android:text="@string/forgotpass"
    android:padding="7dp"
    android:gravity="bottom|center_horizontal"
    android:paddingLeft="10dp"
    android:layout_marginBottom="30dp"
    android:bottomLeftRadius="10dp"
    android:bottomRightRadius="50dp"
    android:fontFamily="sans-serif-condensed"
    android:textColor="@color/colorAccent"
    android:textStyle="bold"
    android:textSize="16sp"
    android:topLeftRadius="10dp"
    android:topRightRadius="10dp"
   />

</LinearLayout>

Android: ListView elements with multiple clickable buttons

This is sort of an appendage @znq's answer...

There are many cases where you want to know the row position for a clicked item AND you want to know which view in the row was tapped. This is going to be a lot more important in tablet UIs.

You can do this with the following custom adapter:

private static class CustomCursorAdapter extends CursorAdapter {

    protected ListView mListView;

    protected static class RowViewHolder {
        public TextView mTitle;
        public TextView mText;
    }

    public CustomCursorAdapter(Activity activity) {
        super();
        mListView = activity.getListView();
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // do what you need to do
    }

    @Override
    public View newView(Context context, Cursor cursor, ViewGroup parent) {
        View view = View.inflate(context, R.layout.row_layout, null);

        RowViewHolder holder = new RowViewHolder();
        holder.mTitle = (TextView) view.findViewById(R.id.Title);
        holder.mText = (TextView) view.findViewById(R.id.Text);

        holder.mTitle.setOnClickListener(mOnTitleClickListener);
        holder.mText.setOnClickListener(mOnTextClickListener);

        view.setTag(holder);

        return view;
    }

    private OnClickListener mOnTitleClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = mListView.getPositionForView((View) v.getParent());
            Log.v(TAG, "Title clicked, row %d", position);
        }
    };

    private OnClickListener mOnTextClickListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            final int position = mListView.getPositionForView((View) v.getParent());
            Log.v(TAG, "Text clicked, row %d", position);
        }
    };
}

select and echo a single field from mysql db using PHP

$eventid = $_GET['id'];
$field = $_GET['field'];
$result = mysql_query("SELECT $field FROM `events` WHERE `id` = '$eventid' ");
$row = mysql_fetch_array($result);
echo $row[$field];

but beware of sql injection cause you are using $_GET directly in a query. The danger of injection is particularly bad because there's no database function to escape identifiers. Instead, you need to pass the field through a whitelist or (better still) use a different name externally than the column name and map the external names to column names. Invalid external names would result in an error.

Format date to MM/dd/yyyy in JavaScript

All other answers don't quite solve the issue. They print the date formatted as mm/dd/yyyy but the question was regarding MM/dd/yyyy. Notice the subtle difference? MM indicates that a leading zero must pad the month if the month is a single digit, thus having it always be a double digit number.

i.e. whereas mm/dd would be 3/31, MM/dd would be 03/31.

I've created a simple function to achieve this. Notice that the same padding is applied not only to the month but also to the day of the month, which in fact makes this MM/DD/yyyy:

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
  var year = date.getFullYear();_x000D_
_x000D_
  var month = (1 + date.getMonth()).toString();_x000D_
  month = month.length > 1 ? month : '0' + month;_x000D_
_x000D_
  var day = date.getDate().toString();_x000D_
  day = day.length > 1 ? day : '0' + day;_x000D_
  _x000D_
  return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_


Update for ES2017 using String.padStart(), supported by all major browsers except IE.

_x000D_
_x000D_
function getFormattedDate(date) {_x000D_
    let year = date.getFullYear();_x000D_
    let month = (1 + date.getMonth()).toString().padStart(2, '0');_x000D_
    let day = date.getDate().toString().padStart(2, '0');_x000D_
  _x000D_
    return month + '/' + day + '/' + year;_x000D_
}
_x000D_
_x000D_
_x000D_

Cut off text in string after/before separator in powershell

$text = "test.txt ; 131 136 80 89 119 17 60 123 210 121 188 42 136 200 131 198"

$text.split(';')[1].split(' ')

Does JavaScript guarantee object property order?

As of ES2015, property order is guaranteed for certain methods that iterate over properties. but not others. Unfortunately, the methods which are not guaranteed to have an order are generally the most often used:

  • Object.keys, Object.values, Object.entries
  • for..in loops
  • JSON.stringify

But, as of ES2020, property order for these previously untrustworthy methods will be guaranteed by the specification to be iterated over in the same deterministic manner as the others, due to to the finished proposal: for-in mechanics.

Just like with the methods which have a guaranteed iteration order (like Reflect.ownKeys and Object.getOwnPropertyNames), the previously-unspecified methods will also iterate in the following order:

  • Numeric array keys, in ascending numeric order
  • All other non-Symbol keys, in insertion order
  • Symbol keys, in insertion order

This is what pretty much every implementation does already (and has done for many years), but the new proposal has made it official.

Although the current specification leaves for..in iteration order "almost totally unspecified, real engines tend to be more consistent:"

The lack of specificity in ECMA-262 does not reflect reality. In discussion going back years, implementors have observed that there are some constraints on the behavior of for-in which anyone who wants to run code on the web needs to follow.

Because every implementation already iterates over properties predictably, it can be put into the specification without breaking backwards compatibility.


There are a few weird cases which implementations currently do not agree on, and in such cases, the resulting order will continue be unspecified. For property order to be guaranteed:

Neither the object being iterated nor anything in its prototype chain is a proxy, typed array, module namespace object, or host exotic object.

Neither the object nor anything in its prototype chain has its prototype change during iteration.

Neither the object nor anything in its prototype chain has a property deleted during iteration.

Nothing in the object's prototype chain has a property added during iteration.

No property of the object or anything in its prototype chain has its enumerability change during iteration.

No non-enumerable property shadows an enumerable one.

Killing a process using Java

Try it:

String command = "killall <your_proccess>";
Process p = Runtime.getRuntime().exec(command);
p.destroy();

if the process is still alive, add:

p.destroyForcibly();

Passing Objects By Reference or Value in C#

I guess its clearer when you do it like this. I recommend downloading LinqPad to test things like this.

void Main()
{
    var Person = new Person(){FirstName = "Egli", LastName = "Becerra"};

    //Will update egli
    WontUpdate(Person);
    Console.WriteLine("WontUpdate");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateImplicitly(Person);
    Console.WriteLine("UpdateImplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");

    UpdateExplicitly(ref Person);
    Console.WriteLine("UpdateExplicitly");
    Console.WriteLine($"First name: {Person.FirstName}, Last name: {Person.LastName}\n");
}

//Class to test
public class Person{
    public string FirstName {get; set;}
    public string LastName {get; set;}

    public string printName(){
        return $"First name: {FirstName} Last name:{LastName}";
    }
}

public static void WontUpdate(Person p)
{
    //New instance does jack...
    var newP = new Person(){FirstName = p.FirstName, LastName = p.LastName};
    newP.FirstName = "Favio";
    newP.LastName = "Becerra";
}

public static void UpdateImplicitly(Person p)
{
    //Passing by reference implicitly
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

public static void UpdateExplicitly(ref Person p)
{
    //Again passing by reference explicitly (reduntant)
    p.FirstName = "Favio";
    p.LastName = "Becerra";
}

And that should output

WontUpdate

First name: Egli, Last name: Becerra

UpdateImplicitly

First name: Favio, Last name: Becerra

UpdateExplicitly

First name: Favio, Last name: Becerra

No Exception while type casting with a null in java

This is very handy when using a method that would otherwise be ambiguous. For example: JDialog has constructors with the following signatures:

JDialog(Frame, String, boolean, GraphicsConfiguration)
JDialog(Dialog, String, boolean, GraphicsConfiguration)

I need to use this constructor, because I want to set the GraphicsConfiguration, but I have no parent for this dialog, so the first argument should be null. Using

JDialog(null, String, boolean, Graphicsconfiguration) 

is ambiguous, so in this case I can narrow the call by casting null to one of the supported types:

JDialog((Frame) null, String, boolean, GraphicsConfiguration)

Changing navigation title programmatically

In Swift 4:

Swift 4

override func viewDidLoad() {
    super.viewDidLoad()

    self.title = "Your title"
}

I hope it helps, regards!

How do I use CMake?

Cmake from Windows terminal:

mkdir build
cd build/
cmake ..
cmake --build . --config Release
./Release/main.exe

Clang vs GCC - which produces faster binaries?

Phoronix did some benchmarks about this, but it is about a snapshot version of Clang/LLVM from a few months back. The results being that things were more-or-less a push; neither GCC nor Clang is definitively better in all cases.

Since you'd use the latest Clang, it's maybe a little less relevant. Then again, GCC 4.6 is slated to have some major optimizations for Core 2 and i7, apparently.

I figure Clang's faster compilation speed will be nicer for original developers, and then when you push the code out into the world, Linux distro/BSD/etc. end-users will use GCC for the faster binaries.

Populating a dictionary using for loops (python)

>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

iOS Remote Debugging

You cannot directly remote debug Chrome on iOS currently. It uses a uiWebView that may act subtly different than Mobile Safari.

You have a few options.

Option 1: Remote-debug Mobile Safari using Safari's inspector. If your issue reproduces in Mobile Safari, this is definitely the best way to go. In fact, going through the iOS simulator is even easier.

Option 2: Use Weinre for a slimmed down debugging experience. Weinre doesn't have much features but sometimes it's good enough.

Option 3: Remote debug a proper uiWebView that functions the same.

Here's the best way to do this. You'll need to install XCode.

  1. Go to github.com/paulirish/iOS-WebView-App and "Download Zip" or clone.
  2. Open XCode, open existing project, and choose the project you just downloaded.
  3. Open WebViewAppDelegate.m and change the urlString to be the URL you want to test.
  4. Run the app in the iOS Simulator.
  5. Open Safari, Open the Develop Menu, Choose iOS Simulator and select your webview.
  6. Safari Inspector will now be inspecting your uiWebView.

enter image description here

enter image description here

enter image description here

SQL Server : error converting data type varchar to numeric

There's no guarantee that SQL Server won't attempt to perform the CONVERT to numeric(20,0) before it runs the filter in the WHERE clause.

And, even if it did, ISNUMERIC isn't adequate, since it recognises £ and 1d4 as being numeric, neither of which can be converted to numeric(20,0).(*)

Split it into two separate queries, the first of which filters the results and places them in a temp table or table variable, the second of which performs the conversion. (Subqueries and CTEs are inadequate to prevent the optimizer from attempting the conversion before the filter)

For your filter, probably use account_code not like '%[^0-9]%' instead of ISNUMERIC.


(*) ISNUMERIC answers the question that no-one (so far as I'm aware) has ever wanted to ask - "can this string be converted to any of the numeric datatypes - I don't care which?" - when obviously, what most people want to ask is "can this string be converted to x?" where x is a specific target datatype.

How do I disable form resizing for users?

Use the FormBorderStyle property of your Form:

this.FormBorderStyle = FormBorderStyle.FixedDialog;

Swift Error: Editor placeholder in source file

Sometimes, XCode does not forget the line which had an "Editor Placeholder" even if you have replaced it with a value. Cut the portion of the code where XCode is complaining and paste the code back to the same place to make the error message go away. This worked for me.

How can I send a file document to the printer and have it print?

I know the tag says Windows Forms... but, if anyone is interested in a WPF application method, System.Printing works like a charm.

var file = File.ReadAllBytes(pdfFilePath);
var printQueue = LocalPrintServer.GetDefaultPrintQueue();

using (var job = printQueue.AddJob())
using (var stream = job.JobStream)
{
    stream.Write(file, 0, file.Length);
}

Just remember to include System.Printing reference, if it's not already included. Now, this method does not play well with ASP.NET or Windows Service. It should not be used with Windows Forms, as it has System.Drawing.Printing. I don't have a single issue with my PDF printing using the above code.

I should mention, however, that if your printer does not support Direct Print for PDF file format, you're out of luck with this method.

Logging best practices

We use Log4Net at work as the logging provider, with a singleton wrapper for the log instance (although the singleton is under review, questioning whether they are a good idea or not).

We chose it for the following reasons:

  • Simple configuration/ reconfiguration on various environments
  • Good number of pre-built appenders
  • One of the CMS's we use already had it built in
  • Nice number of log levels and configurations around them

I should mention, this is speaking from an ASP.NET development point of view

I can see some merits in using the Trace that is in the .NET framework but I'm not entirely sold on it, mainly because the components I work with don't really do any Trace calls. The only thing that I frequently use that does is System.Net.Mail from what I can tell.

So we have a library which wraps log4net and within our code we just need stuff like this:

Logger.Instance.Warn("Something to warn about");
Logger.Instance.Fatal("Something went bad!", new Exception());

try {
  var i = int.Parse("Hello World");
} catch(FormatException, ex) {
  Logger.Instance.Error(ex);
}

Within the methods we do a check to see if the logging level is enabled, so you don't have redundant calls to the log4net API (so if Debug isn't enabled, the debug statements are ignored), but when I get some time I'll be updating it to expose those so that you can do the checks yourself. This will prevent evaluations being undertaken when they shouldn't, eg:

Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);

This will become:

if(Logger.DebugEnabled) Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);

(Save a bit of execusion time)

By default we log at two locations:

  1. File system of the website (in a non-served file extension)
  2. Email sending for Error & Fatal

Files are done as rolling of each day or 10mb (IIRC). We don't use the EventLog as it can require higher security than we often want to give a site.

I find Notepad works just fine for reading logs.

"No Content-Security-Policy meta tag found." error in my phonegap application

For me it was enough to reinstall whitelist plugin:

cordova plugin remove cordova-plugin-whitelist

and then

cordova plugin add cordova-plugin-whitelist

It looks like updating from previous versions of Cordova was not succesful.

How to create text file and insert data to that file on Android

Using this code you can write to a text file in the SDCard. Along with it, you need to set a permission in the Android Manifest.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

This is the code :

public void generateNoteOnSD(Context context, String sFileName, String sBody) {
    try {
        File root = new File(Environment.getExternalStorageDirectory(), "Notes");
        if (!root.exists()) {
            root.mkdirs();
        }
        File gpxfile = new File(root, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();
        Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Before writing files you must also check whether your SDCard is mounted & the external storage state is writable.

Environment.getExternalStorageState()

Unprotect workbook without password

No longer works for spreadsheets Protected with Excel 2013 or later -- they improved the pw hash. So now need to unzip .xlsx and hack the internals.

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

This code works for me with IE8 and Firefox

<td>
    <textarea style="width:100%" rows=3 name="abc">Modify width:% accordingly</textarea>
</td>

how to set default main class in java?

You can set the Main-Class attribute in the jar file's manifest to point to which file you want to run automatically.

how to open a page in new tab on button click in asp.net?

You can add to your button OnClientClick like so:

<asp:Button ID="" runat="Server" Text="" OnClick="btnNewEntry_Click" OnClientClick="target ='_blank';"/>

This will change the current form's target for all buttons to open in new tab. So to complete the fix you can then use 2 approaches:

  1. For any other button in this form, add to client click a "reset form target" function like so:
function ResetTarget() {
   window.document.forms[0].target = '';
}
  1. Add the same code inside the function inside a setTimeout() so the code will reset the form's target after few moments. See this answer https://stackoverflow.com/a/40682253/8445364

Adding header for HttpURLConnection

I have used the following code in the past and it had worked with basic authentication enabled in TomCat:

URL myURL = new URL(serviceURL);
HttpURLConnection myURLConnection = (HttpURLConnection)myURL.openConnection();

String userCredentials = "username:password";
String basicAuth = "Basic " + new String(Base64.getEncoder().encode(userCredentials.getBytes()));

myURLConnection.setRequestProperty ("Authorization", basicAuth);
myURLConnection.setRequestMethod("POST");
myURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
myURLConnection.setRequestProperty("Content-Length", "" + postData.getBytes().length);
myURLConnection.setRequestProperty("Content-Language", "en-US");
myURLConnection.setUseCaches(false);
myURLConnection.setDoInput(true);
myURLConnection.setDoOutput(true);

You can try the above code. The code above is for POST, and you can modify it for GET

How do I parse JSON in Android?

  1. Writing JSON Parser Class

    public class JSONParser {
    
        static InputStream is = null;
        static JSONObject jObj = null;
        static String json = "";
    
        // constructor
        public JSONParser() {}
    
        public JSONObject getJSONFromUrl(String url) {
    
            // Making HTTP request
            try {
                // defaultHttpClient
                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);
    
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
    
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        is, "iso-8859-1"), 8);
                StringBuilder sb = new StringBuilder();
                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
                is.close();
                json = sb.toString();
            } catch (Exception e) {
                Log.e("Buffer Error", "Error converting result " + e.toString());
            }
    
            // try parse the string to a JSON object
            try {
                jObj = new JSONObject(json);
            } catch (JSONException e) {
                Log.e("JSON Parser", "Error parsing data " + e.toString());
            }
    
            // return JSON String
            return jObj;
    
        }
    }
    
  2. Parsing JSON Data
    Once you created parser class next thing is to know how to use that class. Below i am explaining how to parse the json (taken in this example) using the parser class.

    2.1. Store all these node names in variables: In the contacts json we have items like name, email, address, gender and phone numbers. So first thing is to store all these node names in variables. Open your main activity class and declare store all node names in static variables.

    // url to make request
    private static String url = "http://api.9android.net/contacts";
    
    // JSON Node names
    private static final String TAG_CONTACTS = "contacts";
    private static final String TAG_ID = "id";
    private static final String TAG_NAME = "name";
    private static final String TAG_EMAIL = "email";
    private static final String TAG_ADDRESS = "address";
    private static final String TAG_GENDER = "gender";
    private static final String TAG_PHONE = "phone";
    private static final String TAG_PHONE_MOBILE = "mobile";
    private static final String TAG_PHONE_HOME = "home";
    private static final String TAG_PHONE_OFFICE = "office";
    
    // contacts JSONArray
    JSONArray contacts = null;
    

    2.2. Use parser class to get JSONObject and looping through each json item. Below i am creating an instance of JSONParser class and using for loop i am looping through each json item and finally storing each json data in variable.

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();
    
    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);
    
        try {
        // Getting Array of Contacts
        contacts = json.getJSONArray(TAG_CONTACTS);
    
        // looping through All Contacts
        for(int i = 0; i < contacts.length(); i++){
            JSONObject c = contacts.getJSONObject(i);
    
            // Storing each json item in variable
            String id = c.getString(TAG_ID);
            String name = c.getString(TAG_NAME);
            String email = c.getString(TAG_EMAIL);
            String address = c.getString(TAG_ADDRESS);
            String gender = c.getString(TAG_GENDER);
    
            // Phone number is agin JSON Object
            JSONObject phone = c.getJSONObject(TAG_PHONE);
            String mobile = phone.getString(TAG_PHONE_MOBILE);
            String home = phone.getString(TAG_PHONE_HOME);
            String office = phone.getString(TAG_PHONE_OFFICE);
    
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }
    

How to convert ASCII code (0-255) to its corresponding character?

One can iterate from a to z like this

int asciiForLowerA = 97;
int asciiForLowerZ = 122;
for(int asciiCode = asciiForLowerA; asciiCode <= asciiForLowerZ; asciiCode++){
    search(sCurrentLine, searchKey + Character.toString ((char) asciiCode));
}

How do I replace part of a string in PHP?

This is probably what you need:

$text = str_replace(' ', '_', substr($text, 0, 10));

Algorithm to return all combinations of k elements from n

Here is an elegant, generic implementation in Scala, as described on 99 Scala Problems.

object P26 {
  def flatMapSublists[A,B](ls: List[A])(f: (List[A]) => List[B]): List[B] = 
    ls match {
      case Nil => Nil
      case sublist@(_ :: tail) => f(sublist) ::: flatMapSublists(tail)(f)
    }

  def combinations[A](n: Int, ls: List[A]): List[List[A]] =
    if (n == 0) List(Nil)
    else flatMapSublists(ls) { sl =>
      combinations(n - 1, sl.tail) map {sl.head :: _}
    }
}

What is a constant reference? (not a reference to a constant)

The clearest answer. Does “X& const x” make any sense?

No, it is nonsense

To find out what the above declaration means, read it right-to-left: “x is a const reference to a X”. But that is redundant — references are always const, in the sense that you can never reseat a reference to make it refer to a different object. Never. With or without the const.

In other words, “X& const x” is functionally equivalent to “X& x”. Since you’re gaining nothing by adding the const after the &, you shouldn’t add it: it will confuse people — the const will make some people think that the X is const, as if you had said “const X& x”.

What is a blob URL and why it is used?

This Javascript function purports to show the difference between the Blob File API and the Data API to download a JSON file in the client browser:

_x000D_
_x000D_
/**_x000D_
 * Save a text as file using HTML <a> temporary element and Blob_x000D_
 * @author Loreto Parisi_x000D_
 */_x000D_
_x000D_
var saveAsFile = function(fileName, fileContents) {_x000D_
    if (typeof(Blob) != 'undefined') { // Alternative 1: using Blob_x000D_
        var textFileAsBlob = new Blob([fileContents], {type: 'text/plain'});_x000D_
        var downloadLink = document.createElement("a");_x000D_
        downloadLink.download = fileName;_x000D_
        if (window.webkitURL != null) {_x000D_
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);_x000D_
        } else {_x000D_
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);_x000D_
            downloadLink.onclick = document.body.removeChild(event.target);_x000D_
            downloadLink.style.display = "none";_x000D_
            document.body.appendChild(downloadLink);_x000D_
        }_x000D_
        downloadLink.click();_x000D_
    } else { // Alternative 2: using Data_x000D_
        var pp = document.createElement('a');_x000D_
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' +_x000D_
            encodeURIComponent(fileContents));_x000D_
        pp.setAttribute('download', fileName);_x000D_
        pp.onclick = document.body.removeChild(event.target);_x000D_
        pp.click();_x000D_
    }_x000D_
} // saveAsFile_x000D_
_x000D_
/* Example */_x000D_
var jsonObject = {"name": "John", "age": 30, "car": null};_x000D_
saveAsFile('out.json', JSON.stringify(jsonObject, null, 2));
_x000D_
_x000D_
_x000D_

The function is called like saveAsFile('out.json', jsonString);. It will create a ByteStream immediately recognized by the browser that will download the generated file directly using the File API URL.createObjectURL.

In the else, it is possible to see the same result obtained via the href element plus the Data API, but this has several limitations that the Blob API has not.

How can I close a browser window without receiving the "Do you want to close this window" prompt?

I am going to post this because this is what I am currently using for my site and it works in both Google Chrome and IE 10 without receiving any popup messages:

<html>
    <head>
    </head>
    <body onload="window.close();">
    </body>
</html>

I have a function on my site that I want to run to save an on/off variable to session without directly going to a new page so I just open a tiny popup webpage. That webpage then closes itself immediately with the onload="window.close();" function.

Convert integer to binary in C#

http://zamirsblog.blogspot.com/2011/10/convert-decimal-to-binary-in-c.html

    public string DecimalToBinary(string data)
    {
        string result = string.Empty;
        int rem = 0;
        try
        {
            if (!IsNumeric(data))
                error = "Invalid Value - This is not a numeric value";
            else
            {
                int num = int.Parse(data);
                while (num > 0)
                {
                    rem = num % 2;
                    num = num / 2;
                    result = rem.ToString() + result;
                }
            }
        }
        catch (Exception ex)
        {
            error = ex.Message;
        }
        return result;
    }

OpenCV get pixel channel value from Mat image

Assuming the type is CV_8UC3 you would do this:

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        Vec3b bgrPixel = foo.at<Vec3b>(i, j);

        // do something with BGR values...
    }
}

Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.

EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:

Here is how you might go about this:

uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
        bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
        bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R

        // do something with BGR values...
    }
}

Or alternatively:

int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;

for(int i = 0; i < foo.rows; i++)
{
    uint8_t* rowPtr = foo.row(i);
    for(int j = 0; j < foo.cols; j++)
    {
        bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
        bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
        bgrPixel.val[2] = rowPtr[j*cn + 2]; // R

        // do something with BGR values...
    }
}

Foreach value from POST from form

i wouldn't do it this way

I'd use name arrays in the form elements

so i'd get the layout

$_POST['field'][0]['name'] = 'value';
$_POST['field'][0]['price'] = 'value';
$_POST['field'][1]['name'] = 'value';
$_POST['field'][1]['price'] = 'value';

then you could do an array slice to get the amount you need

How to correctly set the ORACLE_HOME variable on Ubuntu 9.x?

set <ORACLE_HOME> path variable

example

path ORACLE_HOME

value is C:\oraclexe\app\oracle\product\10.2.0\server

enter image description here

how do I strip white space when grabbing text with jQuery?

Use the replace function in js:

var emailAdd = $(this).text().replace(/ /g,'');

That will remove all the spaces

If you want to remove the leading and trailing whitespace only, use the jQuery $.trim method :

var emailAdd = $.trim($(this).text());

How to edit a text file in my terminal

You can open the file again using vi helloworld.txt and then use cat /path/your_file to view it.

Error Importing SSL certificate : Not an X.509 Certificate

I changed 3 things and then it works:

  1. There is a column of spaces, I removed them
  2. Changed the line break from windows CRLF to linux LF
  3. Removed the empty line at the end.

MySQL error code: 1175 during UPDATE in MySQL Workbench

Follow the following steps before executing the UPDATE command: In MySQL Workbench

  1. Go to Edit --> Preferences
  2. Click "SQL Editor" tab and uncheck "Safe Updates" check box
  3. Query --> Reconnect to Server // logout and then login
  4. Now execute your SQL query

p.s., No need to restart the MySQL daemon!

How do I change the android actionbar title and icon

To make a single icon be usable by all your action bars you can do this in your Android Manifest.

<application
    android:logo="@drawable/Image">

    ...

</application>

encrypt and decrypt md5

/* you  can match the exact string with table value*/

if(md5("string to match") == $res["hashstring"])
 echo "login correct";

How can I change the color of AlertDialog title and the color of the line under it

In case you are using extending the dialog the use:

requestWindowFeature(Window.FEATURE_NO_TITLE);

Android OnClickListener - identify a button

Or you can try the same but without listeners. On your button XML definition:

android:onClick="ButtonOnClick"

And in your code define the method ButtonOnClick:

public void ButtonOnClick(View v) {
    switch (v.getId()) {
      case R.id.button1:
        doSomething1();
        break;
      case R.id.button2:
        doSomething2();
        break;
      }
}

The application may be doing too much work on its main thread

I am not an expert, but I got this debug message when I wanted to send data from my android application to a web server. Though I used AsyncTask class and did the data transfer in background, for getting the result data back from server I used get() method of the AsyncTask class which makes the UI synchronous which means that your UI will be waiting for too long. So my advice is to make your app do every network oriented tasks on a separate thread.

stop service in android

onDestroyed()

is wrong name for

onDestroy()  

Did you make a mistake only in this question or in your code too?

Why my $.ajax showing "preflight is invalid redirect error"?

I had the same problem and it kept me up for days. At the end, I realised that my URL pointing to the app was wrong altogether. example:

URL: 'http://api.example.com/'
URL: 'https://api.example.com/'.

If it's http or https verify.
Check the redirecting URL and make sure it's the same thing you're passing along.

SQL Query - Using Order By in UNION

(SELECT table1.field1 FROM table1 
UNION
SELECT table2.field1 FROM table2) ORDER BY field1 

Work? Remember think sets. Get the set you want using a union and then perform your operations on it.

How can I get the MAC and the IP address of a connected client in PHP?

All you need to do is to put arp into diferrent group.

Default:

-rwxr-xr-x 1 root root 48K 2008-11-11 18:11 /usr/sbin/arp*

With command:

sudo chown root:www-data /usr/sbin/arp

you will get:

-rwxr-xr-x 1 root www-data 48K 2008-11-11 18:11 /usr/sbin/arp*

And because apache is a daemon running under the user www-data, it's now able to execute this command.

So if you now use a PHP script, e.g.:

<?php
$mac = system('arp -an');
echo $mac;
?>

you will get the output of linux arp -an command.

How to implement onBackPressed() in Fragments?

I had the same problem and I created a new listener for it and used in my fragments.

1 - Your activity should have a listener interface and a list of listeners in it

2 - You should implement methods for adding and removing the listeners

3 - You should override the onBackPressed method to check that any of the listeners use the back press or not

public class MainActivity ... {

    /**
     * Back press listener list. Used for notifying fragments when onBackPressed called
     */
    private Stack<BackPressListener> backPressListeners = new Stack<BackPressListener>();


    ...

    /**
     * Adding new listener to back press listener stack
     * @param backPressListener
     */
    public void addBackPressListener(BackPressListener backPressListener) {
        backPressListeners.add(backPressListener);
    }

    /**
     * Removing the listener from back press listener stack
     * @param backPressListener
     */
    public void removeBackPressListener(BackPressListener backPressListener) {
        backPressListeners.remove(backPressListener);
    }


    // Overriding onBackPressed to check that is there any listener using this back press
    @Override
    public void onBackPressed() {

        // checks if is there any back press listeners use this press
        for(BackPressListener backPressListener : backPressListeners) {
            if(backPressListener.onBackPressed()) return;
        }

        // if not returns in the loop, calls super onBackPressed
        super.onBackPressed();
    }

}

4 - Your fragment must implement the interface for back press

5 - You need to add the fragment as a listener for back press

6 - You should return true from onBackPressed if the fragment uses this back press

7 - IMPORTANT - You must remove the fragment from the list onDestroy

public class MyFragment extends Fragment implements MainActivity.BackPressListener {


    ...

    @Override
    public void onAttach(Activity activity) {
        super.onCreate(savedInstanceState);

        // adding the fragment to listener list
        ((MainActivity) activity).addBackPressListener(this);
    }

    ...

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

        // removing the fragment from the listener list
        ((MainActivity) getActivity()).removeBackPressListener(this);
    }

    ...

    @Override
    public boolean onBackPressed() {

        // you should check that if this fragment is the currently used fragment or not
        // if this fragment is not used at the moment you should return false
        if(!isThisFragmentVisibleAtTheMoment) return false;

        if (isThisFragmentUsingBackPress) {
            // do what you need to do
            return true;
        }
        return false;
    }
}

There is a Stack used instead of the ArrayList to be able to start from the latest fragment. There may be a problem also while adding fragments to the back stack. So you need to check that the fragment is visible or not while using back press. Otherwise one of the fragments will use the event and latest fragment will not be closed on back press.

I hope this solves the problem for everyone.

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

Custom li list-style with font-awesome icon

Now that the ::marker element is available in evergreen browsers, this is how you could use it, including using :hover to change the marker. As you can see, now you can use any Unicode character you want as a list item marker and even use custom counters.

_x000D_
_x000D_
@charset "UTF-8";
@counter-style fancy {
  system: fixed;
  symbols:   ;
  suffix: " ";
}

p {
  margin-left: 8em;
}

p.note {
  display: list-item;
  counter-increment: note-counter;
}

p.note::marker {
  content: "Note " counter(note-counter) ":";
}

ol {
  margin-left: 8em;
  padding-left: 0;
}

ol li {
  list-style-type: lower-roman;
}

ol li::marker {
  color: blue;
  font-weight: bold;
}

ul {
  margin-left: 8em;
  padding-left: 0;
}

ul.happy li::marker {
  content: "";
}

ul.happy li:hover {
  color: blue;
}

ul.happy li:hover::marker {
  content: "";
}

ul.fancy {
  list-style: fancy;
}
_x000D_
<p>This is the first paragraph in this document.</p>
<p class="note">This is a very short document.</p>
<ol>
  <li>This is the first item.
    <li>This is the second item.
      <li>This is the third item.
</ol>
<p>This is the end.</p>

<ul class="happy">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<ul class="fancy">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
_x000D_
_x000D_
_x000D_

Eclipse - java.lang.ClassNotFoundException

I was hit with this issue also and was able to come up with a sufficient solution for my case. If your Eclipse project has a .classpath file in your project root (see it in Navigator view instead of Package Explorer view), be sure that your Maven classpathentry appears prior to your JRE Container classpathentry.

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>

If your project does not have a .classpath file, you can edit your project's Java Build Path to switch the Order and Export. If your project has the .classpath file and you only change your ordering in the Java Build Path, you will see that the ordering is not impacted and the issue will continue to occur.

And a project->clean never hurts things after you make the change.

Show space, tab, CRLF characters in editor of Visual Studio

For those who are looking for a button toggle:

The name of this command is View white space in GUI menu (Edit -> Advanced -> View white space).

Menu toggle

The name of this command in the Add command popup is Toggle Visual Space.

Button toggle.

How can I get dict from sqlite query?

Even using the sqlite3.Row class-- you still can't use string formatting in the form of:

print "%(id)i - %(name)s: %(value)s" % row

In order to get past this, I use a helper function that takes the row and converts to a dictionary. I only use this when the dictionary object is preferable to the Row object (e.g. for things like string formatting where the Row object doesn't natively support the dictionary API as well). But use the Row object all other times.

def dict_from_row(row):
    return dict(zip(row.keys(), row))       

Is it safe to expose Firebase apiKey to the public?

EXPOSURE OF API KEYS ISN'T A SECURITY RISK BUT ANYONE CAN PUT YOUR CREDENTIALS ON THEIR SITE.

Open api keys leads to attacks that can use a lot resources at firebase that will definitely cost your hard money.

You can always restrict you firebase project keys to domains / IP's.

https://console.cloud.google.com/apis/credentials/key

select your project Id and key and restrict it to Your Android/iOs/web App.

How to convert float to int with Java

If you want to convert a float value into an integer value, you have several ways to do it that depends on how do you want to round the float value.

First way is floor rounding the float value:

float myFloat = 3.14f;
int myInteger = (int)myFloat;

The output of this code will be 3, even if the myFloat value is closer to 4.

The second way is ceil rounding the float value:

float myFloat = 3.14f;
int myInteger = Math.ceil(myFloat);

The output of this code will be 4, because the rounding mode is always looking for the highest value.

Convert integers to strings to create output filenames at run time

I already showed this elsewhere on SO (How to use a variable in the format specifier statement? , not an exact duplicate IMHO), but I think it is worthwhile to place it here. It is possible to use the techniques from other answers for this question to make a simple function

function itoa(i) result(res)
  character(:),allocatable :: res
  integer,intent(in) :: i
  character(range(i)+2) :: tmp
  write(tmp,'(i0)') i
  res = trim(tmp)
end function

which you can use after without worrying about trimming and left-adjusting and without writing to a temporary variable:

OPEN(1, FILE = 'Output'//itoa(i)//'.TXT')

It requires Fortran 2003 because of the allocatable string.

Copy all the lines to clipboard

I tried a few of the commands that people have mentioned above. None worked. Then I got hold of the simplest of them all.

Step 1: vi <filename>
Step 2: Right click on the title bar of the Putty window
Step 3: Select "Clear scrollback" (to avoid copying the rest of your SSH session)
Step 4: Right click again and select "Copy all to clipboard".

How to Set the Background Color of a JButton on the Mac OS

If you are not required to use Apple's look and feel, a simple fix is to put the following code in your application or applet, before you add any GUI components to your JFrame or JApplet:

 try {
    UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() );
 } catch (Exception e) {
            e.printStackTrace();
 }

That will set the look and feel to the cross-platform look and feel, and the setBackground() method will then work to change a JButton's background color.

What does 'var that = this;' mean in JavaScript?

From Crockford

By convention, we make a private that variable. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

JS Fiddle

function usesThis(name) {
    this.myName = name;

    function returnMe() {
        return this;        //scope is lost because of the inner function
    }

    return {
        returnMe : returnMe
    }
}

function usesThat(name) {
    var that = this;
    this.myName = name;

    function returnMe() {
        return that;            //scope is baked in with 'that' to the "class"
    }

    return {
        returnMe : returnMe
    }
}

var usesthat = new usesThat('Dave');
var usesthis = new usesThis('John');
alert("UsesThat thinks it's called " + usesthat.returnMe().myName + '\r\n' +
      "UsesThis thinks it's called " + usesthis.returnMe().myName);

This alerts...

UsesThat thinks it's called Dave

UsesThis thinks it's called undefined

SQL Query NOT Between Two Dates

How about trying:

select * from 'test_table'
where end_date < CAST('2009-12-15' AS DATE)
or start_date > CAST('2010-01-02' AS DATE)

which will return all date ranges which do not overlap your date range at all.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

How to make an unaware datetime timezone aware in python

quite new to Python and I encountered the same issue. I find this solution quite simple and for me it works fine (Python 3.6):

unaware=parser.parse("2020-05-01 0:00:00")
aware=unaware.replace(tzinfo=tz.tzlocal()).astimezone(tz.tzlocal())

How to initialize all members of an array to the same value?

Here is another way:

static void
unhandled_interrupt(struct trap_frame *frame, int irq, void *arg)
{
    //this code intentionally left blank
}

static struct irqtbl_s vector_tbl[XCHAL_NUM_INTERRUPTS] = {
    [0 ... XCHAL_NUM_INTERRUPTS-1] {unhandled_interrupt, NULL},
};

See:

C-Extensions

Designated inits

Then ask the question: When can one use C extensions?

The code sample above is in an embedded system and will never see the light from another compiler.

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

pixels = np.array(pixels) in this line you reassign pixels. So, it may not a list anyhow. Though pixels is not a list it has no attributes append. Does it make sense?

MySQL error #1054 - Unknown column in 'Field List'

I had this error aswell.

I am working in mysql workbench. When giving the values they have to be inside "". That solved it for me.

Create Table from JSON Data with angularjs and ng-repeat

To render any json in tabular format:

<table>
    <thead>
      <tr>
        <th ng-repeat="(key, value) in vm.records[0]">{{key}}</th>
      </tr>
    </thead>
    <tbody>
      <tr ng-repeat="(key, value) in vm.records">
        <td ng-repeat="(key, value) in value">
          {{value}}
        </td>
      </tr>
    </tbody>
</table>

See complete code in detail with other features

How to verify CuDNN installation?

My answer shows how to check the version of CuDNN installed, which is usually something that you also want to verify. You first need to find the installed cudnn file and then parse this file. To find the file, you can use:

whereis cudnn.h
CUDNN_H_PATH=$(whereis cudnn.h)

If that doesn't work, see "Redhat distributions" below.

Once you find this location you can then do the following (replacing ${CUDNN_H_PATH} with the path):

cat ${CUDNN_H_PATH} | grep CUDNN_MAJOR -A 2

The result should look something like this:

#define CUDNN_MAJOR 7
#define CUDNN_MINOR 5
#define CUDNN_PATCHLEVEL 0
--
#define CUDNN_VERSION (CUDNN_MAJOR * 1000 + CUDNN_MINOR * 100 + CUDNN_PATCHLEVEL)

Which means the version is 7.5.0.

Ubuntu 18.04 (via sudo apt install nvidia-cuda-toolkit)

This method of installation installs cuda in /usr/include and /usr/lib/cuda/lib64, hence the file you need to look at is in /usr/include/cudnn.h.

CUDNN_H_PATH=/usr/include/cudnn.h
cat ${CUDNN_H_PATH} | grep CUDNN_MAJOR -A 2

Debian and Ubuntu

From CuDNN v5 onwards (at least when you install via sudo dpkg -i <library_name>.deb packages), it looks like you might need to use the following:

cat /usr/include/x86_64-linux-gnu/cudnn_v*.h | grep CUDNN_MAJOR -A 2

For example:

$ cat /usr/include/x86_64-linux-gnu/cudnn_v*.h | grep CUDNN_MAJOR -A 2                                                         
#define CUDNN_MAJOR      6
#define CUDNN_MINOR      0
#define CUDNN_PATCHLEVEL 21
--
#define CUDNN_VERSION    (CUDNN_MAJOR * 1000 + CUDNN_MINOR * 100 + CUDNN_PATCHLEVEL)

#include "driver_types.h"
                      

indicates that CuDNN version 6.0.21 is installed.

Redhat distributions

On CentOS, I found the location of CUDA with:

$ whereis cuda
cuda: /usr/local/cuda

I then used the procedure about on the cudnn.h file that I found from this location:

$ cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2

This view is not constrained

You just have to right-click on the widget and choose "center" -> "horizontally" and do it again then choose ->"vertically" This worked for me...

Compare two dates in Java

in my case, I just had to do something like this :

date1.toString().equals(date2.toString())

And it worked!

Difference between "managed" and "unmanaged"

Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).

http://en.wikipedia.org/wiki/Managed_code

http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

I'm not sure about HQL, but in JPA you just call the query's setParameter with the parameter and collection.

Query q = entityManager.createQuery("SELECT p FROM Peron p WHERE name IN (:names)");
q.setParameter("names", names);

where names is the collection of names you're searching for

Collection<String> names = new ArrayList<String();
names.add("Joe");
names.add("Jane");
names.add("Bob");

AngularJS Uploading An Image With ng-upload

There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)

html

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.

controller

$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $http.post(uploadUrl, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( ...all right!... ).error( ..damn!... );

};

The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

Serialize and Deserialize Json and Json Array in Unity

Don't trim the [] and you should be fine. [] identify a JSON array which is exactly what you require to be able to iterate its elements.

How do I run SSH commands on remote system using Java?

JSch is a pure Java implementation of SSH2 that helps you run commands on remote machines. You can find it here, and there are some examples here.

You can use exec.java.

In a bootstrap responsive page how to center a div

Try this, For the example, I used a fixed height. I think it is doesn't affect the responsive scenario.

_x000D_
_x000D_
<html lang="en">_x000D_
<head>_x000D_
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">_x000D_
</head>_x000D_
<body>_x000D_
    <div class="d-flex justify-content-center align-items-center bg-secondary w-100" style="height: 300px;">_x000D_
        <div class="bg-primary" style="width: 200px; height: 50px;"></div>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

getting the reason why websockets closed with close code 1006

Thought this might be handy for others. Knowing regex is useful, kids. Stay in school.

Edit: Turned it into a handy dandy function!

let specificStatusCodeMappings = {
    '1000': 'Normal Closure',
    '1001': 'Going Away',
    '1002': 'Protocol Error',
    '1003': 'Unsupported Data',
    '1004': '(For future)',
    '1005': 'No Status Received',
    '1006': 'Abnormal Closure',
    '1007': 'Invalid frame payload data',
    '1008': 'Policy Violation',
    '1009': 'Message too big',
    '1010': 'Missing Extension',
    '1011': 'Internal Error',
    '1012': 'Service Restart',
    '1013': 'Try Again Later',
    '1014': 'Bad Gateway',
    '1015': 'TLS Handshake'
};

function getStatusCodeString(code) {
    if (code >= 0 && code <= 999) {
        return '(Unused)';
    } else if (code >= 1016) {
        if (code <= 1999) {
            return '(For WebSocket standard)';
        } else if (code <= 2999) {
            return '(For WebSocket extensions)';
        } else if (code <= 3999) {
            return '(For libraries and frameworks)';
        } else if (code <= 4999) {
            return '(For applications)';
        }
    }
    if (typeof(specificStatusCodeMappings[code]) !== 'undefined') {
        return specificStatusCodeMappings[code];
    }
    return '(Unknown)';
}

Usage:

getStatusCodeString(1006); //'Abnormal Closure'

{
    '0-999': '(Unused)',
    '1016-1999': '(For WebSocket standard)',
    '2000-2999': '(For WebSocket extensions)',
    '3000-3999': '(For libraries and frameworks)',
    '4000-4999': '(For applications)'
}

{
    '1000': 'Normal Closure',
    '1001': 'Going Away',
    '1002': 'Protocol Error',
    '1003': 'Unsupported Data',
    '1004': '(For future)',
    '1005': 'No Status Received',
    '1006': 'Abnormal Closure',
    '1007': 'Invalid frame payload data',
    '1008': 'Policy Violation',
    '1009': 'Message too big',
    '1010': 'Missing Extension',
    '1011': 'Internal Error',
    '1012': 'Service Restart',
    '1013': 'Try Again Later',
    '1014': 'Bad Gateway',
    '1015': 'TLS Handshake'
}

Source (with minor edits for terseness): https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes

T-SQL How to create tables dynamically in stored procedures?

You can write the below code:-

create procedure spCreateTable
   as
    begin
       create table testtb(Name varchar(20))
    end

execute it as:-

exec spCreateTable

Copy Files from Windows to the Ubuntu Subsystem

You should only access Linux files system (those located in lxss folder) from inside WSL; DO NOT create/modify any files in lxss folder in Windows - it's dangerous and WSL will not see these files.

Files can be shared between WSL and Windows, though; put the file outside of lxss folder. You can access them via drvFS (/mnt) such as /mnt/c/Users/yourusername/files within WSL. These files stay synced between WSL and Windows.

For details and why, see: https://blogs.msdn.microsoft.com/commandline/2016/11/17/do-not-change-linux-files-using-windows-apps-and-tools/

Visual Studio: LINK : fatal error LNK1181: cannot open input file

I'm stumbling into the same issue. For me it seems to be caused by having 2 projects with the same name, one depending on the other.

For example, I have one project named Foo which produces Foo.lib. I then have another project that's also named Foo which produces Foo.exe and links in Foo.lib.

I watched the file activity w/ Process Monitor. What seems to be happening is Foo(lib) is built first--which is proper because Foo(exe) is marked as depending on Foo(lib). This is all fine and builds successfully, and is placed in the output directory--$(OutDir)$(TargetName)$(TargetExt). Then Foo(exe) is triggered to rebuild. Well, a rebuild is a clean followed by a build. It seems like the 'clean' stage of Foo.exe is deleting Foo.lib from the output directory. This also explains why a subsequent 'build' works--that doesn't delete output files.

A bug in VS I guess.

Unfortunately I don't have a solution to the problem as it involves Rebuild. A workaround is to manually issue Clean, and then Build.

Check that Field Exists with MongoDB

Suppose we have a collection like below:

{ 
  "_id":"1234"
  "open":"Yes"
  "things":{
             "paper":1234
             "bottle":"Available"
             "bottle_count":40
            } 
}

We want to know if the bottle field is present or not?

Ans:

db.products.find({"things.bottle":{"$exists":true}})

How To Pass GET Parameters To Laravel From With GET Method ?

An alternative to msturdy's solution is using the request helper method available to you.

This works in exactly the same way, without the need to import the Input namespace use Illuminate\Support\Facades\Input at the top of your controller.

For example:

class SearchController extends BaseController {

    public function search()
    {
        $category = request('category', 'default');
        $term = request('term'); // no default defined

        ...
    }
}

Calculate relative time in C#

There are also a package called Humanizr on Nuget, and it actually works really well, and is in the .NET Foundation.

DateTime.UtcNow.AddHours(-30).Humanize() => "yesterday"
DateTime.UtcNow.AddHours(-2).Humanize() => "2 hours ago"

DateTime.UtcNow.AddHours(30).Humanize() => "tomorrow"
DateTime.UtcNow.AddHours(2).Humanize() => "2 hours from now"

TimeSpan.FromMilliseconds(1299630020).Humanize() => "2 weeks"
TimeSpan.FromMilliseconds(1299630020).Humanize(3) => "2 weeks, 1 day, 1 hour"

Scott Hanselman has a writeup on it on his blog

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

I have a short version for you. It works well for me!

var match      = str.match(/[abc]/gi);
var firstIndex = str.indexOf(match[0]);
var lastIndex  = str.lastIndexOf(match[match.length-1]);

And if you want a prototype version:

String.prototype.indexOfRegex = function(regex){
  var match = this.match(regex);
  return match ? this.indexOf(match[0]) : -1;
}

String.prototype.lastIndexOfRegex = function(regex){
  var match = this.match(regex);
  return match ? this.lastIndexOf(match[match.length-1]) : -1;
}

EDIT : if you want to add support for fromIndex

String.prototype.indexOfRegex = function(regex, fromIndex){
  var str = fromIndex ? this.substring(fromIndex) : this;
  var match = str.match(regex);
  return match ? str.indexOf(match[0]) + fromIndex : -1;
}

String.prototype.lastIndexOfRegex = function(regex, fromIndex){
  var str = fromIndex ? this.substring(0, fromIndex) : this;
  var match = str.match(regex);
  return match ? str.lastIndexOf(match[match.length-1]) : -1;
}

To use it, as simple as this:

var firstIndex = str.indexOfRegex(/[abc]/gi);
var lastIndex  = str.lastIndexOfRegex(/[abc]/gi);

How to display all methods of an object?

Math has static method where you can call directly like Math.abs() while Date has static method like Date.now() and also instance method where you need to create new instance first var time = new Date() to call time.getHours().

// The instance method of Date can be found on `Date.prototype` so you can just call:
var keys = Object.getOwnPropertyNames(Date.prototype);

// And for the static method
var keys = Object.getOwnPropertyNames(Date);

// But if the instance already created you need to
// pass its constructor
var time = new Date();
var staticKeys = Object.getOwnPropertyNames(time.constructor);
var instanceKeys = Object.getOwnPropertyNames(time.constructor.prototype);

Of course you will need to filter the obtained keys for the static method to get actual method names, because you can also get length, name that aren't a function on the list.

But how if we want to obtain all available method from class that extend another class?
Of course you will need to scan through the root of prototype like using __proto__. For saving your time you can use script below to get static method and deep method instance.

_x000D_
_x000D_
// var keys = new Set();_x000D_
function getStaticMethods(keys, clas){_x000D_
    var keys2 = Object.getOwnPropertyNames(clas);_x000D_
_x000D_
    for(var i = 0; i < keys2.length; i++){_x000D_
        if(clas[keys2[i]].constructor === Function)_x000D_
            keys.add(keys2[i]);_x000D_
    }_x000D_
}_x000D_
_x000D_
function getPrototypeMethods(keys, clas){_x000D_
    if(clas.prototype === void 0)_x000D_
        return;_x000D_
_x000D_
    var keys2 = Object.getOwnPropertyNames(clas.prototype);_x000D_
    for (var i = keys2.length - 1; i >= 0; i--) {_x000D_
        if(keys2[i] !== 'constructor')_x000D_
            keys.add(keys2[i]);_x000D_
    }_x000D_
_x000D_
    var deep = Object.getPrototypeOf(clas);_x000D_
    if(deep.prototype !== void 0)_x000D_
        getPrototypeMethods(keys, deep);_x000D_
}_x000D_
_x000D_
// ====== Usage example ======_x000D_
// To avoid duplicate on deeper prototype we use `Set`_x000D_
var keys = new Set();_x000D_
getStaticMethods(keys, Date);_x000D_
getPrototypeMethods(keys, Date);_x000D_
_x000D_
console.log(Array.from(keys));
_x000D_
_x000D_
_x000D_

If you want to obtain methods from created instance, don't forget to pass the constructor of it.

Use string in switch case in java

String value = someMethod();
switch(0) {
default:
    if ("apple".equals(value)) {
        method1();
        break;
    }
    if ("carrot".equals(value)) {
        method2();
        break;
    }
    if ("mango".equals(value)) {
        method3();
        break;
    }
    if ("orance".equals(value)) {
        method4();
        break;
    }
}

Determine the type of an object?

In many practical cases instead of using type or isinstance you can also use @functools.singledispatch, which is used to define generic functions (function composed of multiple functions implementing the same operation for different types).

In other words, you would want to use it when you have a code like the following:

def do_something(arg):
    if isinstance(arg, int):
        ... # some code specific to processing integers
    if isinstance(arg, str):
        ... # some code specific to processing strings
    if isinstance(arg, list):
        ... # some code specific to processing lists
    ...  # etc

Here is a small example of how it works:

from functools import singledispatch


@singledispatch
def say_type(arg):
    raise NotImplementedError(f"I don't work with {type(arg)}")


@say_type.register
def _(arg: int):
    print(f"{arg} is an integer")


@say_type.register
def _(arg: bool):
    print(f"{arg} is a boolean")
>>> say_type(0)
0 is an integer
>>> say_type(False)
False is a boolean
>>> say_type(dict())
# long error traceback ending with:
NotImplementedError: I don't work with <class 'dict'>

Additionaly we can use abstract classes to cover several types at once:

from collections.abc import Sequence


@say_type.register
def _(arg: Sequence):
    print(f"{arg} is a sequence!")
>>> say_type([0, 1, 2])
[0, 1, 2] is a sequence!
>>> say_type((1, 2, 3))
(1, 2, 3) is a sequence!

SQL Server Management Studio – tips for improving the TSQL coding process

F5 to run the current query is an easy win, after that, the generic MS editor commands of CTRL + K + C to comment out the selected text and then CTRL + K + U to uncomment.

How do I hide anchor text without hiding the anchor?

Mini tip:

I had the following scenario:

<a href="/page/">My link text
:after
</a>

I hided the text with font-size: 0, so I could use a FontAwesome icon for it. This worked on Chrome 36, Firefox 31 and IE9+.

I wouldn't recommend color: transparent because the text stil exists and is selectable. Using line-height: 0px didn't allow me to use :after. Maybe because my element was a inline-block.

Visibility: hidden: Didn't allow me to use :after.

text-indent: -9999px;: Also moved the :after element

How to configure robots.txt to allow everything?

That file will allow all crawlers access

User-agent: *
Allow: /

This basically allows all user agents (the *) to all parts of the site (the /).

How to embed a .mov file in HTML?

Well, if you don't want to do the work yourself (object elements aren't really all that hard), you could always use Mike Alsup's Media plugin: http://jquery.malsup.com/media/

Matplotlib 2 Subplots, 1 Colorbar

To add to @abevieiramota's excellent answer, you can get the euqivalent of tight_layout with constrained_layout. You will still get large horizontal gaps if you use imshow instead of pcolormesh because of the 1:1 aspect ratio imposed by imshow.

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2, constrained_layout=True)
for ax in axes.flat:
    im = ax.pcolormesh(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.flat)
plt.show()

enter image description here

Close Bootstrap modal on form submit

give id to submit button

<button id="btnSave" type="submit" class="btn btn-success"><i class="glyphicon glyphicon-trash"></i> Save</button>

$('#btnSave').click(function() {
   $('#StudentModal').modal('hide');
});

Also you forgot to close last div.

</div>

Hope this helps.

Perl read line by line

If you had use strict turned on, you would have found out that $++foo doesn't make any sense.

Here's how to do it:

use strict;
use warnings;

my $file = 'SnPmaster.txt';
open my $info, $file or die "Could not open $file: $!";

while( my $line = <$info>)  {   
    print $line;    
    last if $. == 2;
}

close $info;

This takes advantage of the special variable $. which keeps track of the line number in the current file. (See perlvar)

If you want to use a counter instead, use

my $count = 0;
while( my $line = <$info>)  {   
    print $line;    
    last if ++$count == 2;
}

Difference between .keystore file and .jks file

One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

How to extract hours and minutes from a datetime.datetime object?

It's easier to use the timestamp for this things since Tweepy gets both

import datetime
print(datetime.datetime.fromtimestamp(int(t1)).strftime('%H:%M'))

adb remount permission denied, but able to access super user in shell -- android

Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.

How to loop through an associative array and get the key?

Nobody answered with regular for loop? Sometimes I find it more readable and prefer for over foreach
So here it is:

$array = array('key1' => 'value1', 'key2' => 'value2'); 

$keys = array_keys($array);

for($i=0; $i < count($keys); ++$i) {
    echo $keys[$i] . ' ' . $array[$keys[$i]] . "\n";
}

/*
  prints:
  key1 value1
  key2 value2
*/

Use SQL Server Management Studio to connect remotely to an SQL Server Express instance hosted on an Azure Virtual Machine

I too struggled with something similar. My guess is your actual problem is connecting to a SQL Express instance running on a different machine. The steps to do this can be summarized as follows:

  1. Ensure SQL Express is configured for SQL Authentication as well as Windows Authentication (the default). You do this via SQL Server Management Studio (SSMS) Server Properties/Security
  2. In SSMS create a new login called "sqlUser", say, with a suitable password, "sql", say. Ensure this new login is set for SQL Authentication, not Windows Authentication. SSMS Server Security/Logins/Properties/General. Also ensure "Enforce password policy" is unchecked
  3. Under Properties/Server Roles ensure this new user has the "sysadmin" role
  4. In SQL Server Configuration Manager SSCM (search for SQLServerManagerxx.msc file in Windows\SysWOW64 if you can't find SSCM) under SQL Server Network Configuration/Protocols for SQLExpress make sure TCP/IP is enabled. You can disable Named Pipes if you want
  5. Right-click protocol TCP/IP and on the IPAddresses tab, ensure every one of the IP addresses is set to Enabled Yes, and TCP Port 1433 (this is the default port for SQL Server)
  6. In Windows Firewall (WF.msc) create two new Inbound Rules - one for SQL Server and another for SQL Browser Service. For SQL Server you need to open TCP Port 1433 (if you are using the default port for SQL Server) and very importantly for the SQL Browser Service you need to open UDP Port 1434. Name these two rules suitably in your firewall
  7. Stop and restart the SQL Server Service using either SSCM or the Services.msc snap-in
  8. In the Services.msc snap-in make sure SQL Browser Service Startup Type is Automatic and then start this service

At this point you should be able to connect remotely, using SQL Authentication, user "sqlUser" password "sql" to the SQL Express instance configured as above. A final tip and easy way to check this out is to create an empty text file with the .UDL extension, say "Test.UDL" on your desktop. Double-clicking to edit this file invokes the Microsoft Data Link Properties dialog with which you can quickly test your remote SQL connection

Cannot open solution file in Visual Studio Code

Use vscode-solution-explorer extension:

This extension adds a Visual Studio Solution File explorer panel in Visual Studio Code. Now you can navigate into your solution following the original Visual Studio structure.

https://github.com/fernandoescolar/vscode-solution-explorer

enter image description here

Thanks @fernandoescolar

Is there a way to reset IIS 7.5 to factory settings?

There is one way that I have used my self. Go to Control Panel\Programs\Turn Windows features on or off then uninstall IIS and all of its components completely. I restart windows but I'm not sure if it's required or not. Then install it again from the same path.

CASE IN statement with multiple values

You can return the same value from several matches:

SELECT
  CASE c.Number
    WHEN '1121231' THEN 1
    WHEN '31242323' THEN 1
    WHEN '234523' THEN 2
    WHEN '2342423' THEN 2
  END AS Test
FROM tblClient c

This will probably result in the same execution plan as Martins suggestion, so it's more a matter of how you want to write it.

HTML input type=file, get the image before submitting the form

Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.

Check if a row exists using old mysql_* API

If you just want to compare only one row with $lactureName then use following

function checkLectureStatus($lectureName)
{
 $con = connectvar();
 mysql_select_db("mydatabase", $con);
 $result = mysql_query("SELECT * FROM preditors_assigned WHERE lecture_name='$lectureName'");
  if(mysql_num_rows($result) > 0)
  {
         mysql_close($con);
         return "Assigned";
  }
  else
  {
        mysql_close($con);
        return "Available";
  }
}

jQuery ajax upload file in asp.net mvc

You can't upload files via ajax, you need to use an iFrame or some other trickery to do a full postback. This is mainly due to security concerns.

Here's a decent write-up including a sample project using SWFUpload and ASP.Net MVC by Steve Sanderson. It's the first thing I read getting this working properly with Asp.Net MVC (I was new to MVC at the time as well), hopefully it's as helpful for you.

WPF Image Dynamically changing Image source during runtime

I can think of two things:

First, try loading the image with:

string strUri2 = String.Format(@"pack://application:,,,/MyAseemby;component/resources/main titles/{0}", CurrenSelection.TitleImage);
imgTitle.Source = new BitmapImage(new Uri(strUri2));

Maybe the problem is with WinForm's image resizing, if the image is stretched set Stretch on the image control to "Uniform" or "UnfirofmToFill".

Second option is that maybe the image is not aligned to the pixel grid, you can read about it on my blog at http://www.nbdtech.com/blog/archive/2008/11/20/blurred-images-in-wpf.aspx

DateTime's representation in milliseconds?

As of .NET 4.6, you can use a DateTimeOffset object to get the unix milliseconds. It has a constructor which takes a DateTime object, so you can just pass in your object as demonstrated below.

DateTime yourDateTime;
long yourDateTimeMilliseconds = new DateTimeOffset(yourDateTime).ToUnixTimeMilliseconds();

As noted in other answers, make sure yourDateTime has the correct Kind specified, or use .ToUniversalTime() to convert it to UTC time first.

Here you can learn more about DateTimeOffset.

Check if any type of files exist in a directory using BATCH script

To check if a folder contains at least one file

>nul 2>nul dir /a-d "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder or any of its descendents contain at least one file

>nul 2>nul dir /a-d /s "folderName\*" && (echo Files exist) || (echo No file found)

To check if a folder contains at least one file or folder.
Note addition of /a option to enable finding of hidden and system files/folders.

dir /b /a "folderName\*" | >nul findstr "^" && (echo Files and/or Folders exist) || (echo No File or Folder found)

To check if a folder contains at least one folder

dir /b /ad "folderName\*" | >nul findstr "^" && (echo Folders exist) || (echo No folder found)

*ngIf and *ngFor on same element causing error

You can not use more than one Structural Directive in Angular on the same element, it makes a bad confusion and structure, so you need to apply them in 2 separate nested elements(or you can use ng-container), read this statement from Angular team:

One structural directive per host element

Someday you'll want to repeat a block of HTML but only when a particular condition is true. You'll try to put both an *ngFor and an *ngIf on the same host element. Angular won't let you. You may apply only one structural directive to an element.

The reason is simplicity. Structural directives can do complex things with the host element and its descendents. When two directives lay claim to the same host element, which one takes precedence? Which should go first, the NgIf or the NgFor? Can the NgIf cancel the effect of the NgFor? If so (and it seems like it should be so), how should Angular generalize the ability to cancel for other structural directives?

There are no easy answers to these questions. Prohibiting multiple structural directives makes them moot. There's an easy solution for this use case: put the *ngIf on a container element that wraps the *ngFor element. One or both elements can be an ng-container so you don't have to introduce extra levels of HTML.

So you can use ng-container (Angular4) as the wrapper (will be deleted from the dom) or a div or span if you have class or some other attributes as below:

<div class="right" *ngIf="show">
  <div *ngFor="let thing of stuff">
    {{log(thing)}}
    <span>{{thing.name}}</span>
  </div>
</div>

Java Round up Any Number

10 years later but that problem still caught me.

So this is the answer to those that are too late as me.

This does not work

int b = (int) Math.ceil(a / 100);

Cause the result a / 100 turns out to be an integer and it's rounded so Math.ceil can't do anything about it.

You have to avoid the rounded operation with this

int b = (int) Math.ceil((float) a / 100);

Now it works.

Having services in React application

Same situation: Having done multiple Angular projects and moving to React, not having a simple way to provide services through DI seems like a missing piece (the particulars of the service aside).

Using context and ES7 decorators we can come close:

https://jaysoo.ca/2015/06/09/react-contexts-and-dependency-injection/

Seems these guys have taken it a step further / in a different direction:

http://blog.wolksoftware.com/dependency-injection-in-react-powered-inversifyjs

Still feels like working against the grain. Will revisit this answer in 6 months time after undertaking a major React project.

EDIT: Back 6 months later with some more React experience. Consider the nature of the logic:

  1. Is it tied (only) to UI? Move it into a component (accepted answer).
  2. Is it tied (only) to state management? Move it into a thunk.
  3. Tied to both? Move to separate file, consume in component through a selector and in thunks.

Some also reach for HOCs for reuse but for me the above covers almost all use cases. Also, consider scaling state management using ducks to keep concerns separate and state UI-centric.

Android: how to parse URL String with spaces to URI object?

I wrote this function:

public static String encode(@NonNull String uriString) {
    if (TextUtils.isEmpty(uriString)) {
        Assert.fail("Uri string cannot be empty!");
        return uriString;
    }
    // getQueryParameterNames is not exist then cannot iterate on queries
    if (Build.VERSION.SDK_INT < 11) {
        return uriString;
    }

    // Check if uri has valid characters
    // See https://tools.ietf.org/html/rfc3986
    Pattern allowedUrlCharacters = Pattern.compile("([A-Za-z0-9_.~:/?\\#\\[\\]@!$&'()*+,;" +
            "=-]|%[0-9a-fA-F]{2})+");
    Matcher matcher = allowedUrlCharacters.matcher(uriString);
    String validUri = null;
    if (matcher.find()) {
        validUri = matcher.group();
    }
    if (TextUtils.isEmpty(validUri) || uriString.length() == validUri.length()) {
        return uriString;
    }

    // The uriString is not encoded. Then recreate the uri and encode it this time
    Uri uri = Uri.parse(uriString);
    Uri.Builder uriBuilder = new Uri.Builder()
            .scheme(uri.getScheme())
            .authority(uri.getAuthority());
    for (String path : uri.getPathSegments()) {
        uriBuilder.appendPath(path);
    }
    for (String key : uri.getQueryParameterNames()) {
        uriBuilder.appendQueryParameter(key, uri.getQueryParameter(key));
    }
    String correctUrl = uriBuilder.build().toString();
    return correctUrl;
}

How to keep footer at bottom of screen

Perhaps the easiest is to use position: absolute to fix to the bottom, then a suitable margin/padding to make sure that the other text doesn't spill over the top of it.

css:

<style>
  body {
    margin: 0 0 20px;
  }
  .footer {
    position: absolute;
    bottom: 0;
    height: 20px;
    background: #f0f0f0;
    width: 100%;
  }
</style>

Here is the html main content.

<div class="footer"> Here is the footer. </div>

How to read from input until newline is found using scanf()?

Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().

Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.

How to exclude a directory from ant fileset, based on directories contents

The following approach works for me:

<exclude name="**/dir_name_to_exclude/**" />

Default FirebaseApp is not initialized

If you recently update your Android Studio to 3.3.1 that have a problem with com.google.gms:google-services (Below 4.2.0) dependencies So please update com.google.gms:google-services to 4.2.0.

dependencies {
    classpath 'com.android.tools.build:gradle:3.3.1'
    classpath 'com.google.gms:google-services:4.2.0'
    }

Objective-C - Remove last character from string

The documentation is your friend, NSString supports a call substringWithRange that can shorten the string that you have an return the shortened String. You cannot modify an instance of NSString it is immutable. If you have an NSMutableString is has a method called deleteCharactersInRange that can modify the string in place

...
NSRange r;
r.location = 0;
r.size = [mutable length]-1;
NSString* shorted = [stringValue substringWithRange:r];
...

bootstrap datepicker today as default

I used this a little example and it worked.

$('#date').datetimepicker({
    defaultDate: new Date()
});

demo : http://jsfiddle.net/m2fjw57b/1/

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

ReactJS: Warning: setState(...): Cannot update during an existing state transition

From react docs Passing arguments to event handlers

<button onClick={(e) => this.deleteRow(id, e)}>Delete Row</button>
<button onClick={this.deleteRow.bind(this, id)}>Delete Row</button>

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

How to set minDate to current date in jQuery UI Datepicker?

Use this one :

 onSelect: function(dateText) {
                 $("input#DateTo").datepicker('option', 'minDate', dateText);
            }

This may be useful : http://jsfiddle.net/injulkarnilesh/xNeTe/

MongoDB: How to query for records where field is null or not set?

If the sent_at field is not there when its not set then:

db.emails.count({sent_at: {$exists: false}})

If its there and null, or not there at all:

db.emails.count({sent_at: null})

Refer here for querying and null

PreparedStatement setNull(..)

Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways

setNull(..)

and

set<ClassName>(.., null)) 

behave the same way.

How to go back to previous page if back button is pressed in WebView?

This is my solution. It works also in Fragment.

webView.setOnKeyListener(new OnKeyListener()
{
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event)
    {
        if(event.getAction() == KeyEvent.ACTION_DOWN)
        {
            WebView webView = (WebView) v;

            switch(keyCode)
            {
                case KeyEvent.KEYCODE_BACK:
                    if(webView.canGoBack())
                    {
                        webView.goBack();
                        return true;
                    }
                    break;
            }
        }

        return false;
    }
});

What is android:weightSum in android, and how does it work?

The documentation says it best and includes an example, (highlighting mine).

android:weightSum

Defines the maximum weight sum. If unspecified, the sum is computed by adding the layout_weight of all of the children. This can be used for instance to give a single child 50% of the total available space by giving it a layout_weight of 0.5 and setting the weightSum to 1.0.

So to correct superM's example, suppose you have a LinearLayout with horizontal orientation that contains two ImageViews and a TextView with. You define the TextView to have a fixed size, and you'd like the two ImageViews to take up the remaining space equally.

To accomplish this, you would apply layout_weight 1 to each ImageView, none on the TextView, and a weightSum of 2.0 on the LinearLayout.

why $(window).load() is not working in jQuery?

in jquery-3.1.1

_x000D_
_x000D_
$("#id").load(function(){_x000D_
//code goes here});
_x000D_
_x000D_
_x000D_

will not work because load function is no more work