Programs & Examples On #Comautomationfactory

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

I downloaded a project from github with .idea folder. After deleting that folder, everything was ok.

JavaScript adding decimal numbers issue

Use toFixed to convert it to a string with some decimal places shaved off, and then convert it back to a number.

+(0.1 + 0.2).toFixed(12) // 0.3

It looks like IE's toFixed has some weird behavior, so if you need to support IE something like this might be better:

Math.round((0.1 + 0.2) * 1e12) / 1e12

How can I get the current page's full URL on a Windows/IIS server?

The posttitle part of the URL is after your index.php file, which is a common way of providing friendly URLs without using mod_rewrite. The posttitle is actually therefore part of the query string, so you should be able to get it using $_SERVER['QUERY_STRING']

Using Chrome, how to find to which events are bound to an element

Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)

Google Chromes developer tools has a search function built into the scripts section

If you are unfamiliar with this tool: (just in case)

  • right click anywhere on a page (in chrome)
  • click 'Inspect Element'
  • click the 'Scripts' tab
  • Search bar in the top right

Doing a quick search for the #ID should take you to the binding function eventually.

Ex: searching for #foo would take you to

$('#foo').click(function(){ alert('bar'); })

enter image description here

How can I stage and commit all files, including newly added files, using a single command?

Not sure why these answers all dance around what I believe to be the right solution but for what it's worth here is what I use:

1. Create an alias:

git config --global alias.coa "!git add -A && git commit -m"

2. Add all files & commit with a message:

git coa "A bunch of horrible changes"

NOTE: coa is short for commit all and can be replaced with anything your heart desires

How to swap two variables in JavaScript

Swap using Bitwise

let a = 10;
let b = 20;
a ^= b;
y ^= a;
a ^= b;

Single line Swap "using Array"

[a, b] = [b, a]

How to change the project in GCP using CLI commands

I do prefer aliases, and for things that might need multiple commands, based on your project needs, I prefer functions...

Example

function switchGCPProject() {
        gcloud config set project [Project Name]
        // if you are using GKE use the following
        gcloud config set container/cluster [Cluster Name]
        // if you are using GCE use the following
        gcloud config set compute/zone [Zone]
        gcloud config set compute/region [region]
        // if you are using GKE use the following
        gcloud container clusters get-credentials [cluster name] --zone [Zone] --project [project name]
        export GOOGLE_APPLICATION_CREDENTIALS=path-to-credentials.json
}

How to Convert Datetime to Date in dd/MM/yyyy format

Give a different alias

SELECT  Convert(varchar,A.InsertDate,103) as converted_Tran_Date from table as A
order by A.InsertDate 

