Programs & Examples On #Job control

linux: kill background task

This should kill all background processes:

jobs -p | xargs kill -9

Conda environments not showing up in Jupyter Notebook

In my case, using Windows 10 and conda 4.6.11, by running the commands

conda install nb_conda

conda install -c conda-forge nb_conda_kernels

from the terminal while having the environment active didn't do the job after I opened Jupyter from the same command line using conda jupyter notebook.

The solution was apparently to opened Jupyter from the Anaconda Navigator by going to my environment in Environments: Open Anaconda Navigator, select the environment in Environments, press on the "play" button on the chosen environment, and select 'open with Jupyter Notebook'.

Environments in Anaconda Navigator to run Jupyter from the selected environment

What is the difference between decodeURIComponent and decodeURI?

As I had the same question, but didn't find the answer here, I made some tests in order to figure out what the difference actually is. I did this, since I need the encoding for something, which is not URL/URI related.

  • encodeURIComponent("A") returns "A", it does not encode "A" to "%41"
  • decodeURIComponent("%41") returns "A".
  • encodeURI("A") returns "A", it does not encode "A" to "%41"
  • decodeURI("%41") returns "A".

-That means both can decode alphanumeric characters, even though they did not encode them. However...

  • encodeURIComponent("&") returns "%26".
  • decodeURIComponent("%26") returns "&".
  • encodeURI("&") returns "&".
  • decodeURI("%26") returns "%26".

Even though encodeURIComponent does not encode all characters, decodeURIComponent can decode any value between %00 and %7F.

Note: It appears that if you try to decode a value above %7F (unless it's a unicode value), then your script will fail with an "URI error".

Python URLLib / URLLib2 POST

u = urllib2.urlopen('http://myserver/inout-tracker', data)
h.request('POST', '/inout-tracker/index.php', data, headers)

Using the path /inout-tracker without a trailing / doesn't fetch index.php. Instead the server will issue a 302 redirect to the version with the trailing /.

Doing a 302 will typically cause clients to convert a POST to a GET request.

How can I install Visual Studio Code extensions offline?

If you have a specific (legacy) version of VSCode on your offline instance, pulling the latest extensions might not properly integrate.

To make sure that VSCode and the extensions work together, they must all be installed together on the online machine. This resolves any dependencies (with specific versions), and ensures the exact configuration of the offline instance.

Quick steps:

Install the VSCode version, turn off updating, and install the extensions. Copy the extensions from the installed location and place them on the target machine.

Detailed steps:

Install the exact version of VSCode on online machine. Then turn off updates by going to File -> Preferences -> Settings. In the Settings window, under User Settings -> Application, go to Update section, and change the parameter for Channel to none. This prevents VSCode from reaching out to the internet and auto-updating your versions to the latest.

Then go to the VSCode extensions section and install all of your desired extensions. Copy the installed extensions from their install location (with windows its C:\Users\<username>\.vscode\extensions) to the same location on the target machine.

Works perfectly.

Bootstrap Modal Backdrop Remaining

An issue I was having (may help someone) was simply that I was using a partial to load the Modal.

<li data-toggle="modal" data-target="#priceInfoModal">
<label>Listing Price</label>
<i class="fa fa-money"></i>
@Html.Partial("EditPartials/PriceInfo_Edit")
</li>

I had placed the partial call inside the same list item So data-target="#priceInfoModal" and div id="priceInfoModal" were in the same container causing me to not be able to close my modal

Javascript to check whether a checkbox is being checked or unchecked

function CHeck(){
    var ChkBox = document.getElementById("CheckBox1");
    alert(ChkBox.Checked);
}

<asp:CheckBox ID="CheckBox1" runat="server" onclick="CHeck()" />

Is an empty href valid?

A word of caution:

In my experience, omitting the href attribute causes problems for accessibility as the keyboard navigation will ignore it and never give it focus like it will when href is present. Manually including your element in the tabindex is a way around that.

Why is Visual Studio 2013 very slow?

There is a good workaround for this solution if you are experiencing slowness in rendering the .cs files and .cshtml files.

Just close all the files opened so that the cache gets cleared and open the required files again.

Bootstrap tab activation with JQuery

Applying a selector from the .nav-tabs seems to be working: See this demo.

$(document).ready(function(){
    activaTab('aaa');
});

function activaTab(tab){
    $('.nav-tabs a[href="#' + tab + '"]').tab('show');
};

I would prefer @codedme's answer, since if you know which tab you want prior to page load, you should probably change the page html and not use JS for this particular task.

I tweaked the demo for his answer, as well.

(If this is not working for you, please specify your setting - browser, environment, etc.)

Escape double quote in VB string

Another example:

Dim myPath As String = """" & Path.Combine(part1, part2) & """"

Good luck!

What does %~d0 mean in a Windows batch file?

Another tip that would help a lot is that to set the current directory to a different drive one would have to use %~d0 first, then cd %~dp0. This will change the directory to the batch file's drive, then change to its folder.

For #oneLinerLovers, cd /d %~dp0 will change both the drive and directory :)

Hope this helps someone.

Copy or rsync command

For a local copy, the only advantage of rsync is that it will avoid copying if the file already exists in the destination directory. The definition of "already exists" is (a) same file name (b) same size (c) same timestamp. (Maybe same owner/group; I am not sure...)

The "rsync algorithm" is great for incremental updates of a file over a slow network link, but it will not buy you much for a local copy, as it needs to read the existing (partial) file to run it's "diff" computation.

So if you are running this sort of command frequently, and the set of changed files is small relative to the total number of files, you should find that rsync is faster than cp. (Also rsync has a --delete option that you might find useful.)

How to call a vue.js function on page load

You need to do something like this (If you want to call the method on page load):

new Vue({
    // ...
    methods:{
        getUnits: function() {...}
    },
    created: function(){
        this.getUnits()
    }
});

How to test valid UUID/GUID?

Beside Gambol's answer that will do the job in nearly all cases, all answers given so far missed that the grouped formatting (8-4-4-4-12) is not mandatory to encode GUIDs in text. It's used extremely often but obviously also a plain chain of 32 hexadecimal digits can be valid.[1] regexenh:

/^[0-9a-f]{8}-?[0-9a-f]{4}-?[1-5][0-9a-f]{3}-?[89ab][0-9a-f]{3}-?[0-9a-f]{12}$/i

[1] The question is about checking variables, so we should include the user-unfriendly form as well.

How to add "class" to host element?

for multiple classes situation, as @jbojcic mentioned above, you can use:

host: {class: 'A B C'}

Calculating distance between two geographic locations

public double distance(Double latitude, Double longitude, double e, double f) {
        double d2r = Math.PI / 180;

        double dlong = (longitude - f) * d2r;
        double dlat = (latitude - e) * d2r;
        double a = Math.pow(Math.sin(dlat / 2.0), 2) + Math.cos(e * d2r)
                * Math.cos(latitude * d2r) * Math.pow(Math.sin(dlong / 2.0), 2)
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = 6367 * c;
                return d;

    }

Limit results in jQuery UI Autocomplete

Plugin: jquery-ui-autocomplete-scroll with scroller and limit results are beautiful

$('#task').autocomplete({
  maxShowItems: 5,
  source: myarray
});

Global and local variables in R

Variables declared inside a function are local to that function. For instance:

foo <- function() {
    bar <- 1
}
foo()
bar

gives the following error: Error: object 'bar' not found.

If you want to make bar a global variable, you should do:

foo <- function() {
    bar <<- 1
}
foo()
bar

In this case bar is accessible from outside the function.

However, unlike C, C++ or many other languages, brackets do not determine the scope of variables. For instance, in the following code snippet:

if (x > 10) {
    y <- 0
}
else {
    y <- 1
}

y remains accessible after the if-else statement.

As you well say, you can also create nested environments. You can have a look at these two links for understanding how to use them:

  1. http://stat.ethz.ch/R-manual/R-devel/library/base/html/environment.html
  2. http://stat.ethz.ch/R-manual/R-devel/library/base/html/get.html

Here you have a small example:

test.env <- new.env()

assign('var', 100, envir=test.env)
# or simply
test.env$var <- 100

get('var') # var cannot be found since it is not defined in this environment
get('var', envir=test.env) # now it can be found

How to serialize SqlAlchemy result to JSON?

Maybe you can use a class like this

from sqlalchemy.ext.declarative import declared_attr
from sqlalchemy import Table


class Custom:
    """Some custom logic here!"""

    __table__: Table  # def for mypy

    @declared_attr
    def __tablename__(cls):  # pylint: disable=no-self-argument
        return cls.__name__  # pylint: disable= no-member

    def to_dict(self) -> Dict[str, Any]:
        """Serializes only column data."""
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}

Base = declarative_base(cls=Custom)

class MyOwnTable(Base):
    #COLUMNS!

With that all objects have the to_dict method

Find rows that have the same value on a column in MySQL

Here is query to find email's which are used for more then one login_id:

SELECT email
FROM table
GROUP BY email
HAVING count(*) > 1

You'll need second (of nested) query to get list of login_id by email.

Wget output document and headers to STDOUT

It works here:

    $ wget -S -O - http://google.com
HTTP request sent, awaiting response... 
  HTTP/1.1 301 Moved Permanently
  Location: http://www.google.com/
  Content-Type: text/html; charset=UTF-8
  Date: Sat, 25 Aug 2012 10:15:38 GMT
  Expires: Mon, 24 Sep 2012 10:15:38 GMT
  Cache-Control: public, max-age=2592000
  Server: gws
  Content-Length: 219
  X-XSS-Protection: 1; mode=block
  X-Frame-Options: SAMEORIGIN
Location: http://www.google.com/ [following]
--2012-08-25 12:20:29--  http://www.google.com/
Resolving www.google.com (www.google.com)... 173.194.69.99, 173.194.69.104, 173.194.69.106, ...

  ...skipped a few more redirections ...

    [<=>                                                                                                                                     ] 0           --.-K/s              
<!doctype html><html itemscope="itemscope" itemtype="http://schema.org/WebPage"><head><meta itemprop="image" content="/images/google_favicon_128.png"><ti 

... skipped ...

perhaps you need to update your wget (~$ wget --version GNU Wget 1.14 built on linux-gnu.)

HTML5 Video Autoplay not working correctly

