Programs & Examples On #Office 2007

For issues relating to Microsoft Office, version 2007.

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

Here is what you do in Excel 2003:

  1. In your sheet of interest, go to Format -> Sheet -> Hide and hide your sheet.
  2. Go to Tools -> Protection -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Here is what you do in Excel 2007:

  1. In your sheet of interest, go to Home ribbon -> Format -> Hide & Unhide -> Hide Sheet and hide your sheet.
  2. Go to Review ribbon -> Protect Workbook, make sure Structure is selected, and enter your password of choice.

Once this is done, the sheet is hidden and cannot be unhidden without the password. Make sense?


If you really need to keep some calculations secret, try this: use Access (or another Excel workbook or some other DB of your choice) to calculate what you need calculated, and export only the "unclassified" results to your Excel workbook.

Call web service in excel

For an updated answer see this SO question:

calling web service using VBA code in excel 2010

Both threads should be merged though.

excel delete row if column contains value from to-remove-list

Here is how I would do it if working with a large number of "to remove" values that would take a long time to manually remove.

  • -Put Original List in Column A -Put To Remove list in Column B -Select both columns, then "Conditional Formatting"
    -Select "Hightlight Cells Rules" --> "Duplicate Values"
    -The duplicates should be hightlighted in both columns
    -Then select Column A and then "Sort & Filter" ---> "Custom Sort"
    -In the dialog box that appears, select the middle option "Sort On" and pick "Cell Color"
    -Then select the next option "Sort Order" and choose "No Cell Color" "On bottom"
    -All the highlighted cells should be at the top of the list. -Select all the highlighted cells by scrolling down the list, then click delete.

How to calculate the inverse of the normal cumulative distribution function in python?

NORMSINV (mentioned in a comment) is the inverse of the CDF of the standard normal distribution. Using scipy, you can compute this with the ppf method of the scipy.stats.norm object. The acronym ppf stands for percent point function, which is another name for the quantile function.

In [20]: from scipy.stats import norm

In [21]: norm.ppf(0.95)
Out[21]: 1.6448536269514722

Check that it is the inverse of the CDF:

In [34]: norm.cdf(norm.ppf(0.95))
Out[34]: 0.94999999999999996

By default, norm.ppf uses mean=0 and stddev=1, which is the "standard" normal distribution. You can use a different mean and standard deviation by specifying the loc and scale arguments, respectively.

In [35]: norm.ppf(0.95, loc=10, scale=2)
Out[35]: 13.289707253902945

If you look at the source code for scipy.stats.norm, you'll find that the ppf method ultimately calls scipy.special.ndtri. So to compute the inverse of the CDF of the standard normal distribution, you could use that function directly:

In [43]: from scipy.special import ndtri

In [44]: ndtri(0.95)
Out[44]: 1.6448536269514722

How to Troubleshoot Intermittent SQL Timeout Errors

The issue is because of a bad query the time to executing query is taking more than 60 seconds or a Lock on the Table

The issue looks like a deadlock is occurring; we have queries which are blocking the queries to complete in time. The default timeout for a query is 60 secs and beyond that we will have the SQLException for timeout.

Please check the SQL Server logs for deadlocks. The other way to solve the issue to to increase the Timeout on the Command Object (Temp Solution).

Get selected text from a drop-down list (select box) using jQuery

var someName = "Test";

$("#<%= ddltest.ClientID %>").each(function () {
    $('option', this).each(function () {
        if ($(this).text().toLowerCase() == someName) {
            $(this).attr('selected', 'selected')
        };
    });
});

That will help you to get right direction. Above code is fully tested if you need further help let me know.

Add inline style using Javascript

You can try with this

nFilter.style.cssText = 'width:330px;float:left;';

That should do it for you.

"Find next" in Vim

It is n for next and N for previous.

And if you use reverse search with ? (for example, ?cake) instead of /, it is the other way round.

If it is installed on your system, you should try to run vimtutor command from your terminal, which will start a tutorial of the basic Vim commands.

Rob Wells advice about * and # is also very pertinent.

How to get a shell environment variable in a makefile?

all:
    echo ${PATH}

Or change PATH just for one command:

all:
    PATH=/my/path:${PATH} cmd

Correct way to try/except using Python requests module?

Exception object also contains original response e.response, that could be useful if need to see error body in response from the server. For example:

try:
    r = requests.post('somerestapi.com/post-here', data={'birthday': '9/9/3999'})
    r.raise_for_status()
except requests.exceptions.HTTPError as e:
    print (e.response.text)

List of IP Space used by Facebook

The list from 2020-05-23 is:

31.13.24.0/21
31.13.64.0/18
45.64.40.0/22
66.220.144.0/20
69.63.176.0/20
69.171.224.0/19
74.119.76.0/22
102.132.96.0/20
103.4.96.0/22
129.134.0.0/16
147.75.208.0/20
157.240.0.0/16
173.252.64.0/18
179.60.192.0/22
185.60.216.0/22
185.89.216.0/22
199.201.64.0/22
204.15.20.0/22

The method to fetch this list is already documented on Facebook's Developer site, you can make a whois call to see all IPs assigned to Facebook:

whois -h whois.radb.net -- '-i origin AS32934' | grep ^route

Difference between <? super T> and <? extends T> in Java

I love the answer from @Bert F but this is the way my brain sees it.

I have an X in my hand. If I want to write my X into a List, that List needs to be either a List of X or a List of things that my X can be upcast to as I write them in i.e. any superclass of X...

List<? super   X>

If I get a List and I want to read an X out of that List, that better be a List of X or a List of things that can be upcast to X as I read them out, i.e. anything that extends X

List<? extends X>

Hope this helps.

List file names based on a filename pattern and file content?

Assume LMN2011* files are inside /home/me but skipping anything in /home/me/temp or below:

find /home/me -name 'LMN2011*' -not -path "/home/me/temp/*" -print | xargs grep 'LMN20113456'

How to add a border just on the top side of a UIView

If I'm building from within the storyboard, I prefer add an UIView behind my useful UIView... If I want to create a border on the top of my UIView, I just increase the height of the background UIView by my border width.. The same can be done for any other side :)

ToggleClass animate jQuery?

You can simply use CSS transitions, see this fiddle

.on {
color:#fff;
transition:all 1s;
}

.off{
color:#000;
transition:all 1s;
}

Arrays.asList() of an array

You are trying to cast int[] to Integer[], this is not possible.

You can use commons-lang's ArrayUtils to convert the ints to Integers before getting the List from the array:

public int getTheNumber(int[] factors) {
    Integer[] integers = ArrayUtils.toObject(factors);
    ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(integers));
    Collections.sort(f);
    return f.get(0)*f.get(f.size()-1);
}    

Is there a way to iterate over a dictionary?

Yes, NSDictionary supports fast enumeration. With Objective-C 2.0, you can do this:

// To print out all key-value pairs in the NSDictionary myDict
for(id key in myDict)
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

The alternate method (which you have to use if you're targeting Mac OS X pre-10.5, but you can still use on 10.5 and iPhone) is to use an NSEnumerator:

NSEnumerator *enumerator = [myDict keyEnumerator];
id key;
// extra parens to suppress warning about using = instead of ==
while((key = [enumerator nextObject]))
    NSLog(@"key=%@ value=%@", key, [myDict objectForKey:key]);

How to use systemctl in Ubuntu 14.04

Ubuntu 14 and lower does not have "systemctl" Source: https://docs.docker.com/install/linux/linux-postinstall/#configure-docker-to-start-on-boot

Configure Docker to start on boot:

Most current Linux distributions (RHEL, CentOS, Fedora, Ubuntu 16.04 and higher) use systemd to manage which services start when the system boots. Ubuntu 14.10 and below use upstart.

1) systemd (Ubuntu 16 and above):

$ sudo systemctl enable docker

To disable this behavior, use disable instead.

$ sudo systemctl disable docker

2) upstart (Ubuntu 14 and below):

Docker is automatically configured to start on boot using upstart. To disable this behavior, use the following command:

$ echo manual | sudo tee /etc/init/docker.override
chkconfig

$ sudo chkconfig docker on

Done.

How to make a <div> appear in front of regular text/tables

It moves table down because there is no much space, try to decrease/increase width of certain elements so that it finds some space and does not push the table down. Also you may want to use absolute positioning to position the div at exactly the place you want, for example:

<style>
 #div_id
 {
   position:absolute;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

If you want to appear it over something, you also need to give it z-index, so it might look like this:

<style>
 #div_id
 {
   position:absolute;
   z-index:999;
   top:100px; /* set top value */
   left:100px; /* set left value */
   width:100px;  /* set width value */
 }
</style>

Get public/external IP address?

Using a great similar service

private string GetPublicIpAddress()
{
    var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");

    request.UserAgent = "curl"; // this will tell the server to return the information as if the request was made by the linux "curl" command

    string publicIPAddress;

    request.Method = "GET";
    using (WebResponse response = request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            publicIPAddress = reader.ReadToEnd();
        }
    }

    return publicIPAddress.Replace("\n", "");
}

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

How to import Maven dependency in Android Studio/IntelliJ?

As of version 0.8.9, Android Studio supports the Maven Central Repository by default. So to add an external maven dependency all you need to do is edit the module's build.gradle file and insert a line into the dependencies section like this:

dependencies {

    // Remote binary dependency
    compile 'net.schmizz:sshj:0.10.0'

}

You will see a message appear like 'Sync now...' - click it and wait for the maven repo to be downloaded along with all of its dependencies. There will be some messages in the status bar at the bottom telling you what's happening regarding the download. After it finishes this, the imported JAR file along with its dependencies will be listed in the External Repositories tree in the Project Browser window, as shown below.

enter image description here

Some further explanations here: http://developer.android.com/sdk/installing/studio-build.html

How do you change the formatting options in Visual Studio Code?

At the VS code

press Ctrl+Shift+P

then type Format Document With...

At the end of the list click on Configure Default Formatter...

Now you can choose your favorite beautifier from the list.

Update 2021

if "Format Document With..." didn't exist any more, go to file => preferences => settings then navigate to Extensions => Vetur scroll a little bit then you will see format > defaultFormatter:css, now you can pick any document formatter that you installed bofer for different file type extensions.

Type List vs type ArrayList in Java

It is considered good style to store a reference to a HashSet or TreeSet in a variable of type Set.

Set<String> names = new HashSet<String>();

This way, you have to change only one line if you decide to use a TreeSet instead.

Also, methods that operate on sets should specify parameters of type Set:

public static void print(Set<String> s)

Then the method can be used for all set implementations.

In theory, we should make the same recommendation for linked lists, namely to save LinkedList references in variables of type List. However, in the Java library, the List interface is common to both the ArrayList and the LinkedList class. In particular, it has get and set methods for random access, even though these methods are very inefficient for linked lists.

You can’t write efficient code if you don’t know whether random access is efficient or not.

This is plainly a serious design error in the standard library, and I cannot recommend using the List interface for that reason.

To see just how embarrassing that error is, have a look at the source code for the binarySearch method of the Collections class. That method takes a List parameter, but binary search makes no sense for a linked list. The code then clumsily tries to discover whether the list is a linked list, and then switches to a linear search!

The Set interface and the Map interface, are well designed, and you should use them.

How can a LEFT OUTER JOIN return more records than exist in the left table?

Each record from the left table will be returned as many times as there are matching records on the right table -- at least 1, but could easily be more than 1.

Pythonic way to combine FOR loop and IF statement

A simple way to find unique common elements of lists a and b:

a = [1,2,3]
b = [3,6,2]
for both in set(a) & set(b):
    print(both)

Read from file in eclipse

You are searching/reading the file "fiel.txt" in the execution directory (where the class are stored, i think).

If you whish to read the file in a given directory, you have to says so :

File file = new File(System.getProperty("user.dir")+"/"+"file.txt");

You could also give the directory with a relative path, eg "./images/photo.gif) for a subdirecory for example.

Note that there is also a property for the separator (hard-coded to "/" in my exemple)

regards Guillaume

Check whether user has a Chrome extension installed

Here is an other modern approach:

const checkExtension = (id, src, callback) => {
    let e = new Image()
    e.src = 'chrome-extension://'+ id +'/'+ src
    e.onload = () => callback(1), e.onerror = () => callback(0)
}

// "src" must be included to "web_accessible_resources" in manifest.json
checkExtension('gighmmpiobklfepjocnamgkkbiglidom', 'icons/icon24.png', (ok) => {
    console.log('AdBlock: %s', ok ? 'installed' : 'not installed')
})
checkExtension('bhlhnicpbhignbdhedgjhgdocnmhomnp', 'images/checkmark-icon.png', (ok) => {
    console.log('ColorZilla: %s', ok ? 'installed' : 'not installed')
})

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

One graph can replace many words:

enter image description here

Enjoy! :-)

# I have updated the correct image...

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

In case of Homebrew, the directory for data files is /usr/local/var/mysql

to see which my.cnf file is used here are the search locations from my environment /etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf

So to clean up this error I did the following

mysqladmin -u root shutdown
rm /usr/local/var/mysql/<dbname>/problemtablename.ibd

Note: in my case i didnt care about the data as it is dev setup, probably happened because i restored my laptop with timemachine

Assign static IP to Docker container

This works for me.

Create a network with docker network create --subnet=172.17.0.0/16 selnet

Run docker image docker run --net selnet --ip 172.18.0.2 hub

At first, I got

docker: Error response from daemon: Invalid address 172.17.0.2: It does not belong to any of this network's subnets.
ERRO[0000] error waiting for container: context canceled

Solution: Increased the 2nd quadruple of the IP [.18. instead of .17.]

Making a Bootstrap table column fit to content

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />_x000D_
_x000D_
<h5>Left</h5>_x000D_
<table class="table table-responsive">_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <th>Action</th>        _x000D_
            <th>Name</th>_x000D_
            <th>Payment Method</th>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td  style="width:1px; white-space:nowrap;">_x000D_
                <a role="button" class="btn btn-default btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">View</a>_x000D_
                <a role="button" class="btn btn-primary btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Edit</a>_x000D_
                <a role="button" class="btn btn-danger btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Delete</a>                _x000D_
            </td>        _x000D_
            <td>Bart Foo</td>_x000D_
            <td>Visa</td>_x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>_x000D_
_x000D_
<h5>Right</h5>_x000D_
_x000D_
<table class="table table-responsive">_x000D_
    <tbody>_x000D_
        <tr>                    _x000D_
            <th>Name</th>_x000D_
            <th>Payment Method</th>_x000D_
            <th>Action</th>            _x000D_
        </tr>_x000D_
        <tr>_x000D_
_x000D_
            <td>Bart Foo</td>_x000D_
            <td>Visa</td>_x000D_
            <td  style="width:1px; white-space:nowrap;">_x000D_
                <a role="button" class="btn btn-default btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">View</a>_x000D_
                <a role="button" class="btn btn-primary btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Edit</a>_x000D_
                <a role="button" class="btn btn-danger btn-xs" href="/Payments/View/NnrN_8tMB0CkVXt06nkrYg">Delete</a>                _x000D_
            </td>            _x000D_
        </tr>_x000D_
    </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

PHP - Debugging Curl

If you just want a very quick way to debug the result:

$ch = curl_init();
curl_exec($ch);
$curl_error = curl_error($ch);
echo "<script>console.log($curl_error);</script>"

href="file://" doesn't work

Although the ffile:////.exe used to work (for example - some versions of early html 4) it appears html 5 disallows this. Tested using the following:

<a href="ffile:///<path name>/<filename>.exe" TestLink /a> 
<a href="ffile://<path name>/<filename>.exe" TestLink /a> 
<a href="ffile:/<path name>/<filename>.exe" TestLink /a> 
<a href="ffile:<path name>/<filename>.exe" TestLink /a> 
<a href="ffile://///<path name>/<filename>.exe" TestLink /a> 
<a href="file://<path name>/<filename>.exe" TestLink /a> 
<a href="file:/<path name>/<filename>.exe" TestLink /a> 
<a href="file:<path name>/<filename>.exe" TestLink /a> 
<a href="ffile://///<path name>/<filename>.exe" TestLink /a>

as well as ... 1/ substituted the "ffile" with just "file" 2/ all the above variations with the http:// prefixed before the ffile or file.

The best I could see was there is a possibility that if one wanted to open (edit) or save the file, it could be accomplished. However, the exec file would not execute otherwise.

Displaying unicode symbols in HTML

Make sure that you actually save the file as UTF-8, alternatively use HTML entities (&#nnn;) for the special characters.

index.php not loading by default

While adding 'DirectoryIndex index.php' to a .htaccess file may work,

NOTE:

In general, you should never use .htaccess files

This is quoted from http://httpd.apache.org/docs/1.3/howto/htaccess.html
Although this refers to an older version of apache, I believe the principle still applies.

Adding the following to your httpd.conf (if you have access to it) is considered better form, causes less server overhead and has the exact same effect:

<Directory /myapp>
DirectoryIndex index.php
</Directory>

How do I get client IP address in ASP.NET CORE?

The API has been updated. Not sure when it changed but according to Damien Edwards in late December, you can now do this:

var remoteIpAddress = request.HttpContext.Connection.RemoteIpAddress;

Formatting floats without trailing zeros

For float you could use this:

def format_float(num):
    return ('%i' if num == int(num) else '%s') % num

Test it:

>>> format_float(1.00000)
'1'
>>> format_float(1.1234567890000000000)
'1.123456789'

For Decimal see solution here: https://stackoverflow.com/a/42668598/5917543

yii2 hidden input value

Use the following:

echo $form->field($model, 'hidden1')->hiddenInput(['value'=> $value])->label(false);

CLEAR SCREEN - Oracle SQL Developer shortcut?

Ctrl+Shift+D, but you have to put focus on the script output panel first...which you can do via the KB.

Run script.

Alt+PgDn     -  puts you in Script Output panel.
Ctrl+Shift+D -  clears panel.
Alt+PgUp     -  puts you back in editor panel. 

Android JSONObject - How can I loop through a flat JSON object to get each key and value

Use the keys() iterator to iterate over all the properties, and call get() for each.

Iterator<String> iter = json.keys();
while (iter.hasNext()) {
    String key = iter.next();
    try {
        Object value = json.get(key);
    } catch (JSONException e) {
        // Something went wrong!
    }
}

Change image source with JavaScript

I know this question is old, but for the one's what are new, here is what you can do:

HTML

<img id="demo" src="myImage.png">

<button onclick="myFunction()">Click Me!</button>

JAVASCRIPT

function myFunction() {
document.getElementById('demo').src = "myImage.png";
}

How to find the remainder of a division in C?

Use the modulus operator %, it returns the remainder.

int a = 5;
int b = 3;

if (a % b != 0) {
   printf("The remainder is: %i", a%b);
}

VBA Date as integer

You can use bellow code example for date string like mdate and Now() like toDay, you can also calculate deference between both date like Aging

Public Sub test(mdate As String)
    Dim toDay As String
    mdate = Round(CDbl(CDate(mdate)), 0)
    toDay = Round(CDbl(Now()), 0)
    Dim Aging as String
    Aging = toDay - mdate
    MsgBox ("So aging is -" & Aging & vbCr & "from the date - " & _
    Format(mdate, "dd-mm-yyyy")) & " to " & Format(toDay, "dd-mm-yyyy"))
End Sub

NB: Used CDate for convert Date String to Valid Date

I am using this in Office 2007 :)

JavaScript variable number of arguments to function

In (most) recent browsers, you can accept variable number of arguments with this syntax:

function my_log(...args) {
     // args is an Array
     console.log(args);
     // You can pass this array as parameters to another function
     console.log(...args);
}

Here's a small example:

function foo(x, ...args) {
  console.log(x, args, ...args, arguments);
}

foo('a', 'b', 'c', z='d')

=>

a
Array(3) [ "b", "c", "d" ]
b c d
Arguments
?    0: "a"
    ?1: "b"
    ?2: "c"
    ?3: "d"
    ?length: 4

Documentation and more examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters

How do I print a double value with full precision using cout?

Use std::setprecision:

std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()/mysql_num_rows etc... expects parameter 1 to be resource

Your code should be something like this

$username = $_POST['username'];
$password = $_POST['password'];
$query = "SELECT * FROM Users WHERE UserName LIKE '$username'";
echo $query;
$result = mysql_query($query);

if($result === FALSE) {
    die(mysql_error("error message for the user")); 
}

while($row = mysql_fetch_array($result))
{
    echo $row['FirstName'];
}

Once done with that, you would get the query printed on the screen. Try this query on your server and see if it produces the desired results. Most of the times the error is in the query. Rest of the code is correct.

What size should TabBar images be?

According to my practice, I use the 40 x 40 for standard iPad tab bar item icon, 80 X 80 for retina.

From the Apple reference. https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/MobileHIG/BarIcons.html#//apple_ref/doc/uid/TP40006556-CH21-SW1

If you want to create a bar icon that looks like it's related to the iOS 7 icon family, use a very thin stroke to draw it. Specifically, a 2-pixel stroke (high resolution) works well for detailed icons and a 3-pixel stroke works well for less detailed icons.

Regardless of the icon’s visual style, create a toolbar or navigation bar icon in the following sizes:

About 44 x 44 pixels About 22 x 22 pixels (standard resolution) Regardless of the icon’s visual style, create a tab bar icon in the following sizes:

About 50 x 50 pixels (96 x 64 pixels maximum) About 25 x 25 pixels (48 x 32 pixels maximum) for standard resolution

What is the best alternative IDE to Visual Studio

If you're into C# and VB.Net and don't mind open source then you could use SharpDevelop. It does a pretty good job!

Decorators with parameters?

It is well known that the following two pieces of code are nearly equivalent:

@dec
def foo():
    pass    foo = dec(foo)

############################################
foo = dec(foo)

A common mistake is to think that @ simply hides the leftmost argument.

@dec(1, 2, 3)
def foo():
    pass    
###########################################
foo = dec(foo, 1, 2, 3)

It would be much easier to write decorators if the above is how @ worked. Unfortunately, that’s not the way things are done.


Consider a decorator Waitwhich haults program execution for a few seconds. If you don't pass in a Wait-time then the default value is 1 seconds. Use-cases are shown below.

##################################################
@Wait
def print_something(something):
    print(something)

##################################################
@Wait(3)
def print_something_else(something_else):
    print(something_else)

##################################################
@Wait(delay=3)
def print_something_else(something_else):
    print(something_else)

When Wait has an argument, such as @Wait(3), then the call Wait(3) is executed before anything else happens.

That is, the following two pieces of code are equivalent

@Wait(3)
def print_something_else(something_else):
    print(something_else)

###############################################
return_value = Wait(3)
@return_value
def print_something_else(something_else):
    print(something_else)

This is a problem.

if `Wait` has no arguments:
    `Wait` is the decorator.
else: # `Wait` receives arguments
    `Wait` is not the decorator itself.
    Instead, `Wait` ***returns*** the decorator

One solution is shown below:

Let us begin by creating the following class, DelayedDecorator:

class DelayedDecorator:
    def __init__(i, cls, *args, **kwargs):
        print("Delayed Decorator __init__", cls, args, kwargs)
        i._cls = cls
        i._args = args
        i._kwargs = kwargs
    def __call__(i, func):
        print("Delayed Decorator __call__", func)
        if not (callable(func)):
            import io
            with io.StringIO() as ss:
                print(
                    "If only one input, input must be callable",
                    "Instead, received:",
                    repr(func),
                    sep="\n",
                    file=ss
                )
                msg = ss.getvalue()
            raise TypeError(msg)
        return i._cls(func, *i._args, **i._kwargs)

Now we can write things like:

 dec = DelayedDecorator(Wait, delay=4)
 @dec
 def delayed_print(something):
    print(something)

Note that:

  • dec does not not accept multiple arguments.
  • dec only accepts the function to be wrapped.

    import inspect class PolyArgDecoratorMeta(type): def call(Wait, *args, **kwargs): try: arg_count = len(args) if (arg_count == 1): if callable(args[0]): SuperClass = inspect.getmro(PolyArgDecoratorMeta)[1] r = SuperClass.call(Wait, args[0]) else: r = DelayedDecorator(Wait, *args, **kwargs) else: r = DelayedDecorator(Wait, *args, **kwargs) finally: pass return r

    import time class Wait(metaclass=PolyArgDecoratorMeta): def init(i, func, delay = 2): i._func = func i._delay = delay

    def __call__(i, *args, **kwargs):
        time.sleep(i._delay)
        r = i._func(*args, **kwargs)
        return r 
    

The following two pieces of code are equivalent:

@Wait
def print_something(something):
     print (something)

##################################################

def print_something(something):
    print(something)
print_something = Wait(print_something)

We can print "something" to the console very slowly, as follows:

print_something("something")

#################################################
@Wait(delay=1)
def print_something_else(something_else):
    print(something_else)

##################################################
def print_something_else(something_else):
    print(something_else)

dd = DelayedDecorator(Wait, delay=1)
print_something_else = dd(print_something_else)

##################################################

print_something_else("something")

Final Notes

It may look like a lot of code, but you don't have to write the classes DelayedDecorator and PolyArgDecoratorMeta every-time. The only code you have to personally write something like as follows, which is fairly short:

from PolyArgDecoratorMeta import PolyArgDecoratorMeta
import time
class Wait(metaclass=PolyArgDecoratorMeta):
 def __init__(i, func, delay = 2):
     i._func = func
     i._delay = delay

 def __call__(i, *args, **kwargs):
     time.sleep(i._delay)
     r = i._func(*args, **kwargs)
     return r

git pull error "The requested URL returned error: 503 while accessing"

Every one please avoid modifying post buffer and advising it to others. It may help in some cases but it breaks others. If you have modified your post buffer for pushing your large project. Undo it using following command. git config --global --unset http.postBuffer git config --local --unset http.postBuffer

I modified my post buffer to fix one of the issues I had with git but it was the reason for my future problems with git.

Failed to resolve: com.google.firebase:firebase-core:16.0.1

Go to

Settings -> Android SDK -> SDK Tools ->

and make sure you install Google Play Services

Delete all rows in table

I would suggest using TRUNCATE TABLE, it's quicker and uses less resources than DELETE FROM xxx

Here's the related MSDN article

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

You can update the angular with command 'ng update --all'. It will take time but make sure your all components are up to date.

Error: Configuration with name 'default' not found in Android Studio

For me, (as per some comments I have seen), the issue was that gradle could not find the build.gradle for the imported library. This configuration is straight-forward but the error message is a bit cryptic. For instance I was using the android-map-utils project and had to include it in my settings.gradle by appending these 2 lines like this.

include ':android-map-utils'
project(':android-map-utils').projectDir = new File(settingsDir, '..\\..\\modules\\android-maps-utils-master\\library')

Path of the library is relative to the my project's settings.gradle file. Then, I simply referenced it in my dependencies of my app's build.gradle file like this

...

    dependencies {
    ....
        compile project(':android-map-utils')
    ....

    }

I recommend importing one module at a time, compiling and checking it.

Use RSA private key to generate public key?

here in this code first we are creating RSA key which is private but it has pair of its public key as well so to get your actual public key we simply do this

openssl rsa -in mykey.pem -pubout > mykey.pub

hope you get it for more info check this

Has anyone gotten HTML emails working with Twitter Bootstrap?

I spent some time recently looking into building html email templates, the best solution I found was to use this http://htmlemailboilerplate.com/. I have since built 3 quite complex templates and they have worked well in the various email clients.

How to truncate a foreign key constrained table?

You cannot TRUNCATE a table that has FK constraints applied on it (TRUNCATE is not the same as DELETE).

To work around this, use either of these solutions. Both present risks of damaging the data integrity.

Option 1:

  1. Remove constraints
  2. Perform TRUNCATE
  3. Delete manually the rows that now have references to nowhere
  4. Create constraints

Option 2: suggested by user447951 in their answer

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

type checking in javascript

I know you're interested in Integer numbers so I won't re answer that but if you ever wanted to check for Floating Point numbers you could do this.

function isFloat( x )
{
    return ( typeof x === "number" && Math.abs( x % 1 ) > 0);
}

Note: This MAY treat numbers ending in .0 (or any logically equivalent number of 0's) as an INTEGER. It actually needs a floating point precision error to occur to detect the floating point values in that case.

Ex.

alert(isFloat(5.2));   //returns true
alert(isFloat(5));     //returns false
alert(isFloat(5.0));   //return could be either true or false

Convert columns to string in Pandas

pandas >= 1.0: It's time to stop using astype(str)!

Prior to pandas 1.0 (well, 0.25 actually) this was the defacto way of declaring a Series/column as as string:

# pandas <= 0.25
# Note to pedants: specifying the type is unnecessary since pandas will 
# automagically infer the type as object
s = pd.Series(['a', 'b', 'c'], dtype=str)
s.dtype
# dtype('O')

From pandas 1.0 onwards, consider using "string" type instead.

# pandas >= 1.0
s = pd.Series(['a', 'b', 'c'], dtype="string")
s.dtype
# StringDtype

Here's why, as quoted by the docs:

  1. You can accidentally store a mixture of strings and non-strings in an object dtype array. It’s better to have a dedicated dtype.

  2. object dtype breaks dtype-specific operations like DataFrame.select_dtypes(). There isn’t a clear way to select just text while excluding non-text but still object-dtype columns.

  3. When reading code, the contents of an object dtype array is less clear than 'string'.

See also the section on Behavioral Differences between "string" and object.

Extension types (introduced in 0.24 and formalized in 1.0) are closer to pandas than numpy, which is good because numpy types are not powerful enough. For example NumPy does not have any way of representing missing data in integer data (since type(NaN) == float). But pandas can using Nullable Integer columns.


Why should I stop using it?

Accidentally mixing dtypes
The first reason, as outlined in the docs is that you can accidentally store non-text data in object columns.

# pandas <= 0.25
pd.Series(['a', 'b', 1.23])   # whoops, this should have been "1.23"

0       a
1       b
2    1.23
dtype: object

pd.Series(['a', 'b', 1.23]).tolist()
# ['a', 'b', 1.23]   # oops, pandas was storing this as float all the time.
# pandas >= 1.0
pd.Series(['a', 'b', 1.23], dtype="string")

0       a
1       b
2    1.23
dtype: string

pd.Series(['a', 'b', 1.23], dtype="string").tolist()
# ['a', 'b', '1.23']   # it's a string and we just averted some potentially nasty bugs.

Challenging to differentiate strings and other python objects
Another obvious example example is that it's harder to distinguish between "strings" and "objects". Objects are essentially the blanket type for any type that does not support vectorizable operations.

Consider,

# Setup
df = pd.DataFrame({'A': ['a', 'b', 'c'], 'B': [{}, [1, 2, 3], 123]})
df
 
   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

Upto pandas 0.25, there was virtually no way to distinguish that "A" and "B" do not have the same type of data.

# pandas <= 0.25  
df.dtypes

A    object
B    object
dtype: object

df.select_dtypes(object)

   A          B
0  a         {}
1  b  [1, 2, 3]
2  c        123

From pandas 1.0, this becomes a lot simpler:

# pandas >= 1.0
# Convenience function I call to help illustrate my point.
df = df.convert_dtypes()
df.dtypes

A    string
B    object
dtype: object

df.select_dtypes("string")

   A
0  a
1  b
2  c

Readability
This is self-explanatory ;-)


OK, so should I stop using it right now?

...No. As of writing this answer (version 1.1), there are no performance benefits but the docs expect future enhancements to significantly improve performance and reduce memory usage for "string" columns as opposed to objects. With that said, however, it's never too early to form good habits!

git - pulling from specific branch

It's often clearer to separate the two actions git pull does. The first thing it does is update the local tracking branc that corresponds to the remote branch. This can be done with git fetch. The second is that it then merges in changes, which can of course be done with git merge, though other options such as git rebase are occasionally useful.

Can't accept license agreement Android SDK Platform 24

If you want to avoid creating the licence folder manually, and in case your sdk is not in the "Users/User" you can go to android studio => Configure => SDK Manager and install any component, i installed the google usb driver from the sdk tools, it automatically generated the license in the correct location.

PHP reindex array?

array_values does the job :

$myArray  = array_values($myArray);

Also some other php function do not preserve the keys, i.e. reset the index.

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

Creating Threads in python

Did you override the run() method? If you overrided __init__, did you make sure to call the base threading.Thread.__init__()?

After starting the two threads, does the main thread continue to do work indefinitely/block/join on the child threads so that main thread execution does not end before the child threads complete their tasks?

And finally, are you getting any unhandled exceptions?

Non-static variable cannot be referenced from a static context

The static keyword modifies the lifecycle of a method or variable within a class. A static method or variable is created at the time a class is loaded. A method or variable that is not declared as static is created only when the class is instantiated as an object for example by using the new operator.

The lifecycle of a class, in broad terms, is:

  1. the source code for the class is written creating a template or pattern or stamp which can then be used to
  2. create an object with the new operator using the class to make an instance of the class as an actual object and then when done with the object
  3. destroy the object reclaiming the resources it is holding such as memory during garbage collection.

In order to have an initial entry point for an application, Java has adopted the convention that the Java program must have a class that contains a method with an agreed upon or special name. This special method is called main(). Since the method must exist whether the class containing the main method has been instantiated or not, the main() method must be declared with the static modifier so that as soon as the class is loaded, the main() method is available.

The result is that when you start your Java application by a command line such as java helloworld a series of actions happen. First of all a Java Virtual Machine is started up and initialized. Next the helloworld.class file containing the compiled Java code is loaded into the Java Virtual Machine. Then the Java Virtual Machine looks for a method in the helloworld class that is called main(String [] args). this method must be static so that it will exist even though the class has not actually been instantiated as an object. The Java Virtual Machine does not create an instance of the class by creating an object from the class. It just loads the class and starts execution at the main() method.

So you need to create an instance of your class as an object and then you can access the methods and variables of the class that have not been declared with the static modifier. Once your Java program has started with the main() function you can then use any variables or methods that have the modifier of static since they exist as part of the class being loaded.

However, those variables and methods of the class which are outside of the main() method which do not have the static modifier can not be used until an instance of the class has been created as an object within the main() method. After creating the object you can then use the variables and methods of the object. An attempt to use the variables and methods of the class which do not have the static modifier without going through an object of the class is caught by the Java compiler at compile time and flagged as an error.

import java.io.*;

class HelloWorld {
    int myInt;      // this is a class variable that is unique to each object
    static int myInt2;  // this is a class variable shared by all objects of this class

    static void main (String [] args) {
        // this is the main entry point for this Java application
        System.out.println ("Hello, World\n");
        myInt2 = 14;    // able to access the static int
        HelloWorld myWorld = new HelloWorld();
        myWorld.myInt = 32;   // able to access non-static through an object
    }
}

How to get a cookie from an AJAX response?

xhr.getResponseHeader('Set-Cookie');

It won't work for me.

I use this

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

success: function(output, status, xhr) {
    alert(getCookie("MyCookie"));
},

http://www.w3schools.com/js/js_cookies.asp

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Adding java.util.list will resolve your problem because List interface which you are trying to use is part of java.util.list package.

how to convert string to numerical values in mongodb

You can easily convert the string data type to numerical data type.

Don't forget to change collectionName & FieldName. for ex : CollectionNmae : Users & FieldName : Contactno.

Try this query..

db.collectionName.find().forEach( function (x) {
x.FieldName = parseInt(x.FieldName);
db.collectionName.save(x);
});

"A lambda expression with a statement body cannot be converted to an expression tree"

For your specific case, the body is for creating a variable, and switching to IEnumerable will force all the operations to be processed on client-side, I propose the following solution.

Obj[] myArray = objects
.Select(o => new
{
    SomeLocalVar = o.someVar, // You can even use any LINQ statement here
    Info = o,
}).Select(o => new Obj()
{
    Var1 = o.SomeLocalVar,
    Var2 = o.Info.var2,
    Var3 = o.SomeLocalVar.SubValue1,
    Var4 = o.SomeLocalVar.SubValue2,
}).ToArray();

Edit: Rename for C# Coding Convention

grunt: command not found when running from terminal

For windows

npm install -g grunt-cli

npm install load-grunt-tasks

Then run

grunt

DateTimePicker: pick both date and time

You can get it to display time. From that you will probably have to have two controls (one date, one time) the accomplish what you want.

Why I can't change directories using "cd"?

I have a simple bash script called p to manage directory changing on
github.com/godzilla/bash-stuff
just put the script in your local bin directory (/usr/local/bin)
and put

alias p='. p'

in your .bashrc

How to automatically generate getters and setters in Android Studio

Right click on Editor then Select Source -> Generate Getters and Setters or press Alt + Shift + S enter image description here

CodeIgniter -> Get current URL relative to base url

In CI v3, you can try:

function partial_uri($start = 0) {
    return join('/',array_slice(get_instance()->uri->segment_array(), $start));
}

This will drop the number of URL segments specified by the $start argument. If your URL is http://localhost/dropbox/derrek/shopredux/ahahaha/hihihi, then:

partial_uri(3);  # returns "ahahaha/hihihi"

jQuery: print_r() display equivalent?

You could use very easily reflection to list all properties, methods and values.

For Gecko based browsers you can use the .toSource() method:

var data = new Object();
data["firstname"] = "John";
data["lastname"] = "Smith";
data["age"] = 21;

alert(data.toSource()); //Will return "({firstname:"John", lastname:"Smith", age:21})"

But since you use Firebug, why not just use console.log?

How to get a parent element to appear above child

You would need to use position:relative or position:absolute on both the parent and child to use z-index.

How to perform Unwind segue programmatically?

  1. Create a manual segue (ctrl-drag from File’s Owner to Exit),
  2. Choose it in the Left Controller Menu below green EXIT button.

Choose it in the Left Controller Menu below green EXIT button

Insert Name of Segue to unwind.

Then,- (void)performSegueWithIdentifier:(NSString *)identifier sender:(id)sender. with your segue identify.

Vertical rulers in Visual Studio Code

With Visual Studio Code 1.27.2:

  1. When I go to File > Preference > Settings, I get the following tab

    Screenshot

  2. I type rulers in Search settings and I get the following list of settings

    screenshot

  3. Clicking on the first Edit in settings.json, I can edit the user settings

    screenshot

  4. Clicking on the pen icon that appears to the left of the setting in Default user settings I can copy it on the user settings and edit it

With Visual Studio Code 1.38.1, the screenshot shown on the third point changes to the following one.

enter image description here

The panel for selecting the default user setting values isn't shown anymore.

update query with join on two tables

update addresses set cid=id where id in (select id from customers)

How to correctly iterate through getElementsByClassName

 <!--something like this--> 
<html>
<body>



<!-- i've used for loop...this pointer takes current element to apply a 
 particular change on it ...other elements take change by else condition 
-->  


<div class="classname" onclick="myFunction(this);">first</div>  
<div class="classname" onclick="myFunction(this);">second</div>