Why shouldn't `'` be used to escape single quotes?

If you need to write semantically correct mark-up, even in HTML5, you must not use ' to escape single quotes. Although, I can imagine you actually meant apostrophe rather then single quote.

single quotes and apostrophes are not the same, semantically, although they might look the same.

Here's one apostrophe.

Use ' to insert it if you need HTML4 support. (edited)

In British English, single quotes are used like this:

"He told me to 'give it a try'", I said.

Quotes come in pairs. You can use:

<p><q>He told me to <q>give it a try</q></q>, I said.<p>

to have nested quotes in a semantically correct way, deferring the substitution of the actual characters to the rendering engine. This substitution can then be affected by CSS rules, like:

q {
  quotes: '"' '"' '<' '>';
} 

An old but seemingly still relevant article about semantically correct mark-up: The Trouble With EM ’n EN (and Other Shady Characters).

(edited) This used to be:

Use ’ to insert it if you need HTML4 support.

But, as @James_pic pointed out, that is not the straight single quote, but the "Single curved quote, right".

Transferring files over SSH

You need to scp something somewhere. You have scp ./styles/, so you're saying secure copy ./styles/, but not where to copy it to.

Generally, if you want to download, it will go:

# download: remote -> local
scp user@remote_host:remote_file local_file 

where local_file might actually be a directory to put the file you're copying in. To upload, it's the opposite:

# upload: local -> remote
scp local_file user@remote_host:remote_file

If you want to copy a whole directory, you will need -r. Think of scp as like cp, except you can specify a file with user@remote_host:file as well as just local files.

Edit: As noted in a comment, if the usernames on the local and remote hosts are the same, then the user can be omitted when specifying a remote file.

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

System.IO.Compression is now available as a nuget package maintained by Microsoft.

To use ZipFile you need to download System.IO.Compression.ZipFile nuget package.

Formatting numbers (decimal places, thousands separators, etc) with CSS

No, you have to use javascript once it's in the DOM or format it via your language server-side (PHP/ruby/python etc.)

PHP output showing little black diamonds with a question mark

This is a charset issue. As such, it can have gone wrong on many different levels, but most likely, the strings in your database are utf-8 encoded, and you are presenting them as iso-8859-1. Or the other way around.

The proper way to fix this problem, is to get your character-sets straight. The simplest strategy, since you're using PHP, is to use iso-8859-1 throughout your application. To do this, you must ensure that:

  • All PHP source-files are saved as iso-8859-1 (Not to be confused with cp-1252).
  • Your web-server is configured to serve files with charset=iso-8859-1
  • Alternatively, you can override the webservers settings from within the PHP-document, using header.
  • In addition, you may insert a meta-tag in you HTML, that specifies the same thing, but this isn't strictly needed.
  • You may also specify the accept-charset attribute on your <form> elements.
  • Database tables are defined with encoding as latin1
  • The database connection between PHP to and database is set to latin1

If you already have data in your database, you should be aware that they are probably messed up already. If you are not already in production phase, just wipe it all and start over. Otherwise you'll have to do some data cleanup.

A note on meta-tags, since everybody misunderstands what they are:

When a web-server serves a file (A HTML-document), it sends some information, that isn't presented directly in the browser. This is known as HTTP-headers. One such header, is the Content-Type header, which specifies the mimetype of the file (Eg. text/html) as well as the encoding (aka charset). While most webservers will send a Content-Type header with charset info, it's optional. If it isn't present, the browser will instead interpret any meta-tags with http-equiv="Content-Type". It's important to realise that the meta-tag is only interpreted if the webserver doesn't send the header. In practice this means that it's only used if the page is saved to disk and then opened from there.

This page has a very good explanation of these things.

CSS3 Transition - Fade out effect

You forgot to add a position property to the .dummy-wrap class, and the top/left/bottom/right values don't apply to statically positioned elements (the default)

http://jsfiddle.net/dYBD2/2/

Ruby on Rails: Clear a cached page

rake tmp:cache:clear might be what you're looking for.

Unzipping files in Python

If you are using Python 3.2 or later:

import zipfile
with zipfile.ZipFile("file.zip","r") as zip_ref:
    zip_ref.extractall("targetdir")

You dont need to use the close or try/catch with this as it uses the context manager construction.

Set Canvas size using javascript

You can also use this script , just change the height and width

<canvas id="Canvas01" width="500" height="400" style="border:2px solid #FF9933; margin-left:10px; margin-top:10px;"></canvas>

   <script>
      var canvas = document.getElementById("Canvas01");
      var ctx = canvas.getContext("2d");

c# razor url parameter from view

You can use the following:

Request.Params["paramName"]

See also: When do Request.Params and Request.Form differ?

adding comment in .properties files

Writing the properties file with multiple comments is not supported. Why ?

PropertyFile.java

public class PropertyFile extends Task {

    /* ========================================================================
     *
     * Instance variables.
     */

    // Use this to prepend a message to the properties file
    private String              comment;

    private Properties          properties;

The ant property file task is backed by a java.util.Properties class which stores comments using the store() method. Only one comment is taken from the task and that is passed on to the Properties class to save into the file.

The way to get around this is to write your own task that is backed by commons properties instead of java.util.Properties. The commons properties file is backed by a property layout which allows settings comments for individual keys in the properties file. Save the properties file with the save() method and modify the new task to accept multiple comments through <comment> elements.

Removing an element from an Array (Java)

Nice looking solution would be to use a List instead of array in the first place.

List.remove(index)

If you have to use arrays, two calls to System.arraycopy will most likely be the fastest.

Foo[] result = new Foo[source.length - 1];
System.arraycopy(source, 0, result, 0, index);
if (source.length != index) {
    System.arraycopy(source, index + 1, result, index, source.length - index - 1);
}

(Arrays.asList is also a good candidate for working with arrays, but it doesn't seem to support remove.)

What is the difference between vmalloc and kmalloc?

What are the advantages of having a contiguous block of memory? Specifically, why would I need to have a contiguous physical block of memory in a system call? Is there any reason I couldn't just use vmalloc?

From Google's "I'm Feeling Lucky" on vmalloc:

kmalloc is the preferred way, as long as you don't need very big areas. The trouble is, if you want to do DMA from/to some hardware device, you'll need to use kmalloc, and you'll probably need bigger chunk. The solution is to allocate memory as soon as possible, before memory gets fragmented.

How to overwrite files with Copy-Item in PowerShell

Robocopy is designed for reliable copying with many copy options, file selection restart, etc.

/xf to excludes files and /e for subdirectories:

robocopy $copyAdmin $AdminPath /e /xf "web.config" "Deploy"

How do I build an import library (.lib) AND a DLL in Visual C++?

By selecting 'Class Library' you were accidentally telling it to make a .Net Library using the CLI (managed) extenstion of C++.

Instead, create a Win32 project, and in the Application Settings on the next page, choose 'DLL'.

You can also make an MFC DLL or ATL DLL from those library choices if you want to go that route, but it sounds like you don't.

Custom seekbar (thumb size, color and background)

  • First at all, use android:splitTrack="false" for the transparency problem of your thumb.

  • For the seekbar.png, you have to use a 9 patch. It would be good for the rounded border and the shadow of your image.

CURL to access a page that requires a login from a different page

The web site likely uses cookies to store your session information. When you run

curl --user user:pass https://xyz.com/a  #works ok
curl https://xyz.com/b #doesn't work

curl is run twice, in two separate sessions. Thus when the second command runs, the cookies set by the 1st command are not available; it's just as if you logged in to page a in one browser session, and tried to access page b in a different one.

What you need to do is save the cookies created by the first command:

curl --user user:pass --cookie-jar ./somefile https://xyz.com/a

and then read them back in when running the second:

curl --cookie ./somefile https://xyz.com/b

Alternatively you can try downloading both files in the same command, which I think will use the same cookies.

Mailto: Body formatting

Forget it; this might work with Outlook or maybe even GMail but you won't be able to get this working properly supporting most other E-mail clients out there (and there's a shitton of 'em).

You're better of using a simple PHP script (check out PHPMailer) or use a hosted solution (Google "email form hosted", "free email form hosting" or something similar)

By the way, you are looking for the term "Percent-encoding" (also called url-encoding and Javascript uses encodeUri/encodeUriComponent (make sure you understand the differences!)). You will need to encode a whole lot more than just newlines.

Difference between except: and except Exception as e: in Python

Using the second form gives you a variable (named based upon the as clause, in your example e) in the except block scope with the exception object bound to it so you can use the infomration in the exception (type, message, stack trace, etc) to handle the exception in a more specially tailored manor.

Remove special symbols and extra spaces and replace with underscore using the replace method

It was not asked precisely to remove accent (only special characters), but I needed to.

The solutions givens here works but they don’t remove accent: é, è, etc.

So, before doing epascarello’s solution, you can also do:

_x000D_
_x000D_
var newString = "développeur & intégrateur";_x000D_
_x000D_
newString = replaceAccents(newString);_x000D_
newString = newString.replace(/[^A-Z0-9]+/ig, "_");_x000D_
alert(newString);_x000D_
_x000D_
/**_x000D_
 * Replaces all accented chars with regular ones_x000D_
 */_x000D_
function replaceAccents(str) {_x000D_
  // Verifies if the String has accents and replace them_x000D_
  if (str.search(/[\xC0-\xFF]/g) > -1) {_x000D_
    str = str_x000D_
      .replace(/[\xC0-\xC5]/g, "A")_x000D_
      .replace(/[\xC6]/g, "AE")_x000D_
      .replace(/[\xC7]/g, "C")_x000D_
      .replace(/[\xC8-\xCB]/g, "E")_x000D_
      .replace(/[\xCC-\xCF]/g, "I")_x000D_
      .replace(/[\xD0]/g, "D")_x000D_
      .replace(/[\xD1]/g, "N")_x000D_
      .replace(/[\xD2-\xD6\xD8]/g, "O")_x000D_
      .replace(/[\xD9-\xDC]/g, "U")_x000D_
      .replace(/[\xDD]/g, "Y")_x000D_
      .replace(/[\xDE]/g, "P")_x000D_
      .replace(/[\xE0-\xE5]/g, "a")_x000D_
      .replace(/[\xE6]/g, "ae")_x000D_
      .replace(/[\xE7]/g, "c")_x000D_
      .replace(/[\xE8-\xEB]/g, "e")_x000D_
      .replace(/[\xEC-\xEF]/g, "i")_x000D_
      .replace(/[\xF1]/g, "n")_x000D_
      .replace(/[\xF2-\xF6\xF8]/g, "o")_x000D_
      .replace(/[\xF9-\xFC]/g, "u")_x000D_
      .replace(/[\xFE]/g, "p")_x000D_
      .replace(/[\xFD\xFF]/g, "y");_x000D_
  }_x000D_
_x000D_
  return str;_x000D_
}
_x000D_
_x000D_
_x000D_

Source: https://gist.github.com/jonlabelle/5375315

Can I dynamically add HTML within a div tag from C# on load event?

Use asp:Panel for that. It translates into a div.

Find duplicates and delete all in notepad++

If it is possible to change the sequence of the lines you could do:

  1. sort line with Edit -> Line Operations -> Sort Lines Lexicographically ascending
  2. do a Find / Replace:
    • Find What: ^(.*\r?\n)\1+
    • Replace with: (Nothing, leave empty)
    • Check Regular Expression in the lower left
    • Click Replace All

How it works: The sorting puts the duplicates behind each other. The find matches a line ^(.*\r?\n) and captures the line in \1 then it continues and tries to find \1 one or more times (+) behind the first match. Such a block of duplicates (if it exists) is replaced with nothing.

The \r?\n should deal nicely with Windows and Unix lineendings.

What is git tag, How to create tags & How to checkout git remote tag(s)

To get the specific tag code try to create a new branch add get the tag code in it. I have done it by command : $git checkout -b newBranchName tagName

Django ChoiceField

Better Way to Provide Choice inside a django Model :

from django.db import models

class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    GRADUATE = 'GR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
        (GRADUATE, 'Graduate'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

How to run VBScript from command line without Cscript/Wscript

Why don't you just stash the vbscript in a batch/vbscript file hybrid. Name the batch hybrid Converter.bat and you can execute it directly as Converter from the cmd line. Sure you can default ALL scripts to run from Cscript or Wscript, but if you want to execute your vbs as a windows script rather than a console script, this could cause some confusion later on. So just set your code to a batch file and run it directly.

Check the answer -> Here

And here is an example:

Converter.bat

::' VBS/Batch Hybrid
::' --- Batch portion ---------
rem^ &@echo off
rem^ &call :'sub
rem^ &exit /b

:'sub
rem^ &echo begin batch
rem^ &cscript //nologo //e:vbscript "%~f0"
rem^ &echo end batch
rem^ &exit /b

'----- VBS portion -----
Dim tester
tester = "Convert data here"
Msgbox tester

How to disable 'X-Frame-Options' response header in Spring Security?

Most likely you don't want to deactivate this Header completely, but use SAMEORIGIN. If you are using the Java Configs (Spring Boot) and would like to allow the X-Frame-Options: SAMEORIGIN, then you would need to use the following.


For older Spring Security versions:

http
   .headers()
       .addHeaderWriter(new XFrameOptionsHeaderWriter(XFrameOptionsHeaderWriter.XFrameOptionsMode.SAMEORIGIN))

For newer versions like Spring Security 4.0.2:

http
   .headers()
      .frameOptions()
         .sameOrigin();

Oracle SqlDeveloper JDK path

another thing you could try is to rename your old jdk folder, lets say its:

C:\Program Files\Java\jdk1.7.0_04

change it to saomething like:

C:\Program Files\Java\xxxjdk1.7.0_04

Now, you should once again asked to set your jdk folder location on Oracle SqlDeveloper launch, and you can chose the right path.

Not the most elegant solution, but it worked for me.

Milos

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Extracting specific columns in numpy array

One more thing you should pay attention to when selecting columns from N-D array using a list like this:

data[:,:,[1,9]]

If you are removing a dimension (by selecting only one row, for example), the resulting array will be (for some reason) permuted. So:

print data.shape            # gives [10,20,30]
selection = data[1,:,[1,9]]
print selection.shape       # gives [2,20] instead of [20,2]!!

Android, How to create option Menu

Android UI programming is a little bit tricky. To enable the Options menu, in addition to the code you wrote, we also need to call setHasOptionsMenu(true) in your overriden method OnCreate(). Hope this will help you out.

Remove Elements from a HashSet while Iterating

The reason you get a ConcurrentModificationException is because an entry is removed via Set.remove() as opposed to Iterator.remove(). If an entry is removed via Set.remove() while an iteration is being done, you will get a ConcurrentModificationException. On the other hand, removal of entries via Iterator.remove() while iteration is supported in this case.

The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.

If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.

for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
    Integer element = it.next();
    if (element % 2 == 0) {
        it.remove();
    }
}

Finding all possible combinations of numbers to reach a given sum

Here is a Java version which is well suited for small N and very large target sum, when complexity O(t*N) (the dynamic solution) is greater than the exponential algorithm. My version uses a meet in the middle attack, along with a little bit shifting in order to reduce the complexity from the classic naive O(n*2^n) to O(2^(n/2)).

If you want to use this for sets with between 32 and 64 elements, you should change the int which represents the current subset in the step function to a long although performance will obviously drastically decrease as the set size increases. If you want to use this for a set with odd number of elements, you should add a 0 to the set to make it even numbered.

import java.util.ArrayList;
import java.util.List;

public class SubsetSumMiddleAttack {
    static final int target = 100000000;
    static final int[] set = new int[]{ ... };

    static List<Subset> evens = new ArrayList<>();
    static List<Subset> odds = new ArrayList<>();

    static int[][] split(int[] superSet) {
        int[][] ret = new int[2][superSet.length / 2]; 

        for (int i = 0; i < superSet.length; i++) ret[i % 2][i / 2] = superSet[i];

        return ret;
    }

    static void step(int[] superSet, List<Subset> accumulator, int subset, int sum, int counter) {
        accumulator.add(new Subset(subset, sum));
        if (counter != superSet.length) {
            step(superSet, accumulator, subset + (1 << counter), sum + superSet[counter], counter + 1);
            step(superSet, accumulator, subset, sum, counter + 1);
        }
    }

    static void printSubset(Subset e, Subset o) {
        String ret = "";
        for (int i = 0; i < 32; i++) {
            if (i % 2 == 0) {
                if ((1 & (e.subset >> (i / 2))) == 1) ret += " + " + set[i];
            }
            else {
                if ((1 & (o.subset >> (i / 2))) == 1) ret += " + " + set[i];
            }
        }
        if (ret.startsWith(" ")) ret = ret.substring(3) + " = " + (e.sum + o.sum);
        System.out.println(ret);
    }

    public static void main(String[] args) {
        int[][] superSets = split(set);

        step(superSets[0], evens, 0,0,0);
        step(superSets[1], odds, 0,0,0);

        for (Subset e : evens) {
            for (Subset o : odds) {
                if (e.sum + o.sum == target) printSubset(e, o);
            }
        }
    }
}

class Subset {
    int subset;
    int sum;

    Subset(int subset, int sum) {
        this.subset = subset;
        this.sum = sum;
    }
}

How to make System.out.println() shorter

Some interesting alternatives:

OPTION 1

PrintStream p = System.out;
p.println("hello");

OPTION 2

PrintWriter p = new PrintWriter(System.out, true);
p.println("Hello");

Is it ok to scrape data from Google results?

Google will eventually block your IP when you exceed a certain amount of requests.

how to count length of the JSON array element

I think you should try

data = {"shareInfo":[{"id":"1","a":"sss","b":"sss","question":"whi?"},
{"id":"2","a":"sss","b":"sss","question":"whi?"},
{"id":"3","a":"sss","b":"sss","question":"whi?"},
{"id":"4","a":"sss","b":"sss","question":"whi?"}]};

ShareInfoLength = data.shareInfo.length;
alert(ShareInfoLength);
for(var i=0; i<ShareInfoLength; i++)
{
alert(Object.keys(data.shareInfo[i]).length);
}

Minimum rights required to run a windows service as a domain account

"BypassTraverseChecking" means that you can directly access any deep-level subdirectory even if you don't have all the intermediary access privileges to directories in between, i.e. all directories above it towards root level .

How to sort in-place using the merge sort algorithm?

Just for reference, here is a nice implementation of a stable in-place merge sort. Complicated, but not too bad.

I ended up implementing both a stable in-place merge sort and a stable in-place quicksort in Java. Please note the complexity is O(n (log n)^2)

When to use IMG vs. CSS background-image?

Some answers overcomplicate the scenario here. This is a dead simple situation.

Just answer to this question every time you'd like to place an image:

Is this part of the content or part of the design?

If you can't answer this, you probably don't know what you're doing or what you want to do!

Also, DO NOT consider beside the two technique, just because you'd wish to be "printer friendly" or not. Also DO NOT hide content from a SEO point of view with CSS. If you find yourself managing your content in CSS files, you shot yourself in the leg. This is just a trivial decision of what is content or not. Every other aspect should be ignored.

Create SQLite Database and table

The next link will bring you to a great tutorial, that helped me a lot!

How to SQLITE in C#

I nearly used everything in that article to create the SQLite database for my own C# Application.

Don't forget to download the SQLite.dll, and add it as a reference to your project. This can be done using NuGet and by adding the dll manually.

After you added the reference, refer to the dll from your code using the following line on top of your class:

using System.Data.SQLite;

You can find the dll's here:

SQLite DLL's

You can find the NuGet way here:

NuGet

Up next is the create script. Creating a database file:

SQLiteConnection.CreateFile("MyDatabase.sqlite");

SQLiteConnection m_dbConnection = new SQLiteConnection("Data Source=MyDatabase.sqlite;Version=3;");
m_dbConnection.Open();

string sql = "create table highscores (name varchar(20), score int)";

SQLiteCommand command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

sql = "insert into highscores (name, score) values ('Me', 9001)";

command = new SQLiteCommand(sql, m_dbConnection);
command.ExecuteNonQuery();

m_dbConnection.Close();

After you created a create script in C#, I think you might want to add rollback transactions, it is safer and it will keep your database from failing, because the data will be committed at the end in one big piece as an atomic operation to the database and not in little pieces, where it could fail at 5th of 10 queries for example.

Example on how to use transactions:

 using (TransactionScope tran = new TransactionScope())
 {
     //Insert create script here.

     //Indicates that creating the SQLiteDatabase went succesfully, so the database can be committed.
     tran.Complete();
 }

Setting top and left CSS attributes

div.style yields an object (CSSStyleDeclaration). Since it's an object, you can alternatively use the following:

div.style["top"] = "200px";
div.style["left"] = "200px";

This is useful, for example, if you need to access a "variable" property:

div.style[prop] = "200px";

Get a list of dates between two dates

We had a similar problem with BIRT reports in that we wanted to report on those days that had no data. Since there were no entries for those dates, the easiest solution for us was to create a simple table that stored all dates and use that to get ranges or join to get zero values for that date.

We have a job that runs every month to ensure that the table is populated 5 years out into the future. The table is created thus:

create table all_dates (
    dt date primary key
);

No doubt there are magical tricky ways to do this with different DBMS' but we always opt for the simplest solution. The storage requirements for the table are minimal and it makes the queries so much simpler and portable. This sort of solution is almost always better from a performance point-of-view since it doesn't require per-row calculations on the data.

The other option (and we've used this before) is to ensure there's an entry in the table for every date. We swept the table periodically and added zero entries for dates and/or times that didn't exist. This may not be an option in your case, it depends on the data stored.

If you really think it's a hassle to keep the all_dates table populated, a stored procedure is the way to go which will return a dataset containing those dates. This will almost certainly be slower since you have to calculate the range every time it's called rather than just pulling pre-calculated data from a table.

But, to be honest, you could populate the table out for 1000 years without any serious data storage problems - 365,000 16-byte (for example) dates plus an index duplicating the date plus 20% overhead for safety, I'd roughly estimate at about 14M [365,000 * 16 * 2 * 1.2 = 14,016,000 bytes]), a minuscule table in the scheme of things.

How do I disable form resizing for users?

Change this property and try this at design time:

FormBorderStyle = FormBorderStyle.FixedDialog;

Designer view before the change:

Enter image description here

Transpose a range in VBA

Strictly in reference to prefacing "transpose", by the book, either one will work; i.e., application.transpose() OR worksheetfunction.transpose(), and by experience, if you really like typing, application.WorksheetFunction.Transpose() will work also-

How To Save Canvas As An Image With canvas.toDataURL()?

I created a small library that does this (along with some other handy conversions). It's called reimg, and it's really simple to use.

ReImg.fromCanvas(yourCanvasElement).toPng()

What are the differences between type() and isinstance()?

Here's an example where isinstance achieves something that type cannot:

class Vehicle:
    pass

class Truck(Vehicle):
    pass

in this case, a truck object is a Vehicle, but you'll get this:

isinstance(Vehicle(), Vehicle)  # returns True
type(Vehicle()) == Vehicle      # returns True
isinstance(Truck(), Vehicle)    # returns True
type(Truck()) == Vehicle        # returns False, and this probably won't be what you want.

In other words, isinstance is true for subclasses, too.

Also see: How to compare type of an object in Python?

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

check whether there is a comma at the end.

                            },
                            {
                                name: '???. ??????? ?? ?????. ?3/?',
                                data: graph_high3,
                                dataGrouping: {
                                    units: groupingUnits,
                                    groupPixelWidth: 40,
                                    approximation: "average",
                                    enabled: true,
                                    units: [[
                                            'minute',
                                            [1]
                                        ]]
                                }
                            }   // if , - SCRIPT5007

Loop through checkboxes and count each one checked or unchecked

I don't think enough time was paid attention to the schema considerations brought up in the original post. So, here is something to consider for any newbies.

Let's say you went ahead and built this solution. All of your menial values are conctenated into a single value and stored in the database. You are indeed saving [a little] space in your database and some time coding.

Now let's consider that you must perform the frequent and easy task of adding a new checkbox between the current checkboxes 3 & 4. Your development manager, customer, whatever expects this to be a simple change.

So you add the checkbox to the UI (the easy part). Your looping code would already concatenate the values no matter how many checkboxes. You also figure your database field is just a varchar or other string type so it should be fine as well.

What happens when customers or you try to view the data from before the change? You're essentially serializing from left to right. However, now the values after 3 are all off by 1 character. What are you going to do with all of your existing data? Are you going write an application, pull it all back out of the database, process it to add in a default value for the new question position and then store it all back in the database? What happens when you have several new values a week or month apart? What if you move the locations and jQuery processes them in a different order? All your data is hosed and has to be reprocessed again to rearrange it.

The whole concept of NOT providing a tight key-value relationship is ludacris and will wind up getting you into trouble sooner rather than later. For those of you considering this, please don't. The other suggestions for schema changes are fine. Use a child table, more fields in the main table, a question-answer table, etc. Just don't store non-labeled data when the structure of that data is subject to change.

C# Call a method in a new thread

Asynchronous version:

private async Task DoAsync()
{
    await Task.Run(async () =>
    {
        //Do something awaitable here
    });
}

jQuery UI Slider (setting programmatically)

One part of @gaurav solution worked for jQuery 2.1.3 and JQuery UI 1.10.2 with multiple sliders. My project is using four range sliders to filter data with this filter.js plugin. Other solutions were resetting the slider handles back to their starting end points just fine, but apparently they were not firing an event that filter.js understood. So here's how I looped through the sliders:

$("yourSliderSelection").each (function () {
    var hs = $(this); 
    var options = $(this).slider('option');

    //reset the ui
    $(this).slider( 'values', [ options.min, options.max ] ); 

    //refresh/trigger event so that filter.js can reset handling the data
    hs.slider('option', 'slide').call(
        hs, 
        null, 
        {
            handle: $('.ui-slider-handle', hs),
            values: [options.min, options.max]
        }
    );

});

The hs.slider() code resets the data, but not the UI in my scenario. Hope this helps others.

Javascript: Unicode string to hex

Here is my take: these functions convert a UTF8 string to a proper HEX without the extra zeroes padding. A real UTF8 string has characters with 1, 2, 3 and 4 bytes length.

While working on this I found a couple key things that solved my problems:

  1. str.split('') doesn't handle multi-byte characters like emojis correctly. The proper/modern way to handle this is with Array.from(str)
  2. encodeURIComponent() and decodeURIComponent() are great tools to convert between string and hex. They are pretty standard, they handle UTF8 correctly.
  3. (Most) ASCII characters (codes 0 - 127) don't get URI encoded, so they need to handled separately. But c.charCodeAt(0).toString(16) works perfectly for those
    function utf8ToHex(str) {
      return Array.from(str).map(c => 
        c.charCodeAt(0) < 128 ? c.charCodeAt(0).toString(16) : 
        encodeURIComponent(c).replace(/\%/g,'').toLowerCase()
      ).join('');
    },
    function hexToUtf8: function(hex) {
      return decodeURIComponent('%' + hex.match(/.{1,2}/g).join('%'));
    }

Demo: https://jsfiddle.net/lyquix/k2tjbrvq/

How to convert comma-separated String to List?

List commaseperated = new ArrayList();
String mylist = "item1 , item2 , item3";
mylist = Arrays.asList(myStr.trim().split(" , "));

// enter code here

Javascript "Uncaught TypeError: object is not a function" associativity question

I was getting this same error and spent a day and a half trying to find a solution. Naomi's answer lead me to the solution I needed.

My input (type=button) had an attribute name that was identical to a function name that was being called by the onClick event. Once I changed the attribute name everything worked.

<input type="button" name="clearEmployer" onClick="clearEmployer();">

changed to:

<input type="button" name="clearEmployerBtn" onClick="clearEmployer();">

How do I remove the first characters of a specific column in a table?

If you have to remove the first few characters that are preceded by a special character like #, this is a good one:

UPDATE tblInvalidID
SET [ColumnName] =stuff(ColumnName, 1, charindex('#', ColumnName), ' ') 

Print a list in reverse order with range()?

because range(n) produces an iterable there are all sorts of nice things you can do which will produce the result you desire, such as:

range(n)[::-1]

if loops are ok, we can make sort of a queue:

a = []
for i in range(n):
    a.insert(0,a)
return a

or maybe use the reverse() method on it:

reverse(range(n))

JPQL SELECT between date statement

public List<Student> findStudentByReports(Date startDate, Date endDate) {
    System.out.println("call findStudentMethd******************with this pattern"
                    + startDate
                    + endDate
                    + "*********************************************");

    return em
            .createQuery(
                    "' select attendence from Attendence attendence where attendence.admissionDate BETWEEN : startDate '' AND endDate ''"
                            + "'")
            .setParameter("startDate", startDate, TemporalType.DATE)
            .setParameter("endDate", endDate, TemporalType.DATE)
            .getResultList();

}

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

Simple PowerShell commands to set this in the registry;

New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
Set-ItemProperty -Path "HKCR:\Microsoft.PowerShellScript.1\Shell\open\command" -name '(Default)' -Value '"C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -noLogo -ExecutionPolicy unrestricted -file "%1"'

Python dictionary: Get list of values for list of keys

Here are three ways.

Raising KeyError when key is not found:

result = [mapping[k] for k in iterable]

Default values for missing keys.

result = [mapping.get(k, default_value) for k in iterable]

Skipping missing keys.

result = [mapping[k] for k in iterable if k in mapping]

How to export private key from a keystore of self-signed certificate

public static void main(String[] args) {

try {
        String keystorePass = "20174";
        String keyPass = "rav@789";
        String alias = "TyaGi!";
        InputStream keystoreStream = new FileInputStream("D:/keyFile.jks");
        KeyStore keystore = KeyStore.getInstance("JCEKS");
        keystore.load(keystoreStream, keystorePass.toCharArray());
        Key key = keystore.getKey(alias, keyPass.toCharArray());

        byte[] bt = key.getEncoded();
        String s = new String(bt);
        System.out.println("------>"+s);      
        String str12 = Base64.encodeBase64String(bt);

        System.out.println("Fetched Key From JKS : " + str12);

    } catch (KeyStoreException | IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException ex) {
        System.out.println(ex);

    }
}

PHP date() with timezone?

Try this. You can pass either unix timestamp, or datetime string

public static function convertToTimezone($timestamp, $fromTimezone, $toTimezone, $format='Y-m-d H:i:s') 
    {
        $datetime = is_numeric($timestamp) ?
                    DateTime::createFromFormat ('U' , $timestamp, new DateTimeZone($fromTimezone)) :
                    new DateTime($timestamp, new DateTimeZone($fromTimezone));

        $datetime->setTimezone(new DateTimeZone($toTimezone));

        return $datetime->format($format);
    }

How to add ASP.NET 4.0 as Application Pool on IIS 7, Windows 7

Chances are you need to install .NET 4 (Which will also create a new AppPool for you)

First make sure you have IIS installed then perform the following steps:

  1. Open your command prompt (Windows + R) and type cmd and press ENTER
    You may need to start this as an administrator if you have UAC enabled.
    To do so, locate the exe (usually you can start typing with Start Menu open), right click and select "Run as Administrator"
  2. Type cd C:\Windows\Microsoft.NET\Framework\v4.0.30319\ and press ENTER.
  3. Type aspnet_regiis.exe -ir and press ENTER again.
    • If this is a fresh version of IIS (no other sites running on it) or you're not worried about the hosted sites breaking with a framework change you can use -i instead of -ir. This will change their AppPools for you and steps 5-on shouldn't be necessary.
    • at this point you will see it begin working on installing .NET's framework in to IIS for you
  4. Close the DOS prompt, re-open your start menu and right click Computer and select Manage
  5. Expand the left-hand side (Services and Applications) and select Internet Information Services
    • You'll now have a new applet within the content window exclusively for IIS.
  6. Expand out your computer and locate the Application Pools node, and select it. (You should now see ASP.NET v4.0 listed)
  7. Expand out your Sites node and locate the site you want to modify (select it)
  8. To the right you'll notice Basic Settings... just below the Edit Site text. Click this, and a new window should appear
  9. Select the .NET 4 AppPool using the Select... button and click ok.
  10. Restart the site, and you should be good-to-go.

(You can repeat steps 7-on for every site you want to apply .NET 4 on as well).


Additional References:

  1. .NET 4 Framework
    The framework for those that don't already have it.
  2. How do I run a command with elevated privileges?
    Directions on how to run the command prompt with Administrator rights.
  3. aspnet_regiis.exe options
    For those that might want to know what -ir or -i does (or the difference between them) or what other options are available. (I typically use -ir to prevent any older sites currently running from breaking on a framework change but that's up to you.)

ImportError: No module named dateutil.parser

None of the solutions worked for me. If you are using PIP do:

pip install pycrypto==2.6.1

How to remove the first and the last character of a string

Here you go

_x000D_
_x000D_
var yourString = "/installers/";_x000D_
var result = yourString.substring(1, yourString.length-1);_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Or you can use .slice as suggested by Ankit Gupta

_x000D_
_x000D_
var yourString = "/installers/services/";_x000D_
_x000D_
var result = yourString.slice(1,-1);_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

Documentation for the slice and substring.

Appending to an empty DataFrame in Pandas?

And if you want to add a row, you can use a dictionary:

df = pd.DataFrame()
df = df.append({'name': 'Zed', 'age': 9, 'height': 2}, ignore_index=True)

which gives you:

   age  height name
0    9       2  Zed

Fast Linux file count for a large number of files

find, ls, and perl tested against 40,000 files has the same speed (though I didn't try to clear the cache):

[user@server logs]$ time find . | wc -l
42917

real    0m0.054s
user    0m0.018s
sys     0m0.040s

[user@server logs]$ time /bin/ls -f | wc -l
42918

real    0m0.059s
user    0m0.027s
sys     0m0.037s

And with Perl's opendir and readdir, the same time:

[user@server logs]$ time perl -e 'opendir D, "."; @files = readdir D; closedir D; print scalar(@files)."\n"'
42918

real    0m0.057s
user    0m0.024s
sys     0m0.033s

Note: I used /bin/ls -f to make sure to bypass the alias option which might slow a little bit and -f to avoid file ordering. ls without -f is twice slower than find/perl except if ls is used with -f, it seems to be the same time:

[user@server logs]$ time /bin/ls . | wc -l
42916

real    0m0.109s
user    0m0.070s
sys     0m0.044s

I also would like to have some script to ask the file system directly without all the unnecessary information.

The tests were based on the answers of Peter van der Heijden, glenn jackman, and mark4o.

How to monitor network calls made from iOS Simulator

Wireshark it

Select your interface

enter image description here

Add filter start the capture

enter image description here


Testing

Click on any action or button that would trigger a GET/POST/PUT/DELETE request

You will see it on listed in the wireshark

enter image description here

If you want to know more details about one specific packet, just select it and Follow > HTTP Stream.

enter image description here

hope this help others !!

JavaScript math, round to two decimal places

To handle rounding to any number of decimal places, a function with 2 lines of code will suffice for most needs. Here's some sample code to play with.



    var testNum = 134.9567654;
    var decPl = 2;
    var testRes = roundDec(testNum,decPl);  
    alert (testNum + ' rounded to ' + decPl + ' decimal places is ' + testRes);

    function roundDec(nbr,dec_places){
        var mult = Math.pow(10,dec_places);
        return Math.round(nbr * mult) / mult;
    }

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

Fatal error: Call to undefined function socket_create()

Open the php.ini file in your server environment and remove ; from ;extension=sockets. if it's doesn't work, you have to download the socket extension for PHP and put it into ext directory in the php installation path. Restart your http server and everything should work.

Convert HTML5 into standalone Android App

You can use https://appery.io/ It is the same phonegap but in very convinient wrapper

Best way to "push" into C# array

As said before, List provides functionality to add elements in a clean way, to do the same with arrays, you have to resize them to accomodate extra elements, see code below:

int[] arr = new int[2];
arr[0] = 1;
arr[1] = 2;
//without this line we'd get a exception
Array.Resize(ref arr, 3);
arr[2] = 3;

Regarding your idea with loop:

elements of an array are set to their default values when array is initialized. So your approach would be good, if you want to fill "blanks" in array holding reference types (which have default value null).

But it wouldn't work with value types, as they are initialized with 0!

How to escape JSON string?

The methods offered here are faulty.
Why venture that far when you could just use System.Web.HttpUtility.JavaScriptEncode ?

If you're on a lower framework, you can just copy paste it from mono

Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs

    public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
    {
        if (string.IsNullOrEmpty(value))
            return addDoubleQuotes ? "\"\"" : string.Empty;

        int len = value.Length;
        bool needEncode = false;
        char c;
        for (int i = 0; i < len; i++)
        {
            c = value[i];

            if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
            {
                needEncode = true;
                break;
            }
        }

        if (!needEncode)
            return addDoubleQuotes ? "\"" + value + "\"" : value;

        var sb = new System.Text.StringBuilder();
        if (addDoubleQuotes)
            sb.Append('"');

        for (int i = 0; i < len; i++)
        {
            c = value[i];
            if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
                sb.AppendFormat("\\u{0:x4}", (int)c);
            else switch ((int)c)
                {
                    case 8:
                        sb.Append("\\b");
                        break;

                    case 9:
                        sb.Append("\\t");
                        break;

                    case 10:
                        sb.Append("\\n");
                        break;

                    case 12:
                        sb.Append("\\f");
                        break;

                    case 13:
                        sb.Append("\\r");
                        break;

                    case 34:
                        sb.Append("\\\"");
                        break;

                    case 92:
                        sb.Append("\\\\");
                        break;

                    default:
                        sb.Append(c);
                        break;
                }
        }

        if (addDoubleQuotes)
            sb.Append('"');

        return sb.ToString();
    }

This can be compacted into

// https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{

    private static  bool NeedEscape(string src, int i)
    {
        char c = src[i];
        return c < 32 || c == '"' || c == '\\'
            // Broken lead surrogate
            || (c >= '\uD800' && c <= '\uDBFF' &&
                (i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
            // Broken tail surrogate
            || (c >= '\uDC00' && c <= '\uDFFF' &&
                (i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
            // To produce valid JavaScript
            || c == '\u2028' || c == '\u2029'
            // Escape "</" for <script> tags
            || (c == '/' && i > 0 && src[i - 1] == '<');
    }



    public static string EscapeString(string src)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        int start = 0;
        for (int i = 0; i < src.Length; i++)
            if (NeedEscape(src, i))
            {
                sb.Append(src, start, i - start);
                switch (src[i])
                {
                    case '\b': sb.Append("\\b"); break;
                    case '\f': sb.Append("\\f"); break;
                    case '\n': sb.Append("\\n"); break;
                    case '\r': sb.Append("\\r"); break;
                    case '\t': sb.Append("\\t"); break;
                    case '\"': sb.Append("\\\""); break;
                    case '\\': sb.Append("\\\\"); break;
                    case '/': sb.Append("\\/"); break;
                    default:
                        sb.Append("\\u");
                        sb.Append(((int)src[i]).ToString("x04"));
                        break;
                }
                start = i + 1;
            }
        sb.Append(src, start, src.Length - start);
        return sb.ToString();
    }
}

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

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

Hope this helps but please let me know if you need more details.

How to remove a web site from google analytics

AS of 2018

Login to your analytics account
Select the account/property you want to delete
Click the  button. (left side bottom menu)
Click on property settings
To the right you will see Move To Trash Can Click on that
You will see the bellow screen. click on Delete Property button

or if you want to delete the account

follow the same steps, but this time click on the Accoutn Settings tab see below

Now Click on Move to Trash Can (button to the right)

when you see the next screen confirm to delete the account by clicking on the Trash Account button.

How to delete a website from google analytics

How to disable XDebug

Apache/2.4.33 (Win64) PHP/7.2.4 myHomeBrew stack

At end of php.ini I use the following to manage Xdebug for use with PhpStorm

; jch ~ Sweet analizer at https://xdebug.org/wizard.php for matching xdebug to php version.
; jch ~ When upgrading php versions check if newer xdebug.dll is needed in ext directory.
; jch Renamed... zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug-2.6.0-7.2-vc15-x86_64.dll

zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll

; jch !!!! Added the following for Xdebug with PhpStorm

[Xdebug]
; zend_extension=<full_path_to_xdebug_extension>
; xdebug.remote_host=<the host where PhpStorm is running (e.g. localhost)>
; xdebug.remote_port=<the port to which Xdebug tries to connect on the host where PhpStorm is running (default 9000)>

xdebug.remote_enable=1
xdebug.remote_host=localhost
xdebug.remote_port=9000

xdebug.profiler_enable=1
xdebug.profiler_output_dir="E:\x64Stack\Xdebug_profiler_output"
xdebug.idekey=PHPSTORM
xdebug.remote_autostart=1

; jch ~~~~~~~~~To turn Xdebug off(disable) uncomment the following 3 lines restart Apache~~~~~~~~~ 
;xdebug.remote_autostart=0  
;xdebug.remote_enable=0
;xdebug.profiler_enable=0

; !!! Might get a little more speed by also commenting out this line above... 
;;; zend_extension = E:\x64Stack\PHP\php7.2.4\ext\php_xdebug.dll
; so that Xdebug is both disabled AND not loaded

How can I read an input string of unknown length?

Take a character pointer to store required string.If you have some idea about possible size of string then use function

char *fgets (char *str, int size, FILE* file);`