_x000D_
_x000D_
html {_x000D_
  padding: 20px 0;_x000D_
  background-color: #efefef;_x000D_
}_x000D_
_x000D_
body {_x000D_
  width: 400px;_x000D_
  padding: 40px;_x000D_
  margin: 0 auto;_x000D_
  background: #fff;_x000D_
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
video {_x000D_
  width: 400px;_x000D_
  display: block;_x000D_
}
_x000D_
<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>_x000D_
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />_x000D_
    Your browser does not support the video tag or the file format of this video._x000D_
</video>
_x000D_
_x000D_
_x000D_

Having Django serve downloadable files

You should use sendfile apis given by popular servers like apache or nginx in production. Many years i was using sendfile api of these servers for protecting files. Then created a simple middleware based django app for this purpose suitable for both development & production purpose.You can access the source code here.
UPDATE: in new version python provider uses django FileResponse if available and also adds support for many server implementations from lighthttp, caddy to hiawatha

Usage

pip install django-fileprovider
  • add fileprovider app to INSTALLED_APPS settings,
  • add fileprovider.middleware.FileProviderMiddleware to MIDDLEWARE_CLASSES settings
  • set FILEPROVIDER_NAME settings to nginx or apache in production, by default it is python for development purpose.

in your classbased or function views set response header X-File value to absolute path to the file. For example,

def hello(request):  
   // code to check or protect the file from unauthorized access
   response = HttpResponse()  
   response['X-File'] = '/absolute/path/to/file'  
   return response  

django-fileprovider impemented in a way that your code will need only minimum modification.

Nginx configuration

To protect file from direct access you can set the configuration as

 location /files/ {
  internal;
  root   /home/sideffect0/secret_files/;
 }

Here nginx sets a location url /files/ only access internaly, if you are using above configuration you can set X-File as,

response['X-File'] = '/files/filename.extension' 

By doing this with nginx configuration, the file will be protected & also you can control the file from django views

What is Options +FollowSymLinks?

You might try searching the internet for ".htaccess Options not allowed here".

A suggestion I found (using google) is:

Check to make sure that your httpd.conf file has AllowOverride All.

A .htaccess file that works for me on Mint Linux (placed in the Laravel /public folder):

# Apache configuration file
# http://httpd.apache.org/docs/2.2/mod/quickreference.html

# Turning on the rewrite engine is necessary for the following rules and
# features. "+FollowSymLinks" must be enabled for this to work symbolically.

<IfModule mod_rewrite.c>
    Options +FollowSymLinks
    RewriteEngine On
</IfModule>

# For all files not found in the file system, reroute the request to the
# "index.php" front controller, keeping the query string intact

<IfModule mod_rewrite.c>
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

Hope this helps you. Otherwise you could ask a question on the Laravel forum (http://forums.laravel.com/), there are some really helpful people hanging around there.

Entity Framework Provider type could not be loaded?

I finally resolved this. Turns out, I had an erroneous implementation of IDIsposable in my repository class. I fixed that. The erroneous implementation caused a stackoverflow exception since I wasn't disposing off resources properly. This caused VS not to run the tests and the test execution engine crashed.

I filed it with Microsoft here ( this was before I got the correct solution). connect.microsoft.com/VisualStudio/feedback/details/775868/vs-test-execution-crashes-in-vs-2012#details

Anyway, the builds now run fine on teamcity. ALthough, I am still curious why neither VS Test execution engine had a graceful way of telling me what was happening not Team City.

I discovered the root cause by manually debugging the test ( which I only realised after so many days , the fix took me 5 seconds).

Hopefully this will help someone who comes across such issues.

How to set text color in submit button?

you try this:

<input type="submit" style="font-face: 'Comic Sans MS'; font-size: larger; color: teal; background-color: #FFFFC0; border: 3pt ridge lightgrey" value=" Send Me! ">

EF Code First "Invalid column name 'Discriminator'" but no inheritance

I had a similar problem, not exactly the same conditions and then i saw this post. Hope it helps someone. Apparently i was using one of my EF entity models a base class for a type that was not specified as a db set in my dbcontext. To fix this issue i had to create a base class that had all the properties common to the two types and inherit from the new base class among the two types.

Example:

//Bad Flow
    //class defined in dbcontext as a dbset
    public class Customer{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //class not defined in dbcontext as a dbset
    public class DuplicateCustomer:Customer{ 
       public object DuplicateId {get; set;}
    }


    //Good/Correct flow*
    //Common base class
    public class CustomerBase{ 
       public int Id {get; set;}
       public string Name {get; set;}
    }

    //entity model referenced in dbcontext as a dbset
    public class Customer: CustomerBase{

    }

    //entity model not referenced in dbcontext as a dbset
    public class DuplicateCustomer:CustomerBase{

       public object DuplicateId {get; set;}

    }

Is calculating an MD5 hash less CPU intensive than SHA family functions?

The real answer is : It depends

There are a couple factors to consider, the most obvious are : the cpu you are running these algorithms on and the implementation of the algorithms.

For instance, me and my friend both run the exact same openssl version and get slightly different results with different Intel Core i7 cpus.

My test at work with an Intel(R) Core(TM) i7-2600 CPU @ 3.40GHz

The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              64257.97k   187370.26k   406435.07k   576544.43k   649827.67k
sha1             73225.75k   202701.20k   432679.68k   601140.57k   679900.50k

And his with an Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz

The 'numbers' are in 1000s of bytes per second processed.
type             16 bytes     64 bytes    256 bytes   1024 bytes   8192 bytes
md5              51859.12k   156255.78k   350252.00k   513141.73k   590701.52k
sha1             56492.56k   156300.76k   328688.76k   452450.92k   508625.68k

We both are running the exact same binaries of OpenSSL 1.0.1j 15 Oct 2014 from the ArchLinux official package.

My opinion on this is that with the added security of sha1, cpu designers are more likely to improve the speed of sha1 and more programmers will be working on the algorithm's optimization than md5sum.

I guess that md5 will no longer be used some day since it seems that it has no advantage over sha1. I also tested some cases on real files and the results were always the same in both cases (likely limited by disk I/O).

md5sum of a large 4.6GB file took the exact same time than sha1sum of the same file, same goes with many small files (488 in the same directory). I ran the tests a dozen times and they were consitently getting the same results.

--

It would be very interesting to investigate this further. I guess there are some experts around that could provide a solid answer to why sha1 is getting faster than md5 on newer processors.

How to put a new line into a wpf TextBlock control?

You can try putting a new line in the data:

<data>Foo bar baz 
 baz bar</data>

If that does not work you might need to parse the string manually.

If you need direct XAML that's easy by the way:

<TextBlock>
    Lorem <LineBreak/>
    Ipsum
</TextBlock>

Adding values to specific DataTable cells

If it were a completely new row that you wanted to only set one value, you would need to add the whole row and then set the individual value:

DataRow dr = dt.NewRow();
dr[3].Value = "Some Value";
dt.Rows.Add(dr);

Otherwise, you can find the existing row and set the cell value

DataRow dr = dt.Rows[theRowNumber];
dr[3] = "New Value";

Difference between Xms and Xmx and XX:MaxPermSize

Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.

The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.

-Xmssize Specifies the initial heap size.

-Xmxsize Specifies the maximum heap size.

-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.

Sizes are expressed in bytes. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes.

References:

How is the java memory pool divided?

What is perm space?

Java (JVM) Memory Model – Memory Management in Java

Java 7 SE Command Line Options

Java 7 HotSpot VM Options

How to define the css :hover state in a jQuery selector?

Use JQuery Hover to add/remove class or style on Hover:

$( "mah div" ).hover(
  function() {
    $( this ).css("background-color","red");
  }, function() {
    $( this ).css("background-color",""); //to remove property set it to ''
  }
);

How to change the background colour's opacity in CSS

Use RGB values combined with opacity to get the transparency that you wish.

For instance,

<div style=" background: rgb(255, 0, 0) ; opacity: 0.2;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.4;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.6;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 0.8;">&nbsp;</div>
<div style=" background: rgb(255, 0, 0) ; opacity: 1;">&nbsp;</div>

Similarly, with actual values without opacity, will give the below.

<div style=" background: rgb(243, 191, 189) ; ">&nbsp;</div>
<div style=" background: rgb(246, 143, 142) ; ">&nbsp;</div>
<div style=" background: rgb(249, 95 , 94)  ; ">&nbsp;</div>
<div style=" background: rgb(252, 47, 47)   ; ">&nbsp;</div>
<div style=" background: rgb(255, 0, 0)     ; ">&nbsp;</div>

You can have a look at this WORKING EXAMPLE.

Now, if we specifically target your issue, here is the WORKING DEMO SPECIFIC TO YOUR ISSUE.

The HTML

<div class="social">
    <img src="http://www.google.co.in/images/srpr/logo4w.png" border="0" />
</div>

The CSS:

social img{
    opacity:0.5;
}
.social img:hover {
    opacity:1;
    background-color:black;
    cursor:pointer;
    background: rgb(255, 0, 0) ; opacity: 0.5;
}

Hope this helps Now.

Define an alias in fish shell

Just use alias. Here's a basic example:

# Define alias in shell
alias rmi "rm -i"

# Define alias in config file
alias rmi="rm -i"

# This is equivalent to entering the following function:
function rmi
    rm -i $argv
end

# Then, to save it across terminal sessions:
funcsave rmi

This last command creates the file ~/.config/fish/functions/rmi.fish.

Interested people might like to find out more about fish aliases in the official manual.

java.security.AccessControlException: Access denied (java.io.FilePermission

Although it is not recommended, but if you really want to let your web application access a folder outside its deployment directory. You need to add following permission in java.policy file (path is as in the reply of Petey B)

permission java.io.FilePermission "your folder path", "write"

In your case it would be

permission java.io.FilePermission "S:/PDSPopulatingProgram/-", "write"

Here /- means any files or sub-folders inside this folder.

Warning: But by doing this, you are inviting some security risk.

symfony 2 No route found for "GET /"

This work for me:

cache:clear --env=prod

How do I subtract minutes from a date in javascript?

This is what I did: see on Codepen

var somedate = 1473888180593;
var myStartDate;
//var myStartDate = somedate - durationInMuntes;

myStartDate = new Date(dateAfterSubtracted('minutes', 100));

alert("The event will start on " + myStartDate.toDateString() + " at " + myStartDate.toTimeString());

function dateAfterSubtracted(range, amount){
    var now = new Date();
    if(range === 'years'){
        return now.setDate(now.getYear() - amount);
    }
    if(range === 'months'){
        return now.setDate(now.getMonth() - amount);
    }
    if(range === 'days'){
        return now.setDate(now.getDate() - amount);
    }
    if(range === 'hours'){
        return now.setDate(now.getHours() - amount);
    }
    if(range === 'minutes'){
        return now.setDate(now.getMinutes() - amount);
    }
    else {
        return null;
    }
}

How to launch a Google Chrome Tab with specific URL using C#

If the user doesn't have Chrome, it will throw an exception like this:

    //chrome.exe http://xxx.xxx.xxx --incognito
    //chrome.exe http://xxx.xxx.xxx -incognito
    //chrome.exe --incognito http://xxx.xxx.xxx
    //chrome.exe -incognito http://xxx.xxx.xxx
    private static void Chrome(string link)
    {
        string url = "";

        if (!string.IsNullOrEmpty(link)) //if empty just run the browser
        {
            if (link.Contains('.')) //check if it's an url or a google search
            {
                url = link;
            }
            else
            {
                url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
            }
        }

        try
        {
            Process.Start("chrome.exe", url + " --incognito");
        }
        catch (System.ComponentModel.Win32Exception e)
        {
            MessageBox.Show("Unable to find Google Chrome...",
                "chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

Get loop counter/index using for…of syntax in JavaScript

In ES6, it is good to use for - of loop. You can get index in for of like this

for (let [index, val] of array.entries()) {
        // your code goes here    
}

Note that Array.entries() returns an iterator, which is what allows it to work in the for-of loop; don't confuse this with Object.entries(), which returns an array of key-value pairs.

Set System.Drawing.Color values

You could create a color using the static FromArgb method:

Color redColor = Color.FromArgb(255, 0, 0);

You can also specify the alpha using the following overload.

How do I find duplicates across multiple columns?

 SELECT name, city, count(*) as qty 
 FROM stuff 
 GROUP BY name, city HAVING count(*)> 1

Securing a password in a properties file

The poor mans compromise solution is to use a simplistic multi signature approach.

For Example the DBA sets the applications database password to a 50 character random string. TAKqWskc4ncvKaJTyDcgAHq82X7tX6GfK2fc386bmNw3muknjU

He or she give half the password to the application developer who then hard codes it into the java binary.

private String pass1 = "TAKqWskc4ncvKaJTyDcgAHq82"

The other half of the password is passed as a command line argument. the DBA gives pass2 to the system support or admin person who either enters it a application start time or puts it into the automated application start up script.

java -jar /myapplication.jar -pass2 X7tX6GfK2fc386bmNw3muknjU

When the application starts it uses pass1 + pass2 and connects to the database.

This solution has many advantages with out the downfalls mentioned.

You can safely put half the password in a command line arguments as reading it wont help you much unless you are the developer who has the other half of the password.

The DBA can also still change the second half of the password and the developer need not have to re-deploy the application.

The source code can also be semi public as reading it and the password will not give you application access.

You can further improve the situation by adding restrictions on the IP address ranges the database will accept connections from.

download file using an ajax request

For those looking a more modern approach, you can use the fetch API. The following example shows how to download a spreadsheet file. It is easily done with the following code.

fetch(url, {
    body: JSON.stringify(data),
    method: 'POST',
    headers: {
        'Content-Type': 'application/json; charset=utf-8'
    },
})
.then(response => response.blob())
.then(response => {
    const blob = new Blob([response], {type: 'application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
    const downloadUrl = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = downloadUrl;
    a.download = "file.xlsx";
    document.body.appendChild(a);
    a.click();
})

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following link.

Important: In this example I am sending a JSON request to a server listening on the given url. This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8, as to let the server know the type of request it will receive.

Instagram: Share photo from webpage

As of November 17, 2015. This rule has officially changed. Instagram has deprecated the rule against using their API to upload images.

Good luck.

jquery data selector

Here's a plugin that simplifies life https://github.com/rootical/jQueryDataSelector

Use it like that:

data selector           jQuery selector
  $$('name')              $('[data-name]')
  $$('name', 10)          $('[data-name=10]')
  $$('name', false)       $('[data-name=false]')
  $$('name', null)        $('[data-name]')
  $$('name', {})          Syntax error

Input placeholders for Internet Explorer

Best one in my experience is https://github.com/mathiasbynens/jquery-placeholder (recommended by html5please.com). http://afarkas.github.com/webshim/demos/index.html also has a good solution among its much more extensive library of polyfills.

Apache default VirtualHost

I will say what worked for me, the others answers above didn't help to my case at all. I hope it can help someone.

Actually, I'm using Virtual host configuration (sites-available / sites-enabled) on EC2 Linux AMI with Apache/2.4.39 (Amazon). So, I have 1 ec2 instance to serve many sites (domains).

Considering that you already have Virtual Host installed and working. In my folder /etc/httpd/sites-available, I have some files with domain names (suffix .conf), for example: domain.com.conf. Create a new file like that.

sudo nano /etc/httpd/sites-available/domain.com.conf

<VirtualHost *:80>
    ServerName www.domain.com
    ServerAlias domain.com
    DocumentRoot /var/www/html/domain
</VirtualHost>

For each file.conf in sites-available, I create a symbolic link:

sudo ln -s /etc/httpd/sites-available/domain.com.conf /etc/httpd/sites-enabled/domain.com.conf

This is the default configuration, so, if access directly by IP of Server, you will be redirect to DocumentRoot of the first file (.conf) in sites-available folder, sorted by filename.

To have a default DocumentRoot folder when access by IP, you have to create a file named 0a.conf, then apache will serve this site because this new file will be the first in sites-available folder.

You must create a symbolic link:

sudo ln -s /etc/httpd/sites-available/0a.conf /etc/httpd/sites-enabled/0a.conf

To check serving order, use it:

sudo apachectl -S

Now, restart apache, and check out it.

Be happy =)

jquery: $(window).scrollTop() but no $(window).scrollBottom()

I would say that a scrollBottom as a direct opposite of scrollTop should be:

var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

Here is a small ugly test that works for me:

// SCROLLTESTER START //
$('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;"></h1>').insertAfter('body');

$(window).scroll(function () {
  var st = $(window).scrollTop();
  var scrollBottom = $(document).height() - $(window).height() - $(window).scrollTop();

  $('#st').replaceWith('<h1 id="st" style="position: fixed; right: 25px; bottom: 25px;">scrollTop: ' + st + '<br>scrollBottom: ' + scrollBottom + '</h1>');
});
// SCROLLTESTER END //

How to pass parameters using ui-sref in ui-router to controller

I've created an example to show how to. Updated state definition would be:

  $stateProvider
    .state('home', {
      url: '/:foo?bar',
      views: {
        '': {
          templateUrl: 'tpl.home.html',
          controller: 'MainRootCtrl'

        },
        ...
      }

And this would be the controller:

.controller('MainRootCtrl', function($scope, $state, $stateParams) {
    //..
    var foo = $stateParams.foo; //getting fooVal
    var bar = $stateParams.bar; //getting barVal
    //..
    $scope.state = $state.current
    $scope.params = $stateParams; 
})

What we can see is that the state home now has url defined as:

url: '/:foo?bar',

which means, that the params in url are expected as

/fooVal?bar=barValue

These two links will correctly pass arguments into the controller:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">

Also, the controller does consume $stateParams instead of $stateParam.

Link to doc:

You can check it here

params : {}

There is also new, more granular setting params : {}. As we've already seen, we can declare parameters as part of url. But with params : {} configuration - we can extend this definition or even introduce paramters which are not part of the url:

.state('other', {
    url: '/other/:foo?bar',
    params: { 
        // here we define default value for foo
        // we also set squash to false, to force injecting
        // even the default value into url
        foo: {
          value: 'defaultValue',
          squash: false,
        },
        // this parameter is now array
        // we can pass more items, and expect them as []
        bar : { 
          array : true,
        },
        // this param is not part of url
        // it could be passed with $state.go or ui-sref 
        hiddenParam: 'YES',
      },
    ...

Settings available for params are described in the documentation of the $stateProvider

Below is just an extract

  • value - {object|function=}: specifies the default value for this parameter. This implicitly sets this parameter as optional...
  • array - {boolean=}: (default: false) If true, the param value will be treated as an array of values.
  • squash - {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.

We can call these params this way:

// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&amp;bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">

Check it in action here

C# Help reading foreign characters using StreamReader

I'm also reading an exported file which contains french and German languages. I used Encoding.GetEncoding("iso-8859-1"), true which worked out without any challenges.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Add the following css to disable the default scroll:

body {
    overflow: hidden;
}

And change the #content css to this to make the scroll only on content body:

#content {
    max-height: calc(100% - 120px);
    overflow-y: scroll;
    padding: 0px 10%;
    margin-top: 60px;
}

See fiddle here.


Edit:

Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  bottom: 30px;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 50px;_x000D_
}_x000D_
footer {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

Get current domain

The only secure way of doing this

The only guaranteed secure method of retrieving the current domain is to store it in a secure location yourself.

Most frameworks take care of storing the domain for you, so you will want to consult the documentation for your particular framework. If you're not using a framework, consider storing the domain in one of the following places:

Secure methods of storing the domain Used By
A config file Joomla, Drupal/Symfony
The database WordPress
An environmental variable Laravel
A service registry Kubernetes DNS

The following work... but they're not secure

Hackers can make the following variables output whatever domain they want. This can lead to cache poisoning and barely noticeable phishing attacks.

$_SERVER['HTTP_HOST']

This gets the domain from the request headers which are open to manipulation by hackers. Same with:

$_SERVER['SERVER_NAME']

This one can be made better if the Apache setting usecanonicalname is turned off; in which case $_SERVER['SERVER_NAME'] will no longer be allowed to be populated with arbitrary values and will be secure. This is, however, non-default and not as common of a setup.

In popular systems

Below is how you can get the current domain in the following frameworks/systems:

WordPress

$urlparts = parse_url(home_url());
$domain = $urlparts['host'];

If you're constructing a URL in WordPress, just use home_url or site_url, or any of the other URL functions.

Laravel

request()->getHost()

The request()->getHost function is inherited from Symfony, and has been secure since the 2013 CVE-2013-4752 was patched.

Drupal

The installer does not yet take care of making this secure (issue #2404259). But in Drupal 8 there is documentation you can you can follow at Trusted Host Settings to secure your Drupal installation after which the following can be used:

\Drupal::request()->getHost();

Other frameworks

Feel free to edit this answer to include how to get the current domain in your favorite framework. When doing so, please include a link to the relevant source code or to anything else that would help me verify that the framework is doing things securely.


Addendum

Exploitation examples:

  1. Cache poisoning can happen if a botnet continuously requests a page using the wrong hosts header. The resulting HTML will then include links to the attackers website where they can phish your users. At first the malicious links will only be sent back to the hacker, but if the hacker does enough requests, the malicious version of the page will end up in your cache where it will be distributed to other users.

  2. A phishing attack can happen if you store links in the database based on the hosts header. For example, let say you store the absolute URL to a user's profiles on a forum. By using the wrong header, a hacker could get anyone who clicks on their profile link to be sent a phishing site.

  3. Password reset poisoning can happen if a hacker uses a malicious hosts header when filling out the password reset form for a different user. That user will then get an email containing a password reset link that leads to a phishing site. Another more complex form of this skips the user having to do anything by getting the email to bounce and resend to one of the hacker's SMTP servers (for example CVE-2017-8295.)

  4. Here are some more malicious examples

Additional Caveats and Notes:

  • When usecanonicalname is turned off the $_SERVER['SERVER_NAME'] is populated with the same header $_SERVER['HTTP_HOST'] would have used anyways (plus the port). This is Apache's default setup. If you or devops turns this on then you're okay -- ish -- but do you really want to rely on a separate team, or yourself three years in the future, to keep what would appear to be a minor configuration at a non-default value? Even though this makes things secure, I would caution against relying on this setup.
  • Redhat, however, does turn usecanonical on by default [source].
  • If serverAlias is used in the virtual hosts entry, and the aliased domain is requested, $_SERVER['SERVER_NAME'] will not return the current domain, but will return the value of the serverName directive.
  • If the serverName cannot be resolved, the operating system's hostname command is used in its place [source].
  • If the host header is left out, the server will behave as if usecanonical was on [source].
  • Lastly, I just tried exploiting this on my local server, and was unable to spoof the hosts header. I'm not sure if there was an update to Apache that addressed this, or if I was just doing something wrong. Regardless, this header would still be exploitable in environments where virtual hosts are not being used.

Little Rant:

     This question received hundreds of thousands of views without a single mention of the security problems at hand! It shouldn't be this way, but just because a Stack Overflow answer is popular, that doesn't mean it is secure.



How to style a checkbox using CSS

Simple to implement and easily customizable solution

After a lot of search and testing I got this solution which is simple to implement and easier to customize. In this solution:

  1. You don't need external libraries and files
  2. You don't need to add extra HTML in your page
  3. You don't need to change checkbox names and id

Simple put the flowing CSS at the top of your page and all checkboxes style will change like this:

Enter image description here

_x000D_
_x000D_
input[type=checkbox] {
  transform: scale(1.5);
}

input[type=checkbox] {
  width: 30px;
  height: 30px;
  margin-right: 8px;
  cursor: pointer;
  font-size: 17px;
  visibility: hidden;
}

input[type=checkbox]:after {
  content: " ";
  background-color: #fff;
  display: inline-block;
  margin-left: 10px;
  padding-bottom: 5px;
  color: #00BFF0;
  width: 22px;
  height: 25px;
  visibility: visible;
  border: 1px solid #00BFF0;
  padding-left: 3px;
  border-radius: 5px;
}

input[type=checkbox]:checked:after {
  content: "\2714";
  padding: -5px;
  font-weight: bold;
}
_x000D_
<input type="checkbox" id="checkbox1" />
<label for="checkbox1">Checkbox</label>
_x000D_
_x000D_
_x000D_

FULL OUTER JOIN vs. FULL JOIN

It's true that some databases recognize the OUTER keyword. Some do not. Where it is recognized, it is usually an optional keyword. Almost always, FULL JOIN and FULL OUTER JOIN do exactly the same thing. (I can't think of an example where they do not. Can anyone else think of one?)

This may leave you wondering, "Why would it even be a keyword if it has no meaning?" The answer boils down to programming style.

In the old days, programmers strived to make their code as compact as possible. Every character meant longer processing time. We used 1, 2, and 3 letter variables. We used 2 digit years. We eliminated all unnecessary white space. Some people still program that way. It's not about processing time anymore. It's more about fast coding.

Modern programmers are learning to use more descriptive variables and put more remarks and documentation into their code. Using extra words like OUTER make sure that other people who read the code will have an easier time understanding it. There will be less ambiguity. This style is much more readable and kinder to the people in the future who will have to maintain that code.

How to filter specific apps for ACTION_SEND intent (and set a different text for each app)

Intent emailIntent = new Intent(Intent.ACTION_SENDTO, 
    Uri.fromParts("mailto", "[email protected]", null));
emailIntent.putExtra(Intent.EXTRA_SUBJECT, text);
startActivity(Intent.createChooser(emailIntent, "Send email..."));

Java 8 Iterable.forEach() vs foreach loop

I feel that I need to extend my comment a bit...

About paradigm\style

That's probably the most notable aspect. FP became popular due to what you can get avoiding side-effects. I won't delve deep into what pros\cons you can get from this, since this is not related to the question.

However, I will say that the iteration using Iterable.forEach is inspired by FP and rather result of bringing more FP to Java (ironically, I'd say that there is no much use for forEach in pure FP, since it does nothing except introducing side-effects).

In the end I would say that it is rather a matter of taste\style\paradigm you are currently writing in.

About parallelism.

From performance point of view there is no promised notable benefits from using Iterable.forEach over foreach(...).

According to official docs on Iterable.forEach :

Performs the given action on the contents of the Iterable, in the order elements occur when iterating, until all elements have been processed or the action throws an exception.

... i.e. docs pretty much clear that there will be no implicit parallelism. Adding one would be LSP violation.

Now, there are "parallell collections" that are promised in Java 8, but to work with those you need to me more explicit and put some extra care to use them (see mschenk74's answer for example).

BTW: in this case Stream.forEach will be used, and it doesn't guarantee that actual work will be done in parallell (depends on underlying collection).

UPDATE: might be not that obvious and a little stretched at a glance but there is another facet of style and readability perspective.

First of all - plain old forloops are plain and old. Everybody already knows them.

Second, and more important - you probably want to use Iterable.forEach only with one-liner lambdas. If "body" gets heavier - they tend to be not-that readable. You have 2 options from here - use inner classes (yuck) or use plain old forloop. People often gets annoyed when they see the same things (iteratins over collections) being done various vays/styles in the same codebase, and this seems to be the case.

Again, this might or might not be an issue. Depends on people working on code.

How to print float to n decimal places including trailing 0s?

For Python versions in 2.6+ and 3.x

You can use the str.format method. Examples:

>>> print('{0:.16f}'.format(1.6))
1.6000000000000001

>>> print('{0:.15f}'.format(1.6))
1.600000000000000

Note the 1 at the end of the first example is rounding error; it happens because exact representation of the decimal number 1.6 requires an infinite number binary digits. Since floating-point numbers have a finite number of bits, the number is rounded to a nearby, but not equal, value.

For Python versions prior to 2.6 (at least back to 2.0)

You can use the "modulo-formatting" syntax (this works for Python 2.6 and 2.7 too):

>>> print '%.16f' % 1.6
1.6000000000000001

>>> print '%.15f' % 1.6
1.600000000000000

Hosting ASP.NET in IIS7 gives Access is denied?

I was facing this issue after pulling from remote master and adding to the appsettings on web.config. I solved it by enabling Windows Authentication:

Click on the project and press f4

Make sure Windows Auth is enabled:

enter image description here

An object reference is required to access a non-static member

Make your audioSounds and minTime variables as static variables, as you are using them in a static method (playSound).

Marking a method as static prevents the usage of non-static (instance) members in that method.

To understand more , please read this SO QA:

Static keyword in c#

"Find next" in Vim

When I was beginning I needed to watch a demo.

How to search in Vim

  1. type /
  2. type search term e.g. "var"
  3. press enter
  4. for next instance press n (for previous N)

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Node.js: Python not found exception due to node-sass and node-gyp

Node-sass tries to download the binary for you platform when installing. Node 5 is supported by 3.8 https://github.com/sass/node-sass/releases/tag/v3.8.0 If your Jenkins can't download the prebuilt binary, then you need to follow the platform requirements on Node-gyp README (Python2, VS or MSBuild, ...) If possible I'd suggest updating your Node to at least 6 since 5 isn't supported by Node anymore. If you want to upgrade to 8, you'll need to update node-sass to 4.5.3

Batch Extract path and filename from a variable

if you want infos from the actual running batchfile, try this :

@echo off
set myNameFull=%0
echo myNameFull     %myNameFull%
set myNameShort=%~n0
echo myNameShort    %myNameShort%
set myNameLong=%~nx0
echo myNameLong     %myNameLong%
set myPath=%~dp0
echo myPath         %myPath%
set myLogfileWpath=%myPath%%myNameShort%.log
echo myLogfileWpath %myLogfileWpath%

more samples? C:> HELP CALL

%0 = parameter 0 = batchfile %1 = parameter 1 - 1st par. passed to batchfile... so you can try that stuff (e.g. "~dp") between 1st (e.g. "%") and last (e.g. "1") also for parameters

What's the best strategy for unit-testing database-driven applications?

I have been asking this question for a long time, but I think there is no silver bullet for that.

What I currently do is mocking the DAO objects and keeping a in memory representation of a good collection of objects that represent interesting cases of data that could live on the database.

The main problem I see with that approach is that you're covering only the code that interacts with your DAO layer, but never testing the DAO itself, and in my experience I see that a lot of errors happen on that layer as well. I also keep a few unit tests that run against the database (for the sake of using TDD or quick testing locally), but those tests are never run on my continuous integration server, since we don't keep a database for that purpose and I think tests that run on CI server should be self-contained.

Another approach I find very interesting, but not always worth since is a little time consuming, is to create the same schema you use for production on an embedded database that just runs within the unit testing.

Even though there's no question this approach improves your coverage, there are a few drawbacks, since you have to be as close as possible to ANSI SQL to make it work both with your current DBMS and the embedded replacement.

No matter what you think is more relevant for your code, there are a few projects out there that may make it easier, like DbUnit.

Initialize a vector array of strings

It is 2017, but this thread is top in my search engine, today the following methods are preferred (initializer lists)

std::vector<std::string> v = { "xyzzy", "plugh", "abracadabra" };
std::vector<std::string> v({ "xyzzy", "plugh", "abracadabra" });
std::vector<std::string> v{ "xyzzy", "plugh", "abracadabra" }; 

From https://en.wikipedia.org/wiki/C%2B%2B11#Initializer_lists

What are the advantages of Sublime Text over Notepad++ and vice-versa?

One thing that should be considered is licensing.

Notepad++ is free (as in speech and as in beer) for perpetual use, released under the GPL license, whereas Sublime Text 2 requires a license.

To quote the Sublime Text 2 website:

..a license must be purchased for continued use. There is currently no enforced time limit for the evaluation.

The same is now true of Sublime Text 3, and a paid upgrade will be needed for future versions.

Upgrade Policy A license is valid for Sublime Text 3, and includes all point updates, as well as access to prior versions (e.g., Sublime Text 2). Future major versions, such as Sublime Text 4, will be a paid upgrade.

This licensing requirement is still correct as of Dec 2019.

DateTime group by date and hour

SELECT [activity_dt], COUNT(*) as [Count]
  FROM 
 (SELECT dateadd(hh, datediff(hh, '20010101', [activity_dt]), '20010101') as [activity_dt]
    FROM table) abc
 GROUP BY [activity_dt]

right click context menu for datagridview

For the position for the context menu, y found the problem that I needed a it to be relative to the DataGridView, and the event I needed to use gives the poistion relative to the cell clicked. I haven't found a better solution so I implemented this function in the commons class, so I call it from wherever I need.

It's quite tested and works well. I Hope you find it useful.

    /// <summary>
    /// When DataGridView_CellMouseClick ocurs, it gives the position relative to the cell clicked, but for context menus you need the position relative to the DataGridView
    /// </summary>
    /// <param name="dgv">DataGridView that produces the event</param>
    /// <param name="e">Event arguments produced</param>
    /// <returns>The Location of the click, relative to the DataGridView</returns>
    public static Point PositionRelativeToDataGridViewFromDataGridViewCellMouseEventArgs(DataGridView dgv, DataGridViewCellMouseEventArgs e)
    {
        int x = e.X;
        int y = e.Y;
        if (dgv.RowHeadersVisible)
            x += dgv.RowHeadersWidth;
        if (dgv.ColumnHeadersVisible)
            y += dgv.ColumnHeadersHeight;
        for (int j = 0; j < e.ColumnIndex; j++)
            if (dgv.Columns[j].Visible)
                x += dgv.Columns[j].Width;
        for (int i = 0; i < e.RowIndex; i++)
            if (dgv.Rows[i].Visible)
                y += dgv.Rows[i].Height;
        return new Point(x, y);
    }

How to store an array into mysql?

You may want to tackle this as follows:

CREATE TABLE comments (
    comment_id int, 
    body varchar(100), 
    PRIMARY KEY (comment_id)
);

CREATE TABLE users (
    user_id int, 
    username varchar(20), 
    PRIMARY KEY (user_id)
);

CREATE TABLE comments_votes (
    comment_id int, 
    user_id int, 
    vote_type int, 
    PRIMARY KEY (comment_id, user_id)
);

The composite primary key (comment_id, user_id) on the intersection table comments_votes will prevent users from voting multiple times on the same comments.

Let's insert some data in the above schema:

INSERT INTO comments VALUES (1, 'first comment');
INSERT INTO comments VALUES (2, 'second comment');
INSERT INTO comments VALUES (3, 'third comment');

INSERT INTO users VALUES (1, 'user_a');
INSERT INTO users VALUES (2, 'user_b');
INSERT INTO users VALUES (3, 'user_c');

Now let's add some votes for user 1:

INSERT INTO comments_votes VALUES (1, 1, 1);
INSERT INTO comments_votes VALUES (2, 1, 1);

The above means that user 1 gave a vote of type 1 on comments 1 and 2.

If the same user tries to vote again on one of those comments, the database will reject it:

INSERT INTO comments_votes VALUES (1, 1, 1);
ERROR 1062 (23000): Duplicate entry '1-1' for key 'PRIMARY'

If you will be using the InnoDB storage engine, it will also be wise to use foreign key constraints on the comment_id and user_id fields of the intersection table. However note that MyISAM, the default storage engine in MySQL, does not enforce foreign key constraints:

CREATE TABLE comments (
    comment_id int, 
    body varchar(100), 
    PRIMARY KEY (comment_id)
) ENGINE=INNODB;

CREATE TABLE users (
    user_id int, 
    username varchar(20), 
    PRIMARY KEY (user_id)
) ENGINE=INNODB;

CREATE TABLE comments_votes (
    comment_id int, 
    user_id int, 
    vote_type int, 
    PRIMARY KEY (comment_id, user_id),
    FOREIGN KEY (comment_id) REFERENCES comments (comment_id),
    FOREIGN KEY (user_id) REFERENCES users (user_id)
) ENGINE=INNODB;

These foreign keys guarantee that a row in comments_votes will never have a comment_id or user_id value that doesn't exist in the comments and users tables, respectively. Foreign keys aren't required to have a working relational database, but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity).

In fact, referential integrity is something that would have been very difficult to enforce if you were to store serialized arrays into a single database field.

Get the value of checked checkbox?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var ckbox = $("input[name='ips']");_x000D_
  var chkId = '';_x000D_
  $('input').on('click', function() {_x000D_
    _x000D_
    if (ckbox.is(':checked')) {_x000D_
      $("input[name='ips']:checked").each ( function() {_x000D_
      chkId = $(this).val() + ",";_x000D_
        chkId = chkId.slice(0, -1);_x000D_
    });_x000D_
       _x000D_
       alert ( $(this).val() ); // return all values of checkboxes checked_x000D_
       alert(chkId); // return value of checkbox checked_x000D_
    }     _x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="ips" value="12520">_x000D_
<input type="checkbox" name="ips" value="12521">_x000D_
<input type="checkbox" name="ips" value="12522">
_x000D_
_x000D_
_x000D_

How to change letter spacing in a Textview?

I built a custom class that extends TextView and solves this problem... Check out my answer here =)

How do you add an array to another array in Ruby and not end up with a multi-dimensional result?

I'm surprised nobody has mentioned reduce, which works well when you have an array of arrays:

lists = [["a", "b"], ["c", "d"]]
flatlist = lists.reduce(:+)  # ["a", "b", "c", "d"]

Postgres: INSERT if does not exist already

I know this question is from a while ago, but thought this might help someone. I think the easiest way to do this is via a trigger. E.g.:

Create Function ignore_dups() Returns Trigger
As $$
Begin
    If Exists (
        Select
            *
        From
            hundred h
        Where
            -- Assuming all three fields are primary key
            h.name = NEW.name
            And h.hundred_slug = NEW.hundred_slug
            And h.status = NEW.status
    ) Then
        Return NULL;
    End If;
    Return NEW;
End;
$$ Language plpgsql;

Create Trigger ignore_dups
    Before Insert On hundred
    For Each Row
    Execute Procedure ignore_dups();

Execute this code from a psql prompt (or however you like to execute queries directly on the database). Then you can insert as normal from Python. E.g.:

sql = "Insert Into hundreds (name, name_slug, status) Values (%s, %s, %s)"
cursor.execute(sql, (hundred, hundred_slug, status))

Note that as @Thomas_Wouters already mentioned, the code above takes advantage of parameters rather than concatenating the string.

In oracle, how do I change my session to display UTF8?

Okay, per http://www.oracle.com/technology/tech/globalization/htdocs/nls_lang%20faq.htm:

NLS_LANG cannot be changed by ALTER SESSION, NLS_LANGUAGE and NLS_TERRITORY can. However NLS_LANGUAGE and /or NLS_TERRITORY cannot be set as "standalone" parameters in the environment or registry on the client.

Evidently the "right" solution is, before logging into Oracle at all, setting the following environment variable:

export NLS_LANG=AMERICAN_AMERICA.UTF8

Oracle gets a big fat F for usability.

Why is my Git Submodule HEAD detached from master?

i got tired of it always detaching so i just use a shell script to build it out for all my modules. i assume all submodules are on master: here is the script:

#!/bin/bash
echo "Good Day Friend, building all submodules while checking out from MASTER branch."

git submodule update 
git submodule foreach git checkout master 
git submodule foreach git pull origin master 

execute it from your parent module

How to pass objects to functions in C++?

Do I need to pass pointers, references, or non-pointer and non-reference values?

This is a question that matters when writing a function and choosing the types of the parameters it takes. That choice will affect how the function is called and it depends on a few things.

The simplest option is to pass objects by value. This basically creates a copy of the object in the function, which has many advantages. But sometimes copying is costly, in which case a constant reference, const&, is usually best. And sometimes you need your object to be changed by the function. Then a non-constant reference, &, is needed.

For guidance on the choice of parameter types, see the Functions section of the C++ Core Guidelines, starting with F.15. As a general rule, try to avoid raw pointers, *.

Jquery Smooth Scroll To DIV - Using ID value from Link

Ids are meant to be unique, and never use an id that starts with a number, use data-attributes instead to set the target like so :

<div id="searchbycharacter">
    <a class="searchbychar" href="#" data-target="numeric">0-9 |</a> 
    <a class="searchbychar" href="#" data-target="A"> A |</a> 
    <a class="searchbychar" href="#" data-target="B"> B |</a> 
    <a class="searchbychar" href="#" data-target="C"> C |</a> 
    ... Untill Z
</div>

As for the jquery :

$(document).on('click','.searchbychar', function(event) {
    event.preventDefault();
    var target = "#" + this.getAttribute('data-target');
    $('html, body').animate({
        scrollTop: $(target).offset().top
    }, 2000);
});

Display current date and time without punctuation

A simple example in shell script

#!/bin/bash

current_date_time="`date +%Y%m%d%H%M%S`";
echo $current_date_time;

With out punctuation format :- +%Y%m%d%H%M%S
With punctuation :- +%Y-%m-%d %H:%M:%S

How to download Javadoc to read offline?

F.ex. http://docs.oracle.com/javase/7/docs/ has a link to download "JDK 7 Documentation" in the sidebar under "Downloads". I'd expect the same for other versions.

Set environment variables on Mac OS X Lion

Unfortunately none of these answers solved the specific problem I had.

Here's a simple solution without having to mess with bash. In my case, it was getting gradle to work (for Android Studio).

Btw, These steps relate to OSX (Mountain Lion 10.8.5)

  • Open up Terminal.
  • Run the following command:

    sudo nano /etc/paths (or sudo vim /etc/paths for vim)

    nano

  • Go to the bottom of the file, and enter the path you wish to add.
  • Hit control-x to quit.
  • Enter 'Y' to save the modified buffer.
  • Open a new terminal window then type:

    echo $PATH

You should see the new path appended to the end of the PATH

I got these details from this post:

http://architectryan.com/2012/10/02/add-to-the-path-on-mac-os-x-mountain-lion/#.UkED3rxPp3Q

I hope that can help someone else

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

Bubble Sort Homework

def bubble_sort(l):
    exchanged = True
    iteration = 0
    n = len(l)

    while(exchanged):
        iteration += 1
        exchanged = False

        # Move the largest element to the end of the list
        for i in range(n-1):
            if l[i] > l[i+1]:
                exchanged = True
                l[i], l[i+1] = l[i+1], l[i]
        n -= 1   # Largest element already towards the end

    print 'Iterations: %s' %(iteration)
    return l

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

Escaping quotation marks in PHP

Use a backslash as such

"From time to \"time\"";

Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this

'From time to "time"';

The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such

$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"

As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:

$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

How do I determine the size of my array in C?

The simplest Answer:

#include <stdio.h>

int main(void) {

    int a[] = {2,3,4,5,4,5,6,78,9,91,435,4,5,76,7,34};//for Example only
    int size;

    size = sizeof(a)/sizeof(a[0]);//Method

    printf ("size = %d",size);
    return 0;
}

How to darken an image on mouseover?

I realise this is a little late but you could add the following to your code. This won't work for transparent pngs though, you'd need a cropping mask for that. Which I'm now going to see about.

outerLink {
    overflow: hidden;
    position: relative;
}

outerLink:hover:after {
    background: #000;
    content: "";
    display: block;
    height: 100%;
    left: 0;
    opacity: 0.5;
    position: absolute;
    top: 0;
    width: 100%;
}

How to use concerns in Rails 4

In concerns make file filename.rb

For example I want in my application where attribute create_by exist update there value by 1, and 0 for updated_by

module TestConcern 
  extend ActiveSupport::Concern

  def checkattributes   
    if self.has_attribute?(:created_by)
      self.update_attributes(created_by: 1)
    end
    if self.has_attribute?(:updated_by)
      self.update_attributes(updated_by: 0)
    end
  end

end

If you want to pass arguments in action

included do
   before_action only: [:create] do
     blaablaa(options)
   end
end

after that include in your model like this:

class Role < ActiveRecord::Base
  include TestConcern
end

How to perform a sum of an int[] array

int sum = 0;
for(int i = 0; i < A.length; i++){
  sum += A[i];
}

Adding Counter in shell script

You may do this with a for loop instead of a while:

max_loop=20
for ((count = 0; count < max_loop; count++)); do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       break
  else
       echo "Sleeping for half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

if [ "$count" -eq "$max_loop" ]; then
  echo "Maximum number of trials reached" >&2
  exit 1
fi

How can I change the class of an element with jQuery>

Use jQuery's

$(this).addClass('showhideExtra_up_hover');

and

$(this).addClass('showhideExtra_down_hover');

How to handle Pop-up in Selenium WebDriver using Java

Do not make the situation complex. Use ID if they are available.

driver.get("http://www.rediff.com");
WebElement sign = driver.findElement(By.linkText("Sign in"));
sign.click();
WebElement email_id= driver.findElement(By.id("c_uname"));
email_id.sendKeys("hi");

How to print out a variable in makefile

I usually echo with an error if I wanted to see the variable value.(Only if you wanted to see the value. It will stop execution.)

@echo $(error NDK_PROJECT_PATH= $(NDK_PROJECT_PATH))

Python how to exit main function

You can use sys.exit() to exit from the middle of the main function.

However, I would recommend not doing any logic there. Instead, put everything in a function, and call that from __main__ - then you can use return as normal.

Is there a way to automatically generate getters and setters in Eclipse?

Right click on the property you want to generate the getter and setters for and choose

Source -> Generate Getters and Setters...

What are the differences between WCF and ASMX web services?

There's a lot of talks going on regarding the simplicity of asmx web services over WCF. Let me clarify few points here.

  • Its true that novice web service developers will get started easily in asmx web services. Visual Studio does all the work for them and readily creates a Hello World project.
  • But if you can learn WCF (which off course wont take much time) then you can get to see that WCF is also quite simple, and you can go ahead easily.
  • Its important to remember that these said complexities in WCF are actually attributed to the beautiful features that it brings along with it. There are addressing, bindings, contracts and endpoints, services & clients all mentioned in the config file. The beauty is your business logic is segregated and maintained safely. Tomorrow if you need to change the binding from basicHttpBinding to netTcpBinding you can easily create a binding in config file and use it. So all the changes related to clients, communication channels, bindings etc are to be done in the configuration leaving the business logic safe & intact, which makes real good sense.
  • WCF "web services" are part of a much broader spectrum of remote communication enabled through WCF. You will get a much higher degree of flexibility and portability doing things in WCF than through traditional ASMX because WCF is designed, from the ground up, to summarize all of the different distributed programming infrastructures offered by Microsoft. An endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces the amount of new code needed when porting or changing business needs, targets, etc.
  • Web Services can be accessed only over HTTP & it works in stateless environment, where WCF is flexible because its services can be hosted in different types of applications. You can host your WCF services in Console, Windows Services, IIS & WAS, which are again different ways of creating new projects in Visual Studio.
  • ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you can see WCF as trying to logically group together all the different ways of getting two apps to communicate in the world of Microsoft; ASMX was just one of these many ways and so is now grouped under the WCF umbrella of capabilities.
  • You will always like to use Visual Studio for NET 4.0 or 4.5 as it makes life easy while creating WCF services.
  • The major difference is that Web Services Use XmlSerializer. But WCF Uses DataContractSerializer which is better in Performance as compared to XmlSerializer. That's why WCF performs way better than other communication technology counterparts from .NET like asmx, .NET remoting etc.

Not to forget that I was one of those guys who liked asmx services more than WCF, but that time I was not well aware of WCF services and its capabilities. I was scared of the WCF configurations. But I dared and and tried writing few WCF services of my own, and when I learnt more of WCF, now I have no inhibitions about WCF and I recommend them to anyone & everyone. Happy coding!!!

Cannot convert lambda expression to type 'string' because it is not a delegate type

If it's not related to missing using directives stated by other users, this will also happen if there is another problem with your query.

Take a look on VS compiler error list : For example, if the "Value" variable in your query doesn't exist, you will have the "lambda to string" error, and a few errors after another one more related to the unknown/erroneous field.

In your case it could be :

objContentLine = (from q in db.qryContents
                  where q.LineID == Value
                  orderby q.RowID descending
                  select q).FirstOrDefault();

Errors:

Error 241 Cannot convert lambda expression to type 'string' because it is not a delegate type

Error 242 Delegate 'System.Func<..>' does not take 1 arguments

Error 243 The name 'Value' does not exist in the current context

Fix the "Value" variable error and the other errors will also disappear.

Getting View's coordinates relative to the root layout

I wrote myself two utility methods that seem to work in most conditions, handling scroll, translation and scaling, but not rotation. I did this after trying to use offsetDescendantRectToMyCoords() in the framework, which had inconsistent accuracy. It worked in some cases but gave wrong results in others.

"point" is a float array with two elements (the x & y coordinates), "ancestor" is a viewgroup somewhere above the "descendant" in the tree hierarchy.

First a method that goes from descendant coordinates to ancestor:

public static void transformToAncestor(float[] point, final View ancestor, final View descendant) {
    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = left + px + (point[0] - px) * sx + tx - scrollX;
    point[1] = top + py + (point[1] - py) * sy + ty - scrollY;

    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToAncestor(point, ancestor, (View) parent);
    }
}

Next the inverse, from ancestor to descendant:

public static void transformToDescendant(float[] point, final View ancestor, final View descendant) {
    ViewParent parent = descendant.getParent();
    if (descendant != ancestor && parent != ancestor && parent instanceof View) {
        transformToDescendant(point, ancestor, (View) parent);
    }

    final float scrollX = descendant.getScrollX();
    final float scrollY = descendant.getScrollY();
    final float left = descendant.getLeft();
    final float top = descendant.getTop();
    final float px = descendant.getPivotX();
    final float py = descendant.getPivotY();
    final float tx = descendant.getTranslationX();
    final float ty = descendant.getTranslationY();
    final float sx = descendant.getScaleX();
    final float sy = descendant.getScaleY();

    point[0] = px + (point[0] + scrollX - left - tx - px) / sx;
    point[1] = py + (point[1] + scrollY - top - ty - py) / sy;
}

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

I think the best way to work with dates between C# and SQL is, of course, use parametrized queries, and always work with DateTime objects on C# and the ToString() formating options it provides.

You better execute set datetime <format> (here you have the set dateformat explanation on MSDN) before working with dates on SQL Server so you don't get in trouble, like for example set datetime ymd. You only need to do it once per connection because it mantains the format while open, so a good practice would be to do it just after openning the connection to the database.
Then, you can always work with 'yyyy-MM-dd HH:mm:ss:ffff' formats.

To pass the DateTime object to your parametrized query you can use DateTime.ToString('yyyy-MM-dd HH:mm:ss:ffff').

For parsing weird formatted dates on C# you can use DateTime.ParseExact() method, where you have the option to specify exactly what the input format is: DateTime.ParseExact(<some date string>, 'dd/MM-yyyy',CultureInfo.InvariantCulture). Here you have the DateTime.ParseExact() explanation on MSDN)

CSS center display inline block?

If you have a <div> with text-align:center;, then any text inside it will be centered with respect to the width of that container element. inline-block elements are treated as text for this purpose, so they will also be centered.

SQL UPDATE SET one column to be equal to a value in a related table referenced by a different column?

below works for mysql

update table1 INNER JOIN table2 on table1.col1 =  table2.col1
set table1.col1 =  table2.col2

How to delete a file via PHP?

$files = [
    './first.jpg',
    './second.jpg',
    './third.jpg'
];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
    } else {
        // File not found.
    }
}

Need a query that returns every field that contains a specified letter

select *
from table
where keyword like '%a%'
and keyword like '%b%'

ps This will be super slow. You may want to investigate full text indexing solutions.

Select all contents of textbox when it receives focus (Vanilla JS or jQuery)

I sow this one some where , work perfectly !

            $('input').on('focus', function (e) {
                $(this)
                $(element).one('mouseup', function () {
                        $(this).select();
                        return false;
                    })                        .select();
            });

Print an ArrayList with a for-each loop

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

class ArrLst{

    public static void main(String args[]){

        List l=new ArrayList();
        l.add(10);
        l.add(11);
        l.add(12);
        l.add(13);
        l.add(14);
        l.forEach((a)->System.out.println(a));
    }
}

How to install an apk on the emulator in Android Studio?

Much easier is just to start your emulator, then go to sdk/platform-tools and use adb from there to install apk. Like:

adb install xxx.apk

It will install it on running emulator.

How to implement the Android ActionBar back button?

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

in onCreated method for the new apis.

Declaring and initializing arrays in C

No, you can't set them to arbitrary values in one statement (unless done as part of the declaration).

You can either do it with code, something like:

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 27;
:
myArray[99] = -7;

or (if there's a formula):

for (int i = 0; i < 100; i++) myArray[i] = i + 1;

The other possibility is to keep around some templates that are set at declaration time and use them to initialise your array, something like:

static const int onceArr[]  = {  0,  1,  2,  3,  4,..., 99};
static const int twiceArr[] = {  0,  2,  4,  6,  8,...,198};
:
int myArray[7];
:
memcpy (myArray, twiceArr, sizeof (myArray));

This has the advantage of (most likely) being faster and allows you to create smaller arrays than the templates. I've used this method in situations where I have to re-initialise an array fast but to a specific state (if the state were all zeros, I would just use memset).


You can even localise it to an initialisation function:

void initMyArray (int *arr, size_t sz) {
    static const int template[] = {2, 3, 5, 7, 11, 13, 17, 19, 21, ..., 9973};
    memcpy (arr, template, sz);
}
:
int myArray[100];
initMyArray (myArray, sizeof(myArray));

The static array will (almost certainly) be created at compile time so there will be no run-time cost for that, and the memcpy should be blindingly fast, likely faster than 1,229 assignment statements but very definitely less typing on your part :-).

Get a list of all the files in a directory (recursive)

The following works for me in Gradle / Groovy for build.gradle for an Android project, without having to import groovy.io.FileType (NOTE: Does not recurse subdirectories, but when I found this solution I no longer cared about recursion, so you may not either):

FileCollection proGuardFileCollection = files { file('./proguard').listFiles() }
proGuardFileCollection.each {
    println "Proguard file located and processed: " + it
}

Get Application Name/ Label via ADB Shell or Terminal

just enter the following command on command prompt after launching the app:

adb shell dumpsys window windows | find "mCurrentFocus"

if executing the command on linux terminal replace find by grep

Can't build create-react-app project with custom PUBLIC_URL

Have a look at the documentation. You can have a .env file which picks up the PUBLIC_URL

Although you should remember that what its used for -

You may use this variable to force assets to be referenced verbatim to the url you provide (hostname included). This may be particularly useful when using a CDN to host your application.

Adding an onclick event to a table row

Simple way is generating code as bellow:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<style>_x000D_
  table, td {_x000D_
      border:1px solid black;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<p>Click on each tr element to alert its index position in the table:</p>_x000D_
<table>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<script>_x000D_
  function myFunction(x) {_x000D_
      alert("Row index is: " + x.rowIndex);_x000D_
  }_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

JavaScript code for getting the selected value from a combo box

It probably is the # sign like tho others have mentioned because this appears to work just fine.

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>

</head>
<body>

    <select id="#ticket_category_clone">
  <option value="hw">Hardware</option>
  <option>fsdf</option>
  <option>sfsd</option>
  <option>sdfs</option>
</select>
<script type="text/javascript">
    (function check() {
        var e = document.getElementById("#ticket_category_clone");
        var str = e.options[e.selectedIndex].text;

        alert(str);
        if (str === "Hardware") { 
            alert('Hi'); 
        }


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

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

jQuery Ajax error handling, show custom exception messages

A general/reusable solution

This answer is provided for future reference to all those that bump into this problem. Solution consists of two things:

  1. Custom exception ModelStateException that gets thrown when validation fails on the server (model state reports validation errors when we use data annotations and use strong typed controller action parameters)
  2. Custom controller action error filter HandleModelStateExceptionAttribute that catches custom exception and returns HTTP error status with model state error in the body

This provides the optimal infrastructure for jQuery Ajax calls to use their full potential with success and error handlers.

Client side code

$.ajax({
    type: "POST",
    url: "some/url",
    success: function(data, status, xhr) {
        // handle success
    },
    error: function(xhr, status, error) {
        // handle error
    }
});

Server side code

[HandleModelStateException]
public ActionResult Create(User user)
{
    if (!this.ModelState.IsValid)
    {
        throw new ModelStateException(this.ModelState);
    }

    // create new user because validation was successful
}

The whole problem is detailed in this blog post where you can find all the code to run this in your application.

How to count digits, letters, spaces for a string in Python?

Following code replaces any nun-numeric character with '', allowing you to count number of such characters with function len.

import re
len(re.sub("[^0-9]", "", my_string))

Alphabetical:

import re
len(re.sub("[^a-zA-Z]", "", my_string))

More info - https://docs.python.org/3/library/re.html

How do you replace all the occurrences of a certain character in a string?

You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:

>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'

This would of course fail if there is multiple numbers in the input. a quick check would be:

assert(age in input_given)

and also:

assert(len(name)<len(input_given))

Python - List of unique dictionaries

Pretty straightforward option:

L = [
    {'id':1,'name':'john', 'age':34},
    {'id':1,'name':'john', 'age':34},
    {'id':2,'name':'hanna', 'age':30},
    ]


D = dict()
for l in L: D[l['id']] = l
output = list(D.values())
print output

Type Checking: typeof, GetType, or is?

You can use "typeof()" operator in C# but you need to call the namespace using System.IO; You must use "is" keyword if you wish to check for a type.

A component is changing an uncontrolled input of type text to be controlled error in ReactJS

const [name, setName] = useState()

generates error as soon as you type in the text field

const [name, setName] = useState('') // <-- by putting in quotes 

will fix the issue on this string example.

ReactJS lifecycle method inside a function Component

if you using react 16.8 you can use react Hooks... React Hooks are functions that let you “hook into” React state and lifecycle features from function components... docs

select from one table, insert into another table oracle sql query

try this query below:

Insert into tab1 (tab1.column1,tab1.column2) 
select tab2.column1, 'hard coded  value' 
from tab2 
where tab2.column='value';

What is secret key for JWT based authentication and how to generate it?

What is the secret key does, you may have already known till now. It is basically HMAC SH256 (Secure Hash). The Secret is a symmetrical key.

Using the same key you can generate, & reverify, edit, etc.

For more secure, you can go with private, public key (asymmetric way). Private key to create token, public key to verify at client level.

Coming to secret key what to give You can give anything, "sudsif", "sdfn2173", any length

you can use online generator, or manually write

I prefer using openssl

C:\Users\xyz\Desktop>openssl rand -base64 12
65JymYzDDqqLW8Eg

generate, then encode with base 64

C:\Users\xyz\Desktop>openssl rand -out openssl-secret.txt -hex 20

The generated value is saved inside the file named "openssl-secret.txt"

generate, & store into a file.

One thing is giving 12 will generate, 12 characters only, but since it is base 64 encoded, it will be (4/3*n) ceiling value.

I recommend reading this article

https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/

Get local IP address in Node.js

Here's what might be the cleanest, simplest answer without dependencies & that works across all platforms.

const { lookup } = require('dns').promises;
const { hostname } = require('os');

async function getMyIPAddress(options) {
  return (await lookup(hostname(), options))
    .address;
}

Github Windows 'Failed to sync this branch'

This error comes because of a merge conflict in files. I faced it after I had updated my Maven Project's pom.xml but didn't commit it. Using

git status
error: Your local changes to the following files would be overwritten by merge:
<my project>/pom.xml
Please, commit your changes or stash them before you can merge.
Aborting

as the above post suggested helped finding any conflicting changes and you can decide to discard or commit.

How do I exit from a function?

Use the return keyword.

From MSDN:

The return statement terminates execution of the method in which it appears and returns control to the calling method. It can also return the value of the optional expression. If the method is of the type void, the return statement can be omitted.

So in your case, the usage would be:

private void button1_Click(object sender, EventArgs e)
{
    if (textBox1.Text == "" || textBox2.Text == "" || textBox3.Text == "")
    {
        return; //exit this event
    }
}

Call a url from javascript

Yes, what you are asking for is called AJAX or XMLHttpRequest. You can either use a library like jQuery to simplify making the call (due to cross-browser compatibility issues), or write your own handler.

In jQuery:

$.GET('url.asp', {data: 'here'}, function(data){ /* what to do with the data returned */ })

In plain vanilla javaScript (from w3c):

var xmlhttp;
function loadXMLDoc(url)
{
    xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for all new browsers
      xmlhttp=new XMLHttpRequest();
  }
else if (window.ActiveXObject)
  {// code for IE5 and IE6
      xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
      xmlhttp.onreadystatechange=state_Change;
      xmlhttp.open("GET",url,true);
      xmlhttp.send(null);
  }
else
  {
      alert("Your browser does not support XMLHTTP.");
  }
}

function state_Change()
{
    if (xmlhttp.readyState==4)
      {// 4 = "loaded"
          if (xmlhttp.status==200)
            {// 200 = OK
             //xmlhttp.data and shtuff
            // ...our code here...
        }
  else
        {
            alert("Problem retrieving data");
        }
  }
}

IOError: [Errno 32] Broken pipe: Python

The problem is due to SIGPIPE handling. You can solve this problem using the following code:

from signal import signal, SIGPIPE, SIG_DFL
signal(SIGPIPE,SIG_DFL) 

See here for background on this solution. Better answer here.

Form Submission without page refresh

<!-- index.php -->
    <!DOCTYPE html>
    <html>
    <head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    </head>
    <body>
    <form id="myForm">
        <input type="text" name="fname" id="fname"/>
        <input type="submit" name="click" value="button" />
    </form>
    <script>
    $(document).ready(function(){

         $(function(){
            $("#myForm").submit(function(event){
                event.preventDefault();
                $.ajax({
                    method: 'POST',
                    url: 'submit.php',
                    dataType: "json",
                    contentType: "application/json",
                    data : $('#myForm').serialize(),
                    success: function(data){
                        alert(data);
                    },
                    error: function(xhr, desc, err){
                        console.log(err);
                    }
                });
            });
        });
    });
    </script>
    </body>
    </html>
<!-- submit.php -->
<?php
$value ="call";
header('Content-Type: application/json');
echo json_encode($value);
?>

How to autosize a textarea using Prototype?

Here's a Prototype version of resizing a text area that is not dependent on the number of columns in the textarea. This is a superior technique because it allows you to control the text area via CSS as well as have variable width textarea. Additionally, this version displays the number of characters remaining. While not requested, it's a pretty useful feature and is easily removed if unwanted.

//inspired by: http://github.com/jaz303/jquery-grab-bag/blob/63d7e445b09698272b2923cb081878fd145b5e3d/javascripts/jquery.autogrow-textarea.js
if (window.Widget == undefined) window.Widget = {}; 

Widget.Textarea = Class.create({
  initialize: function(textarea, options)
  {
    this.textarea = $(textarea);
    this.options = $H({
      'min_height' : 30,
      'max_length' : 400
    }).update(options);

    this.textarea.observe('keyup', this.refresh.bind(this));

    this._shadow = new Element('div').setStyle({
      lineHeight : this.textarea.getStyle('lineHeight'),
      fontSize : this.textarea.getStyle('fontSize'),
      fontFamily : this.textarea.getStyle('fontFamily'),
      position : 'absolute',
      top: '-10000px',
      left: '-10000px',
      width: this.textarea.getWidth() + 'px'
    });
    this.textarea.insert({ after: this._shadow });

    this._remainingCharacters = new Element('p').addClassName('remainingCharacters');
    this.textarea.insert({after: this._remainingCharacters});  
    this.refresh();  
  },

  refresh: function()
  { 
    this._shadow.update($F(this.textarea).replace(/\n/g, '<br/>'));
    this.textarea.setStyle({
      height: Math.max(parseInt(this._shadow.getHeight()) + parseInt(this.textarea.getStyle('lineHeight').replace('px', '')), this.options.get('min_height')) + 'px'
    });

    var remaining = this.options.get('max_length') - $F(this.textarea).length;
    this._remainingCharacters.update(Math.abs(remaining)  + ' characters ' + (remaining > 0 ? 'remaining' : 'over the limit'));
  }
});

Create the widget by calling new Widget.Textarea('element_id'). The default options can be overridden by passing them as an object, e.g. new Widget.Textarea('element_id', { max_length: 600, min_height: 50}). If you want to create it for all textareas on the page, do something like:

Event.observe(window, 'load', function() {
  $$('textarea').each(function(textarea) {
    new Widget.Textarea(textarea);
  });   
});

Best way to reverse a string

public static string reverse(string s) 
{
    string r = "";
    for (int i = s.Length; i > 0; i--) r += s[i - 1];
    return r;
}

How can I remove a key from a Python dictionary?

To delete a key regardless of whether it is in the dictionary, use the two-argument form of dict.pop():

my_dict.pop('key', None)

This will return my_dict[key] if key exists in the dictionary, and None otherwise. If the second parameter is not specified (ie. my_dict.pop('key')) and key does not exist, a KeyError is raised.

To delete a key that is guaranteed to exist, you can also use

del my_dict['key']

This will raise a KeyError if the key is not in the dictionary.

How to decode jwt token in javascript without using a library?

In Node.js (TypeScript):

import { TextDecoder } from 'util';

function decode(jwt: string) {
    const { 0: encodedHeader, 1: encodedPayload, 2: signature, length } = jwt.split('.');

    if (length !== 3) {
        throw new TypeError('Invalid JWT');
    }

    const decode = (input: string): JSON => { return JSON.parse(new TextDecoder().decode(new Uint8Array(Buffer.from(input, 'base64')))); };

    return { header: decode(encodedHeader), payload: decode(encodedPayload), signature: signature };
}

With jose by panva on GitHub, you could use the minimal import { decode as base64Decode } from 'jose/util/base64url' and replace new Uint8Array(Buffer.from(input, 'base64')) with base64Decode(input). Code should then work in both browser and Node.js.

React.createElement: type is invalid -- expected a string

I just spent 30 minutes trying to solve this BASIC basic issue.

My problem was I was importing react native elements

eg import React, { Text, Image, Component } from 'react';

And trying to use them, which caused me to receive this error.

Once I switch from <Text> to <p> and <Image> to <img> everything worked as expected.

AngularJS access scope from outside js function

The accepted answer is great. I wanted to look at what happens to the Angular scope in the context of ng-repeat. The thing is, Angular will create a sub-scope for each repeated item. When calling into a method defined on the original $scope, that retains its original value (due to javascript closure). However, the this refers the calling scope/object. This works out well, so long as you're clear on when $scope and this are the same and when they are different. hth

Here is a fiddle that illustrates the difference: https://jsfiddle.net/creitzel/oxsxjcyc/

How to use Class<T> in Java?

Just to throw in another example, the generic version of Class (Class<T>) allows one to write generic functions such as the one below.

public static <T extends Enum<T>>Optional<T> optionalFromString(
        @NotNull Class<T> clazz,
        String name
) {
    return Optional<T> opt = Optional.ofNullable(name)
            .map(String::trim)
            .filter(StringUtils::isNotBlank)
            .map(String::toUpperCase)
            .flatMap(n -> {
                try {
                    return Optional.of(Enum.valueOf(clazz, n));
                } catch (Exception e) {
                    return Optional.empty();
                }
            });
}

How can I format the output of a bash command in neat columns

Try

xargs -n2  printf "%-20s%s\n"

or even

xargs printf "%-20s%s\n"

if input is not very large.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

Other solutions didn't work form me, here's mine. It applies only to Xcode 8 when running in Swift 2.3 legacy mode:

Looks like Interface Builder is trying to rename the method that should be hooked up to the button.

Here's a radar with more details.

The solution (workaround) is to manually replace the method parameter name to _:

@IBAction func editPictureTapped(sender: UIButton) {  // not working
    print("Tapped")
}

Change to this:

@IBAction func editPictureTapped(_: UIButton) {     // working OK
    print("Tapped")
}

How can I convert a DateTime to the number of seconds since 1970?

That's basically it. These are the methods I use to convert to and from Unix epoch time:

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    return origin.AddSeconds(timestamp);
}

public static double ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan diff = date.ToUniversalTime() - origin;
    return Math.Floor(diff.TotalSeconds);
}

Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch.

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

If you're on a shared server like me the host said it was a result of hitting memory limits, so they kill scripts which results in the "Premature end of script headers" seen in this error. They referred me to this:

https://help.dreamhost.com/hc/en-us/articles/216540488-Why-did-procwatch-kill-processes-on-my-Shared-serv

Given an increase in memory, the issues went. I think a backup plugin Updraft on wordpress was perhaps over zealous in its duty/settings.

Python not working in command prompt?

Here's one for for office workers using a computer shared by others.

I did put my user path in path and created the PYTHONPATH variables in my computer's PATH variable. Its listed under Environment Variables in Computer Properties -> Advanced Settings in Windows 7.

Example:

C:\Users\randuser\AppData\Local\Programs\Python\Python37

This made it so I could use the command prompt.

Hope this helped.

Command /Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/clang failed with exit code 1

For me this error appears after cloning the project from a repository. Someone removed a white space from the projects name (renamed: "The Project" to "TheProject") which caused some Build Settings errors to unvalid paths.

Sometimes reading the whole error logs is not a bad idea....

TypeError: 'tuple' object does not support item assignment when swapping values

Evaluating "1,2,3" results in (1, 2, 3), a tuple. As you've discovered, tuples are immutable. Convert to a list before processing.

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

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

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

javac: file not found: first.java Usage: javac <options> <source files>

SET path of JRE as well

jre is nothing but responsible for execute the program

PATH Variable value:

C:\Program Files\Java\jdk1.8.0\bin;C:\Program Files\Java\jre\bin;.;

Kill tomcat service running on any port, Windows

netstat -ano | findstr :3010

enter image description here

taskkill /F /PID

enter image description here

But it won't work for me

then I tried taskkill -PID <processorid> -F

Example:- taskkill -PID 33192 -F Here 33192 is the processorid and it works enter image description here

Scrolling a flexbox with overflowing content

Working with position:absolute; along with flex:

Position the flex item with position: relative. Then inside of it, add another <div> element with:

position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;

This extends the element to the boundaries of its relative-positioned parent, but does not allow to extend it. Inside, overflow: auto; will then work as expected.

  • the code snippet included in the answer - Click on enter image description here and then click on Full Page after running the snippet OR
  • Click here for the CODEPEN
  • The result: enter image description here

_x000D_
_x000D_
.all-0 {_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
}_x000D_
p {_x000D_
  text-align: justify;_x000D_
}_x000D_
.bottom-0 {_x000D_
  bottom: 0;_x000D_
}_x000D_
.overflow-auto {_x000D_
  overflow: auto;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
_x000D_
<div class="p-5 w-100">_x000D_
  <div class="row bg-dark m-0">_x000D_
    <div class="col-sm-9 p-0 d-flex flex-wrap">_x000D_
      <!-- LEFT-SIDE - ROW-1 -->_x000D_
      <div class="row m-0 p-0">_x000D_
        <!-- CARD 1 -->_x000D_
        <div class="col-md-8 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/700x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- CARD 2 -->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
      <div class="row m-0">_x000D_
        <!-- CARD 3 -->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- CARD 4 -->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
        <!-- CARD 5-->_x000D_
        <div class="col-md-4 p-0 d-flex">_x000D_
          <div class="my-card-content bg-white p-2 m-2 d-flex flex-column">_x000D_
            <img class="img img-fluid" src="https://via.placeholder.com/400x250">_x000D_
            <h4>Heading 1</h4>_x000D_
            <p>_x000D_
              Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old..._x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="col-sm-3 p-0">_x000D_
      <div class="bg-white m-2 p-2 position-absolute all-0 d-flex flex-column">_x000D_
        <h4>Social Sidebar...</h4>_x000D_
        <hr />_x000D_
        <div class="d-flex overflow-auto">_x000D_
          <p>_x000D_
            Topping candy tiramisu soufflé fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart._x000D_
            opping candy tiramisu soufflé fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart._x000D_
            opping candy tiramisu soufflé fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva fruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart._x000D_
            Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate bar. Bear claw ice cream_x000D_
            chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halvafruitcake ice cream chocolate_x000D_
            bar. Bear claw ice cream chocolate bar donut sweet tart. Pudding cupcake danish apple pie apple pie. Halva_x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

Good Luck...

How to read from a file or STDIN in Bash?

Code ${1:-/dev/stdin} will just understand first argument, so, how about this.

ARGS='$*'
if [ -z "$*" ]; then
  ARGS='-'
fi
eval "cat -- $ARGS" | while read line
do
   echo "$line"
done

AJAX Mailchimp signup form integration

Based on gbinflames' answer, this is what worked for me:

Generate a simple mailchimp list sign up form , copy the action URL and method (post) to your custom form. Also rename your form field names to all capital ( name='EMAIL' as in original mailchimp code, EMAIL,FNAME,LNAME,... ), then use this:

      $form=$('#your-subscribe-form'); // use any lookup method at your convenience

      $.ajax({
      type: $form.attr('method'),
      url: $form.attr('action').replace('/post?', '/post-json?').concat('&c=?'),
      data: $form.serialize(),
      timeout: 5000, // Set timeout value, 5 seconds
      cache       : false,
      dataType    : 'jsonp',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { // put user friendly connection error message  },
      success     : function(data) {
          if (data.result != "success") {
              // mailchimp returned error, check data.msg
          } else {
              // It worked, carry on...
          }
      }

Adding whitespace in Java

If you have an Instance of the EditText available at the point in your code where you want add whitespace, then this code below will work. There may be some things to consider, for example the code below may trigger any TextWatcher you have set to this EditText, idk for sure, just saying, but this will work when trying to append blank space like this: " ", hasn't worked.

messageInputBox.dispatchKeyEvent(new KeyEvent(0, 0, 0, KeyEvent.KEYCODE_SPACE, 0, 0, 0, 0,
                        KeyEvent.KEYCODE_ENDCALL));

Switch android x86 screen resolution

Based on my experience, it's enough to use the following additional boot options:

UVESA_MODE=320x480 DPI=160

No need to add vga definition. Watch out for DPI value! As bigger one makes your icons bigger.

To add the previous boot options, go to debug mode (during grub menu selection)

mount -o remount,rw /mnt
vi /mnt/grub/menu.lst

Now edit on this line:

kernel /android-2.3-RC1/kernel quiet root=/dev/ram0 androidboot_hardware=eeepc acpi_sleep=s3_bios,s3_mode SRC=/android-2.3-RC1 SDCARD=/data/sdcard.img UVESA_MODE=320x480 DPI=160

Reboot

What does <T> (angle brackets) mean in Java?

Generic classes are a type of class that takes in a data type as a parameter when it's created. This type parameter is specified using angle brackets and the type can change each time a new instance of the class is instantiated. For instance, let's create an ArrayList for Employee objects and another for Company objects

ArrayList<Employee> employees = new ArrayList<Employee>();
ArrayList<Company> companies = new ArrayList<Company>();

You'll notice that we're using the same ArrayList class to create both lists and we pass in the Employee or Company type using angle brackets. Having one generic class be able to handle multiple types of data cuts down on having a lot of classes that perform similar tasks. Generics also help to cut down on bugs by giving everything a strong type which helps the compiler point out errors. By specifying a type for ArrayList, the compiler will throw an error if you try to add an Employee to the Company list or vice versa.

How to display list items on console window in C#

Actually you can do it pretty simple, since the list have a ForEach method and since you can pass in Console.WriteLine as a method group. The compiler will then use an implicit conversion to convert the method group to, in this case, an Action<int> and pick the most specific method from the group, in this case Console.WriteLine(int):

  var list = new List<int>(Enumerable.Range(0, 50));

  list.ForEach(Console.WriteLine);

Works with strings too =)

To be utterly pedantic (and I'm not suggesting a change to your answer - just commenting for the sake of interest) Console.WriteLine is a method group. The compiler then uses an implicit conversion from the method group to Action<int>, picking the most specific method (Console.WriteLine(int) in this case).

How can I concatenate a string and a number in Python?

Python is strongly typed. There are no implicit type conversions.

You have to do one of these:

"asd%d" % 9
"asd" + str(9)

make: Nothing to be done for `all'

When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.

If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.

If they are not present, make blindly builds everything under the rule.

Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!

python int( ) function

Integers (int for short) are the numbers you count with 0, 1, 2, 3 ... and their negative counterparts ... -3, -2, -1 the ones without the decimal part.

So once you introduce a decimal point, your not really dealing with integers. You're dealing with rational numbers. The Python float or decimal types are what you want to represent or approximate these numbers.

You may be used to a language that automatically does this for you(Php). Python, though, has an explicit preference for forcing code to be explicit instead implicit.

fill an array in C#

You could try something like this:

I have initialzed the array for having value 5, you could put your number similarly.

int[] arr = new int[10]; // your initial array

arr = arr.Select(i => 5).ToArray(); // array initialized to 5.

Remove spaces from std::string in C++

The best thing to do is to use the algorithm remove_if and isspace:

remove_if(str.begin(), str.end(), isspace);

Now the algorithm itself can't change the container(only modify the values), so it actually shuffles the values around and returns a pointer to where the end now should be. So we have to call string::erase to actually modify the length of the container:

str.erase(remove_if(str.begin(), str.end(), isspace), str.end());

We should also note that remove_if will make at most one copy of the data. Here is a sample implementation:

template<typename T, typename P>
T remove_if(T beg, T end, P pred)
{
    T dest = beg;
    for (T itr = beg;itr != end; ++itr)
        if (!pred(*itr))
            *(dest++) = *itr;
    return dest;
}

get all keys set in memcached

Base on @mu ? answer here. I've written a cache dump script.

The script dumps all the content of a memcached server. It's tested with Ubuntu 12.04 and a localhost memcached, so your milage may vary.

#!/usr/bin/env bash

echo 'stats items'  \
| nc localhost 11211  \
| grep -oe ':[0-9]*:'  \
| grep -oe '[0-9]*'  \
| sort  \
| uniq  \
| xargs -L1 -I{} bash -c 'echo "stats cachedump {} 1000" | nc localhost 11211'

What it does, it goes through all the cache slabs and print 1000 entries of each.

Please be aware of certain limits of this script i.e. it may not scale for a 5GB cache server for example. But it's useful for debugging purposes on a local machine.

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

Override back button to act like home button

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:

A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

These seems appropriate for your requirements.

How to add header to a dataset in R?

in case you are interested in reading some data from a .txt file and only extract few columns of that file into a new .txt file with a customized header, the following code might be useful:

# input some data from 2 different .txt files:
civit_gps <- read.csv(file="/path2/gpsFile.csv",head=TRUE,sep=",")
civit_cam <- read.csv(file="/path2/cameraFile.txt",head=TRUE,sep=",")

# assign the name for the output file:
seqName <- "seq1_data.txt"

#=========================================================
# Extract data from imported files
#=========================================================
# From Camera:
frame_idx <- civit_cam$X.frame
qx        <- civit_cam$q.x.rad.
qy        <- civit_cam$q.y.rad.
qz        <- civit_cam$q.z.rad.
qw        <- civit_cam$q.w

# From GPS:
gpsT      <- civit_gps$X.gpsTime.sec.
latitude  <- civit_gps$Latitude.deg.
longitude <- civit_gps$Longitude.deg.
altitude  <- civit_gps$H.Ell.m.
heading   <- civit_gps$Heading.deg.
pitch     <- civit_gps$pitch.deg.
roll      <- civit_gps$roll.deg.
gpsTime_corr <- civit_gps[frame_idx,1]

#=========================================================
# Export new data into the output txt file
#=========================================================
myData <- data.frame(c(gpsTime_corr),
                     c(frame_idx),
                     c(qx),
                     c(qy),
                     c(qz),
                     c(qw))
# Write :
cat("#GPSTime,frameIdx,qx,qy,qz,qw\n", file=seqName)
write.table(myData, file = seqName,row.names=FALSE,col.names=FALSE,append=TRUE,sep = ",")

Of course, you should modify this sample script based on your own application.

How to loop through Excel files and load them into a database using SSIS package?

Here is one possible way of doing this based on the assumption that there will not be any blank sheets in the Excel files and also all the sheets follow the exact same structure. Also, under the assumption that the file extension is only .xlsx

Following example was created using SSIS 2008 R2 and Excel 2007. The working folder for this example is F:\Temp\

In the folder path F:\Temp\, create an Excel 2007 spreadsheet file named States_1.xlsx with two worksheets.

Sheet 1 of States_1.xlsx contained the following data

States_1_Sheet_1

Sheet 2 of States_1.xlsx contained the following data

States_1_Sheet_2

In the folder path F:\Temp\, create another Excel 2007 spreadsheet file named States_2.xlsx with two worksheets.

Sheet 1 of States_2.xlsx contained the following data

States_2_Sheet_1

Sheet 2 of States_2.xlsx contained the following data

States_2_Sheet_2

Create a table in SQL Server named dbo.Destination using the below create script. Excel sheet data will be inserted into this table.

CREATE TABLE [dbo].[Destination](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [State] [nvarchar](255) NULL,
    [Country] [nvarchar](255) NULL,
    [FilePath] [nvarchar](255) NULL,
    [SheetName] [nvarchar](255) NULL,
CONSTRAINT [PK_Destination] PRIMARY KEY CLUSTERED ([Id] ASC)) ON [PRIMARY]
GO

The table is currently empty.

Empty table

Create a new SSIS package and on the package, create the following 4 variables. FolderPath will contain the folder where the Excel files are stored. FilePattern will contain the extension of the files that will be looped through and this example works only for .xlsx. FilePath will be assigned with a value by the Foreach Loop container but we need a valid path to begin with for design time and it is currently populated with the path F:\Temp\States_1.xlsx of the first Excel file. SheetName will contain the actual sheet name but we need to populate with initial value Sheet1$ to avoid design time error.

Variables

In the package's connection manager, create an ADO.NET connection with the following configuration and name it as ExcelSchema.

Select the provider Microsoft Office 12.0 Access Database Engine OLE DB Provider under .Net Providers for OleDb. Provide the file path F:\Temp\States_1.xlsx

ExcelSchema 1

Click on the All section on the left side and set the property Extended Properties to Excel 12.0 to denote the version of Excel. Here in this case 12.0 denotes Excel 2007. Click on the Test Connection to make sure that the connection succeeds.

ExcelSchema 2

Create an Excel connection manager named Excel as shown below.

Excel

Create an OLE DB Connection SQL Server named SQLServer. So, we should have three connections on the package as shown below.

Connections

We need to do the following connection string changes so that the Excel file is dynamically changed as the files are looped through.

On the connection ExcelSchema, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

ExcelSchema ServerName

Similarly on the connection Excel, configure the expression ServerName to use the variable FilePath. Click on the ellipsis button to configure the expression.

Excel ServerName

On the Control Flow, place two Foreach Loop containers one within the other. The first Foreach Loop container named Loop files will loop through the files. The second Foreach Loop container will through the sheets within the container. Within the inner For each loop container, place a Data Flow Task that will read the Excel files and load data into SQL

Control Flow

Configure the first Foreach loop container named Loop files as shown below:

Foreach Loop 1 Collection

Foreach Loop 1 Variable Mappings

Configure the first Foreach loop container named Loop sheets as shown below:

Foreach Loop 2 Collection

Foreach Loop 2 Variable Mappings

Inside the data flow task, place an Excel Source, Derived Column and OLE DB Destination as shown below:

Data Flow Task

Configure the Excel Source to read the appropriate Excel file and the sheet that is currently being looped through.

Excel Source Connection Manager

Excel Source Columns

Configure the derived column to create new columns for file name and sheet name. This is just to demonstrate this example but has no significance.

Derived column

Configure the OLE DB destination to insert the data into the SQL table.

OLE DB Destination Connection Manager

OLE DB Destination Columns

Below screenshot shows successful execution of the package.

Execution successful

Below screenshot shows that data from the 4 workbooks in 2 Excel spreadsheets that were creating in the beginning of this answer is correctly loaded into the SQL table dbo.Destination.

SQL table

Hope that helps.

Directory Chooser in HTML page

In case if you are the server and the user (e.g. you are creating an app which works via browser and you need to choose a folder) then try to call JFileChooser from the server when some button is clicked in the browser

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

This code snipped is from here

How to select between brackets (or quotes or ...) in Vim?

For selecting within single quotes use vi'.

For selecting within parenthesis use vi(.

Unpacking a list / tuple of pairs into two lists / tuples

>>> source_list = ('1','a'),('2','b'),('3','c'),('4','d')
>>> list1, list2 = zip(*source_list)
>>> list1
('1', '2', '3', '4')
>>> list2
('a', 'b', 'c', 'd')

Edit: Note that zip(*iterable) is its own inverse:

>>> list(source_list) == zip(*zip(*source_list))
True

When unpacking into two lists, this becomes:

>>> list1, list2 = zip(*source_list)
>>> list(source_list) == zip(list1, list2)
True

Addition suggested by rocksportrocker.

Finding the layers and layer sizes for each Docker image

This will inspect the docker image and print the layers:

$ docker image inspect nginx -f '{{.RootFS.Layers}}'
[sha256:d626a8ad97a1f9c1f2c4db3814751ada64f60aed927764a3f994fcd88363b659 sha256:82b81d779f8352b20e52295afc6d0eab7e61c0ec7af96d85b8cda7800285d97d sha256:7ab428981537aa7d0c79bc1acbf208c71e57d9678f7deca4267cc03fba26b9c8]

Change first commit of project with Git?

As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root for git rebase:

"git rebase [-i] --root $tip" can now be used to rewrite all the history leading to "$tip" down to the root commit.

That new behavior was initially discussed here:

I personally think "git rebase -i --root" should be made to just work without requiring "--onto" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.

The patch followed.


(original answer, February 2010)

As mentioned in the Git FAQ (and this SO question), the idea is:

  1. Create new temporary branch
  2. Rewind it to the commit you want to change using git reset --hard
  3. Change that commit (it would be top of current HEAD, and you can modify the content of any file)
  4. Rebase branch on top of changed commit, using:

    git rebase --onto <tmp branch> <commit after changed> <branch>`
    

The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter to make sure the content of that file does not contain in any commit the sensible information.

In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

I picked node-sass implementer for libsass because it is based on node.js.

Installing node-sass

  • (Prerequisite) If you don't have npm, install Node.js first.
  • $ npm install -g node-sass installs node-sass globally -g.

This will hopefully install all you need, if not read libsass at the bottom.

How to use node-sass from Command line and npm scripts

General format:

$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css

Examples:

  1. $ node-sass my-styles.scss my-styles.css compiles a single file manually.
  2. $ node-sass my-sass-folder/ -o my-css-folder/ compiles all the files in a folder manually.
  3. $ node-sass -w sass/ -o css/ compiles all the files in a folder automatically whenever the source file(s) are modified. -w adds a watch for changes to the file(s).

More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.

You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.

  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • Add "sass": "node-sass -w sass/ -o css/" to scripts in package.json file. It should look something like this:
"scripts": {
    "test" : "bla bla bla",
    "sass": "node-sass -w sass/ -o css/"
 }
  • $ npm run sass will compile your files.

How to use with gulp

  • $ npm install -g gulp installs Gulp globally.
  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • $ npm install --save-dev gulp installs Gulp locally. --save-dev adds gulp to devDependencies in package.json.
  • $ npm install gulp-sass --save-dev installs gulp-sass locally.
  • Setup gulp for your project by creating a gulpfile.js file in your project root folder with this content:
'use strict';
var gulp = require('gulp');

A basic example to transpile

Add this code to your gulpfile.js:

var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
  gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

$ gulp sass runs the above task which compiles .scss file(s) in the sass folder and generates .css file(s) in the css folder.

To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js:

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

All is set now! Just run the watch task:

$ gulp sass:watch

How to use with Node.js

As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.

What about libsass?

Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:

LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.

List all devices, partitions and volumes in Powershell

Run command:

Get-PsDrive -PsProvider FileSystem

For more info see:

How do I prompt a user for confirmation in bash script?

This way you get 'y' 'yes' or 'Enter'

 read -r -p "Are you sure? [Y/n]" response
 response=${response,,} # tolower
 if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
 fi

If you are using zsh try this:

read "response?Are you sure ? [Y/n] "
response=${response:l} #tolower
if [[ $response =~ ^(yes|y| ) ]] || [[ -z $response ]]; then
    your-action-here
fi

Creating a "logical exclusive or" operator in Java

You can just write (a!=b)

This would work the same as way as a ^ b.

Entity Framework Join 3 Tables

This is untested, but I believe the syntax should work for a lambda query. As you join more tables with this syntax you have to drill further down into the new objects to reach the values you want to manipulate.

var fullEntries = dbContext.tbl_EntryPoint
    .Join(
        dbContext.tbl_Entry,
        entryPoint => entryPoint.EID,
        entry => entry.EID,
        (entryPoint, entry) => new { entryPoint, entry }
    )
    .Join(
        dbContext.tbl_Title,
        combinedEntry => combinedEntry.entry.TID,
        title => title.TID,
        (combinedEntry, title) => new 
        {
            UID = combinedEntry.entry.OwnerUID,
            TID = combinedEntry.entry.TID,
            EID = combinedEntry.entryPoint.EID,
            Title = title.Title
        }
    )
    .Where(fullEntry => fullEntry.UID == user.UID)
    .Take(10);

What are Keycloak's OAuth2 / OpenID Connect endpoints?

For Keycloak 1.2 the above information can be retrieved via the url

http://keycloakhost:keycloakport/auth/realms/{realm}/.well-known/openid-configuration

For example, if the realm name is demo:

http://keycloakhost:keycloakport/auth/realms/demo/.well-known/openid-configuration

An example output from above url:

{
    "issuer": "http://localhost:8080/auth/realms/demo",
    "authorization_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/auth",
    "token_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/token",
    "userinfo_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/userinfo",
    "end_session_endpoint": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/logout",
    "jwks_uri": "http://localhost:8080/auth/realms/demo/protocol/openid-connect/certs",
    "grant_types_supported": [
        "authorization_code",
        "refresh_token",
        "password"
    ],
    "response_types_supported": [
        "code"
    ],
    "subject_types_supported": [
        "public"
    ],
    "id_token_signing_alg_values_supported": [
        "RS256"
    ],
    "response_modes_supported": [
        "query"
    ]
}

Found information at https://issues.jboss.org/browse/KEYCLOAK-571

Note: You might need to add your client to the Valid Redirect URI list

What is 'Context' on Android?

Think of it as the VM that has siloed the process the app or service is running in. The siloed environment has access to a bunch of underlying system information and certain permitted resources. You need that context to get at those services.

Oracle SQL Developer - tables cannot be seen

grant select on sys.external_tab$ to [myUser]; worked for me. thanx Codo

WPF loading spinner

With Images

Visual summary of options for spinning icons. Recorded using Screen To Gif.


Font-Awesome-WPF

Documentation on GitHub.

Install via NuGet:

PM> Install-Package FontAwesome.WPF

Looks like this:

XAML:

<fa:ImageAwesome Icon="Spinner" Spin="True" SpinDuration="4" />

Icons pictured are Spinner, CircleOutlineNotch, Refresh and Cog. There are many others.


Method from @HAdes

XAML copy/paste.

Error when using scp command "bash: scp: command not found"

Check if scp is installed or not on from where you want want to copy check using which scp

If it's already installed, it will print you a path like /usr/bin/scp Else, install scp using:

yum -y install openssh-clients

Then copy command

scp -r [email protected]:/var/www/html/database_backup/restore_fullbackup/backup_20140308-023002.sql  /var/www/html/db_bkp/

MySQL INSERT INTO ... VALUES and SELECT

INSERT INTO table1 (col1, col2)
SELECT "a string", 5, TheNameOfTheFieldInTable2
FROM table2 where ...

Jackson JSON custom serialization for certain fields

Add a @JsonProperty annotated getter, which returns a String, for the favoriteNumber field:

public class Person {
    public String name;
    public int age;
    private int favoriteNumber;

    public Person(String name, int age, int favoriteNumber) {
        this.name = name;
        this.age = age;
        this.favoriteNumber = favoriteNumber;
    }

    @JsonProperty
    public String getFavoriteNumber() {
        return String.valueOf(favoriteNumber);
    }

    public static void main(String... args) throws Exception {
        Person p = new Person("Joe", 25, 123);
        ObjectMapper mapper = new ObjectMapper();
        System.out.println(mapper.writeValueAsString(p)); 
        // {"name":"Joe","age":25,"favoriteNumber":"123"}
    }
}

How many bytes does one Unicode character take?

Strangely enough, nobody pointed out how to calculate how many bytes is taking one Unicode char. Here is the rule for UTF-8 encoded strings:

Binary    Hex          Comments
0xxxxxxx  0x00..0x7F   Only byte of a 1-byte character encoding
10xxxxxx  0x80..0xBF   Continuation byte: one of 1-3 bytes following the first
110xxxxx  0xC0..0xDF   First byte of a 2-byte character encoding
1110xxxx  0xE0..0xEF   First byte of a 3-byte character encoding
11110xxx  0xF0..0xF7   First byte of a 4-byte character encoding

So the quick answer is: it takes 1 to 4 bytes, depending on the first one which will indicate how many bytes it'll take up.

Making the iPhone vibrate

From "iPhone Tutorial: Better way to check capabilities of iOS devices":

There are two seemingly similar functions that take a parameter kSystemSoundID_Vibrate:

1) AudioServicesPlayAlertSound(kSystemSoundID_Vibrate);
2) AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);

Both of the functions vibrate the iPhone. But, when you use the first function on devices that don’t support vibration, it plays a beep sound. The second function, on the other hand, does nothing on unsupported devices. So if you are going to vibrate the device continuously, as an alert, common sense says, use function 2.

First, add the AudioToolbox framework AudioToolbox.framework to your target in Build Phases.

Then, import this header file:

#import <AudioToolbox/AudioServices.h>

Fastest method to escape HTML tags as HTML entities?

I'll add XMLSerializer to the pile. It provides the fastest result without using any object caching (not on the serializer, nor on the Text node).

function serializeTextNode(text) {
  return new XMLSerializer().serializeToString(document.createTextNode(text));
}

The added bonus is that it supports attributes which is serialized differently than text nodes:

function serializeAttributeValue(value) {
  const attr = document.createAttribute('a');
  attr.value = value;
  return new XMLSerializer().serializeToString(attr);
}

You can see what it's actually replacing by checking the spec, both for text nodes and for attribute values. The full documentation has more node types, but the concept is the same.

As for performance, it's the fastest when not cached. When you do allow caching, then calling innerHTML on an HTMLElement with a child Text node is fastest. Regex would be slowest (as proven by other comments). Of course, XMLSerializer could be faster on other browsers, but in my (limited) testing, a innerHTML is fastest.


Fastest single line:

new XMLSerializer().serializeToString(document.createTextNode(text));

Fastest with caching:

const cachedElementParent = document.createElement('div');
const cachedChildTextNode = document.createTextNode('');
cachedElementParent.appendChild(cachedChildTextNode);

function serializeTextNode(text) {
  cachedChildTextNode.nodeValue = text;
  return cachedElementParent.innerHTML;
}

https://jsperf.com/htmlentityencode/1

For div to extend full height

This is an old question. CSS has evolved. There now is the vh (viewport height) unit, also new layout options like flexbox or CSS grid to achieve classical designs in cleaner ways.

Get UTC time and local time from NSDate object

let date = Date() 
print(date) // printed date is UTC 

If you are using playground, use a print statement to check the time. Playground shows local time until you print it. Do not depend on the right side panel of playground. enter image description here

This code gives date in UTC. If you need the local time, you should call the following extension with timezone as Timezone.current

 extension Date {

   var currentUTCTimeZoneDate: String {
        let formatter = DateFormatter()
        formatter.timeZone = TimeZone(identifier: "UTC")
        formatter.amSymbol = "AM"
        formatter.pmSymbol = "PM"
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"

        return formatter.string(from: self)
    }
}

For UTC time, use it like: Date().currentUTCTimeZoneDate

How can I connect to Android with ADB over TCP?

Steps :

  1. su -- To switch to super user.
  2. setprop service.adb.tcp.port 5555 - To specify the tcp Port - 5555 is the port number here
  3. stop adbd - To stop the adbd service.
  4. start adbd - To start adbd service.

this works perfectly with ssh from my windows PC

I try to do this on the boot on my cyanogen mobile or launch this with plink. With plink I can't launch shell with su right ... sudo or su command not works. On boot I don't know how it's works! My shell program works from ssh with su -c "sh /storage/sdcard1/start_adb.sh" with the last 3 commands (without su --)

Thanks

PHP: HTTP or HTTPS?

$_SERVER['HTTPS']

This will contain a 'non-empty' value if the request was sent through HTTPS

PHP Server Variables

Get path of executable

The following works as a quick and dirty solution, but note that it is far from being foolproof:

#include <iostream>

using namespace std ;

int main( int argc, char** argv)
{
    cout << argv[0] << endl ;
    return 0;
}

node.js vs. meteor.js what's the difference?

A loose analogy is, "Meteor is to Node as Rails is to Ruby." It's a large, opinionated framework that uses Node on the server. Node itself is just a low-level framework providing functions for sending and receiving HTTP requests and performing other I/O.

Meteor is radically ambitious: By default, every page it serves is actually a Handlebars template that's kept in sync with the server. Try the Leaderboard example: You create a template that simply says "List the names and scores," and every time any client changes a name or score, the page updates with the new data—not just for that client, but for everyone viewing the page.

Another difference: While Node itself is stable and widely used in production, Meteor is in a "preview" state. There are serious bugs, and certain things that don't fit with Meteor's data-centric conceptual model (such as animations) are very hard to do.

If you love playing with new technologies, give Meteor a spin. If you want a more traditional, stable web framework built on Node, take a look at Express.

Eclipse HotKey: how to switch between tabs?

You can use ALT+Left to go to your previous tab, or ALT+Right to go to forward. This method is using tab-switching like history, though, so it will go to the previous tab you had open, and forward if you've gone "back" once or more. A bit weird, I know, but it works. You can always "reset" the history by clicking through every tab once.

jQuery '.each' and attaching '.click' event

No need to use .each. click already binds to all div occurrences.

$('div').click(function(e) {
    ..    
});

See Demo

Note: use hard binding such as .click to make sure dynamically loaded elements don't get bound.

How to get rows count of internal table in abap?

I don't think there is a SAP parameter for that kind of result. Though the code below will deliver.

LOOP AT intTab.

  AT END OF value.

    result = sy-tabix.

    write result.  

  ENDAT.

ENDLOOP.

Replace whitespaces with tabs in linux

This will replace consecutive spaces with one space (but not tab).

tr -s '[:blank:]'

This will replace consecutive spaces with a tab.

tr -s '[:blank:]' '\t'

How to enable and use HTTP PUT and DELETE with Apache2 and PHP?

On linux, /etc/apache2/mods-enabled/php5.conf dans php5.load exists. If not, enables this modules (may require to sudo apt-get install libapache2-mod-php5).

Understanding slice notation

It's pretty simple really:

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

There is also the step value, which can be used with any of the above:

a[start:stop:step] # start through not past stop, by step

The key point to remember is that the :stop value represents the first value that is not in the selected slice. So, the difference between stop and start is the number of elements selected (if step is 1, the default).

The other feature is that start or stop may be a negative number, which means it counts from the end of the array instead of the beginning. So:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

Similarly, step may be a negative number:

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

Relation to slice() object

The slicing operator [] is actually being used in the above code with a slice() object using the : notation (which is only valid within []), i.e.:

a[start:stop:step]

is equivalent to:

a[slice(start, stop, step)]

Slice objects also behave slightly differently depending on the number of arguments, similarly to range(), i.e. both slice(stop) and slice(start, stop[, step]) are supported. To skip specifying a given argument, one might use None, so that e.g. a[start:] is equivalent to a[slice(start, None)] or a[::-1] is equivalent to a[slice(None, None, -1)].

While the :-based notation is very helpful for simple slicing, the explicit use of slice() objects simplifies the programmatic generation of slicing.

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

How to solve static declaration follows non-static declaration in GCC C code?

You have declared a function as nonstatic in some file and you have implemented as static in another file or somewhere in the same file can cause this problem also. For example, the following code will produce this error.

void inlet_update_my_ratio(object_t *myobject);
//some where the implementation is like this
static void inlet_update_my_ratio(object_t *myobject) {
//code
}

If you remove the static from the implementation, the error will go away as below.

 void inlet_update_my_ratio(object_t *myobject) {
    //code
    }

How do I read the contents of a Node.js stream into a string variable?

(This answer is from years ago, when it was the best answer. There is now a better answer below this. I haven't kept up with node.js, and I cannot delete this answer because it is marked "correct on this question". If you are thinking of down clicking, what do you want me to do?)

The key is to use the data and end events of a Readable Stream. Listen to these events:

stream.on('data', (chunk) => { ... });
stream.on('end', () => { ... });

When you receive the data event, add the new chunk of data to a Buffer created to collect the data.

When you receive the end event, convert the completed Buffer into a string, if necessary. Then do what you need to do with it.

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool