Programs & Examples On #Sqltransaction

how to use sqltransaction in c#

First you don't need a transaction since you are just querying select statements and since they are both select statement you can just combine them into one query separated by space and use Dataset to get the all the tables retrieved. Its better this way since you made only one transaction to the database because database transactions are expensive hence your code is faster. Second of you really have to use a transaction, just assign the transaction to the SqlCommand like

sqlCommand.Transaction = transaction;

And also just use one SqlCommand don't declare more than one, since variables consume space and we are also on the topic of making your code more efficient, do that by assigning commandText to different query string and executing them like

sqlCommand.CommandText = "select * from table1";
sqlCommand.ExecuteNonQuery();
sqlCommand.CommandText = "select * from table2";
sqlCommand.ExecuteNonQuery();

How to get "their" changes in the middle of conflicting Git rebase?

If you want to pull a particular file from another branch just do

git checkout branch1 -- filenamefoo.txt

This will pull a version of the file from one branch into the current tree

Difference between Encapsulation and Abstraction

Abstraction

In Java, abstraction means hiding the information to the real world. It establishes the contract between the party to tell about “what should we do to make use of the service”.

Example, In API development, only abstracted information of the service has been revealed to the world rather the actual implementation. Interface in java can help achieve this concept very well.

Interface provides contract between the parties, example, producer and consumer. Producer produces the goods without letting know the consumer how the product is being made. But, through interface, Producer let all consumer know what product can buy. With the help of abstraction, producer can markets the product to their consumers.

Encapsulation:

Encapsulation is one level down of abstraction. Same product company try shielding information from each other production group. Example, if a company produce wine and chocolate, encapsulation helps shielding information how each product Is being made from each other.

  1. If I have individual package one for wine and another one for chocolate, and if all the classes are declared in the package as default access modifier, we are giving package level encapsulation for all classes.
  2. Within a package, if we declare each class filed (member field) as private and having a public method to access those fields, this way giving class level encapsulation to those fields

How to resolve the C:\fakepath?

I came accross the same problem. In IE8 it could be worked-around by creating a hidden input after the file input control. The fill this with the value of it's previous sibling. In IE9 this has been fixed aswell.

My reason in wanting to get to know the full path was to create an javascript image preview before uploading. Now I have to upload the file to create a preview of the selected image.

jQuery pass more parameters into callback

It's actually easier than everyone's making it sound... especially if you use the $.ajax({}) base syntax vs. one of the helper functions.

Just pass in the key: value pair like you would on any object, when you setup your ajax request... (because $(this) hasn't changed context yet, it's still the trigger for the bind call above)

<script type="text/javascript">
$(".qty input").bind("keypress change", function() {
    $.ajax({
        url: "/order_items/change/"+$(this).attr("data-order-item-id")+"/qty:"+$(this).val()+"/returnas.json",
        type: "POST",
        dataType: "json",
        qty_input: $(this),
        anything_else_i_want_to_pass_in: "foo",
        success: function(json_data, textStatus, jqXHR) {
            /* here is the input, which triggered this AJAX request */
            console.log(this.qty_input);
            /* here is any other parameter you set when initializing the ajax method */
            console.log(this.anything_else_i_want_to_pass_in);
        }
    });
});
</script>

One of the reasons this is better than setting the var, is that the var is global and as such, overwritable... if you have 2 things which can trigger ajax calls, you could in theory trigger them faster than ajax call responds, and you'd have the value for the second call passed into the first. Using this method, above, that wouldn't happen (and it's pretty simple to use too).

java.lang.ClassNotFoundException: com.sun.jersey.spi.container.servlet.ServletContainer

In pom.xml file we need to add

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-core</artifactId>
    <version>1.8</version>
</dependency>

A Java collection of value pairs? (tuples?)

AbstractMap.SimpleEntry

Easy you are looking for this:

java.util.List<java.util.Map.Entry<String,Integer>> pairList= new java.util.ArrayList<>();

How can you fill it?

java.util.Map.Entry<String,Integer> pair1=new java.util.AbstractMap.SimpleEntry<>("Not Unique key1",1);
java.util.Map.Entry<String,Integer> pair2=new java.util.AbstractMap.SimpleEntry<>("Not Unique key2",2);
pairList.add(pair1);
pairList.add(pair2);

This simplifies to:

Entry<String,Integer> pair1=new SimpleEntry<>("Not Unique key1",1);
Entry<String,Integer> pair2=new SimpleEntry<>("Not Unique key2",2);
pairList.add(pair1);
pairList.add(pair2);

And, with the help of a createEntry method, can further reduce the verbosity to:

pairList.add(createEntry("Not Unique key1", 1));
pairList.add(createEntry("Not Unique key2", 2));

Since ArrayList isn't final, it can be subclassed to expose an of method (and the aforementioned createEntry method), resulting in the syntactically terse:

TupleList<java.util.Map.Entry<String,Integer>> pair = new TupleList<>();
pair.of("Not Unique key1", 1);
pair.of("Not Unique key2", 2);

How to loop through file names returned by find?

I like to use find which is first assigned to variable and IFS switched to new line as follow:

FilesFound=$(find . -name "*.txt")

IFSbkp="$IFS"
IFS=$'\n'
counter=1;
for file in $FilesFound; do
    echo "${counter}: ${file}"
    let counter++;
done
IFS="$IFSbkp"

As commented by @Konrad Rudolph this will not work with "new lines" in file name. I still think it is handy as it covers most of the cases when you need to loop over command output.

Ternary operator in PowerShell

Try powershell's switch statement as an alternative, especially for variable assignment - multiple lines, but readable.

Example,

$WinVer = switch ( Test-Path $Env:windir\SysWOW64 ) {
  $true    { "64-bit" }
  $false   { "32-bit" }
}
"This version of Windows is $WinVer"

Java : Cannot format given Object as a Date

DateFormat.format only works on Date values.

You should use two SimpleDateFormat objects: one for parsing, and one for formatting. For example:

// Note, MM is months, not mm
DateFormat outputFormat = new SimpleDateFormat("MM/yyyy", Locale.US);
DateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSX", Locale.US);

String inputText = "2012-11-17T00:00:00.000-05:00";
Date date = inputFormat.parse(inputText);
String outputText = outputFormat.format(date);

EDIT: Note that you may well want to specify the time zone and/or locale in your formats, and you should also consider using Joda Time instead of all of this to start with - it's a much better date/time API.

Remove insignificant trailing zeros from a number?

How about just multiplying by one like this?

var x = 1.234000*1; // becomes 1.234

var y = 1.234001*1; // stays as 1.234001

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

I know it might be late but I'm just adding to Lanti's answer since it's the most popular, I had the same problem as Wouter Vanherck in the comments and I can't comment yet.

What helped for me was instead of just replacing \xampp\apache\conf\extra\httpd-xampp.conf I replaced the whole apache folder. I basically did the same thing with it as with the php folder (steps 2 and 3).

Now the error is fixed and Apache starts just fine.

Tooltips for cells in HTML table (no Javascript)

Yes. You can use the title attribute on cell elements, with poor usability, or you can use CSS tooltips (several existing questions, possibly duplicates of this one).

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

How to make a HTML list appear horizontally instead of vertically using CSS only?

Using display: inline-flex

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
  display: inline-flex_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Using display: inline-block

_x000D_
_x000D_
#menu ul {_x000D_
  list-style: none;_x000D_
  margin: 0;_x000D_
  padding: 0;_x000D_
}_x000D_
_x000D_
#menu li {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div id="menu">_x000D_
  <ul>_x000D_
    <li>1 menu item</li>_x000D_
    <li>2 menu item</li>_x000D_
    <li>3 menu item</li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I set the driver's python version in spark?

You need to make sure the standalone project you're launching is launched with Python 3. If you are submitting your standalone program through spark-submit then it should work fine, but if you are launching it with python make sure you use python3 to start your app.

Also, make sure you have set your env variables in ./conf/spark-env.sh (if it doesn't exist you can use spark-env.sh.template as a base.)

In C++ check if std::vector<string> contains a certain value

You can use std::find as follows:

if (std::find(v.begin(), v.end(), "abc") != v.end())
{
  // Element in vector.
}

To be able to use std::find: include <algorithm>.

Python JSON encoding

The data you are encoding is a keyless array, so JSON encodes it with [] brackets. See www.json.org for more information about that. The curly braces are used for lists with key/value pairs.

From www.json.org:

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array. An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

An object is an unordered set of name/value pairs. An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).

An array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

jquery select option click handler

you can attach a focus event to select

$('#select_id').focus(function() {
    console.log('Handler for .focus() called.');
});

Best Java obfuscator?

Check out my article Protect Your Java Code - Through Obfuscators And Beyond [Archived] for a discussion of obfuscation vs three other ways to make the reverse engineering of your apps more expensive, and a collection of links to tools and further reading materials.

How to Migrate to WKWebView?

Swift 4

    let webView = WKWebView()   // Set Frame as per requirment, I am leaving it for you
    let url = URL(string: "http://www.google.com")!
    webView.load(URLRequest(url: url))
    view.addSubview(webView)

Can I remove the URL from my print css, so the web address doesn't print?

The headers and footers for printing from browsers is, sadly, a browser preference, not a document-level element that you can style. Refer to my very similar question for further workarounds and disappointment.

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

error: resource android:attr/fontVariationSettings not found

My case was really different. I had set android:text=" ??? " property of my TetxtView in my layout file, when I changed it to android:text=" ? " it worked. I have no idea why this works, maybe it helps someone. It took me hours to find the issue.

Iterating through a JSON object

After deserializing the JSON, you have a python object. Use the regular object methods.

In this case you have a list made of dictionaries:

json_object[0].items()

json_object[0]["title"]

etc.

Mathematical functions in Swift

You can use them right inline:

var square = 9.4
var floored = floor(square)
var root = sqrt(floored)

println("Starting with \(square), we rounded down to \(floored), then took the square root to end up with \(root)")

Use 'import module' or 'from module import'?

since many people answered here but i am just trying my best :)

  1. import module is best when you don't know which item you have to import from module. In this way it may be difficult to debug when problem raises because you don't know which item have problem.

  2. form module import <foo> is best when you know which item you require to import and also helpful in more controlling using importing specific item according to your need. Using this way debugging may be easy because you know which item you imported.

Order Bars in ggplot2 bar graph

You just need to specify the Position column to be an ordered factor where the levels are ordered by their counts:

theTable <- transform( theTable,
       Position = ordered(Position, levels = names( sort(-table(Position)))))

(Note that the table(Position) produces a frequency-count of the Position column.)

Then your ggplot function will show the bars in decreasing order of count. I don't know if there's an option in geom_bar to do this without having to explicitly create an ordered factor.

How to detect if a stored procedure already exists

You can write a query as follows:

IF OBJECT_ID('ProcedureName','P') IS NOT NULL
    DROP PROC ProcedureName
GO

CREATE PROCEDURE [dbo].[ProcedureName]
...your query here....

To be more specific on the above syntax:
OBJECT_ID is a unique id number for an object within the database, this is used internally by SQL Server. Since we are passing ProcedureName followed by you object type P which tells the SQL Server that you should find the object called ProcedureName which is of type procedure i.e., P

This query will find the procedure and if it is available it will drop it and create new one.

For detailed information about OBJECT_ID and Object types please visit : SYS.Objects

How to insert text at beginning of a multi-line selection in vi/Vim

To insert "ABC" at the begining of each line:

1) Go to command mode

2) :% norm I ABC

Send string to stdin

You can use one-line heredoc

cat <<< "This is coming from the stdin"

the above is the same as

cat <<EOF
This is coming from the stdin
EOF

or you can redirect output from a command, like

diff <(ls /bin) <(ls /usr/bin)

or you can read as

while read line
do
   echo =$line=
done < some_file

or simply

echo something | read param

CSS - how to make image container width fixed and height auto stretched

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/

"Server Tomcat v7.0 Server at localhost failed to start" without stack trace while it works in terminal

i encountered this problem ,becaues i define servlet mapping in servlet class and web.xml.

You must to be careful to check whether you have defined servlet mapping in your servlet class and web.xml

1)delete @WebServlet("...")

@WebServlet("/Login")
public class Login extends HttpServlet {
}

OR

2)delete <servlet></servlet> <servlet-mapping></servlet-mapping>

<servlet>
    <servlet-name>ServletLogin</servlet-name>
    <servlet-class>Login</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>ServletLogin</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

Reason:

I use apache tomcat 7.0 which supports servlet 3.0.

With Java EE annotations, the standard web.xml deployment descriptor is

optional. According to the servlet 3.0 specification at

http://jcp.org/en/jsr/detail?id=315

How to transfer paid android apps from one google account to another google account

Google has this to say on transferring data between accounts.

http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304

It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.

It's conveniently titled: "Moving Product Data"

http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582

How to convert numbers to words without using num2word library?

I know that this is a very old post and I am probably very late to the party, but hopefully this will help someone else. This has worked for me.

phone_words = input('Phone: ')
numbered_words = {
    '0': 'zero',
    '1': 'one',
    '2': 'two',
    '3': 'three',
    '4': 'four',
    '5': 'five',
    '6': 'six',
    '7': 'seven',
    '8': 'eight',
    '9': 'nine'
}
output = ""
for ch in phone_words:
    output += numbered_words.get(ch, "!") + " "
phone_words = numbered_words

print(output)

How to indent HTML tags in Notepad++

Step 1: Open plugin manager in notepad++

Plugins -> Plugin Manager -> Show Plugin Manager.

Step 2:install XML Tool plugin

Search "XML TOOLS" from the "Available" option then click in install.

Now you can use shortcut key CTRL+ALT+SHIFT+B to indent the code.

How can I compare two ordered lists in python?

If you want to just check if they are identical or not, a == b should give you true / false with ordering taken into account.

In case you want to compare elements, you can use numpy for comparison

c = (numpy.array(a) == numpy.array(b))

Here, c will contain an array with 3 elements all of which are true (for your example). In the event elements of a and b don't match, then the corresponding elements in c will be false.

Combining two Series into a DataFrame in pandas

Pandas will automatically align these passed in series and create the joint index They happen to be the same here. reset_index moves the index to a column.

In [2]: s1 = Series(randn(5),index=[1,2,4,5,6])

In [4]: s2 = Series(randn(5),index=[1,2,4,5,6])

In [8]: DataFrame(dict(s1 = s1, s2 = s2)).reset_index()
Out[8]: 
   index        s1        s2
0      1 -0.176143  0.128635
1      2 -1.286470  0.908497
2      4 -0.995881  0.528050
3      5  0.402241  0.458870
4      6  0.380457  0.072251

How do you hide the Address bar in Google Chrome for Chrome Apps?

enter image description here

in macOS make service by automator.

that's it. you can assign short cut.

How can I get an HTTP response body as a string?

How about just this?

org.apache.commons.io.IOUtils.toString(new URL("http://www.someurl.com/"));

NLS_NUMERIC_CHARACTERS setting for decimal

Jaanna, the session parameters in Oracle SQL Developer are dependent on your client computer, while the NLS parameters on PL/SQL is from server.

For example the NLS_NUMERIC_CHARACTERS on client computer can be ',.' while it's '.,' on server.

So when you run script from PL/SQL and Oracle SQL Developer the decimal separator can be completely different for the same script, unless you alter session with your expected NLS_NUMERIC_CHARACTERS in the script.

One way to easily test your session parameter is to do:

select to_number(5/2) from dual;

Programmatically extract contents of InstallShield setup.exe

The free and open-source program called cabextract will list and extract the contents of not just .cab-files, but Macrovision's archives too:

% cabextract /tmp/QLWREL.EXE
Extracting cabinet: /tmp/QLWREL.EXE
  extracting ikernel.dll
  extracting IsProBENT.tlb
  ....
  extracting IScript.dll
  extracting iKernel.rgs

All done, no errors.

adb not finding my device / phone (MacOS X)

Also make sure you check the vendors website for their "USB" drivers. I had this problem with my AT&T Galaxy Note (Running Android 2.3.6) and it wasn't being recognized by the adb without a driver install that I got from the samsung website.

jQuery - Uncaught RangeError: Maximum call stack size exceeded

Your calls are made recursively which pushes functions on to the stack infinitely that causes max call stack exceeded error due to recursive behavior. Instead try using setTimeout which is a callback.

Also based on your markup your selector is wrong. it should be #advisersDiv

Demo

function fadeIn() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).addClass("pulse");
    setTimeout(fadeOut,1); //<-- Provide any delay here
};

function fadeOut() {
    $('#pulseDiv').find('div#advisersDiv').delay(400).removeClass("pulse");
    setTimeout(fadeIn,1);//<-- Provide any delay here
};
fadeIn();

Counting the number of elements with the values of x in a vector

Using table but without comparing with names:

numbers <- c(4,23,4,23,5,43,54,56,657,67,67,435)
x <- 67
numbertable <- table(numbers)
numbertable[as.character(x)]
#67 
# 2 

table is useful when you are using the counts of different elements several times. If you need only one count, use sum(numbers == x)

ASP.NET MVC 404 Error Handling

What I can recomend is to look on FilterAttribute. For example MVC already has HandleErrorAttribute. You can customize it to handle only 404. Reply if you are interesed I will look example.

BTW

Solution(with last route) that you have accepted in previous question does not work in much of the situations. Second solution with HandleUnknownAction will work but require to make this change in each controller or to have single base controller.

My choice is a solution with HandleUnknownAction.

How do I pass a URL with multiple parameters into a URL?

You have to escape the & character. Turn your

&

into

&amp;

and you should be good.

Correct path for img on React.js

Place the logo in your public folder under e.g. public/img/logo.png and then refer to the public folder as %PUBLIC_URL%:

<img src="%PUBLIC_URL%/img/logo.png"/>

The use of %PUBLIC_URL% in the above will be replaced with the URL of the public folder during the build. Only files inside the public folder can be referenced from the HTML.

Unlike "/img/logo.png" or "logo.png", "%PUBLIC_URL%/img/logo.png" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running npm run build.

How do I jump out of a foreach loop in C#?

var ind=0;
foreach(string s in sList){
    if(s.equals("ok")){
        return true;
    }
    ind++;
}
if (ind==sList.length){
    return false;
}

Clearing an HTML file upload field via JavaScript

Simple solution:

document.getElementById("upload-files").value = "";

How to call another controller Action From a controller in Mvc

Let the resolver automatically do that.

Inside A controller:

public class AController : ApiController
{
    private readonly BController _bController;

    public AController(
    BController bController)
    {
        _bController = bController;
    }

    public httpMethod{
    var result =  _bController.OtherMethodBController(parameters);
    ....
    }

}

How do I initialise all entries of a matrix with a specific value?

As mentioned in other answers you can use:

>> tic; x=5*ones(10,1); toc
Elapsed time is 0.000415 seconds.

An even faster method is:

>> tic;  x=5; x=x(ones(10,1)); toc
Elapsed time is 0.000257 seconds.

Concatenating null strings in Java

This is behavior specified in the Java API's String.valueOf(Object) method. When you do concatenation, valueOf is used to get the String representation. There is a special case if the Object is null, in which case the string "null" is used.

public static String valueOf(Object obj)

Returns the string representation of the Object argument.

Parameters: obj - an Object.

Returns:

if the argument is null, then a string equal to "null"; otherwise, the value of obj.toString() is returned.

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

I had a similar problem running SciPy on my computer. There are two ways to fix this problem: 1. Yes you do need to cd into your python directory. 2. Sometimes you have to tell the computer explicitly what path to go through, you have to find the program you're using, open up the properties, and reroute the path it takes to run. 3. consult the manual: http://matplotlib.org/users/installing.html or http://www.scipy.org/install.html

the Scipy package is very finicky, and needs things spelled out in obnoxious detail.

How do I declare a namespace in JavaScript?

In JavaScript there are no predefined methods to use namespaces. In JavaScript we have to create our own methods to define NameSpaces. Here is a procedure we follow in Oodles technologies.

Register a NameSpace Following is the function to register a name space

//Register NameSpaces Function
function registerNS(args){
 var nameSpaceParts = args.split(".");
 var root = window;

 for(var i=0; i < nameSpaceParts.length; i++)
 {
  if(typeof root[nameSpaceParts[i]] == "undefined")
   root[nameSpaceParts[i]] = new Object();

  root = root[nameSpaceParts[i]];
 }
}

To register a Namespace just call the above function with the argument as name space separated by '.' (dot). For Example Let your application name is oodles. You can make a namespace by following method

registerNS("oodles.HomeUtilities");
registerNS("oodles.GlobalUtilities");
var $OHU = oodles.HomeUtilities;
var $OGU = oodles.GlobalUtilities;

Basically it will create your NameSpaces structure like below in backend:

var oodles = {
    "HomeUtilities": {},
    "GlobalUtilities": {}
};

In the above function you have register a namespace called "oodles.HomeUtilities" and "oodles.GlobalUtilities". To call these namespaces we make an variable i.e. var $OHU and var $OGU.

These variables are nothing but an alias to Intializing the namespace. Now, Whenever you declare a function that belong to HomeUtilities you will declare it like following:

$OHU.initialization = function(){
    //Your Code Here
};

Above is the function name initialization and it is put into an namespace $OHU. and to call this function anywhere in the script files. Just use following code.

$OHU.initialization();

Similarly, with the another NameSpaces.

Hope it helps.

Can I create view with parameter in MySQL?

I previously came up with a different workaround that doesn't use stored procedures, but instead uses a parameter table and some connection_id() magic.

EDIT (Copied up from comments)

create a table that contains a column called connection_id (make it a bigint). Place columns in that table for parameters for the view. Put a primary key on the connection_id. replace into the parameter table and use CONNECTION_ID() to populate the connection_id value. In the view use a cross join to the parameter table and put WHERE param_table.connection_id = CONNECTION_ID(). This will cross join with only one row from the parameter table which is what you want. You can then use the other columns in the where clause for example where orders.order_id = param_table.order_id.

how to auto select an input field and the text in it on page load

I found a very simple method that works well:

<input type="text" onclick="this.focus();this.select()">

Rails 4 LIKE query - ActiveRecord adds quotes

.find(:all, where: "value LIKE product_%", params: { limit: 20, page: 1 })

UIButton action in table view cell

in Swift 4

in cellForRowAt indexPath:

 cell.prescriptionButton.addTarget(self, action: Selector("onClicked:"), for: .touchUpInside)

function that run after user pressed button:

@objc func onClicked(sender: UIButton){
        let tag = sender.tag


    }

Convert InputStream to byte array in Java

See the InputStream.available() documentation:

It is particularly important to realize that you must not use this method to size a container and assume that you can read the entirety of the stream without needing to resize the container. Such callers should probably write everything they read to a ByteArrayOutputStream and convert that to a byte array. Alternatively, if you're reading from a file, File.length returns the current length of the file (though assuming the file's length can't change may be incorrect, reading a file is inherently racy).

C++ error : terminate called after throwing an instance of 'std::bad_alloc'

Something throws an exception of type std::bad_alloc, indicating that you ran out of memory. This exception is propagated through until main, where it "falls off" your program and causes the error message you see.

Since nobody here knows what "RectInvoice", "rectInvoiceVector", "vect", "im" and so on are, we cannot tell you what exactly causes the out-of-memory condition. You didn't even post your real code, because w h looks like a syntax error.

How to enable file sharing for my app?

Maybe it's obvious for you guys but I scratched my head for a while because the folder didn't show up in the files app. I actually needed to store something in the folder. you could achieve this by

  • saving some files into your document directory of the app
  • move something from iCloud Drive to your app (in the move dialog the folder will show up). As soon as there are no files in your folder anymore, it's gonna disappear from the "on my iPad tab".

How to set the opacity/alpha of a UIImage?

Swift 5:

extension UIImage {
  func withAlphaComponent(_ alpha: CGFloat) -> UIImage? {
    UIGraphicsBeginImageContextWithOptions(size, false, scale)
    defer { UIGraphicsEndImageContext() }

    draw(at: .zero, blendMode: .normal, alpha: alpha)
    return UIGraphicsGetImageFromCurrentImageContext()
  }
}

How do I hide anchor text without hiding the anchor?

Try

 a{
    line-height: 0; 
    font-size: 0;
    color: transparent; 
 }


The color: transparent; covers an issue with Webkit browsers still displaying 1px of the text.

How can I find out which server hosts LDAP on my windows domain?

If you're using AD you can use serverless binding to locate a domain controller for the default domain, then use LDAP://rootDSE to get information about the directory server, as described in the linked article.

How do I make XAML DataGridColumns fill the entire DataGrid?

As noted, the ColumnWidth="*" worked perfectly well for a DataGrid in XAML.

I used it in this context:

<DataGrid ColumnWidth="*" ItemsSource="{Binding AllFolders, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />

How do I replace multiple spaces with a single space in C#?

Many answers are providing the right output but for those looking for the best performances, I did improve Nolanar's answer (which was the best answer for performance) by about 10%.

public static string MergeSpaces(this string str)
{

    if (str == null)
    {
        return null;
    }
    else
    {
        StringBuilder stringBuilder = new StringBuilder(str.Length);

        int i = 0;
        foreach (char c in str)
        {
            if (c != ' ' || i == 0 || str[i - 1] != ' ')
                stringBuilder.Append(c);
            i++;
        }
        return stringBuilder.ToString();
    }

}

Anaconda-Navigator - Ubuntu16.04

I am running Anaconda Navigator on Kubuntu 17.04 & getting a successful launch of the navigator window. Not knowing any of your error messages or statement; you could try reinstalling with command: conda install -c anaconda anaconda-navigator

How do you test that a Python function throws an exception?

Since Python 2.7 you can use context manager to get ahold of the actual Exception object thrown:

import unittest

def broken_function():
    raise Exception('This is broken')

class MyTestCase(unittest.TestCase):
    def test(self):
        with self.assertRaises(Exception) as context:
            broken_function()

        self.assertTrue('This is broken' in context.exception)

if __name__ == '__main__':
    unittest.main()

http://docs.python.org/dev/library/unittest.html#unittest.TestCase.assertRaises


In Python 3.5, you have to wrap context.exception in str, otherwise you'll get a TypeError

self.assertTrue('This is broken' in str(context.exception))

How do I store and retrieve a blob from sqlite?

I ended up with this method for inserting a blob:

   protected Boolean updateByteArrayInTable(String table, String value, byte[] byteArray, String expr)
   {
      try
      {
         SQLiteCommand mycommand = new SQLiteCommand(connection);
         mycommand.CommandText = "update " + table + " set " + value + "=@image" + " where " + expr;
         SQLiteParameter parameter = new SQLiteParameter("@image", System.Data.DbType.Binary);
         parameter.Value = byteArray;
         mycommand.Parameters.Add(parameter);

         int rowsUpdated = mycommand.ExecuteNonQuery();
         return (rowsUpdated>0);
      }
      catch (Exception)
      {
         return false;
      }
   }

For reading it back the code is:

   protected DataTable executeQuery(String command)
   {
      DataTable dt = new DataTable();
      try
      {
         SQLiteCommand mycommand = new SQLiteCommand(connection);
         mycommand.CommandText = command;
         SQLiteDataReader reader = mycommand.ExecuteReader();
         dt.Load(reader);
         reader.Close();
         return dt;
      }
      catch (Exception)
      {
         return null;
      }
   }

   protected DataTable getAllWhere(String table, String sort, String expr)
   {
      String cmd = "select * from " + table;
      if (sort != null)
         cmd += " order by " + sort;
      if (expr != null)
         cmd += " where " + expr;
      DataTable dt = executeQuery(cmd);
      return dt;
   }

   public DataRow getImage(long rowId) {
      String where = KEY_ROWID_IMAGE + " = " + Convert.ToString(rowId);
      DataTable dt = getAllWhere(DATABASE_TABLE_IMAGES, null, where);
      DataRow dr = null;
      if (dt.Rows.Count > 0) // should be just 1 row
         dr = dt.Rows[0];
      return dr;
   }

   public byte[] getImage(DataRow dr) {
      try
      {
         object image = dr[KEY_IMAGE];
         if (!Convert.IsDBNull(image))
            return (byte[])image;
         else
            return null;
      } catch(Exception) {
         return null;
      }
   }

   DataRow dri = getImage(rowId);
   byte[] image = getImage(dri);

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

It is very likely that the pickled file is empty.

It is surprisingly easy to overwrite a pickle file if you're copying and pasting code.

For example the following writes a pickle file:

pickle.dump(df,open('df.p','wb'))

And if you copied this code to reopen it, but forgot to change 'wb' to 'rb' then you would overwrite the file:

df=pickle.load(open('df.p','wb'))

The correct syntax is

df=pickle.load(open('df.p','rb'))

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

JavaScript - Get Browser Height

You'll want something like this, taken from http://www.howtocreate.co.uk/tutorials/javascript/browserwindow

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  window.alert( 'Width = ' + myWidth );
  window.alert( 'Height = ' + myHeight );
}

So that's innerHeight for modern browsers, documentElement.clientHeight for IE, body.clientHeight for deprecated/quirks.

Flash CS4 refuses to let go

I have found one related behaviour that may help (sounds like your specific problem runs deeper though):

Flash checks whether a source file needs recompiling by looking at timestamps. If its compiled version is older than the source file, it will recompile. But it doesn't check whether the compiled version was generated from the same source file or not.

Specifically, if you have your actionscript files under version control, and you Revert a change, the reverted file will usually have an older timestamp, and Flash will ignore it.

How to find out the server IP address (using JavaScript) that the browser is connected to?

Fairly certain this cannot be done. However you could use your preferred server-side language to print the server's IP to the client, and then use it however you like. For example, in PHP:

<script type="text/javascript">
    var ip = "<?php echo $_SERVER['SERVER_ADDR']; ?>";
    alert(ip);
</script>

This depends on your server's security setup though - some may block this.

VBA: How to display an error message just like the standard error message which has a "Debug" button?

For Me I just wanted to see the error in my VBA application so in the function I created the below code..

Function Database_FileRpt
'-------------------------
On Error GoTo CleanFail
'-------------------------
'
' Create_DailyReport_Action and code


CleanFail:

'*************************************

MsgBox "********************" _

& vbCrLf & "Err.Number: " & Err.Number _

& vbCrLf & "Err.Description: " & Err.Description _

& vbCrLf & "Err.Source: " & Err.Source _

& vbCrLf & "********************" _

& vbCrLf & "...Exiting VBA Function: Database_FileRpt" _

& vbCrLf & "...Excel VBA Program Reset." _

, , "VBA Error Exception Raised!"

*************************************

 ' Note that the next line will reset the error object to 0, the variables 
above are used to remember the values
' so that the same error can be re-raised

Err.Clear

' *************************************

Resume CleanExit

CleanExit:

'cleanup code , if any, goes here. runs regardless of error state.

Exit Function  ' SUB  or Function    

End Function  ' end of Database_FileRpt

' ------------------

Defining constant string in Java?

Or another typical standard in the industry is to have a Constants.java named class file containing all the constants to be used all over the project.

How to force a list to be vertical using html css

I would add this to the LI's CSS

.list-item
{
    float: left;
    clear: left;
}

Uninstall Node.JS using Linux command line?

The answer of George Bailey works fine. I would just add the following flags and use sudo if needed:

 sudo rm -rf bin/node bin/node-waf include/node lib/node lib/pkgconfig/nodejs.pc share/man/man1/node

Saving changes after table edit in SQL Server Management Studio

Rather than unchecking the box (a poor solution), you should STOP editing data that way. If data must be changed, then do it with a script, so that you can easily port it to production and so that it is under source control. This also makes it easier to refresh testing changes after production has been pushed down to dev to enable developers to be working against fresher data.

How to download a file from my server using SSH (using PuTTY on Windows)

If your server have a http service you can compress your directory and download the compressed file.

Compress:

tar -zcvf archive-name.tar.gz -C directory-name .

Download throught your browser:

http://the-server-ip/archive-name.tar.gz

If you don't have direct access to the server ip, do a ssh tunnel throught putty, and forward the 80 port in some local port, and you can download the file.

What is Mocking?

There are plenty of answers on SO and good posts on the web about mocking. One place that you might want to start looking is the post by Martin Fowler Mocks Aren't Stubs where he discusses a lot of the ideas of mocking.

In one paragraph - Mocking is one particlar technique to allow testing of a unit of code with out being reliant upon dependencies. In general, what differentiates mocking from other methods is that mock objects used to replace code dependencies will allow expectations to be set - a mock object will know how it is meant to be called by your code and how to respond.


Your original question mentioned TypeMock, so I've left my answer to that below:

TypeMock is the name of a commercial mocking framework.

It offers all the features of the free mocking frameworks like RhinoMocks and Moq, plus some more powerful options.

Whether or not you need TypeMock is highly debatable - you can do most mocking you would ever want with free mocking libraries, and many argue that the abilities offered by TypeMock will often lead you away from well encapsulated design.

As another answer stated 'TypeMocking' is not actually a defined concept, but could be taken to mean the type of mocking that TypeMock offers, using the CLR profiler to intercept .Net calls at runtime, giving much greater ability to fake objects (not requirements such as needing interfaces or virtual methods).

How to remove the left part of a string?

If the string is fixed you can simply use:

if line.startswith("Path="):
    return line[5:]

which gives you everything from position 5 on in the string (a string is also a sequence so these sequence operators work here, too).

Or you can split the line at the first =:

if "=" in line:
    param, value = line.split("=",1)

Then param is "Path" and value is the rest after the first =.

"Post Image data using POSTMAN"

Now you can hover the key input and select "file", which will give you a file selector in the value column:

enter image description here

How to capitalize first letter of each word, like a 2-word city?

There's a good answer here:

function toTitleCase(str) {
    return str.replace(/\w\S*/g, function(txt){
        return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();
    });
}

or in ES6:

var text = "foo bar loo zoo moo";
text = text.toLowerCase()
    .split(' ')
    .map((s) => s.charAt(0).toUpperCase() + s.substring(1))
    .join(' ');

How to get the type of a variable in MATLAB?

class() function is the equivalent of typeof()

You can also use isa() to check if a variable is of a particular type. If you want to be even more specific, you can use ischar(), isfloat(), iscell(), etc.

How to repair COMException error 80040154?

Move excel variables which are global declare in your form to local like in my form I have:

Dim xls As New MyExcel.Interop.Application  
Dim xlb As MyExcel.Interop.Workbook

above two lines were declare global in my form so i moved these two lines to local function and now tool is working fine.

WPF - add static items to a combo box

<ComboBox Text="Something">
            <ComboBoxItem Content="Item1"></ComboBoxItem >
            <ComboBoxItem Content="Item2"></ComboBoxItem >
            <ComboBoxItem Content="Item3"></ComboBoxItem >
</ComboBox>

Last Run Date on a Stored Procedure in SQL Server

I use this:

use YourDB;

SELECT 
    object_name(object_id), 
    last_execution_time, 
    last_elapsed_time, 
    execution_count
FROM   
     sys.dm_exec_procedure_stats ps 
where 
      lower(object_name(object_id)) like 'Appl-Name%'
order by 1

MySQL Update Column +1?

How about:

update table
set columnname = columnname + 1
where id = <some id>

How do I get the n-th level parent of an element in jQuery?

Since parents() returns the ancestor elements ordered from the closest to the outer ones, you can chain it into eq():

$('#element').parents().eq(0);  // "Father".
$('#element').parents().eq(2);  // "Great-grandfather".

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

Is "else if" faster than "switch() case"?

Technically, they produce the exact same result so they should be optimizable in pretty much the same way. However, there are more chances that the compiler will optimize the switch case with a jump table than the ifs.

I'm talking about the general case here. For 5 entries, the average number of tests performed for the ifs should be less than 2.5, assuming you order the conditions by frequency. Hardly a bottleneck to write home about unless in a very tight loop.

How to press back button in android programmatically?

Sometimes is useful to override method onBackPressed() because in case you work with fragments and you're changing between them if you push backbutton they return to the previous fragment.

When should I really use noexcept?

  1. There are many examples of functions that I know will never throw, but for which the compiler cannot determine so on its own. Should I append noexcept to the function declaration in all such cases?

noexcept is tricky, as it is part of the functions interface. Especially, if you are writing a library, your client code can depend on the noexcept property. It can be difficult to change it later, as you might break existing code. That might be less of a concern when you are implementing code that is only used by your application.

If you have a function that cannot throw, ask yourself whether it will like stay noexcept or would that restrict future implementations? For example, you might want to introduce error checking of illegal arguments by throwing exceptions (e.g., for unit tests), or you might depend on other library code that could change its exception specification. In that case, it is safer to be conservative and omit noexcept.

On the other hand, if you are confident that the function should never throw and it is correct that it is part of the specification, you should declare it noexcept. However, keep in mind that the compiler will not be able to detect violations of noexcept if your implementation changes.

  1. For which situations should I be more careful about the use of noexcept, and for which situations can I get away with the implied noexcept(false)?

There are four classes of functions that should you should concentrate on because they will likely have the biggest impact:

  1. move operations (move assignment operator and move constructors)
  2. swap operations
  3. memory deallocators (operator delete, operator delete[])
  4. destructors (though these are implicitly noexcept(true) unless you make them noexcept(false))

These functions should generally be noexcept, and it is most likely that library implementations can make use of the noexcept property. For example, std::vector can use non-throwing move operations without sacrificing strong exception guarantees. Otherwise, it will have to fall back to copying elements (as it did in C++98).

This kind of optimization is on the algorithmic level and does not rely on compiler optimizations. It can have a significant impact, especially if the elements are expensive to copy.

  1. When can I realistically expect to observe a performance improvement after using noexcept? In particular, give an example of code for which a C++ compiler is able to generate better machine code after the addition of noexcept.

The advantage of noexcept against no exception specification or throw() is that the standard allows the compilers more freedom when it comes to stack unwinding. Even in the throw() case, the compiler has to completely unwind the stack (and it has to do it in the exact reverse order of the object constructions).

In the noexcept case, on the other hand, it is not required to do that. There is no requirement that the stack has to be unwound (but the compiler is still allowed to do it). That freedom allows further code optimization as it lowers the overhead of always being able to unwind the stack.

The related question about noexcept, stack unwinding and performance goes into more details about the overhead when stack unwinding is required.

I also recommend Scott Meyers book "Effective Modern C++", "Item 14: Declare functions noexcept if they won't emit exceptions" for further reading.

Simple example of threading in C++

Create a function that you want the thread to execute, eg:

void task1(std::string msg)
{
    std::cout << "task1 says: " << msg;
}

Now create the thread object that will ultimately invoke the function above like so:

std::thread t1(task1, "Hello");

(You need to #include <thread> to access the std::thread class)

The constructor's arguments are the function the thread will execute, followed by the function's parameters. The thread is automatically started upon construction.

If later on you want to wait for the thread to be done executing the function, call:

t1.join(); 

(Joining means that the thread who invoked the new thread will wait for the new thread to finish execution, before it will continue its own execution).


The Code

#include <string>
#include <iostream>
#include <thread>

using namespace std;

// The function we want to execute on the new thread.
void task1(string msg)
{
    cout << "task1 says: " << msg;
}

int main()
{
    // Constructs the new thread and runs it. Does not block execution.
    thread t1(task1, "Hello");

    // Do other things...

    // Makes the main thread wait for the new thread to finish execution, therefore blocks its own execution.
    t1.join();
}

More information about std::thread here

  • On GCC, compile with -std=c++0x -pthread.
  • This should work for any operating-system, granted your compiler supports this (C++11) feature.

UIButton: how to center an image and a text using imageEdgeInsets and titleEdgeInsets?

Or you can just use this category:

@interface UIButton (VerticalLayout)  

- (void)centerVerticallyWithPadding:(float)padding;  
- (void)centerVertically;  

@end  


@implementation UIButton (VerticalLayout)  

- (void)centerVerticallyWithPadding:(float)padding 
{      
    CGSize imageSize = self.imageView.frame.size;  
    CGSize titleSize = self.titleLabel.frame.size;  

    CGFloat totalHeight = (imageSize.height + titleSize.height + padding);  

    self.imageEdgeInsets = UIEdgeInsetsMake(- (totalHeight - imageSize.height),
                                            0.0f,
                                            0.0f,
                                            - titleSize.width);

    self.titleEdgeInsets = UIEdgeInsetsMake(0.0f,
                                            - imageSize.width,
                                            - (totalHeight - titleSize.height),
                                            0.0f);

}


- (void)centerVertically
{  
    const CGFloat kDefaultPadding = 6.0f;

    [self centerVerticallyWithPadding:kDefaultPadding];  
}  


@end

How to parse a text file with C#

One way that I've found really useful in situations like this is to go old-school and use the Jet OLEDB provider, together with a schema.ini file to read large tab-delimited files in using ADO.Net. Obviously, this method is really only useful if you know the format of the file to be imported.

public void ImportCsvFile(string filename)
{
    FileInfo file = new FileInfo(filename);

    using (OleDbConnection con = 
            new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\"" +
            file.DirectoryName + "\";
            Extended Properties='text;HDR=Yes;FMT=TabDelimited';"))
    {
        using (OleDbCommand cmd = new OleDbCommand(string.Format
                                  ("SELECT * FROM [{0}]", file.Name), con))
        {
            con.Open();

            // Using a DataReader to process the data
            using (OleDbDataReader reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // Process the current reader entry...
                }
            }

            // Using a DataTable to process the data
            using (OleDbDataAdapter adp = new OleDbDataAdapter(cmd))
            {
                DataTable tbl = new DataTable("MyTable");
                adp.Fill(tbl);

                foreach (DataRow row in tbl.Rows)
                {
                    // Process the current row...
                }
            }
        }
    }
} 

Once you have the data in a nice format like a datatable, filtering out the data you need becomes pretty trivial.

don't fail jenkins build if execute shell fails

To stop further execution when command fails:

command || exit 0

To continue execution when command fails:

command || true

curl posting with header application/x-www-form-urlencoded

 $curl = curl_init();
 curl_setopt_array($curl, array(
            CURLOPT_URL => "http://example.com",
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => "value1=111&value2=222",
            CURLOPT_HTTPHEADER => array(
                "cache-control: no-cache",
                "content-type: application/x-www-form-urlencoded"
            ),
        ));
 $response = curl_exec($curl);
 $err = curl_error($curl);

 curl_close($curl);

 if (!$err)
 {
      var_dump($response);
 }

Reading a text file with SQL Server

if you want to read the file into a table at one time you should use BULK INSERT. ON the other hand if you preffer to parse the file line by line to make your own checks, you should take a look at this web: https://www.simple-talk.com/sql/t-sql-programming/reading-and-writing-files-in-sql-server-using-t-sql/ It is possible that you need to activate your xp_cmdshell or other OLE Automation features. Simple Google it and the script will appear. Hope to be useful.

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

You've encountered a local time discontinuity:

When local standard time was about to reach Sunday, 1. January 1928, 00:00:00 clocks were turned backward 0:05:52 hours to Saturday, 31. December 1927, 23:54:08 local standard time instead

This is not particularly strange and has happened pretty much everywhere at one time or another as timezones were switched or changed due to political or administrative actions.

Angular 2 Sibling Component Communication

Updated to rc.4: When trying to get data passed between sibling components in angular 2, The simplest way right now (angular.rc.4) is to take advantage of angular2's hierarchal dependency injection and create a shared service.

Here would be the service:

import {Injectable} from '@angular/core';

@Injectable()
export class SharedService {
    dataArray: string[] = [];

    insertData(data: string){
        this.dataArray.unshift(data);
    }
}

Now, here would be the PARENT component

import {Component} from '@angular/core';
import {SharedService} from './shared.service';
import {ChildComponent} from './child.component';
import {ChildSiblingComponent} from './child-sibling.component';
@Component({
    selector: 'parent-component',
    template: `
        <h1>Parent</h1>
        <div>
            <child-component></child-component>
            <child-sibling-component></child-sibling-component>
        </div>
    `,
    providers: [SharedService],
    directives: [ChildComponent, ChildSiblingComponent]
})
export class parentComponent{

} 

and its two children

child 1

import {Component, OnInit} from '@angular/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-component',
    template: `
        <h1>I am a child</h1>
        <div>
            <ul *ngFor="#data in data">
                <li>{{data}}</li>
            </ul>
        </div>
    `
})
export class ChildComponent implements OnInit{
    data: string[] = [];
    constructor(
        private _sharedService: SharedService) { }
    ngOnInit():any {
        this.data = this._sharedService.dataArray;
    }
}

child 2 (It's sibling)

import {Component} from 'angular2/core';
import {SharedService} from './shared.service'

@Component({
    selector: 'child-sibling-component',
    template: `
        <h1>I am a child</h1>
        <input type="text" [(ngModel)]="data"/>
        <button (click)="addData()"></button>
    `
})
export class ChildSiblingComponent{
    data: string = 'Testing data';
    constructor(
        private _sharedService: SharedService){}
    addData(){
        this._sharedService.insertData(this.data);
        this.data = '';
    }
}

NOW: Things to take note of when using this method.

  1. Only include the service provider for the shared service in the PARENT component and NOT the children.
  2. You still have to include constructors and import the service in the children
  3. This answer was originally answered for an early angular 2 beta version. All that has changed though are the import statements, so that is all you need to update if you used the original version by chance.

Filter df when values matches part of a string in pyspark

pyspark.sql.Column.contains() is only available in pyspark version 2.2 and above.

df.where(df.location.contains('google.com'))

What is the difference between Tomcat, JBoss and Glassfish?

Apache tomcat is just an only serverlet container it does not support for Enterprise Java application(JEE). JBoss and Glassfish are supporting for JEE application but Glassfish much heavy than JBOSS server : Reference Slide

Converting string to byte array in C#

This question has been answered sufficiently many times, but with C# 7.2 and the introduction of the Span type, there is a faster way to do this in unsafe code:

public static class StringSupport
{
    private static readonly int _charSize = sizeof(char);

    public static unsafe byte[] GetBytes(string str)
    {
        if (str == null) throw new ArgumentNullException(nameof(str));
        if (str.Length == 0) return new byte[0];

        fixed (char* p = str)
        {
            return new Span<byte>(p, str.Length * _charSize).ToArray();
        }
    }

    public static unsafe string GetString(byte[] bytes)
    {
        if (bytes == null) throw new ArgumentNullException(nameof(bytes));
        if (bytes.Length % _charSize != 0) throw new ArgumentException($"Invalid {nameof(bytes)} length");
        if (bytes.Length == 0) return string.Empty;

        fixed (byte* p = bytes)
        {
            return new string(new Span<char>(p, bytes.Length / _charSize));
        }
    }
}

Keep in mind that the bytes represent a UTF-16 encoded string (called "Unicode" in C# land).

Some quick benchmarking shows that the above methods are roughly 5x faster than their Encoding.Unicode.GetBytes(...)/GetString(...) implementations for medium sized strings (30-50 chars), and even faster for larger strings. These methods also seem to be faster than using pointers with Marshal.Copy(..) or Buffer.MemoryCopy(...).

Executing periodic actions in Python

At the end of foo(), create a Timer which calls foo() itself after 10 seconds.
Because, Timer create a new thread to call foo().
You can do other stuff without being blocked.

import time, threading
def foo():
    print(time.ctime())
    threading.Timer(10, foo).start()

foo()

#output:
#Thu Dec 22 14:46:08 2011
#Thu Dec 22 14:46:18 2011
#Thu Dec 22 14:46:28 2011
#Thu Dec 22 14:46:38 2011

How to make matrices in Python?

If you don't want to use numpy, you could use the list of lists concept. To create any 2D array, just use the following syntax:

  mat = [[input() for i in range (col)] for j in range (row)]

and then enter the values you want.

SQL WHERE ID IN (id1, id2, ..., idn)

An alternative approach might be to use another table to contain id values. This other table can then be inner joined on your TABLE to constrain returned rows. This will have the major advantage that you won't need dynamic SQL (problematic at the best of times), and you won't have an infinitely long IN clause.

You would truncate this other table, insert your large number of rows, then perhaps create an index to aid the join performance. It would also let you detach the accumulation of these rows from the retrieval of data, perhaps giving you more options to tune performance.

Update: Although you could use a temporary table, I did not mean to imply that you must or even should. A permanent table used for temporary data is a common solution with merits beyond that described here.

How to determine previous page URL in Angular?

I had some struggle to access the previous url inside a guard.
Without implementing a custom solution, this one is working for me.

public constructor(private readonly router: Router) {
};

public ngOnInit() {
   this.router.getCurrentNavigation().previousNavigation.initialUrl.toString();
}

The initial url will be the previous url page.

How can I get the source directory of a Bash script from within the script itself?

This one-liner works on Cygwin even if the script has been called from Windows with bash -c <script>:

set mydir="$(cygpath "$(dirname "$0")")"

Wavy shape with css

I think this is the right way to make a shape like you want. By using the SVG possibilities, and an container to keep the shape responsive.

_x000D_
_x000D_
svg {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
}_x000D_
.container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%;_x000D_
  vertical-align: middle;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <svg viewBox="0 0 500 500" preserveAspectRatio="xMinYMin meet">_x000D_
    <path d="M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z" style="stroke: none; fill:red;"></path>_x000D_
  </svg>_x000D_
</div>
_x000D_
_x000D_
_x000D_

get current date with 'yyyy-MM-dd' format in Angular 4

app.component.html

<div>
     <h5 style="color:#ffffff;">{{myDate | date:'fullDate'}}</h5>
</div>

app.component.ts

export class AppComponent implements OnInit {
myDate = Date.now();    //date 

Contain form within a bootstrap popover?

Either replace double quotes around type="text" with single quotes, Like

"<form><input type='text'/></form>"

OR

replace double quotes wrapping data-content with singe quotes, Like

data-content='<form><input type="text"/></form>'

Identifying country by IP address

I know that it is a very old post but for the sake of the users who are landed here and looking for a solution, if you are using Cloudflare as your DNS then you can activate IP geolocation and get the value from the request header,

here is the code snippet in C# after you enable IP geolocation in Cloudflare through the network tab

 var countryCode = HttpContext.Request.Headers.Get("cf-ipcountry"); // in older asp.net versions like webform use HttpContext.Current.Request. ...
 var countryName = new RegionInfo(CountryCode)?.EnglishName;

you can simply map it to other programming languages, please take a look at the Cloudflare's documentation here


but if you are really insisting on using a 3rd party solution to have more precise information about the visitors using their IP here is a complete, ready to use implementation using C#:

the 3rd party I have used is https://ipstack.com, you can simply register for a free plan and get an access token to use for 10K API requests each month, I am using the JSON model to retrieve and like to convert all the info the API gives me, here we go:

The DTO:

    using System;
    using Newtonsoft.Json;

     public partial class GeoLocationModel
     {
        [JsonProperty("ip")]
        public string Ip { get; set; }

        [JsonProperty("hostname")]
        public string Hostname { get; set; }

        [JsonProperty("type")]
        public string Type { get; set; }

        [JsonProperty("continent_code")]
        public string ContinentCode { get; set; }

        [JsonProperty("continent_name")]
        public string ContinentName { get; set; }

        [JsonProperty("country_code")]
        public string CountryCode { get; set; }

        [JsonProperty("country_name")]
        public string CountryName { get; set; }

        [JsonProperty("region_code")]
        public string RegionCode { get; set; }

        [JsonProperty("region_name")]
        public string RegionName { get; set; }

        [JsonProperty("city")]
        public string City { get; set; }

        [JsonProperty("zip")]
        public long Zip { get; set; }

        [JsonProperty("latitude")]
        public double Latitude { get; set; }

        [JsonProperty("longitude")]
        public double Longitude { get; set; }

        [JsonProperty("location")]
        public Location Location { get; set; }

        [JsonProperty("time_zone")]
        public TimeZone TimeZone { get; set; }

        [JsonProperty("currency")]
        public Currency Currency { get; set; }

        [JsonProperty("connection")]
        public Connection Connection { get; set; }

        [JsonProperty("security")]
        public Security Security { get; set; }
     }

    public partial class Connection
    {
        [JsonProperty("asn")]
        public long Asn { get; set; }

        [JsonProperty("isp")]
        public string Isp { get; set; }
    }

    public partial class Currency
    {
        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("plural")]
        public string Plural { get; set; }

        [JsonProperty("symbol")]
        public string Symbol { get; set; }

        [JsonProperty("symbol_native")]
        public string SymbolNative { get; set; }
    }

    public partial class Location
    {
        [JsonProperty("geoname_id")]
        public long GeonameId { get; set; }

        [JsonProperty("capital")]
        public string Capital { get; set; }

        [JsonProperty("languages")]
        public Language[] Languages { get; set; }

        [JsonProperty("country_flag")]
        public Uri CountryFlag { get; set; }

        [JsonProperty("country_flag_emoji")]
        public string CountryFlagEmoji { get; set; }

        [JsonProperty("country_flag_emoji_unicode")]
        public string CountryFlagEmojiUnicode { get; set; }

        [JsonProperty("calling_code")]
        public long CallingCode { get; set; }

        [JsonProperty("is_eu")]
        public bool IsEu { get; set; }
    }

    public partial class Language
    {
        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("native")]
        public string Native { get; set; }
    }

    public partial class Security
    {
        [JsonProperty("is_proxy")]
        public bool IsProxy { get; set; }

        [JsonProperty("proxy_type")]
        public object ProxyType { get; set; }

        [JsonProperty("is_crawler")]
        public bool IsCrawler { get; set; }

        [JsonProperty("crawler_name")]
        public object CrawlerName { get; set; }

        [JsonProperty("crawler_type")]
        public object CrawlerType { get; set; }

        [JsonProperty("is_tor")]
        public bool IsTor { get; set; }

        [JsonProperty("threat_level")]
        public string ThreatLevel { get; set; }

        [JsonProperty("threat_types")]
        public object ThreatTypes { get; set; }
    }

    public partial class TimeZone
    {
        [JsonProperty("id")]
        public string Id { get; set; }

        [JsonProperty("current_time")]
        public DateTimeOffset CurrentTime { get; set; }

        [JsonProperty("gmt_offset")]
        public long GmtOffset { get; set; }

        [JsonProperty("code")]
        public string Code { get; set; }

        [JsonProperty("is_daylight_saving")]
        public bool IsDaylightSaving { get; set; }
    }

The Helper:

    using System.Configuration;
    using System.IO;
    using System.Net;
    using System.Threading.Tasks;

    public class GeoLocationHelper
    {
        public static async Task<GeoLocationModel> GetGeoLocationByIp(string ipAddress)
        {
            var request = WebRequest.Create(string.Format("http://api.ipstack.com/{0}?access_key={1}", ipAddress, ConfigurationManager.AppSettings["ipStackAccessKey"]));
            var response = await request.GetResponseAsync();
            using (var stream = new StreamReader(response.GetResponseStream()))
            {
                var jsonGeoData = await stream.ReadToEndAsync();
                return Newtonsoft.Json.JsonConvert.DeserializeObject<GeoLocationModel>(jsonGeoData);
            }
        }
    }

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Also you can try to formulate your answer in the form of a SELECT CASE Statement. You can then later create simple if then's that use your results if needed as you have narrowed down the possibilities.

SELECT @Result =   
CASE @inputParam   
WHEN 1 THEN 1   
WHEN 2 THEN 2   
WHEN 3 THEN 1   
ELSE 4   
END  

IF @Result = 1   
BEGIN  
...  
END  

IF @Result = 2   
BEGIN   
....  
END  

IF @Result = 4   
BEGIN   
//Error handling code   
END   

HTML/CSS: Making two floating divs the same height

you can get this working with js:

<script>
    $(document).ready(function() {
        var height = Math.max($("#left").height(), $("#right").height());
        $("#left").height(height);
        $("#right").height(height);
    });
</script>

How to remove all CSS classes using jQuery/JavaScript?

Hang on, doesn't removeClass() default to removing all classes if nothing specific is specified? So

$("#item").removeClass();

will do it on its own...

How to list all `env` properties within jenkins pipeline job?

I use Blue Ocean plugin and did not like each environment entry getting its own block. I want one block with all the lines.

Prints poorly:

sh 'echo `env`'

Prints poorly:

sh 'env > env.txt'
for (String i : readFile('env.txt').split("\r?\n")) {
    println i
}

Prints well:

sh 'env > env.txt'
sh 'cat env.txt'

Prints well: (as mentioned by @mjfroehlich)

echo sh(script: 'env', returnStdout: true)

Search for executable files using find command

On GNU versions of find you can use -executable:

find . -type f -executable -print

For BSD versions of find, you can use -perm with + and an octal mask:

find . -type f -perm +111 -print

In this context "+" means "any of these bits are set" and 111 is the execute bits.

Note that this is not identical to the -executable predicate in GNU find. In particular, -executable tests that the file can be executed by the current user, while -perm +111 just tests if any execute permissions are set.

Older versions of GNU find also support the -perm +111 syntax, but as of 4.5.12 this syntax is no longer supported. Instead, you can use -perm /111 to get this behavior.

What does "exec sp_reset_connection" mean in Sql Server Profiler?

Like the other answers said, sp_reset_connection indicates that connection pool is being reused. Be aware of one particular consequence!

Jimmy Mays' MSDN Blog said:

sp_reset_connection does NOT reset the transaction isolation level to the server default from the previous connection's setting.

UPDATE: Starting with SQL 2014, for client drivers with TDS version 7.3 or higher, the transaction isolation levels will be reset back to the default.

ref: SQL Server: Isolation level leaks across pooled connections

Here is some additional information:

What does sp_reset_connection do?

Data access API's layers like ODBC, OLE-DB and System.Data.SqlClient all call the (internal) stored procedure sp_reset_connection when re-using a connection from a connection pool. It does this to reset the state of the connection before it gets re-used, however nowhere is documented what things get reset. This article tries to document the parts of the connection that get reset.

sp_reset_connection resets the following aspects of a connection:

  • All error states and numbers (like @@error)

  • Stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query

  • Waits for any outstanding I/O operations that is outstanding

  • Frees any held buffers on the server by the connection

  • Unlocks any buffer resources that are used by the connection

  • Releases all allocated memory owned by the connection

  • Clears any work or temporary tables that are created by the connection

  • Kills all global cursors owned by the connection

  • Closes any open SQL-XML handles that are open

  • Deletes any open SQL-XML related work tables

  • Closes all system tables

  • Closes all user tables

  • Drops all temporary objects

  • Aborts open transactions

  • Defects from a distributed transaction when enlisted

  • Decrements the reference count for users in current database which releases shared database locks

  • Frees acquired locks

  • Releases any acquired handles

  • Resets all SET options to the default values

  • Resets the @@rowcount value

  • Resets the @@identity value

  • Resets any session level trace options using dbcc traceon()

  • Resets CONTEXT_INFO to NULL in SQL Server 2005 and newer [ not part of the original article ]

sp_reset_connection will NOT reset:

  • Security context, which is why connection pooling matches connections based on the exact connection string

  • Application roles entered using sp_setapprole, since application roles could not be reverted at all prior to SQL Server 2005. Starting in SQL Server 2005, app roles can be reverted, but only with additional information that is not part of the session. Before closing the connection, application roles need to be manually reverted via sp_unsetapprole using a "cookie" value that is captured when sp_setapprole is executed.

Note: I am including the list here as I do not want it to be lost in the ever transient web.

Android REST client, Sample?

There is plenty of libraries out there and I'm using this one: https://github.com/nerde/rest-resource. This was created by me, and, as you can see in the documentation, it's way cleaner and simpler than the other ones. It's not focused on Android, but I'm using in it and it's working pretty well.

It supports HTTP Basic Auth. It does the dirty job of serializing and deserializing JSON objects. You will like it, specially if your API is Rails like.

Format number as percent in MS SQL Server

Using FORMAT function in new versions of SQL Server is much simpler and allows much more control:

FORMAT(yournumber, '#,##0.0%')

Benefit of this is you can control additional things like thousand separators and you don't get that space between the number and '%'.

Smooth GPS data

One method that uses less math/theory is to sample 2, 5, 7, or 10 data points at a time and determine those which are outliers. A less accurate measure of an outlier than a Kalman Filter is to to use the following algorithm to take all pair wise distances between points and throw out the one that is furthest from the the others. Typically those values are replaced with the value closest to the outlying value you are replacing

For example

Smoothing at five sample points A, B, C, D, E

ATOTAL = SUM of distances AB AC AD AE

BTOTAL = SUM of distances AB BC BD BE

CTOTAL = SUM of distances AC BC CD CE

DTOTAL = SUM of distances DA DB DC DE

ETOTAL = SUM of distances EA EB EC DE

If BTOTAL is largest you would replace point B with D if BD = min { AB, BC, BD, BE }

This smoothing determines outliers and can be augmented by using the midpoint of BD instead of point D to smooth the positional line. Your mileage may vary and more mathematically rigorous solutions exist.

What is a daemon thread in Java?

Definition of Daemon (Computing):

A background process that handles requests for services such as print spooling and file transfers, and is dormant when not required.

—— Source: English by Oxford Dictionaries

What is Daemon thread in Java?

  • Daemon threads can shut down any time in between their flow, Non-Daemon i.e. user thread executes completely.
  • Daemon threads are threads that run intermittently in the background as long as other non-daemon threads are running.
  • When all of the non-daemon threads complete, daemon threads terminates automatically.
  • Daemon threads are service providers for user threads running in the same process.
  • The JVM does not care about daemon threads to complete when in Running state, not even finally block also let execute. JVM do give preference to non-daemon threads that is created by us.
  • Daemon threads acts as services in Windows.
  • The JVM stops the daemon threads when all user threads (in contrast to the daemon threads) are terminated. Hence daemon threads can be used to implement, for example, a monitoring functionality as the thread is stopped by the JVM as soon as all user threads have stopped.

How to write a test which expects an Error to be thrown in Jasmine?

As mentioned previously, a function needs to be passed to toThrow as it is the function you're describing in your test: "I expect this function to throw x"

expect(() => parser.parse(raw))
  .toThrow(new Error('Parsing is not possible'));

If using Jasmine-Matchers you can also use one of the following when they suit the situation;

// I just want to know that an error was
// thrown and nothing more about it
expect(() => parser.parse(raw))
  .toThrowAnyError();

or

// I just want to know that an error of 
// a given type was thrown and nothing more
expect(() => parser.parse(raw))
  .toThrowErrorOfType(TypeError);

List of Java class file format major version numbers?

These come from the class version. If you try to load something compiled for java 6 in a java 5 runtime you'll get the error, incompatible class version, got 50, expected 49. Or something like that.

See here in byte offset 7 for more info.

Additional info can also be found here.

How to use regex in String.contains() method in Java

String.contains

String.contains works with String, period. It doesn't work with regex. It will check whether the exact String specified appear in the current String or not.

Note that String.contains does not check for word boundary; it simply checks for substring.

Regex solution

Regex is more powerful than String.contains, since you can enforce word boundary on the keywords (among other things). This means you can search for the keywords as words, rather than just substrings.

Use String.matches with the following regex:

"(?s).*\\bstores\\b.*\\bstore\\b.*\\bproduct\\b.*"

The RAW regex (remove the escaping done in string literal - this is what you get when you print out the string above):

(?s).*\bstores\b.*\bstore\b.*\bproduct\b.*

The \b checks for word boundary, so that you don't get a match for restores store products. Note that stores 3store_product is also rejected, since digit and _ are considered part of a word, but I doubt this case appear in natural text.

Since word boundary is checked for both sides, the regex above will search for exact words. In other words, stores stores product will not match the regex above, since you are searching for the word store without s.

. normally match any character except a number of new line characters. (?s) at the beginning makes . matches any character without exception (thanks to Tim Pietzcker for pointing this out).

Can I open a dropdownlist using jQuery

No you can't.

You can change the size to make it larger... similar to Dreas idea, but it is the size you need to change.

<select id="countries" size="6">
  <option value="1">Country 1</option>
  <option value="2">Country 2</option>
  <option value="3">Country 3</option>
  <option value="4">Country 4</option>
  <option value="5">Country 5</option>
  <option value="6">Country 6</option>
</select>

Bootstrap modal: is not a function

The problem is due to having jQuery instances more than one time. Take care if you are using many files with multiples instance of jQuery. Just leave 1 instance of jQuery and your code will work.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

Change Oracle port from port 8080

Oracle (database) can use many ports. when you install the software it scans for free ports and decides which port to use then.

The database listener defaults to 1520 but will use 1521 or 1522 if 1520 is not available. This can be adjusted in the listener.ora files.

The Enterprise Manager, web-based database administration tool defaults to port 80 but will use 8080 if 80 is not available.

See here for details on how to change the port number for enterprise manager: http://download-uk.oracle.com/docs/cd/B14099_19/integrate.1012/b19370/manage_oem.htm#i1012853

Finding Number of Cores in Java

If you want to dubbel check the amount of cores you have on your machine to the number your java program is giving you.

In Linux terminal: lscpu

In Windows terminal (cmd): echo %NUMBER_OF_PROCESSORS%

In Mac terminal: sysctl -n hw.ncpu

How can I get the current array index in a foreach loop?

You can get the index value with this

foreach ($arr as $key => $val)
{
    $key = (int) $key;
    //With the variable $key you can get access to the current array index
    //You can use $val[$key] to

}

How to convert any date format to yyyy-MM-dd

Try this code:

 lblUDate.Text = DateTime.Parse(ds.Tables[0].Rows[0]["AppMstRealPaidTime"].ToString()).ToString("yyyy-MM-dd");

getting "No column was specified for column 2 of 'd'" in sql server cte?

Because you are creatin a table expression, you have to specify the structure of that table, you can achive this on two way:

1: In the select you can use the original columnnames (as in your first example), but with aggregates you have to use an alias (also in conflicting names). Like

sum(totalitems) as bkdqty

2: You need to specify the column names rigth after the name of the talbe, and then you just have to take care that the count of the names should mach the number of coulms was selected in the query. Like:

d (duration, bkdqty) 
AS (Select.... ) 

With the second solution both of your query will work!

Java Scanner class reading strings

use sc.nextLine(); two time so that we can read the last line of string

sc.nextLine() sc.nextLine()

The name 'controlname' does not exist in the current context

Solution option #2 offered above works for windows forms applications and not web aspx application. I got similar error in web application, I resolved this by deleting a file where I had a user control by the same name, this aspx file was actually a backup file and was not referenced anywhere in the process, but still it caused the error because the name of user control registered on the backup file was named exactly same on the aspx file which was referenced in process flow. So I deleted the backup file and built solution, build succeeded.

Hope this helps some one in similar scenario.

Vijaya Laxmi.

Export to CSV using jQuery and html

A tiny update for @Terry Young answer, i.e. add IE 10+ support

if (window.navigator.msSaveOrOpenBlob) {
  // IE 10+
  var blob = new Blob([decodeURIComponent(encodeURI(csvString))], {
    type: 'text/csv;charset=' + document.characterSet
  });
  window.navigator.msSaveBlob(blob, filename);
} else {
  // actual real browsers
  //Data URI
  csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvData);

    $(this).attr({
      'download': filename,
      'href': csvData,
      'target': '_blank'
    });
}

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

How to scroll to an element?

Jul 2019 - Dedicated hook/function

A dedicated hook/function can hide implementation details, and provides a simple API to your components.

React 16.8 + Functional Component

const useScroll = () => {
  const elRef = useRef(null);
  const executeScroll = () => elRef.current.scrollIntoView();

  return [executeScroll, elRef];
};

Use it in any functional component.

const ScrollDemo = () => {
    const [executeScroll, elRef] = useScroll()
    useEffect(executeScroll, []) // Runs after component mounts
    
    return <div ref={elRef}>Element to scroll to</div> 
}

full demo

React 16.3 + class Component

const utilizeScroll = () => {
  const elRef = React.createRef();
  const executeScroll = () => elRef.current.scrollIntoView();

  return { executeScroll, elRef };
};

Use it in any class component.

class ScrollDemo extends Component {
  constructor(props) {
    super(props);
    this.elScroll = utilizeScroll();
  }

  componentDidMount() {
    this.elScroll.executeScroll();
  }

  render(){
    return <div ref={this.elScroll.elRef}>Element to scroll to</div> 
  }
} 

Full demo

Eclipse Optimize Imports to Include Static Imports

Shortcut for static import: CTRL + SHIFT + M

Killing a process using Java

On Windows, you could use this command.

taskkill /F /IM <processname>.exe 

To kill it forcefully, you may use;

Runtime.getRuntime().exec("taskkill /F /IM <processname>.exe")

Can gcc output C code after preprocessing?

cpp is the preprocessor.

Run cpp filename.c to output the preprocessed code, or better, redirect it to a file with cpp filename.c > filename.preprocessed.

Gson: Directly convert String to JsonObject (no POJO)

com.google.gson.JsonParser#parse(java.lang.String) is now deprecated

so use com.google.gson.JsonParser#parseString, it works pretty well

Kotlin Example:

val mJsonObject = JsonParser.parseString(myStringJsonbject).asJsonObject

Java Example:

JsonObject mJsonObject = JsonParser.parseString(myStringJsonbject).getAsJsonObject();

Autonumber value of last inserted row - MS Access / VBA

In your example, because you use CurrentDB to execute your INSERT you've made it harder for yourself. Instead, this will work:

  Dim query As String
  Dim newRow As Long  ' note change of data type
  Dim db As DAO.Database

  query = "INSERT INTO InvoiceNumbers (date) VALUES (" & NOW() & ");"
  Set db = CurrentDB
  db.Execute(query)
  newRow = db.OpenRecordset("SELECT @@IDENTITY")(0)
  Set db = Nothing

I used to do INSERTs by opening an AddOnly recordset and picking up the ID from there, but this here is a lot more efficient. And note that it doesn't require ADO.

Align text in a table header

Try to use text-align in style attribute to align center.

<th class="not_mapped_style" style="text-align:center">DisplayName</th>

Replace non ASCII character from string

This would be the Unicode solution

String s = "A função, Ãugent";
String r = s.replaceAll("\\P{InBasic_Latin}", "");

\p{InBasic_Latin} is the Unicode block that contains all letters in the Unicode range U+0000..U+007F (see regular-expression.info)

\P{InBasic_Latin} is the negated \p{InBasic_Latin}

Remove all multiple spaces in Javascript and replace with single space

You can also replace without a regular expression.

while(str.indexOf('  ')!=-1)str.replace('  ',' ');

How do I run .sh or .bat files from Terminal?

Drag-And-Drop

Easiest way for a lazy Mac user like me: Drag-and-drop the startup.sh file from the Finder to the Terminal window and press Return.

To shutdown Tomcat, do the same with shutdown.sh.

You can delete all the .bat files as they are only for a Windows PC, of no use on a Mac to other Unix computer. I delete them as it makes it easier to read that folder's listing.

File Permissions

I find that a fresh Tomcat download will not run on my Mac because of file permission restrictions throwing errors during startup. I use the BatChmod app which wraps a GUI around the equivelant Unix commands to reset file permissions.

Port-Forwarding

Unix systems protect access to ports numbered under 1024. So if you want to use port 80 with Tomcat you will need to learn how to do "port-forwarding" to forward incoming requests to port 8080 where Tomcat listens by default. To do port-forwarding, you issue commands to the packet-filtering (firewall) app built into Mac OS X (and BSD). In the old days we used ipfw. In Mac OS X 10.7 (Lion) and later Apple is moving to a newer tool, pf.

How can I make a CSS glass/blur effect work for an overlay?

Here's a possible solution.

HTML

<img id="source" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />

<div id="crop">
    <img id="overlay" src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>

CSS

#crop {
    overflow: hidden;

    position: absolute;
    left: 100px;
    top: 100px;

    width: 450px;
    height: 150px;
}

#overlay {
    -webkit-filter:blur(4px);
    filter:blur(4px);

    width: 450px;
}

#source {
    height: 300px;
    width: auto;
    position: absolute;
    left: 100px;
    top: 100px;
}

I know the CSS can be simplified and you probably should get rid of the ids. The idea here is to use a div as a cropping container and then apply blur on duplicate of the image. Fiddle

To make this work in Firefox, you would have to use SVG hack.

Python strip() multiple characters?

I did a time test here, using each method 100000 times in a loop. The results surprised me. (The results still surprise me after editing them in response to valid criticism in the comments.)

Here's the script:

import timeit

bad_chars = '(){}<>'

setup = """import re
import string
s = 'Barack (of Washington)'
bad_chars = '(){}<>'
rgx = re.compile('[%s]' % bad_chars)"""

timer = timeit.Timer('o = "".join(c for c in s if c not in bad_chars)', setup=setup)
print "List comprehension: ",  timer.timeit(100000)


timer = timeit.Timer("o= rgx.sub('', s)", setup=setup)
print "Regular expression: ", timer.timeit(100000)

timer = timeit.Timer('for c in bad_chars: s = s.replace(c, "")', setup=setup)
print "Replace in loop: ", timer.timeit(100000)

timer = timeit.Timer('s.translate(string.maketrans("", "", ), bad_chars)', setup=setup)
print "string.translate: ", timer.timeit(100000)

Here are the results:

List comprehension:  0.631745100021
Regular expression:  0.155561923981
Replace in loop:  0.235936164856
string.translate:  0.0965719223022

Results on other runs follow a similar pattern. If speed is not the primary concern, however, I still think string.translate is not the most readable; the other three are more obvious, though slower to varying degrees.

MySQL: How to copy rows, but change a few fields?

As long as Event_ID is Integer, do this:

INSERT INTO Table (foo, bar, Event_ID)
SELECT foo, bar, (Event_ID + 155)
  FROM Table
WHERE Event_ID = "120"

How to Execute SQL Script File in Java?

JDBC does not support this option (although a specific DB driver may offer this). Anyway, there should not be a problem with loading all file contents into memory.

How do I force git to use LF instead of CR+LF under windows?

core.autocrlf=input is the right setting for what you want, but you might have to do a git update-index --refresh and/or a git reset --hard for the change to take effect.

With core.autocrlf set to input, git will not apply newline-conversion on check-out (so if you have LF in the repo, you'll get LF), but it will make sure that in case you mess up and introduce some CRLFs in the working copy somehow, they won't make their way into the repo.

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

Html.DropDownList - Disabled/Readonly

I had to disable the dropdownlist and hide the primary ID

<div class="form-group">
        @Html.LabelFor(model => model.OBJ_ID, "Objs", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("OBJ_ID", null, htmlAttributes: new { @class = "form-control", @disabled = "disabled"})
            @Html.HiddenFor(m => m.OBJ_ID)
            @Html.ValidationMessageFor(model => model.OBJ_ID, "", new { @class = "text-danger" })
        </div>
    </div>

How do I extract text that lies between parentheses (round brackets)?

I came across this while I was looking for a solution to a very similar implementation.

Here is a snippet from my actual code. Starts substring from the first char (index 0).

 string separator = "\n";     //line terminator

 string output;
 string input= "HowAreYou?\nLets go there!";

 output = input.Substring(0, input.IndexOf(separator)); 

Is it possible to animate scrollTop with jQuery?

I was having issues where the animation was always starting from the top of the page after a page refresh in the other examples.

I fixed this by not animating the css directly but rather calling window.scrollTo(); on each step:

$({myScrollTop:window.pageYOffset}).animate({myScrollTop:300}, {
  duration: 600,
  easing: 'swing',
  step: function(val) {
    window.scrollTo(0, val);
  }
});

This also gets around the html vs body issue as it's using cross-browser JavaScript.

Have a look at http://james.padolsey.com/javascript/fun-with-jquerys-animate/ for more information on what you can do with jQuery's animate function.

How do you change library location in R?

This post is just to mention an additional option. In case you need to set custom R libs in your Linux shell script you may easily do so by

export R_LIBS="~/R/lib"

See R admin guide on complete list of options.

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

I know this is an old thread, but I just cannot steer away from posting some useful info on this. I see the Zip question come up a lot and this answers nearlly most of the common questions.

To get around framework issues of using 4.5+... Their is a ZipStorer class created by jaime-olivares: https://github.com/jaime-olivares/zipstorer, he also has added an example of how to use this class as well and has also added an example of how to search for a specific filename as well.

And for reference on how to use this and iterate through for a certain file extension as example you could do this:

#region
/// <summary>
/// Custom Method - Check if 'string' has '.png' or '.PNG' extension.
/// </summary>
static bool HasPNGExtension(string filename)
{
    return Path.GetExtension(filename).Equals(".png", StringComparison.InvariantCultureIgnoreCase)
        || Path.GetExtension(filename).Equals(".PNG", StringComparison.InvariantCultureIgnoreCase);
}
#endregion

private void button1_Click(object sender, EventArgs e)
{
    //NOTE: I recommend you add path checking first here, added the below as example ONLY.
    string ZIPfileLocationHere = @"C:\Users\Name\Desktop\test.zip";
    string EXTRACTIONLocationHere = @"C:\Users\Name\Desktop";

    //Opens existing zip file.
    ZipStorer zip = ZipStorer.Open(ZIPfileLocationHere, FileAccess.Read);

    //Read all directory contents.
    List<ZipStorer.ZipFileEntry> dir = zip.ReadCentralDir();

    foreach (ZipStorer.ZipFileEntry entry in dir)
    {
        try
        {
            //If the files in the zip are "*.png or *.PNG" extract them.
            string path = Path.Combine(EXTRACTIONLocationHere, (entry.FilenameInZip));
            if (HasPNGExtension(path))
            {
                //Extract the file.
                zip.ExtractFile(entry, path);
            }
        }
        catch (InvalidDataException)
        {
            MessageBox.Show("Error: The ZIP file is invalid or corrupted");
            continue;
        }
        catch
        {
            MessageBox.Show("Error: An unknown error ocurred while processing the ZIP file.");
            continue;
        }
    }
    zip.Close();
}

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

Difference between File.separator and slash in paths

As the gentlemen described the difference with variant details.

I would like to recommend the use of the Apache Commons io api, class FilenameUtils when dealing with files in a program with the possibility of deploying on multiple OSs.

Excel Formula: Count cells where value is date

Here's my solution. If your cells will contain only dates or blanks, just compare it to another date. If the cell can be converted to date, it will be counted.

=COUNTIF(C:C,">1/1/1900")
## Counts all the dates in column C

Caution, cells with numbers will be counted.

How do I change the default application icon in Java?

Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.

com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );

That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.

jQuery Date Picker - disable past dates

you have to declare current date into variables like this

 $(function() {
    var date = new Date();
    var currentMonth = date.getMonth();
    var currentDate = date.getDate();
    var currentYear = date.getFullYear();
    $('#datepicker').datepicker({
    minDate: new Date(currentYear, currentMonth, currentDate)
    });
})

Plot multiple lines (data series) each with unique color in R

More than one line can be drawn on the same chart by using the lines()function

# Create the data for the chart.
v <- c(7,12,28,3,41)
t <- c(14,7,6,19,3)

# Give the chart file a name.
png(file = "line_chart_2_lines.jpg")

# Plot the bar chart.
plot(v,type = "o",col = "red", xlab = "Month", ylab = "Rain fall", 
   main = "Rain fall chart")

lines(t, type = "o", col = "blue")

# Save the file.
dev.off()

OUTPUT enter image description here

How can I change the default Mysql connection timeout when connecting through python?

I know this is an old question but just for the record this can also be done by passing appropriate connection options as arguments to the _mysql.connect call. For example,

con = _mysql.connect(host='localhost', user='dell-pc', passwd='', db='test',
          connect_timeout=1000)

Notice the use of keyword parameters (host, passwd, etc.). They improve the readability of your code.

For detail about different arguments that you can pass to _mysql.connect, see MySQLdb API documentation

Modify XML existing content in C#

Using LINQ to xml if you are using framework 3.5

using System.Xml.Linq;

XDocument xmlFile = XDocument.Load("books.xml"); 
var query = from c in xmlFile.Elements("catalog").Elements("book")    
            select c; 
foreach (XElement book in query) 
{
    book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");

What are good ways to prevent SQL injection?

My answer is quite easy:

Use Entity Framework for communication between C# and your SQL database. That will make parameterized SQL strings that isn't vulnerable to SQL injection.

As a bonus, it's very easy to work with as well.

Java, How do I get current index/key in "for each" loop

As others pointed out, 'not possible directly'. I am guessing that you want some kind of index key for Song? Just create another field (a member variable) in Element. Increment it when you add Song to the collection.

How to remove the arrows from input[type="number"] in Opera

Those arrows are part of the Shadow DOM, which are basically DOM elements on your page which are hidden from you. If you're new to the idea, a good introductory read can be found here.

For the most part, the Shadow DOM saves us time and is good. But there are instances, like this question, where you want to modify it.

You can modify these in Webkit now with the right selectors, but this is still in the early stages of development. The Shadow DOM itself has no unified selectors yet, so the webkit selectors are proprietary (and it isn't just a matter of appending -webkit, like in other cases).

Because of this, it seems likely that Opera just hasn't gotten around to adding this yet. Finding resources about Opera Shadow DOM modifications is tough, though. A few unreliable internet sources I've found all say or suggest that Opera doesn't currently support Shadow DOM manipulation.

I spent a bit of time looking through the Opera website to see if there'd be any mention of it, along with trying to find them in Dragonfly...neither search had any luck. Because of the silence on this issue, and the developing nature of the Shadow DOM + Shadow DOM manipulation, it seems to be a safe conclusion that you just can't do it in Opera, at least for now.

Change button background color using swift language

/*Swift-5 update*/

let tempBtn: UIButton = UIButton(frame: CGRect(x: 5, y: 20, width: 40, height: 40))       
tempBtn.backgroundColor = UIColor.red

Initializing a two dimensional std::vector

Let's say you want to initialize 2D vector, m*n, with initial value to be 0

we could do this

#include<iostream>
int main(){ 
    int m = 2, n = 5;

    vector<vector<int>> vec(m, vector<int> (n, 0));

    return 0;
}

How to check for null/empty/whitespace values with a single test?

Every single persons suggestion to run a query in Oracle to find records whose specific field is just blank, (this is not including (null) or any other field just a blank line) did not work. I tried every single suggested code. Guess I will keep searching online.

*****UPDATE*****

I tried this and it worked, not sure why it would not work if < 1 but for some reason < 2 worked and only returned records whose field is just blank

select [columnName] from [tableName] where LENGTH(columnName) < 2 ;

I am guessing whatever script that was used to convert data over has left something in the field even though it shows blank, that is my guess anyways as to why the < 2 works but not < 1

However, if you have any other values in that column field that is less than two characters then you might have to come up with another solution. If there are not a lot of other characters then you can single them out.

Hope my solution helps someone else out there some day.

Using Java 8's Optional with Stream::flatMap

I'm adding this second answer based on a proposed edit by user srborlongan to my other answer. I think the technique proposed was interesting, but it wasn't really suitable as an edit to my answer. Others agreed and the proposed edit was voted down. (I wasn't one of the voters.) The technique has merit, though. It would have been best if srborlongan had posted his/her own answer. This hasn't happened yet, and I didn't want the technique to be lost in the mists of the StackOverflow rejected edit history, so I decided to surface it as a separate answer myself.

Basically the technique is to use some of the Optional methods in a clever way to avoid having to use a ternary operator (? :) or an if/else statement.

My inline example would be rewritten this way:

Optional<Other> result =
    things.stream()
          .map(this::resolve)
          .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))
          .findFirst();

An my example that uses a helper method would be rewritten this way:

/**
 * Turns an Optional<T> into a Stream<T> of length zero or one depending upon
 * whether a value is present.
 */
static <T> Stream<T> streamopt(Optional<T> opt) {
    return opt.map(Stream::of)
              .orElseGet(Stream::empty);
}

Optional<Other> result =
    things.stream()
          .flatMap(t -> streamopt(resolve(t)))
          .findFirst();

COMMENTARY

Let's compare the original vs modified versions directly:

// original
.flatMap(o -> o.isPresent() ? Stream.of(o.get()) : Stream.empty())

// modified
.flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty))

The original is a straightforward if workmanlike approach: we get an Optional<Other>; if it has a value, we return a stream containing that value, and if it has no value, we return an empty stream. Pretty simple and easy to explain.

The modification is clever and has the advantage that it avoids conditionals. (I know that some people dislike the ternary operator. If misused it can indeed make code hard to understand.) However, sometimes things can be too clever. The modified code also starts off with an Optional<Other>. Then it calls Optional.map which is defined as follows:

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

The map(Stream::of) call returns an Optional<Stream<Other>>. If a value was present in the input Optional, the returned Optional contains a Stream that contains the single Other result. But if the value was not present, the result is an empty Optional.

Next, the call to orElseGet(Stream::empty) returns a value of type Stream<Other>. If its input value is present, it gets the value, which is the single-element Stream<Other>. Otherwise (if the input value is absent) it returns an empty Stream<Other>. So the result is correct, the same as the original conditional code.

In the comments discussing on my answer, regarding the rejected edit, I had described this technique as "more concise but also more obscure". I stand by this. It took me a while to figure out what it was doing, and it also took me a while to write up the above description of what it was doing. The key subtlety is the transformation from Optional<Other> to Optional<Stream<Other>>. Once you grok this it makes sense, but it wasn't obvious to me.

I'll acknowledge, though, that things that are initially obscure can become idiomatic over time. It might be that this technique ends up being the best way in practice, at least until Optional.stream gets added (if it ever does).

UPDATE: Optional.stream has been added to JDK 9.

Item frequency count in Python

The Counter class in the collections module is purpose built to solve this type of problem:

from collections import Counter
words = "apple banana apple strawberry banana lemon"
Counter(words.split())
# Counter({'apple': 2, 'banana': 2, 'strawberry': 1, 'lemon': 1})

CSS3 Transition not working

A general answer for a general question... Transitions can't animate properties that are auto. If you have a transition not working, check that the starting value of the property is explicitly set. (For example, to make a node collapse, when it's height is auto and must stay that way, put the transition on max-height instead. Give max-height a sensible initial value, then transition it to 0)

What is the difference between varchar and nvarchar?

nVarchar will help you to store Unicode characters. It is the way to go if you want to store localized data.

scp files from local to remote machine error: no such file or directory

As @Astariul said, path to the file might cause this bug.
In addition, any parent directory which contains non-ASCII character, for example Chinese, will cause this.
In that case, you should rename you parent directory

How do I do base64 encoding on iOS?

I have done it using the following class..

@implementation Base64Converter
static char base64EncodingTable[64] = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L',  'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7',    '8', '9', '+', '/'
};
+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {

unsigned long ixtext, lentext;

long ctremaining;

unsigned char input[3], output[4];

short i, charsonline = 0, ctcopy;

const unsigned char *raw;

NSMutableString *result;

lentext = [data length];

if (lentext < 1)
    return @"";

result = [NSMutableString stringWithCapacity: lentext];

raw = [data bytes];

ixtext = 0;

while (true) {

    ctremaining = lentext - ixtext;

    if (ctremaining <= 0)
        break;

    for (i = 0; i < 3; i++) {
        unsigned long ix = ixtext + i;
        if (ix < lentext)
            input[i] = raw[ix];
        else
            input[i] = 0;
    }

    output[0] = (input[0] & 0xFC) >> 2;

    output[1] = ((input[0] & 0x03) << 4) | ((input[1] & 0xF0) >> 4);

    output[2] = ((input[1] & 0x0F) << 2) | ((input[2] & 0xC0) >> 6);

    output[3] = input[2] & 0x3F;

    ctcopy = 4;

    switch (ctremaining) {
        case 1:
            ctcopy = 2;
            break;

        case 2:
            ctcopy = 3;
            break;
    }

    for (i = 0; i < ctcopy; i++)
        [result appendString: [NSString stringWithFormat: @"%c", base64EncodingTable[output[i]]]];

    for (i = ctcopy; i < 4; i++)
        [result appendString: @"="];

    ixtext += 3;

    charsonline += 4;

    if ((length > 0) && (charsonline >= length))
        charsonline = 0;
}
return result;
}
@end

While calling call

 [Base64Converter base64StringFromData:dataval length:lengthval];

That's it...

Change font size of UISegmentedControl

You can get at the actual font for the UILabel by recursively examining each of the views starting with the UISegmentedControl. I don't know if this is the best way to do it, but it works.

@interface tmpSegmentedControlTextViewController : UIViewController {
}

@property (nonatomic, assign) IBOutlet UISegmentedControl * theControl;

@end

@implementation tmpSegmentedControlTextViewController

@synthesize theControl; // UISegmentedControl

- (void)viewDidLoad {
  [self printControl:[self theControl]];
  [super viewDidLoad];
}

- (void) printControl:(UIView *) view {
  NSArray * views = [view subviews];
  NSInteger idx,idxMax;
  for (idx = 0, idxMax = views.count; idx < idxMax; idx++) {
    UIView * thisView = [views objectAtIndex:idx];
    UILabel * tmpLabel = (UILabel *) thisView;
    if ([tmpLabel respondsToSelector:@selector(text)]) {
      NSLog(@"TEXT for view %d: %@",idx,tmpLabel.text);
      [tmpLabel setTextColor:[UIColor blackColor]];
    }

    if (thisView.subviews.count) {
      NSLog(@"View has subviews");
      [self printControl:thisView];
    }
  }
}

@end

In the code above I am just setting the text color of the UILabel, but you could grab or set the font property as well I suppose.

How is CountDownLatch used in Java Multithreading?

package practice;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch c= new CountDownLatch(3);  // need to decrements the count (3) to zero by calling countDown() method so that main thread will wake up after calling await() method 
        Task t = new Task(c);
        Task t1 = new Task(c);
        Task t2 = new Task(c);
        t.start();
        t1.start();
        t2.start();
        c.await(); // when count becomes zero main thread will wake up 
        System.out.println("This will print after count down latch count become zero");
    }
}

class Task extends Thread{
    CountDownLatch c;

    public Task(CountDownLatch c) {
        this.c = c;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(1000);
            c.countDown();   // each thread decrement the count by one 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Ruby on Rails: Where to define global constants?

Another option, if you want to define your constants in one place:

module DSL
  module Constants
    MY_CONSTANT = 1
  end
end

But still make them globally visible without having to access them in fully qualified way:

DSL::Constants::MY_CONSTANT # => 1
MY_CONSTANT # => NameError: uninitialized constant MY_CONSTANT
Object.instance_eval { include DSL::Constants }
MY_CONSTANT # => 1

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

on ubuntu 18.04 in etc/phpmyadmin/config.inc.php comment all the block

Optional: User for advanced features

How to stop C# console applications from closing automatically?

Alternatively, you can delay the closing using the following code:

System.Threading.Thread.Sleep(1000);

Note the Sleep is using milliseconds.

How to drop a database with Mongoose?

To drop all documents in a collection:

await mongoose.connection.db.dropDatabase();

This answer is based off the mongoose index.d.ts file:

dropDatabase(): Promise<any>;

"google is not defined" when using Google Maps V3 in Firefox remotely

try this:

<script src="https://maps.googleapis.com/maps/api/js"></script>

it works for me... the point is, change HTTP to HTTPS

Maximum size of an Array in Javascript

Like @maerics said, your target machine and browser will determine performance.

But for some real world numbers, on my 2017 enterprise Chromebook, running the operation:

console.time();
Array(x).fill(0).filter(x => x < 6).length
console.timeEnd();
  • x=5e4 takes 16ms, good enough for 60fps
  • x=4e6 takes 250ms, which is noticeable but not a big deal
  • x=3e7 takes 1300ms, which is pretty bad
  • x=4e7 takes 11000ms and allocates an extra 2.5GB of memory

So around 30 million elements is a hard upper limit, because the javascript VM falls off a cliff at 40 million elements and will probably crash the process.


EDIT: In the code above, I'm actually filling the array with elements and looping over them, simulating the minimum of what an app might want to do with an array. If you just run Array(2**32-1) you're creating a sparse array that's closer to an empty JavaScript object with a length, like {length: 4294967295}. If you actually tried to use all those 4 billion elements, you'll definitely your user's javascript process.

Is it possible to use global variables in Rust?

It's possible but no heap allocation allowed directly. Heap allocation is performed at runtime. Here are a few examples:

static SOME_INT: i32 = 5;
static SOME_STR: &'static str = "A static string";
static SOME_STRUCT: MyStruct = MyStruct {
    number: 10,
    string: "Some string",
};
static mut db: Option<sqlite::Connection> = None;

fn main() {
    println!("{}", SOME_INT);
    println!("{}", SOME_STR);
    println!("{}", SOME_STRUCT.number);
    println!("{}", SOME_STRUCT.string);

    unsafe {
        db = Some(open_database());
    }
}

struct MyStruct {
    number: i32,
    string: &'static str,
}

Python: Best way to add to sys.path relative to the current running script

This is what I use:

import os, sys
sys.path.append(os.path.join(os.path.dirname(__file__), "lib"))

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Entity Framework - Include Multiple Levels of Properties

Let me state it clearly that you can use the string overload to include nested levels regardless of the multiplicities of the corresponding relationships, if you don't mind using string literals:

query.Include("Collection.Property")

Relative frequencies / proportions with dplyr

Here is a base R answer using aggregate and ave :

df1 <- with(mtcars, aggregate(list(n = mpg), list(am = am, gear = gear), length))
df1$prop <- with(df1, n/ave(n, am, FUN = sum))
#Also with prop.table
#df1$prop <- with(df1, ave(n, am, FUN = prop.table))
df1

#  am gear  n      prop
#1  0    3 15 0.7894737
#2  0    4  4 0.2105263
#3  1    4  8 0.6153846
#4  1    5  5 0.3846154 

We can also use prop.table but the output displays differently.

prop.table(table(mtcars$am, mtcars$gear), 1)
   
#            3         4         5
#  0 0.7894737 0.2105263 0.0000000
#  1 0.0000000 0.6153846 0.3846154

Select multiple columns from a table, but group by one

You can try this:

Select ProductID,ProductName,Sum(OrderQuantity) 
 from OrderDetails Group By ProductID, ProductName

You're only required to Group By columns that doesn't come with an aggregate function in the Select clause. So you can just use Group By ProductID and ProductName in this case.

Resize external website content to fit iFrame width

What you can do is set specific width and height to your iframe (for example these could be equal to your window dimensions) and then applying a scale transformation to it. The scale value will be the ratio between your window width and the dimension you wanted to set to your iframe.

E.g.

<iframe width="1024" height="768" src="http://www.bbc.com" style="-webkit-transform:scale(0.5);-moz-transform-scale(0.5);"></iframe>

How to calculate mean, median, mode and range from a set of numbers

Yes, there does seem to be 3rd libraries (none in Java Math). Two that have come up are:

http://opsresearch.com/app/

http://www.iro.umontreal.ca/~simardr/ssj/indexe.html

but, it is actually not that difficult to write your own methods to calculate mean, median, mode and range.

MEAN

public static double mean(double[] m) {
    double sum = 0;
    for (int i = 0; i < m.length; i++) {
        sum += m[i];
    }
    return sum / m.length;
}

MEDIAN

// the array double[] m MUST BE SORTED
public static double median(double[] m) {
    int middle = m.length/2;
    if (m.length%2 == 1) {
        return m[middle];
    } else {
        return (m[middle-1] + m[middle]) / 2.0;
    }
}

MODE

public static int mode(int a[]) {
    int maxValue, maxCount;

    for (int i = 0; i < a.length; ++i) {
        int count = 0;
        for (int j = 0; j < a.length; ++j) {
            if (a[j] == a[i]) ++count;
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = a[i];
        }
    }

    return maxValue;
}

UPDATE

As has been pointed out by Neelesh Salpe, the above does not cater for multi-modal collections. We can fix this quite easily:

public static List<Integer> mode(final int[] numbers) {
    final List<Integer> modes = new ArrayList<Integer>();
    final Map<Integer, Integer> countMap = new HashMap<Integer, Integer>();

    int max = -1;

    for (final int n : numbers) {
        int count = 0;

        if (countMap.containsKey(n)) {
            count = countMap.get(n) + 1;
        } else {
            count = 1;
        }

        countMap.put(n, count);

        if (count > max) {
            max = count;
        }
    }

    for (final Map.Entry<Integer, Integer> tuple : countMap.entrySet()) {
        if (tuple.getValue() == max) {
            modes.add(tuple.getKey());
        }
    }

    return modes;
}

ADDITION

If you are using Java 8 or higher, you can also determine the modes like this:

public static List<Integer> getModes(final List<Integer> numbers) {
    final Map<Integer, Long> countFrequencies = numbers.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    final long maxFrequency = countFrequencies.values().stream()
            .mapToLong(count -> count)
            .max().orElse(-1);

    return countFrequencies.entrySet().stream()
            .filter(tuple -> tuple.getValue() == maxFrequency)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());
}

How to extract the n-th elements from a list of tuples?

Using islice and chain.from_iterable:

>>> from itertools import chain, islice
>>> elements = [(1,1,1),(2,3,7),(3,5,10)]
>>> list(chain.from_iterable(islice(item, 1, 2) for item in elements))
[1, 3, 5]

This can be useful when you need more than one element:

>>> elements = [(0, 1, 2, 3, 4, 5), 
                (10, 11, 12, 13, 14, 15), 
                (20, 21, 22, 23, 24, 25)]
>>> list(chain.from_iterable(islice(tuple_, 2, 5) for tuple_ in elements))
[2, 3, 4, 12, 13, 14, 22, 23, 24]