else you can allocate memory on runtime too using malloc() function which dynamically provides requested memory.

Postgres: How to do Composite keys?

Your compound PRIMARY KEY specification already does what you want. Omit the line that's giving you a syntax error, and omit the redundant CONSTRAINT (already implied), too:

 CREATE TABLE tags
      (
               question_id INTEGER NOT NULL,
               tag_id SERIAL NOT NULL,
               tag1 VARCHAR(20),
               tag2 VARCHAR(20),
               tag3 VARCHAR(20),
               PRIMARY KEY(question_id, tag_id)
      );

NOTICE:  CREATE TABLE will create implicit sequence "tags_tag_id_seq" for serial column "tags.tag_id"
    NOTICE:  CREATE TABLE / PRIMARY KEY will create implicit index "tags_pkey" for table "tags"
    CREATE TABLE
    pg=> \d tags
                                         Table "public.tags"
       Column    |         Type          |                       Modifiers       
    -------------+-----------------------+-------------------------------------------------------
     question_id | integer               | not null
     tag_id      | integer               | not null default nextval('tags_tag_id_seq'::regclass)
     tag1        | character varying(20) |
     tag2        | character varying(20) |
     tag3        | character varying(20) |
    Indexes:
        "tags_pkey" PRIMARY KEY, btree (question_id, tag_id)

Resolve promises one after another (i.e. in sequence)?

If someone else needs a guaranteed way of STRICTLY sequential way of resolving Promises when performing CRUD operations you also can use the following code as a basis.

As long as you add 'return' before calling each function, describing a Promise, and use this example as a basis the next .then() function call will CONSISTENTLY start after the completion of the previous one:

getRidOfOlderShoutsPromise = () => {
    return readShoutsPromise('BEFORE')
    .then(() => {
        return deleteOlderShoutsPromise();
    })
    .then(() => {
        return readShoutsPromise('AFTER')
    })
    .catch(err => console.log(err.message));
}

deleteOlderShoutsPromise = () => {
    return new Promise ( (resolve, reject) => {
        console.log("in deleteOlderShouts");
        let d = new Date();
        let TwoMinuteAgo = d - 1000 * 90 ;
        All_Shouts.deleteMany({ dateTime: {$lt: TwoMinuteAgo}}, function(err) {
            if (err) reject();
            console.log("DELETED OLDs at "+d);
            resolve();        
        });
    });
}

readShoutsPromise = (tex) => {
    return new Promise( (resolve, reject) => {
        console.log("in readShoutsPromise -"+tex);
        All_Shouts
        .find({})
        .sort([['dateTime', 'ascending']])
        .exec(function (err, data){
            if (err) reject();
            let d = new Date();
            console.log("shouts "+tex+" delete PROMISE = "+data.length +"; date ="+d);
            resolve(data);
        });    
    });
}

Hiding elements in responsive layout?

Bootstrap 4 Beta Answer:

d-block d-md-none to hide on medium, large and extra large devices.

d-none d-md-block to hide on small and extra-small devices.

enter image description here

Note that you can also inline by replacing d-*-block with d-*-inline-block


Old answer: Bootstrap 4 Alpha

  • You can use the classes .hidden-*-up to hide on a given size and larger devices

    .hidden-md-up to hide on medium, large and extra large devices.

  • The same goes with .hidden-*-down to hide on a given size and smaller devices

    .hidden-md-down to hide on medium, small and extra-small devices

  • visible-* is no longer an option with bootstrap 4

  • To display only on medium devices, you can combine the two:

    hidden-sm-down and hidden-xl-up

The valid sizes are:

  • xs for phones in portrait mode (<34em)
  • sm for phones in landscape mode (=34em)
  • md for tablets (=48em)
  • lg for desktops (=62em)
  • xl for desktops (=75em)

This was as of Bootstrap 4, alpha 5 (January 2017). More details here: http://v4-alpha.getbootstrap.com/layout/responsive-utilities/

On Bootstrap 4.3.x: https://getbootstrap.com/docs/4.3/utilities/display/

Bootstrap 3 Collapse show state with Chevron icon

Angular seems to cause issues with the JavaScript-based approaches here ( at least the ones I've tried ) . I found this solution here: http://www.codeproject.com/Articles/987311/Collapsible-Responsive-Master-Child-Grid-Using-Ang . The gist of it is to use data-ng-click on the toggle button and make the method to change the button in the controller using the $scope context .

I guess I could provide more detail... my buttons are set to the glyphicon of the initial state of the div they collapse ( glyphicon-chevron-right == collapsed div ) .

page.html:

<div class="title-1">
    <button data-toggle="collapse" data-target="#panel-{{ p_idx }}" class="dropdown-toggle title-btn glyphicon glyphicon-chevron-right" data-ng-click="collapse($event)"></button>
</div>
<div id="panel-{{ p_idx }}" class="collapse sect">
    ...
</div>

controllers.js:

.controller('PageController', function($scope, $rootScope) {
    $scope.collapse = function (event) {
        $(event.target).toggleClass("glyphicon-chevron-down glyphicon-chevron-right");
    };
)

Wordpress - Images not showing up in the Media Library

How did you upload those images; via FTP or through WP uploader? You have to upload images THROUGH WP uploader in order to show them in the image library.

JavaScript "cannot read property "bar" of undefined

Compound checking:

   if (thing.foo && thing.foo.bar) {
      ... thing.foor.bar exists;
   }

jQuery selector for id starts with specific text

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

Text overflow ellipsis on two lines

It seems more elegant combining two classes. You can drop two-lines class if only one row need see:

_x000D_
_x000D_
.ellipse {_x000D_
          white-space: nowrap;_x000D_
          display:inline-block;_x000D_
          overflow: hidden;_x000D_
          text-overflow: ellipsis;_x000D_
       }_x000D_
      .two-lines {_x000D_
          -webkit-line-clamp: 2;_x000D_
          display: -webkit-box;_x000D_
          -webkit-box-orient: vertical;_x000D_
          white-space: normal;_x000D_
      }_x000D_
      .width{_x000D_
          width:100px;_x000D_
          border:1px solid hotpink;_x000D_
      }
_x000D_
        <span class='width ellipse'>_x000D_
          some texts some texts some texts some texts some texts some texts some texts_x000D_
       </span>_x000D_
_x000D_
       <span class='width ellipse two-lines'>_x000D_
          some texts some texts some texts some texts some texts some texts some texts_x000D_
       </span>
_x000D_
_x000D_
_x000D_

Split Strings into words with multiple word boundary delimiters

Here is the answer with some explanation.

st = "Hey, you - what are you doing here!?"

# replace all the non alpha-numeric with space and then join.
new_string = ''.join([x.replace(x, ' ') if not x.isalnum() else x for x in st])
# output of new_string
'Hey  you  what are you doing here  '

# str.split() will remove all the empty string if separator is not provided
new_list = new_string.split()

# output of new_list
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']

# we can join it to get a complete string without any non alpha-numeric character
' '.join(new_list)
# output
'Hey you what are you doing'

or in one line, we can do like this:

(''.join([x.replace(x, ' ') if not x.isalnum() else x for x in st])).split()

# output
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']

updated answer

"While .. End While" doesn't work in VBA?

While constructs are terminated not with an End While but with a Wend.

While counter < 20
    counter = counter + 1
Wend

Note that this information is readily available in the documentation; just press F1. The page you link to deals with Visual Basic .NET, not VBA. While (no pun intended) there is some degree of overlap in syntax between VBA and VB.NET, one can't just assume that the documentation for the one can be applied directly to the other.

Also in the VBA help file:

Tip The Do...Loop statement provides a more structured and flexible way to perform looping.

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

in my case it was the path lenght (incl. file name).

..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Debug\boost_unit_test_framework-vc90-mt-gd-1_57.lib;

as for the release the path was (this has worked correctly):

..\..\..\..\..\..\..\SWX\Binary\VS2008\Output\Win32\Release\boost_unit_test_framework-vc90-mt-1_57.lib;

==> one char shorter.

  1. i have also verified this by renaming the lib file (using shorter name) and changing this in the

Linker -> input -> additoinal dependencies

  1. i have also verified this by adding absolut path instead of relative path as all those ".." has extended the path string, too. this has also worked.

so the problem for me was the total size of the path + filename string was too long!

pip cannot install anything

pip has mirror support

pip --use-mirrors install yolk

As of version 1.5, this option will be removed:

1.5 (unreleased)

BACKWARD INCOMPATIBLE pip no longer supports the --use-mirrors, -M, and --mirrors flags. The mirroring support has been removed. In order to use a mirror specify it as the primary index with -i or --index-url, or as an additional index with --extra-index-url. (Pull #1098, CVE-2013-5123)

BACKWARD INCOMPATIBLE pip no longer will scrape insecure external urls by default nor will it install externally hosted files by default. Users may opt into installing externally hosted or insecure files or urls using --allow-external PROJECT and --allow-insecure PROJECT. (Pull #1055)

Added colors to the logging output in order to draw attention to important warnings and errors. (Pull #1109)

Added warnings when using an insecure index, find-link, or dependency link. (Pull #1121)

CSS Equivalent of the "if" statement

Your stylesheet should be thought of as a static table of available variables that your html document can call on based on what you need to display. The logic should be in your javascript and html, use javascript to dynamically apply attributes based on conditions if you really need to. Stylesheets are not the place for logic.

Appending items to a list of lists in python

import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions) 
with open('data.csv', 'r') as f:
    for rec in csv.DictReader(f):
        for l, col in zip(data, cols):
            l.append(float(rec[col]))
print data

# [[3.0, 3.0], [0.01, 0.01]]

TypeScript for ... of with index / key?

.forEach already has this ability:

const someArray = [9, 2, 5];
someArray.forEach((value, index) => {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
});

But if you want the abilities of for...of, then you can map the array to the index and value:

for (const { index, value } of someArray.map((value, index) => ({ index, value }))) {
    console.log(index); // 0, 1, 2
    console.log(value); // 9, 2, 5
}

That's a little long, so it may help to put it in a reusable function:

function toEntries<T>(a: T[]) {
    return a.map((value, index) => [index, value] as const);
}

for (const [index, value] of toEntries(someArray)) {
    // ..etc..
}

Iterable Version

This will work when targeting ES3 or ES5 if you compile with the --downlevelIteration compiler option.

function* toEntries<T>(values: T[] | IterableIterator<T>) {
    let index = 0;
    for (const value of values) {
        yield [index, value] as const;
        index++;
    }
}

Array.prototype.entries() - ES6+

If you are able to target ES6+ environments then you can use the .entries() method as outlined in Arnavion's answer.

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

Well, you have some options.

You could configure sudo to not prompt for a password. This is not recommended, due to the security risks.

You could write an expect script to read the password and supply it to sudo when required, but that's clunky and fragile.

I would recommend designing the script to run as root and drop its privileges whenever they're not needed. Simply have it sudo -u someotheruser command for the commands that don't require root.

(If they have to run specifically as the user invoking the script, then you could have the script save the uid and invoke a second script via sudo with the id as an argument, so it knows who to su to..)

How to delete row in gridview using rowdeleting event?

The solution is somewhat simple; once you have deleted the row from the datagrid (Your code ONLY removes the row from the grid and NOT the datasource) then you do not need to do anything else. As you are doing a databind operation immediately after, without updating the datasource, you are re-adding all the rows from the source to the gridview control (including the row removed from the grid in the previous statement).

To simply delete from the grid without a datasource then just call the delete operation on the grid and that is all you need to do... no databinding is needed after that.

ImportError: No module named apiclient.discovery

The same error can be seen if you are creating a Python module and your executing the script after installing it via pip or pipx command. In this case ensure you have declared what the project minimally needs to run correctly into install_requires section of your setup.py file, so in this case:

install_requires=[
    "google-api-python-client>=1.12.3",
    "google-auth-httplib2>=0.0.4",
    "google-auth-oauthlib>=0.4.1"
]

How to add parameters into a WebRequest?

Use stream to write content to webrequest

string data = "username=<value>&password=<value>"; //replace <value>
byte[] dataStream = Encoding.UTF8.GetBytes(data);
private string urlPath = "http://xxx.xxx.xxx/manager/";
string request = urlPath + "index.php/org/get_org_form";
WebRequest webRequest = WebRequest.Create(request);
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.ContentLength = dataStream.Length;  
Stream newStream=webRequest.GetRequestStream();
// Send the data.
newStream.Write(dataStream,0,dataStream.Length);
newStream.Close();
WebResponse webResponse = webRequest.GetResponse();  

Preloading @font-face fonts?

Recently I was working on a game compatible with CocoonJS with DOM limited to the canvas element - here is my approach:

Using fillText with a font that has not been loaded yet will execute properly but with no visual feedback - so the canvas plane will stay intact - all you have to do is periodically check the canvas for any changes (for example looping through getImageData searching for any non transparent pixel) that will happen when the font loads properly.

I have explained this technique a little bit more in my recent article http://rezoner.net/preloading-font-face-using-canvas,686

PHP remove special character from string

See example.

/**
 * nv_get_plaintext()
 *
 * @param mixed $string
 * @return
 */
function nv_get_plaintext( $string, $keep_image = false, $keep_link = false )
{
    // Get image tags
    if( $keep_image )
    {
        if( preg_match_all( "/\<img[^\>]*src=\"([^\"]*)\"[^\>]*\>/is", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $textimg = '';
                if( strpos( $match[1][$key], 'data:image/png;base64' ) === false )
                {
                    $textimg = " " . $match[1][$key];
                }
                if( preg_match_all( "/\<img[^\>]*alt=\"([^\"]+)\"[^\>]*\>/is", $_m, $m_alt ) )
                {
                    $textimg .= " " . $m_alt[1][0];
                }
                $string = str_replace( $_m, $textimg, $string );
            }
        }
    }

    // Get link tags
    if( $keep_link )
    {
        if( preg_match_all( "/\<a[^\>]*href=\"([^\"]+)\"[^\>]*\>(.*)\<\/a\>/isU", $string, $match ) )
        {
            foreach( $match[0] as $key => $_m )
            {
                $string = str_replace( $_m, $match[1][$key] . " " . $match[2][$key], $string );
            }
        }
    }

    $string = str_replace( ' ', ' ', strip_tags( $string ) );
    return preg_replace( '/[ ]+/', ' ', $string );
}

How do I get the absolute directory of a file in bash?

This will work for both file and folder:

absPath(){
    if [[ -d "$1" ]]; then
        cd "$1"
        echo "$(pwd -P)"
    else 
        cd "$(dirname "$1")"
        echo "$(pwd -P)/$(basename "$1")"
    fi
}

When should I use a struct rather than a class in C#?

With the exception of the valuetypes that are used directly by the runtime and various others for PInvoke purposes, you should only use valuetypes in 2 scenarios.

  1. When you need copy semantics.
  2. When you need automatic initialization, normally in arrays of these types.

java Arrays.sort 2d array

Welcome Java 8:

Arrays.sort(myArr, (a, b) -> Double.compare(a[0], b[0]));

MVC3 EditorFor readOnly

The EditorFor html helper does not have overloads that take HTML attributes. In this case, you need to use something more specific like TextBoxFor:

<div class="editor-field">
    @Html.TextBoxFor(model => model.userName, new 
        { disabled = "disabled", @readonly = "readonly" })
</div>

You can still use EditorFor, but you will need to have a TextBoxFor in a custom EditorTemplate:

public class MyModel
{
    [UIHint("userName")]
    public string userName { ;get; set; }
}

Then, in your Views/Shared/EditorTemplates folder, create a file userName.cshtml. In that file, put this:

@model string
@Html.TextBoxFor(m => m, new { disabled = "disabled", @readonly = "readonly" })

T-SQL split string

Instead of recursive CTEs and while loops, has anyone considered a more set-based approach? Note that this function was written for the question, which was based on SQL Server 2008 and comma as the delimiter. In SQL Server 2016 and above (and in compatibility level 130 and above), STRING_SPLIT() is a better option.

CREATE FUNCTION dbo.SplitString
(
  @List     nvarchar(max),
  @Delim    nvarchar(255)
)
RETURNS TABLE
AS
  RETURN ( SELECT [Value] FROM 
  ( 
    SELECT [Value] = LTRIM(RTRIM(SUBSTRING(@List, [Number],
      CHARINDEX(@Delim, @List + @Delim, [Number]) - [Number])))
    FROM (SELECT Number = ROW_NUMBER() OVER (ORDER BY name)
      FROM sys.all_columns) AS x WHERE Number <= LEN(@List)
      AND SUBSTRING(@Delim + @List, [Number], DATALENGTH(@Delim)/2) = @Delim
    ) AS y
  );
GO

If you want to avoid the limitation of the length of the string being <= the number of rows in sys.all_columns (9,980 in model in SQL Server 2017; much higher in your own user databases), you can use other approaches for deriving the numbers, such as building your own table of numbers. You could also use a recursive CTE in cases where you can't use system tables or create your own:

CREATE FUNCTION dbo.SplitString
(
  @List     nvarchar(max),
  @Delim    nvarchar(255)
)
RETURNS TABLE WITH SCHEMABINDING
AS
   RETURN ( WITH n(n) AS (SELECT 1 UNION ALL SELECT n+1 
       FROM n WHERE n <= LEN(@List))
       SELECT [Value] = SUBSTRING(@List, n, 
       CHARINDEX(@Delim, @List + @Delim, n) - n)
       FROM n WHERE n <= LEN(@List)
      AND SUBSTRING(@Delim + @List, n, DATALENGTH(@Delim)/2) = @Delim
   );
GO

But you'll have to append OPTION (MAXRECURSION 0) (or MAXRECURSION <longest possible string length if < 32768>) to the outer query in order to avoid errors with recursion for strings > 100 characters. If that is also not a good alternative then see this answer as pointed out in the comments.

(Also, the delimiter will have to be NCHAR(<=1228). Still researching why.)

More on split functions, why (and proof that) while loops and recursive CTEs don't scale, and better alternatives, if splitting strings coming from the application layer:

Repository access denied. access via a deployment key is read-only

You have to delete the deployment key first if you are going to add the same key under Manage Account SSH Key.

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

Recommended date format for REST GET API

Check this article for the 5 laws of API dates and times HERE:

  • Law #1: Use ISO-8601 for your dates
  • Law #2: Accept any timezone
  • Law #3: Store it in UTC
  • Law #4: Return it in UTC
  • Law #5: Don’t use time if you don’t need it

More info in the docs.

Angular is automatically adding 'ng-invalid' class on 'required' fields

Since the fields are empty they are not valid, so the ng-invalid and ng-invalid-required classes are added properly.

You can use the class ng-pristine to check out whether the fields have already been used or not.

ReferenceError: describe is not defined NodeJs

if you are using vscode, want to debug your files

I used tdd before, it throw ReferenceError: describe is not defined

But, when I use bdd, it works!

waste half day to solve it....

    {
      "type": "node",
      "request": "launch",
      "name": "Mocha Tests",
      "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
      "args": [
        "-u",
        "bdd",// set to bdd, not tdd
        "--timeout",
        "999999",
        "--colors",
        "${workspaceFolder}/test/**/*.js"
      ],
      "internalConsoleOptions": "openOnSessionStart"
},

Simple mediaplayer play mp3 from file path?

Use the code below it worked for me.

MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/mnt/sdcard/yourdirectory/youraudiofile.mp3");
mp.prepare();
mp.start();

Eclipse CDT project built but "Launch Failed. Binary Not Found"

press ctrl +B and then You can use the Run button.

How do I check for null values in JavaScript?

Actually I think you may need to use if (value !== null || value !== undefined) because if you use if (value) you may also filter 0 or false values.

Consider these two functions:

const firstTest = value => {
    if (value) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}
const secondTest = value => {
    if (value !== null && value !== undefined) {
        console.log('passed');
    } else {
        console.log('failed');
    }
}

firstTest(0);            // result: failed
secondTest(0);           // result: passed

firstTest(false);        // result: failed
secondTest(false);       // result: passed

firstTest('');           // result: failed
secondTest('');          // result: passed

firstTest(null);         // result: failed
secondTest(null);        // result: failed

firstTest(undefined);    // result: failed
secondTest(undefined);   // result: failed

In my situation, I just needed to check if the value is null and undefined and I did not want to filter 0 or false or '' values. so I used the second test, but you may need to filter them too which may cause you to use first test.

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: mydata,
        **contentType: false,
        processData: false**
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}

Python Pandas merge only certain columns

You want to use TWO brackets, so if you are doing a VLOOKUP sort of action:

df = pd.merge(df,df2[['Key_Column','Target_Column']],on='Key_Column', how='left')

This will give you everything in the original df + add that one corresponding column in df2 that you want to join.

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

Permanently add a directory to PYTHONPATH?

This is an update to this thread which has some old answers.

For those using MAC-OS Catalina or some newer (>= 10.15), it was introduced a new Terminal named zsh (a substitute to the old bash).

I had some problems with the answers above due to this change, and I somewhat did a workaround by creating the file ~/.zshrc and pasting the file directory to the $PATH and $PYTHONPATH

So, first I did:

nano ~/.zshrc

When the editor opened I pasted the following content:

export PATH="${PATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"
export PYTHONPATH="${PYTHONPATH}:/Users/caio.hc.oliveira/Library/Python/3.7/bin"

saved it, and restarted the terminal.

IMPORTANT: The path above is set to my computer's path, you would have to adapt it to your python.

How to check if element is visible after scrolling?

How about

function isInView(elem){
   return $(elem).offset().top - $(window).scrollTop() < $(elem).height() ;
}

After that you can trigger whatever you want once the element is in view like this

$(window).scroll(function(){
   if (isInView($('.classOfDivToCheck')))
      //fire whatever you what 
      dothis();
})

That works for me just fine

jQuery input button click event listener

First thing first, button() is a jQuery ui function to create a button widget which has nothing to do with jQuery core, it just styles the button.
So if you want to use the widget add jQuery ui's javascript and CSS files or alternatively remove it, like this:

$("#filter").click(function(){
    alert('clicked!');
});

Another thing that might have caused you the problem is if you didn't wait for the input to be rendered and wrote the code before the input. jQuery has the ready function, or it's alias $(func) which execute the callback once the DOM is ready.
Usage:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

So even if the order is this it will work:

$(function(){
    $("#filter").click(function(){
        alert('clicked!');
    });
});

<input type="button" id="filter" name="filter" value="Filter" />

DEMO

Using CSS how to change only the 2nd column of a table

To change only the second column of a table use the following:

General Case:

table td + td{  /* this will go to the 2nd column of a table directly */

background:red

}

Your case:

.countTable table table td + td{ 

background: red

}

Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question

How to get the Parent's parent directory in Powershell?

Version for a directory

get-item is your friendly helping hand here.

(get-item $scriptPath ).parent.parent

If you Want the string only

(get-item $scriptPath ).parent.parent.FullName

Version for a file

If $scriptPath points to a file then you have to call Directory property on it first, so the call would look like this

(get-item $scriptPath).Directory.Parent.Parent.FullName

Remarks
This will only work if $scriptPath exists. Otherwise you have to use Split-Path cmdlet.

How can I round down a number in Javascript?

Was fiddling round with someone elses code today and found the following which seems rounds down as well:

var dec = 12.3453465,
int = dec >> 0; // returns 12

For more info on the Sign-propagating right shift(>>) see MDN Bitwise Operators

It took me a while to work out what this was doing :D

But as highlighted above, Math.floor() works and looks more readable in my opinion.

How to modify a specified commit?

Interactive rebase with --autosquash is something I frequently use when I need to fixup previous commits deeper in the history. It essentially speeds up the process that ZelluX's answer illustrates, and is especially handy when you have more than one commit you need to edit.

From the documentation:

--autosquash

When the commit log message begins with "squash! …?" (or "fixup! …?"), and there is a commit whose title begins with the same …?, automatically modify the todo list of rebase -i so that the commit marked for squashing comes right after the commit to be modified

Assume you have a history that looks like this:

$ git log --graph --oneline
* b42d293 Commit3
* e8adec4 Commit2
* faaf19f Commit1

and you have changes that you want to amend to Commit2 then commit your changes using

$ git commit -m "fixup! Commit2"

alternatively you can use the commit-sha instead of the commit message, so "fixup! e8adec4 or even just a prefix of the commit message.

Then initiate an interactive rebase on the commit before

$ git rebase e8adec4^ -i --autosquash

your editor will open with the commits already correctly ordered

pick e8adec4 Commit2
fixup 54e1a99 fixup! Commit2
pick b42d293 Commit3

all you need to do is save and exit

SFTP file transfer using Java JSch

The most trivial way to upload a file over SFTP with JSch is:

JSch jsch = new JSch();
Session session = jsch.getSession(user, host);
session.setPassword(password);
session.connect();

ChannelSftp sftpChannel = (ChannelSftp) session.openChannel("sftp");
sftpChannel.connect();

sftpChannel.put("C:/source/local/path/file.zip", "/target/remote/path/file.zip");

Similarly for a download:

sftpChannel.get("/source/remote/path/file.zip", "C:/target/local/path/file.zip");

You may need to deal with UnknownHostKey exception.

JAXB: How to ignore namespace during unmarshalling XML document?

I have encoding problems with XMLFilter solution, so I made XMLStreamReader to ignore namespaces:

class XMLReaderWithoutNamespace extends StreamReaderDelegate {
    public XMLReaderWithoutNamespace(XMLStreamReader reader) {
      super(reader);
    }
    @Override
    public String getAttributeNamespace(int arg0) {
      return "";
    }
    @Override
    public String getNamespaceURI() {
      return "";
    }
}

InputStream is = new FileInputStream(name);
XMLStreamReader xsr = XMLInputFactory.newFactory().createXMLStreamReader(is);
XMLReaderWithoutNamespace xr = new XMLReaderWithoutNamespace(xsr);
Unmarshaller um = jc.createUnmarshaller();
Object res = um.unmarshal(xr);

How to use private Github repo as npm dependency

It can be done via https and oauth or ssh.

https and oauth: create an access token that has "repo" scope and then use this syntax:

"package-name": "git+https://<github_token>:[email protected]/<user>/<repo>.git"

or

ssh: setup ssh and then use this syntax:

"package-name": "git+ssh://[email protected]:<user>/<repo>.git"

(note the use of colon instead of slash before user)

Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2:java (default-cli)

I had the same problem but after deleting the old plugin for org.codehaus.mojo it worked.

I use this

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>exec-maven-plugin</artifactId>
    <version>1.2</version>
</plugin>

How can I view an old version of a file with Git?

You can use git show with a path from the root of the repository (./ or ../ for relative pathing):

$ git show REVISION:path/to/file

Replace REVISION with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)

For example, to view the version of file <repository-root>/src/main.c from 4 commits ago, use:

$ git show HEAD~4:src/main.c

Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show.

Sequence contains no elements?

This will solve the problem,

var blogPosts = (from p in dc.BlogPosts
             where p.BlogPostID == ID
             select p);
if(blogPosts.Any())
{
  var post = post.Single();
}

Functional, Declarative, and Imperative Programming

There's not really any non-ambiguous, objective definition for these. Here is how I would define them:

Imperative - The focus is on what steps the computer should take rather than what the computer will do (ex. C, C++, Java).

Declarative - The focus is on what the computer should do rather than how it should do it (ex. SQL).

Functional - a subset of declarative languages that has heavy focus on recursion

How do I initialize an empty array in C#?

Combining @nawfal & @Kobi suggestions:

namespace Extensions
{
    /// <summary> Useful in number of places that return an empty byte array to avoid unnecessary memory allocation. </summary>
    public static class Array<T>
    {
        public static readonly T[] Empty = new T[0];
    }
}

Usage example:

Array<string>.Empty

UPDATE 2019-05-14

(credits to @Jaider ty)

Better use .Net API:

public static T[] Empty<T> ();

https://docs.microsoft.com/en-us/dotnet/api/system.array.empty?view=netframework-4.8

Applies to:

.NET Core: 3.0 Preview 5 2.2 2.1 2.0 1.1 1.0

.NET Framework: 4.8 4.7.2 4.7.1 4.7 4.6.2 4.6.1 4.6

.NET Standard: 2.1 Preview 2.0 1.6 1.5 1.4 1.3

...

HTH

Radio buttons not checked in jQuery

(!$('#radio').is(':checked'))

This worked for me

How to delete zero components in a vector in Matlab?

If you just wish to remove the zeros, leaving the non-zeros behind in a, then the very best solution is

a(a==0) = [];

This deletes the zero elements, using a logical indexing approach in MATLAB. When the index to a vector is a boolean vector of the same length as the vector, then MATLAB can use that boolean result to index it with. So this is equivalent to

a(find(a==0)) = [];

And, when you set some array elements to [] in MATLAB, the convention is to delete them.

If you want to put the zeros into a new result b, while leaving a unchanged, the best way is probably

b = a(a ~= 0);

Again, logical indexing is used here. You could have used the equivalent version (in terms of the result) of

b = a(find(a ~= 0));

but mlint will end up flagging the line as one where the purely logical index was more efficient, and thus more appropriate.

As always, beware EXACT tests for zero or for any number, if you would have accepted elements of a that were within some epsilonic tolerance of zero. Do those tests like this

b = a(abs(a) >= tol);

This retains only those elements of a that are at least as large as your tolerance.

How to save data file into .RData?

Alternatively, when you want to save individual R objects, I recommend using saveRDS.

You can save R objects using saveRDS, then load them into R with a new variable name using readRDS.

Example:

# Save the city object
saveRDS(city, "city.rds")

# ...

# Load the city object as city
city <- readRDS("city.rds")

# Or with a different name
city2 <- readRDS("city.rds")

But when you want to save many/all your objects in your workspace, use Manetheran's answer.

Angular2: Cannot read property 'name' of undefined

You just needed to read a little further and you would have been introduced to the *ngIf structural directive.

selectedHero.name doesn't exist yet because the user has yet to select a hero so it returns undefined.

<div *ngIf="selectedHero">
  <h2>{{selectedHero.name}} details!</h2>
  <div><label>id: </label>{{selectedHero.id}}</div>
  <div>
    <label>name: </label>
    <input [(ngModel)]="selectedHero.name" placeholder="name"/>
  </div>
</div>

The *ngIf directive keeps selectedHero off the DOM until it is selected and therefore becomes truthy.

This document helped me understand structural directives.

Android WebView not loading an HTTPS URL

Per correct answer by fargth, follows is a small code sample that might help.

First, create a class that extends WebViewClient and which is set to ignore SSL errors:

// SSL Error Tolerant Web View Client
private class SSLTolerentWebViewClient extends WebViewClient {

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed(); // Ignore SSL certificate errors
            }

}

Then with your web view object (initiated in the OnCreate() method), set its web view client to be an instance of the override class:

 mWebView.setWebViewClient(
                new SSLTolerentWebViewClient()
        );

jQuery remove special characters from string and more

Remove numbers, underscore, white-spaces and special characters from the string sentence.

str.replace(/[0-9`~!@#$%^&*()_|+\-=?;:'",.<>\{\}\[\]\\\/]/gi,'');

Demo

SQL Server replace, remove all after certain character

For the times when some fields have a ";" and some do not you can also add a semi-colon to the field and use the same method described.

SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)

AngularJS check if form is valid in controller

The BusinessCtrl is initialised before the createBusinessForm's FormController. Even if you have the ngController on the form won't work the way you wanted. You can't help this (you can create your ngControllerDirective, and try to trick the priority.) this is how angularjs works.

See this plnkr for example: http://plnkr.co/edit/WYyu3raWQHkJ7XQzpDtY?p=preview

Responsive bootstrap 3 timepicker?

As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.

Getting files by creation date in .NET

this could work for you.

using System.Linq;

DirectoryInfo info = new DirectoryInfo("PATH_TO_DIRECTORY_HERE");
FileInfo[] files = info.GetFiles().OrderBy(p => p.CreationTime).ToArray();
foreach (FileInfo file in files)
{
    // DO Something...
}

How to write an async method with out parameter?

The limitation of the async methods not accepting out parameters applies only to the compiler-generated async methods, these declared with the async keyword. It doesn't apply to hand-crafted async methods. In other words it is possible to create Task returning methods accepting out parameters. For example lets say that we already have a ParseIntAsync method that throws, and we want to create a TryParseIntAsync that doesn't throw. We could implement it like this:

public static Task<bool> TryParseIntAsync(string s, out Task<int> result)
{
    var tcs = new TaskCompletionSource<int>();
    result = tcs.Task;
    return ParseIntAsync(s).ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            tcs.SetException(t.Exception.InnerException);
            return false;
        }
        tcs.SetResult(t.Result);
        return true;
    }, default, TaskContinuationOptions.None, TaskScheduler.Default);
}

Using the TaskCompletionSource and the ContinueWith method is a bit awkward, but there is no other option since we can't use the convenient await keyword inside this method.

Usage example:

if (await TryParseIntAsync("-13", out var result))
{
    Console.WriteLine($"Result: {await result}");
}
else
{
    Console.WriteLine($"Parse failed");
}

Update: If the async logic is too complex to be expressed without await, then it could be encapsulated inside a nested asynchronous anonymous delegate. A TaskCompletionSource would still be needed for the out parameter. It is possible that the out parameter could be completed before the completion of the main task, as in the example bellow:

public static Task<string> GetDataAsync(string url, out Task<int> rawDataLength)
{
    var tcs = new TaskCompletionSource<int>();
    rawDataLength = tcs.Task;
    return ((Func<Task<string>>)(async () =>
    {
        var response = await GetResponseAsync(url);
        var rawData = await GetRawDataAsync(response);
        tcs.SetResult(rawData.Length);
        return await FilterDataAsync(rawData);
    }))();
}

This example assumes the existence of three asynchronous methods GetResponseAsync, GetRawDataAsync and FilterDataAsync that are called in succession. The out parameter is completed on the completion of the second method. The GetDataAsync method could be used like this:

var data = await GetDataAsync("http://example.com", out var rawDataLength);
Console.WriteLine($"Data: {data}");
Console.WriteLine($"RawDataLength: {await rawDataLength}");

Awaiting the data before awaiting the rawDataLength is important in this simplified example, because in case of an exception the out parameter will never be completed.

How do I force Postgres to use a particular index?

Check your random_page_cost

This problem typically happens when the estimated cost of an index scan is too high and doesn't correctly reflect reality. You may need to lower the random_page_cost configuration parameter to fix this. From the Postgres documentation:

Reducing this value [...] will cause the system to prefer index scans; raising it will make index scans look relatively more expensive.

You can do a quick test whether this will actually make Postgres use the index:

EXPLAIN <query>;              # Uses sequential scan
SET random_page_cost = 1;
EXPLAIN <query>;              # May use index scan now

You can restore the default value with SET random_page_cost = DEFAULT; again.

Background

Index scans require non-sequential disk page fetches. Postgres uses random_page_cost to estimate the cost of such non-sequential fetches in relation to sequential fetches. The default value is 4.0, thus assuming an average cost factor of 4 compared to sequential fetches (taking caching effects into account).

The problem however is that this default value is unsuitable in the following important real-life scenarios:

1) Solid-state drives

As per the documentation:

Storage that has a low random read cost relative to sequential, e.g. solid-state drives, might be better modeled with a lower value for random_page_cost, e.g., 1.1.

This slide from a speak at PostgresConf 2018 also says that random_page_cost should be set to something between 1.0 and 2.0 for solid-state drives.

2) Cached data

If the required index data is already cached in RAM, an index scan will always be significantly faster than a sequential scan. The documentation says:

If your data is likely to be completely in cache, [...] decreasing random_page_cost can be appropriate.

The problem is that you of course can't easily know whether the relevant data is already cached. However, if a specific index is frequently used, and if the system has sufficient RAM, then data is likely to be cached eventually, and random_page_cost should be set to a lower value. You'll have to experiment with different values and see what works for you.

You might also want to use the pg_prewarm extension for explicit data caching.


How do I create a file at a specific path?

The besty practice is to use '/' and a so called 'raw string' to define file path in Python.

path = r"C:/Test.py"

However, a normal program may not have the permission to write in the C: drive root directory. You may need to allow your program to do so, or choose something more reasonable since you probably not need to do so.

How can I check if a program exists from a Bash script?

I have a function defined in my .bashrc that makes this easier.

command_exists () {
    type "$1" &> /dev/null ;
}

Here's an example of how it's used (from my .bash_profile.)

if command_exists mvim ; then
    export VISUAL="mvim --nofork"
fi

Catch checked change event of a checkbox

This code does what your need:

<input type="checkbox" id="check" >check it</input>

$("#check").change( function(){
   if( $(this).is(':checked') ) {
        alert("checked");
    }else{
        alert("unchecked");
   }
});

Also, you can check it on jsfiddle

Remove multiple whitespaces

This is what I would use:

a. Make sure to use double quotes, for example:

$row['message'] = "This is   a Text \n and so on \t     Text text.";

b. To remove extra whitespace, use:

$ro = preg_replace('/\s+/', ' ', $row['message']); 
echo $ro;

It may not be the fastest solution, but I think it will require the least code, and it should work. I've never used mysql, though, so I may be wrong.

Adding a user on .htpasswd

FWIW, htpasswd -n username will output the result directly to stdout, and avoid touching files altogether.

Access to the path is denied

My problem was something like that:

FileStream ms = new FileStream(path, FileMode.Open, FileAccess.ReadWrite);

but instead of using path I should use File.FullName... I don't know if it's going to help anyone else, just passing my own experience with this erro given!

Detect if value is number in MySQL

You can use Regular Expression too... it would be like:

SELECT * FROM myTable WHERE col1 REGEXP '^[0-9]+$';

Reference: http://dev.mysql.com/doc/refman/5.1/en/regexp.html

Inserting one list into another list in java?

Excerpt from the Java API for addAll(collection c) in Interface List see here

"Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's iterator (optional operation)."

You you will have as much object as you have in both lists - the number of objects in your first list plus the number of objects you have in your second list - in your case 100.

What's the most efficient way to test two integer ranges for overlap?

Given two ranges [x1,x2], [y1,y2]

def is_overlapping(x1,x2,y1,y2):
    return max(x1,y1) <= min(x2,y2)

Counting the number of option tags in a select tag in jQuery

The W3C solution:

var len = document.getElementById("input1").length;

How to get the date 7 days earlier date from current date in Java

For all date related functionality, you should consider using Joda Library. Java's date api's are very poorly designed. Joda provides very nice API.

Proper use of mutexes in Python

You have to unlock your Mutex at sometime...

Sort an ArrayList based on an object field

Use a custom comparator:

Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});

How do I change db schema to dbo

Use this code if you want to change all tables, views, and procedures at once.

BEGIN
DECLARE @name NVARCHAR(MAX)
        , @sql NVARCHAR(MAX)
        , @oldSchema NVARCHAR(MAX) = 'MyOldSchema'
        , @newSchema NVARCHAR(MAX) = 'dbo'
        
DECLARE objCursor CURSOR FOR
        SELECT  o.name
        FROM    sys.objects o
        WHERE   type IN ('P', 'U', 'V')

OPEN    objCursor
        FETCH NEXT FROM objCursor INTO @name
        WHILE   @@FETCH_STATUS = 0
        BEGIN
            SET @sql = 'ALTER SCHEMA '+ @newSchema +' TRANSFER '+ @oldSchema + '.' +  @name         
            BEGIN TRY
                exec(@sql)
                PRINT 'Success: ' + @sql
            END TRY
            BEGIN CATCH
                PRINT 'Error executing: ' + @sql
            END CATCH
            FETCH NEXT FROM objCursor INTO @name
        END
CLOSE   objCursor
DEALLOCATE  objCursor

END

It will execute a code like this

ALTER SCHEMA dbo TRANSFER MyOldSchema.xx_GetUserInformation

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

Convert columns to string in Pandas

Using .apply() with a lambda conversion function also works in this case:

total_rows['ColumnID'] = total_rows['ColumnID'].apply(lambda x: str(x))

For entire dataframes you can use .applymap(). (but in any case probably .astype() is faster)

Formatting floats without trailing zeros

"{:.5g}".format(x)

I use this to format floats to trail zeros.

How to convert a column of DataTable to a List

I make a sample for you , and I hope this is helpful...

    static void Main(string[] args)
    {
        var cols = new string[] { "col1", "col2", "col3", "col4", "col5" };

        DataTable table = new DataTable();
        foreach (var col in cols)
            table.Columns.Add(col);

        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });
        table.Rows.Add(new object[] { "1", "2", "3", "4", "5" });

        foreach (var col in cols)
        {
            var results = from p in table.AsEnumerable()
                          select p[col];

            Console.WriteLine("*************************");
            foreach (var result in results)
            {
                Console.WriteLine(result);
            }
        }


        Console.ReadLine();
    }

How to rename uploaded file before saving it into a directory?

/* create new name file */
$filename   = uniqid() . "-" . time(); // 5dab1961e93a7-1571494241
$extension  = pathinfo( $_FILES["file"]["name"], PATHINFO_EXTENSION ); // jpg
$basename   = $filename . "." . $extension; // 5dab1961e93a7_1571494241.jpg

$source       = $_FILES["file"]["tmp_name"];
$destination  = "../img/imageDirectory/{$basename}";

/* move the file */
move_uploaded_file( $source, $destination );

echo "Stored in: {$destination}";

How to check if a file exists from inside a batch file

Try something like the following example, quoted from the output of IF /? on Windows XP:

IF EXIST filename. (
    del filename.
) ELSE (
    echo filename. missing.
)

You can also check for a missing file with IF NOT EXIST.

The IF command is quite powerful. The output of IF /? will reward careful reading. For that matter, try the /? option on many of the other built-in commands for lots of hidden gems.  

If statement for strings in python?

proceed = "y", "Y"
if answer in proceed:

Also, you don't want

answer = str(input("Is the information correct? Enter Y for yes or N for no"))

You want

answer = raw_input("Is the information correct? Enter Y for yes or N for no")

input() evaluates whatever is entered as a Python expression, raw_input() returns a string.

Edit: That is only true on Python 2. On Python 3, input is fine, although str() wrapping is still redundant.

Swift do-try-catch syntax

I was also disappointed by the lack of type a function can throw, but I get it now thanks to @rickster and I'll summarize it like this: let's say we could specify the type a function throws, we would have something like this:

enum MyError: ErrorType { case ErrorA, ErrorB }

func myFunctionThatThrows() throws MyError { ...throw .ErrorA...throw .ErrorB... }

do {
    try myFunctionThatThrows()
}
case .ErrorA { ... }
case .ErrorB { ... }

The problem is that even if we don't change anything in myFunctionThatThrows, if we just add an error case to MyError:

enum MyError: ErrorType { case ErrorA, ErrorB, ErrorC }

we are screwed because our do/try/catch is no longer exhaustive, as well as any other place where we called functions that throw MyError

How do I upgrade to Python 3.6 with conda?

Best method I found:

source activate old_env
conda env export > old_env.yml

Then process it with something like this:

with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
    for line in fin:
        if 'py35' in line:  # replace by the version you want to supersede
            line = line[:line.rfind('=')] + '\n'
        fout.write(line)

then edit manually the first (name: ...) and last line (prefix: ...) to reflect your new environment name and run:

conda env create -f new_env.yml

you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env is found incompatible or missing for the new python version.

I wish there was a built-in, easier way...

How can I delete an item from an array in VB.NET?

As Heinzi said, an array has a fixed size. In order to 'remove an item' or 'resize' it, you'll have to create a new array with the desired size and copy the items you need as appropriate.

Here's code to remove an item from an array:

<System.Runtime.CompilerServices.Extension()> _
Function RemoveAt(Of T)(ByVal arr As T(), ByVal index As Integer) As T()
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        Return outArr
    End If
End Function

You can use it as such:

Module Module1

    Sub Main()
        Dim arr = New String() {"abc", "mno", "xyz"}
        arr.RemoveAt(1)
    End Sub
End Module

The code above removes the second element ("mno") [which has an index of 1] from the array.

You need to be developing in .NET 3.5 or higher in order to use the extension method. If you're using .NET 2.0 or 3.0, you can call the method as such

arr = RemoveAt(arr, 1)

I hope this is what you need.

Update

After running tests based on ToolMakerSteve's comment it appears the initial code does not modify the array you want to update because of the ByVal used in the function's declaration. However, writing code like arr = arr.RemoveAt(1) or arr = RemoveAt(arr, 1) does modify the array because it reassigns the modified array to the original.

Find below the updated method (subroutine) for removing an element from an array.

<System.Runtime.CompilerServices.Extension()> _
Public Sub RemoveAt(Of T)(ByRef arr As T(), ByVal index As Integer)
    Dim uBound = arr.GetUpperBound(0)
    Dim lBound = arr.GetLowerBound(0)
    Dim arrLen = uBound - lBound

    If index < lBound OrElse index > uBound Then
        Throw New ArgumentOutOfRangeException( _
        String.Format("Index must be from {0} to {1}.", lBound, uBound))

    Else
        'create an array 1 element less than the input array
        Dim outArr(arrLen - 1) As T
        'copy the first part of the input array
        Array.Copy(arr, 0, outArr, 0, index)
        'then copy the second part of the input array
        Array.Copy(arr, index + 1, outArr, index, uBound - index)

        arr = outArr
    End If
End Sub

Usage of the method is similar to the original, except there is no return value this time so trying to assign an array from the return value will not work because nothing is returned.

Dim arr = New String() {"abc", "mno", "xyz"}
arr.RemoveAt(1)  ' Output: {"abc", "mno"} (works on .NET 3.5 and higher)
RemoveAt(arr, 1) ' Output: {"abc", "mno"} (works on all versions of .NET fx)
arr = arr.RemoveAt(1)  'will not work; no return value
arr = RemoveAt(arr, 1) 'will not work; no return value

Note:

  1. I use a temporary array for the process because it makes my intentions clear and that is exactly what VB.NET does behind the scenes when you do Redim Preserve. If you would like to modify the array in-place using Redim Preserve, see ToolmakerSteve's answer.

  2. The RemoveAt methods written here are extension methods. In order for them to work, you will have to paste them in a Module. Extension methods will not work in VB.NET if they are placed in a Class.

  3. Important If you will be modifying your array with lots of 'removes', it is highly recommended to use a different data structure such as List(Of T) as suggested by other answerers to this question.

More than 1 row in <Input type="textarea" />

Why not use the <textarea> tag?

?<textarea id="txtArea" rows="10" cols="70"></textarea>

Does Python have a package/module management system?

It's called setuptools. You run it with the "easy_install" command.

You can find the directory at http://pypi.python.org/

How to get the size of a string in Python?

Do you want to find the length of the string in python language ? If you want to find the length of the word, you can use the len function.

string = input("Enter the string : ")

print("The string length is : ",len(string))

OUTPUT : -

Enter the string : viral

The string length is : 5

How to vertically center <div> inside the parent element with CSS?

divs can't be vertically aligned that way, you can however use margins or position:relative to modify its location.

.includes() not working in Internet Explorer

includes() is not supported by most browsers. Your options are either to use

-polyfill from MDN https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/includes

or to use

-indexof()

var str = "abcde";
var n = str.indexOf("cd");

Which gives you n=2

This is widely supported.

how does Request.QueryString work?

The Request object is the entire request sent out to some server. This object comes with a QueryString dictionary that is everything after '?' in the URL.

Not sure exactly what you were looking for in an answer, but check out http://en.wikipedia.org/wiki/Query_string

How to recover Git objects damaged by hard disk failure?

I have resolved this problem to add some change like git add -A and git commit again.

Difference between Running and Starting a Docker container

daniele3004's answer is already pretty good.

Just a quick and dirty formula for people like me who mixes up run and start from time to time:

docker run [...] = docker pull [...] + docker start [...]

Print <div id="printarea"></div> only?

Use a special Stylesheet for printing

<link rel="stylesheet" href="print.css" type="text/css" media="print" />

and then add a class i.e. "noprint" to every tag which's content you don't want to print.

In the CSS use

.noprint {
  display: none;
}

Selecting last element in JavaScript array

Use the slice() method:

my_array.slice(-1)[0]

Parsing XML with namespace in Python via 'ElementTree'

I've been using similar code to this and have found it's always worth reading the documentation... as usual!

findall() will only find elements which are direct children of the current tag. So, not really ALL.

It might be worth your while trying to get your code working with the following, especially if you're dealing with big and complex xml files so that that sub-sub-elements (etc.) are also included. If you know yourself where elements are in your xml, then I suppose it'll be fine! Just thought this was worth remembering.

root.iter()

ref: https://docs.python.org/3/library/xml.etree.elementtree.html#finding-interesting-elements "Element.findall() finds only elements with a tag which are direct children of the current element. Element.find() finds the first child with a particular tag, and Element.text accesses the element’s text content. Element.get() accesses the element’s attributes:"

How can I detect if this dictionary key exists in C#?

You can use ContainsKey:

if (dict.ContainsKey(key)) { ... }

or TryGetValue:

dict.TryGetValue(key, out value);

Update: according to a comment the actual class here is not an IDictionary but a PhysicalAddressDictionary, so the methods are Contains and TryGetValue but they work in the same way.

Example usage:

PhysicalAddressEntry entry;
PhysicalAddressKey key = c.PhysicalAddresses[PhysicalAddressKey.Home].Street;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    row["HomeStreet"] = entry;
}

Update 2: here is the working code (compiled by question asker)

PhysicalAddressEntry entry;
PhysicalAddressKey key = PhysicalAddressKey.Home;
if (c.PhysicalAddresses.TryGetValue(key, out entry))
{
    if (entry.Street != null)
    {
        row["HomeStreet"] = entry.Street.ToString();
    }
}

...with the inner conditional repeated as necessary for each key required. The TryGetValue is only done once per PhysicalAddressKey (Home, Work, etc).

Excel how to fill all selected blank cells with text

I don't believe search and replace will do it for you (doesn't work for me in Excel 2010 Home). Are you sure you want to put "null" in EVERY cell in the sheet? That is millions of cells, in which case there is no way a search and replace would be able to handle it memory-wise (correct me if I am wrong).

In the case I am right and you don't want millions of "null" cells, then here is a macro. It asks you to select the range then put "null" inside every cell that was blank.

Sub FillWithNull()

Dim cell As range
Dim myRange As range

Set myRange = Application.InputBox("Select the range", Type:=8)
Application.ScreenUpdating = False

For Each cell In myRange
    If Len(cell) = 0 Then
        cell.Value = "Null"
    End If
Next

Application.ScreenUpdating = True

End Sub

Multiple Errors Installing Visual Studio 2015 Community Edition

Success!

I had similar problems and tried re-installing several times, but no joy. I was looking at installing individual packages from the ISO and all of the fiddling around - not happy at all.

I finally got it to "install" by simply selecting "repair" rather than "uninstall" in control panel / programs. It took quite a while to do the "repair" though. In the end it is installed and working.

This worked for me. It may help others - easier to try than many other options, anyway.

Is there a reason for C#'s reuse of the variable in a foreach?

Having been bitten by this, I have a habit of including locally defined variables in the innermost scope which I use to transfer to any closure. In your example:

foreach (var s in strings)
    query = query.Where(i => i.Prop == s); // access to modified closure

I do:

foreach (var s in strings)
{
    string search = s;
    query = query.Where(i => i.Prop == search); // New definition ensures unique per iteration.
}        

Once you have that habit, you can avoid it in the very rare case you actually intended to bind to the outer scopes. To be honest, I don't think I have ever done so.

How do I resolve a TesseractNotFoundError?

This occurs under windows (at least in tesseract version 3.05) when the current directory is on a different drive from where tesseract is installed.

Something in tesseract is expecting data files to be in \Program Files... (rather than C:\Program Files, say). So if you're not on the same drive letter as tesseract, it will fail. It would be great if we could work around it by temporarily changing drives (under windows only) to the tesseract installation drive before executing tesseract, and changing back after. Example in your case: You can copy yourmodule_python.py to "C/Program Files (x86)/Tesseract-OCR/" and RUN!

What are Runtime.getRuntime().totalMemory() and freeMemory()?

Runtime#totalMemory - the memory that the JVM has allocated thus far. This isn't necessarily what is in use or the maximum.

Runtime#maxMemory - the maximum amount of memory that the JVM has been configured to use. Once your process reaches this amount, the JVM will not allocate more and instead GC much more frequently.

Runtime#freeMemory - I'm not sure if this is measured from the max or the portion of the total that is unused. I am guessing it is a measurement of the portion of total which is unused.

Understanding The Modulus Operator %

Step 1 : 5/7 = 0.71

Step 2 : Take the left side of the decimal , so we take 0 from 0.71 and multiply by 7 0*7 = 0;

Step # : 5-0 = 5 ; Therefore , 5%7 =5

How to see data from .RData file?

I think the problem is that you load isfar data.frame but you overwrite it by value returned by load.

Try either:

load("C:/Users/isfar.RData") 
head(isfar)

Or more general way

load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex) 

ERROR 1115 (42000): Unknown character set: 'utf8mb4'

Just open your sql file with a text editor and search for 'utf8mb4' and replace with utf8.I hope it would work for you

How to sort by Date with DataTables jquery plugin?

Specify the column's type as type: 'date':

{title: 'Expiration Date', data: 'ExpirationDate', type: 'date'}

How do I perform the SQL Join equivalent in MongoDB?

We can merge two collection by using mongoDB sub query. Here is example, Commentss--

`db.commentss.insert([
  { uid:12345, pid:444, comment:"blah" },
  { uid:12345, pid:888, comment:"asdf" },
  { uid:99999, pid:444, comment:"qwer" }])`

Userss--

db.userss.insert([
  { uid:12345, name:"john" },
  { uid:99999, name:"mia"  }])

MongoDB sub query for JOIN--

`db.commentss.find().forEach(
    function (newComments) {
        newComments.userss = db.userss.find( { "uid": newComments.uid } ).toArray();
        db.newCommentUsers.insert(newComments);
    }
);`

Get result from newly generated Collection--

db.newCommentUsers.find().pretty()

Result--

`{
    "_id" : ObjectId("5511236e29709afa03f226ef"),
    "uid" : 12345,
    "pid" : 444,
    "comment" : "blah",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f0"),
    "uid" : 12345,
    "pid" : 888,
    "comment" : "asdf",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f1"),
    "uid" : 99999,
    "pid" : 444,
    "comment" : "qwer",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f3"),
            "uid" : 99999,
            "name" : "mia"
        }
    ]
}`

Hope so this will help.

Cutting the videos based on start and end time using ffmpeg

new answer (fast)

You can make bash do the math for you, and it works with milliseconds.

toSeconds() {
    awk -F: 'NF==3 { print ($1 * 3600) + ($2 * 60) + $3 } NF==2 { print ($1 * 60) + $2 } NF==1 { print 0 + $1 }' <<< $1
}

StartSeconds=$(toSeconds "45.5")
EndSeconds=$(toSeconds "1:00.5")
Duration=$(bc <<< "(${EndSeconds} + 0.01) - ${StartSeconds}" | awk '{ printf "%.4f", $0 }')
ffmpeg -ss $StartSeconds -i input.mpg -t $Duration output.mpg

This, like the old answer, will produce a 15 second clip. This method is ideal even when clipping from deep within a large file because seeking isn't disabled, unlike the old answer. And yes, I've verified it's frame perfect.

NOTE: The start-time is INCLUSIVE and the end-time is normally EXCLUSIVE, hence the +0.01, to make it inclusive.

If you use mpv you can enable millisecond timecodes in the OSD with --osd-fractions


old answer with explanation (slow)

To cut based on start and end time from the source video and avoid having to do math, specify the end time as the input option and the start time as the output option.

ffmpeg -t 1:00 -i input.mpg -ss 45 output.mpg

This will produce a 15 second cut from 0:45 to 1:00.

This is because when -ss is given as an output option, the discarded time is still included in the total time read from the input, which -t uses to know when to stop. Whereas if -ss is given as an input option, the start time is seeked and not counted, which is where the confusion comes from.

It's slower than seeking since the omitted segment is still processed before being discarded, but this is the only way to do it as far as I know. If you're clipping from deep within a large file, it's more prudent to just do the math and use -ss for the input.

SyntaxError: Unexpected token o in JSON at position 1

Give a try catch like this, this will parse it if its stringified or else will take the default value

let example;
   try {
   example  = JSON.parse(data)
  } catch(e) {
    example = data
  }

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

I had the same problem and I found this solution working with bindParam :

    bindParam(':param', $myvar = NULL, PDO::PARAM_INT);

isset() and empty() - what to use

Empty returns true if the var is not set. But isset returns true even if the var is not empty.