<script>
function myFunction(p) {
 var x = document.getElementsByClassName("classname");
 var i;
 for (i = 0; i < x.length; i++) {
    if(x[i] == p)
    {
x[i].style.background="blue";
    }
    else{
x[i].style.background="red";
    }
}
}


</script>
<!--this script will only work for a class with onclick event but if u want 
to use all class of same name then u can use querySelectorAll() ...-->




var variable_name=document.querySelectorAll('.classname');
for(var i=0;i<variable_name.length;i++){
variable_name[i].(--your option--);
}



 <!--if u like to divide it on some logic apply it inside this for loop 
 using your nodelist-->

</body>
</html>

How to create a DOM node as an object?

I'd put it in the DOM first. I'm not sure why my first example failed. That's really weird.

var e = $("<ul><li><div class='bar'>bla</div></li></ul>");
$('li', e).attr('id','a1234');  // set the attribute 
$('body').append(e); // put it into the DOM     

Putting e (the returns elements) gives jQuery context under which to apply the CSS selector. This keeps it from applying the ID to other elements in the DOM tree.

The issue appears to be that you aren't using the UL. If you put a naked li in the DOM tree, you're going to have issues. I thought it could handle/workaround this, but it can't.

You may not be putting naked LI's in your DOM tree for your "real" implementation, but the UL's are necessary for this to work. Sigh.

Example: http://jsbin.com/iceqo

By the way, you may also be interested in microtemplating.

How to generate an openSSL key using a passphrase from the command line?

If you don't use a passphrase, then the private key is not encrypted with any symmetric cipher - it is output completely unprotected.

You can generate a keypair, supplying the password on the command-line using an invocation like (in this case, the password is foobar):

openssl genrsa -aes128 -passout pass:foobar 3072

However, note that this passphrase could be grabbed by any other process running on the machine at the time, since command-line arguments are generally visible to all processes.

A better alternative is to write the passphrase into a temporary file that is protected with file permissions, and specify that:

openssl genrsa -aes128 -passout file:passphrase.txt 3072

Or supply the passphrase on standard input:

openssl genrsa -aes128 -passout stdin 3072

You can also used a named pipe with the file: option, or a file descriptor.


To then obtain the matching public key, you need to use openssl rsa, supplying the same passphrase with the -passin parameter as was used to encrypt the private key:

openssl rsa -passin file:passphrase.txt -pubout

(This expects the encrypted private key on standard input - you can instead read it from a file using -in <file>).


Example of creating a 3072-bit private and public key pair in files, with the private key pair encrypted with password foobar:

openssl genrsa -aes128 -passout pass:foobar -out privkey.pem 3072
openssl rsa -in privkey.pem -passin pass:foobar -pubout -out privkey.pub

How to get the clicked link's href with jquery?

Suppose we have three anchor tags like ,

<a  href="ID=1" class="testClick">Test1.</a>
<br />
<a  href="ID=2" class="testClick">Test2.</a>
<br />
<a  href="ID=3" class="testClick">Test3.</a>

now in script

$(".testClick").click(function () {
        var anchorValue= $(this).attr("href");
        alert(anchorValue);
});

use this keyword instead of className (testClick)

Create a list with initial capacity in Python

For some applications, a dictionary may be what you are looking for. For example, in the find_totient method, I found it more convenient to use a dictionary since I didn't have a zero index.

def totient(n):
    totient = 0

    if n == 1:
        totient = 1
    else:
        for i in range(1, n):
            if math.gcd(i, n) == 1:
                totient += 1
    return totient

def find_totients(max):
    totients = dict()
    for i in range(1,max+1):
        totients[i] = totient(i)

    print('Totients:')
    for i in range(1,max+1):
        print(i,totients[i])

This problem could also be solved with a preallocated list:

def find_totients(max):
    totients = None*(max+1)
    for i in range(1,max+1):
        totients[i] = totient(i)

    print('Totients:')
    for i in range(1,max+1):
        print(i,totients[i])

I feel that this is not as elegant and prone to bugs because I'm storing None which could throw an exception if I accidentally use them wrong, and because I need to think about edge cases that the map lets me avoid.

It's true the dictionary won't be as efficient, but as others have commented, small differences in speed are not always worth significant maintenance hazards.

how to find seconds since 1970 in java

The answer you want, "1317427200", is achieved if your reference months are January and October. If so, the dates you are looking for are 1970-JAN-01 and 2011-OCT-01, correct?

Then the problem are these numbers you are using for your months.

See, if you check the Calendar API documentation or even the constants provided in there ("Calendar.JANUARY", "Calendar.FEBRUARY" and so on), you'll discover that months start at 0 (being January).

So checking your code, you are passing february and november, which would result in "1317510000".

Best regards.

How to set width of a div in percent in JavaScript?

I always do it like this:

$("#id").css("width", "50%");

C# Get a control's position on a form

This is what i've done works like a charm

            private static int _x=0, _y=0;
        private static Point _point;
        public static Point LocationInForm(Control c)
        {
            if (c.Parent == null) 
            {
                _x += c.Location.X;
                _y += c.Location.Y;
                _point = new Point(_x, _y);
                _x = 0; _y = 0;
                return _point;
            }
            else if ((c.Parent is System.Windows.Forms.Form))
            {
                _point = new Point(_x, _y);
                _x = 0; _y = 0;
                return _point;
            }
            else 
            {
                _x += c.Location.X;
                _y += c.Location.Y;
                LocationInForm(c.Parent);
            }
            return new Point(1,1);
        }

How to get first N elements of a list in C#?

var firstFiveItems = myList.Take(5);

Or to slice:

var secondFiveItems = myList.Skip(5).Take(5);

And of course often it's convenient to get the first five items according to some kind of order:

var firstFiveArrivals = myList.OrderBy(i => i.ArrivalTime).Take(5);

What does file:///android_asset/www/index.html mean?

file:/// is a URI (Uniform Resource Identifier) that simply distinguishes from the standard URI that we all know of too well - http://.

It does imply an absolute path name pointing to the root directory in any environment, but in the context of Android, it's a convention to tell the Android run-time to say "Here, the directory www has a file called index.html located in the assets folder in the root of the project".

That is how assets are loaded at runtime, for example, a WebView widget would know exactly where to load the embedded resource file by specifying the file:/// URI.

Consider the code example:

WebView webViewer = (WebView) findViewById(R.id.webViewer);
webView.loadUrl("file:///android_asset/www/index.html");

A very easy mistake to make here is this, some would infer it to as file:///android_assets, notice the plural of assets in the URI and wonder why the embedded resource is not working!

How to getElementByClass instead of GetElementById with JavaScript?

Append IDs at the class declaration

.aclass, #hashone, #hashtwo{ ...codes... }
document.getElementById( "hashone" ).style.visibility = "hidden";

How to get file path in iPhone app

Since it is your files in your app bundle, I think you can use pathForResource:ofType: to get the full pathname of your file.

Here is an example:

NSString* filePath = [[NSBundle mainBundle] pathForResource:@"your_file_name" 
                                            ofType:@"the_file_extension"];

How to extract the nth word and count word occurrences in a MySQL string?

No, there isn't a syntax for extracting text using regular expressions. You have to use the ordinary string manipulation functions.

Alternatively select the entire value from the database (or the first n characters if you are worried about too much data transfer) and then use a regular expression on the client.

get data from mysql database to use in javascript

Probably the easiest way to do it is to have a php file return JSON. So let's say you have a file query.php,

$result = mysql_query("SELECT field_name, field_value
                       FROM the_table");
$to_encode = array();
while($row = mysql_fetch_assoc($result)) {
  $to_encode[] = $row;
}
echo json_encode($to_encode);

If you're constrained to using document.write (as you note in the comments below) then give your fields an id attribute like so: <input type="text" id="field1" />. You can reference that field with this jQuery: $("#field1").val().

Here's a complete example with the HTML. If we're assuming your fields are called field1 and field2, then

<!DOCTYPE html>
<html>
  <head>
    <title>That's about it</title>
  </head>
  <body>
    <form>
      <input type="text" id="field1" />
      <input type="text" id="field2" />
    </form>
  </body>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
  <script>
    $.getJSON('data.php', function(data) {
      $.each(data, function(fieldName, fieldValue) {
        $("#" + fieldName).val(fieldValue);
      });
    });
  </script>
</html>

That's insertion after the HTML has been constructed, which might be easiest. If you mean to populate data while you're dynamically constructing the HTML, then you'd still want the PHP file to return JSON, you would just add it directly into the value attribute.

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

GetFiles with multiple extensions

You can't do that, because GetFiles only accepts a single search pattern. Instead, you can call GetFiles with no pattern, and filter the results in code:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.GetFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

If you're working with .NET 4, you can use the EnumerateFiles method to avoid loading all FileInfo objects in memory at once:

string[] extensions = new[] { ".jpg", ".tiff", ".bmp" };

FileInfo[] files =
    dinfo.EnumerateFiles()
         .Where(f => extensions.Contains(f.Extension.ToLower()))
         .ToArray();

How to check if array element is null to avoid NullPointerException in Java

It does not.

See below. The program you posted runs as supposed.

C:\oreyes\samples\java\arrays>type ArrayNullTest.java
public class ArrayNullTest {
    public static void main( String [] args ) {
        Object[][] someArray = new Object[5][];
            for (int i=0; i<=someArray.length-1; i++) {
                 if (someArray[i]!=null ) {
                     System.out.println("It wasn't null");
                 } else {
                     System.out.printf("Element at %d was null \n", i );
                 }
             }
     }
}


C:\oreyes\samples\java\arrays>javac ArrayNullTest.java

C:\oreyes\samples\java\arrays>java ArrayNullTest
Element at 0 was null
Element at 1 was null
Element at 2 was null
Element at 3 was null
Element at 4 was null

C:\oreyes\samples\java\arrays>

Reversing an Array in Java

Or you could loop through it backeards

int[] firstArray = new int[]{1,2,3,4};
int[] reversedArray = new int[firstArray.length];
int j = 0;
for (int i = firstArray.length -1; i > 0; i--){
    reversedArray[j++] = firstArray[i];
}

(note: I have not compiled this but hopefully it is correct)

What is the difference between old style and new style classes in Python?

From New-style and classic classes:

Up to Python 2.1, old-style classes were the only flavour available to the user.

The concept of (old-style) class is unrelated to the concept of type: if x is an instance of an old-style class, then x.__class__ designates the class of x, but type(x) is always <type 'instance'>.

This reflects the fact that all old-style instances, independently of their class, are implemented with a single built-in type, called instance.

New-style classes were introduced in Python 2.2 to unify the concepts of class and type. A new-style class is simply a user-defined type, no more, no less.

If x is an instance of a new-style class, then type(x) is typically the same as x.__class__ (although this is not guaranteed – a new-style class instance is permitted to override the value returned for x.__class__).

The major motivation for introducing new-style classes is to provide a unified object model with a full meta-model.

It also has a number of immediate benefits, like the ability to subclass most built-in types, or the introduction of "descriptors", which enable computed properties.

For compatibility reasons, classes are still old-style by default.

New-style classes are created by specifying another new-style class (i.e. a type) as a parent class, or the "top-level type" object if no other parent is needed.

The behaviour of new-style classes differs from that of old-style classes in a number of important details in addition to what type returns.

Some of these changes are fundamental to the new object model, like the way special methods are invoked. Others are "fixes" that could not be implemented before for compatibility concerns, like the method resolution order in case of multiple inheritance.

Python 3 only has new-style classes.

No matter if you subclass from object or not, classes are new-style in Python 3.

How can I use a C++ library from node.js?

Here is an interesting article on Getting your C++ to the Web with Node.js

three general ways of integrating C++ code with a Node.js application - although there are lots of variations within each category:

  1. Automation - call your C++ as a standalone app in a child process.
  2. Shared library - pack your C++ routines in a shared library (dll) and call those routines from Node.js directly.
  3. Node.js Addon - compile your C++ code as a native Node.js module/addon.

How to fix java.net.SocketException: Broken pipe?

The above answers illustrate the reason for this java.net.SocketException: Broken pipe: the other end closed the connection. I would like to share experience what happened when I encountered it:

  1. in a client's request, the Content-Type header is mistakenly set larger than request body actually is (in fact there was no body at all)
  2. the bottom service in tomcat socket was waiting for that sized body data (http is on TCP which ensures delivery by encapsulating and ...)
  3. when 60 seconds expired, tomcat throws time out exception: Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception java.net.SocketTimeoutException: null
  4. client receives a response with status code 500 because of the timeout exception.
  5. client close connection (because it receives response).
  6. tomcat throws java.net.SocketException: Broken pipe because client closed it.

Sometimes, tomcat does not throw broken pip exception, because timeout exception close the connection, why such a difference is confusing me too.

getResourceAsStream() vs FileInputStream

classname.getResourceAsStream() loads a file via the classloader of classname. If the class came from a jar file, that is where the resource will be loaded from.

FileInputStream is used to read a file from the filesystem.

Python: Pandas Dataframe how to multiply entire column with a scalar

A little late to the game, but for future searchers, this also should work:

df.quantity = df.quantity  * -1

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

How to get the list of all installed color schemes in Vim?

Looking at my system's menu.vim (look for 'Color Scheme submenu') and @chappar's answer, I came up with the following function:

" Returns the list of available color schemes
function! GetColorSchemes()
   return uniq(sort(map(
   \  globpath(&runtimepath, "colors/*.vim", 0, 1),  
   \  'fnamemodify(v:val, ":t:r")'
   \)))
endfunction

It does the following:

  1. Gets the list of available color scheme scripts under all runtime paths (globpath, runtimepath)
  2. Maps the script paths to their base names (strips parent dirs and extension) (map, fnamemodify)
  3. Sorts and removes duplicates (uniq, sort)

Then to use the function I do something like this:

let s:schemes = GetColorSchemes()
if index(s:schemes, 'solarized') >= 0
   colorscheme solarized
elseif index(s:schemes, 'darkblue') >= 0
   colorscheme darkblue
endif

Which means I prefer the 'solarized' and then the 'darkblue' schemes; if none of them is available, do nothing.

Add item to array in VBScript

Not an answer Or Why 'tricky' is bad:

>> a = Array(1)
>> a = Split(Join(a, "||") & "||2", "||")
>> WScript.Echo a(0) + a(1)
>>
12

Python subprocess/Popen with a modified environment

To temporarily set an environment variable without having to copy the os.envrion object etc, I do this:

process = subprocess.Popen(['env', 'RSYNC_PASSWORD=foobar', 'rsync', \
'rsync://[email protected]::'], stdout=subprocess.PIPE)

Does Python support short-circuiting?

Yes. Try the following in your python interpreter:

and

>>>False and 3/0
False
>>>True and 3/0
ZeroDivisionError: integer division or modulo by zero

or

>>>True or 3/0
True
>>>False or 3/0
ZeroDivisionError: integer division or modulo by zero

Url.Action parameters?

Here is another simple way to do it

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID'>Print</a>

Where is @Model.ID is a parameter

And here there is a second example.

<a class="nav-link"
   href='@Url.Action("Print1", "DeviceCertificates", new { Area = "Diagnostics"})\@Model.ID?param2=ViewBag.P2&param3=ViewBag.P3'>Print</a>

Error in MySQL when setting default value for DATE or DATETIME

set global sql_mode = 'STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION';

What is the proper declaration of main in C++?

The main function must be declared as a non-member function in the global namespace. This means that it cannot be a static or non-static member function of a class, nor can it be placed in a namespace (even the unnamed namespace).

The name main is not reserved in C++ except as a function in the global namespace. You are free to declare other entities named main, including among other things, classes, variables, enumerations, member functions, and non-member functions not in the global namespace.

You can declare a function named main as a member function or in a namespace, but such a function would not be the main function that designates where the program starts.

The main function cannot be declared as static or inline. It also cannot be overloaded; there can be only one function named main in the global namespace.

The main function cannot be used in your program: you are not allowed to call the main function from anywhere in your code, nor are you allowed to take its address.

The return type of main must be int. No other return type is allowed (this rule is in bold because it is very common to see incorrect programs that declare main with a return type of void; this is probably the most frequently violated rule concerning the main function).

There are two declarations of main that must be allowed:

int main()               // (1)
int main(int, char*[])   // (2)

In (1), there are no parameters.

In (2), there are two parameters and they are conventionally named argc and argv, respectively. argv is a pointer to an array of C strings representing the arguments to the program. argc is the number of arguments in the argv array.

Usually, argv[0] contains the name of the program, but this is not always the case. argv[argc] is guaranteed to be a null pointer.

Note that since an array type argument (like char*[]) is really just a pointer type argument in disguise, the following two are both valid ways to write (2) and they both mean exactly the same thing:

int main(int argc, char* argv[])
int main(int argc, char** argv)

Some implementations may allow other types and numbers of parameters; you'd have to check the documentation of your implementation to see what it supports.

main() is expected to return zero to indicate success and non-zero to indicate failure. You are not required to explicitly write a return statement in main(): if you let main() return without an explicit return statement, it's the same as if you had written return 0;. The following two main() functions have the same behavior:

int main() { }
int main() { return 0; }

There are two macros, EXIT_SUCCESS and EXIT_FAILURE, defined in <cstdlib> that can also be returned from main() to indicate success and failure, respectively.

The value returned by main() is passed to the exit() function, which terminates the program.

Note that all of this applies only when compiling for a hosted environment (informally, an environment where you have a full standard library and there's an OS running your program). It is also possible to compile a C++ program for a freestanding environment (for example, some types of embedded systems), in which case startup and termination are wholly implementation-defined and a main() function may not even be required. If you're writing C++ for a modern desktop OS, though, you're compiling for a hosted environment.

Override element.style using CSS

Although it's often frowned upon, you can technically use:

display: inline !important;

It generally isn't good practice but in some cases might be necessary. What you should do is edit your code so that you aren't applying a style to the <li> elements in the first place.

Hiding a form and showing another when a button is clicked in a Windows Forms application

Anything after Application.Run( ) will only be executed when the main form closes.

What you could do is handle the VisibleChanged event as follows:

static Form1 form1;
static Form2 form2;

static void Main()
{

    Application.EnableVisualStyles();
    Application.SetCompatibleTextRenderingDefault(false);
    form2 = new Form2();
    form1 = new Form1();
    form2.Hide();
    form1.VisibleChanged += OnForm1Changed;
    Application.Run(form1);

}

static void OnForm1Changed( object sender, EventArgs args )
{
    if ( !form1.Visible )
    {
        form2.Show( );
    }
}

Jquery: How to check if the element has certain css class/style

Question is asking for two different things:

  1. An element has certain class
  2. An element has certain style.

Second question has been already answered. For the first one, I would do it this way:

if($("#someElement").is(".test")){
    // Has class test assigned, eventually combined with other classes
}
else{
    // Does not have it
}

Generating a random & unique 8 character string using MySQL

Here's another method for generating a random string:

SELECT SUBSTRING(MD5(RAND()) FROM 1 FOR 8) AS myrandomstring

What is the largest Safe UDP Packet Size on the Internet

IPv4 minimum reassembly buffer size is 576, IPv6 has it at 1500. Subtract header sizes from here. See UNIX Network Programming by W. Richard Stevens :)

How do I align a number like this in C?

Looking at the edited question, you need to find the number of digits in the largest number to be presented, and then generate the printf() format using sprintf(), or using %*d with the number of digits being passed as an int for the * and then the value. Once you've got the biggest number (and you have to determine that in advance), you can determine the number of digits with an 'integer logarithm' algorithm (how many times can you divide by 10 before you get to zero), or by using snprintf() with the buffer length of zero, the format %d and null for the string; the return value tells you how many characters would have been formatted.

If you don't know and cannot determine the maximum number ahead of its appearance, you are snookered - there is nothing you can do.

Could not load file or assembly '' or one of its dependencies

  • Does the version number match?
  • It's weird to see you're trying to load a .lib file instead of a dll. Perhaps you wanted to load a dll instead?
  • To debug this kind of problems, try Fusion Logging
  • You say you're using only one library, but that library might have some dependencies you're not aware of. This SO question deals with listing the dependencies of a managed .NET assembly.

Replace string within file contents

with open("Stud.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line.replace('A', 'Orange'))

Getting msbuild.exe without installing Visual Studio

The latest (as of Jan 2019) stand-alone MSBuild installers can be found here: https://www.visualstudio.com/downloads/

Scroll down to "Tools for Visual Studio 2019" and choose "Build Tools for Visual Studio 2019" (despite the name, it's for users who don't want the full IDE)

See this question for additional information.

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

Accessing the last entry in a Map

When using numbers as the key, I suppose you could also try this:

        Map<Long, String> map = new HashMap<>();
        map.put(4L, "The First");
        map.put(6L, "The Second");
        map.put(11L, "The Last");

        long lastKey = 0;
        //you entered Map<Long, String> entry
        for (Map.Entry<Long, String> entry : map.entrySet()) {
            lastKey = entry.getKey();
        }
        System.out.println(lastKey); // 11

How do you 'redo' changes after 'undo' with Emacs?

By default, redo in Emacs requires pressing C-g, then undo.

However it's possible use Emacs built-in undo to implement a redo command too.

The package undo-fu, uses Emacs built-in undo functionality to expose both undo and redo.

Wrapping text inside input type="text" element HTML/CSS

That is the textarea's job - for multiline text input. The input won't do it; it wasn't designed to do it.

So use a textarea. Besides their visual differences, they are accessed via JavaScript the same way (use value property).

You can prevent newlines being entered via the input event and simply using a replace(/\n/g, '').

Multiple separate IF conditions in SQL Server

IF you are checking one variable against multiple condition then you would use something like this Here the block of code where the condition is true will be executed and other blocks will be ignored.

IF(@Var1 Condition1)
     BEGIN
      /*Your Code Goes here*/
     END

ELSE IF(@Var1 Condition2)
      BEGIN
        /*Your Code Goes here*/ 
      END 

    ELSE      --<--- Default Task if none of the above is true
     BEGIN
       /*Your Code Goes here*/
     END

If you are checking conditions against multiple variables then you would have to go for multiple IF Statements, Each block of code will be executed independently from other blocks.

IF(@Var1 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END


IF(@Var2 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END


IF(@Var3 Condition1)
 BEGIN
   /*Your Code Goes here*/
 END

After every IF statement if there are more than one statement being executed you MUST put them in BEGIN..END Block. Anyway it is always best practice to use BEGIN..END blocks

Update

Found something in your code some BEGIN END you are missing

ELSE IF(@ID IS NOT NULL AND @ID in (SELECT ID FROM Places))   -- Outer Most Block ELSE IF
BEGIN   
     SELECT @MyName = Name ...  
    ...Some stuff....                       
    IF(SOMETHNG_1)         -- IF
                 --BEGIN
        BEGIN TRY               
            UPDATE ....                                                                 
        END TRY

        BEGIN CATCH
            SELECT ERROR_MESSAGE() AS 'Message' 
            RETURN -1
        END CATCH
                -- END
    ELSE IF(SOMETHNG_2)    -- ELSE IF
                 -- BEGIN
        BEGIN TRY
            UPDATE ...                                                      
        END TRY
        BEGIN CATCH
            SELECT ERROR_MESSAGE() AS 'Message' 
            RETURN -1
        END CATCH   
               -- END
    ELSE                  -- ELSE
        BEGIN
            BEGIN TRY
                UPDATE ...                                                              
            END TRY
            BEGIN CATCH
                SELECT ERROR_MESSAGE() AS 'Message' 
                RETURN -1
            END CATCH   
         END             
      --The above works I then insert this below and these if statement become nested----
          IF(@A!= @SA)
            BEGIN
             exec Store procedure 
                    @FIELD = 15,
                    ... more params...
            END                 
        IF(@S!= @SS)
          BEGIN
             exec Store procedure 
                    @FIELD = 10,
                    ... more params...

How do I make Visual Studio pause after executing a console application in debug mode?

Just use a logging library, like log4net, and have it log to a file appender.

Creating a timer in python

import time
def timer(n):
    while n!=0:
        n=n-1
        time.sleep(n)#time.sleep(seconds) #here you can mention seconds according to your requirement.
        print "00 : ",n
timer(30) #here you can change n according to your requirement.

Redis strings vs Redis hashes to represent JSON: efficiency?

It depends on how you access the data:

Go for Option 1:

  • If you use most of the fields on most of your accesses.
  • If there is variance on possible keys

Go for Option 2:

  • If you use just single fields on most of your accesses.
  • If you always know which fields are available

P.S.: As a rule of the thumb, go for the option which requires fewer queries on most of your use cases.

MySQL Install: ERROR: Failed to build gem native extension

I had a similar experience, so here are the things that I tried

Firstly, I tried to install mysql's required packages by running the command below in my terminal

sudo apt-get install build-essential libmysqlclient-dev

Secondly, I tried updating rubygems on my system by running the command below in my terminal

sudo gem update --system

But I was still experiencing the same issue. After much research I realized that I was using an almost out-of-date version of the mysql gem. I simply needed to use the mysql2 gem (mysql2 gem)and not the mysql gem, so I fixed it by running the command below in my terminal

gem install mysql2

This worked fine for me. Before running the last command, ensure that you've ran the first and second commands to be sure that everything is fine on your system.

That's all.

I hope this helps

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

Where is Python's sys.path initialized from?

"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"

-- http://docs.python.org/library/sys.html#sys.path

Get names of all files from a folder with Ruby

In Ruby 2.5 you can now use Dir.children. It gets filenames as an array except for "." and ".."

Example:

Dir.children("testdir")   #=> ["config.h", "main.rb"]

http://ruby-doc.org/core-2.5.0/Dir.html#method-c-children

Get full path of a file with FileUpload Control

Try

Server.MapPath(FileUpload1.FileName);

Edit: This answer describes how to get the path to a file on the server. It does not describe how to get the path to a file on the client, which is what the question asked. The answer to that question is "you can't", because modern browser will not tell you the path on the client, for security reasons.

why are there two different kinds of for loops in java?

There is an excellent summary of this feature in the article The For-Each Loop. It shows by example how using the for-each style can produce clearer code that is easier to read and write.

Remove Blank option from Select Option with AngularJS

Change your code like this. You forget about the value inside option. Before you assign the ng-model. It must have a value. Only then it doesn't get the undefined value.

<div ng-app="MyApp1">
<div ng-controller="MyController">
    <input type="text" ng-model="feed.name" placeholder="Name" />
     <select ng-model="feed">
        <option ng-repeat="template in configs" value="template.value">{{template.name}}    
 </option>
    </select>
    </div>
 </div>

JS

 var MyApp=angular.module('MyApp1',[])
 MyApp.controller('MyController',function($scope) {  
      $scope.feed = 'config1';      
      $scope.configs = [
         {'name': 'Config 1', 'value': 'config1'},
         {'name': 'Config 2', 'value': 'config2'},
         {'name': 'Config 3', 'value': 'config3'}
      ];
 });

Convert a RGB Color Value to a Hexadecimal String

You can use

String hex = String.format("#%02x%02x%02x", r, g, b);  

Use capital X's if you want your resulting hex-digits to be capitalized (#FFFFFF vs. #ffffff).

Converting double to string with N decimals, dot as decimal separator, and no thousand separator

I prefer to use ToString() and IFormatProvider.

double value = 100000.3
Console.WriteLine(value.ToString("0,0.00", new CultureInfo("en-US", false)));

Output: 10,000.30

How to use Typescript with native ES6 Promises

A. If using "target": "es5" and TypeScript version below 2.0:

typings install es6-promise --save --global --source dt

B. If using "target": "es5" and TypeScript version 2.0 or higer:

"compilerOptions": {
    "lib": ["es5", "es2015.promise"]
}

C. If using "target": "es6", there's no need to do anything.

Centering a div block without the width

I found a more elegant solution, combining "inline-block" to avoid using float and the hacky clear:both. It still requires nested divs tho, which isnt very semantic but it just works...

div.outer{
    display:inline-block;
    position:relative;
    left:50%;
}

div.inner{
    position:relative;
    left:-50%;
}

Hope it helps!

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

REST security is transport dependent while SOAP security is not.

REST inherits security measures from the underlying transport while SOAP defines its own via WS-Security.

When we talk about REST, over HTTP - all security measures applied HTTP are inherited and this is known as transport level security.

Transport level security, secures your message only while its on the wire - as soon as it leaves the wire, the message is no more secured.

But, with WS-Security, its message level security - even though the message leaves the transport channel it will be still protected. Also - with message level security you can partly encrypt the message [not the entire message, but only the parts you want] - but with transport level security you can't do it.

WS-Security has measures for authentication, integrity, confidentiality and non-repudiation while SSL doesn't support non repudiation [with 2-legged OAuth it does].

In performance-wise SSL is very much faster than WS-Security.

Thanks...

SQL Error: ORA-00922: missing or invalid option

You should not use space character while naming database objects. Even though it's possible by using double quotes(quoted identifiers), CREATE TABLE "chartered flight" ..., it's not recommended. Take a closer look here

PHP String to Float

$rootbeer = (float) $InvoicedUnits;

Should do it for you. Check out Type-Juggling. You should also read String conversion to Numbers.

Where are include files stored - Ubuntu Linux, GCC

gcc is a rich and complex "orchestrating" program that calls many other programs to perform its duties. For the specific purpose of seeing where #include "goo" and #include <zap> will search on your system, I recommend:

$ touch a.c
$ gcc -v -E a.c
 ...
#include "..." search starts here:
#include <...> search starts here:
 /usr/local/include
 /usr/lib/gcc/i686-apple-darwin9/4.0.1/include
 /usr/include
 /System/Library/Frameworks (framework directory)
 /Library/Frameworks (framework directory)
End of search list.
# 1 "a.c"

This is one way to see the search lists for included files, including (if any) directories into which #include "..." will look but #include <...> won't. This specific list I'm showing is actually on Mac OS X (aka Darwin) but the commands I recommend will show you the search lists (as well as interesting configuration details that I've replaced with ... here;-) on any system on which gcc runs properly.

Sending XML data using HTTP POST with PHP

you can use cURL library for posting data: http://www.php.net/curl

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch, CURLOPT_URL, "http://websiteURL");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "XML=".$xmlcontent."&password=".$password."&etc=etc");
$content=curl_exec($ch);

where postfield contains XML you need to send - you will need to name the postfield the API service (Clickatell I guess) expects

Difference between 'struct' and 'typedef struct' in C++?

Struct is to create a data type. The typedef is to set a nickname for a data type.

How to put a text beside the image?

If you or some other fox who need to have link with Icon Image and text as link text beside the image see bellow code:

CSS

.linkWithImageIcon{

    Display:inline-block;
}
.MyLink{
  Background:#FF3300;
  width:200px;
  height:70px;
  vertical-align:top;
  display:inline-block; font-weight:bold;
} 

.MyLinkText{
  /*---The margin depends on how the image size is ---*/
  display:inline-block; margin-top:5px;
}

HTML

<a href="#" class="MyLink"><img src="./yourImageIcon.png" /><span class="MyLinkText">SIGN IN</span></a>

enter image description here

if you see the image the white portion is image icon and other is style this way you can create different buttons with any type of Icons you want to design

Why do we have to override the equals() method in Java?

To answer your question, firstly I would strongly recommend looking at the Documentation.

Without overriding the equals() method, it will act like "==". When you use the "==" operator on objects, it simply checks to see if those pointers refer to the same object. Not if their members contain the same value.

We override to keep our code clean, and abstract the comparison logic from the If statement, into the object. This is considered good practice and takes advantage of Java's heavily Object Oriented Approach.

How to uninstall a Windows Service when there is no executable for it left on the system?

Remove Windows Service via Registry

Its very easy to remove a service from registry if you know the right path. Here is how I did that:

  1. Run Regedit or Regedt32

  2. Go to the registry entry "HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services"

  3. Look for the service that you want delete and delete it. You can look at the keys to know what files the service was using and delete them as well (if necessary).

Delete Windows Service via Command Window

Alternatively, you can also use command prompt and delete a service using following command:

sc delete

You can also create service by using following command

sc create "MorganTechService" binpath= "C:\Program Files\MorganTechSPace\myservice.exe"

Note: You may have to reboot the system to get the list updated in service manager.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }

decorate your model like this. can use a bootstrap date time picker I used this one. https://github.com/Eonasdan/bootstrap-datetimepicker/

I suppose you already have bundles for bootstrap css and js

Your date picker bundle entries

 bundles.Add(new ScriptBundle("~/bundles/datePicker").Include(
           "~/Scripts/moment.min.js",
           "~/Scripts/bootstrap-datetimepicker.min.js"));

        bundles.Add(new StyleBundle("~/Content/datepicker").Include(
                 "~/Content/bootstrap-datetimepicker.min.css"));

Render bundles on your Layout View

@Styles.Render("~/Content/datepicker")
@Scripts.Render("~/bundles/datePicker")

Your HTML in view

<div class="form-group">
        @Html.LabelFor(model => model.BirthDate, htmlAttributes: new { @class = "lead col-md-2" })
        <div class="col-md-10">
            @Html.TextBoxFor(model => model.BirthDate, new { @class = "datetimepicker form-control" })
            @Html.ValidationMessageFor(model => model.BirthDate, "", new { @class = "text-danger" })
        </div>
</div>

At the end of your view add this.

<script>
    $(document).ready(function () {
        $('.datetimepicker').datetimepicker({
            format: 'lll'
        });
    });
</script>

How to capture the android device screen content?

Use the following code:

Bitmap bitmap;
View v1 = MyView.getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);

Here MyView is the View through which we need include in the screen. You can also get DrawingCache from of any View this way (without getRootView()).


There is also another way..
If we having ScrollView as root view then its better to use following code,

LayoutInflater inflater = (LayoutInflater) this.getSystemService(LAYOUT_INFLATER_SERVICE);
FrameLayout root = (FrameLayout) inflater.inflate(R.layout.activity_main, null); // activity_main is UI(xml) file we used in our Activity class. FrameLayout is root view of my UI(xml) file.
root.setDrawingCacheEnabled(true);
Bitmap bitmap = getBitmapFromView(this.getWindow().findViewById(R.id.frameLayout)); // here give id of our root layout (here its my FrameLayout's id)
root.setDrawingCacheEnabled(false);

Here is the getBitmapFromView() method

public static Bitmap getBitmapFromView(View view) {
        //Define a bitmap with the same size as the view
        Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),Bitmap.Config.ARGB_8888);
        //Bind a canvas to it
        Canvas canvas = new Canvas(returnedBitmap);
        //Get the view's background
        Drawable bgDrawable =view.getBackground();
        if (bgDrawable!=null) 
            //has background drawable, then draw it on the canvas
            bgDrawable.draw(canvas);
        else 
            //does not have background drawable, then draw white background on the canvas
            canvas.drawColor(Color.WHITE);
        // draw the view on the canvas
        view.draw(canvas);
        //return the bitmap
        return returnedBitmap;
    }

It will display entire screen including content hidden in your ScrollView


UPDATED AS ON 20-04-2016

There is another better way to take screenshot.
Here I have taken screenshot of WebView.

WebView w = new WebView(this);
    w.setWebViewClient(new WebViewClient()
    {
        public void onPageFinished(final WebView webView, String url) {

            new Handler().postDelayed(new Runnable(){
                @Override
                public void run() {
                    webView.measure(View.MeasureSpec.makeMeasureSpec(
                                    View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED),
                            View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
                    webView.layout(0, 0, webView.getMeasuredWidth(),
                            webView.getMeasuredHeight());
                    webView.setDrawingCacheEnabled(true);
                    webView.buildDrawingCache();
                    Bitmap bitmap = Bitmap.createBitmap(webView.getMeasuredWidth(),
                            webView.getMeasuredHeight(), Bitmap.Config.ARGB_8888);

                    Canvas canvas = new Canvas(bitmap);
                    Paint paint = new Paint();
                    int height = bitmap.getHeight();
                    canvas.drawBitmap(bitmap, 0, height, paint);
                    webView.draw(canvas);

                    if (bitmap != null) {
                        try {
                            String filePath = Environment.getExternalStorageDirectory()
                                    .toString();
                            OutputStream out = null;
                            File file = new File(filePath, "/webviewScreenShot.png");
                            out = new FileOutputStream(file);

                            bitmap.compress(Bitmap.CompressFormat.PNG, 50, out);
                            out.flush();
                            out.close();
                            bitmap.recycle();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }, 1000);
        }
    });

Hope this helps..!

How to dynamically create columns in datatable and assign values to it?

What have you tried, what was the problem?

Creating DataColumns and add values to a DataTable is straight forward:

Dim dt = New DataTable()
Dim dcID = New DataColumn("ID", GetType(Int32))
Dim dcName = New DataColumn("Name", GetType(String))
dt.Columns.Add(dcID)
dt.Columns.Add(dcName)
For i = 1 To 1000
    dt.Rows.Add(i, "Row #" & i)
Next

Edit:

If you want to read a xml file and load a DataTable from it, you can use DataTable.ReadXml.

Using jQuery Fancybox or Lightbox to display a contact form

Greybox cannot handle forms inside it on its own. It requires a forms plugin. No iframes or external html files needed. Don't forget to download the greybox.css file too as the page misses that bit out.

Kiss Jquery UI goodbye and a lightbox hello. You can get it here.

Vim clear last search highlighting

I use the following in my ~/.vimrc

nnoremap <Leader><space> :noh<Enter>

This makes it very easy and quick to clear the current highlighted search. My leader key is mapped to \ so this makes the action very easy to perform with my right pinky finger and thumb.

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

Thanks for sharing this. It helped a lot. The one difference in my applicationHost.config was

            <add name="SharePoint14Module" image="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\owssvr.dll" preCondition="appPoolName=SharePoint Central Administration v4,bitness64;SharePoint - 80" />

Note the multiple semicolon seperated entries. This is probably because I have a single box install of SPS.

How do I plot in real-time in a while loop using matplotlib?

If you're interested in realtime plotting, I'd recommend looking into matplotlib's animation API. In particular, using blit to avoid redrawing the background on every frame can give you substantial speed gains (~10x):

#!/usr/bin/env python

import numpy as np
import time
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt


def randomwalk(dims=(256, 256), n=20, sigma=5, alpha=0.95, seed=1):
    """ A simple random walk with memory """

    r, c = dims
    gen = np.random.RandomState(seed)
    pos = gen.rand(2, n) * ((r,), (c,))
    old_delta = gen.randn(2, n) * sigma

    while True:
        delta = (1. - alpha) * gen.randn(2, n) * sigma + alpha * old_delta
        pos += delta
        for ii in xrange(n):
            if not (0. <= pos[0, ii] < r):
                pos[0, ii] = abs(pos[0, ii] % r)
            if not (0. <= pos[1, ii] < c):
                pos[1, ii] = abs(pos[1, ii] % c)
        old_delta = delta
        yield pos


def run(niter=1000, doblit=True):
    """
    Display the simulation using matplotlib, optionally using blit for speed
    """

    fig, ax = plt.subplots(1, 1)
    ax.set_aspect('equal')
    ax.set_xlim(0, 255)
    ax.set_ylim(0, 255)
    ax.hold(True)
    rw = randomwalk()
    x, y = rw.next()

    plt.show(False)
    plt.draw()

    if doblit:
        # cache the background
        background = fig.canvas.copy_from_bbox(ax.bbox)

    points = ax.plot(x, y, 'o')[0]
    tic = time.time()

    for ii in xrange(niter):

        # update the xy data
        x, y = rw.next()
        points.set_data(x, y)

        if doblit:
            # restore background
            fig.canvas.restore_region(background)

            # redraw just the points
            ax.draw_artist(points)

            # fill in the axes rectangle
            fig.canvas.blit(ax.bbox)

        else:
            # redraw everything
            fig.canvas.draw()

    plt.close(fig)
    print "Blit = %s, average FPS: %.2f" % (
        str(doblit), niter / (time.time() - tic))

if __name__ == '__main__':
    run(doblit=False)
    run(doblit=True)

Output:

Blit = False, average FPS: 54.37
Blit = True, average FPS: 438.27

Docker-Compose with multiple services

The thing is that you are using the option -t when running your container.

Could you check if enabling the tty option (see reference) in your docker-compose.yml file the container keeps running?

version: '2'
services:
  ubuntu:
        build: .
        container_name: ubuntu
        volumes:
            - ~/sph/laravel52:/www/laravel
        ports:
          - "80:80"
        tty: true

Open CSV file via VBA (performance)

Workbooks.Open does work too.

Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", Local:=True

this works/is needed because i use Excel in germany and excel does use "," to separate .csv by default because i use an english installation of windows. even if you use the code below excel forces the "," separator.

Workbooks.Open ActiveWorkbook.Path & "\Test.csv", , , 6, , , , , ";"

and Workbooks.Open ActiveWorkbook.Path & "\Temp.csv", , , 4 +variants of this do not work(!)

why do they even have the delimiter parameter if it is blocked by the Local parameter ?! this makes no sense at all. but now it works.

Undefined function mysql_connect()

Well, this is your chance! It looks like PDO is ready; use that instead.

Try checking to see if the PHP MySQL extension module is being loaded:

<?php
    phpinfo();
?>

If it's not there, add the following to the php.ini file:

extension=php_mysql.dll

PHP convert XML to JSON

$templateData =  $_POST['data'];

// initializing or creating array
$template_info =  $templateData;

// creating object of SimpleXMLElement
$xml_template_info = new SimpleXMLElement("<?xml version=\"1.0\"?><template></template>");

// function call to convert array to xml
array_to_xml($template_info,$xml_template_info);

//saving generated xml file
 $xml_template_info->asXML(dirname(__FILE__)."/manifest.xml") ;

// function defination to convert array to xml
function array_to_xml($template_info, &$xml_template_info) {
    foreach($template_info as $key => $value) {
        if(is_array($value)) {
            if(!is_numeric($key)){
                $subnode = $xml_template_info->addChild($key);
                if(is_array($value)){
                    $cont = 0;
                    foreach(array_keys($value) as $k){
                        if(is_numeric($k)) $cont++;
                    }
                }

                if($cont>0){
                    for($i=0; $i < $cont; $i++){
                        $subnode = $xml_body_info->addChild($key);
                        array_to_xml($value[$i], $subnode);
                    }
                }else{
                    $subnode = $xml_body_info->addChild($key);
                    array_to_xml($value, $subnode);
                }
            }
            else{
                array_to_xml($value, $xml_template_info);
            }
        }
        else {
            $xml_template_info->addChild($key,$value);
        }
    }
}

"Multiple definition", "first defined here" errors

Maybe you included the .c file in makefile multiple times.

How to create an integer array in Python?

If you need to initialize an array fast, you might do it by blocks instead of with a generator initializer, and it's going to be much faster. Creating a list by [0]*count is just as fast, still.

import array

def zerofill(arr, count):
    count *= arr.itemsize
    blocksize = 1024
    blocks, rest = divmod(count, blocksize)
    for _ in xrange(blocks):
        arr.fromstring("\x00"*blocksize)
    arr.fromstring("\x00"*rest)

def test_zerofill(count):
    iarr = array.array('i')
    zerofill(iarr, count)
    assert len(iarr) == count

def test_generator(count):
    iarr = array.array('i', (0 for _ in xrange(count)))
    assert len(iarr) == count

def test_list(count):
    L = [0]*count
    assert len(L) == count

if __name__ == '__main__':
    import timeit
    c = 100000
    n = 10
    print timeit.Timer("test(c)", "from __main__ import c, test_zerofill as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_generator as test").repeat(number=n)
    print timeit.Timer("test(c)", "from __main__ import c, test_list as test").repeat(number=n)

Results:

(array in blocks) [0.022809982299804688, 0.014942169189453125, 0.014089107513427734]
(array with generator) [1.1884641647338867, 1.1728270053863525, 1.1622772216796875]
(list) [0.023866891860961914, 0.035660028457641602, 0.023386955261230469]

A server is already running. Check …/tmp/pids/server.pid. Exiting - rails

You can delete the server.pid file.

rm /your_project_path/tmp/pids/server.pid

Else:

try in OSX:

sudo lsof -iTCP -sTCP:LISTEN -P | grep :3000

or in linux:

ps -aef | grep rails

or

lsof -wni tcp:3000

kill the process using

kill -9 PID (eg,2786)

Converting java.util.Properties to HashMap<String,String>

You can use this:

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

props.forEach((key, value) -> map.put(key.toString(), value.toString()));

Is PowerShell ready to replace my Cygwin shell on Windows?

As someone whose career focused on Windows enterprise development from 1997 - 2010, the obvious answer would be PowerShell for all the good reasons given previously (e.g., it is part of Microsoft's enterprise strategy; it integrates well with Windows/COM/.NET; and using objects instead of files provides for a "richer" coding model). For that reason I'd been using and promoting PowerShell for the last two years or so, with the express belief I was following the "Word of Bill."

However, as a pragmatist I'm no longer sure PowerShell is such a great answer. While it's an excellent Windows tool and provides a much needed step towards filling the historic hole that is the Window command line, as we all watch Microsoft's grip on consumer computing slip it seems increasingly likely that Microsoft has a massive battle ahead to keep its OS as important to the enterprise of the future.

Indeed, given I find my work is increasingly in heterogeneous environments, I'm finding it much more useful to use Bash scripts at the moment, as they not only work on Linux, Solaris and Mac OS X, but they also work—with the help of Cygwin—on Windows.

So if you buy into the belief that the future of the OS is commoditized rather than a monopolized, then it seems to make sense to opt for an agile development tool strategy that keeps away from proprietary tools where feasible. If however you see your future being dominated by all-that-is-Redmond then go for PowerShell.

Trying to detect browser close event

Try following code works for me under Linux chrome environment. Before running make sure jquery is attached to the document.

$(document).ready(function()
{
    $(window).bind("beforeunload", function() { 
        return confirm("Do you really want to close?"); 
    });
});

For simple follow following steps:

  1. open http://jsfiddle.net/
  2. enter something into html, css or javascript box
  3. try to close tab in chrome

It should show following picture:

enter image description here

How to import local packages in go?

Local package is a annoying problem in go.

For some projects in our company we decide not use sub packages at all.

  • $ glide install
  • $ go get
  • $ go install

All work.

For some projects we use sub packages, and import local packages with full path:

import "xxxx.gitlab.xx/xxgroup/xxproject/xxsubpackage

But if we fork this project, then the subpackages still refer the original one.

CSS How to set div height 100% minus nPx

If you don't want to use absolute positioning and all that jazz, here's a fix I like to use:

your html:

<body>    
   <div id="header"></div>
   <div id="wrapper"></div>
</body>

your css:

body {
     height:100%;
     padding-top:60px;
}
#header {
     margin-top:60px;
     height:60px;
}
#wrapper {
     height:100%;
}

Does Git Add have a verbose switch

For some git-commands you can specify --verbose,

git 'command' --verbose

or

git 'command' -v.

Make sure the switch is after the actual git command. Otherwise - it won't work!

Also useful:

git 'command' --dry-run 

Using group by and having clause

Because we can not use Where clause with aggregate functions like count(),min(), sum() etc. so having clause came into existence to overcome this problem in sql. see example for having clause go through this link

http://www.sqlfundamental.com/having-clause.php

Convert wchar_t to char

An easy way is :

        wstring your_wchar_in_ws(<your wchar>);
        string your_wchar_in_str(your_wchar_in_ws.begin(), your_wchar_in_ws.end());
        char* your_wchar_in_char =  your_wchar_in_str.c_str();

I'm using this method for years :)

Special characters like @ and & in cURL POST data

Just found another solutions worked for me. You can use '\' sign before your one special.

passwd=\@31\&3*J

How to run code after some delay in Flutter?

Figured it out

class AnimatedFlutterLogo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => new _AnimatedFlutterLogoState();
}

class _AnimatedFlutterLogoState extends State<AnimatedFlutterLogo> {
  Timer _timer;
  FlutterLogoStyle _logoStyle = FlutterLogoStyle.markOnly;

  _AnimatedFlutterLogoState() {
    _timer = new Timer(const Duration(milliseconds: 400), () {
      setState(() {
        _logoStyle = FlutterLogoStyle.horizontal;
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    _timer.cancel();
  }

  @override
  Widget build(BuildContext context) {
    return new FlutterLogo(
      size: 200.0,
      textColor: Palette.white,
      style: _logoStyle,
    );
  }
}

How to display a loading screen while site content loads

#Pure css method

Place this at the top of your code (before header tag)

_x000D_
_x000D_
<style> .loader {_x000D_
  position: fixed;_x000D_
  background-color: #FFF;_x000D_
  opacity: 1;_x000D_
  height: 100%;_x000D_
  width: 100%;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  z-index: 10;_x000D_
}_x000D_
</style>
_x000D_
<div class="loader">_x000D_
  Your Content For Load Screen_x000D_
</div>
_x000D_
_x000D_
_x000D_

And This At The Bottom after all other code (except /html tag)

_x000D_
_x000D_
<style>_x000D_
.loader {_x000D_
    -webkit-animation: load-out 1s;_x000D_
    animation: load-out 1s;_x000D_
    -webkit-animation-fill-mode: forwards;_x000D_
    animation-fill-mode: forwards;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes load-out {_x000D_
    from {_x000D_
        top: 0;_x000D_
        opacity: 1;_x000D_
    }_x000D_
_x000D_
    to {_x000D_
        top: 100%;_x000D_
        opacity: 0;_x000D_
    }_x000D_
}_x000D_
_x000D_
@keyframes load-out {_x000D_
    from {_x000D_
        top: 0;_x000D_
        opacity: 1;_x000D_
    }_x000D_
_x000D_
    to {_x000D_
        top: 100%;_x000D_
        opacity: 0;_x000D_
    }_x000D_
}_x000D_
</style>
_x000D_
_x000D_
_x000D_

This always works for me 100% of the time

How to see the proxy settings on windows?

An update to @rleelr:
It's possible to view proxy settings in Google Chrome:

chrome://net-internals/#http2

Then select

View live HTTP/2 sessions

Then select one of the live sessions (you need to have some tabs open). There you find:

[...]
t=504112 [st= 0] +HTTP2_SESSION  [dt=?]
                  --> host = "play.google.com:443"
                  --> proxy = "PROXY www.xxx.yyy.zzz:8080"
[...]
                              ============================

How do I set the maximum line length in PyCharm?

Here is screenshot of my Pycharm. Required settings is in following path: File -> Settings -> Editor -> Code Style -> General: Right margin (columns)

Pycharm 4 Settings Screenshot

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

The 'best' way to do this would be to set a property on a view object once the update is successful. You can then access this property in the view and inform the user accordingly.

Having said that it would be possible to trigger an alert from the controller code by doing something like this -

public ActionResult ActionName(PostBackData postbackdata)
{
    //your DB code
    return new JavascriptResult { Script = "alert('Successfully registered');" };
}

You can find further info in this question - How to display "Message box" using MVC3 controller

jQuery callback on image load (even when the image is cached)

Just re-add the src argument on a separate line after the img oject is defined. This will trick IE into triggering the lad-event. It is ugly, but it is the simplest workaround I've found so far.

jQuery('<img/>', {
    src: url,
    id: 'whatever'
})
.load(function() {
})
.appendTo('#someelement');
$('#whatever').attr('src', url); // trigger .load on IE

Run Function After Delay

You can simply use jQuery’s delay() method to set the delay time interval.

HTML code:

  <div class="box"></div>

JQuery code:

  $(document).ready(function(){ 
    $(".show-box").click(function(){
      $(this).text('loading...').delay(1000).queue(function() {
        $(this).hide();
        showBox(); 
        $(this).dequeue();
      });        
    });
  });

You can see an example here: How to Call a Function After Some Time in jQuery

I can't install python-ldap

For most systems, the build requirements are now mentioned in python-ldap's documentation, in the "Installing" section.

If anything is missing for your system (or your system is missing entirely), please let maintainer know! (As of 2018, I am the maintainer, so a comment here should be enough. Or you can send a pull request or mail.)

How to drop SQL default constraint without knowing its name?

Drop all default contstraints in a database - safe for nvarchar(max) threshold.

/* WARNING: THE SAMPLE BELOW; DROPS ALL THE DEFAULT CONSTRAINTS IN A DATABASE */ 
/* MAY 03, 2013 - BY WISEROOT  */
declare @table_name nvarchar(128)
declare @column_name nvarchar(128)
declare @df_name nvarchar(128)
declare @cmd nvarchar(128) 

declare table_names cursor for 
 SELECT t.name TableName, c.name ColumnName
 FROM sys.columns c INNER JOIN
     sys.tables t ON c.object_id = t.object_id INNER JOIN
     sys.schemas s ON t.schema_id = s.schema_id
     ORDER BY T.name, c.name

     open table_names
fetch next from table_names into @table_name , @column_name
while @@fetch_status = 0
BEGIN

if exists (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = @table_name and c.name = @column_name)
BEGIN
    SET @df_name = (SELECT top(1) d.name from sys.tables t join sys.default_constraints d on d.parent_object_id = t.object_id join sys.columns c on c.object_id = t.object_id and c.column_id = d.parent_column_id where t.name = @table_name and c.name = @column_name)
    select @cmd = 'ALTER TABLE [' + @table_name +  '] DROP CONSTRAINT [' +  @df_name + ']'
    print @cmd
    EXEC sp_executeSQL @cmd;
END

  fetch next from table_names into @table_name , @column_name
END

close table_names 
deallocate table_names

How to get a list of column names

Using @Tarkus's answer, here are the regexes I used in R:

getColNames <- function(conn, tableName) {
    x <- dbGetQuery( conn, paste0("SELECT sql FROM sqlite_master WHERE tbl_name = '",tableName,"' AND type = 'table'") )[1,1]
    x <- str_split(x,"\\n")[[1]][-1]
    x <- sub("[()]","",x)
    res <- gsub( '"',"",str_extract( x[1], '".+"' ) )
    x <- x[-1]
    x <- x[-length(x)]
    res <- c( res, gsub( "\\t", "", str_extract( x, "\\t[0-9a-zA-Z_]+" ) ) )
    res
}

Code is somewhat sloppy, but it appears to work.

Best way to show a loading/progress indicator?

Actually if you are waiting for response from a server it should be done programatically. You may create a progress dialog and dismiss it, but then again that is not "the android way".

Currently the recommended method is to use a DialogFragment :

public class MySpinnerDialog extends DialogFragment {

    public MySpinnerDialog() {
        // use empty constructors. If something is needed use onCreate's
    }

    @Override
    public Dialog onCreateDialog(final Bundle savedInstanceState) {

        _dialog = new ProgressDialog(getActivity());
        this.setStyle(STYLE_NO_TITLE, getTheme()); // You can use styles or inflate a view
        _dialog.setMessage("Spinning.."); // set your messages if not inflated from XML

        _dialog.setCancelable(false);  

        return _dialog;
    }
}

Then in your activity you set your Fragment manager and show the dialog once the wait for the server started:

FragmentManager fm = getSupportFragmentManager();
MySpinnerDialog myInstance = new MySpinnerDialog();
}
myInstance.show(fm, "some_tag");

Once your server has responded complete you will dismiss it:

myInstance.dismiss()

Remember that the progressdialog is a spinner or a progressbar depending on the attributes, read more on the api guide

Moving Average Pandas

The rolling mean returns a Series you only have to add it as a new column of your DataFrame (MA) as described below.

For information, the rolling_mean function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

df['MA'] = df.rolling(window=5).mean()

print(df)
#             Value    MA
# Date                   
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

How to create nested directories using Mkdir in Golang?

os.Mkdir is used to create a single directory. To create a folder path, instead try using:

os.MkdirAll(folderPath, os.ModePerm)

Go documentation

func MkdirAll(path string, perm FileMode) error

MkdirAll creates a directory named path, along with any necessary parents, and returns nil, or else returns an error. The permission bits perm are used for all directories that MkdirAll creates. If path is already a directory, MkdirAll does nothing and returns nil.

Edit:

Updated to correctly use os.ModePerm instead.
For concatenation of file paths, use package path/filepath as described in @Chris' answer.

Angular 2 router no base href set

https://angular.io/docs/ts/latest/guide/router.html

Add the base element just after the <head> tag. If the app folder is the application root, as it is for our application, set the href value exactly as shown here.

The <base href="/"> tells the Angular router what is the static part of the URL. The router then only modifies the remaining part of the URL.

<head>
  <base href="/">
  ...
</head>

Alternatively add

>= Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';

@NgModule({
  declarations: [AppComponent],
  imports: [routing /* or RouterModule */], 
  providers: [{provide: APP_BASE_HREF, useValue : '/' }]
]); 

in your bootstrap.

In older versions the imports had to be like

< Angular2 RC.6

import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  {provide: APP_BASE_HREF, useValue : '/' });
]); 

< RC.0

import {provide} from 'angular2/core';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS, 
  provide(APP_BASE_HREF, {useValue : '/' });
]); 

< beta.17

import {APP_BASE_HREF} from 'angular2/router';

>= beta.17

import {APP_BASE_HREF} from 'angular2/platform/common';

See also Location and HashLocationStrategy stopped working in beta.16

How to refresh Gridview after pressed a button in asp.net

Adding the GridView1.DataBind() to the button click event did not work for me. However, adding it to the SqlDataSource1_Updated event did though.

Protected Sub SqlDataSource1_Updated(sender As Object, e As SqlDataSourceStatusEventArgs) Handles SqlDataSource1.Updated
    GridView1.DataBind()
End Sub

How to enable CORS in AngularJs

This issue occurs because of web application security model policy that is Same Origin Policy Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. That means requester must match the exact host, protocol, and port of requesting site.

We have multiple options to over come this CORS header issue.

  1. Using Proxy - In this solution we will run a proxy such that when request goes through the proxy it will appear like it is some same origin. If you are using the nodeJS you can use cors-anywhere to do the proxy stuff. https://www.npmjs.com/package/cors-anywhere.

    Example:-

    var host = process.env.HOST || '0.0.0.0';
    var port = process.env.PORT || 8080;
    var cors_proxy = require('cors-anywhere');
    cors_proxy.createServer({
        originWhitelist: [], // Allow all origins
        requireHeader: ['origin', 'x-requested-with'],
        removeHeaders: ['cookie', 'cookie2']
    }).listen(port, host, function() {
        console.log('Running CORS Anywhere on ' + host + ':' + port);
    });
    
  2. JSONP - JSONP is a method for sending JSON data without worrying about cross-domain issues.It does not use the XMLHttpRequest object.It uses the <script> tag instead. https://www.w3schools.com/js/js_json_jsonp.asp

  3. Server Side - On server side we need to enable cross-origin requests. First we will get the Preflighted requests (OPTIONS) and we need to allow the request that is status code 200 (ok).

    Preflighted requests first send an HTTP OPTIONS request header to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if it uses methods other than GET or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted. It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

    If you are using the spring just adding the bellow code will resolves the issue. Here I have disabled the csrf token that doesn't matter enable/disable according to your requirement.

    @SpringBootApplication
    public class SupplierServicesApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(SupplierServicesApplication.class, args);
        }
    
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**").allowedOrigins("*");
                }
            };
        }
    }
    

    If you are using the spring security use below code along with above code.

    @Configuration
    @EnableWebSecurity
    public class SupplierSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().authorizeRequests().antMatchers(HttpMethod.OPTIONS, "/**").permitAll().antMatchers("/**").authenticated().and()
                    .httpBasic();
        }
    
    }
    

How to set custom location for local installation of npm package?

After searching for this myself wanting several projects with shared dependencies to be DRYer, I’ve found:

  • Installing locally is the Node way for anything you want to use via require()
  • Installing globally is for binaries you want in your path, but is not intended for anything via require()
  • Using a prefix means you need to add appropriate bin and man paths to $PATH
  • npm link (info) lets you use a local install as a source for globals

? stick to the Node way and install locally

ref:

Get only filename from url in php without any variable values which exist in the url

$url = "learner.com/learningphp.php?lid=1348";
$l = parse_url($url);
print_r(stristr($l['path'], "/"));

How to remove default mouse-over effect on WPF buttons?

Using a template trigger:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
    <Setter Property="Background" Value="White"></Setter>
    ...
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type Button}">
                <Border Background="{TemplateBinding Background}">
                    <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Background" Value="White"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Shell - How to find directory of some command?

In the TENEX C Shell, tcsh, one can list a command's location(s), or if it is a built-in command, using the where command e.g.:

tcsh% where python
/usr/local/bin/python
/usr/bin/python

tcsh% where cd
cd is a shell built-in
/usr/bin/cd

How do pointer-to-pointer's work in C? (and when might you use them?)

Pointers to Pointers

Since we can have pointers to int, and pointers to char, and pointers to any structures we've defined, and in fact pointers to any type in C, it shouldn't come as too much of a surprise that we can have pointers to other pointers.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

Never used it myself, but my C friends tell me Purify.

Javascript Date - set just the date, ignoring time?

If you don't mind creating an extra date object, you could try:

var tempDate = new Date(parseInt(item.timestamp, 10));
var visitDate = new Date (tempDate.getUTCFullYear(), tempDate.getUTCMonth(), tempDate.getUTCDate());

I do something very similar to get a date of the current month without the time.

HTML colspan in CSS

There is no colspan in css as far as I know, but there will be column-span for multi column layout in the near future, but since it is only a draft in CSS3, you can check it in here. Anyway you can do a workaround using div and span with table-like display like this.

This would be the HTML:

<div class="table">
  <div class="row">
    <span class="cell red first"></span>
    <span class="cell blue fill"></span>
    <span class="cell green last"></span>
  </div>
</div>
<div class="table">
  <div class="row">
    <span class="cell black"></span>
  </div>
</div>

And this would be the css:

  /* this is to reproduce table-like structure
     for the sake of table-less layout. */
  .table { display:table; table-layout:fixed; width:100px; }
  .row { display:table-row; height:10px; }
  .cell { display:table-cell; }

  /* this is where the colspan tricks works. */
  span { width:100%; }

  /* below is for visual recognition test purposes only. */
  .red { background:red; }
  .blue { background:blue; }
  .green { background:green; }
  .black { background:black; }

  /* this is the benefit of using table display, it is able 
     to set the width of it's child object to fill the rest of 
     the parent width as in table */
  .first { width: 20px; }
  .last { width: 30px; }
  .fill { width: 100%; }

The only reason to use this trick is to gain the benefit of table-layout behaviour, I use it alot if only setting div and span width to certain percentage didn't fullfil our design requirement.

But if you don't need to benefit from the table-layout behaviour, then durilai's answer would suit you enough.

Declaring and using MySQL varchar variables

In Mysql, We can declare and use variables with set command like below

mysql> set @foo="manjeet";
mysql> select * from table where name = @foo;

Shell script to delete directories older than n days

I was struggling to get this right using the scripts provided above and some other scripts especially when files and folder names had newline or spaces.

Finally stumbled on tmpreaper and it has been worked pretty well for us so far.

tmpreaper -t 5d ~/Downloads


tmpreaper  --protect '*.c' -t 5h ~/my_prg

Original Source link

Has features like test, which checks the directories recursively and lists them. Ability to delete symlinks, files or directories and also the protection mode for a certain pattern while deleting

Formula to check if string is empty in Crystal Reports

On the formula menu just Select "Default Values for Nulls" then just add all the fields like the below:

{@Table.Field1} + {@Table.Field2} + {@Table.Field3} + {@Table.Field4} + {@Table.Field5}

Sniffing/logging your own Android Bluetooth traffic

Android 4.4 (Kit Kat) does have a new sniffing capability for Bluetooth. You should give it a try.

If you don’t own a sniffing device however, you aren’t necessarily out of luck. In many cases we can obtain positive results with a new feature introduced in Android 4.4: the ability to capture all Bluetooth HCI packets and save them to a file.

When the Analyst has finished populating the capture file by running the application being tested, he can pull the file generated by Android into the external storage of the device and analyze it (with Wireshark, for example).

Once this setting is activated, Android will save the packet capture to /sdcard/btsnoop_hci.log to be pulled by the analyst and inspected.

Type the following in case /sdcard/ is not the right path on your particular device:

adb shell echo \$EXTERNAL_STORAGE

We can then open a shell and pull the file: $adb pull /sdcard/btsnoop_hci.log and inspect it with Wireshark, just like a PCAP collected by sniffing WiFi traffic for example, so it is very simple and well supported:

screenshot of wireshark capture using Android HCI Snoop

[source]

You can enable this by going to Settings->Developer Options, then checking the box next to "Bluetooth HCI Snoop Log."