Programs & Examples On #Client side templating

What are the differences between Mustache.js and Handlebars.js?

You've pretty much nailed it, however Mustache templates can also be compiled.

Mustache is missing helpers and the more advanced blocks because it strives to be logicless. Handlebars' custom helpers can be very useful, but often end up introducing logic into your templates.

Mustache has many different compilers (JavaScript, Ruby, Python, C, etc.). Handlebars began in JavaScript, now there are projects like django-handlebars, handlebars.java, handlebars-ruby, lightncandy (PHP), and handlebars-objc.

Is there a real solution to debug cordova apps

FOR ANDROID:

You only need to enable “USB remote debugger” within your android device and plug with a USB cable. Then open your application in the device. Chrome will detect the remote browser and you can see the console in the same way than you see it when you use Chrome locally.

Use this link: chrome://inspect/#devices in Chrome browser (you'll have to paste it into the nav bar).

If your app crashes in the device you only need to see the console’s log within your browser and see what happens. You also can add functionality, change variables, and override functions in the same way than we do it with our local browser.

Read this article for more information on the steps to take.

This will work ONLY with devices running Android 4.4+.

FOR iOS:

Use Safari for iOS, follow these steps:

1.In your iOS device go to Settings > Safari > Advanced > Web Inspector to enable Web Inspector

2.Open Safari on your iOS device.

3.Connect it to your computer via USB.

4.Open Safari on your computer.

5.In Safari’s menu, go to Develop and, look for your device’s name.

6.Select the tab you want to debug.

enter image description here

When do you use the "this" keyword?

1 - Common Java setter idiom:

 public void setFoo(int foo) {
     this.foo = foo;
 }

2 - When calling a function with this object as a parameter

notifier.addListener(this);

How to split a python string on new line characters

a.txt

this is line 1
this is line 2

code:

Python 3.4.0 (default, Mar 20 2014, 22:43:40) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> file = open('a.txt').read()
>>> file
>>> file.split('\n')
['this is line 1', 'this is line 2', '']

I'm on Linux, but I guess you just use \r\n on Windows and it would also work

Platform.runLater and Task in JavaFX

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

Code using Platform.runLater(...):

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();

it suffers from none of the flaws exhibited in the previous code

Reference : Worker Threading in JavaFX 2.0

Windows batch script launch program and exit console

start "" "%SystemRoot%\Notepad.exe"

Keep the "" in between start and your application path.


Added explanation:

Normally when we launch a program from a batch file like below, we'll have the black windows at the background like OP said.

%SystemRoot%\Notepad.exe

This was cause by Notepad running in same command prompt (process). The command prompt will close AFTER notepad is closed. To avoid that, we can use the start command to start a separate process like this.

start %SystemRoot%\Notepad.exe

This command is fine as long it doesn't has space in the path. To handle space in the path for just in case, we added the " quotes like this.

start "%SystemRoot%\Notepad.exe"

However running this command would just start another blank command prompt. Why? If you lookup to the start /?, the start command will recognize the argument between the " as the title of the new command prompt it is going to launch. So, to solve that, we have the command like this:

start "" "%SystemRoot%\Notepad.exe"

The first argument of "" is to set the title (which we set as blank), and the second argument of "%SystemRoot%\Notepad.exe" is the target command to run (that support spaces in the path).

If you need to add parameters to the command, just append them quoted, i.e.:

start "" "%SystemRoot%\Notepad.exe" "<filename>" 

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

Check if a string is a valid Windows directory (folder) path

    private bool IsValidPath(string path)
    {
        Regex driveCheck = new Regex(@"^[a-zA-Z]:\\$");
        if (!driveCheck.IsMatch(path.Substring(0, 3))) return false;
        string strTheseAreInvalidFileNameChars = new string(Path.GetInvalidPathChars());
        strTheseAreInvalidFileNameChars += @":/?*" + "\"";
        Regex containsABadCharacter = new Regex("[" + Regex.Escape(strTheseAreInvalidFileNameChars) + "]");
        if (containsABadCharacter.IsMatch(path.Substring(3, path.Length - 3)))
            return false;

        DirectoryInfo dir = new DirectoryInfo(Path.GetFullPath(path));
        if (!dir.Exists)
            dir.Create();
        return true;
    }

How do I check OS with a preprocessor directive?

Based on nadeausoftware and Lambda Fairy's answer.

#include <stdio.h>

/**
 * Determination a platform of an operation system
 * Fully supported supported only GNU GCC/G++, partially on Clang/LLVM
 */

#if defined(_WIN32)
    #define PLATFORM_NAME "windows" // Windows
#elif defined(_WIN64)
    #define PLATFORM_NAME "windows" // Windows
#elif defined(__CYGWIN__) && !defined(_WIN32)
    #define PLATFORM_NAME "windows" // Windows (Cygwin POSIX under Microsoft Window)
#elif defined(__ANDROID__)
    #define PLATFORM_NAME "android" // Android (implies Linux, so it must come first)
#elif defined(__linux__)
    #define PLATFORM_NAME "linux" // Debian, Ubuntu, Gentoo, Fedora, openSUSE, RedHat, Centos and other
#elif defined(__unix__) || !defined(__APPLE__) && defined(__MACH__)
    #include <sys/param.h>
    #if defined(BSD)
        #define PLATFORM_NAME "bsd" // FreeBSD, NetBSD, OpenBSD, DragonFly BSD
    #endif
#elif defined(__hpux)
    #define PLATFORM_NAME "hp-ux" // HP-UX
#elif defined(_AIX)
    #define PLATFORM_NAME "aix" // IBM AIX
#elif defined(__APPLE__) && defined(__MACH__) // Apple OSX and iOS (Darwin)
    #include <TargetConditionals.h>
    #if TARGET_IPHONE_SIMULATOR == 1
        #define PLATFORM_NAME "ios" // Apple iOS
    #elif TARGET_OS_IPHONE == 1
        #define PLATFORM_NAME "ios" // Apple iOS
    #elif TARGET_OS_MAC == 1
        #define PLATFORM_NAME "osx" // Apple OSX
    #endif
#elif defined(__sun) && defined(__SVR4)
    #define PLATFORM_NAME "solaris" // Oracle Solaris, Open Indiana
#else
    #define PLATFORM_NAME NULL
#endif

// Return a name of platform, if determined, otherwise - an empty string
const char *get_platform_name() {
    return (PLATFORM_NAME == NULL) ? "" : PLATFORM_NAME;
}

int main(int argc, char *argv[]) {
    puts(get_platform_name());
    return 0;
}

Tested with GCC and clang on:

  • Debian 8
  • Windows (MinGW)
  • Windows (Cygwin)

Using NSPredicate to filter an NSArray based on NSDictionary keys

#import <Foundation/Foundation.h>
// clang -framework Foundation Siegfried.m 
    int
main() {
    NSArray *arr = @[
        @{@"1" : @"Fafner"},
        @{@"1" : @"Fasolt"}
    ];
    NSPredicate *p = [NSPredicate predicateWithFormat:
        @"SELF['1'] CONTAINS 'e'"];
    NSArray *res = [arr filteredArrayUsingPredicate:p];
    NSLog(@"Siegfried %@", res);
    return 0;
}

Jenkins Slave port number for firewall

We had a similar situation, but in our case Infosec agreed to allow any to 1, so we didnt had to fix the slave port, rather fixing the master to high level JNLP port 49187 worked ("Configure Global Security" -> "TCP port for JNLP slave agents").

TCP
49187 - Fixed jnlp port
8080 - jenkins http port

Other ports needed to launch slave as a windows service

TCP
135 
139 
445

UDP
137
138

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

Detect HTTP or HTTPS then force HTTPS in JavaScript

You can do:

  <script type="text/javascript">        
        if (window.location.protocol != "https:") {
           window.location.protocol = "https";
        }
    </script>

Skip rows during csv import pandas

skip[1] will skip second line, not the first one.

jQuery - Check if DOM element already exists

(()=> {
    var elem = document.querySelector('.elem');  
    (
        (elem) ? 
        console.log(elem+' was found.') :
        console.log('not found')
    )
})();

If it exists, it spits out the specified element as a DOM object. With JQuery $('.elem') it only tells you that it's an object if found but not which.

Put a Delay in Javascript

If you're okay with ES2017, await is good:

const DEF_DELAY = 1000;

function sleep(ms) {
  return new Promise(resolve => setTimeout(resolve, ms || DEF_DELAY));
}

await sleep(100);

Note that the await part needs to be in an async function:

//IIAFE (immediately invoked async function expression)
(async()=>{
  //Do some stuff
  await sleep(100);
  //Do some more stuff
})()

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

You could try a subquery:

SELECT DISTINCT TEST.* FROM (
    SELECT rsc.RadioServiceCodeId,
        rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
    FROM sbi_l_radioservicecodes rsc
       INNER JOIN sbi_l_radioservicecodegroups rscg ON  rsc.radioservicecodeid = rscg.radioservicecodeid
    WHERE rscg.radioservicegroupid IN 
       (select val from dbo.fnParseArray(@RadioServiceGroup,','))
        OR @RadioServiceGroup IS NULL  
    ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
) as TEST

What is the difference between `new Object()` and object literal notation?

On my machine using Node.js, I ran the following:

console.log('Testing Array:');
console.time('using[]');
for(var i=0; i<200000000; i++){var arr = []};
console.timeEnd('using[]');

console.time('using new');
for(var i=0; i<200000000; i++){var arr = new Array};
console.timeEnd('using new');

console.log('Testing Object:');

console.time('using{}');
for(var i=0; i<200000000; i++){var obj = {}};
console.timeEnd('using{}');

console.time('using new');
for(var i=0; i<200000000; i++){var obj = new Object};
console.timeEnd('using new');

Note, this is an extension of what is found here: Why is arr = [] faster than arr = new Array?

my output was the following:

Testing Array:
using[]: 1091ms
using new: 2286ms
Testing Object:
using{}: 870ms
using new: 5637ms

so clearly {} and [] are faster than using new for creating empty objects/arrays.

Python 2.7.10 error "from urllib.request import urlopen" no module named request

You are right the urllib and urllib2 packages have been split into urllib.request , urllib.parse and urllib.error packages in Python 3.x. The latter packages do not exist in Python 2.x

From documentation -

The urllib module has been split into parts and renamed in Python 3 to urllib.request, urllib.parse, and urllib.error.

From urllib2 documentation -

The urllib2 module has been split across several modules in Python 3 named urllib.request and urllib.error.

So I am pretty sure the code you downloaded has been written for Python 3.x , since they are using a library that is only present in Python 3.x .

There is a urllib package in python, but it does not have the request subpackage. Also, lets assume you do lots of work and somehow make request subpackage available in Python 2.x .

There is a very very high probability that you will run into more issues, there is lots of incompatibility between Python 2.x and Python 3.x , in the end you would most probably end up rewriting atleast half the code from github (and most probably reading and understanding the complete code from there).

Even then there may be other bugs arising from the fact that some of the implementation details changed between Python 2.x to Python 3.x (As an example - list comprehension got its own namespace in Python 3.x)

You are better off trying to download and use Python 3 , than trying to make code written for Python 3.x compatible with Python 2.x

deleting folder from java

The javadoc for File.delete()

public boolean delete()

Deletes the file or directory denoted by this abstract pathname. If this pathname >denotes a directory, then the directory must be empty in order to be deleted.

So a folder has to be empty or deleting it will fail. Your code currently fills the folder list with the top most folder first, followed by its sub folders. Since you iterrate through the list in the same way it will try to delete the top most folder before deleting its subfolders, this will fail.

Changing these line

    for(String filePath : folderList) {
        File tempFile = new File(filePath);
        tempFile.delete();
    }

to this

    for(int i = folderList.size()-1;i>=0;i--) {
        File tempFile = new File(folderList.get(i));
        tempFile.delete();
    }

should cause your code to delete the sub folders first.

The delete operation also returns false when it fails, so you can check this value to do some error handling if necessary.

no match for ‘operator<<’ in ‘std::operator

You need to overload operator << for mystruct class

Something like :-

friend ostream& operator << (ostream& os, const mystruct& m)
{
    os << m.m_a <<" " << m.m_b << endl;
    return os ;
}

See here

Set up DNS based URL forwarding in Amazon Route53

The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.

AWS S3:

  1. Create a Bucket named with your full domain, like aws.example.com
  2. On the bucket properties, select Redirect all requests to another host name and enter your URL: https://myaccount.signin.aws.amazon.com/console/

AWS Route53:

  1. Create a record set type A. Change Alias to Yes. Click on Alias Target field and select the S3 bucket you created in the previous step.

Reference: How to redirect domains using Amazon Web Services

AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?

How can I store JavaScript variable output into a PHP variable?

JavaScript variable = PHP variable try follow:-

<script>
var a="Hello";
<?php
$variable='a';
?>
</script>

Note:-It run only when you do php code under script tag.I have a successfully initialise php variable.

Better way to call javascript function in a tag

Neither is good.

Behaviour should be configured independent of the actual markup. For instance, in jQuery you might do something like

$('#the-element').click(function () { /* perform action here */ });

in a separate <script> block.

The advantage of this is that it

  1. Separates markup and behaviour in the same way that CSS separates markup and style
  2. Centralises configuration (this is somewhat a corollary of 1).
  3. Is trivially extensible to include more than one argument using jQuery’s powerful selector syntax

Furthermore, it degrades gracefully (but so would using the onclick event) since you can provide the link tags with a href in case the user doesn’t have JavaScript enabled.

Of course, these arguments still count if you’re not using jQuery or another JavaScript library (but why do that?).

Regex Named Groups in Java

(Update: August 2011)

As geofflane mentions in his answer, Java 7 now support named groups.
tchrist points out in the comment that the support is limited.
He details the limitations in his great answer "Java Regex Helper"

Java 7 regex named group support was presented back in September 2010 in Oracle's blog.

In the official release of Java 7, the constructs to support the named capturing group are:

  • (?<name>capturing text) to define a named group "name"
  • \k<name> to backreference a named group "name"
  • ${name} to reference to captured group in Matcher's replacement string
  • Matcher.group(String name) to return the captured input subsequence by the given "named group".

Other alternatives for pre-Java 7 were:


(Original answer: Jan 2009, with the next two links now broken)

You can not refer to named group, unless you code your own version of Regex...

That is precisely what Gorbush2 did in this thread.

Regex2

(limited implementation, as pointed out again by tchrist, as it looks only for ASCII identifiers. tchrist details the limitation as:

only being able to have one named group per same name (which you don’t always have control over!) and not being able to use them for in-regex recursion.

Note: You can find true regex recursion examples in Perl and PCRE regexes, as mentioned in Regexp Power, PCRE specs and Matching Strings with Balanced Parentheses slide)

Example:

String:

"TEST 123"

RegExp:

"(?<login>\\w+) (?<id>\\d+)"

Access

matcher.group(1) ==> TEST
matcher.group("login") ==> TEST
matcher.name(1) ==> login

Replace

matcher.replaceAll("aaaaa_$1_sssss_$2____") ==> aaaaa_TEST_sssss_123____
matcher.replaceAll("aaaaa_${login}_sssss_${id}____") ==> aaaaa_TEST_sssss_123____ 

(extract from the implementation)

public final class Pattern
    implements java.io.Serializable
{
[...]
    /**
     * Parses a group and returns the head node of a set of nodes that process
     * the group. Sometimes a double return system is used where the tail is
     * returned in root.
     */
    private Node group0() {
        boolean capturingGroup = false;
        Node head = null;
        Node tail = null;
        int save = flags;
        root = null;
        int ch = next();
        if (ch == '?') {
            ch = skip();
            switch (ch) {

            case '<':   // (?<xxx)  look behind or group name
                ch = read();
                int start = cursor;
[...]
                // test forGroupName
                int startChar = ch;
                while(ASCII.isWord(ch) && ch != '>') ch=read();
                if(ch == '>'){
                    // valid group name
                    int len = cursor-start;
                    int[] newtemp = new int[2*(len) + 2];
                    //System.arraycopy(temp, start, newtemp, 0, len);
                    StringBuilder name = new StringBuilder();
                    for(int i = start; i< cursor; i++){
                        name.append((char)temp[i-1]);
                    }
                    // create Named group
                    head = createGroup(false);
                    ((GroupTail)root).name = name.toString();

                    capturingGroup = true;
                    tail = root;
                    head.next = expr(tail);
                    break;
                }

CodeIgniter: How to use WHERE clause and OR clause

Active record method or_where is to be used:

$this->db->select("*")
->from("table_name")
->where("first", $first)
->or_where("second", $second);

delete map[key] in go?

Copied from Go 1 release notes

In the old language, to delete the entry with key k from the map represented by m, one wrote the statement,

m[k] = value, false

This syntax was a peculiar special case, the only two-to-one assignment. It required passing a value (usually ignored) that is evaluated but discarded, plus a boolean that was nearly always the constant false. It did the job but was odd and a point of contention.

In Go 1, that syntax has gone; instead there is a new built-in function, delete. The call

delete(m, k)

will delete the map entry retrieved by the expression m[k]. There is no return value. Deleting a non-existent entry is a no-op.

Updating: Running go fix will convert expressions of the form m[k] = value, false into delete(m, k) when it is clear that the ignored value can be safely discarded from the program and false refers to the predefined boolean constant. The fix tool will flag other uses of the syntax for inspection by the programmer.

What is the question mark for in a Typescript parameter name

parameter?: type is a shorthand for parameter: type | undefined

'LIKE ('%this%' OR '%that%') and something=else' not working

Try something like:

WHERE (column LIKE '%this%' OR column LIKE '%that%') AND something = else

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

How to find out when a particular table was created in Oracle?

SELECT created
  FROM dba_objects
 WHERE object_name = <<your table name>>
   AND owner = <<owner of the table>>
   AND object_type = 'TABLE'

will tell you when a table was created (if you don't have access to DBA_OBJECTS, you could use ALL_OBJECTS instead assuming you have SELECT privileges on the table).

The general answer to getting timestamps from a row, though, is that you can only get that data if you have added columns to track that information (assuming, of course, that your application populates the columns as well). There are various special cases, however. If the DML happened relatively recently (most likely in the last couple hours), you should be able to get the timestamps from a flashback query. If the DML happened in the last few days (or however long you keep your archived logs), you could use LogMiner to extract the timestamps but that is going to be a very expensive operation particularly if you're getting timestamps for many rows. If you build the table with ROWDEPENDENCIES enabled (not the default), you can use

SELECT scn_to_timestamp( ora_rowscn ) last_modified_date,
       ora_rowscn last_modified_scn,
       <<other columns>>
  FROM <<your table>>

to get the last modification date and SCN (system change number) for the row. By default, though, without ROWDEPENDENCIES, the SCN is only at the block level. The SCN_TO_TIMESTAMP function also isn't going to be able to map SCN's to timestamps forever.

How to change the color of winform DataGridview header?

dataGridView1.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;

remove inner shadow of text input

Set border: 1px solid black to make all sides equals and remove any kind of custom border (other than solid). Also, set box-shadow: none to remove any inset shadow applied to it.

Android - Start service on boot

Your Service may be getting shut down before it completes due to the device going to sleep after booting. You need to obtain a wake lock first. Luckily, the Support library gives us a class to do this:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        // This is the Intent to deliver to our service.
        Intent service = new Intent(context, SimpleWakefulService.class);

        // Start the service, keeping the device awake while it is launching.
        Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
        startWakefulService(context, service);
    }
}

then, in your Service, make sure to release the wake lock:

    @Override
    protected void onHandleIntent(Intent intent) {
        // At this point SimpleWakefulReceiver is still holding a wake lock
        // for us.  We can do whatever we need to here and then tell it that
        // it can release the wakelock.

...
        Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
        SimpleWakefulReceiver.completeWakefulIntent(intent);
    }

Don't forget to add the WAKE_LOCK permission:

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

How to add a default include path for GCC in Linux?

Create an alias for gcc with your favorite includes.

alias mygcc='gcc -I /whatever/'

Is there any way to set environment variables in Visual Studio Code?

As it does not answer your question but searching vm arguments I stumbled on this page and there seem to be no other. So if you want to pass vm arguments its like so

{
  "version": "0.2.0",
  "configurations": [
    {
      "type": "java",
      "name": "ddtBatch",
      "request": "launch",
      "mainClass": "com.something.MyApplication",
      "projectName": "MyProject",
      "args": "Hello",
      "vmArgs": "-Dspring.config.location=./application.properties"
    }
  ]
}

How to determine if a decimal/double is an integer?

There are any number of ways to do this. For example:

double d = 5.0;
bool isInt = d == (int)d;

You can also use modulo.

double d = 5.0;
bool isInt = d % 1 == 0;

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

Change Twitter Bootstrap Tooltip content on click

With Tooltip object Boostrap :

$(element).attr('data-original-title', 'New value');
$(element).data('bs.tooltip').tip().find('.tooltip-inner').text('New value');

Print out the values of a (Mat) matrix in OpenCV C++

I think using the matrix.at<type>(x,y) is not the best way to iterate trough a Mat object! If I recall correctly matrix.at<type>(x,y) will iterate from the beginning of the matrix each time you call it(I might be wrong though). I would suggest using cv::MatIterator_

cv::Mat someMat(1, 4, CV_64F, &someData);;
cv::MatIterator_<double> _it = someMat.begin<double>();
for(;_it!=someMat.end<double>(); _it++){
    std::cout << *_it << std::endl;
}

Mapping US zip code to time zone

There's actually a great Google API for this. It takes in a location and returns the timezone for that location. Should be simple enough to create a bash or python script to get the results for each address in a CSV file or database then save the timezone information.

https://developers.google.com/maps/documentation/timezone/start

Request Endpoint:

https://maps.googleapis.com/maps/api/timezone/json?location=38.908133,-77.047119&timestamp=1458000000&key=YOUR_API_KEY

Response:

{
   "dstOffset" : 3600,
   "rawOffset" : -18000,
   "status" : "OK",
   "timeZoneId" : "America/New_York",
   "timeZoneName" : "Eastern Daylight Time"
}

Asynchronous Function Call in PHP

Nowadays, it's better to use queues than threads (for those who don't use Laravel there are tons of other implementations out there like this).

The basic idea is, your original PHP script puts tasks or jobs into a queue. Then you have queue job workers running elsewhere, taking jobs out of the queue and starts processing them independently of the original PHP.

The advantages are:

  1. Scalability - you can just add worker nodes to keep up with demand. In this way, tasks are run in parallel.
  2. Reliability - modern queue managers such as RabbitMQ, ZeroMQ, Redis, etc, are made to be extremely reliable.

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

How to parse a string into a nullable int

I suggest code bellow. You may work with exception, when convert error occured.

public static class Utils {      
public static bool TryParse<Tin, Tout>(this Tin obj, Func<Tin, Tout> onConvert, Action<Tout> onFill, Action<Exception> onError) {
  Tout value = default(Tout);
  bool ret = true;
  try {
    value = onConvert(obj);
  }
  catch (Exception exc) {
    onError(exc);
    ret = false;
  }
  if (ret)
    onFill(value);
  return ret;
}

public static bool TryParse(this string str, Action<int?> onFill, Action<Exception> onError) {
  return Utils.TryParse(str
    , s => string.IsNullOrEmpty(s) ? null : (int?)int.Parse(s)
    , onFill
    , onError);
}
public static bool TryParse(this string str, Action<int> onFill, Action<Exception> onError) {
  return Utils.TryParse(str
    , s => int.Parse(s)
    , onFill
    , onError);
}
}

Use this extension method in code (fill int? Age property of a person class):

string ageStr = AgeTextBox.Text;
Utils.TryParse(ageStr, i => person.Age = i, exc => { MessageBox.Show(exc.Message); });

OR

AgeTextBox.Text.TryParse(i => person.Age = i, exc => { MessageBox.Show(exc.Message); });

Python dictionary : TypeError: unhashable type: 'list'

The error you gave is due to the fact that in python, dictionary keys must be immutable types (if key can change, there will be problems), and list is a mutable type.

Your error says that you try to use a list as dictionary key, you'll have to change your list into tuples if you want to put them as keys in your dictionary.

According to the python doc :

The only types of values not acceptable as keys are values containing lists or dictionaries or other mutable types that are compared by value rather than by object identity, the reason being that the efficient implementation of dictionaries requires a key’s hash value to remain constant

How to call external url in jquery?

Hi url should be calling a function which in return will give response

$.ajax({
url:'function to call url',
...
...

});

try using/calling API facebook method

How do I kill background processes / jobs when my shell script exits?

A nice version that works under Linux, BSD and MacOS X. First tries to send SIGTERM, and if it doesn't succeed, kills the process after 10 seconds.

KillJobs() {
    for job in $(jobs -p); do
            kill -s SIGTERM $job > /dev/null 2>&1 || (sleep 10 && kill -9 $job > /dev/null 2>&1 &)

    done
}

TrapQuit() {
    # Whatever you need to clean here
    KillJobs
}

trap TrapQuit EXIT

Please note that jobs does not include grand children processes.

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

Pan & Zoom Image

I also tried this answer but was not entirely happy with the result. I kept googling around and finally found a Nuget Package that helped me to manage the result I wanted, anno 2021. I would like to share it with the former developers of Stack Overflow.

I used this Nuget Package Gu.WPF.Geometry found via this Github Repository. All credits for develoment should go to Johan Larsson, the owner of this package.

How I used it? I wanted to have the commands as buttons below the zoombox, as shown here in MachineLayoutControl.xaml .

<UserControl
   x:Class="MyLib.MachineLayoutControl"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   xmlns:csmachinelayoutdrawlib="clr-namespace:CSMachineLayoutDrawLib"
   xmlns:effects="http://gu.se/Geometry">
   <UserControl.Resources>
       <ResourceDictionary Source="Resources/ResourceDictionaries/AllResourceDictionariesCombined.xaml" />
   </UserControl.Resources>

   <Grid Margin="0">
       <Grid.RowDefinitions>
           <RowDefinition Height="*" />
           <RowDefinition Height="Auto" />
       </Grid.RowDefinitions>

       <Border
           Grid.Row="0"
           Margin="0,0"
           Padding="0"
           BorderThickness="1"
           Style="{StaticResource Border_Head}"
           Visibility="Visible">
           <effects:Zoombox
               x:Name="ImageBox"
               IsManipulationEnabled="True"
               MaxZoom="10"
               MinZoom="0.1"
               Visibility="{Binding Zoombox_Visibility}">
               <ContentControl Content="{Binding Viewing_Canvas}" />
           </effects:Zoombox>
       </Border>
           <StackPanel
               Grid.Column="1"
               Margin="10"
               HorizontalAlignment="Right"
               Orientation="Horizontal">
               <Button
                   Command="effects:ZoomCommands.Increase"
                   CommandParameter="2.0"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom In"
                   Style="{StaticResource StyleForResizeButtons}" />

               <Button
                   Command="effects:ZoomCommands.Decrease"
                   CommandParameter="2.0"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom Out"
                   Style="{StaticResource StyleForResizeButtons}" />

               <Button
                   Command="effects:ZoomCommands.Uniform"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="See Full Machine"
                   Style="{StaticResource StyleForResizeButtons}" />

               <Button
                   Command="effects:ZoomCommands.UniformToFill"
                   CommandTarget="{Binding ElementName=ImageBox}"
                   Content="Zoom To Machine Width"
                   Style="{StaticResource StyleForResizeButtons}" />
   
           </StackPanel>

</Grid>
</UserControl>

In the underlying Viewmodel, I had the following relevant code:

public Visibility Zoombox_Visibility { get => movZoombox_Visibility; set { movZoombox_Visibility = value; OnPropertyChanged(nameof(Zoombox_Visibility)); } }
public Canvas Viewing_Canvas { get => mdvViewing_Canvas; private set => mdvViewing_Canvas = value; }

Also, I wanted that immediately on loading, the Uniform to Fill Command was executed, this is something that I managed to do in the code-behind MachineLayoutControl.xaml.cs . You see that I only set the Zoombox to visible if the command is executed, to avoid "flickering" when the usercontrol is loading.

    public partial class MachineLayoutControl : UserControl
    {
        #region Constructors

        public MachineLayoutControl()
        {
            InitializeComponent();
            Loaded += MyWindow_Loaded;
        }

        #endregion Constructors

        #region EventHandlers

        private void MyWindow_Loaded(object sender, RoutedEventArgs e)
        {
            Application.Current.Dispatcher.BeginInvoke(
               DispatcherPriority.ApplicationIdle,
               new Action(() =>
               {
                   ZoomCommands.Uniform.Execute(null, ImageBox);
                   ((MachineLayoutControlViewModel)DataContext).Zoombox_Visibility = Visibility.Visible;
               }));
        }

        #endregion EventHandlers
    }

Result

C++ JSON Serialization

For that you need reflection in C/C++ language, that doesn't exists. You need to have some meta data describing the structure of your classes (members, inherited base classes). For the moment C/C++ compilers doesn't provide automatically that information in built binaries.

I had the same idea in mind, and I used GCC XML project to get this information. It outputs XML data describing class structures. I have built a project and I'm explaining some key points in this page :

Serialization is easy, but we have to deal with complex data structure implementations (std::string, std::map for example) that play with allocated buffers. Deserialization is more complex and you need to rebuild your object with all its members, plus references to vtables ... a painful implementation.

For example you can serialize like that :

    // Random class initialization
    com::class1* aObject = new com::class1();

    for (int i=0; i<10; i++){
            aObject->setData(i,i);
    }      

    aObject->pdata = new char[7];
    for (int i=0; i<7; i++){
            aObject->pdata[i] = 7-i;
    }
    // dictionary initialization
    cjson::dictionary aDict("./data/dictionary.xml");

    // json transformation
    std::string aJson = aDict.toJson<com::class1>(aObject);

    // print encoded class
    cout << aJson << std::endl ;

To deserialize data it works like that:

    // decode the object
    com::class1* aDecodedObject = aDict.fromJson<com::class1>(aJson);

    // modify data
    aDecodedObject->setData(4,22);

    // json transformation
    aJson = aDict.toJson<com::class1>(aDecodedObject);

    // print encoded class
    cout << aJson << std::endl ;

Ouptuts:

>:~/cjson$ ./main
{"_index":54,"_inner":  {"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,4,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
{"_index":54,"_inner":{"_ident":"test","pi":3.141593},"_name":"first","com::class0::_type":"type","com::class0::data":[0,1,2,3,22,5,6,7,8,9],"com::classb::_ref":"ref","com::classm1::_type":"typem1","com::classm1::pdata":[7,6,5,4,3,2,1]}
>:~/cjson$ 

Usually these implementations are compiler dependent (ABI Specification for example), and requires external description to work (GCCXML output), such are not really easy to integrate to projects.

How to avoid the "divide by zero" error in SQL?

This seemed to be the best fix for my situation when trying to address dividing by zero, which does happen in my data.

Suppose you want to calculate the male–female ratios for various school clubs, but you discover that the following query fails and issues a divide-by-zero error when it tries to calculate ratio for the Lord of the Rings Club, which has no women:

SELECT club_id, males, females, males/females AS ratio
  FROM school_clubs;

You can use the function NULLIF to avoid division by zero. NULLIF compares two expressions and returns null if they are equal or the first expression otherwise.

Rewrite the query as:

SELECT club_id, males, females, males/NULLIF(females, 0) AS ratio
  FROM school_clubs;

Any number divided by NULL gives NULL, and no error is generated.

How to add pandas data to an existing csv file?

A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.

from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
     file_to=open(path,mode)
     yield file_to
     file_to.close()


##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
      saved_df.to_csv('yourcsv.csv',mode='a',header=False)`

How to implement 2D vector array?

I use this piece of code . works fine for me .copy it and run on your computer. you'll understand by yourself .

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    vector <vector <int> > matrix;
    size_t row=3 , col=3 ;
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            vector <int> colVector ;
            matrix.push_back(colVector) ;
            matrix.at(i).push_back(cnt++) ;
        }
    }
    matrix.at(1).at(1) = 0;     //matrix.at(columns).at(rows) = intValue 
    //printing all elements
    for(int i=0,cnt=1 ; i<row ; i++)
    {
        for(int j=0 ; j<col ; j++)
        {
            cout<<matrix[i][j] <<" " ;
        }
        cout<<endl ;
    }
}

How to bind RadioButtons to an enum?

You can create the radio buttons dynamically, ListBox can help you do that, without converters, quite simple.

The concrete steps are below:

  • create a ListBox and set the ItemsSource for the listbox as the enum MyLovelyEnum and binding the SelectedItem of the ListBox to the VeryLovelyEnum property.
  • then the Radio Buttons for each ListBoxItem will be created.
  • Step 1: add the enum to static resources for your Window, UserControl or Grid etc.
    <Window.Resources>
        <ObjectDataProvider MethodName="GetValues"
                            ObjectType="{x:Type system:Enum}"
                            x:Key="MyLovelyEnum">
            <ObjectDataProvider.MethodParameters>
                <x:Type TypeName="local:MyLovelyEnum" />
            </ObjectDataProvider.MethodParameters>
        </ObjectDataProvider>
    </Window.Resources>
  • Step 2: Use the List Box and Control Template to populate each item inside as Radio button
    <ListBox ItemsSource="{Binding Source={StaticResource MyLovelyEnum}}" SelectedItem="{Binding VeryLovelyEnum, Mode=TwoWay}" >
        <ListBox.Resources>
            <Style TargetType="{x:Type ListBoxItem}">
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <RadioButton
                                Content="{TemplateBinding ContentPresenter.Content}"
                                IsChecked="{Binding Path=IsSelected,
                                RelativeSource={RelativeSource TemplatedParent},
                                Mode=TwoWay}" />
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </ListBox.Resources>
    </ListBox>

The advantage is: if someday your enum class changes, you do not need to update the GUI (XAML file).

References: https://brianlagunas.com/a-better-way-to-data-bind-enums-in-wpf/

Sorting a Python list by two fields

employees.sort(key = lambda x:x[1])
employees.sort(key = lambda x:x[0])

We can also use .sort with lambda 2 times because python sort is in place and stable. This will first sort the list according to the second element, x[1]. Then, it will sort the first element, x[0] (highest priority).

employees[0] = Employee's Name
employees[1] = Employee's Salary

This is equivalent to doing the following: employees.sort(key = lambda x:(x[0], x[1]))

python pandas remove duplicate columns

Transposing is inefficient for large DataFrames. Here is an alternative:

def duplicate_columns(frame):
    groups = frame.columns.to_series().groupby(frame.dtypes).groups
    dups = []
    for t, v in groups.items():
        dcols = frame[v].to_dict(orient="list")

        vs = dcols.values()
        ks = dcols.keys()
        lvs = len(vs)

        for i in range(lvs):
            for j in range(i+1,lvs):
                if vs[i] == vs[j]: 
                    dups.append(ks[i])
                    break

    return dups       

Use it like this:

dups = duplicate_columns(frame)
frame = frame.drop(dups, axis=1)

Edit

A memory efficient version that treats nans like any other value:

from pandas.core.common import array_equivalent

def duplicate_columns(frame):
    groups = frame.columns.to_series().groupby(frame.dtypes).groups
    dups = []

    for t, v in groups.items():

        cs = frame[v].columns
        vs = frame[v]
        lcs = len(cs)

        for i in range(lcs):
            ia = vs.iloc[:,i].values
            for j in range(i+1, lcs):
                ja = vs.iloc[:,j].values
                if array_equivalent(ia, ja):
                    dups.append(cs[i])
                    break

    return dups

How to get first and last element in an array in java?

// Array of doubles
double[] array_doubles = {2.5, 6.2, 8.2, 4846.354, 9.6};

// First position
double firstNum = array_doubles[0]; // 2.5

// Last position
double lastNum = array_doubles[array_doubles.length - 1]; // 9.6

This is the same in any array.

Centering brand logo in Bootstrap Navbar

Updated 2018

Bootstrap 3

See if this example helps: http://bootply.com/mQh8DyRfWY

The brand is centered using..

.navbar-brand
{
    position: absolute;
    width: 100%;
    left: 0;
    top: 0;
    text-align: center;
    margin: auto;
}

Your markup is for Bootstrap 2, not 3. There is no longer a navbar-inner.

EDIT - Another approach is using transform: translateX(-50%);

.navbar-brand {
  transform: translateX(-50%);
  left: 50%;
  position: absolute;
}

http://www.bootply.com/V7vKDfk46G

Bootstrap 4

In Bootstrap 4, mx-auto or flexbox can be used to center the brand and other elements. See How to position navbar contents in Bootstrap 4 for an explanation.

Also see:

Bootstrap NavBar with left, center or right aligned items

Laravel 5 not finding css files

In the root path create a .htaccess file with

<IfModule mod_rewrite.c>
Options +FollowSymLinks
RewriteEngine On

RewriteCond %{REQUEST_URI} !^/public/ 

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f



RewriteRule ^(.*)$ /public/$1 
#RewriteRule ^ index.php [L]
RewriteRule ^(/)?$ public/index.php [L] 
</IfModule>

In public directory create a .htaccess file

<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>

    RewriteEngine On

    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

if you have done any changes in public/index.php file correct them with the right path then your site will be live.

what will solve with this?

  • Hosting issue of laravel project.
  • Css not work on laravel.
  • Laravel site not work.
  • laravel site load with domain/public/index.php
  • laravel project does not redirect correctly

Timer function to provide time in nano seconds using C++

I'm using Borland code here is the code ti_hund gives me some times a negativnumber but timing is fairly good.

#include <dos.h>

void main() 
{
struct  time t;
int Hour,Min,Sec,Hun;
gettime(&t);
Hour=t.ti_hour;
Min=t.ti_min;
Sec=t.ti_sec;
Hun=t.ti_hund;
printf("Start time is: %2d:%02d:%02d.%02d\n",
   t.ti_hour, t.ti_min, t.ti_sec, t.ti_hund);
....
your code to time
...

// read the time here remove Hours and min if the time is in sec

gettime(&t);
printf("\nTid Hour:%d Min:%d Sec:%d  Hundreds:%d\n",t.ti_hour-Hour,
                             t.ti_min-Min,t.ti_sec-Sec,t.ti_hund-Hun);
printf("\n\nAlt Ferdig Press a Key\n\n");
getch();
} // end main

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

No shadow by default on Toolbar?

You can't use the elevation attribute before API 21 (Android Lollipop). You can however add the shadow programmatically, for example using a custom view placed below the Toolbar.

@layout/toolbar

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/blue"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

<View
    android:id="@+id/toolbar_shadow"
    android:layout_width="match_parent"
    android:layout_height="3dp"
    android:background="@drawable/toolbar_dropshadow" />

@drawable/toolbar_dropshadow

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
    <gradient
        android:startColor="@android:color/transparent"
        android:endColor="#88333333"
        android:angle="90"/> </shape>

in your activity layout <include layout="@layout/toolbar" />

enter image description here

Laravel - check if Ajax request

To check an ajax request you can use if (Request::ajax())

Note: If you are using laravel 5, then in the controller replace

use Illuminate\Http\Request;

with

use Request; 

I hope it'll work.

How to get Url Hash (#) from server side

Probably the only choice is to read it on the client side and transfer it manually to the server (GET/POST/AJAX). Regards Artur

You may see also how to play with back button and browser history at Malcan

How do I get time of a Python program's execution?

time.clock()

Deprecated since version 3.3: The behavior of this function depends on the platform: use perf_counter() or process_time() instead, depending on your requirements, to have a well-defined behavior.

time.perf_counter()

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide.

time.process_time()

Return the value (in fractional seconds) of the sum of the system and user CPU time of the current process. It does not include time elapsed during sleep.

start = time.process_time()
... do something
elapsed = (time.process_time() - start)

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

JQuery: How to get selected radio button value?

To get the value of the selected Radio Button, Use RadioButtonName and the Form Id containing the RadioButton.

$('input[name=radioName]:checked', '#myForm').val()

OR by only

$('form input[type=radio]:checked').val();

Video file formats supported in iPhone

Quoting the iPhone OS Technology Overview:

iPhone OS provides support for full-screen video playback through the Media Player framework (MediaPlayer.framework). This framework supports the playback of movie files with the .mov, .mp4, .m4v, and .3gp filename extensions and using the following compression standards:

  • H.264 video, up to 1.5 Mbps, 640 by 480 pixels, 30 frames per second, Low-Complexity version of the H.264 Baseline Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • H.264 video, up to 768 Kbps, 320 by 240 pixels, 30 frames per second, Baseline Profile up to Level 1.3 with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • MPEG-4 video, up to 2.5 Mbps, 640 by 480 pixels, 30 frames per second, Simple Profile with AAC-LC audio up to 160 Kbps, 48kHz, stereo audio in .m4v, .mp4, and .mov file formats
  • Numerous audio formats, including the ones listed in “Audio Technologies”

For information about the classes of the Media Player framework, see Media Player Framework Reference.

what is trailing whitespace and how can I handle this?

Trailing whitespace:

It is extra spaces (and tabs) at the end of line      
                                                 ^^^^^ here

Strip them:

#!/usr/bin/env python2
"""\
strip trailing whitespace from file
usage: stripspace.py <file>
"""

import sys

if len(sys.argv[1:]) != 1:
  sys.exit(__doc__)

content = ''
outsize = 0
inp = outp = sys.argv[1]
with open(inp, 'rb') as infile:
  content = infile.read()
with open(outp, 'wb') as output:
  for line in content.splitlines():
    newline = line.rstrip(" \t")
    outsize += len(newline) + 1
    output.write(newline + '\n')

print("Done. Stripped %s bytes." % (len(content)-outsize))

https://gist.github.com/techtonik/c86f0ea6a86ed3f38893

Beginner Python Practice?

Try Project Euler:

Project Euler is a series of challenging mathematical/computer programming problems that will require more than just mathematical insights to solve. Although mathematics will help you arrive at elegant and efficient methods, the use of a computer and programming skills will be required to solve most problems.

The problem is:

Add all the natural numbers below 1000 that are multiples of 3 or 5.

This question will probably introduce you to Python for-loops and the range() builtin function in the least. It might lead you to discover list comprehensions, or generator expressions and the sum() builtin function.

Canvas width and height in HTML5

A canvas has 2 sizes, the dimension of the pixels in the canvas (it's backingstore or drawingBuffer) and the display size. The number of pixels is set using the the canvas attributes. In HTML

<canvas width="400" height="300"></canvas>

Or in JavaScript

someCanvasElement.width = 400;
someCanvasElement.height = 300;

Separate from that are the canvas's CSS style width and height

In CSS

canvas {  /* or some other selector */
   width: 500px;
   height: 400px;
}

Or in JavaScript

canvas.style.width = "500px";
canvas.style.height = "400px";

The arguably best way to make a canvas 1x1 pixels is to ALWAYS USE CSS to choose the size then write a tiny bit of JavaScript to make the number of pixels match that size.

function resizeCanvasToDisplaySize(canvas) {
   // look up the size the canvas is being displayed
   const width = canvas.clientWidth;
   const height = canvas.clientHeight;

   // If it's resolution does not match change it
   if (canvas.width !== width || canvas.height !== height) {
     canvas.width = width;
     canvas.height = height;
     return true;
   }

   return false;
}

Why is this the best way? Because it works in most cases without having to change any code.

Here's a full window canvas:

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { display: block; width: 100vw; height: 100vh; }
_x000D_
<canvas id="c"></canvas>
_x000D_
_x000D_
_x000D_

And Here's a canvas as a float in a paragraph

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width  / spacing + 1;_x000D_
  const down   = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y <= down; ++y) {_x000D_
    for (let x = 0; x <= across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
span { _x000D_
   width: 250px; _x000D_
   height: 100px; _x000D_
   float: left; _x000D_
   padding: 1em 1em 1em 0;_x000D_
   display: inline-block;_x000D_
}_x000D_
canvas {_x000D_
   width: 100%;_x000D_
   height: 100%;_x000D_
}
_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim <span class="diagram"><canvas id="c"></canvas></span>_x000D_
vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
<br/><br/>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>
_x000D_
_x000D_
_x000D_

Here's a canvas in a sizable control panel

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
_x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}_x000D_
_x000D_
// ----- the code above related to the canvas does not change ----_x000D_
// ---- the code below is related to the slider ----_x000D_
const $ = document.querySelector.bind(document);_x000D_
const left = $(".left");_x000D_
const slider = $(".slider");_x000D_
let dragging;_x000D_
let lastX;_x000D_
let startWidth;_x000D_
_x000D_
slider.addEventListener('mousedown', e => {_x000D_
 lastX = e.pageX;_x000D_
 dragging = true;_x000D_
});_x000D_
_x000D_
window.addEventListener('mouseup', e => {_x000D_
 dragging = false;_x000D_
});_x000D_
_x000D_
window.addEventListener('mousemove', e => {_x000D_
  if (dragging) {_x000D_
    const deltaX = e.pageX - lastX;_x000D_
    left.style.width = left.clientWidth + deltaX + "px";_x000D_
    lastX = e.pageX;_x000D_
  }_x000D_
});
_x000D_
body { _x000D_
  margin: 0;_x000D_
}_x000D_
.frame {_x000D_
  display: flex;_x000D_
  align-items: space-between;_x000D_
  height: 100vh;_x000D_
}_x000D_
.left {_x000D_
  width: 70%;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
}  _x000D_
canvas {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
}_x000D_
pre {_x000D_
  padding: 1em;_x000D_
}_x000D_
.slider {_x000D_
  width: 10px;_x000D_
  background: #000;_x000D_
}_x000D_
.right {_x000D_
  flex 1 1 auto;_x000D_
}
_x000D_
<div class="frame">_x000D_
  <div class="left">_x000D_
     <canvas id="c"></canvas>_x000D_
  </div>_x000D_
  <div class="slider">_x000D_
  _x000D_
  </div>_x000D_
  <div class="right">_x000D_
     <pre>_x000D_
* controls_x000D_
* go _x000D_
* here_x000D_
_x000D_
&lt;- drag this_x000D_
     </pre>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

here's a canvas as a background

_x000D_
_x000D_
const ctx = document.querySelector("#c").getContext("2d");_x000D_
_x000D_
function render(time) {_x000D_
  time *= 0.001;_x000D_
  resizeCanvasToDisplaySize(ctx.canvas);_x000D_
 _x000D_
  ctx.fillStyle = "#DDE";_x000D_
  ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height);_x000D_
  ctx.save();_x000D_
 _x000D_
  const spacing = 64;_x000D_
  const size = 48;_x000D_
  const across = ctx.canvas.width / spacing + 1;_x000D_
  const down = ctx.canvas.height / spacing + 1;_x000D_
  const s = Math.sin(time);_x000D_
  const c = Math.cos(time);_x000D_
  for (let y = 0; y < down; ++y) {_x000D_
    for (let x = 0; x < across; ++x) {_x000D_
      ctx.setTransform(c, -s, s, c, x * spacing, y * spacing);_x000D_
      ctx.strokeRect(-size / 2, -size / 2, size, size);_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  ctx.restore();_x000D_
  _x000D_
  requestAnimationFrame(render);_x000D_
}_x000D_
requestAnimationFrame(render);_x000D_
_x000D_
function resizeCanvasToDisplaySize(canvas) {_x000D_
   // look up the size the canvas is being displayed_x000D_
   const width = canvas.clientWidth;_x000D_
   const height = canvas.clientHeight;_x000D_
_x000D_
   // If it's resolution does not match change it_x000D_
   if (canvas.width !== width || canvas.height !== height) {_x000D_
     canvas.width = width;_x000D_
     canvas.height = height;_x000D_
     return true;_x000D_
   }_x000D_
_x000D_
   return false;_x000D_
}
_x000D_
body { margin: 0; }_x000D_
canvas { _x000D_
  display: block; _x000D_
  width: 100vw; _x000D_
  height: 100vh;  _x000D_
  position: fixed;_x000D_
}_x000D_
#content {_x000D_
  position: absolute;_x000D_
  margin: 0 1em;_x000D_
  font-size: xx-large;_x000D_
  font-family: sans-serif;_x000D_
  font-weight: bold;_x000D_
  text-shadow: 2px  2px 0 #FFF, _x000D_
              -2px -2px 0 #FFF,_x000D_
              -2px  2px 0 #FFF,_x000D_
               2px -2px 0 #FFF;_x000D_
}
_x000D_
<canvas id="c"></canvas>_x000D_
<div id="content">_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Praesent cursus venenatis metus. Mauris ac nibh at odio scelerisque scelerisque. Donec ut enim vel urna gravida imperdiet id ac odio. Aenean congue hendrerit eros id facilisis. In vitae leo ullamcorper, aliquet leo a, vehicula magna. Proin sollicitudin vestibulum aliquet. Sed et varius justo._x000D_
</p>_x000D_
<p>_x000D_
Quisque tempor metus in porttitor placerat. Nulla vehicula sem nec ipsum commodo, at tincidunt orci porttitor. Duis porttitor egestas dui eu viverra. Sed et ipsum eget odio pharetra semper. Integer tempor orci quam, eget aliquet velit consectetur sit amet. Maecenas maximus placerat arcu in varius. Morbi semper, quam a ullamcorper interdum, augue nisl sagittis urna, sed pharetra lectus ex nec elit. Nullam viverra lacinia tellus, bibendum maximus nisl dictum id. Phasellus mauris quam, rutrum ut congue non, hendrerit sollicitudin urna._x000D_
</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Because I didn't set the attributes the only thing that changed in each sample is the CSS (as far as the canvas is concerned)

Notes:

  • Don't put borders or padding on a canvas element. Computing the size to subtract from the number of dimensions of the element is troublesome

Ignore .classpath and .project from Git

Add the below lines in .gitignore and place the file inside ur project folder

/target/
/.classpath
/*.project
/.settings
/*.springBeans

Displaying Total in Footer of GridView and also Add Sum of columns(row vise) in last Column

     <asp:TemplateField HeaderText="ExEmp" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"
                                                                    FooterStyle-BackColor="BurlyWood" FooterStyle-HorizontalAlign="Center">
                                                                    <ItemTemplate>
                                                                        <asp:TextBox ID="txtNoOfExEmp" runat="server" CssClass="form-control input-sm m-bot15"
                                                                            Font-Bold="true" onkeypress="return isNumberKey(event)" Text='<%#Bind("ExEmp") %>'></asp:TextBox>
                                                                    </ItemTemplate>
                                                                    <HeaderStyle HorizontalAlign="Center"></HeaderStyle>
                                                                    <ItemStyle HorizontalAlign="Center" Width="50px" />
                                                                    <FooterTemplate>
                                                                        <asp:Label ID="lblTotNoOfExEmp" Font-Bold="true" runat="server" Text="0" CssClass="form-label"></asp:Label>
                                                                    </FooterTemplate>
                                                                </asp:TemplateField>


 private void TotalExEmpOFMonth()
    {
        Label lbl_TotNoOfExEmp = (Label)GrdPFRecord.FooterRow.FindControl("lblTotNoOfExEmp");
        /*Sum of the  Total Amount Of month*/
        foreach (GridViewRow gvr in GrdPFRecord.Rows)
        {
            TextBox txt_NoOfExEmp = (TextBox)gvr.FindControl("txtNoOfExEmp");
            lbl_TotNoOfExEmp.Text = (Convert.ToDouble(txt_NoOfExEmp.Text) + Convert.ToDouble(lbl_TotNoOfExEmp.Text)).ToString();
            lbl_TotNoOfExEmp.Text = string.Format("{0:F0}", Decimal.Parse(lbl_TotNoOfExEmp.Text));



        }
    }

check if file exists on remote host with ssh

Here is a simple approach:

#!/bin/bash
USE_IP='-o StrictHostKeyChecking=no [email protected]'

FILE_NAME=/home/user/file.txt

SSH_PASS='sshpass -p password-for-remote-machine'

if $SSH_PASS ssh $USE_IP stat $FILE_NAME \> /dev/null 2\>\&1
            then
                    echo "File exists"
            else
                    echo "File does not exist"

fi

You need to install sshpass on your machine to work it.

Client on Node.js: Uncaught ReferenceError: require is not defined

Even using this won't work. I think the best solution is Browserify:

module.exports = {
  func1: function () {
   console.log("I am function 1");
  },
  func2: function () {
    console.log("I am function 2");
  }
};

-getFunc1.js-
var common = require('./common');
common.func1();

Set NA to 0 in R

A solution using mutate_all from dplyr in case you want to add that to your dplyr pipeline:

library(dplyr)
df %>%
  mutate_all(funs(ifelse(is.na(.), 0, .)))

Result:

   A B C
1  0 0 0
2  1 0 0
3  2 0 2
4  3 0 5
5  0 0 2
6  0 0 1
7  1 0 1
8  2 0 5
9  3 0 2
10 0 0 4
11 0 0 3
12 1 0 5
13 2 0 5
14 3 0 0
15 0 0 1

If in any case you only want to replace the NA's in numeric columns, which I assume it might be the case in modeling, you can use mutate_if:

library(dplyr)
df %>%
  mutate_if(is.numeric, funs(ifelse(is.na(.), 0, .)))

or in base R:

replace(is.na(df), 0)

Result:

   A    B C
1  0    0 0
2  1 <NA> 0
3  2    0 2
4  3 <NA> 5
5  0    0 2
6  0 <NA> 1
7  1    0 1
8  2 <NA> 5
9  3    0 2
10 0 <NA> 4
11 0    0 3
12 1 <NA> 5
13 2    0 5
14 3 <NA> 0
15 0    0 1

Update

with dplyr 1.0.0, across is introduced:

library(dplyr)
# Replace `NA` for all columns
df %>%
  mutate(across(everything(), ~ ifelse(is.na(.), 0, .)))

# Replace `NA` for numeric columns
df %>%
  mutate(across(where(is.numeric), ~ ifelse(is.na(.), 0, .)))

Data:

set.seed(123)
df <- data.frame(A=rep(c(0:3, NA), 3), 
                 B=rep(c("0", NA), length.out = 15), 
                 C=sample(c(0:5, NA), 15, replace = TRUE))

How to write to an existing excel file without overwriting data (using pandas)?

Here is a helper function:

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None

    (c) [MaxU](https://stackoverflow.com/users/5741205/maxu?tab=profile)
    """
    from openpyxl import load_workbook

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist 
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError


    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)
        
        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)
        
        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()
            

NOTE: for Pandas < 0.21.0, replace sheet_name with sheetname!

Usage examples:

append_df_to_excel('d:/temp/test.xlsx', df)

append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)

append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False)

append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False, startrow=25)

What are the -Xms and -Xmx parameters when starting JVM?

The question itself has already been addressed above. Just adding part of the default values.

As per http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

The default value of Xmx will depend on platform and amount of memory available in the system.

Detect all Firefox versions in JS

This will detect any version of Firefox:

var isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') > -1;

more specifically:

if(navigator.userAgent.toLowerCase().indexOf('firefox') > -1){
     // Do Firefox-related activities
}

You may want to consider using feature-detection ala Modernizr, or a related tool, to accomplish what you need.

Laravel 5.2 Missing required parameters for [Route: user.profile] [URI: user/{nickname}/profile]

Route::group(['middleware' => 'web'], function () {
Route::auth();

Route::get('/', ['as' => 'home', 'uses' => 'BaseController@index']);

Route::group(['namespace' => 'User', 'prefix' => 'user'], function(){
    Route::get('{nickname}/settings', ['as' => 'user.settings', 'uses' => 'SettingsController@index']);
    Route::get('{nickname}/profile', ['as' => 'user.profile', 'uses' => 'ProfileController@index']);
});
});

How to open a web server port on EC2 instance

You need to open TCP port 8787 in the ec2 Security Group. Also need to open the same port on the EC2 instance's firewall.

Compilation error: stray ‘\302’ in program etc

The explanations given here are correct. I just wanted to add that this problem might be because you copied the code from somewhere, from a website or a pdf file due to which there are some invalid characters in the code.

Try to find those invalid characters, or just retype the code if you can't. It will definitely compile then.

Source: stray error reason

Database corruption with MariaDB : Table doesn't exist in engine

Something has deleted your ibdata1 file where InnoDB keeps the dictionary. Definitely it's not MySQL who does it.

UPDATE: I made a tutorial on how to fix the error - https://youtu.be/014KbCYayuE

How get sound input from microphone in python, and process it on the fly?

I know it's an old question, but if someone is looking here again... see https://python-sounddevice.readthedocs.io/en/0.4.1/index.html .

It has a nice example "Input to Ouput Pass-Through" here https://python-sounddevice.readthedocs.io/en/0.4.1/examples.html#input-to-output-pass-through .

... and a lot of other examples as well ...

Sql Server : How to use an aggregate function like MAX in a WHERE clause

You could use a sub query...

WHERE t1.field3 = (SELECT MAX(st1.field3) FROM table1 AS st1)

But I would actually move this out of the where clause and into the join statement, as an AND for the ON clause.

RS256 vs HS256: What's the difference?

short answer, specific to OAuth2,

  • HS256 user client secret to generate the token signature and same secret is required to validate the token in back-end. So you should have a copy of that secret in your back-end server to verify the signature.
  • RS256 use public key encryption to sign the token.Signature(hash) will create using private key and it can verify using public key. So, no need of private key or client secret to store in back-end server, but back-end server will fetch the public key from openid configuration url in your tenant (https://[tenant]/.well-known/openid-configuration) to verify the token. KID parameter inside the access_toekn will use to detect the correct key(public) from openid-configuration.

Numpy - Replace a number with NaN

A[A==NDV]=numpy.nan

A==NDV will produce a boolean array that can be used as an index for A

How to hide reference counts in VS2013?

I guess you probably are running the preview of VS2013 Ultimate, because it is not present in my professional preview. But looking online I found that the feature is called Code Information Indicators or CodeLens, and can be located under

Tools ? Options ? Text Editor ? All Languages ? CodeLens

(for RC/final version)

or

Tools ? Options ? Text Editor ? All Languages ? Code Information Indicators

(for preview version)

That was according to this link. It seems to be pretty well hidden.

In Visual Studio 2013 RTM, you can also get to the CodeLens options by right clicking the indicators themselves in the editor:

editor options

documented in the Q&A section of the msdn CodeLens documentation

How to change webservice url endpoint?

I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.

<wsdl:service name="serviceMethodName_2">
  <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
    <soap:address location="http://new_end_point_adress"/>
  </wsdl:port>
</wsdl:service>

This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).

pandas read_csv index_col=None not working with delimiters at the end of each line

Re: craigts's response, for anyone having trouble with using either False or None parameters for index_col, such as in cases where you're trying to get rid of a range index, you can instead use an integer to specify the column you want to use as the index. For example:

df = pd.read_csv('file.csv', index_col=0)

The above will set the first column as the index (and not add a range index in my "common case").

Update

Given the popularity of this answer, I thought i'd add some context/ a demo:

# Setting up the dummy data
In [1]: df = pd.DataFrame({"A":[1, 2, 3], "B":[4, 5, 6]})

In [2]: df
Out[2]:
   A  B
0  1  4
1  2  5
2  3  6

In [3]: df.to_csv('file.csv', index=None)
File[3]:
A  B
1  4
2  5
3  6

Reading without index_col or with None/False will all result in a range index:

In [4]: pd.read_csv('file.csv')
Out[4]:
   A  B
0  1  4
1  2  5
2  3  6

# Note that this is the default behavior, so the same as In [4]
In [5]: pd.read_csv('file.csv', index_col=None)
Out[5]:
   A  B
0  1  4
1  2  5
2  3  6

In [6]: pd.read_csv('file.csv', index_col=False)
Out[6]:
   A  B
0  1  4
1  2  5
2  3  6

However, if we specify that "A" (the 0th column) is actually the index, we can avoid the range index:

In [7]: pd.read_csv('file.csv', index_col=0)
Out[7]:
   B
A
1  4
2  5
3  6

Winforms issue - Error creating window handle

I added a check that makes it work...

if (_form.Handle.ToInt32() > 0)
{
   _form.Invoke(method, args);
}

it is always true, but the form throws an error without it. BTW, my handle is around 4.9 million

How to locate the Path of the current project directory in Java (IDE)?

What about System.getProperty("user.dir")? It'll give you the working directory from where your program was launched.

See System Properties from the Java Tutorial for an overview of Java's System Properties.

Is it possible to overwrite a function in PHP

I would include all functions of one case in an include file, and the others in another include.

For instance simple.inc would contain function boofoo() { simple } and really.inc would contain function boofoo() { really }

It helps the readability / maintenance of your program, having all functions of the same kind in the same inc.

Then at the top of your main module

  if ($_GET['foolevel'] == 10) {
    include "really.inc";
  }
  else {
    include "simple.inc";
  }

How to use _CRT_SECURE_NO_WARNINGS

For a quick fix or test, I find it handy just adding #define _CRT_SECURE_NO_WARNINGS to the top of the file before all #include

#define _CRT_SECURE_NO_WARNINGS
#include ...
int main(){
    //...
}

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Run PowerShell command from command prompt (no ps1 script)

Run it on a single command line like so:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile 
  -WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath> 
  -Recurse -FileType <type>"

How to delete duplicate rows in SQL Server?

Deleting duplicates from a huge(several millions of records) table might take long time . I suggest that you do a bulk insert into a temp table of the selected rows rather than deleting.

--REWRITING YOUR CODE(TAKE NOTE OF THE 3RD LINE) WITH CTE AS(SELECT NAME,ROW_NUMBER() 
OVER (PARTITION BY NAME ORDER BY NAME) ID FROM @TB) SELECT * INTO #unique_records FROM 
CTE WHERE ID =1;

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

Calling Javascript from a html form

Remove javascript: from onclick=".., onsubmit=".. declarations

javascript: prefix is used only in href="" or similar attributes (not events related)

Java HashMap: How to get a key and value by index?

Here is the general solution if you really only want the first key's value

Object firstKey = myHashMap.keySet().toArray()[0];
Object valueForFirstKey = myHashMap.get(firstKey);

How to generate random number with the specific length in python

You could create a function who consumes an list of int, transforms in string to concatenate and cast do int again, something like this:

import random

def generate_random_number(length):
    return int(''.join([str(random.randint(0,10)) for _ in range(length)]))

Mipmap drawables for icons

It seems Google have updated their docs since all these answers, so hopefully this will help someone else in future :) Just came across this question myself, while creating a new (new new) project.

TL;DR: drawables may be stripped out as part of dp-specific resource optimisation. Mipmaps will not be stripped.

Different home screen launcher apps on different devices show app launcher icons at various resolutions. When app resource optimization techniques remove resources for unused screen densities, launcher icons can wind up looking fuzzy because the launcher app has to upscale a lower-resolution icon for display. To avoid these display issues, apps should use the mipmap/ resource folders for launcher icons. The Android system preserves these resources regardless of density stripping, and ensures that launcher apps can pick icons with the best resolution for display.

(from http://developer.android.com/tools/projects/index.html#mipmap)

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

The first line of every source file of your project must be the following:

#include <stdafx.h>

Visit here to understand Precompiled Headers

Java getHours(), getMinutes() and getSeconds()

Try this:

Calendar calendar = Calendar.getInstance();
calendar.setTime(yourdate);
int hours = calendar.get(Calendar.HOUR_OF_DAY);
int minutes = calendar.get(Calendar.MINUTE);
int seconds = calendar.get(Calendar.SECOND);

Edit:

hours, minutes, seconds

above will be the hours, minutes and seconds after converting yourdate to System Timezone!

Hash table runtime complexity (insert, search and delete)

Ideally, a hashtable is O(1). The problem is if two keys are not equal, however they result in the same hash.

For example, imagine the strings "it was the best of times it was the worst of times" and "Green Eggs and Ham" both resulted in a hash value of 123.

When the first string is inserted, it's put in bucket 123. When the second string is inserted, it would see that a value already exists for bucket 123. It would then compare the new value to the existing value, and see they are not equal. In this case, an array or linked list is created for that key. At this point, retrieving this value becomes O(n) as the hashtable needs to iterate through each value in that bucket to find the desired one.

For this reason, when using a hash table, it's important to use a key with a really good hash function that's both fast and doesn't often result in duplicate values for different objects.

Make sense?

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

ddd is a graphical front-end to gdb that is pretty nice. One of the down sides is a classic X interface, but I seem to recall it being pretty intuitive.

How to change the color of an image on hover

If the icon is from Font Awesome (https://fontawesome.com/icons/) then you could tap into the color css property to change it's background.

fb-icon{
color:none;
}

fb-icon:hover{
color:#0000ff;
}

This is irrespective of the color it had. So you could use an entirely different color in its usual state and define another in its active state.

Android refresh current activity

this is what worked for me as seen here.

Just use it or add it to a static class helper and just call it from anywher in your project.

/**
Current Activity instance will go through its lifecycle to onDestroy() and a new instance then created after it.
*/
@SuppressLint("NewApi")
  public static final void recreateActivityCompat(final Activity a) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
      a.recreate();
    } else {
      final Intent intent = a.getIntent();
      intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
      a.finish();
      a.overridePendingTransition(0, 0);
      a.startActivity(intent);
      a.overridePendingTransition(0, 0);
   }
}

Check if all values of array are equal

I think the simplest way to do this is to create a loop to compare the each value to the next. As long as there is a break in the "chain" then it would return false. If the first is equal to the second, the second equal to the third and so on, then we can conclude that all elements of the array are equal to each other.

given an array data[], then you can use:

for(x=0;x<data.length - 1;x++){
    if (data[x] != data[x+1]){
        isEqual = false;            
    }
}
alert("All elements are equal is " + isEqual);

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

This is Chrome's hint to tell you that if you type $0 on the console, it will be equivalent to that specific element.

Internally, Chrome maintains a stack, where $0 is the selected element, $1 is the element that was last selected, $2 would be the one that was selected before $1 and so on.

Here are some of its applications:

  • Accessing DOM elements from console: $0
  • Accessing their properties from console: $0.parentElement
  • Updating their properties from console: $1.classList.add(...)
  • Updating CSS elements from console: $0.styles.backgroundColor="aqua"
  • Triggering CSS events from console: $0.click()
  • And doing a lot more complex stuffs, like: $0.appendChild(document.createElement("div"))

Watch all of this in action:

enter image description here

Backing statement:

Yes, I agree there are better ways to perform these actions, but this feature can come out handy in certain intricate scenarios, like when a DOM element needs to be clicked but it is not possible to do so from the UI because it is covered by other elements or, for some reason, is not visible on UI at that moment.

What are the "standard unambiguous date" formats for string-to-date conversion in R?

This is documented behavior. From ?as.Date:

format: A character string. If not specified, it will try '"%Y-%m-%d"' then '"%Y/%m/%d"' on the first non-'NA' element, and give an error if neither works.

as.Date("01 Jan 2000") yields an error because the format isn't one of the two listed above. as.Date("01/01/2000") yields an incorrect answer because the date isn't in one of the two formats listed above.

I take "standard unambiguous" to mean "ISO-8601" (even though as.Date isn't that strict, as "%m/%d/%Y" isn't ISO-8601).

If you receive this error, the solution is to specify the format your date (or datetimes) are in, using the formats described in ?strptime. Be sure to use particular care if your data contain day/month names and/or abbreviations, as the conversion will depend on your locale (see the examples in ?strptime and read ?LC_TIME).

Bootstrap Alert Auto Close

I found this to be a better solution

$(".alert-dismissible").fadeTo(2000, 500).slideUp(500, function(){
    $(".alert-dismissible").alert('close');
});

What is duck typing?

I see a lot of answers that repeat the old idiom:

If it looks like a duck and quacks like a duck, it's a duck

and then dive into an explanation of what you can do with duck typing, or an example which seems to obfuscate the concept further.

I don't find that much help.

This is the best attempt at a plain english answer about duck typing that I have found:

Duck Typing means that an object is defined by what it can do, not by what it is.

This means that we are less concerned with the class/type of an object and more concerned with what methods can be called on it and what operations can be performed on it. We don't care about it's type, we care about what it can do.

PHP write file from input to txt

If you use file_put_contents you don't need to do a fopen -> fwrite -> fclose, the file_put_contents does all that for you. You should also check if the webserver has write rights in the directory where you are trying to write your "data.txt" file.

Depending on your PHP version (if it's old) you might not have the file_get/put_contents functions. Check your webserver log to see if any error appeared when you executed the script.

NSRange to Range<String.Index>

As of Swift 4 (Xcode 9), the Swift standard library provides methods to convert between Swift string ranges (Range<String.Index>) and NSString ranges (NSRange). Example:

let str = "abc"
let r1 = str.range(of: "")!

// String range to NSRange:
let n1 = NSRange(r1, in: str)
print((str as NSString).substring(with: n1)) // 

// NSRange back to String range:
let r2 = Range(n1, in: str)!
print(str[r2]) // 

Therefore the text replacement in the text field delegate method can now be done as

func textField(_ textField: UITextField,
               shouldChangeCharactersIn range: NSRange,
               replacementString string: String) -> Bool {

    if let oldString = textField.text {
        let newString = oldString.replacingCharacters(in: Range(range, in: oldString)!,
                                                      with: string)
        // ...
    }
    // ...
}

(Older answers for Swift 3 and earlier:)

As of Swift 1.2, String.Index has an initializer

init?(_ utf16Index: UTF16Index, within characters: String)

which can be used to convert NSRange to Range<String.Index> correctly (including all cases of Emojis, Regional Indicators or other extended grapheme clusters) without intermediate conversion to an NSString:

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        let from16 = advance(utf16.startIndex, nsRange.location, utf16.endIndex)
        let to16 = advance(from16, nsRange.length, utf16.endIndex)
        if let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

This method returns an optional string range because not all NSRanges are valid for a given Swift string.

The UITextFieldDelegate delegate method can then be written as

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

    if let swRange = textField.text.rangeFromNSRange(range) {
        let newString = textField.text.stringByReplacingCharactersInRange(swRange, withString: string)
        // ...
    }
    return true
}

The inverse conversion is

extension String {
    func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
        let utf16view = self.utf16
        let from = String.UTF16View.Index(range.startIndex, within: utf16view) 
        let to = String.UTF16View.Index(range.endIndex, within: utf16view)
        return NSMakeRange(from - utf16view.startIndex, to - from)
    }
}

A simple test:

let str = "abc"
let r1 = str.rangeOfString("")!

// String range to NSRange:
let n1 = str.NSRangeFromRange(r1)
println((str as NSString).substringWithRange(n1)) // 

// NSRange back to String range:
let r2 = str.rangeFromNSRange(n1)!
println(str.substringWithRange(r2)) // 

Update for Swift 2:

The Swift 2 version of rangeFromNSRange() was already given by Serhii Yakovenko in this answer, I am including it here for completeness:

extension String {
    func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? {
        let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex)
        let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex)
        if let from = String.Index(from16, within: self),
            let to = String.Index(to16, within: self) {
                return from ..< to
        }
        return nil
    }
}

The Swift 2 version of NSRangeFromRange() is

extension String {
    func NSRangeFromRange(range : Range<String.Index>) -> NSRange {
        let utf16view = self.utf16
        let from = String.UTF16View.Index(range.startIndex, within: utf16view)
        let to = String.UTF16View.Index(range.endIndex, within: utf16view)
        return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to))
    }
}

Update for Swift 3 (Xcode 8):

extension String {
    func nsRange(from range: Range<String.Index>) -> NSRange {
        let from = range.lowerBound.samePosition(in: utf16)
        let to = range.upperBound.samePosition(in: utf16)
        return NSRange(location: utf16.distance(from: utf16.startIndex, to: from),
                       length: utf16.distance(from: from, to: to))
    }
}

extension String {
    func range(from nsRange: NSRange) -> Range<String.Index>? {
        guard
            let from16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location, limitedBy: utf16.endIndex),
            let to16 = utf16.index(utf16.startIndex, offsetBy: nsRange.location + nsRange.length, limitedBy: utf16.endIndex),
            let from = from16.samePosition(in: self),
            let to = to16.samePosition(in: self)
            else { return nil }
        return from ..< to
    }
}

Example:

let str = "abc"
let r1 = str.range(of: "")!

// String range to NSRange:
let n1 = str.nsRange(from: r1)
print((str as NSString).substring(with: n1)) // 

// NSRange back to String range:
let r2 = str.range(from: n1)!
print(str.substring(with: r2)) // 

How can I bring my application window to the front?

While I agree with everyone, this is no-nice behavior, here is code:

[DllImport("User32.dll")]
public static extern Int32 SetForegroundWindow(int hWnd);   


SetForegroundWindow(Handle.ToInt32());

Update

David is completely right, for completeness I include the list of conditions that must apply for this to work (+1 for David!):

  • The process is the foreground process.
  • The process was started by the foreground process.
  • The process received the last input event.
  • There is no foreground process.
  • The foreground process is being debugged.
  • The foreground is not locked (see LockSetForegroundWindow).
  • The foreground lock time-out has expired (see SPI_GETFOREGROUNDLOCKTIMEOUT in SystemParametersInfo).
  • No menus are active.

Use superscripts in R axis labels

@The Thunder Chimp You can split text in such a way that some sections are affected by super(or sub) script and others aren't through the use of *. For your example, with splitting the word "moment" from "4th" -

plot(rnorm(30), xlab = expression('4'^th*'moment'))

Is there a way to reduce the size of the git folder?

git clean -d -f -i is the best way to do it.

This will help to clean in a more controlled manner.

-i stands for interactive.

On Selenium WebDriver how to get Text from Span Tag

String kk = wd.findElement(By.xpath(//*[@id='customSelect_3']/div[1]/span));

kk.getText().toString();

System.out.println(+kk.getText().toString());

Quickest way to convert XML to JSON in Java

I found this the quick and easy way: Used: org.json.XML class from java-json.jar

if (statusCode == 200 && inputStream != null) {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
    StringBuilder responseStrBuilder = new StringBuilder();

    String inputStr;
    while ((inputStr = bufferedReader.readLine()) != null) {
        responseStrBuilder.append(inputStr);
    }

    jsonObject = XML.toJSONObject(responseStrBuilder.toString());
}

How to replace special characters in a string?

That depends on what you mean. If you just want to get rid of them, do this:
(Update: Apparently you want to keep digits as well, use the second lines in that case)

String alphaOnly = input.replaceAll("[^a-zA-Z]+","");
String alphaAndDigits = input.replaceAll("[^a-zA-Z0-9]+","");

or the equivalent:

String alphaOnly = input.replaceAll("[^\\p{Alpha}]+","");
String alphaAndDigits = input.replaceAll("[^\\p{Alpha}\\p{Digit}]+","");

(All of these can be significantly improved by precompiling the regex pattern and storing it in a constant)

Or, with Guava:

private static final CharMatcher ALNUM =
  CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z'))
  .or(CharMatcher.inRange('0', '9')).precomputed();
// ...
String alphaAndDigits = ALNUM.retainFrom(input);

But if you want to turn accented characters into something sensible that's still ascii, look at these questions:

How do I add a ToolTip to a control?

Here is your article for doing it with code

private void Form1_Load(object sender, System.EventArgs e)
{
     // Create the ToolTip and associate with the Form container.
     ToolTip toolTip1 = new ToolTip();

     // Set up the delays for the ToolTip.
     toolTip1.AutoPopDelay = 5000;
     toolTip1.InitialDelay = 1000;
     toolTip1.ReshowDelay = 500;
     // Force the ToolTip text to be displayed whether or not the form is active.
     toolTip1.ShowAlways = true;

     // Set up the ToolTip text for the Button and Checkbox.
     toolTip1.SetToolTip(this.button1, "My button1");
     toolTip1.SetToolTip(this.checkBox1, "My checkBox1");
}

Resolving IP Address from hostname with PowerShell

You could use vcsjones's solution, but this might cause problems with further ping/tracert commands, since the result is an array of addresses and you need only one.

To select the proper address, Send an ICMP echo request and read the Address property of the echo reply:

$ping = New-Object System.Net.NetworkInformation.Ping
$ip = $($ping.Send("yourhosthere").Address).IPAddressToString

Though the remarks from the documentation say:

The Address returned by any of the Send overloads can originate from a malicious remote computer. Do not connect to the remote computer using this address. Use DNS to determine the IP address of the machine to which you want to connect.

Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

Align HTML input fields by :

in my case i always put these stuffs in a p tag like

<p> name : < input type=text /> </p>

and so on and then applying the css like

p {
  text-align:left;
}

p input {
  float:right;
}

You need to specify the width of the p tag.because the input tags will float all the way right.

This css will also affect the submit button. You need to override the rule for this tag.

Object cannot be cast from DBNull to other types

Reason for the error: In an object-oriented programming language, null means the absence of a reference to an object. DBNull represents an uninitialized variant or nonexistent database column. Source:MSDN

Actual Code which I faced error:

Before changed the code:

    if( ds.Tables[0].Rows[0][0] == null ) //   Which is not working

     {
            seqno  = 1; 
      }
    else
    {
          seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
     }

After changed the code:

   if( ds.Tables[0].Rows[0][0] == DBNull.Value ) //which is working properly
        {
                    seqno  = 1; 
         }
            else
            {
                  seqno = Convert.ToInt16(ds.Tables[0].Rows[0][0]) + 1;
             }

Conclusion: when the database value return the null value, we recommend to use the DBNull class instead of just specifying as a null like in C# language.

How to send and retrieve parameters using $state.go toParams and $stateParams?

Not sure if it will work with AngularJS v1.2.0-rc.2 with ui-router v0.2.0. I have tested this solution on AngularJS v1.3.14 with ui-router v0.2.13.

I just realize that is not necessary to pass the parameter in the URL as gwhn recommends.

Just add your parameters with a default value on your state definition. Your state can still have an Url value.

$stateProvider.state('state1', {
    url : '/url',
    templateUrl : "new.html",
    controller : 'TestController',
    params: {new_param: null}
});

and add the param to $state.go()

$state.go('state1',{new_param: "Going places!"});

IF... OR IF... in a windows batch file

While dbenham's answer is pretty good, relying on IF DEFINED can get you in loads of trouble if the variable you're checking isn't an environment variable. Script variables don't get this special treatment.

While this might seem like some ludicrous undocumented BS, doing a simple shell query of IF with IF /? reveals that,

The DEFINED conditional works just like EXIST except it takes an environment variable name and returns true if the environment variable is defined.

In regards to answering this question, is there a reason to not just use a simple flag after a series of evaluations? That seems the most flexible OR check to me, both in regards to underlying logic and readability. For example:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true)
IF %some_string%=="desired result" (Set Evaluated_True=true)
IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

Obviously, they can be any sort of conditional evaluation, but I'm just sharing a few examples.

If you wanted to have it all on one line, written-wise, you could just chain them together with && like:

Set Evaluated_True=false

IF %condition_1%==true (Set Evaluated_True=true) && IF %some_string%=="desired result" (Set Evaluated_True=true) && IF %set_numerical_variable% EQ %desired_numerical_value% (Set Evaluated_True=true)

IF %Evaluated_True%==true (echo This is where you do your passing logic) ELSE (echo This is where you do your failing logic)

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

Latex Remove Spaces Between Items in List

It's easier with the enumitem package:

\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
  \item foo
  \item bar
  \item baz
\end{itemize}

Even more compact:
\begin{itemize}[noitemsep,nolistsep]
  \item foo
  \item bar
  \item baz
\end{itemize}
\end{document}

example

The enumitem package provides a lot of features to customize bullets, numbering and lengths.

The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

How do I kill the process currently using a port on localhost in Windows?

the first step

netstat -vanp tcp | grep 8888

example

tcp4     0      0    127.0.0.1.8888   *.*    LISTEN      131072 131072  76061    0
tcp46    0      0    *.8888           *.*    LISTEN      131072 131072  50523    0

the second step: find your PIDs and kill them

in my case

sudo kill -9 76061 50523

Android Left to Right slide animation

Made a sample code implementing the same with slide effects from left, right, top and bottom. (For those who dont want to make all those anim xml files :) )

Checkout out the code on github

C#: How to add subitems in ListView

I think the quickest/neatest way to do this:

For each class have string[] obj.ToListViewItem() method and then do this:

foreach(var item in personList)
{
    listView1.Items.Add(new ListViewItem(item.ToListViewItem()));
}

Here is an example definition

public class Person
{
    public string Name { get; set; }
    public string Address { get; set; }
    public DateTime DOB { get; set; }
    public uint ID { get; set; }

    public string[] ToListViewItem()
    {
        return new string[] {
            ID.ToString("000000"),
            Name,
            Address,
            DOB.ToShortDateString()
        };
    }
}

As an added bonus you can have a static method that returns ColumnHeader[] list for setting up the listview columns with

listView1.Columns.AddRange(Person.ListViewHeaders());

Validate form field only on submit or user input

Use $dirty flag to show the error only after user interacted with the input:

<div>
  <input type="email" name="email" ng-model="user.email" required />
  <span ng-show="form.email.$dirty && form.email.$error.required">Email is required</span>
</div>

If you want to trigger the errors only after the user has submitted the form than you may use a separate flag variable as in:

<form ng-submit="submit()" name="form" ng-controller="MyCtrl">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="(form.email.$dirty || submitted) && form.email.$error.required">
      Email is required
    </span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>
function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  } 
};

Then, if all that JS inside ng-showexpression looks too much for you, you can abstract it into a separate method:

function MyCtrl($scope){
  $scope.submit = function(){
    // Set the 'submitted' flag to true
    $scope.submitted = true;
    // Send the form to server
    // $http.post ...
  }

  $scope.hasError = function(field, validation){
    if(validation){
      return ($scope.form[field].$dirty && $scope.form[field].$error[validation]) || ($scope.submitted && $scope.form[field].$error[validation]);
    }
    return ($scope.form[field].$dirty && $scope.form[field].$invalid) || ($scope.submitted && $scope.form[field].$invalid);
  };

};
<form ng-submit="submit()" name="form">
  <div>
    <input type="email" name="email" ng-model="user.email" required />
    <span ng-show="hasError('email', 'required')">required</span>
  </div>

  <div>
    <button type="submit">Submit</button>
  </div>
</form>

Renaming Column Names in Pandas Groupby function

For the first question I think answer would be:

<your DataFrame>.rename(columns={'count':'Total_Numbers'})

or

<your DataFrame>.columns = ['ID', 'Region', 'Total_Numbers']

As for second one I'd say the answer would be no. It's possible to use it like 'df.ID' because of python datamodel:

Attribute references are translated to lookups in this dictionary, e.g., m.x is equivalent to m.dict["x"]

Deserialize JSON into C# dynamic object?

I am using like this in my code and it's working fine

using System.Web.Script.Serialization;
JavaScriptSerializer oJS = new JavaScriptSerializer();
RootObject oRootObject = new RootObject();
oRootObject = oJS.Deserialize<RootObject>(Your JSon String);

How do I measure the execution time of JavaScript code with callbacks?

There is a method that is designed for this. Check out process.hrtime(); .

So, I basically put this at the top of my app.

var start = process.hrtime();

var elapsed_time = function(note){
    var precision = 3; // 3 decimal places
    var elapsed = process.hrtime(start)[1] / 1000000; // divide by a million to get nano to milli
    console.log(process.hrtime(start)[0] + " s, " + elapsed.toFixed(precision) + " ms - " + note); // print message + time
    start = process.hrtime(); // reset the timer
}

Then I use it to see how long functions take. Here's a basic example that prints the contents of a text file called "output.txt":

var debug = true;
http.createServer(function(request, response) {

    if(debug) console.log("----------------------------------");
    if(debug) elapsed_time("recieved request");

    var send_html = function(err, contents) {
        if(debug) elapsed_time("start send_html()");
        response.writeHead(200, {'Content-Type': 'text/html' } );
        response.end(contents);
        if(debug) elapsed_time("end send_html()");
    }

    if(debug) elapsed_time("start readFile()");
    fs.readFile('output.txt', send_html);
    if(debug) elapsed_time("end readFile()");

}).listen(8080);

Here's a quick test you can run in a terminal (BASH shell):

for i in {1..100}; do echo $i; curl http://localhost:8080/; done

Validate SSL certificates with Python

I have added a distribution to the Python Package Index which makes the match_hostname() function from the Python 3.2 ssl package available on previous versions of Python.

http://pypi.python.org/pypi/backports.ssl_match_hostname/

You can install it with:

pip install backports.ssl_match_hostname

Or you can make it a dependency listed in your project's setup.py. Either way, it can be used like this:

from backports.ssl_match_hostname import match_hostname, CertificateError
...
sslsock = ssl.wrap_socket(sock, ssl_version=ssl.PROTOCOL_SSLv3,
                      cert_reqs=ssl.CERT_REQUIRED, ca_certs=...)
try:
    match_hostname(sslsock.getpeercert(), hostname)
except CertificateError, ce:
    ...

Bootstrap: 'TypeError undefined is not a function'/'has no method 'tab'' when using bootstrap-tabs

This can also be caused if you include bootstrap.js before jquery.js.

Others might have the same problem I did.

Include jQuery before bootstrap.

How to iterate over array of objects in Handlebars?

I meant in the template() call..

You just need to pass the results as an object. So instead of calling

var html = template(data);

do

var html = template({apidata: data});

and use {{#each apidata}} in your template code

demo at http://jsfiddle.net/KPCh4/4/
(removed some leftover if code that crashed)

Deny direct access to all .php files except index.php

Allow only 2 ip , all other will block

Order Deny,Allow
Deny from all
Allow from 173.11.227.73 108.222.245.179

Pandas sum by groupby, but exclude certain columns

The agg function will do this for you. Pass the columns and function as a dict with column, output:

df.groupby(['Country', 'Item_Code']).agg({'Y1961': np.sum, 'Y1962': [np.sum, np.mean]})  # Added example for two output columns from a single input column

This will display only the group by columns, and the specified aggregate columns. In this example I included two agg functions applied to 'Y1962'.

To get exactly what you hoped to see, included the other columns in the group by, and apply sums to the Y variables in the frame:

df.groupby(['Code', 'Country', 'Item_Code', 'Item', 'Ele_Code', 'Unit']).agg({'Y1961': np.sum, 'Y1962': np.sum, 'Y1963': np.sum})

X11/Xlib.h not found in Ubuntu

Why not try find /usr/include/X11 -name Xlib.h

If there is a hit, you have Xlib.h

If not install it using sudo apt-get install libx11-dev

and you are good to go :)

Using context in a fragment

getActivity() is a child of Context so that should work for you

Get day of week using NSDate

This code is to find the whole current week. It is written in Swift 2.0 :

var i = 2
var weekday: [String] = []
var weekdate: [String] = []
var weekmonth: [String] = []

@IBAction func buttonaction(sender: AnyObject) {

    let currentDate = NSDate()
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MMM-dd-yyyy"
    let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate)
    let weekdays = getDayOfWeek(dayOfWeekStrings)
    let calendar = NSCalendar.currentCalendar()

    while((weekdays - weekdays) + i < 9)
    {
        let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-weekdays+i), toDate: NSDate(), options: [])

        let dayFormatter = NSDateFormatter()
        dayFormatter.dateFormat = "EEEE"
        let dayOfWeekString = dayFormatter.stringFromDate(weekFirstDate!)
        weekday.append(dayOfWeekString)

        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "dd"
        let dateOfWeekString = dateFormatter.stringFromDate(weekFirstDate!)
        weekdate.append(dateOfWeekString)

        let monthFormatter = NSDateFormatter()
        monthFormatter.dateFormat = "MMMM"
        let monthOfWeekString = monthFormatter.stringFromDate(weekFirstDate!)
        weekmonth.append(monthOfWeekString)

        i++
    }

    for(var j = 0; j<7 ; j++)
    {
    let day = weekday[j]
    let date = weekdate[j]
    let month = weekmonth[j]
    var wholeweek = date + "-" + month + "(" + day + ")"
    print(wholeweek)
    }

}

func getDayOfWeek(today:String)->Int {
    let formatter  = NSDateFormatter()
    formatter.dateFormat = "MMM-dd-yyyy"
    let todayDate = formatter.dateFromString(today)!
    let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
    let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
    let daynumber = myComponents.weekday
    return daynumber
}

The output will be like this:

14March(Monday) 15March(Tuesday) 16March(Wednesday) 17March(Thursday) 18March(Friday) 19March(Saturday) 20March(Sunday)

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

When encoding query values, either form, plus or percent-20, is valid; however, since the bandwidth of the internet isn't infinite, you should use plus, since it's two fewer bytes.

When or Why to use a "SET DEFINE OFF" in Oracle Database

Here is the example:

SQL> set define off;
SQL> select * from dual where dummy='&var';

no rows selected

SQL> set define on
SQL> /
Enter value for var: X
old   1: select * from dual where dummy='&var'
new   1: select * from dual where dummy='X'

D
-
X

With set define off, it took a row with &var value, prompted a user to enter a value for it and replaced &var with the entered value (in this case, X).

How to convert a set to a list in python?

It is already a list

type(my_set)
>>> <type 'list'>

Do you want something like

my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]

EDIT : Output of your last comment

>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]

I'm wondering if you did something like this :

>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

Which characters make a URL invalid?

I need to select character to split urls in string, so I decided to create list of characters which could not be found in URL by myself:

>>> allowed = "-_.~!*'();:@&=+$,/?%#[]?@ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
>>> from string import printable
>>> ''.join(set(printable).difference(set(allowed)))
'`" <\x0b\n\r\x0c\\\t{^}|>'

So, the possible choices are the newline, tab, space, backslash and "<>{}^|. I guess I'll go with the space or newline. :)

Capitalize words in string

My solution:

String.prototype.toCapital = function () {
    return this.toLowerCase().split(' ').map(function (i) {
        if (i.length > 2) {
            return i.charAt(0).toUpperCase() + i.substr(1);
        }

        return i;
    }).join(' ');
};

Example:

'álL riGht'.toCapital();
// Returns 'Áll Right'

How Can I Override Style Info from a CSS Class in the Body of a Page?

you can test a color by writing the CSS inline like <div style="color:red";>...</div>

How to install JRE 1.7 on Mac OS X and use it with Eclipse?

Try editing your eclipse.ini file and add the following at the top

-vm
/Library/Java/JavaVirtualMachines/jdk1.7.0_09.jdk/Contents/Home

Of course the path may be slightly different, looks like I have an older version...

I'm not sure if it will add itself automatically. If not go into

Preferences --> Java --> Installed JREs

Click Add and follow the instructions there to add it

Set title background color

This code helps to change the background of the title bar programmatically in Android. Change the color to any color you want.

public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_layout);
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#1c2833")));

}

Measuring text height to be drawn on Canvas ( Android )

You must use Rect.width() and Rect.Height() which returned from getTextBounds() instead. That works for me.

Calculate the display width of a string in Java

If you just want to use AWT, then use Graphics.getFontMetrics (optionally specifying the font, for a non-default one) to get a FontMetrics and then FontMetrics.stringWidth to find the width for the specified string.

For example, if you have a Graphics variable called g, you'd use:

int width = g.getFontMetrics().stringWidth(text);

For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.

Can anonymous class implement interface?

Anonymous types can implement interfaces via a dynamic proxy.

I wrote an extension method on GitHub and a blog post http://wblo.gs/feE to support this scenario.

The method can be used like this:

class Program
{
    static void Main(string[] args)
    {
        var developer = new { Name = "Jason Bowers" };

        PrintDeveloperName(developer.DuckCast<IDeveloper>());

        Console.ReadKey();
    }

    private static void PrintDeveloperName(IDeveloper developer)
    {
        Console.WriteLine(developer.Name);
    }
}

public interface IDeveloper
{
    string Name { get; }
}

how to configuring a xampp web server for different root directory

  • Go to C:\xampp\apache\conf\httpd.conf
  • Open httpd.conf
  • Find tag : DocumentRoot "C:/xampp/htdocs"
  • Edit tag to : DocumentRoot "C:/xampp/htdocs/myproject/web"
  • Now find tag and change it to < Directory "C:/xampp/htdocs/myproject/web" >

  • Restart Your Apache

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

Whenever I'm testing something with PHP/Curl, I try it from the command line first, figure out what works, and then port my options to PHP.

Can I give a default value to parameters or optional parameters in C# functions?

This functionality is available from C# 4.0 - it was introduced in Visual Studio 2010. And you can use it in project for .NET 3.5. So there is no need to upgrade old projects in .NET 3.5 to .NET 4.0.

You have to just use Visual Studio 2010, but remember that it should compile to default language version (set it in project Properties->Buid->Advanced...)

This MSDN page has more information about optional parameters in VS 2010.

Passing variables through handlebars partial

Handlebars partials take a second parameter which becomes the context for the partial:

{{> person this}}

In versions v2.0.0 alpha and later, you can also pass a hash of named parameters:

{{> person headline='Headline'}}

You can see the tests for these scenarios: https://github.com/wycats/handlebars.js/blob/ce74c36118ffed1779889d97e6a2a1028ae61510/spec/qunit_spec.js#L456-L462 https://github.com/wycats/handlebars.js/blob/e290ec24f131f89ddf2c6aeb707a4884d41c3c6d/spec/partials.js#L26-L32

How can I lock the first row and first column of a table when scrolling, possibly using JavaScript and CSS?

Oh well, I looked up for scrollable table with fixed column to understand the need of this specific requirement and your question was one of it with no close answers..

I answered this question Large dynamically sized html table with a fixed scroll row and fixed scroll column which inspired to showcase my work as a plugin https://github.com/meetselva/fixed-table-rows-cols

The plugin basically converts a well formatted HTML table to a scrollable table with fixed table header and columns.

The usage is as below,

$('#myTable').fxdHdrCol({
    fixedCols    : 3,       /* 3 fixed columns */
    width        : "100%",  /* set the width of the container (fixed or percentage)*/
    height       : 500      /* set the height of the container */
});

You can check the demo and documentation here

How to uninstall a windows service and delete its files without rebooting

If in .net ( I'm not sure if it works for all windows services)

  • Stop the service (THis may be why you're having a problem.)
  • InstallUtil -u [name of executable]
  • Installutil -i [name of executable]
  • Start the service again...

Unless I'm changing the service's public interface, I often deploy upgraded versions of my services without even unistalling/reinstalling... ALl I do is stop the service, replace the files and restart the service again...

iPhone system font

Swift

You should always use the system defaults and not hard coding the font name because the default font could be changed by Apple at any time.

There are a couple of system default fonts(normal, bold, italic) with different sizes(label, button, others):

let font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
let font2 = UIFont.boldSystemFont(ofSize: UIFont.systemFontSize)
let font3 = UIFont.italicSystemFont(ofSize: UIFont.systemFontSize)

beaware that the default font size depends on the target view (label, button, others)

Examples:

let labelFont = UIFont.systemFont(ofSize: UIFont.labelFontSize)
let buttonFont = UIFont.systemFont(ofSize: UIFont.buttonFontSize)
let textFieldFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)

How to set width of mat-table column in angular?

we can add attribute width directly to th

eg:

<ng-container matColumnDef="position" >
    <th mat-header-cell *matHeaderCellDef width ="20%"> No. </th>
    <td mat-cell *matCellDef="let element"> {{element.position}} </td>
  </ng-container>

Python: IndexError: list index out of range

I think you mean to put the rolling of the random a,b,c, etc within the loop:

a = None # initialise
while not (a in winning_numbers):
    # keep rolling an a until you get one not in winning_numbers
    a = random.randint(1,30)
    winning_numbers.append(a)

Otherwise, a will be generated just once, and if it is in winning_numbers already, it won't be added. Since the generation of a is outside the while (in your code), if a is already in winning_numbers then too bad, it won't be re-rolled, and you'll have one less winning number.

That could be what causes your error in if guess[i] == winning_numbers[i]. (Your winning_numbers isn't always of length 5).

Finish all previous activities

If you are using startActivityForResult() in your previous activities, just override OnActivityResult() and call the finish(); method inside it in all activities.. This will do the job...

Install / upgrade gradle on Mac OS X

As mentioned in this tutorial, it's as simple as:

To install

brew install gradle

To upgrade

brew upgrade gradle

(using Homebrew of course)

Also see (finally) updated docs.

Cheers :)!

Installing OpenCV for Python on Ubuntu, getting ImportError: No module named cv2.cv

For those who are trying to use 3.1.0 but after installing python says "cv2 module not found".

You likely have python but not python-dev.

sudo apt-get install python-dev

then reinstall 3.1.0 and it'll work.

Java: print contents of text file to screen

Why hasn't anyone thought it was worth mentioning Scanner?

Scanner input = new Scanner(new File("foo.txt"));

while (input.hasNextLine())
{
   System.out.println(input.nextLine());
}

Warning: Found conflicts between different versions of the same dependent assembly

I have another way to do this if you're using Nuget to manage your dependencies. I've discovered that sometimes VS and Nuget don't match up and Nuget is unable to recognize that your projects are out of sync. The packages.config will say one thing but the path shown in References - Properties will indicate something else.

If you're willing to update your dependencies, do the following:

  1. From Solution Explorer, right click the Project and click 'Manage Nuget Packages'

  2. Select 'Installed packages' tab in left pane Record your installed packages You may want to copy your packages.config to your desktop first if you have a lot, so you can cross check it with Google to see what Nuget pkgs are installed

  3. Uninstall your packages. Its OK, we're going to add them right back.

  4. Immediately install the packages you need. What Nuget will do is not only get you the latest version, but will alter your references, and also add the binding redirects for you.

  5. Do this for all of your projects.

  6. At the solution level, do a Clean and Rebuild.

You may want to start with the lower projects and work your way to the higher level ones, and rebuild each project as you go along.

If you don't want to update your dependencies, then you can use the package manager console, and use the syntax Update-Package -ProjectName [yourProjectName] [packageName] -Version [versionNumber]

Why should we include ttf, eot, woff, svg,... in a font-face

Answer in 2019:

Only use WOFF2, or if you need legacy support, WOFF. Do not use any other format

(svg and eot are dead formats, ttf and otf are full system fonts, and should not be used for web purposes)

Original answer from 2012:

In short, font-face is very old, but only recently has been supported by more than IE.

  • eot is needed for Internet Explorers that are older than IE9 - they invented the spec, but eot was a proprietary solution.

  • ttf and otf are normal old fonts, so some people got annoyed that this meant anyone could download expensive-to-license fonts for free.

  • Time passes, SVG 1.1 adds a "fonts" chapter that explains how to model a font purely using SVG markup, and people start to use it. More time passes and it turns out that they are absolutely terrible compared to just a normal font format, and SVG 2 wisely removes the entire chapter again.

  • Then, woff gets invented by people with quite a bit of domain knowledge, which makes it possible to host fonts in a way that throws away bits that are critically important for system installation, but irrelevant for the web (making people worried about piracy happy) and allows for internal compression to better suit the needs of the web (making users and hosts happy). This becomes the preferred format.

  • 2019 edit A few years later, woff2 gets drafted and accepted, which improves the compression, leading to even smaller files, along with the ability to load a single font "in parts" so that a font that supports 20 scripts can be stored as "chunks" on disk instead, with browsers automatically able to load the font "in parts" as needed, rather than needing to transfer the entire font up front, further improving the typesetting experience.

If you don't want to support IE 8 and lower, and iOS 4 and lower, and android 4.3 or earlier, then you can just use WOFF (and WOFF2, a more highly compressed WOFF, for the newest browsers that support it.)

@font-face {
  font-family: 'MyWebFont';
  src:  url('myfont.woff2') format('woff2'),
        url('myfont.woff') format('woff');
}

Support for woff can be checked at http://caniuse.com/woff
Support for woff2 can be checked at http://caniuse.com/woff2

Exit a Script On Error

If you put set -e in a script, the script will terminate as soon as any command inside it fails (i.e. as soon as any command returns a nonzero status). This doesn't let you write your own message, but often the failing command's own messages are enough.

The advantage of this approach is that it's automatic: you don't run the risk of forgetting to deal with an error case.

Commands whose status is tested by a conditional (such as if, && or ||) do not terminate the script (otherwise the conditional would be pointless). An idiom for the occasional command whose failure doesn't matter is command-that-may-fail || true. You can also turn set -e off for a part of the script with set +e.

Command to find information about CPUs on a UNIX machine

There is no standard Unix command, AFAIK. I haven't used Sun OS, but on Linux, you can use this:

cat /proc/cpuinfo

Sorry that it is Linux, not Sun OS. There is probably something similar though for Sun OS.

Create Log File in Powershell

I've been playing with this code for a while now and I have something that works well for me. Log files are numbered with leading '0' but retain their file extension. And I know everyone likes to make functions for everything but I started to remove functions that performed 1 simple task. Why use many word when few do trick? Will likely remove other functions and perhaps create functions out of other blocks. I keep the logger script in a central share and make a local copy if it has changed, or load it from the central location if needed.

First I import the logger:

#Change directory to the script root
cd $PSScriptRoot

#Make a local copy if changed then Import logger
if(test-path "D:\Scripts\logger.ps1"){
    if (Test-Path "\\<server>\share\DCS\Scripts\logger.ps1") {
        if((Get-FileHash "\\<server>\share\DCS\Scripts\logger.ps1").Hash -ne (Get-FileHash "D:\Scripts\logger.ps1").Hash){
            rename-Item -path "..\logger.ps1" -newname "logger$(Get-Date -format 'yyyyMMdd-HH.mm.ss').ps1" -force
            Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force 
        }
    }
}else{
    Copy-Item "\\<server>\share\DCS\Scripts\logger.ps1" -destination "..\" -Force
}
. "..\logger.ps1"

Define the log file:

$logfile = (get-location).path + "\Log\" + $QProfile.replace(" ","_") + "-$metricEnv-$ScriptName.log"

What I log depends on debug levels that I created:

if ($Debug -ge 1){
    $message = "<$pid>Debug:$Debug`-Adding tag `"MetricClass:temp`" to $host_name`:$metric_name"
    Write-Log $message $logfile "DEBUG"
}

I would probably consider myself a bit of a "hack" when it comes to coding so this might not be the prettiest but here is my version of logger.ps1:

# all logging settins are here on top
param(
    [Parameter(Mandatory=$false)]
        [string]$logFile = "$(gc env:computername).log",
    [Parameter(Mandatory=$false)]
        [string]$logLevel = "DEBUG", # ("DEBUG","INFO","WARN","ERROR","FATAL")
    [Parameter(Mandatory=$false)]
        [int64]$logSize = 10mb,
    [Parameter(Mandatory=$false)]
        [int]$logCount = 25
) 
# end of settings

function Write-Log-Line ($line, $logFile) {
    $logFile | %{ 
           If (Test-Path -Path $_) { Get-Item $_ } 
           Else { New-Item -Path $_ -Force } 
    } | Add-Content -Value $Line -erroraction SilentlyCOntinue
}

function Roll-logFile
{
    #function checks to see if file in question is larger than the paramater specified if it is it will roll a log and delete the oldes log if there are more than x logs.
    param(
        [string]$fileName = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")+".log", 
        [int64]$maxSize = $logSize, 
        [int]$maxCount = $logCount
    )
    $logRollStatus = $true
    if(test-path $filename) {
        $file = Get-ChildItem $filename
        # Start the log-roll if the file is big enough

        #Write-Log-Line "$Stamp INFO Log file size is $($file.length), max size $maxSize" $logFile
        #Write-Host "$Stamp INFO Log file size is $('{0:N0}' -f $file.length), max size $('{0:N0}' -f $maxSize)"
        if($file.length -ge $maxSize) {
            Write-Log-Line "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!" $logFile
            #Write-Host "$Stamp INFO Log file size $('{0:N0}' -f $file.length) is larger than max size $('{0:N0}' -f $maxSize). Rolling log file!"
            $fileDir = $file.Directory
            $fbase = $file.BaseName
            $fext = $file.Extension
            $fn = $file.name #this gets the name of the file we started with

            function refresh-log-files {
                 Get-ChildItem $filedir | ?{ $_.Extension -match "$fext" -and $_.name -like "$fbase*"} | Sort-Object lastwritetime
            }
            function fileByIndex($index) {
                $fileByIndex = $files | ?{($_.Name).split("-")[-1].trim("$fext") -eq $($index | % tostring 00)}
                #Write-Log-Line "LOGGER: fileByIndex = $fileByIndex" $logFile
                $fileByIndex
            }
            function getNumberOfFile($theFile) {
                $NumberOfFile = $theFile.Name.split("-")[-1].trim("$fext")
                if ($NumberOfFile -match '[a-z]'){
                    $NumberOfFile = "01"
                }
                #Write-Log-Line "LOGGER: GetNumberOfFile = $NumberOfFile" $logFile
                $NumberOfFile
            }

            refresh-log-files | %{
                [int32]$num = getNumberOfFile $_
                Write-Log-Line "LOGGER: checking log file number $num" $logFile
                if ([int32]$($num | % tostring 00) -ge $maxCount) {
                    write-host "Deleting files above log max count $maxCount : $_"
                    Write-Log-Line "LOGGER: Deleting files above log max count $maxCount : $_" $logFile
                    Remove-Item $_.fullName
                }
            }

            $files = @(refresh-log-files)

            # Now there should be at most $maxCount files, and the highest number is one less than count, unless there are badly named files, eg non-numbers
            for ($i = $files.count; $i -gt 0; $i--) {
                $newfilename = "$fbase-$($i | % tostring 00)$fext"
                #$newfilename = getFileNameByNumber ($i | % tostring 00) 
                if($i -gt 1) {
                    $fileToMove = fileByIndex($i-1)
                } else {
                    $fileToMove = $file
                }
                if (Test-Path $fileToMove.PSPath) { # If there are holes in sequence, file by index might not exist. The 'hole' will shift to next number, as files below hole are moved to fill it
                    write-host "moving '$fileToMove' => '$newfilename'"
                    #Write-Log-Line "LOGGER: moving $fileToMove => $newfilename" $logFile
                    # $fileToMove is a System.IO.FileInfo, but $newfilename is a string. Move-Item takes a string, so we need full path
                    Move-Item ($fileToMove.FullName) -Destination $fileDir\$newfilename -Force
                }
            }
        } else {
            $logRollStatus = $false
        }
    } else {
        $logrollStatus = $false
    }
    $LogRollStatus
}


Function Write-Log {
    [CmdletBinding()]
    Param(
    [Parameter(Mandatory=$True)]
    [string]
    $Message,

    [Parameter(Mandatory=$False)]
    [String]
    $logFile = "log-$(gc env:computername).log",

    [Parameter(Mandatory=$False)]
    [String]
    $Level = "INFO"
    )
    #Write-Host $logFile
    $levels = ("DEBUG","INFO","WARN","ERROR","FATAL")
    $logLevelPos = [array]::IndexOf($levels, $logLevel)
    $levelPos = [array]::IndexOf($levels, $Level)
    $Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss:fff")

    # First roll the log if needed to null to avoid output
    $Null = @(
        Roll-logFile -fileName $logFile -filesize $logSize -logcount $logCount
    )

    if ($logLevelPos -lt 0){
        Write-Log-Line "$Stamp ERROR Wrong logLevel configuration [$logLevel]" $logFile
    }

    if ($levelPos -lt 0){
        Write-Log-Line "$Stamp ERROR Wrong log level parameter [$Level]" $logFile
    }

    # if level parameter is wrong or configuration is wrong I still want to see the 
    # message in log
    if ($levelPos -lt $logLevelPos -and $levelPos -ge 0 -and $logLevelPos -ge 0){
        return
    }

    $Line = "$Stamp $Level $Message"
    Write-Log-Line $Line $logFile
}

How to convert an entire MySQL database characterset and collation to UTF-8?

In case the data is not in the same character set you might consider this snippet from http://dev.mysql.com/doc/refman/5.0/en/charset-conversion.html

If the column has a nonbinary data type (CHAR, VARCHAR, TEXT), its contents should be encoded in the column character set, not some other character set. If the contents are encoded in a different character set, you can convert the column to use a binary data type first, and then to a nonbinary column with the desired character set.

Here is an example:

 ALTER TABLE t1 CHANGE c1 c1 BLOB;
 ALTER TABLE t1 CHANGE c1 c1 VARCHAR(100) CHARACTER SET utf8;

Make sure to choose the right collation, or you might get unique key conflicts. e.g. Éleanore and Eleanore might be considered the same in some collations.

Aside:

I had a situation where certain characters "broke" in emails even though they were stored as UTF-8 in the database. If you are sending emails using utf8 data, you might want to also convert your emails to send in UTF8.

In PHPMailer, just update this line: public $CharSet = 'utf-8';

How to add a new row to datagridview programmatically

//Add a list of BBDD
var item = myEntities.getList().ToList();
//Insert a new object of type in a position of the list       
item.Insert(0,(new Model.getList_Result { id = 0, name = "Coca Cola" }));

//List assigned to DataGridView
dgList.DataSource = item; 

Help with packages in java - import does not work

Okay, just to clarify things that have already been posted.

You should have the directory com, containing the directory company, containing the directory example, containing the file MyClass.java.

From the folder containing com, run:

$ javac com\company\example\MyClass.java

Then:

$ java com.company.example.MyClass
Hello from MyClass!

These must both be done from the root of the source tree. Otherwise, javac and java won't be able to find any other packages (in fact, java wouldn't even be able to run MyClass).

A short example

I created the folders "testpackage" and "testpackage2". Inside testpackage, I created TestPackageClass.java containing the following code:

package testpackage;

import testpackage2.MyClass;

public class TestPackageClass {
    public static void main(String[] args) {
        System.out.println("Hello from testpackage.TestPackageClass!");
        System.out.println("Now accessing " + MyClass.NAME);
    }
}

Inside testpackage2, I created MyClass.java containing the following code:

package testpackage2;
public class MyClass {
    public static String NAME = "testpackage2.MyClass";
}

From the directory containing the two new folders, I ran:

C:\examples>javac testpackage\*.java

C:\examples>javac testpackage2\*.java

Then:

C:\examples>java testpackage.TestPackageClass
Hello from testpackage.TestPackageClass!
Now accessing testpackage2.MyClass

Does that make things any clearer?

What's the easiest way to call a function every 5 seconds in jQuery?

You don't need jquery for this, in plain javascript, the following will work!

var intervalId = window.setInterval(function(){
  /// call your function here
}, 5000);

To stop the loop you can use

clearInterval(intervalId) 

How to force reloading php.ini file?

You also can use graceful restart the apache server with service apache2 reload or apachectl -k graceful. As the apache doc says:

The USR1 or graceful signal causes the parent process to advise the children to exit after their current request (or to exit immediately if they're not serving anything). The parent re-reads its configuration files and re-opens its log files. As each child dies off the parent replaces it with a child from the new generation of the configuration, which begins serving new requests immediately.

What is the simplest way to convert a Java string from all caps (words separated by underscores) to CamelCase (no word separators)?

Here is a code snippet which might help:

String input = "ABC_DEF";
StringBuilder sb = new StringBuilder();
for( String oneString : input.toLowerCase().split("_") )
{
    sb.append( oneString.substring(0,1).toUpperCase() );
    sb.append( oneString.substring(1) );
}

// sb now holds your desired String

Read user input inside a loop

Try to change the loop like this:

for line in $(cat filename); do
    read input
    echo $input;
done

Unit test:

for line in $(cat /etc/passwd); do
    read input
    echo $input;
    echo "[$line]"
done

How to use PHP's password_hash to hash and verify passwords

Never use md5() for securing your password, even with salt, it is always dangerous!!

Make your password secured with latest hashing algorithms as below.

<?php

// Your original Password
$password = '121@121';

//PASSWORD_BCRYPT or PASSWORD_DEFAULT use any in the 2nd parameter
/*
PASSWORD_BCRYPT always results 60 characters long string.
PASSWORD_DEFAULT capacity is beyond 60 characters
*/
$password_encrypted = password_hash($password, PASSWORD_BCRYPT);

For matching with database's encrypted password and user inputted password use the below function.

<?php 

if (password_verify($password_inputted_by_user, $password_encrypted)) {
    // Success!
    echo 'Password Matches';
}else {
    // Invalid credentials
    echo 'Password Mismatch';
}

If you want to use your own salt, use your custom generated function for the same, just follow below, but I not recommend this as It is found deprecated in latest versions of PHP.

Read about password_hash() before using below code.

<?php

$options = [
    'salt' => your_custom_function_for_salt(), 
    //write your own code to generate a suitable & secured salt
    'cost' => 12 // the default cost is 10
];

$hash = password_hash($your_password, PASSWORD_DEFAULT, $options);

foreach with index

It depends on the class you are using.

Dictionary<(Of <(TKey, TValue>)>) Class For Example Support This

The Dictionary<(Of <(TKey, TValue>)>) generic class provides a mapping from a set of keys to a set of values.

For purposes of enumeration, each item in the dictionary is treated as a KeyValuePair<(Of <(TKey, TValue>)>) structure representing a value and its key. The order in which the items are returned is undefined.

foreach (KeyValuePair kvp in myDictionary) {...}

jQuery pass more parameters into callback

For me, and other newbies who has just contacted with Javascript,
I think that the Closeure Solution is a little kind of too confusing.

While I found that, you can easilly pass as many parameters as you want to every ajax callback using jquery.

Here are two easier solutions.

First one, which @zeroasterisk has mentioned above, example:

var $items = $('.some_class');
$.each($items, function(key, item){
    var url = 'http://request_with_params' + $(item).html();
    $.ajax({
        selfDom     : $(item),
        selfData    : 'here is my self defined data',

        url         : url,
        dataType    : 'json',
        success     : function(data, code, jqXHR){
            // in $.ajax callbacks, 
            // [this] keyword references to the options you gived to $.ajax
            // if you had not specified the context of $.ajax callbacks.
            // see http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings context
            var $item = this.selfDom;
            var selfdata = this.selfData;
            $item.html( selfdata );
            ...
        } 
    });
});

Second one, pass self-defined-datas by adding them into the XHR object which exists in the whole ajax-request-response life span.

var $items = $('.some_class');
$.each($items, function(key, item){
    var url = 'http://request_with_params' + $(item).html();
    $.ajax({
        url         : url,
        dataType    : 'json',
        beforeSend  : function(XHR) {
            // ??????,???? jquery??????? XHR
            XHR.selfDom = $(item);
            XHR.selfData = 'here is my self defined data';
        },
        success     : function(data, code, jqXHR){
            // jqXHR is a superset of the browser's native XHR object
            var $item = jqXHR.selfDom;
            var selfdata = jqXHR.selfData;
            $item.html( selfdata );
            ...
        } 
    });
});

As you can see these two solutions has a drawback that : you need write a little more code every time than just write:

$.get/post (url, data, successHandler);

Read more about $.ajax : http://api.jquery.com/jquery.ajax/

Count items in a folder with PowerShell

You can also use an alias

(ls).Count

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

How to generate .angular-cli.json file in Angular Cli?

You are just outside the directory which you are working. Enter into the directory which your project is there and run command ng g c name.

Auto select file in Solution Explorer from its open tab

The best option now is to install the Microsoft Visual Studio add on called Productivity Power Tools.

With this comes "Solution Navigator" (alternative to Solution Explorer, with a lot of benefits) - which then you can use to filter the files to only show "Open". You can even filter files to show "Edited" and "Unsaved".

Copy data into another table

Simple way if new table does not exist and you want to make a copy of old table with everything then following works in SQL Server.

SELECT * INTO NewTable FROM OldTable

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

You can also add labels that are tied to your radio buttons with the same ID, which then allows the user to click the radio button or label to select that item. I'm using constants here for "Male", "Female" and "Unknown", but obviously these could be strings in your model.

<%: Html.RadioButtonFor(m => m.Gender, "Male", 
    new Dictionary<string, object> { { "checked", "checked" }, { "id", "Male" } }) %>
<%: Html.Label("Male") %>

<%: Html.RadioButtonFor(m => m.Gender, "Female", 
    new Dictionary<string, object> { { "id", "Female" } }) %>
<%: Html.Label("Female")%>

<%: Html.RadioButtonFor(m => m.Gender, "Unknown",
    new Dictionary<string, object> { { "id", "Unknown" } }) %>
<%: Html.Label("Unknown")%>

Broken references in Virtualenvs

All the answers are great here, I tried a couple of solutions mentioned above by Ryan, Chris and couldn't resolve the issue, so had to follow a quick and dirty way.

  1. rm -rf <project dir> (or mv <project dir> <backup projct dir> if you want to keep a backup)
  2. git clone <project git url>
  3. Move on!

Nothing novel here, but it makes life easier!

Programmatically scroll a UIScrollView

Here is another use case which worked well for me.

  1. User tap a button/cell.
  2. Scroll to a position just enough to make a target view visible.

Code: Swift 5.3

// Assuming you have a view named "targeView"
scrollView.scroll(to: CGPoint(x:targeView.frame.minX, y:targeView.frame.minY), animated: true)

As you can guess if you want to scroll to make a bottom part of your target view visible then use maxX and minY.

Can I get "&&" or "-and" to work in PowerShell?

I think a simple if statement can accomplish this. Once I saw mkelement0's response that the last exit status is stored in $?, I put the following together:

# Set the first command to a variable
$a=somecommand

# Temporary variable to store exit status of the last command (since we can't write to "$?")
$test=$?

# Run the test
if ($test=$true) { 2nd-command }

So for the OP's example, it would be:

a=(csc /t:exe /out:a.exe SomeFile.cs); $test = $?; if ($test=$true) { a.exe }

how to use List<WebElement> webdriver

Try with below logic

driver.get("http://www.labmultis.info/jpecka.portal-exdrazby/index.php?c1=2&a=s&aa=&ta=1");

List<WebElement> allElements=driver.findElements(By.cssSelector(".list.list-categories li"));

for(WebElement ele :allElements) {
    System.out.println("Name + Number===>"+ele.getText());
    String s=ele.getText();
    s=s.substring(s.indexOf("(")+1, s.indexOf(")"));
    System.out.println("Number==>"+s);
}

====Output======
Name + Number===>Vše (950)
Number==>950
Name + Number===>Byty (181)
Number==>181
Name + Number===>Domy (512)
Number==>512
Name + Number===>Pozemky (172)
Number==>172
Name + Number===>Chaty (28)
Number==>28
Name + Number===>Zemedelské objekty (5)
Number==>5
Name + Number===>Komercní objekty (30)
Number==>30
Name + Number===>Ostatní (22)
Number==>22

Laravel Eloquent where field is X or null

You could merge two queries together:

$merged = $query_one->merge($query_two);

How can I make a div not larger than its contents?

An working demo is here-

_x000D_
_x000D_
.floating-box {_x000D_
    display:-moz-inline-stack;_x000D_
    display: inline-block;_x000D_
_x000D_
    width: fit-content; _x000D_
    height: fit-content;_x000D_
_x000D_
    width: 150px;_x000D_
    height: 75px;_x000D_
    margin: 10px;_x000D_
    border: 3px solid #73AD21;  _x000D_
}
_x000D_
<h2>The Way is using inline-block</h2>_x000D_
_x000D_
Supporting elements are also added in CSS._x000D_
_x000D_
<div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
   <div class="floating-box">Floating box</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make vim paste from (and copy to) system's clipboard?

This would be the lines you need in your vimrc for this purpose:

set clipboard+=unnamed  " use the clipboards of vim and win
set paste               " Paste from a windows or from vim
set go+=a               " Visual selection automatically copied to the clipboard

Repeat each row of data.frame the number of times specified in a column

Another possibility is using tidyr::expand:

library(dplyr)
library(tidyr)

df %>% group_by_at(vars(-freq)) %>% expand(temp = 1:freq) %>% select(-temp)
#> # A tibble: 6 x 2
#> # Groups:   var1, var2 [3]
#>   var1  var2 
#>   <fct> <fct>
#> 1 a     d    
#> 2 b     e    
#> 3 b     e    
#> 4 c     f    
#> 5 c     f    
#> 6 c     f

One-liner version of vonjd's answer:

library(data.table)

setDT(df)[ ,list(freq=rep(1,freq)),by=c("var1","var2")][ ,freq := NULL][]
#>    var1 var2
#> 1:    a    d
#> 2:    b    e
#> 3:    b    e
#> 4:    c    f
#> 5:    c    f
#> 6:    c    f

Created on 2019-05-21 by the reprex package (v0.2.1)

Linking static libraries to other static libraries

A static library is just an archive of .o object files. Extract them with ar (assuming Unix) and pack them back into one big library.