Programs & Examples On #Full table scan

Get latitude and longitude automatically using php, API

$address = str_replace(" ", "+", $address);

$json = file_get_contents("http://maps.google.com/maps/api/geocode/json?address=$address&sensor=false&region=$region");
$json = json_decode($json);

$lat = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lat'};
$long = $json->{'results'}[0]->{'geometry'}->{'location'}->{'lng'};

Batch file to run a command in cmd within a directory

For me, the following is working and running activiti server as well as opening the explorer in browser (with the help of zb226's answer and comment);

START "runas /user:administrator" cmd /K "cd C:\activiti-5.9\setup & ant demo.start"

START /wait localhost:8080/activiti-explorer

Change status bar text color to light in iOS 9 with Objective-C

If you want to change Status Bar Style from the launch screen, You should take this way.

  1. Go to Project -> Target,

  2. Set Status Bar Style to Light Project Setting

  3. Set View controller-based status bar appearance to NO in Info.plist.

Nexus 5 USB driver

Nexus 5 with Win7 x64

-USB computer connection : Uncheck MTP and PTP

-Use a 2.0 USB port.

-Try to use the original USB cable.

Now device manager will detect nexus 5 as an androide device with ADB driver.

Action Image MVC3 Razor

This would be work very fine

<a href="<%:Url.Action("Edit","Account",new {  id=item.UserId }) %>"><img src="../../Content/ThemeNew/images/edit_notes_delete11.png" alt="Edit" width="25px" height="25px" /></a>

JavaScript: SyntaxError: missing ) after argument list

just posting in case anyone else has the same error...

I was using 'await' outside of an 'async' function and for whatever reason that results in a 'missing ) after argument list' error.

The solution was to make the function asynchronous

function functionName(args) {}

becomes

async function functionName(args) {}

Transport security has blocked a cleartext HTTP

By default, iOS only allows HTTPS API. Since HTTP is not secure, you will have to disable App transport security. There are two ways to disable ATS:-

1. Adding source code in project info.plist and add the following code in root tag.

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

2. Using project info.

Click on project on the project on the left pane, select the project as target and choose info tab. You have to add the dictionary in the following structure.

enter image description here

SQLException: No suitable driver found for jdbc:derby://localhost:1527

I was facing the same issue. I was missing DriverManager.registerDriver() call, before getting the connection using the connection URL and user credentials.

It got fixed on Linux as below:

DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527//tmp/Test/DB_Name", user, pass);

For Windows:

DriverManager.registerDriver(new org.apache.derby.jdbc.ClientDriver());
connection = DriverManager.getConnection("jdbc:derby://localhost:1527/C:/Users/Test/DB_Name", user, pass);

Handling the null value from a resultset in JAVA

The description of the getString() method says the following:

 the column value; if the value is SQL NULL, the value returned is null

That means your problem is not that the String value is null, rather some other object is, perhaps your ResultSet or maybe you closed the connection or something like this. Provide the stack trace, that would help.

Parsing a CSV file using NodeJS

fs = require('fs');
fs.readFile('FILENAME WITH PATH','utf8', function(err,content){
if(err){
    console.log('error occured ' +JSON.stringify(err));
 }
 console.log('Fileconetent are ' + JSON.stringify(content));
})

JOptionPane YES/No Options Confirm Dialog Box Issue

You need to look at the return value of the call to showConfirmDialog. I.E.:

int dialogResult = JOptionPane.showConfirmDialog (null, "Would You Like to Save your Previous Note First?","Warning",dialogButton);
if(dialogResult == JOptionPane.YES_OPTION){
  // Saving code here
}

You were testing against dialogButton, which you were using to set the buttons that should be displayed by the dialog, and this variable was never updated - so dialogButton would never have been anything other than JOptionPane.YES_NO_OPTION.

Per the Javadoc for showConfirmDialog:

Returns: an integer indicating the option selected by the user

Could not find module "@angular-devkit/build-angular"

I try all the answers above, but none of them work to me. I had to downgrade the version of Angular-CLI. I run the command ng --version and results:

@angular-devkit/architect          0.10.7
@angular-devkit/build-angular      0.10.7
@angular-devkit/build-ng-packagr   0.10.7
@angular-devkit/build-optimizer    0.10.7
@angular-devkit/build-webpack      0.10.7
@angular-devkit/core               7.0.7 <-- notice this!
@angular-devkit/schematics         8.2.1
@angular/cli                       8.2.1 <-- and this!
@ngtools/json-schema               1.1.0
@ngtools/webpack                   7.0.7
@schematics/angular                8.2.1
@schematics/update                 0.802.1
ng-packagr                         4.7.1
rxjs                               6.3.3
typescript                         3.1.6
webpack                            4.19.1

I open my package.json and search for the line that define the version of CLI:

...
"devDependencies": {
    "@angular-devkit/build-angular": "~0.10.0",
    "@angular-devkit/build-ng-packagr": "~0.10.0",
    "@angular/cli": "~8.2.0" -- I changed here to ~7.0.7
...}
...

I change the version of @angular/cli to ~7.0.7. Then run npm uninstall @angular/cli and install again running npm install -g angular-cli@~7.0.7

Python: count repeated elements in the list

You can do that using count:

my_dict = {i:MyList.count(i) for i in MyList}

>>> print my_dict     #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

Or using collections.Counter:

from collections import Counter

a = dict(Counter(MyList))

>>> print a           #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

How to drop rows from pandas data frame that contains a particular string in a particular column?

pandas has vectorized string operations, so you can just filter out the rows that contain the string you don't want:

In [91]: df = pd.DataFrame(dict(A=[5,3,5,6], C=["foo","bar","fooXYZbar", "bat"]))

In [92]: df
Out[92]:
   A          C
0  5        foo
1  3        bar
2  5  fooXYZbar
3  6        bat

In [93]: df[~df.C.str.contains("XYZ")]
Out[93]:
   A    C
0  5  foo
1  3  bar
3  6  bat

What's the best way to convert a number to a string in JavaScript?

Method toFixed() will also solves the purpose.

var n = 8.434332;
n.toFixed(2)  // 8.43

How to center the text in a JLabel?

myLabel.setHorizontalAlignment(SwingConstants.CENTER);
myLabel.setVerticalAlignment(SwingConstants.CENTER);

If you cannot reconstruct the label for some reason, this is how you edit these properties of a pre-existent JLabel.

How to modify JsonNode in Java?

JsonNode is immutable and is intended for parse operation. However, it can be cast into ObjectNode (and ArrayNode) that allow mutations:

((ObjectNode)jsonNode).put("value", "NO");

For an array, you can use:

((ObjectNode)jsonNode).putArray("arrayName").add(object.ge??tValue());

split string in two on given index and return both parts

You can easily expand it to split on multiple indexes, and to take an array or string

const splitOn = (slicable, ...indices) =>
  [0, ...indices].map((n, i, m) => slicable.slice(n, m[i + 1]));

splitOn('foo', 1);
// ["f", "oo"]

splitOn([1, 2, 3, 4], 2);
// [[1, 2], [3, 4]]

splitOn('fooBAr', 1, 4);
//  ["f", "ooB", "Ar"]

lodash issue tracker: https://github.com/lodash/lodash/issues/3014

How to get the last element of a slice?

Bit less elegant but can also do:

sl[len(sl)-1: len(sl)]

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

how to kill the tty in unix

I had the same problem today. I had NO remaining processes, but the remaining finger entry of user "xxx", which prevent me the deletion of this user using "userdel xxx".

Error message was: userdel: account `xxx' is currently in use.

It looked like a crashed terminal session. So I rebooted, but the issue remained.

last xxx
xxx      pts/5        10.1.2.3     Fri Feb  7 10:25 - crash  (01:27)

So I (re)moved the /var/run/utmp file:

mv /var/run/utmp /var/run/utmp.save ; touch /var/run/utmp

This cleared all finger entries. Unfortunately in this way even the current running sessions will be cleared. If this is an issue for you, you have to reboot, after you (re)moved the utmp file.

However in my case this was the solution. Afterwards I was able to successfully delete the user, using "userdel xxx".

Update elements in a JSONObject

Generic way to update the any JSONObjet with new values.

private static void updateJsonValues(JsonObject jsonObj) {
    for (Map.Entry<String, JsonElement> entry : jsonObj.entrySet()) {
        JsonElement element = entry.getValue();
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        } else if (element.isJsonPrimitive()) {
            jsonObj.addProperty(entry.getKey(), "<provide new value>");
        }

    }
}

private static void parseJsonArray(JsonArray asJsonArray) {
    for (int index = 0; index < asJsonArray.size(); index++) {
        JsonElement element = asJsonArray.get(index);
        if (element.isJsonArray()) {
            parseJsonArray(element.getAsJsonArray());
        } else if (element.isJsonObject()) {
            updateJsonValues(element.getAsJsonObject());
        }

    }
}

How to prevent ENTER keypress to submit a web form?

I Have come across this myself because I have multiple submit buttons with different 'name' values, so that when submitted they do different things on the same php file. The enter / return button breaks this as those values aren't submitted. So I was thinking, does the enter / return button activate the first submit button in the form? That way you could have a 'vanilla' submit button that is either hidden or has a 'name' value that returns the executing php file back to the page with the form in it. Or else a default (hidden) 'name' value that the keypress activates, and the submit buttons overwrite with their own 'name' values. Just a thought.

Better way to generate array of all letters in the alphabet

If you are using Java 8

char[] charArray = IntStream.rangeClosed('A', 'Z')
    .mapToObj(c -> "" + (char) c).collect(Collectors.joining()).toCharArray();

Undoing a git rebase

I actually put a backup tag on the branch before I do any nontrivial operation (most rebases are trivial, but I'd do that if it looks anywhere complex).

Then, restoring is as easy as git reset --hard BACKUP.

Iterating through struct fieldnames in MATLAB

You can use the for each toolbox from http://www.mathworks.com/matlabcentral/fileexchange/48729-for-each.

>> signal
signal = 
sin: {{1x1x25 cell}  {1x1x25 cell}}
cos: {{1x1x25 cell}  {1x1x25 cell}}

>> each(fieldnames(signal))
ans = 
CellIterator with properties:

NumberOfIterations: 2.0000e+000

Usage:

for bridge = each(fieldnames(signal))
   signal.(bridge) = rand(10);
end

I like it very much. Credit of course go to Jeremy Hughes who developed the toolbox.

How to redirect output to a file and stdout

$ program [arguments...] 2>&1 | tee outfile

2>&1 dumps the stderr and stdout streams. tee outfile takes the stream it gets and writes it to the screen and to the file "outfile".

This is probably what most people are looking for. The likely situation is some program or script is working hard for a long time and producing a lot of output. The user wants to check it periodically for progress, but also wants the output written to a file.

The problem (especially when mixing stdout and stderr streams) is that there is reliance on the streams being flushed by the program. If, for example, all the writes to stdout are not flushed, but all the writes to stderr are flushed, then they'll end up out of chronological order in the output file and on the screen.

It's also bad if the program only outputs 1 or 2 lines every few minutes to report progress. In such a case, if the output was not flushed by the program, the user wouldn't even see any output on the screen for hours, because none of it would get pushed through the pipe for hours.

Update: The program unbuffer, part of the expect package, will solve the buffering problem. This will cause stdout and stderr to write to the screen and file immediately and keep them in sync when being combined and redirected to tee. E.g.:

$ unbuffer program [arguments...] 2>&1 | tee outfile

Rebuild or regenerate 'ic_launcher.png' from images in Android Studio

You can create an icon using this website https://romannurik.github.io/AndroidAssetStudio/index.html.

Download the icon, go to File Explorer - where your projects are saved, the default path is C:\Users\Your Name\AndroidStudioProjects\Project Name\app\src\main\res\

and copy the folders you downloaded to the res folder.

Loop through JSON object List

This will work!

$(document).ready(function ()
    {
        $.ajax(
            {
            type: 'POST',
            url: "/Home/MethodName",
            success: function (data) {
                //data is the string that the method returns in a json format, but in string
                var jsonData = JSON.parse(data); //This converts the string to json

                for (var i = 0; i < jsonData.length; i++) //The json object has lenght
                {
                    var object = jsonData[i]; //You are in the current object
                    $('#olListId').append('<li class="someclass>' + object.Atributte  + '</li>'); //now you access the property.

                }

                /* JSON EXAMPLE
                [{ "Atributte": "value" }, 
                { "Atributte": "value" }, 
                { "Atributte": "value" }]
                */
            }
        });
    });

The main thing about this is using the property exactly the same as the attribute of the JSON key-value pair.

Creating a directory in /sdcard fails

If this is happening to you with Android 6 and compile target >= 23, don't forget that we are now using runtime permissions. So giving permissions in the manifest is not enough anymore.

find a minimum value in an array of floats

If you want to use numpy, you must define darr to be a numpy array, not a list:

import numpy as np
darr = np.array([1, 3.14159, 1e100, -2.71828])
print(darr.min())

darr.argmin() will give you the index corresponding to the minimum.

The reason you were getting an error is because argmin is a method understood by numpy arrays, but not by Python lists.

Width equal to content

You can use either of below :-

1) display : inline-block :

http://jsbin.com/feneni/edit?html,css,js,output

Uncomment the line

 float:left;
 clear:both 

and you will find that parent container has collapsed.

2) Using display : table

http://jsbin.com/dujowep/edit?html,css,js,output

How can I Convert HTML to Text in C#?

I had some decoding issues with HtmlAgility and I didn't want to invest time investigating it.

Instead I used that utility from the Microsoft Team Foundation API:

var text = HtmlFilter.ConvertToPlainText(htmlContent);

String.Format alternative in C++

In addition to options suggested by others I can recommend the fmt library which implements string formatting similar to str.format in Python and String.Format in C#. Here's an example:

std::string a = "test";
std::string b = "text.txt";
std::string c = "text1.txt";
std::string result = fmt::format("{0} {1} > {2}", a, b, c);

Disclaimer: I'm the author of this library.

Check if a input box is empty

Quite simple:

<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>

You could also use ng-hide="somefield.length" instead of ng-show="!somefield.length" if that reads more naturally for you.


A better alternative might be to really take advantage of the form abilities of Angular:

<form name="myform">
  <input name="myfield" ng-model="somefield" ng-minlength="5" required>
  <span ng-show="myform.myfield.$error.required">Please enter something!</span>
  <span ng-show="!myform.myfield.$error.required">Good boy!</span>
</form> 

Updated Plnkr here.

Change visibility of ASP.NET label with JavaScript

This is the easiest way I found:

        BtnUpload.Style.Add("display", "none");
        FileUploader.Style.Add("display", "none");
        BtnAccept.Style.Add("display", "inherit");
        BtnClear.Style.Add("display", "inherit");

I have the opposite in the Else, so it handles displaying them as well. This can go in the Page's Load or in a method to refresh the controls on the page.

How can I put an icon inside a TextInput in React Native?

This is working for me in ReactNative 0.60.4

View

<View style={styles.SectionStyle}>
    <Image
        source={require('../assets/images/ico-email.png')} //Change your icon image here
        style={styles.ImageStyle}
    />

    <TextInput
        style={{ flex: 1 }}
        placeholder="Enter Your Name Here"
        underlineColorAndroid="transparent"
    />
</View>

Styles

SectionStyle: {
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#fff',
    borderWidth: 0.5,
    borderColor: '#000',
    height: 40,
    borderRadius: 5,
    margin: 10,
},
ImageStyle: {
    padding: 10,
    margin: 5,
    height: 25,
    width: 25,
    resizeMode: 'stretch',
    alignItems: 'center',
}

What is a mutex?

There are some great answers here, here is another great analogy for explaining what mutex is:

Consider single toilet with a key. When someone enters, they take the key and the toilet is occupied. If someone else needs to use the toilet, they need to wait in a queue. When the person in the toilet is done, they pass the key to the next person in queue. Make sense, right?

Convert the toilet in the story to a shared resource, and the key to a mutex. Taking the key to the toilet (acquire a lock) permits you to use it. If there is no key (the lock is locked) you have to wait. When the key is returned by the person (release the lock) you're free to acquire it now.

Count the number occurrences of a character in a string

count is definitely the most concise and efficient way of counting the occurrence of a character in a string but I tried to come up with a solution using lambda, something like this :

sentence = 'Mary had a little lamb'
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This will result in :

4

Also, there is one more advantage to this is if the sentence is a list of sub-strings containing same characters as above, then also this gives the correct result because of the use of in. Have a look :

sentence = ['M', 'ar', 'y', 'had', 'a', 'little', 'l', 'am', 'b']
sum(map(lambda x : 1 if 'a' in x else 0, sentence))

This also results in :

4

But Of-course this will work only when checking occurrence of single character such as 'a' in this particular case.

How can I post data as form data instead of a request payload?

Just set Content-Type is not enough, url encode form data before send. $http.post(url, jQuery.param(data))

How can I get selector from jQuery object

I was getting multiple elements even after above solutions, so i extended dds1024 work, for even more pin-pointing dom element.

e.g. DIV:nth-child(1) DIV:nth-child(3) DIV:nth-child(1) ARTICLE:nth-child(1) DIV:nth-child(1) DIV:nth-child(8) DIV:nth-child(2) DIV:nth-child(1) DIV:nth-child(2) DIV:nth-child(1) H4:nth-child(2)

Code:

function getSelector(el)
{
    var $el = jQuery(el);

    var selector = $el.parents(":not(html,body)")
                .map(function() { 
                                    var i = jQuery(this).index(); 
                                    i_str = ''; 

                                    if (typeof i != 'undefined') 
                                    {
                                        i = i + 1;
                                        i_str += ":nth-child(" + i + ")";
                                    }

                                    return this.tagName + i_str; 
                                })
                .get().reverse().join(" ");

    if (selector) {
        selector += " "+ $el[0].nodeName;
    }

    var index = $el.index();
    if (typeof index != 'undefined')  {
        index = index + 1;
        selector += ":nth-child(" + index + ")";
    }

    return selector;
}

What is a void pointer in C++?

A void* does not mean anything. It is a pointer, but the type that it points to is not known.

It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

  • It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
  • It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
  • It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to.

This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.

And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

Invalid column name sql error

You have to use '"+texbox1.Text+"','"+texbox2.Text+"','"+texbox3.Text+"'

Instead of "+texbox1.Text+","+texbox2.Text+","+texbox3.Text+"

Notice the extra single quotes.

Returning binary file from controller in ASP.NET Web API

While the suggested solution works fine, there is another way to return a byte array from the controller, with response stream properly formatted :

  • In the request, set header "Accept: application/octet-stream".
  • Server-side, add a media type formatter to support this mime type.

Unfortunately, WebApi does not include any formatter for "application/octet-stream". There is an implementation here on GitHub: BinaryMediaTypeFormatter (there are minor adaptations to make it work for webapi 2, method signatures changed).

You can add this formatter into your global config :

HttpConfiguration config;
// ...
config.Formatters.Add(new BinaryMediaTypeFormatter(false));

WebApi should now use BinaryMediaTypeFormatter if the request specifies the correct Accept header.

I prefer this solution because an action controller returning byte[] is more comfortable to test. Though, the other solution allows you more control if you want to return another content-type than "application/octet-stream" (for example "image/gif").

using lodash .groupBy. how to add your own keys for grouped output?

another way

_.chain(data)
    .groupBy('color')
    .map((users, color) => ({ users, color }))
    .value();

JWT (JSON Web Token) automatic prolongation of expiration

Today, lots of people opt for doing session management with JWTs without being aware of what they are giving up for the sake of perceived simplicity. My answer elaborates on the 2nd part of the questions:

What is the real benefit then? Why not have only one token (not JWT) and keep the expiration on the server?

Are there other options? Is using JWT not suited for this scenario?

JWTs are capable of supporting basic session management with some limitations. Being self-describing tokens, they don't require any state on the server-side. This makes them appealing. For instance, if the service doesn't have a persistence layer, it doesn't need to bring one in just for session management.

However, statelessness is also the leading cause of their shortcomings. Since they are only issued once with fixed content and expiration, you can't do things you would like to with a typical session management setup.

Namely, you can't invalidate them on-demand. This means you can't implement a secure logout as there is no way to expire already issued tokens. You also can't implement idle timeout for the same reason. One solution is to keep a blacklist, but that introduces state.

I wrote a post explaining these drawbacks in more detail. To be clear, you can work around these by adding more complexity (sliding sessions, refresh tokens, etc.)

As for other options, if your clients only interact with your service via a browser, I strongly recommend using a cookie-based session management solution. I also compiled a list authentication methods currently widely used on the web.

The ScriptManager must appear before any controls that need it

On the ASP.NET page, inside the form tags.

Java - Get a list of all Classes loaded in the JVM

Run your code under a JRockit JVM, then use JRCMD <PID> print_class_summary

This will output all loaded classes, one on each line.

How to initialize a vector with fixed length in R

If you want to initialize a vector with numeric values other than zero, use rep

n <- 10
v <- rep(0.05, n)
v

which will give you:

[1] 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05 0.05

SQL - Select first 10 rows only?

The ANSI SQL answer is FETCH FIRST.

SELECT a.names,
         COUNT(b.post_title) AS num
    FROM wp_celebnames a
    JOIN wp_posts b ON INSTR(b.post_title, a.names) > 0
    WHERE b.post_date > DATE_SUB(CURDATE(), INTERVAL 1 DAY)
GROUP BY a.names
ORDER BY num DESC
FETCH FIRST 10 ROWS ONLY

If you want ties to be included, do FETCH FIRST 10 ROWS WITH TIES instead.

To skip a specified number of rows, use OFFSET, e.g.

...
ORDER BY num DESC
OFFSET 20
FETCH FIRST 10 ROWS ONLY

Will skip the first 20 rows, and then fetch 10 rows.

Supported by newer versions of Oracle, PostgreSQL, MS SQL Server, Mimer SQL and DB2 etc.

With CSS, use "..." for overflowed block of multi-lines

The link below provides a pure HTML / CSS solution to this problem.

Browser support - as stated in the article:

So far we have tested on Safari 5.0, IE 9 (must be in standards mode), Opera 12 and Firefox 15.

Older browsers will still work quite well, as the meat of the layout is in normal positioning, margin and padding properties. if your platform is older (e.g. Firefox 3.6, IE 8), you can use the method but redo the gradient as a standalone PNG image or DirectX filter.

http://www.mobify.com/dev/multiline-ellipsis-in-pure-css

the css:

p { margin: 0; padding: 0; font-family: sans-serif;}

.ellipsis {
    overflow: hidden;
    height: 200px;
    line-height: 25px;
    margin: 20px;
    border: 5px solid #AAA; }

.ellipsis:before {
    content:"";
    float: left;
    width: 5px; height: 200px; }

.ellipsis > *:first-child {
    float: right;
    width: 100%;
    margin-left: -5px; }        

.ellipsis:after {
    content: "\02026";  

    box-sizing: content-box;
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;

    float: right; position: relative;
    top: -25px; left: 100%; 
    width: 3em; margin-left: -3em;
    padding-right: 5px;

    text-align: right;

    background: -webkit-gradient(linear, left top, right top,
        from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
    background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);           
    background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }

the html:

<div class="ellipsis">
    <div>
        <p>Call me Ishmael.  Some years ago &ndash; never mind how long precisely &ndash; having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.  It is a way I have of driving off the spleen, and regulating the circulation.  Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off &ndash; then, I account it high time to get to sea as soon as I can.</p>  
    </div>
</div>

the fiddle

(resize browser's window for testing)

PHP Fatal error: Cannot redeclare class

This error might also occur if you define the __construct method more than once.

Laravel update model with unique validation rule for attribute

I have BaseModel class, so I needed something more generic.

//app/BaseModel.php
public function rules()
{
    return $rules = [];
}
public function isValid($id = '')
{

    $validation = Validator::make($this->attributes, $this->rules($id));

    if($validation->passes()) return true;
    $this->errors = $validation->messages();
    return false;
}

In user class let's suppose I need only email and name to be validated:

//app/User.php
//User extends BaseModel
public function rules($id = '')
{
    $rules = [
                'name' => 'required|min:3',
                'email' => 'required|email|unique:users,email',
                'password' => 'required|alpha_num|between:6,12',
                'password_confirmation' => 'same:password|required|alpha_num|between:6,12',
            ];
    if(!empty($id))
    {
        $rules['email'].= ",$id";
        unset($rules['password']);
        unset($rules['password_confirmation']);
    }

    return $rules;
}

I tested this with phpunit and works fine.

//tests/models/UserTest.php 
public function testUpdateExistingUser()
{
    $user = User::find(1);
    $result = $user->id;
    $this->assertEquals(true, $result);
    $user->name = 'test update';
    $user->email = '[email protected]';
    $user->save();

    $this->assertTrue($user->isValid($user->id), 'Expected to pass');

}

I hope will help someone, even if for getting a better idea. Thanks for sharing yours as well. (tested on Laravel 5.0)

How do I print output in new line in PL/SQL?

dbms_output.put_line('Hi,');
dbms_output.put_line('good');
dbms_output.put_line('morning');
dbms_output.put_line('friends');

or

DBMS_OUTPUT.PUT_LINE('Hi, ' || CHR(13) || CHR(10) || 
                     'good' || CHR(13) || CHR(10) ||
                     'morning' || CHR(13) || CHR(10) ||
                     'friends' || CHR(13) || CHR(10) ||);

try it.

libz.so.1: cannot open shared object file

For Arch Linux, it is pacman -S lib32-zlib from multilib, not zlib.

"You may need an appropriate loader to handle this file type" with Webpack and Babel

If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.

var path = require('path');
let webpack = require("webpack");

module.exports = {
    entry: {
        app: './app/App.js',
        vendor: ["react","react-dom"]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../public')
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader?cacheDirectory=true',
            }
        }]
    }
};

This picks up its configuration from my .babelrc file:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers":["last 2 versions"],
                    "node":"current"
                }
            }
        ],["react"]
    ]
}

HttpContext.Current.User.Identity.Name is Empty

As @PaulTheCyclist says, If using IISExpress anonymous authentication is enabled by default, windows authentication is disabled.

This can be changed in what I'm sure used to be called PropertyPages (NOT right-click -> properties). Select the web project

Remove rows not .isin('X')

You have many options. Collating some of the answers above and the accepted answer from this post you can do:
1. df[-df["column"].isin(["value"])]
2. df[~df["column"].isin(["value"])]
3. df[df["column"].isin(["value"]) == False]
4. df[np.logical_not(df["column"].isin(["value"]))]

Note: for option 4 for you'll need to import numpy as np

Update: You can also use the .query method for this too. This allows for method chaining:
5. df.query("column not in @values").
where values is a list of the values that you don't want to include.

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

First time scroll when entering in recycler view first time then use

linearLayoutManager.scrollToPositionWithOffset(messageHashMap.size()-1

put in minus for scroll down for scroll up put in positive value);

if the view is very big in height then scrolltoposition particular offset is used for the top of view then you use

int overallXScroldl =chatMessageBinding.rvChat.computeVerticalScrollOffset();
chatMessageBinding.rvChat.smoothScrollBy(0, Math.abs(overallXScroldl));

PostgreSQL: Which version of PostgreSQL am I running?

use VERSION special variable

$psql -c "\echo :VERSION"

Using C++ filestreams (fstream), how can you determine the size of a file?

Like this:

long begin, end;
ifstream myfile ("example.txt");
begin = myfile.tellg();
myfile.seekg (0, ios::end);
end = myfile.tellg();
myfile.close();
cout << "size: " << (end-begin) << " bytes." << endl;

How do I get column datatype in Oracle with PL-SQL with low privileges?

Note: if you are trying to get this information for tables that are in a different SCHEMA use the all_tab_columns view, we have this problem as our Applications use a different SCHEMA for security purposes.

use the following:

EG:

SELECT
    data_length 
FROM
    all_tab_columns 
WHERE
    upper(table_name) = 'MY_TABLE_NAME' AND upper(column_name) = 'MY_COL_NAME'

Automatically scroll down chat div

    var l = document.getElementsByClassName("chatMessages").length;
    document.getElementsByClassName("chatMessages")[l-1].scrollIntoView();

this should work

The difference between Classes, Objects, and Instances

The concept behind classes and objects is to encapsulate logic into single programming unit. Classes are the blueprints of which objects are created.

Here an example of a class representing a Car:

public class Car {

    int currentSpeed;
    String name;

    public void accelerate() {  
    }

    public void park() {
    }

    public void printCurrentSpeed() {
    }
}

You can create instances of the object Car like this:

Car audi = new Car();
Car toyota = new Car();

I have taken the example from this tutorial

How to count string occurrence in string?

function countInstances(string, word) {
   return string.split(word).length - 1;
}

How to change users in TortoiseSVN

When you use Integrated Windows Authentication (i.e., Active Directory Single Sign-On), you authenticate to AD resources automatically with your AD credentials. You've are already signed in to AD and these credentials are reused automatically. Therefore if your server is IWA-enabled (e.g., VisualSVN Server), the server does not ask you to enter username and password, passing --username and --password does not work, and the SVN client does not cache your credentials on disk, too.

When you want to change the user account that's used to contact the server, you need use the Windows Credential Manager on client side. This is also helpful when your computer is not domain joined and you need to store your AD credentials to access your domain resources.

Follow these steps to save the user's domain credentials to Windows Credential Manager on the user's computer:

  1. Start Control Panel | Credential Manager on the client computer.
  2. Click Add a Windows Credential.
  3. As Internet or network address enter the FQDN of the server machine (e.g., svn.example.com).
  4. As Username enter your domain account's username in the DOMAIN\Username format.
  5. Complete the password field and click OK.

Now when you will contact https://svn.example.com/svn/MyRepo or a similar URL, the client or web browser will use the credentials saved in the Credential Manager to authenticate to the server.

enter image description here

How to ignore files/directories in TFS for avoiding them to go to central source repository?

I'm going to assume you are using Web Site Projects. These automatically crawl their project directory and throw everything into source control. There's no way to stop them.

However, don't despair. Web Application Projects don't exhibit this strange and rather unexpected (imho: moronic) behavior. WAP is an addon on for VS2005 and comes direct with VS2008.

As an alternative to changing your projects to WAP, you might consider moving the Assets folder out of Source control and into a TFS Document Library. Only do this IF the project itself doesn't directly use the assets files.

How do I left align these Bootstrap form items?

I was having the exact same problem. I found the issue within bootstrap.min.css. You need to change the label: label {display:inline-block;} to label {display:block;}

How do I increase memory on Tomcat 7 when running as a Windows Service?

//ES/tomcat -> This may not work if you have changed the service name during the installation.

Either run the command without any service name

.\bin\tomcat7w.exe //ES

or with exact service name

.\bin\tomcat7w.exe //ES/YourServiceName

nodemon command is not recognized in terminal for node js server

I have fixed in this way

  1. uninstall existing local nodemon

    npm uninstall nodemon

  2. install it again globally.

    npm i -g nodemon

SQL Server String or binary data would be truncated

For the others, also check your stored procedure. In my case in my stored procedure CustomSearch I accidentally declared not enough length for my column, so when I entered a big data I received that error even though I have a big length on my database. I just changed the length of my column in my custom search the error goes away. This is just for the reminder. Thanks.

Query for documents where array size is greater than 1

db.accommodations.find({"name":{"$exists":true, "$ne":[], "$not":{"$size":1}}})

"Logging out" of phpMyAdmin?

As said here and i quote:

just change this line on config.inc.php

$cfg['Servers'][$i]['auth_type'] = 'config'; 

to

$cfg['Servers'][$i]['auth_type'] = 'cookie'; 

then you will be prompted to login when you refreshed the page. Afterwards, the log out icon will appear next to home icon.

Floating point comparison functions for C#

I translated the sample from Michael Borgwardt. This is the result:

public static bool NearlyEqual(float a, float b, float epsilon){
    float absA = Math.Abs (a);
    float absB = Math.Abs (b);
    float diff = Math.Abs (a - b);

    if (a == b) {
        return true;
    } else if (a == 0 || b == 0 || diff < float.Epsilon) {
        // a or b is zero or both are extremely close to it
        // relative error is less meaningful here
        return diff < epsilon;
    } else { // use relative error
        return diff / (absA + absB) < epsilon;
    }
}

Feel free to improve this answer.

Codeigniter : calling a method of one controller from other

This is not supported behavior of the MVC System. If you want to execute an action of another controller you just redirect the user to the page you want (i.e. the controller function that consumes the url).

If you want common functionality, you should build a library to be used in the two different controllers.

I can only assume you want to build up your site a bit modular. (I.e. re-use the output of one controller method in other controller methods.) There's some plugins / extensions for CI that help you build like that. However, the simplest way is to use a library to build up common "controls" (i.e. load the model, render the view into a string). Then you can return that string and pass it along to the other controller's view.

You can load into a string by adding true at the end of the view call:

$string_view = $this->load->view('someview', array('data'=>'stuff'), true);

Failed to add the host to the list of know hosts

In your specific case, your known_hosts is a folder, so you need to remove it first.

For other people which experiencing similar issue, please check the right permission to your ~/ssh/known_hosts as it may be owned by different user (e.g. root). So you may try to run:

sudo chown -v $USER ~/.ssh/known_hosts

to fix it.

Retrieve all values from HashMap keys in an ArrayList Java

Why do you want to re-invent the wheel, when you already have something to do your work. Map.keySet() method gives you a Set of all the keys in the Map.

Map<String, Integer> map = new HashMap<String, Integer>();

for (String key: map.keySet()) {
    System.out.println("key : " + key);
    System.out.println("value : " + map.get(key));
}

Also, your 1st for-loop looks odd to me: -

   for(int k = 0; k < list.size(); k++){
            map = (HashMap)list.get(k);
   }

You are iterating over your list, and assigning each element to the same reference - map, which will overwrite all the previous values.. All you will be having is the last map in your list.

EDIT: -

You can also use entrySet if you want both key and value for your map. That would be better bet for you: -

    Map<String, Integer> map = new HashMap<String, Integer>();

    for(Entry<String, Integer> entry: map.entrySet()) {
        System.out.println(entry.getKey());
        System.out.println(entry.getValue());
    }

P.S.: -
Your code looks jumbled to me. I would suggest, keep that code aside, and think about your design one more time. For now, as the code stands, it is very difficult to understand what its trying to do.

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Resizing a button

If you want to call a different size for the button inline, you would probably do it like this:

<div class="button" style="width:60px;height:100px;">This is a button</div>

Or, a better way to have different sizes (say there will be 3 standard sizes for the button) would be to have classes just for size.

For example, you would call your button like this:

<div class="button small">This is a button</div>

And in your CSS

.button.small { width: 60px; height: 100px; }

and just create classes for each size you wish to have. That way you still have the perks of using a stylesheet in case say, you want to change the size of all the small buttons at once.

How do I use T-SQL's Case/When?

As soon as a WHEN statement is true the break is implicit.

You will have to concider which WHEN Expression is the most likely to happen. If you put that WHEN at the end of a long list of WHEN statements, your sql is likely to be slower. So put it up front as the first.

More information here: break in case statement in T-SQL

Difference between datetime and timestamp in sqlserver?

Datetime is a datatype.

Timestamp is a method for row versioning. In fact, in sql server 2008 this column type was renamed (i.e. timestamp is deprecated) to rowversion. It basically means that every time a row is changed, this value is increased. This is done with a database counter which automatically increase for every inserted or updated row.

For more information:

http://www.sqlteam.com/article/timestamps-vs-datetime-data-types

http://msdn.microsoft.com/en-us/library/ms182776.aspx

How to create many labels and textboxes dynamically depending on the value of an integer variable?

You can try this:

int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e) 
{
     TextBox txt = new TextBox();
     this.Controls.Add(txt);
     txt.Top = cleft * 40;
     txt.Size = new Size(200, 16);
     txt.Left = 150;
     cleft = cleft + 1;
     Label lbl = new Label();
     this.Controls.Add(lbl);
     lbl.Top = aleft * 40;
     lbl.Size = new Size(100, 16);
     lbl.ForeColor = Color.Blue;
     lbl.Text = "BoxNo/CardNo";
     lbl.Left = 70;
     aleft = aleft + 1;
     return;
}
private void btd_Click(object sender, EventArgs e)
{ 
    //Here you Delete Text Box One By One(int ix for Text Box)
    for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
    //Here you Delete Lable One By One(int ix for Lable)
    for (int x = this.Controls.Count - 2; x >= 0; x--)
    {
        if (this.Controls[ix] is TextBox) 
        this.Controls[ix].Dispose();
        if (this.Controls[x] is Label) 
        this.Controls[x].Dispose();
        return;
    }
}

SQL Server copy all rows from one table into another i.e duplicate table

Don't have sql server around to test but I think it's just:

insert into newtable select * from oldtable;

Connect to SQL Server Database from PowerShell

Change Integrated security to false in the connection string.

You can check/verify this by opening up the SQL management studio with the username/password you have and see if you can connect/open the database from there. NOTE! Could be a firewall issue as well.

jQuery textbox change event

I have found that this works:

$(document).ready(function(){
    $('textarea').bind('input propertychange', function() {
        //do your update here
    }

})

How to write MySQL query where A contains ( "a" or "b" )

I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0

I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps

Java integer list

code that works, but output is:

10
20
30
40
50

so:

    List<Integer> myCoords = new ArrayList<Integer>();
    myCoords.add(10);
    myCoords.add(20);
    myCoords.add(30);
    myCoords.add(40);
    myCoords.add(50);
    for (Integer number : myCoords) {
        System.out.println(number);
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

excel - if cell is not blank, then do IF statement

You need to use AND statement in your formula

=IF(AND(IF(NOT(ISBLANK(Q2));TRUE;FALSE);Q2<=R2);"1";"0")

And if both conditions are met, return 1.

You could also add more conditions in your AND statement.

use Lodash to sort array of object by value

This method orderBy does not change the input array, you have to assign the result to your array :

var chars = this.state.characters;

chars = _.orderBy(chars, ['name'],['asc']); // Use Lodash to sort array by 'name'

 this.setState({characters: chars})

Execute SQLite script

There are many ways to do this, one way is:

sqlite3 auction.db

Followed by:

sqlite> .read create.sql

In general, the SQLite project has really fantastic documentation! I know we often reach for Google before the docs, but in SQLite's case, the docs really are technical writing at its best. It's clean, clear, and concise.

How to store a dataframe using Pandas

Pandas DataFrames have the to_pickle function which is useful for saving a DataFrame:

import pandas as pd

a = pd.DataFrame({'A':[0,1,0,1,0],'B':[True, True, False, False, False]})
print a
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

a.to_pickle('my_file.pkl')

b = pd.read_pickle('my_file.pkl')
print b
#    A      B
# 0  0   True
# 1  1   True
# 2  0  False
# 3  1  False
# 4  0  False

Change bootstrap navbar background color and font color

I have successfully styled my Bootstrap navbar using the following CSS. Also you didn't define any font in your CSS so that's why the font isn't changing. The site for which this CSS is used can be found here.

.navbar-default .navbar-nav > li > a:hover, .navbar-default .navbar-nav > li > a:focus {
    color: #000; /*Sets the text hover color on navbar*/
}

.navbar-default .navbar-nav > .active > a, .navbar-default .navbar-nav > .active >
        a:hover, .navbar-default .navbar-nav > .active > a:focus {
    color: white; /*BACKGROUND color for active*/
    background-color: #030033;
}

.navbar-default {
    background-color: #0f006f;
    border-color: #030033;
}

.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
    color: #262626;
    text-decoration: none;
    background-color: #66CCFF; /*change color of links in drop down here*/
}

.nav > li > a:hover,
.nav > li > a:focus {
    text-decoration: none;
    background-color: silver; /*Change rollover cell color here*/
}

.navbar-default .navbar-nav > li > a {
    color: white; /*Change active text color here*/
}

How do I seed a random class to avoid getting duplicate random values

I use this for most situations, keep the seed if there is a need to repeat the sequence

    var seed = (int) DateTime.Now.Ticks;
    var random = new Random(seed);

or

    var random = new Random((int)DateTime.Now.Ticks);

MySQL select where column is not empty

If there are spaces in the phone2 field from inadvertant data entry, you can ignore those records with the IFNULL and TRIM functions:

SELECT phone, phone2
FROM jewishyellow.users
WHERE phone LIKE '813%'
    AND TRIM(IFNULL(phone2,'')) <> '';

Merge DLL into EXE?

Also you can use ilmergertool at codeplex with GUI interface.

Serializing class instance to JSON

JSON is not really meant for serializing arbitrary Python objects. It's great for serializing dict objects, but the pickle module is really what you should be using in general. Output from pickle is not really human-readable, but it should unpickle just fine. If you insist on using JSON, you could check out the jsonpickle module, which is an interesting hybrid approach.

https://github.com/jsonpickle/jsonpickle

Check if an HTML input element is empty or has no value entered by user

Your first one was basically right. This, FYI, is bad. It does an equality check between a DOM node and a string:

if (document.getElementById('customx') == ""){

DOM nodes are actually their own type of JavaScript object. Thus this comparison would never work at all since it's doing an equality comparison on two distinctly different data types.

How can I generate random number in specific range in Android?

Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.

How to delete object from array inside foreach loop?

You can also use references on foreach values:

foreach($array as $elementKey => &$element) {
    // $element is the same than &$array[$elementKey]
    if (isset($element['id']) and $element['id'] == 'searched_value') {
        unset($element);
    }
}

How to grant remote access to MySQL for a whole subnet?

after you connect server and you want to connect on your host, you should do the steps below:

  1. write mysql to open mysql
  2. write GRANT ALL ON . to root@'write_your_ip_addres' IDENTIFIED BY 'write_password_to_connect';
  3. press control and X to quit from mysql
  4. write nano /etc/mysql/my.cnf
  5. write # before bind-address = 127.0.0.1 in my.cnf folder
  6. #bind-address = 127.0.0.1
  7. save my.cnf folder with control + X
  8. write service mysql restart
  9. you could connect via navicat on your host

Getting a File's MD5 Checksum in Java

Google guava provides a new API. Find the one below :

public static HashCode hash(File file,
            HashFunction hashFunction)
                     throws IOException

Computes the hash code of the file using hashFunction.

Parameters:
    file - the file to read
    hashFunction - the hash function to use to hash the data
Returns:
    the HashCode of all of the bytes in the file
Throws:
    IOException - if an I/O error occurs
Since:
    12.0

Colorplot of 2D array matplotlib

I'm afraid your posted example is not working, since X and Y aren't defined. So instead of pcolormesh let's use imshow:

import numpy as np
import matplotlib.pyplot as plt

H = np.array([[1, 2, 3, 4],
              [5, 6, 7, 8],
              [9, 10, 11, 12],
              [13, 14, 15, 16]])  # added some commas and array creation code

fig = plt.figure(figsize=(6, 3.2))

ax = fig.add_subplot(111)
ax.set_title('colorMap')
plt.imshow(H)
ax.set_aspect('equal')

cax = fig.add_axes([0.12, 0.1, 0.78, 0.8])
cax.get_xaxis().set_visible(False)
cax.get_yaxis().set_visible(False)
cax.patch.set_alpha(0)
cax.set_frame_on(False)
plt.colorbar(orientation='vertical')
plt.show()

Regex for remove everything after | (with | )

The pipe, |, is a special-character in regex (meaning "or") and you'll have to escape it with a \.

Using your current regex:

\|.*$

I've tried this in Notepad++, as you've mentioned, and it appears to work well.

Sending and receiving data over a network using TcpClient

I have had luck using the socket object directly (rather than the TCP client). I create a Server object that looks something like this (I've edited some stuff such as exception handling out for brevity, but I hope that the idea comes across.)...

public class Server()
{
    private Socket sock;
    // You'll probably want to initialize the port and address in the
    // constructor, or via accessors, but to start your server listening
    // on port 8080 and on any IP address available on the machine...
    private int port = 8080;
    private IPAddress addr = IPAddress.Any;

    // This is the method that starts the server listening.
    public void Start()
    {
        // Create the new socket on which we'll be listening.
        this.sock = new Socket(
            addr.AddressFamily,
            SocketType.Stream,
            ProtocolType.Tcp);
        // Bind the socket to the address and port.
        sock.Bind(new IPEndPoint(this.addr, this.port));
        // Start listening.
        this.sock.Listen(this.backlog);
        // Set up the callback to be notified when somebody requests
        // a new connection.
        this.sock.BeginAccept(this.OnConnectRequest, sock);
    }

    // This is the method that is called when the socket recives a request
    // for a new connection.
    private void OnConnectRequest(IAsyncResult result)
    {
        // Get the socket (which should be this listener's socket) from
        // the argument.
        Socket sock = (Socket)result.AsyncState;
        // Create a new client connection, using the primary socket to
        // spawn a new socket.
        Connection newConn = new Connection(sock.EndAccept(result));
        // Tell the listener socket to start listening again.
        sock.BeginAccept(this.OnConnectRequest, sock);
    }
}

Then, I use a separate Connection class to manage the individual connection with the remote host. That looks something like this...

public class Connection()
{
    private Socket sock;
    // Pick whatever encoding works best for you.  Just make sure the remote 
    // host is using the same encoding.
    private Encoding encoding = Encoding.UTF8;

    public Connection(Socket s)
    {
        this.sock = s;
        // Start listening for incoming data.  (If you want a multi-
        // threaded service, you can start this method up in a separate
        // thread.)
        this.BeginReceive();
    }

    // Call this method to set this connection's socket up to receive data.
    private void BeginReceive()
    {
        this.sock.BeginReceive(
                this.dataRcvBuf, 0,
                this.dataRcvBuf.Length,
                SocketFlags.None,
                new AsyncCallback(this.OnBytesReceived),
                this);
    }

    // This is the method that is called whenever the socket receives
    // incoming bytes.
    protected void OnBytesReceived(IAsyncResult result)
    {
        // End the data receiving that the socket has done and get
        // the number of bytes read.
        int nBytesRec = this.sock.EndReceive(result);
        // If no bytes were received, the connection is closed (at
        // least as far as we're concerned).
        if (nBytesRec <= 0)
        {
            this.sock.Close();
            return;
        }
        // Convert the data we have to a string.
        string strReceived = this.encoding.GetString(
            this.dataRcvBuf, 0, nBytesRec);

        // ...Now, do whatever works best with the string data.
        // You could, for example, look at each character in the string
        // one-at-a-time and check for characters like the "end of text"
        // character ('\u0003') from a client indicating that they've finished
        // sending the current message.  It's totally up to you how you want
        // the protocol to work.

        // Whenever you decide the connection should be closed, call 
        // sock.Close() and don't call sock.BeginReceive() again.  But as long 
        // as you want to keep processing incoming data...

        // Set up again to get the next chunk of data.
        this.sock.BeginReceive(
            this.dataRcvBuf, 0,
            this.dataRcvBuf.Length,
            SocketFlags.None,
            new AsyncCallback(this.OnBytesReceived),
            this);

    }
}

You can use your Connection object to send data by calling its Socket directly, like so...

this.sock.Send(this.encoding.GetBytes("Hello to you, remote host."));

As I said, I've tried to edit the code here for posting, so I apologize if there are any errors in it.

Get JavaScript object from array of objects by value of property

var jsObjects = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}, {a: 7, b: 8}];

to access the third object, use: jsObjects[2];
to access the third object b value, use: jsObjects[2].b;

Why maven? What are the benefits?

Maven can provide benefits for your build process by employing standard conventions and practices to accelerate your development cycle while at the same time helping you achieve a higher rate of success. For a more detailed look at how Maven can help you with your development process please refer to The Benefits of Using Maven.

Assign an initial value to radio button as checked

The other way to set default checked on radio buttons, especially if you're using angularjs is setting the 'ng-checked' flag to "true" eg: <input id="d_man" value="M" ng-disabled="some Value" type="radio" ng-checked="true">Man

the checked="checked" did not work for me..

Angular 2 'component' is not a known element

The problem in my case was missing component declaration in the module, but even after adding the declaration the error persisted. I had stop the server and rebuild the entire project in VS Code for the error to go away.

python 2.7: cannot pip on windows "bash: pip: command not found"

  1. press [win] + Pause
  2. Advanced settings
  3. System variables
  4. Append ;C:\python27\Scripts to the end of Path variable
  5. Restart console

How do you specifically order ggplot2 x axis instead of alphabetical order?

The accepted answer offers a solution which requires changing of the underlying data frame. This is not necessary. One can also simply factorise within the aes() call directly or create a vector for that instead.

This is certainly not much different than user Drew Steen's answer, but with the important difference of not changing the original data frame.

level_order <- c('virginica', 'versicolor', 'setosa') #this vector might be useful for other plots/analyses

ggplot(iris, aes(x = factor(Species, level = level_order), y = Petal.Width)) + geom_col()

or

level_order <- factor(iris$Species, level = c('virginica', 'versicolor', 'setosa'))

ggplot(iris, aes(x = level_order, y = Petal.Width)) + geom_col()

or
directly in the aes() call without a pre-created vector:

ggplot(iris, aes(x = factor(Species, level = c('virginica', 'versicolor', 'setosa')), y = Petal.Width)) + geom_col()

that's for the first version

Python Regex - How to Get Positions and Values of Matches

note that the span & group are indexed for multi capture groups in a regex

regex_with_3_groups=r"([a-z])([0-9]+)([A-Z])"
for match in re.finditer(regex_with_3_groups, string):
    for idx in range(0, 4):
        print(match.span(idx), match.group(idx))

MySQL "Group By" and "Order By"

Here's one approach:

SELECT cur.textID, cur.fromEmail, cur.subject, 
     cur.timestamp, cur.read
FROM incomingEmails cur
LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.timestamp < next.timestamp
WHERE next.timestamp is null
and cur.toUserID = '$userID' 
ORDER BY LOWER(cur.fromEmail)

Basically, you join the table on itself, searching for later rows. In the where clause you state that there cannot be later rows. This gives you only the latest row.

If there can be multiple emails with the same timestamp, this query would need refining. If there's an incremental ID column in the email table, change the JOIN like:

LEFT JOIN incomingEmails next
    on cur.fromEmail = next.fromEmail
    and cur.id < next.id

What is reflection and why is it useful?

I want to answer this question by example. First of all Hibernate project uses Reflection API to generate CRUD statements to bridge the chasm between the running application and the persistence store. When things change in the domain, the Hibernate has to know about them to persist them to the data store and vice versa.

Alternatively works Lombok Project. It just injects code at compile time, result in code being inserted into your domain classes. (I think it is OK for getters and setters)

Hibernate chose reflection because it has minimal impact on the build process for an application.

And from Java 7 we have MethodHandles, which works as Reflection API. In projects, to work with loggers we just copy-paste the next code:

Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getName());

Because it is hard to make typo-error in this case.

How to convert image into byte array and byte array to base64 String in android?

They have wrapped most stuff need to solve your problem, one of the tests looks like this:

String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";

StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));

String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);

Activity <App Name> has leaked ServiceConnection <ServiceConnection Name>@438030a8 that was originally bound here

You should only need to unbind the service in onDestroy(). Then, The warning will go.

See here.

As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().

How to print number with commas as thousands separators?

Here is the locale grouping code after removing irrelevant parts and cleaning it up a little:

(The following only works for integers)

def group(number):
    s = '%d' % number
    groups = []
    while s and s[-1].isdigit():
        groups.append(s[-3:])
        s = s[:-3]
    return s + ','.join(reversed(groups))

>>> group(-23432432434.34)
'-23,432,432,434'

There are already some good answers in here. I just want to add this for future reference. In python 2.7 there is going to be a format specifier for thousands separator. According to python docs it works like this

>>> '{:20,.2f}'.format(f)
'18,446,744,073,709,551,616.00'

In python3.1 you can do the same thing like this:

>>> format(1234567, ',d')
'1,234,567'

How to kill all active and inactive oracle sessions for user

Execute this script:

SELECT 'ALTER SYSTEM KILL SESSION '''||sid||','||serial#||''' IMMEDIATE;' 
FROM v$session 
where username='YOUR_USER';

It will printout sqls, which should be executed.

GCC: array type has incomplete element type

It's the array that's causing trouble in:

void print_graph(g_node graph_node[], double weight[][], int nodes);

The second and subsequent dimensions must be given:

void print_graph(g_node graph_node[], double weight[][32], int nodes);

Or you can just give a pointer to pointer:

void print_graph(g_node graph_node[], double **weight, int nodes);

However, although they look similar, those are very different internally.

If you're using C99, you can use variably-qualified arrays. Quoting an example from the C99 standard (section §6.7.5.2 Array Declarators):

void fvla(int m, int C[m][m]); // valid: VLA with prototype scope

void fvla(int m, int C[m][m])  // valid: adjusted to auto pointer to VLA
{
    typedef int VLA[m][m];     // valid: block scope typedef VLA
    struct tag {
        int (*y)[n];           // invalid: y not ordinary identifier
        int z[n];              // invalid: z not ordinary identifier
    };
    int D[m];                  // valid: auto VLA
    static int E[m];           // invalid: static block scope VLA
    extern int F[m];           // invalid: F has linkage and is VLA
    int (*s)[m];               // valid: auto pointer to VLA
    extern int (*r)[m];        // invalid: r has linkage and points to VLA
    static int (*q)[m] = &B;   // valid: q is a static block pointer to VLA
}

Question in comments

[...] In my main(), the variable I am trying to pass into the function is a double array[][], so how would I pass that into the function? Passing array[0][0] into it gives me incompatible argument type, as does &array and &array[0][0].

In your main(), the variable should be:

double array[10][20];

or something faintly similar; maybe

double array[][20] = { { 1.0, 0.0, ... }, ... };

You should be able to pass that with code like this:

typedef struct graph_node
{
    int X;
    int Y;
    int active;
} g_node;

void print_graph(g_node graph_node[], double weight[][20], int nodes);

int main(void)
{
    g_node g[10];
    double array[10][20];
    int n = 10;

    print_graph(g, array, n);
    return 0;
}

That compiles (to object code) cleanly with GCC 4.2 (i686-apple-darwin11-llvm-gcc-4.2 (GCC) 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2336.9.00)) and also with GCC 4.7.0 on Mac OS X 10.7.3 using the command line:

/usr/bin/gcc -O3 -g -std=c99 -Wall -Wextra -c zzz.c

How to add border around linear layout except at the bottom?

Save this xml and add as a background for the linear layout....

<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <stroke android:width="4dp" android:color="#FF00FF00" /> 
    <solid android:color="#ffffff" /> 
    <padding android:left="7dp" android:top="7dp" 
            android:right="7dp" android:bottom="0dp" /> 
    <corners android:radius="4dp" /> 
</shape>

Hope this helps! :)

No connection could be made because the target machine actively refused it?

There is a service called "SQL Server Browser" that provides SQL Server connection information to clients.

In my case, none of the existing solutions worked because this service was not running. I resumed it and everything went back to working perfectly.

Print a file, skipping the first X lines, in Bash

I needed to do the same and found this thread.

I tried "tail -n +, but it just printed everything.

The more +lines worked nicely on the prompt, but it turned out it behaved totally different when run in headless mode (cronjob).

I finally wrote this myself:

skip=5
FILE="/tmp/filetoprint"
tail -n$((`cat "${FILE}" | wc -l` - skip)) "${FILE}"

Call Javascript function from URL/address bar

you may also place the followinng

<a href='javascript:alert("hello world!");'>Click me</a>

to your html-code, and when you click on 'Click me' hyperlink, javascript will appear in url-bar and Alert dialog will show

error: RPC failed; curl transfer closed with outstanding read data remaining

you need to turn off the compression:

git config --global core.compression 0

then you need to use shallow clone

git clone --depth=1 <url>

then most important step is to cd into your cloned project

cd <shallow cloned project dir>

now deopen the clone,step by step

git fetch --depth=N, with increasing N

eg.

git fetch --depth=4

then,

git fetch --depth=100

then,

git fetch --depth=500

you can choose how many steps you want by replacing this N,

and finally download all of the remaining revisions using,

git fetch --unshallow 

upvote if it helps you :)

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

What does the symbol \0 mean in a string-literal?

Banging my usual drum solo of JUST TRY IT, here's how you can answer questions like that in the future:

$ cat junk.c
#include <stdio.h>

char* string = "Hello\0";

int main(int argv, char** argc)
{
    printf("-->%s<--\n", string);
}
$ gcc -S junk.c
$ cat junk.s

... eliding the unnecessary parts ...

.LC0:
    .string "Hello"
    .string ""

...

.LC1:
    .string "-->%s<--\n"

...

Note here how the string I used for printf is just "-->%s<---\n" while the global string is in two parts: "Hello" and "". The GNU assembler also terminates strings with an implicit NUL character, so the fact that the first string (.LC0) is in those two parts indicates that there are two NULs. The string is thus 7 bytes long. Generally if you really want to know what your compiler is doing with a certain hunk of code, isolate it in a dummy example like this and see what it's doing using -S (for GNU -- MSVC has a flag too for assembler output but I don't know it off-hand). You'll learn a lot about how your code works (or fails to work as the case may be) and you'll get an answer quickly that is 100% guaranteed to match the tools and environment you're working in.

Disable submit button on form submit

Specifically if someone is facing problem in Chrome:

What you need to do to fix this is to use the onSubmit tag in the <form> element to set the submit button disabled. This will allow Chrome to disable the button immediately after it is pressed and the form submission will still go ahead...

<form name ="myform" method="POST" action="dosomething.php" onSubmit="document.getElementById('submit').disabled=true;"> 
     <input type="submit" name="submit" value="Submit" id="submit"> 
</form>

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

Bash loop ping successful

You don't need to use echo or grep. You could do this:

ping -oc 100000 8.8.8.8 > /dev/null && say "up" || say "down"

C# Linq Where Date Between 2 Dates

I had a problem getting this to work.

I had two dates in a db line and I need to add them to a list for yesterday, today and tomorrow.

this is my solution:

        var yesterday = DateTime.Today.AddDays(-1);
        var today = DateTime.Today;
        var tomorrow = DateTime.Today.AddDays(1);            
        var vm = new Model()
        {
            Yesterday = _context.Table.Where(x => x.From <= yesterday && x.To >= yesterday).ToList(),
            Today = _context.Table.Where(x => x.From <= today & x.To >= today).ToList(),
            Tomorrow = _context.Table.Where(x => x.From <= tomorrow & x.To >= tomorrow).ToList()
        };

Does MS Access support "CASE WHEN" clause if connect with ODBC?

You could use IIF statement like in the next example:

SELECT
   IIF(test_expression, value_if_true, value_if_false) AS FIELD_NAME
FROM
   TABLE_NAME

How to grant "grant create session" privilege?

You can grant system privileges with or without the admin option. The default being without admin option.

GRANT CREATE SESSION TO username

or with admin option:

GRANT CREATE SESSION TO username WITH ADMIN OPTION

The Grantee with the ADMIN OPTION can grant and revoke privileges to other users

Initial bytes incorrect after Java AES/CBC decryption

Looks to me like you are not dealing properly with your Initialization Vector (IV). It's been a long time since I last read about AES, IVs and block chaining, but your line

IvParameterSpec ivParameterSpec = new IvParameterSpec(aesKey.getEncoded());

does not seem to be OK. In the case of AES, you can think of the initialization vector as the "initial state" of a cipher instance, and this state is a bit of information that you can not get from your key but from the actual computation of the encrypting cipher. (One could argue that if the IV could be extracted from the key, then it would be of no use, as the key is already given to the cipher instance during its init phase).

Therefore, you should get the IV as a byte[] from the cipher instance at the end of your encryption

  cipherOutputStream.close();
  byte[] iv = encryptCipher.getIV();

and you should initialize your Cipher in DECRYPT_MODE with this byte[] :

  IvParameterSpec ivParameterSpec = new IvParameterSpec(iv);

Then, your decryption should be OK. Hope this helps.

Unexpected character encountered while parsing value

This issue is related to Byte Order Mark in the JSON file. JSON file is not encoded as UTF8 encoding data when saved. Using File.ReadAllText(pathFile) fix this issue.

When we are operating on Byte data and converting that to string and then passing to JsonConvert.DeserializeObject, we can use UTF32 encoding to get the string.

byte[] docBytes = File.ReadAllBytes(filePath);

string jsonString = Encoding.UTF32.GetString(docBytes);

How to explicitly obtain post data in Spring MVC?

Spring MVC runs on top of the Servlet API. So, you can use HttpServletRequest#getParameter() for this:

String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");

The HttpServletRequest should already be available to you inside Spring MVC as one of the method arguments of the handleRequest() method.

python .replace() regex

In order to replace text using regular expression use the re.sub function:

sub(pattern, repl, string[, count, flags])

It will replace non-everlaping instances of pattern by the text passed as string. If you need to analyze the match to extract information about specific group captures, for instance, you can pass a function to the string argument. more info here.

Examples

>>> import re
>>> re.sub(r'a', 'b', 'banana')
'bbnbnb'

>>> re.sub(r'/\d+', '/{id}', '/andre/23/abobora/43435')
'/andre/{id}/abobora/{id}'

Can't import javax.servlet.annotation.WebServlet

I tried to import the servlet-api.jar to eclipse but still the same also tried to build and clean the project. I don't use tomcat on my eclipse only have it on my net-beans. How can I solve the problem.

Do not put the servlet-api.jar in your project. This is only asking for trouble. You need to check in the Project Facets section of your project's properties if the Dynamic Web Module facet is set to version 3.0. You also need to ensure that your /WEB-INF/web.xml (if any) is been declared conform Servlet 3.0 spec. I.e. the <web-app> root declaration must match the following:

<web-app
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">

In order to be able to import javax.servlet stuff, you need to integrate a fullworthy servletcontainer like Tomcat in Eclipse and then reference it in Targeted Runtimes of the project's properties. You can do the same for Google App Engine.

Once again, do not copy container-specific libraries into webapp project as others suggest. It would make your webapp unexecutabele on production containers of a different make/version. You'll get classpath-related errors/exceptions in all colors.

See also:


Unrelated to the concrete question: GAE does not support Servlet 3.0. Its underlying Jetty 7.x container supports max Servlet 2.5 only.

What is the best collation to use for MySQL with PHP?

The accepted answer fairly definitively suggests using utf8_unicode_ci, and whilst for new projects that's great, I wanted to relate my recent contrary experience just in case it saves anyone some time.

Because utf8_general_ci is the default collation for Unicode in MySQL, if you want to use utf8_unicode_ci then you end up having to specify it in a lot of places.

For example, all client connections not only have a default charset (makes sense to me) but also a default collation (i.e. the collation will always default to utf8_general_ci for unicode).

Likely, if you use utf8_unicode_ci for your fields, your scripts that connect to the database will need to be updated to mention the desired collation explicitly -- otherwise queries using text strings can fail when your connection is using the default collation.

The upshot is that when converting an existing system of any size to Unicode/utf8, you may end up being forced to use utf8_general_ci because of the way MySQL handles defaults.

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

To fix this problem, you have to install OpenSSL development package, which is available in standard repositories of all modern Linux distributions.

To install OpenSSL development package on Debian, Ubuntu or their derivatives:

$ sudo apt-get install libssl-dev

To install OpenSSL development package on Fedora, CentOS or RHEL:

$ sudo yum install openssl-devel 

Edit : As @isapir has pointed out, for Fedora version>=22 use the DNF package manager :

dnf install openssl-devel

Multiple variables in a 'with' statement?

From Python 3.10 there is a new feature of Parenthesized context managers, which permits syntax such as:

with (
    A() as a,
    B() as b
):
    do_something(a, b)

How to convert number to words in java

public class NumberConverter {

    private String[] singleDigit = {"", " one", " two", " three",
    " four", " five"," six", " seven", " eight", " nine"};

    private String[] tens = {" ten", " eleven", " twelve", " thirteen",
            " fourteen", " fifteen"," sixteen", " seventeen", " eighteen", " nineteen"};

    private String[] twoDigits = {"", "", " twenty", " thirty",
            " forty", " fifty"," sixty", " seventy", " eighty", " ninety"};

    public String convertToWords(String input) {
        long number = Long.parseLong(input);
        int size = input.length();
        if (size <= 3) {
            int num = (int) number;
            return handle3Digits(num);
        } else if (size > 3 && size <= 6) {
            int thousand = (int)(number/1000);
            int hundred = (int) (number % 1000);
            String thousands = handle3Digits(thousand);

            String hundreds = handle3Digits(hundred);
            String word = "";

            if (!thousands.isEmpty()) {
                word = thousands +" thousand";
            }
            word += hundreds;
            return word;
        } else if (size > 6 && size <= 9) {
            int million = (int) (number/ 1000000);
            number = number % 1000000;
            int thousand = (int)(number/1000);
            int hundred = (int) (number % 1000);

            String millions = handle3Digits(million);
            String thousands = handle3Digits(thousand);
            String hundreds = handle3Digits(hundred);

            String word = "";

            if (!millions.isEmpty()) {
                word = millions +" million";
            }
            if (!thousands.isEmpty()) {
                word += thousands +" thousand";
            }
            word += hundreds;
            return word;
        }

        return "Not implemented yet.";
    }


    private String handle3Digits(int number) {
        if (number <= 0)
            return "";

        String word = "";
        if (number/100 > 0) {
            int dividend = number/100;
            word = singleDigit[dividend] + " hundred";
            number = number % 100;
        }
        if (number/10 > 1) {
            int dividend = number/10;
            number = number % 10;
            word += twoDigits[dividend];
        } else if (number/10 == 1) {
            number = number % 10;
            word += tens[number];
            return word;
        } else {
            number = number % 10;
        }
        if (number > 0) {
            word += singleDigit[number];
        }

        return word;
    }
}

Winforms issue - Error creating window handle

I think it's normally related to the computer running out of memory so it's not able to create any more window handles. Normally windows starts to show some strange behavior at this point as well.

jQuery form validation on button click

Within your click handler, the mistake is the .validate() method; it only initializes the plugin, it does not validate the form.

To eliminate the need to have a submit button within the form, use .valid() to trigger a validation check...

$('#btn').on('click', function() {
    $("#form1").valid();
});

jsFiddle Demo

.validate() - to initialize the plugin (with options) once on DOM ready.

.valid() - to check validation state (boolean value) or to trigger a validation test on the form at any time.

Otherwise, if you had a type="submit" button within the form container, you would not need a special click handler and the .valid() method, as the plugin would capture that automatically.

Demo without click handler


EDIT:

You also have two issues within your HTML...

<input id="field1" type="text" class="required">
  • You don't need class="required" when declaring rules within .validate(). It's redundant and superfluous.

  • The name attribute is missing. Rules are declared within .validate() by their name. The plugin depends upon unique name attributes to keep track of the inputs.

Should be...

<input name="field1" id="field1" type="text" />

How to communicate between iframe and the parent site?

This library supports HTML5 postMessage and legacy browsers with resize+hash https://github.com/ternarylabs/porthole

Edit: Now in 2014, IE6/7 usage is quite low, IE8 and above all support postMessage so I now suggest to just use that.

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

How do you do a deep copy of an object in .NET?

I wrote a deep object copy extension method, based on recursive "MemberwiseClone". It is fast (three times faster than BinaryFormatter), and it works with any object. You don't need a default constructor or serializable attributes.

Source code:

using System.Collections.Generic;
using System.Reflection;
using System.ArrayExtensions;

namespace System
{
    public static class ObjectExtensions
    {
        private static readonly MethodInfo CloneMethod = typeof(Object).GetMethod("MemberwiseClone", BindingFlags.NonPublic | BindingFlags.Instance);

        public static bool IsPrimitive(this Type type)
        {
            if (type == typeof(String)) return true;
            return (type.IsValueType & type.IsPrimitive);
        }

        public static Object Copy(this Object originalObject)
        {
            return InternalCopy(originalObject, new Dictionary<Object, Object>(new ReferenceEqualityComparer()));
        }
        private static Object InternalCopy(Object originalObject, IDictionary<Object, Object> visited)
        {
            if (originalObject == null) return null;
            var typeToReflect = originalObject.GetType();
            if (IsPrimitive(typeToReflect)) return originalObject;
            if (visited.ContainsKey(originalObject)) return visited[originalObject];
            if (typeof(Delegate).IsAssignableFrom(typeToReflect)) return null;
            var cloneObject = CloneMethod.Invoke(originalObject, null);
            if (typeToReflect.IsArray)
            {
                var arrayType = typeToReflect.GetElementType();
                if (IsPrimitive(arrayType) == false)
                {
                    Array clonedArray = (Array)cloneObject;
                    clonedArray.ForEach((array, indices) => array.SetValue(InternalCopy(clonedArray.GetValue(indices), visited), indices));
                }

            }
            visited.Add(originalObject, cloneObject);
            CopyFields(originalObject, visited, cloneObject, typeToReflect);
            RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect);
            return cloneObject;
        }

        private static void RecursiveCopyBaseTypePrivateFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect)
        {
            if (typeToReflect.BaseType != null)
            {
                RecursiveCopyBaseTypePrivateFields(originalObject, visited, cloneObject, typeToReflect.BaseType);
                CopyFields(originalObject, visited, cloneObject, typeToReflect.BaseType, BindingFlags.Instance | BindingFlags.NonPublic, info => info.IsPrivate);
            }
        }

        private static void CopyFields(object originalObject, IDictionary<object, object> visited, object cloneObject, Type typeToReflect, BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy, Func<FieldInfo, bool> filter = null)
        {
            foreach (FieldInfo fieldInfo in typeToReflect.GetFields(bindingFlags))
            {
                if (filter != null && filter(fieldInfo) == false) continue;
                if (IsPrimitive(fieldInfo.FieldType)) continue;
                var originalFieldValue = fieldInfo.GetValue(originalObject);
                var clonedFieldValue = InternalCopy(originalFieldValue, visited);
                fieldInfo.SetValue(cloneObject, clonedFieldValue);
            }
        }
        public static T Copy<T>(this T original)
        {
            return (T)Copy((Object)original);
        }
    }

    public class ReferenceEqualityComparer : EqualityComparer<Object>
    {
        public override bool Equals(object x, object y)
        {
            return ReferenceEquals(x, y);
        }
        public override int GetHashCode(object obj)
        {
            if (obj == null) return 0;
            return obj.GetHashCode();
        }
    }

    namespace ArrayExtensions
    {
        public static class ArrayExtensions
        {
            public static void ForEach(this Array array, Action<Array, int[]> action)
            {
                if (array.LongLength == 0) return;
                ArrayTraverse walker = new ArrayTraverse(array);
                do action(array, walker.Position);
                while (walker.Step());
            }
        }

        internal class ArrayTraverse
        {
            public int[] Position;
            private int[] maxLengths;

            public ArrayTraverse(Array array)
            {
                maxLengths = new int[array.Rank];
                for (int i = 0; i < array.Rank; ++i)
                {
                    maxLengths[i] = array.GetLength(i) - 1;
                }
                Position = new int[array.Rank];
            }

            public bool Step()
            {
                for (int i = 0; i < Position.Length; ++i)
                {
                    if (Position[i] < maxLengths[i])
                    {
                        Position[i]++;
                        for (int j = 0; j < i; j++)
                        {
                            Position[j] = 0;
                        }
                        return true;
                    }
                }
                return false;
            }
        }
    }

}

How to trigger checkbox click event even if it's checked through Javascript code?

Trigger function from jQuery could be your answer.

jQuery docs says: Any event handlers attached with .on() or one of its shortcut methods are triggered when the corresponding event occurs. They can be fired manually, however, with the .trigger() method. A call to .trigger() executes the handlers in the same order they would be if the event were triggered naturally by the user

Thus best one line solution should be:

$('.selector_class').trigger('click');

//or

$('#foo').click();

How can I list all foreign keys referencing a given table in SQL Server?

There is how to get count of all responsibilities for selected Id. Just change @dbTableName value, @dbRowId value and its type (if int you need to remove '' in line no 82 (..SET @SQL = ..)). Enjoy.

DECLARE @dbTableName varchar(max) = 'User'
DECLARE @dbRowId uniqueidentifier = '21d34ecd-c1fd-11e2-8545-002219a42e1c'

DECLARE @FK_ROWCOUNT int
DECLARE @SQL nvarchar(max)

DECLARE @PKTABLE_QUALIFIER sysname
DECLARE @PKTABLE_OWNER sysname
DECLARE @PKTABLE_NAME sysname
DECLARE @PKCOLUMN_NAME sysname
DECLARE @FKTABLE_QUALIFIER sysname
DECLARE @FKTABLE_OWNER sysname
DECLARE @FKTABLE_NAME sysname
DECLARE @FKCOLUMN_NAME sysname
DECLARE @UPDATE_RULE smallint
DECLARE @DELETE_RULE smallint
DECLARE @FK_NAME sysname
DECLARE @PK_NAME sysname
DECLARE @DEFERRABILITY sysname

IF OBJECT_ID('tempdb..#Temp1') IS NOT NULL
    DROP TABLE #Temp1;
CREATE TABLE #Temp1 ( 
    PKTABLE_QUALIFIER sysname,
    PKTABLE_OWNER sysname,
    PKTABLE_NAME sysname,
    PKCOLUMN_NAME sysname,
    FKTABLE_QUALIFIER sysname,
    FKTABLE_OWNER sysname,
    FKTABLE_NAME sysname,
    FKCOLUMN_NAME sysname,
    UPDATE_RULE smallint,
    DELETE_RULE smallint,
    FK_NAME sysname,
    PK_NAME sysname,
    DEFERRABILITY sysname,
    FK_ROWCOUNT int
    );
DECLARE FK_Counter_Cursor CURSOR FOR
    SELECT PKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       PKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O1.SCHEMA_ID)),
       PKTABLE_NAME = CONVERT(SYSNAME,O1.NAME),
       PKCOLUMN_NAME = CONVERT(SYSNAME,C1.NAME),
       FKTABLE_QUALIFIER = CONVERT(SYSNAME,DB_NAME()),
       FKTABLE_OWNER = CONVERT(SYSNAME,SCHEMA_NAME(O2.SCHEMA_ID)),
       FKTABLE_NAME = CONVERT(SYSNAME,O2.NAME),
       FKCOLUMN_NAME = CONVERT(SYSNAME,C2.NAME),
       -- Force the column to be non-nullable (see SQL BU 325751)
       --KEY_SEQ             = isnull(convert(smallint,k.constraint_column_id), sysconv(smallint,0)),
       UPDATE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsUpdateCascade') 
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       DELETE_RULE = CONVERT(SMALLINT,CASE OBJECTPROPERTY(F.OBJECT_ID,'CnstIsDeleteCascade') 
                                        WHEN 1 THEN 0
                                        ELSE 1
                                      END),
       FK_NAME = CONVERT(SYSNAME,OBJECT_NAME(F.OBJECT_ID)),
       PK_NAME = CONVERT(SYSNAME,I.NAME),
       DEFERRABILITY = CONVERT(SMALLINT,7)   -- SQL_NOT_DEFERRABLE
    FROM   SYS.ALL_OBJECTS O1,
           SYS.ALL_OBJECTS O2,
           SYS.ALL_COLUMNS C1,
           SYS.ALL_COLUMNS C2,
           SYS.FOREIGN_KEYS F
           INNER JOIN SYS.FOREIGN_KEY_COLUMNS K
             ON (K.CONSTRAINT_OBJECT_ID = F.OBJECT_ID)
           INNER JOIN SYS.INDEXES I
             ON (F.REFERENCED_OBJECT_ID = I.OBJECT_ID
                 AND F.KEY_INDEX_ID = I.INDEX_ID)
    WHERE  O1.OBJECT_ID = F.REFERENCED_OBJECT_ID
           AND O2.OBJECT_ID = F.PARENT_OBJECT_ID
           AND C1.OBJECT_ID = F.REFERENCED_OBJECT_ID
           AND C2.OBJECT_ID = F.PARENT_OBJECT_ID
           AND C1.COLUMN_ID = K.REFERENCED_COLUMN_ID
           AND C2.COLUMN_ID = K.PARENT_COLUMN_ID
           AND O1.NAME = @dbTableName
OPEN FK_Counter_Cursor;
FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
WHILE @@FETCH_STATUS = 0
   BEGIN
        SET @SQL = 'SELECT @dbCountOut = COUNT(*) FROM [' + @FKTABLE_NAME + '] WHERE [' + @FKCOLUMN_NAME + '] = ''' + CAST(@dbRowId AS varchar(max)) + '''';
        EXECUTE sp_executesql @SQL, N'@dbCountOut int OUTPUT', @dbCountOut = @FK_ROWCOUNT OUTPUT;
        INSERT INTO #Temp1 (PKTABLE_QUALIFIER, PKTABLE_OWNER, PKTABLE_NAME, PKCOLUMN_NAME, FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, FKCOLUMN_NAME, UPDATE_RULE, DELETE_RULE, FK_NAME, PK_NAME, DEFERRABILITY, FK_ROWCOUNT) VALUES (@FKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY, @FK_ROWCOUNT)
      FETCH NEXT FROM FK_Counter_Cursor INTO @PKTABLE_QUALIFIER, @PKTABLE_OWNER, @PKTABLE_NAME, @PKCOLUMN_NAME, @FKTABLE_QUALIFIER, @FKTABLE_OWNER, @FKTABLE_NAME, @FKCOLUMN_NAME, @UPDATE_RULE, @DELETE_RULE, @FK_NAME, @PK_NAME, @DEFERRABILITY;
   END;
CLOSE FK_Counter_Cursor;
DEALLOCATE FK_Counter_Cursor;
GO
SELECT * FROM #Temp1
GO

how to loop through rows columns in excel VBA Macro

I'd recommend the Range object's AutoFill method for this:

rngSource.AutoFill Destination:=rngDest

Specify the Source range that contains the values or formulas you want to fill down, and the Destination range as the whole range that you want the cells filled to. The Destination range must include the Source range. You can fill across as well as down.

It works exactly the same way as it would if you manually "dragged" the cells at the corner with the mouse; absolute and relative formulas work as expected.

Here's an example:

'Set some example values'
Range("A1").Value = "1"
Range("B1").Formula = "=NOW()"
Range("C1").Formula = "=B1+A1"

'AutoFill the values / formulas to row 20'
Range("A1:C1").AutoFill Destination:=Range("A1:C20")

Hope this helps.

Does Index of Array Exist

Assuming you also want to check if the item is not null

if (array.Length > 25 && array[25] != null)
{
    //it exists
}

Passing a method as a parameter in Ruby

You want a proc object:

gaussian = Proc.new do |dist, *args|
  sigma = args.first || 10.0
  ...
end

def weightedknn(data, vec1, k = 5, weightf = gaussian)
  ...
  weight = weightf.call(dist)
  ...
end

Just note that you can't set a default argument in a block declaration like that. So you need to use a splat and setup the default in the proc code itself.


Or, depending on your scope of all this, it may be easier to pass in a method name instead.

def weightedknn(data, vec1, k = 5, weightf = :gaussian)
  ...
  weight = self.send(weightf)
  ...
end

In this case you are just calling a method that is defined on an object rather than passing in a complete chunk of code. Depending on how you structure this you may need replace self.send with object_that_has_the_these_math_methods.send


Last but not least, you can hang a block off the method.

def weightedknn(data, vec1, k = 5)
  ...
  weight = 
    if block_given?
      yield(dist)
    else
      gaussian.call(dist)
    end
  end
  ...
end

weightedknn(foo, bar) do |dist|
  # square the dist
  dist * dist
end

But it sounds like you would like more reusable chunks of code here.

twitter bootstrap navbar fixed top overlapping site

Your answer is right in the docs:

Body padding required

The fixed navbar will overlay your other content, unless you add padding to the top of the <body>. Try out your own values or use our snippet below. Tip: By default, the navbar is 50px high.

body { padding-top: 70px; }

Make sure to include this after the core Bootstrap CSS.

and in the Bootstrap 4 docs...

Fixed navbars use position: fixed, meaning they’re pulled from the normal flow of the DOM and may require custom CSS (e.g., padding-top on the ) to prevent overlap with other elements.

PowerShell to remove text from a string

This is really old, but I wanted to add my slight variation for anyone else who may stumble across this. Regular expressions are powerful things.

To keep the text which falls between the equal sign and the comma:

-replace "^.*?=(.*?),.*?$",'$1'

This regular expression starts at the beginning of the line, wipes all characters until the first equal sign, captures every character until the next comma, then wipes every character until the end of the line. It then replaces the entire line with the capture group (anything within the parentheses). It will match any line that contains at least one equal sign followed by at least one comma. It is similar to the suggestion by Trix, but unlike that suggestion, this will not match lines which only contain either an equal sign or a comma, it must have both in order.

Address already in use: JVM_Bind java

Address already in use: JVM_Bind

means that some other application is already listening on the port your current application is trying to bind.

what you need to do is, either change the port for your current application or better; just find out the already running application and kill it.

on Linux you can find the application pid by using,

netstat -tulpn

mysql said: Cannot connect: invalid settings. xampp

In xampp\phpMyAdmin\config.inc.php : changing:

'config';$cfg['Servers'][$i]['user'] = 'root'

to

'config';$cfg['Servers'][$i]['user'] = 'user'

and

$cfg['Servers'][$i]['controluser'] = 'root'

to

$cfg['Servers'][$i]['controluser'] = 'user'

Solved my Problem.

pandas: multiple conditions while indexing data frame - unexpected behavior

You can also use query(), i.e.:

df_filtered = df.query('a == 4 & b != 2')

jQuery date/time picker

In my view, dates and times should be handled as two separate input boxes for it to be most usable and efficient for the user to input. Let the user input one thing at a time is a good principle, imho.

I use the core UI DatePicker, and the following time picker.

This one is inspired by the one Google Calendar uses:

jQuery timePicker:
examples: http://labs.perifer.se/timedatepicker/
project on github: https://github.com/perifer/timePicker

I found it to be the best among all of the alternatives. User can input fast, it looks clean, is simple, and allows user to input specific times down to the minute.

PS: In my view: sliders (used by some alternative time pickers) take too many clicks and require mouse precision from the user (which makes input slower).

Find a value in DataTable

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

What is the syntax of the enhanced for loop in Java?

Enhanced for loop:

for (String element : array) {

    // rest of code handling current element
}

Traditional for loop equivalent:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

Take a look at these forums: https://blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

How to set Google Chrome in WebDriver

Aditya,

As you said in your last comment that you are trying to access chrome of some other system so based on that you should keep your chrome driver in that system itself.

for example: if you are trying to access linux chrome from windows then you need to put your chrome driver in linux at some place and give permission as 777 and use below code at your windows system.

System.setProperty("webdriver.chrome.driver", "\\var\\www\\Jar\\chromedriver");
Capability= DesiredCapabilities.chrome();   Capability.setPlatform(org.openqa.selenium.Platform.ANY);
browser=new RemoteWebDriver(new URL(nodeURL),Capability);

This is working code of my system.

FFmpeg on Android

Strange that this project hasn't been mentioned: AndroidFFmpeg from Appunite

It has quite detailed step-by-step instructions to copy/paste to command line, for lazy people like me ))

Getting a better understanding of callback functions in JavaScript

Here is a basic example that explains the callback() function in JavaScript:

_x000D_
_x000D_
var x = 0;_x000D_
_x000D_
function testCallBack(param1, param2, callback) {_x000D_
  alert('param1= ' + param1 + ', param2= ' + param2 + ' X=' + x);_x000D_
  if (callback && typeof(callback) === "function") {_x000D_
    x += 1;_x000D_
    alert("Calla Back x= " + x);_x000D_
    x += 1;_x000D_
    callback();_x000D_
  }_x000D_
}_x000D_
_x000D_
testCallBack('ham', 'cheese', function() {_x000D_
  alert("Function X= " + x);_x000D_
});
_x000D_
_x000D_
_x000D_

JSFiddle

Error parsing yaml file: mapping values are not allowed here

Or, if spacing is not the problem, it might want the parent directory name rather than the file name.

Not $ dev_appserver helloapp.py
But $ dev_appserver hello/

For example:

Johns-Mac:hello john$ dev_appserver.py helloworld.py
Traceback (most recent call last):
  File "/usr/local/bin/dev_appserver.py", line 82, in <module>
    _run_file(__file__, globals())
...
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/yaml_listener.py", line 212, in _GenerateEventParameters
    raise yaml_errors.EventListenerYAMLError(e)
google.appengine.api.yaml_errors.EventListenerYAMLError: mapping values are not allowed here
  in "helloworld.py", line 3, column 39

Versus

Johns-Mac:hello john$ cd ..
Johns-Mac:fbm john$ dev_appserver.py hello/
INFO     2014-09-15 11:44:27,828 api_server.py:171] Starting API server at: http://localhost:61049
INFO     2014-09-15 11:44:27,831 dispatcher.py:183] Starting module "default" running at: http://localhost:8080

Drop all data in a pandas dataframe

My favorite:

df = df.iloc[0:0]

But be aware df.index.max() will be nan. To add items I use:

df.loc[0 if math.isnan(df.index.max()) else df.index.max() + 1] = data

What is recursion and when should I use it?

In plain English: Assume you can do 3 things:

  1. Take one apple
  2. Write down tally marks
  3. Count tally marks

You have a lot of apples in front of you on a table and you want to know how many apples there are.

start
  Is the table empty?
  yes: Count the tally marks and cheer like it's your birthday!
  no:  Take 1 apple and put it aside
       Write down a tally mark
       goto start

The process of repeating the same thing till you are done is called recursion.

I hope this is the "plain english" answer you are looking for!

How to check if an email address exists without sending an email?

function EmailValidation($email)
{
    $email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits
    if (eregi('[a-z||0-9]@[a-z||0-9].[a-z]', $email)) {
        //checks to make sure the email address is in a valid format
        $domain = explode( "@", $email ); //get the domain name
        if (@fsockopen ($domain[1],80,$errno,$errstr,3)) {
            //if the connection can be established, the email address is probably valid
            echo "Domain Name is valid ";
            return true;
        } else {
            echo "Con not a email domian";
            return false; //if a connection cannot be established return false
        }
        return false; //if email address is an invalid format return false
    }
}

Strip Leading and Trailing Spaces From Java String

You can try the trim() method.

String newString = oldString.trim();

Take a look at javadocs

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

Dynamically adding HTML form field using jQuery

There appears to be a bug with appendTo using a frameset ID appending to a FORM in Chrome. Swapped out the attribute type directly with div and it works.

static files with express.js

express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.

Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:

By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.

How to send post request with x-www-form-urlencoded body

string urlParameters = "param1=value1&param2=value2";
string _endPointName = "your url post api";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                                                  (se, cert, chain, sslerror) =>
                                                  {
                                                      return true;
                                                  };


using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(urlParameters);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }

How do I clone a generic list in C#?

If you have already referenced Newtonsoft.Json in your project and your objects are serializeable you could always use:

List<T> newList = JsonConvert.DeserializeObject<T>(JsonConvert.SerializeObject(listToCopy))

Possibly not the most efficient way to do it, but unless you're doing it 100s of 1000s of times you may not even notice the speed difference.

Get a list of checked checkboxes in a div using jQuery

I needed the count of all checkboxes which are checked. Instead of writing a loop i did this

$(".myCheckBoxClass:checked").length;

Compare it with the total number of checkboxes to see if they are equal. Hope it will help someone

CMake: How to build external projects and include their targets

cmake's ExternalProject_Add indeed can used, but what I did not like about it - is that it performs something during build, continuous poll, etc... I would prefer to build project during build phase, nothing else. I have tried to override ExternalProject_Add in several attempts, unfortunately without success.

Then I have tried also to add git submodule, but that drags whole git repository, while in certain cases I need only subset of whole git repository. What I have checked - it's indeed possible to perform sparse git checkout, but that require separate function, which I wrote below.

#-----------------------------------------------------------------------------
#
# Performs sparse (partial) git checkout
#
#   into ${checkoutDir} from ${url} of ${branch}
#
# List of folders and files to pull can be specified after that.
#-----------------------------------------------------------------------------
function (SparseGitCheckout checkoutDir url branch)
    if(EXISTS ${checkoutDir})
        return()
    endif()

    message("-------------------------------------------------------------------")
    message("sparse git checkout to ${checkoutDir}...")
    message("-------------------------------------------------------------------")

    file(MAKE_DIRECTORY ${checkoutDir})

    set(cmds "git init")
    set(cmds ${cmds} "git remote add -f origin --no-tags -t master ${url}")
    set(cmds ${cmds} "git config core.sparseCheckout true")

    # This command is executed via file WRITE
    # echo <file or folder> >> .git/info/sparse-checkout")

    set(cmds ${cmds} "git pull --depth=1 origin ${branch}")

    # message("In directory: ${checkoutDir}")

    foreach( cmd ${cmds})
        message("- ${cmd}")
        string(REPLACE " " ";" cmdList ${cmd})

        #message("Outfile: ${outFile}")
        #message("Final command: ${cmdList}")

        if(pull IN_LIST cmdList)
            string (REPLACE ";" "\n" FILES "${ARGN}")
            file(WRITE ${checkoutDir}/.git/info/sparse-checkout ${FILES} )
        endif()

        execute_process(
            COMMAND ${cmdList}
            WORKING_DIRECTORY ${checkoutDir}
            RESULT_VARIABLE ret
        )

        if(NOT ret EQUAL "0")
            message("error: previous command failed, see explanation above")
            file(REMOVE_RECURSE ${checkoutDir})
            break()
        endif()
    endforeach()

endfunction()


SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_197 https://github.com/catchorg/Catch2.git v1.9.7 single_include)
SparseGitCheckout(${CMAKE_BINARY_DIR}/catch_master https://github.com/catchorg/Catch2.git master single_include)

I have added two function calls below just to illustrate how to use the function.

Someone might not like to checkout master / trunk, as that one might be broken - then it's always possible to specify specific tag.

Checkout will be performed only once, until you clear the cache folder.

7-zip commandline

Instead of the option a use option x, this will create the directories but only for extraction, not compression.

test if display = none

$('tbody').find('tr:visible').hightlight(myArray[i]);

Sql Server 'Saving changes is not permitted' error ? Prevent saving changes that require table re-creation

Do you use SSMS?

If yes, goto the menu Tools >> Options >> Designers and uncheck “Prevent Saving changes that require table re-creation”

Way to go from recursion to iteration

Strive to make your recursive call Tail Recursion (recursion where the last statement is the recursive call). Once you have that, converting it to iteration is generally pretty easy.

How to pad a string to a fixed length with spaces in Python?

name = "John" // your variable
result = (name+"               ")[:15] # this adds 15 spaces to the "name"
                                       # but cuts it at 15 characters

How to find the index of an element in an array in Java?

That's not even valid syntax. And you're trying to compare to a string. For arrays you would have to walk the array yourself:

public class T {
  public static void main( String args[] ) {
    char[] list = {'m', 'e', 'y'};

    int index = -1;

    for (int i = 0; (i < list.length) && (index == -1); i++) {
        if (list[i] == 'e') {
            index = i;
        }
    }

    System.out.println(index);
  }
}

If you are using a collection, such as ArrayList<Character> you can also use the indexOf() method:

ArrayList<Character> list = new ArrayList<Character>();
list.add('m');
list.add('e');
list.add('y');

System.out.println(list.indexOf('e'));

There is also the Arrays class which shortens above code:

List list = Arrays.asList(new Character[] { 'm', 'e', 'y' });
System.out.println(list.indexOf('e'));

Check existence of input argument in a Bash shell script

I often use this snippet for simple scripts:

#!/bin/bash

if [ -z "$1" ]; then
    echo -e "\nPlease call '$0 <argument>' to run this command!\n"
    exit 1
fi

How to pop an alert message box using PHP?

You could use Javascript:

// This is in the PHP file and sends a Javascript alert to the client
$message = "wrong answer";
echo "<script type='text/javascript'>alert('$message');</script>";

What is the inclusive range of float and double in Java?

Of course you can use floats or doubles for "critical" things ... Many applications do nothing but crunch numbers using these datatypes.

You might have misunderstood some of the various caveats regarding floating-point numbers, such as the recommendation to never compare for exact equality, and so on.

How to Deep clone in javascript

Avoid use this method

let cloned = JSON.parse(JSON.stringify(objectToClone));

Why? this method will convert 'function,undefined' to null

const myObj = [undefined, null, function () {}, {}, '', true, false, 0, Symbol];

const IsDeepClone = JSON.parse(JSON.stringify(myObj));

console.log(IsDeepClone); //[null, null, null, {…}, "", true, false, 0, null]

try to use deepClone function.There are several above

Generate HTML table from 2D JavaScript array

Generate table and support HTML as input.

Inspired by @spiny-norman https://stackoverflow.com/a/15164796/2326672

And @bornd https://stackoverflow.com/a/6234804/2326672

function escapeHtml(unsafe) {
    return String(unsafe)
         .replace(/&/g, "&amp;")
         .replace(/</g, "&lt;")
         .replace(/>/g, "&gt;")
         .replace(/"/g, "&quot;")
         .replace(/'/g, "&#039;");
 }

function makeTableHTML(myArray) {
    var result = "<table border=1>";
    for(var i=0; i<myArray.length; i++) {
        result += "<tr>";
        for(var j=0; j<myArray[i].length; j++){
            k = escapeHtml((myArray[i][j]));
            result += "<td>"+k+"</td>";
        }
        result += "</tr>";
    }
    result += "</table>";

    return result;
}

Test here with JSFIDDLE - Paste directly from Microsoft Excel to get table

Best way to reset an Oracle sequence to the next value in an existing column?

Today, in Oracle 12c or newer, you probably have the column defined as GENERATED ... AS IDENTITY, and Oracle takes care of the sequence itself.

You can use an ALTER TABLE Statement to modify "START WITH" of the identity.

ALTER TABLE tbl MODIFY ("ID" NUMBER(13,0) GENERATED BY DEFAULT ON NULL AS IDENTITY MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 3580 NOT NULL ENABLE);

Disable PHP in directory (including all sub-directories) with .htaccess

If you're using mod_php, you could put (either in a .htaccess in /USERS or in your httpd.conf for the USERS directory)

RemoveHandler .php

or

RemoveType .php

(depending on whether PHP is enabled using AddHandler or AddType)

PHP files run from another directory will be still able to include files in /USERS (assuming that there is no open_basedir restriction), because this does not go through Apache. If a php file is accessed using apache it will be serverd as plain text.

Edit

Lance Rushing's solution of just denying access to the files is probably better

Batch Files - Error Handling

A successful ping on your local network can be trapped using ERRORLEVEL.

@ECHO OFF
PING 10.0.0.123
IF ERRORLEVEL 1 GOTO NOT-THERE
ECHO IP ADDRESS EXISTS
PAUSE
EXIT
:NOT-THERE
ECHO IP ADDRESS NOT NOT EXIST
PAUSE
EXIT

What is the maximum possible length of a .NET string?

Based on my highly scientific and accurate experiment, it tops out on my machine well before 1,000,000,000 characters. (I'm still running the code below to get a better pinpoint).

UPDATE: After a few hours, I've given up. Final results: Can go a lot bigger than 100,000,000 characters, instantly given System.OutOfMemoryException at 1,000,000,000 characters.

using System;
using System.Collections.Generic;

public class MyClass
{
    public static void Main()
    {
        int i = 100000000;
        try
        {
            for (i = i; i <= int.MaxValue; i += 5000)
            {
                string value = new string('x', i);
                //WL(i);
            }
        }
        catch (Exception exc)
        {
            WL(i);
            WL(exc);
        }
        WL(i);
        RL();
    }

    #region Helper methods

    private static void WL(object text, params object[] args)
    {
        Console.WriteLine(text.ToString(), args);   
    }

    private static void RL()
    {
        Console.ReadLine(); 
    }

    private static void Break() 
    {
        System.Diagnostics.Debugger.Break();
    }

    #endregion
}

How to escape a JSON string to have it in a URL?

encodeURIComponent(JSON.stringify(object_to_be_serialised))

Extract MSI from EXE

There is no need to use any tool !! We can follow the simple way.

I do not know which tool built your self-extracting Setup program and so, I will have to provide a general response.

Most programs of this nature extract the package file (.msi) into the TEMP directory. This behavior is the default behavior of InstallShield Developer.

Without additional information, I would recommend that you simply launch the setup and once the first MSI dialog is displayed, you can examine your TEMP directory for a newly created sub-directory or MSI file. Before cancelling/stopping an installer just copy that MSI file from TEMP folder. After that you can cancel the installation.

Multiple file extensions in OpenFileDialog

Based on First answer here is the complete image selection options:

Filter = @"|All Image Files|*.BMP;*.bmp;*.JPG;*.JPEG*.jpg;*.jpeg;*.PNG;*.png;*.GIF;*.gif;*.tif;*.tiff;*.ico;*.ICO
           |PNG|*.PNG;*.png
           |JPEG|*.JPG;*.JPEG*.jpg;*.jpeg
           |Bitmap(.BMP,.bmp)|*.BMP;*.bmp                                    
           |GIF|*.GIF;*.gif
           |TIF|*.tif;*.tiff
           |ICO|*.ico;*.ICO";

How to compile Go program consisting of multiple files?

New Way (Recommended):

Please take a look at this answer.

Old Way:

Supposing you're writing a program called myprog :

Put all your files in a directory like this

myproject/go/src/myprog/xxx.go

Then add myproject/go to GOPATH

And run

go install myprog

This way you'll be able to add other packages and programs in myproject/go/src if you want.

Reference : http://golang.org/doc/code.html

(this doc is always missed by newcomers, and often ill-understood at first. It should receive the greatest attention of the Go team IMO)

CSV in Python adding an extra carriage return, on Windows

Note that if you use DictWriter, you will have a new line from the open function and a new line from the writerow function. You can use newline='' within the open function to remove the extra newline.

Chart.js v2 - hiding grid lines

If you want them gone by default, you can set:

Chart.defaults.scale.gridLines.display = false;

first-child and last-child with IE8

Since :last-child is a CSS3 pseudo-class, it is not supported in IE8. I believe :first-child is supported, as it's defined in the CSS2.1 specification.

One possible solution is to simply give the last child a class name and style that class.

Another would be to use JavaScript. jQuery makes this particularly easy as it provides a :last-child pseudo-class which should work in IE8. Unfortunately, that could result in a flash of unstyled content while the DOM loads.

What is the proper way to check and uncheck a checkbox in HTML5?

Complementary answer to Robert's answer http://jsfiddle.net/ak9Sb/ in jQuery

When getting/setting checkbox state, one may encounter these phenomenons:

.trigger("click");

Does check an unchecked checkbox, but do not add the checked attribute. If you use triggers, do not try to get the state with "checked" attribute.

.attr("checked", "");

Does not uncheck the checkbox...