Programs & Examples On #Horizontal scaling

horizontal scaling refers to partitioning data in such a way, that parts of data are placed on different servers (which is opposed to vertical scaling, when the same server gets more capacity)

Find current directory and file's directory

1.To get the current directory full path

    >>import os
    >>print os.getcwd()

o/p:"C :\Users\admin\myfolder"

1.To get the current directory folder name alone

    >>import os
    >>str1=os.getcwd()
    >>str2=str1.split('\\')
    >>n=len(str2)
    >>print str2[n-1]

o/p:"myfolder"

for or while loop to do something n times

The fundamental difference in most programming languages is that unless the unexpected happens a for loop will always repeat n times or until a break statement, (which may be conditional), is met then finish with a while loop it may repeat 0 times, 1, more or even forever, depending on a given condition which must be true at the start of each loop for it to execute and always false on exiting the loop, (for completeness a do ... while loop, (or repeat until), for languages that have it, always executes at least once and does not guarantee the condition on the first execution).

It is worth noting that in Python a for or while statement can have break, continue and else statements where:

  • break - terminates the loop
  • continue - moves on to the next time around the loop without executing following code this time around
  • else - is executed if the loop completed without any break statements being executed.

N.B. In the now unsupported Python 2 range produced a list of integers but you could use xrange to use an iterator. In Python 3 range returns an iterator.

So the answer to your question is 'it all depends on what you are trying to do'!

Position last flex item at the end of container

This flexbox principle also works horizontally

During calculations of flex bases and flexible lengths, auto margins are treated as 0.
Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Setting an automatic left margin for the Last Item will do the work.

.last-item {
  margin-left: auto;
}

Code Example:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  width: 400px;_x000D_
  outline: 1px solid black;_x000D_
}_x000D_
_x000D_
p {_x000D_
  height: 50px;_x000D_
  width: 50px;_x000D_
  margin: 5px;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
.last-item {_x000D_
  margin-left: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p></p>_x000D_
  <p class="last-item"></p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Codepen Snippet

This can be very useful for Desktop Footers.

As Envato did here with the company logo.

Codepen Snippet

Determining the last row in a single column

Update 2021 - Considers also empty cells

The accepted answer as well as most of the answers (if not all of them) have one common limitation which might not be the case for the owner of the question (they have contiguous data) but for future readers.

  • Namely, if the selected column contains empty cells in between, the accepted answer would give the wrong result.

For example, consider this very simple scenario:

enter image description here

the accepted solution would give 4 while the correct answer is 6.

Solution:

Find the index of first non-empty value starting from the end of the array by using the reverse method.

const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName('Sheet1')
const lrow = sh.getLastRow();
const Avals = sh.getRange("A1:A"+lrow).getValues();
const Alast  = lrow - Avals.reverse().findIndex(c=>c[0]!='');

Alternative to Intersect in MySQL

Your query would always return an empty recordset since cut_name= '?????' and cut_name='??' will never evaluate to true.

In general, INTERSECT in MySQL should be emulated like this:

SELECT  *
FROM    mytable m
WHERE   EXISTS
        (
        SELECT  NULL
        FROM    othertable o
        WHERE   (o.col1 = m.col1 OR (m.col1 IS NULL AND o.col1 IS NULL))
                AND (o.col2 = m.col2 OR (m.col2 IS NULL AND o.col2 IS NULL))
                AND (o.col3 = m.col3 OR (m.col3 IS NULL AND o.col3 IS NULL))
        )

If both your tables have columns marked as NOT NULL, you can omit the IS NULL parts and rewrite the query with a slightly more efficient IN:

SELECT  *
FROM    mytable m
WHERE   (col1, col2, col3) IN
        (
        SELECT  col1, col2, col3
        FROM    othertable o
        )

How do I use Notepad++ (or other) with msysgit?

I used starikovs' solution. I started with a bash window and gave the commands

cd ~
touch .bashrc

Then I found the .bashrc file in windows explorer, opened it with notepad++ and added

PATH=$PATH:"C:\Program Files (x86)\Notepad++"

so that bash knows where to find Notepad++. (Having Notepad++ in the bash PATH is a useful thing on its own!) Then I pasted his line

git config --global core.editor "notepad++.exe -multiInst"

into a bash window. I started a new bash window for a git repository to test things with the command

git rebase -i HEAD~10

and the file opened in Notepad++ as hoped.

python setup.py uninstall

If you still have files that are supposed to be deleted after re-installing a package, make sure the folder build is also deleted. Therefore, assuming that pkg is the package you want to delete:

rm -r $(python3 -c "import pkg; print(pkg.__path__[0] + '*' )") 
rm -rf build

Obove work out for python3 and delete the package and its *.egg-info file

How can I get the concatenation of two lists in Python without modifying either one?

And if you have more than two lists to concatenate:

import operator
from functools import reduce  # For Python 3
list1, list2, list3 = [1,2,3], ['a','b','c'], [7,8,9]
reduce(operator.add, [list1, list2, list3])

# or with an existing list
all_lists = [list1, list2, list3]
reduce(operator.add, all_lists)

It doesn't actually save you any time (intermediate lists are still created) but nice if you have a variable number of lists to flatten, e.g., *args.

NumPy array is not JSON serializable

You can use Pandas:

import pandas as pd
pd.Series(your_array).to_json(orient='values')

PHP/MySQL: How to create a comment section in your website

You can create a 'comment' table, with an id as primary key, then you add a text field to capture the text inserted by the user and you need another field to link the comment table to the article table (foreign key). Plus you need a field to store the user that has entered a comment, this field can be the user's email. Then you capture via GET or POST the user's email and comment and you insert everything in the DB:

"INSERT INTO comment (comment, email, approved) VALUES ('$comment', '$email', '$approved')"

This is a first hint. Of course adding a comment feature it takes a little bit. Then you should think about a form to let the admin to approve the comments and how to publish the comments in the end of articles.

Using true and false in C

Just include <stdbool.h> if your system provides it. That defines a number of macros, including bool, false, and true (defined to _Bool, 0, and 1 respectively). See section 7.16 of C99 for more details.

CSS: Truncate table cells, but fit as much as possible

Check if "nowrap" solve the issue to an extent. Note: nowrap is not supported in HTML5

<table border="1" style="width: 100%; white-space: nowrap; table-layout: fixed;">
<tr>
    <td style="overflow: hidden; text-overflow: ellipsis;" nowrap >This cells has more content  </td>
    <td style="overflow: hidden; text-overflow: ellipsis;" nowrap >Less content here has more content</td>
</tr>

How to use XMLReader in PHP?

Most of my XML parsing life is spent extracting nuggets of useful information out of truckloads of XML (Amazon MWS). As such, my answer assumes you want only specific information and you know where it is located.

I find the easiest way to use XMLReader is to know which tags I want the information out of and use them. If you know the structure of the XML and it has lots of unique tags, I find that using the first case is the easy. Cases 2 and 3 are just to show you how it can be done for more complex tags. This is extremely fast; I have a discussion of speed over on What is the fastest XML parser in PHP?

The most important thing to remember when doing tag-based parsing like this is to use if ($myXML->nodeType == XMLReader::ELEMENT) {... - which checks to be sure we're only dealing with opening nodes and not whitespace or closing nodes or whatever.

function parseMyXML ($xml) { //pass in an XML string
    $myXML = new XMLReader();
    $myXML->xml($xml);

    while ($myXML->read()) { //start reading.
        if ($myXML->nodeType == XMLReader::ELEMENT) { //only opening tags.
            $tag = $myXML->name; //make $tag contain the name of the tag
            switch ($tag) {
                case 'Tag1': //this tag contains no child elements, only the content we need. And it's unique.
                    $variable = $myXML->readInnerXML(); //now variable contains the contents of tag1
                    break;

                case 'Tag2': //this tag contains child elements, of which we only want one.
                    while($myXML->read()) { //so we tell it to keep reading
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') { // and when it finds the amount tag...
                            $variable2 = $myXML->readInnerXML(); //...put it in $variable2. 
                            break;
                        }
                    }
                    break;

                case 'Tag3': //tag3 also has children, which are not unique, but we need two of the children this time.
                    while($myXML->read()) {
                        if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Amount') {
                            $variable3 = $myXML->readInnerXML();
                            break;
                        } else if ($myXML->nodeType == XMLReader::ELEMENT && $myXML->name === 'Currency') {
                            $variable4 = $myXML->readInnerXML();
                            break;
                        }
                    }
                    break;

            }
        }
    }
$myXML->close();
}

Composer update memory limit

In my case it needed higher permissions along with this memory limit increase.

sudo COMPOSER_MEMORY_LIMIT=2G php /opt/bitnami/php/bin/composer.phar update

What is thread safe or non-thread safe in PHP?

Needed background on concurrency approaches:

Different web servers implement different techniques for handling incoming HTTP requests in parallel. A pretty popular technique is using threads -- that is, the web server will create/dedicate a single thread for each incoming request. The Apache HTTP web server supports multiple models for handling requests, one of which (called the worker MPM) uses threads. But it supports another concurrency model called the prefork MPM which uses processes -- that is, the web server will create/dedicate a single process for each request.

There are also other completely different concurrency models (using Asynchronous sockets and I/O), as well as ones that mix two or even three models together. For the purpose of answering this question, we are only concerned with the two models above, and taking Apache HTTP server as an example.

Needed background on how PHP "integrates" with web servers:

PHP itself does not respond to the actual HTTP requests -- this is the job of the web server. So we configure the web server to forward requests to PHP for processing, then receive the result and send it back to the user. There are multiple ways to chain the web server with PHP. For Apache HTTP Server, the most popular is "mod_php". This module is actually PHP itself, but compiled as a module for the web server, and so it gets loaded right inside it.

There are other methods for chaining PHP with Apache and other web servers, but mod_php is the most popular one and will also serve for answering your question.

You may not have needed to understand these details before, because hosting companies and GNU/Linux distros come with everything prepared for us.

Now, onto your question!

Since with mod_php, PHP gets loaded right into Apache, if Apache is going to handle concurrency using its Worker MPM (that is, using Threads) then PHP must be able to operate within this same multi-threaded environment -- meaning, PHP has to be thread-safe to be able to play ball correctly with Apache!

At this point, you should be thinking "OK, so if I'm using a multi-threaded web server and I'm going to embed PHP right into it, then I must use the thread-safe version of PHP". And this would be correct thinking. However, as it happens, PHP's thread-safety is highly disputed. It's a use-if-you-really-really-know-what-you-are-doing ground.

Final notes

In case you are wondering, my personal advice would be to not use PHP in a multi-threaded environment if you have the choice!

Speaking only of Unix-based environments, I'd say that fortunately, you only have to think of this if you are going to use PHP with Apache web server, in which case you are advised to go with the prefork MPM of Apache (which doesn't use threads, and therefore, PHP thread-safety doesn't matter) and all GNU/Linux distributions that I know of will take that decision for you when you are installing Apache + PHP through their package system, without even prompting you for a choice. If you are going to use other webservers such as nginx or lighttpd, you won't have the option to embed PHP into them anyway. You will be looking at using FastCGI or something equal which works in a different model where PHP is totally outside of the web server with multiple PHP processes used for answering requests through e.g. FastCGI. For such cases, thread-safety also doesn't matter. To see which version your website is using put a file containing <?php phpinfo(); ?> on your site and look for the Server API entry. This could say something like CGI/FastCGI or Apache 2.0 Handler.

If you also look at the command-line version of PHP -- thread safety does not matter.

Finally, if thread-safety doesn't matter so which version should you use -- the thread-safe or the non-thread-safe? Frankly, I don't have a scientific answer! But I'd guess that the non-thread-safe version is faster and/or less buggy, or otherwise they would have just offered the thread-safe version and not bothered to give us the choice!

How do I read a string entered by the user in C?

You can use scanf function to read string

scanf("%[^\n]",name);

i don't know about other better options to receive string,

How do I UPDATE from a SELECT in SQL Server?

Consolidating all the different approaches here.

  1. Select update
  2. Update with a common table expression
  3. Merge

Sample table structure is below and will update from Product_BAK to Product table.

Product

CREATE TABLE [dbo].[Product](
    [Id] [int] IDENTITY(1, 1) NOT NULL,
    [Name] [nvarchar](100) NOT NULL,
    [Description] [nvarchar](100) NULL
) ON [PRIMARY]

Product_BAK

    CREATE TABLE [dbo].[Product_BAK](
        [Id] [int] IDENTITY(1, 1) NOT NULL,
        [Name] [nvarchar](100) NOT NULL,
        [Description] [nvarchar](100) NULL
    ) ON [PRIMARY]

1. Select update

    update P1
    set Name = P2.Name
    from Product P1
    inner join Product_Bak P2 on p1.id = P2.id
    where p1.id = 2

2. Update with a common table expression

    ; With CTE as
    (
        select id, name from Product_Bak where id = 2
    )
    update P
    set Name = P2.name
    from  product P  inner join CTE P2 on P.id = P2.id
    where P2.id = 2

3. Merge

    Merge into product P1
    using Product_Bak P2 on P1.id = P2.id

    when matched then
    update set p1.[description] = p2.[description], p1.name = P2.Name;

In this Merge statement, we can do inset if not finding a matching record in the target, but exist in the source and please find syntax:

    Merge into product P1
    using Product_Bak P2 on P1.id = P2.id;

    when matched then
    update set p1.[description] = p2.[description], p1.name = P2.Name;

    WHEN NOT MATCHED THEN
    insert (name, description)
    values(p2.name, P2.description);

how to pass this element to javascript onclick function and add a class to that clicked element

<div class="row" style="padding-left:21px;">
    <ul class="nav nav-tabs" style="padding-left:40px;">
        <li class="active filter"><a href="#month" onclick="Data(this)">This Month</a></li>
        <li class="filter"><a href="#year" onclick="Data(this)">Year</a></li>
        <li class="filter"><a href="#last60" onclick="Data(this)">60 Days</a></li>
        <li class="filter"><a href="#last90" onclick="Data(this)">90 Days</a></li>
    </ul>

</div>

<script>
    function Data(element)
    {     
       element.removeClass('active');
       element.addClass('active') ;
    }
</script>

java.lang.ClassNotFoundException: org.springframework.web.servlet.DispatcherServlet

Move the jar files from your classpath to web-inf/lib, and run a new tomcat server.

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

With C++11 or higher you can use find() and find_first_of()

Example using find to find a single char:

#include <string>
std::string name = "Aaah";
size_t found_index = name.find('a');
if (found_index != std::string::npos) {
    // Found string containing 'a'
}

Example using find to find a full string & starting from position 5:

std::string name = "Aaah";
size_t found_index = name.find('h', 3);
if (found_index != std::string::npos) {
    // Found string containing 'h'
}

Example using the find_first_of() and only the first char, to search at the start only:

std::string name = ".hidden._di.r";
size_t found_index = name.find_first_of('.');
if (found_index == 0) {
    // Found '.' at first position in string
}

Good luck!

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Determine Whether Two Date Ranges Overlap

Here is yet another solution using JavaScript. Specialities of my solution:

  • Handles null values as infinity
  • Assumes that the lower bound is inclusive and the upper bound exclusive.
  • Comes with a bunch of tests

The tests are based on integers but since date objects in JavaScript are comparable you can just throw in two date objects as well. Or you could throw in the millisecond timestamp.

Code:

/**
 * Compares to comparable objects to find out whether they overlap.
 * It is assumed that the interval is in the format [from,to) (read: from is inclusive, to is exclusive).
 * A null value is interpreted as infinity
 */
function intervalsOverlap(from1, to1, from2, to2) {
    return (to2 === null || from1 < to2) && (to1 === null || to1 > from2);
}

Tests:

describe('', function() {
    function generateTest(firstRange, secondRange, expected) {
        it(JSON.stringify(firstRange) + ' and ' + JSON.stringify(secondRange), function() {
            expect(intervalsOverlap(firstRange[0], firstRange[1], secondRange[0], secondRange[1])).toBe(expected);
        });
    }

    describe('no overlap (touching ends)', function() {
        generateTest([10,20], [20,30], false);
        generateTest([20,30], [10,20], false);

        generateTest([10,20], [20,null], false);
        generateTest([20,null], [10,20], false);

        generateTest([null,20], [20,30], false);
        generateTest([20,30], [null,20], false);
    });

    describe('do overlap (one end overlaps)', function() {
        generateTest([10,20], [19,30], true);
        generateTest([19,30], [10,20], true);

        generateTest([10,20], [null,30], true);
        generateTest([10,20], [19,null], true);
        generateTest([null,30], [10,20], true);
        generateTest([19,null], [10,20], true);
    });

    describe('do overlap (one range included in other range)', function() {
        generateTest([10,40], [20,30], true);
        generateTest([20,30], [10,40], true);

        generateTest([10,40], [null,null], true);
        generateTest([null,null], [10,40], true);
    });

    describe('do overlap (both ranges equal)', function() {
        generateTest([10,20], [10,20], true);

        generateTest([null,20], [null,20], true);
        generateTest([10,null], [10,null], true);
        generateTest([null,null], [null,null], true);
    });
});

Result when run with karma&jasmine&PhantomJS:

PhantomJS 1.9.8 (Linux): Executed 20 of 20 SUCCESS (0.003 secs / 0.004 secs)

Get img thumbnails from Vimeo?

Actually the guy who asked that question posted his own answer.

"Vimeo seem to want me to make a HTTP request, and extract the thumbnail URL from the XML they return..."

The Vimeo API docs are here: http://vimeo.com/api/docs/simple-api

In short, your app needs to make a GET request to an URL like the following:

http://vimeo.com/api/v2/video/video_id.output

and parse the returned data to get the thumbnail URL that you require, then download the file at that URL.

Are these methods thread safe?

It follows the convention that static methods should be thread-safe, but actually in v2 that static api is a proxy to an instance method on a default instance: in the case protobuf-net, it internally minimises contention points, and synchronises the internal state when necessary. Basically the library goes out of its way to do things right so that you can have simple code.

Boolean checking in the 'if' condition

My personal feeling when it comes to reading

if(!status) : if not status

if(status == false) : if status is false

if you are not used to !status reading. I see no harm doing as the second way.

if you use "active" instead of status I thing if(!active) is more readable

Google Chrome redirecting localhost to https

I am facing the same problem but only in Chrome Canary and searching a solution I've found this post.

one of the next versions of Chrome is going to force all domains ending on .dev (and .foo) to be redirected to HTTPs via a preloaded HTTP Strict Transport Security (HSTS) header.

{ "name": "dev", "include_subdomains": true, "mode": "force-https" },
{ "name": "foo", "include_subdomains": true, "mode": "force-https" },

So, change your domains.

Creating a JavaScript cookie on a domain and reading it across sub domains

You can also use the Cookies API and do:

browser.cookies.set({
  url: 'example.com',
  name: 'HelloWorld',
  value: 'HelloWorld',
  expirationDate: myDate
}

MDN Set() Method Documentation

How to apply multiple transforms in CSS?

You can also apply multiple transforms using an extra layer of markup e.g.:

<h3 class="rotated-heading">
    <span class="scaled-up">Hey!</span>
</h3>
<style type="text/css">
.rotated-heading
{
    transform: rotate(10deg);
}

.scaled-up
{
    transform: scale(1.5);
}
</style>

This can be really useful when animating elements with transforms using Javascript.

Detect IE version (prior to v9) in JavaScript

This function will return the IE major version number as an integer, or undefined if the browser isn't Internet Explorer. This, like all user agent solutions, is suceptible to user agent spoofing (which has been an official feature of IE since version 8).

function getIEVersion() {
    var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:)(\d+)/);
    return match ? parseInt(match[1]) : undefined;
}

Best way to define private methods for a class in Objective-C

Defining your private methods in the @implementation block is ideal for most purposes. Clang will see these within the @implementation, regardless of declaration order. There is no need to declare them in a class continuation (aka class extension) or named category.

In some cases, you will need to declare the method in the class continuation (e.g. if using the selector between the class continuation and the @implementation).

static functions are very good for particularly sensitive or speed critical private methods.

A convention for naming prefixes can help you avoid accidentally overriding private methods (I find the class name as a prefix safe).

Named categories (e.g. @interface MONObject (PrivateStuff)) are not a particularly good idea because of potential naming collisions when loading. They're really only useful for friend or protected methods (which are very rarely a good choice). To ensure you are warned of incomplete category implementations, you should actually implement it:

@implementation MONObject (PrivateStuff)
...HERE...
@end

Here's a little annotated cheat sheet:

MONObject.h

@interface MONObject : NSObject

// public declaration required for clients' visibility/use.
@property (nonatomic, assign, readwrite) bool publicBool;

// public declaration required for clients' visibility/use.
- (void)publicMethod;

@end

MONObject.m

@interface MONObject ()
@property (nonatomic, assign, readwrite) bool privateBool;

// you can use a convention where the class name prefix is reserved
// for private methods this can reduce accidental overriding:
- (void)MONObject_privateMethod;

@end

// The potentially good thing about functions is that they are truly
// inaccessible; They may not be overridden, accidentally used,
// looked up via the objc runtime, and will often be eliminated from
// backtraces. Unlike methods, they can also be inlined. If unused
// (e.g. diagnostic omitted in release) or every use is inlined,
// they may be removed from the binary:
static void PrivateMethod(MONObject * pObject) {
    pObject.privateBool = true;
}

@implementation MONObject
{
    bool anIvar;
}

static void AnotherPrivateMethod(MONObject * pObject) {
    if (0 == pObject) {
        assert(0 && "invalid parameter");
        return;
    }

    // if declared in the @implementation scope, you *could* access the
    // private ivars directly (although you should rarely do this):
    pObject->anIvar = true;
}

- (void)publicMethod
{
    // declared below -- but clang can see its declaration in this
    // translation:
    [self privateMethod];
}

// no declaration required.
- (void)privateMethod
{
}

- (void)MONObject_privateMethod
{
}

@end

Another approach which may not be obvious: a C++ type can be both very fast and provide a much higher degree of control, while minimizing the number of exported and loaded objc methods.

How do I get the last character of a string?

The other answers are very complete, and you should definitely use them if you're trying to find the last character of a string. But if you're just trying to use a conditional (e.g. is the last character 'g'), you could also do the following:

if (str.endsWith("g")) {

or, strings

if (str.endsWith("bar")) {

R not finding package even after package installation

Do .libPaths(), close every R runing, check in the first directory, remove the zoo package restart R and install zoo again. Of course you need to have sufficient rights.

Casting objects in Java

Say you have a superclass Fruit and the subclass Banana and you have a method addBananaToBasket()

The method will not accept grapes for example so you want to make sure that you're adding a banana to the basket.

So:

Fruit myFruit = new Banana();
((Banana)myFruit).addBananaToBasket(); ? This is called casting

android start activity from service

I had the same problem, and want to let you know that none of the above worked for me. What worked for me was:

 Intent dialogIntent = new Intent(this, myActivity.class);
 dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
 this.startActivity(dialogIntent);

and in one my subclasses, stored in a separate file I had to:

public static Service myService;

myService = this;

new SubService(myService);

Intent dialogIntent = new Intent(myService, myActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
myService.startActivity(dialogIntent);

All the other answers gave me a nullpointerexception.

how to save DOMPDF generated content to file?

<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) { 
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
    require_once('./dompdf/dompdf_config.inc.php');
    $dompdf = new DOMPDF;                        
    $dompdf->load_html($content);
    $dompdf->render();
    $dompdf->stream("hello.pdf");
}
?>
<html>
    <body>
        <form action="#" method="post">        
            <button name="pdf" type="submit">export</button>
        <table width="100%" border="1">
           <tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>         
            <?php for ($index = 0; $index < 10; $index++) { ?>
            <tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
            <?php } ?>            
        </table>        
        </form>        
    </body>
</html>

Data access object (DAO) in Java

I just want to explain it in my own way with a small story that I experienced in one of my projects. First I want to explain Why DAO is important? rather than go to What is DAO? for better understanding.

Why DAO is important?
In my one project of my project, I used Client.class which contains all the basic information of our system users. Where I need client then every time I need to do an ugly query where it is needed. Then I felt that decreases the readability and made a lot of redundant boilerplate code.

Then one of my senior developers introduced a QueryUtils.class where all queries are added using public static access modifier and then I don't need to do query everywhere. Suppose when I needed activated clients then I just call -

QueryUtils.findAllActivatedClients();

In this way, I made some optimizations of my code.

But there was another problem !!!

I felt that the QueryUtils.class was growing very highly. 100+ methods were included in that class which was also very cumbersome to read and use. Because this class contains other queries of another domain models ( For example- products, categories locations, etc ).

Then the superhero Mr. CTO introduced a new solution named DAO which solved the problem finally. I felt DAO is very domain-specific. For example, he created a DAO called ClientDAO.class where all Client.class related queries are found which seems very easy for me to use and maintain. The giant QueryUtils.class was broken down into many other domain-specific DAO for example - ProductsDAO.class, CategoriesDAO.class, etc which made the code more Readable, more Maintainable, more Decoupled.

What is DAO?

It is an object or interface, which made an easy way to access data from the database without writing complex and ugly queries every time in a reusable way.

Insert into C# with SQLCommand

Use AddWithValue(), but be aware of the possibility of the wrong implicit type conversion.
like this:

cmd.Parameters.AddWithValue("@param1", klantId);
    cmd.Parameters.AddWithValue("@param2", klantNaam);
    cmd.Parameters.AddWithValue("@param3", klantVoornaam);

Difference between <context:annotation-config> and <context:component-scan>

<context:annotation-config>: Scanning and activating annotations for already registered beans in spring config xml.

<context:component-scan>: Bean registration + <context:annotation-config>


@Autowired and @Required are targets property level so bean should register in spring IOC before use these annotations. To enable these annotations either have to register respective beans or include <context:annotation-config />. i.e. <context:annotation-config /> works with registered beans only.

@Required enables RequiredAnnotationBeanPostProcessor processing tool
@Autowired enables AutowiredAnnotationBeanPostProcessor processing tool

Note: Annotation itself nothing to do, we need a Processing Tool, which is a class underneath, responsible for the core process.


@Repository, @Service and @Controller are @Component, and they targets class level.

<context:component-scan> it scans the package and find and register the beans, and it includes the work done by <context:annotation-config />.

Migrating XML to Annotations

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

iPhone get SSID without private library

For iOS 13

As from iOS 13 your app also needs Core Location access in order to use the CNCopyCurrentNetworkInfo function unless it configured the current network or has VPN configurations:
excerpt from https://developer.apple.com/documentation/systemconfiguration/1614126-cncopycurrentnetworkinfo?language=objc

So this is what you need (see apple documentation):
- Link the CoreLocation.framework library
- Add location-services as a UIRequiredDeviceCapabilities Key/Value in Info.plist
- Add a NSLocationWhenInUseUsageDescription Key/Value in Info.plist describing why your app requires Core Location
- Add the "Access WiFi Information" entitlement for your app

Now as an Objective-C example, first check if location access has been accepted before reading the network info using CNCopyCurrentNetworkInfo:

- (void)fetchSSIDInfo {
    NSString *ssid = NSLocalizedString(@"not_found", nil);

    if (@available(iOS 13.0, *)) {
        if ([CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
            NSLog(@"User has explicitly denied authorization for this application, or location services are disabled in Settings.");
        } else {
            CLLocationManager* cllocation = [[CLLocationManager alloc] init];
            if(![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusNotDetermined){
                [cllocation requestWhenInUseAuthorization];
                usleep(500);
                return [self fetchSSIDInfo];
            }
        }
    }

    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    id info = nil;
    for (NSString *ifnam in ifs) {
        info = (__bridge_transfer id)CNCopyCurrentNetworkInfo(
            (__bridge CFStringRef)ifnam);

        NSDictionary *infoDict = (NSDictionary *)info;
        for (NSString *key in infoDict.allKeys) {
            if ([key isEqualToString:@"SSID"]) {
                ssid = [infoDict objectForKey:key];
            }
        }
    }        
        ...
    ...
}

How to define Singleton in TypeScript

In Typescript, one doesn't necessarily have to follow the new instance() Singleton methodology. An imported, constructor-less static class can work equally as well.

Consider:

export class YourSingleton {

   public static foo:bar;

   public static initialise(_initVars:any):void {
     YourSingleton.foo = _initvars.foo;
   }

   public static doThing():bar {
     return YourSingleton.foo
   }
}

You can import the class and refer to YourSingleton.doThing() in any other class. But remember, because this is a static class, it has no constructor so I usually use an intialise() method that is called from a class that imports the Singleton:

import {YourSingleton} from 'singleton.ts';

YourSingleton.initialise(params);
let _result:bar = YourSingleton.doThing();

Don't forget that in a static class, every method and variable needs to also be static so instead of this you would use the full class name YourSingleton.

When is a language considered a scripting language?

For a slightly different take on the question. A scripting language is a programming language but a programming language is not necessarily a scripting language. A scripting language is used to control or script a system. That system could be an operating system where the scripting language would be bash. The system could be a web server with PHP the scripting language. Scripting languages are designed to fill a specific niche; they are domain specific languages. Interactive systems have interpreted scripting languages giving rise to the notion that scripting languages are interpreted; however, this is a consequence of the system and not the scripting language itself.

How to find which version of Oracle is installed on a Linux server (In terminal)

Login as sys user in sql*plus. Then do this query:

select * from v$version; 

or

select * from product_component_version;

How to watch and reload ts-node when TypeScript files change

I would prefer to not use ts-node and always run from dist folder.

To do that, just setup your package.json with default config:

....
"main": "dist/server.js",
  "scripts": {
    "build": "tsc",
    "prestart": "npm run build",
    "start": "node .",
    "dev": "nodemon"
  },
....

and then add nodemon.json config file:

{
  "watch": ["src"],
  "ext": "ts",
  "ignore": ["src/**/*.spec.ts"],
  "exec": "npm restart"
}

Here, i use "exec": "npm restart"
so all ts file will re-compile to js file and then restart the server.

To run while in dev environment,

npm run dev

Using this setup I will always run from the distributed files and no need for ts-node.

Scroll back to the top of scrollable div

This worked for me :

document.getElementById('yourDivID').scrollIntoView();

How to create JSON object using jQuery

How to get append input field value as json like

temp:[
        {
           test:'test 1',
           testData:  [ 
                       {testName: 'do',testId:''}
                         ],
           testRcd:'value'                             
        },
        {
            test:'test 2',
           testData:  [
                            {testName: 'do1',testId:''}
                         ],
           testRcd:'value'                           
        }
      ],

Python 3 string.join() equivalent?

Visit https://www.tutorialspoint.com/python/string_join.htm

s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))

ab cd ef

s="."
print(s.join(seq))

ab.cd.ef

Grant Select on all Tables Owned By Specific User

Well, it's not a single statement, but it's about as close as you can get with oracle:

BEGIN
   FOR R IN (SELECT owner, table_name FROM all_tables WHERE owner='TheOwner') LOOP
      EXECUTE IMMEDIATE 'grant select on '||R.owner||'.'||R.table_name||' to TheUser';
   END LOOP;
END; 

Get last n lines of a file, similar to tail

This is my version of tailf

import sys, time, os

filename = 'path to file'

try:
    with open(filename) as f:
        size = os.path.getsize(filename)
        if size < 1024:
            s = size
        else:
            s = 999
        f.seek(-s, 2)
        l = f.read()
        print l
        while True:
            line = f.readline()
            if not line:
                time.sleep(1)
                continue
            print line
except IOError:
    pass

AttributeError: 'module' object has no attribute 'urlretrieve'

Suppose you have following lines of code

MyUrl = "www.google.com" #Your url goes here
urllib.urlretrieve(MyUrl)

If you are receiving following error message

AttributeError: module 'urllib' has no attribute 'urlretrieve'

Then you should try following code to fix the issue:

import urllib.request
MyUrl = "www.google.com" #Your url goes here
urllib.request.urlretrieve(MyUrl)

Generate SHA hash in C++ using OpenSSL library

Adaptation of @AndiDog version for big file:

static const int K_READ_BUF_SIZE{ 1024 * 16 };

std::optional<std::string> CalcSha256(std::string filename)
{
    // Initialize openssl
    SHA256_CTX context;
    if(!SHA256_Init(&context))
    {
        return std::nullopt;
    }

    // Read file and update calculated SHA
    char buf[K_READ_BUF_SIZE];
    std::ifstream file(filename, std::ifstream::binary);
    while (file.good())
    {
        file.read(buf, sizeof(buf));
        if(!SHA256_Update(&context, buf, file.gcount()))
        {
            return std::nullopt;
        }
    }

    // Get Final SHA
    unsigned char result[SHA256_DIGEST_LENGTH];
    if(!SHA256_Final(result, &context))
    {
        return std::nullopt;
    }

    // Transform byte-array to string
    std::stringstream shastr;
    shastr << std::hex << std::setfill('0');
    for (const auto &byte: result)
    {
        shastr << std::setw(2) << (int)byte;
    }
    return shastr.str();
}

How to print the number of characters in each line of a text file

Try this:

while read line    
do    
    echo -e |wc -m      
done <abc.txt    

Given URL is not permitted by the application configuration

Missing from the other answers is how to allow localhost(or 0.0.0.0 or whatever) as an oauth callback url. Here is the explanation. How can I add localhost:3000 to Facebook App for development

In python, how do I cast a class object to a dict

Like many others, I would suggest implementing a to_dict() function rather than (or in addition to) allowing casting to a dictionary. I think it makes it more obvious that the class supports that kind of functionality. You could easily implement such a method like this:

def to_dict(self):
    class_vars = vars(MyClass)  # get any "default" attrs defined at the class level
    inst_vars = vars(self)  # get any attrs defined on the instance (self)
    all_vars = dict(class_vars)
    all_vars.update(inst_vars)
    # filter out private attributes
    public_vars = {k: v for k, v in all_vars.items() if not k.startswith('_')}
    return public_vars

Byte and char conversion in Java

new String(byteArray, Charset.defaultCharset())

This will convert a byte array to the default charset in java. It may throw exceptions depending on what you supply with the byteArray.

Correct way to pass multiple values for same parameter name in GET request

there is no standard, but most frameworks support both, you can see for example for java spring that it accepts both here

@GetMapping("/api/foos")
@ResponseBody
public String getFoos(@RequestParam List<String> id) {
    return "IDs are " + id;
}

And Spring MVC will map a comma-delimited id parameter:

http://localhost:8080/api/foos?id=1,2,3
----
IDs are [1,2,3]

Or a list of separate id parameters:

http://localhost:8080/api/foos?id=1&id=2
----
IDs are [1,2]

How to use a class object in C++ as a function parameter

class is a keyword that is used only* to introduce class definitions. When you declare new class instances either as local objects or as function parameters you use only the name of the class (which must be in scope) and not the keyword class itself.

e.g.

class ANewType
{
    // ... details
};

This defines a new type called ANewType which is a class type.

You can then use this in function declarations:

void function(ANewType object);

You can then pass objects of type ANewType into the function. The object will be copied into the function parameter so, much like basic types, any attempt to modify the parameter will modify only the parameter in the function and won't affect the object that was originally passed in.

If you want to modify the object outside the function as indicated by the comments in your function body you would need to take the object by reference (or pointer). E.g.

void function(ANewType& object); // object passed by reference

This syntax means that any use of object in the function body refers to the actual object which was passed into the function and not a copy. All modifications will modify this object and be visible once the function has completed.

[* The class keyword is also used in template definitions, but that's a different subject.]

Synchronizing a local Git repository with a remote one

(This info is from The Git User's Manual)

I'm also learning, so this might not be exactly an answer to the question but it might help somebody:

  1. When a remote repository is initially cloned copies of all branches are stored in your local repository (view them with git branch -r)
  2. To update these copies and make them current (i.e. sync them with the remote branch) use git fetch. This will not effect any of you existing, custom created branches.
  3. To override your local branch checkout a fresh version of whatever branch you are working on (Assuming that you have already executed git add origin /path/to/repository) use git checkout origin/branch_name, this will override your locals changes on branch branch_name

What is the use of static synchronized method in java?

In simple words a static synchronized method will lock the class instead of the object, and it will lock the class because the keyword static means: "class instead of instance".

The keyword synchronized means that only one thread can access the method at a time.
And static synchronized mean:

Only one thread can access the class at one time.

Explicitly select items from a list or tuple

Another possible solution:

sek=[]
L=[1,2,3,4,5,6,7,8,9,0]
for i in [2, 4, 7, 0, 3]:
   a=[L[i]]
   sek=sek+a
print (sek)

A Generic error occurred in GDI+ in Bitmap.Save method

    // Once finished with the bitmap objects, we deallocate them.
    originalBMP.Dispose();

    bannerBMP.Dispose();
    oGraphics.Dispose();

This is a programming style that you'll regret sooner or later. Sooner is knocking on the door, you forgot one. You are not disposing newBitmap. Which keeps a lock on the file until the garbage collector runs. If it doesn't run then the second time you try to save to the same file you'll get the klaboom. GDI+ exceptions are too miserable to give a good diagnostic so serious head-scratching ensues. Beyond the thousands of googlable posts that mention this mistake.

Always favor using the using statement. Which never forgets to dispose an object, even if the code throws an exception.

using (var newBitmap = new Bitmap(thumbBMP)) {
    newBitmap.Save("~/image/thumbs/" + "t" + objPropBannerImage.ImageId, ImageFormat.Jpeg);
}

Albeit that it is very unclear why you even create a new bitmap, saving thumbBMP should already be good enough. Anyhoo, give the rest of your disposable objects the same using love.

How can I get the console logs from the iOS Simulator?

I can open the log directly via the iOS simulator: Debug -> Open System Log... Not sure when this was introduced, so it might not be available for earlier versions.

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

please do not set id of child class which is generator class is foreign only set parent class id if your parent class id is assigned... just do one thing dont set id of child class via setter method your problem will be fix.....definately.

How do I launch the Android emulator from the command line?

Just to add here, whenever you get "error: device offline" means that connection with emulator & adb bridge has been broken due to time taken in emulator startup.

Rather than re-starting emulator at this point try below two commands which stops & start adb bridge again.

adb kill-server

adb start-server

Stash just a single file

If you do not want to specify a message with your stashed changes, pass the filename after a double-dash.

$ git stash -- filename.ext

If it's an untracked/new file, you will have to stage it first.

However, if you do want to specify a message, use push.

git stash push -m "describe changes to filename.ext" filename.ext

Both methods work in git versions 2.13+

Best way to create a simple python web service

If you mean "web service" in SOAP/WSDL sense, you might want to look at Generating a WSDL using Python and SOAPpy

Git push existing repo to a new and different remote repo server?

I have had the same problem.

In my case, since I have the original repository in my local machine, I have made a copy in a new folder without any hidden file (.git, .gitignore).

Finally I have added the .gitignore file to the new created folder.

Then I have created and added the new repository from the local path (in my case using GitHub Desktop).

How can I retrieve Id of inserted entity using Entity framework?

It is pretty easy. If you are using DB generated Ids (like IDENTITY in MS SQL) you just need to add entity to ObjectSet and SaveChanges on related ObjectContext. Id will be automatically filled for you:

using (var context = new MyContext())
{
  context.MyEntities.Add(myNewObject);
  context.SaveChanges();

  int id = myNewObject.Id; // Yes it's here
}

Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when auto-generated Ids are used.

storing user input in array

You have at least these 3 issues:

  1. you are not getting the element's value properly
  2. The div that you are trying to use to display whether the values have been saved or not has id display yet in your javascript you attempt to get element myDiv which is not even defined in your markup.
  3. Never name variables with reserved keywords in javascript. using "string" as a variable name is NOT a good thing to do on most of the languages I can think of. I renamed your string variable to "content" instead. See below.

You can save all three values at once by doing:

var title=new Array();
var names=new Array();//renamed to names -added an S- 
                      //to avoid conflicts with the input named "name"
var tickets=new Array();

function insert(){
    var titleValue = document.getElementById('title').value;
    var actorValue = document.getElementById('name').value;
    var ticketsValue = document.getElementById('tickets').value;
    title[title.length]=titleValue;
    names[names.length]=actorValue;
    tickets[tickets.length]=ticketsValue;
  }

And then change the show function to:

function show() {
  var content="<b>All Elements of the Arrays :</b><br>";
  for(var i = 0; i < title.length; i++) {
     content +=title[i]+"<br>";
  }
  for(var i = 0; i < names.length; i++) {
     content +=names[i]+"<br>";
  }
  for(var i = 0; i < tickets.length; i++) {
     content +=tickets[i]+"<br>";
  }
  document.getElementById('display').innerHTML = content; //note that I changed 
                                                    //to 'display' because that's
                                              //what you have in your markup
}

Here's a jsfiddle for you to play around.

Create a pointer to two-dimensional array

You could also add an offset if you want to use negative indexes:

uint8_t l_matrix[10][20];
uint8_t (*matrix_ptr)[20] = l_matrix+5;
matrix_ptr[-4][1]=7;

If your compiler gives an error or warning you could use:

uint8_t (*matrix_ptr)[20] = (uint8_t (*)[20]) l_matrix;

Bootstrap: add margin/padding space between columns

Try this:

<div class="row">
      <div class="col-md-5">
         Set room heater temperature
     </div>
     <div class="col-md-2"></div>
     <div class="col-md-5">
         Set room heater temperature
     </div>
</div>

How to add header to a dataset in R?

You can also use colnames instead of names if you have data.frame or matrix

Adding a new array element to a JSON object

In my case, my JSON object didn't have any existing Array in it, so I had to create array element first and then had to push the element.

  elementToPush = [1, 2, 3]
  if (!obj.arr) this.$set(obj, "arr", [])
  obj.arr.push(elementToPush)  

(This answer may not be relevant to this particular question, but may help someone else)

Adding a line break in MySQL INSERT INTO text

First of all, if you want it displayed on a PHP form, the medium is HTML and so a new line will be rendered with the <br /> tag. Check the source HTML of the page - you may possibly have the new line rendered just as a line break, in which case your problem is simply one of translating the text for output to a web browser.

Ruby replace string with captured regex pattern

Try '\1' for the replacement (single quotes are important, otherwise you need to escape the \):

"foo".gsub(/(o+)/, '\1\1\1')
#=> "foooooo"

But since you only seem to be interested in the capture group, note that you can index a string with a regex:

"foo"[/oo/]
#=> "oo"
"Z_123: foobar"[/^Z_.*(?=:)/]
#=> "Z_123"

How do I import the javax.servlet API in my Eclipse project?

I know this is an old post. However, I observed another instance where in the project already has Tomcat added but we still get this error. Did this to resolve that:
Alt + Enter
Project Facets
On the right, next to details, is another tab "Runtimes". The installed tomcat server will be listed there. Select it.
Save the configuration and DONE!

Hope this helps someone.

What is the Sign Off feature in Git for?

Sign-off is a line at the end of the commit message which certifies who is the author of the commit. Its main purpose is to improve tracking of who did what, especially with patches.

Example commit:

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

It should contain the user real name if used for an open-source project.

If branch maintainer need to slightly modify patches in order to merge them, he could ask the submitter to rediff, but it would be counter-productive. He can adjust the code and put his sign-off at the end so the original author still gets credit for the patch.

Add tests for the payment processor.

Signed-off-by: Humpty Dumpty <[email protected]>

[Project Maintainer: Renamed test methods according to naming convention.]
Signed-off-by: Project Maintainer <[email protected]>

Source: http://gerrit.googlecode.com/svn/documentation/2.0/user-signedoffby.html

Play local (hard-drive) video file with HTML5 video tag?

That will be possible only if the HTML file is also loaded with the file protocol from the local user's harddisk.

If the HTML page is served by HTTP from a server, you can't access any local files by specifying them in a src attribute with the file:// protocol as that would mean you could access any file on the users computer without the user knowing which would be a huge security risk.

As Dimitar Bonev said, you can access a file if the user selects it using a file selector on their own. Without that step, it's forbidden by all browsers for good reasons. Thus, while his answer might prove useful for many people, it loosens the requirement from the code in the original question.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

How to draw border around a UILabel?

Solution for Swift 4:

yourLabel.layer.borderColor = UIColor.green.cgColor

Printing the last column of a line in a file

You can do all of it in awk:

<file awk '$1 ~ /A1/ {m=$NF} END {print m}'

jQuery set radio button

Combining previous answers:

$('input[name="cols"]').filter("[value='Site']").click();

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

You can use Replace instead of INSERT ... ON DUPLICATE KEY UPDATE.

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

This worked for me:

Check the current role you are logged into by using: SELECT CURRENT_USER, SESSION_USER;

Note: It must match with Owner of the schema.

Schema | Name | Type | Owner
--------+--------+-------+----------

If the owner is different, then give all the grants to the current user role from the admin role by :

GRANT 'ROLE_OWNER' to 'CURRENT ROLENAME';

Then try to execute the query, it will give the output as it has access to all the relations now.

How to check ASP.NET Version loaded on a system?

I needed this information too and got information with this method,

Launch PowerShell

run the 'import-module servermanager' command ( without quotes )

after that for asp.net 3.5 check run the 'get-windowsfeature web-asp-net' command ( without quotes )

for asp.net 4.5 check run the 'get-windowsfeature Net-Framework-45-Core' command ( without quotes )

Both of the commands will inform you below Install State header.

Detecting version via GUI in server environment and details can be found in this link.

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

Here is how I encountered this error in Django and fixed it:

Code with error

urlpatterns = [path('home/', views.home, 'home'),]

Correction

urlpatterns = [path('home/', views.home, name='home'),]

Is it better to return null or empty collection?

Depends on the situation. If it is a special case, then return null. If the function just happens to return an empty collection, then obviously returning that is ok. However, returning an empty collection as a special case because of invalid parameters or other reasons is NOT a good idea, because it is masking a special case condition.

Actually, in this case I usually prefer to throw an exception to make sure it is REALLY not ignored :)

Saying that it makes the code more robust (by returning an empty collection) as they do not have to handle the null condition is bad, as it is simply masking a problem that should be handled by the calling code.

How do I revert back to an OpenWrt router configuration?

You can run this command for making a factory reset:

killall dropbear uhttpd; sleep 1; mtd -r erase rootfs_data

How do I convert from int to Long in Java?

I had a great deal of trouble with this. I just wanted to:

thisBill.IntervalCount = jPaidCountSpinner.getValue();

Where IntervalCount is a Long, and the JSpinner was set to return a Long. Eventually I had to write this function:

    public static final Long getLong(Object obj) throws IllegalArgumentException {
    Long rv;

    if((obj.getClass() == Integer.class) || (obj.getClass() == Long.class) || (obj.getClass() == Double.class)) {
        rv = Long.parseLong(obj.toString());
    }
    else if((obj.getClass() == int.class) || (obj.getClass() == long.class) || (obj.getClass() == double.class)) {
        rv = (Long) obj;
    }
    else if(obj.getClass() == String.class) {
        rv = Long.parseLong(obj.toString());
    }
    else {
        throw new IllegalArgumentException("getLong: type " + obj.getClass() + " = \"" + obj.toString() + "\" unaccounted for");
    }

    return rv;
}

which seems to do the trick. No amount of simple casting, none of the above solutions worked for me. Very frustrating.

Android - SMS Broadcast receiver

android.provider.telephony.SMS_RECEIVED is not correct because Telephony is a class and it should be capital as in android.provider.Telephony.SMS_RECEIVED

Run "mvn clean install" in Eclipse

If you want to open command prompt inside your eclipse, this can be a useful approach to link cmd with eclipse.

You can follow this link to get the steps in detail with screenshots. How to use cmd prompt inside Eclipse ?

I'm quoting the steps here:

Step 1: Setup a new External Configuration Tool

In the Eclipse tool go to Run -> External Tools -> External Tools Configurations option.

Step 2: Click New Launch Configuration option in Create, manage and run configuration screen

Step 3: New Configuration screen for configuring the command prompt

Step 4: Provide configuration details of the Command Prompt in the Main tab

Name: Give any name to your configuration (Here it is Command_Prompt)
Location: Location of the CMD.exe in your Windows
Working Directory: Any directory where you want to point the Command prompt

Step 5: Tick the check box Allocate console This will ensure the eclipse console is being used as the command prompt for any input or output.

Step 6: Click Run and you are there!! You will land up in the C: directory as a working directory

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

Since cP/WHM took away the ability to modify User privileges as root in PHPMyAdmin, you have to use the command line to:

mysql>  GRANT FILE ON *.* TO 'user'@'localhost';

Step 2 is to allow that user to dump a file in a specific folder. There are a few ways to do this but I ended up putting a folder in :

/home/user/tmp/db

and

chown mysql:mysql /home/user/tmp/db

That allows the mysql user to write the file. As previous posters have said, you can use the MySQL temp folder too, I don't suppose it really matters but you definitely don't want to make it 0777 permission (world-writeable) unless you want the world to see your data. There is a potential problem if you want to rinse-repeat the process as INTO OUTFILE won't work if the file exists. If your files are owned by a different user then just trying to unlink($file) won't work. If you're like me (paranoid about 0777) then you can set your target directory using:

chmod($dir,0777)

just prior to doing the SQL command, then

chmod($dir,0755)

immediately after, followed by unlink(file) to delete the file. This keeps it all running under your web user and no need to invoke the mysql user.

forEach loop Java 8 for Map entry set

String ss = "Pawan kavita kiyansh Patidar Patidar";
    StringBuilder ress = new StringBuilder();
    
    Map<Character, Integer> fre = ss.chars().boxed()
            .collect(Collectors.toMap(k->Character.valueOf((char) k.intValue()),k->1,Integer::sum));
    
      //fre.forEach((k, v) -> System.out.println((k + ":" + v)));
    
    fre.entrySet().forEach(e ->{
            //System.out.println(e.getKey() + ":" + e.getValue());
            //ress.append(String.valueOf(e.getKey())+e.getValue());
        }); 

    fre.forEach((k,v)->{
        //System.out.println("Item : " + k + " Count : " + v);
        ress.append(String.valueOf(k)+String.valueOf(v));
    });
    
    System.out.println(ress.toString());

Delete empty rows

DELETE FROM table WHERE edit_user IS NULL;

find index of an int in a list

List<string> accountList = new List<string> {"123872", "987653" , "7625019", "028401"};

int i = accountList.FindIndex(x => x.StartsWith("762"));
//This will give you index of 7625019 in list that is 2. value of i will become 2.
//delegate(string ac)
//{
//    return ac.StartsWith(a.AccountNumber);
//}
//);

Adding minutes to date time in PHP

Use strtotime("+5 minute", $date);


Example:

$date = "2017-06-16 08:40:00";
$date = strtotime($date);
$date = strtotime("+5 minute", $date);
echo date('Y-m-d H:i:s', $date);

Invoking modal window in AngularJS Bootstrap UI using JavaScript

To make angular ui $modal work with bootstrap 3 you need to overwrite the styles

.modal {
    display: block;
}
.modal-body:before,
.modal-body:after {
    display: table;
    content: " ";
}
.modal-header:before,
.modal-header:after {
    display: table;
    content: " ";
}

(The last ones are necessary if you use custom directives) and encapsulate the html with

<div class="modal-dialog">
  <div class="modal-content">
    <div class="modal-header">
      <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
      <h4 class="modal-title">Modal title</h4>
    </div>
    <div class="modal-body">
      ...
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      <button type="button" class="btn btn-primary">Save changes</button>
    </div>
  </div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->

How to select only 1 row from oracle sql?

More flexible than select max() is:

select distinct first_row(column_x) over (order by column_y,column_z,...) from Table_A

Overflow Scroll css is not working in the div

If you set a static height for your header, you can use that in a calculation for the size of your wrapper.

http://jsfiddle.net/ske5Lqyv/5/

Using your example code, you can add this CSS:

html, body {
  margin: 0px;
  padding: 0px;
  height: 100%;
}

#container {
  height: 100%;
}

.header {
  height: 64px;
  background-color: lightblue;
}

.wrapper {
  height: calc(100% - 64px);
  overflow-y: auto;
}

Or, you can use flexbox for a more dynamic approach http://jsfiddle.net/19zbs7je/3/

<div id="container">
  <div class="section">
    <div class="header">Heading</div>
    <div class="wrapper">
      <p>Large Text</p>
    </div>
  </div>
</div>

html, body {
  margin: 0px;
  padding: 0px;
  height: 100%;
}

#container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.section {
  flex-grow: 1;
  display: flex;
  flex-direction: column;
  min-height: 0;
}

.header {
  height: 64px;
  background-color: lightblue;
  flex-shrink: 0;
}

.wrapper {
  flex-grow: 1;
  overflow: auto;
  min-height: 100%; 
}

And if you'd like to get even fancier, take a look at my response to this question https://stackoverflow.com/a/52416148/1513083

PHP date() with timezone?

It should like this:

date_default_timezone_set('America/New_York');

error LNK2005: xxx already defined in MSVCRT.lib(MSVCR100.dll) C:\something\LIBCMT.lib(setlocal.obj)

Getting this error, I changed the

c/C++ > Code Generation > Runtime Library to Multi-threaded library (DLL) /MD

for both code project and associated Google Test project. This solved the issue.

Note: all components of the project must have the same definition in c/C++ > Code Generation > Runtime Library. Either DLL or not DLL, but identical.

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

It is possible to get a web application running in full screen in both iOS and Android, it is called a PWA and after mucha hard work, it was the only way around this issue.

PWAs open a number of interesting options for development that should not be missed. I've made a couple already, check out this Public and Private Tender Manual For Designers (Spanish). And here is an English explanation from the CosmicJS site

What are the First and Second Level caches in (N)Hibernate?

Here some basic explanation of hibernate cache...

First level cache is associated with “session” object. The scope of cache objects is of session. Once session is closed, cached objects are gone forever. First level cache is enabled by default and you can not disable it. When we query an entity first time, it is retrieved from database and stored in first level cache associated with hibernate session. If we query same object again with same session object, it will be loaded from cache and no sql query will be executed. The loaded entity can be removed from session using evict() method. The next loading of this entity will again make a database call if it has been removed using evict() method. The whole session cache can be removed using clear() method. It will remove all the entities stored in cache.

Second level cache is apart from first level cache which is available to be used globally in session factory scope. second level cache is created in session factory scope and is available to be used in all sessions which are created using that particular session factory. It also means that once session factory is closed, all cache associated with it die and cache manager also closed down. Whenever hibernate session try to load an entity, the very first place it look for cached copy of entity in first level cache (associated with particular hibernate session). If cached copy of entity is present in first level cache, it is returned as result of load method. If there is no cached entity in first level cache, then second level cache is looked up for cached entity. If second level cache has cached entity, it is returned as result of load method. But, before returning the entity, it is stored in first level cache also so that next invocation to load method for entity will return the entity from first level cache itself, and there will not be need to go to second level cache again. If entity is not found in first level cache and second level cache also, then database query is executed and entity is stored in both cache levels, before returning as response of load() method.

How to drop columns using Rails migration

For older versions of Rails

ruby script/generate migration RemoveFieldNameFromTableName field_name:datatype

For Rails 3 and up

rails generate migration RemoveFieldNameFromTableName field_name:datatype

Export/import jobs in Jenkins

This does not work for existing jobs, however there is Jenkins job builder.

This allows one to keep job definitions in yaml files and in a git repo which is very portable.

Reverse order of foreach list items

<?php
    $j=1; 


      array_reverse($skills_nav);   


    foreach ( $skills_nav as $skill ) {
        $a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
        $a .= $skill->name;                 
        $a .= '</a></li>';
        echo $a;
        echo "\n";
        $j++;
    }
?> 

Scrolling a div with jQuery

An excellent plug-in is jscrollpane

How to find the mysql data directory from command line in windows

Use bellow command from CLI interface

[root@localhost~]# mysqladmin variables -p<password> | grep datadir

call javascript function on hyperlink click

The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:

<div class="menu">
    <a href="http://example.org">Example</a>
    <a href="http://foobar.com">Foobar.com</a>
</div>

<script>
jQuery( 'div.menu a' )
    .click(function() {
        do_the_click( this.href );
        return false;
    });

// play the funky music white boy
function do_the_click( url )
{
    alert( url );
}
</script>

Make elasticsearch only return certain fields?

Yep, Use a better option source filter. If you're searching with JSON it'll look something like this:

{
    "_source": ["user", "message", ...],
    "query": ...,
    "size": ...
}

In ES 2.4 and earlier, you could also use the fields option to the search API:

{
    "fields": ["user", "message", ...],
    "query": ...,
    "size": ...
}

This is deprecated in ES 5+. And source filters are more powerful anyway!

jQueryUI modal dialog does not show close button (x)

Pure CSS Workaround:

I was using both bootstrap and jQuery UI and changing the order of adding the scripts broke some other objects. I ended up using pure CSS workaround:

.ui-dialog-titlebar-close {
  background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_888888_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
  border: medium none;
}
.ui-dialog-titlebar-close:hover {
  background: url("http://code.jquery.com/ui/1.10.3/themes/smoothness/images/ui-icons_222222_256x240.png") repeat scroll -93px -128px rgba(0, 0, 0, 0);
}

Just disable scroll not hide it?

This is the solution we went with. Simply save the scroll position when the overlay is opened, scroll back to the saved position any time the user attempted to scroll the page, and turn the listener off when the overlay is closed.

It's a bit jumpy on IE, but works like a charm on Firefox/Chrome.

_x000D_
_x000D_
var body = $("body"),_x000D_
  overlay = $("#overlay"),_x000D_
  overlayShown = false,_x000D_
  overlayScrollListener = null,_x000D_
  overlaySavedScrollTop = 0,_x000D_
  overlaySavedScrollLeft = 0;_x000D_
_x000D_
function showOverlay() {_x000D_
  overlayShown = true;_x000D_
_x000D_
  // Show overlay_x000D_
  overlay.addClass("overlay-shown");_x000D_
_x000D_
  // Save scroll position_x000D_
  overlaySavedScrollTop = body.scrollTop();_x000D_
  overlaySavedScrollLeft = body.scrollLeft();_x000D_
_x000D_
  // Listen for scroll event_x000D_
  overlayScrollListener = body.scroll(function() {_x000D_
    // Scroll back to saved position_x000D_
    body.scrollTop(overlaySavedScrollTop);_x000D_
    body.scrollLeft(overlaySavedScrollLeft);_x000D_
  });_x000D_
}_x000D_
_x000D_
function hideOverlay() {_x000D_
  overlayShown = false;_x000D_
_x000D_
  // Hide overlay_x000D_
  overlay.removeClass("overlay-shown");_x000D_
_x000D_
  // Turn scroll listener off_x000D_
  if (overlayScrollListener) {_x000D_
    overlayScrollListener.off();_x000D_
    overlayScrollListener = null;_x000D_
  }_x000D_
}_x000D_
_x000D_
// Click toggles overlay_x000D_
$(window).click(function() {_x000D_
  if (!overlayShown) {_x000D_
    showOverlay();_x000D_
  } else {_x000D_
    hideOverlay();_x000D_
  }_x000D_
});
_x000D_
/* Required */_x000D_
html, body { margin: 0; padding: 0; height: 100%; background: #fff; }_x000D_
html { overflow: hidden; }_x000D_
body { overflow-y: scroll; }_x000D_
_x000D_
/* Just for looks */_x000D_
.spacer { height: 300%; background: orange; background: linear-gradient(#ff0, #f0f); }_x000D_
.overlay { position: fixed; top: 20px; bottom: 20px; left: 20px; right: 20px; z-index: -1; background: #fff; box-shadow: 0 0 5px rgba(0, 0, 0, .3); overflow: auto; }_x000D_
.overlay .spacer { background: linear-gradient(#88f, #0ff); }_x000D_
.overlay-shown { z-index: 1; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<h1>Top of page</h1>_x000D_
<p>Click to toggle overlay. (This is only scrollable when overlay is <em>not</em> open.)</p>_x000D_
<div class="spacer"></div>_x000D_
<h1>Bottom of page</h1>_x000D_
<div id="overlay" class="overlay">_x000D_
  <h1>Top of overlay</h1>_x000D_
  <p>Click to toggle overlay. (Containing page is no longer scrollable, but this is.)</p>_x000D_
  <div class="spacer"></div>_x000D_
  <h1>Bottom of overlay</h1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Conversion from 12 hours time to 24 hours time in java

Assuming that you use SimpleDateFormat implicitly or explicitly, you need to use H instead of h in the format string.

E.g

HH:mm:ss

instead of

hh:mm:ss

@viewChild not working - cannot read property nativeElement of undefined

What happens is when these elements are called before the DOM is loaded these kind of errors come up. Always use:

 window.onload = function(){
     this.keywordsInput.nativeElement.focus();
 }

Delaying AngularJS route change until model loaded to prevent flicker

$routeProvider resolve property allows delaying of route change until data is loaded.

First define a route with resolve attribute like this.

angular.module('phonecat', ['phonecatFilters', 'phonecatServices', 'phonecatDirectives']).
  config(['$routeProvider', function($routeProvider) {
    $routeProvider.
      when('/phones', {
        templateUrl: 'partials/phone-list.html', 
        controller: PhoneListCtrl, 
        resolve: PhoneListCtrl.resolve}).
      when('/phones/:phoneId', {
        templateUrl: 'partials/phone-detail.html', 
        controller: PhoneDetailCtrl, 
        resolve: PhoneDetailCtrl.resolve}).
      otherwise({redirectTo: '/phones'});
}]);

notice that the resolve property is defined on route.

function PhoneListCtrl($scope, phones) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

PhoneListCtrl.resolve = {
  phones: function(Phone, $q) {
    // see: https://groups.google.com/forum/?fromgroups=#!topic/angular/DGf7yyD4Oc4
    var deferred = $q.defer();
    Phone.query(function(successData) {
            deferred.resolve(successData); 
    }, function(errorData) {
            deferred.reject(); // you could optionally pass error data here
    });
    return deferred.promise;
  },
  delay: function($q, $defer) {
    var delay = $q.defer();
    $defer(delay.resolve, 1000);
    return delay.promise;
  }
}

Notice that the controller definition contains a resolve object which declares things which should be available to the controller constructor. Here the phones is injected into the controller and it is defined in the resolve property.

The resolve.phones function is responsible for returning a promise. All of the promises are collected and the route change is delayed until after all of the promises are resolved.

Working demo: http://mhevery.github.com/angular-phonecat/app/#/phones Source: https://github.com/mhevery/angular-phonecat/commit/ba33d3ec2d01b70eb5d3d531619bf90153496831

Remove duplicated rows using dplyr

If you want to find the rows that are duplicated you can use find_duplicates from hablar:

library(dplyr)
library(hablar)

df <- tibble(a = c(1, 2, 2, 4),
             b = c(5, 2, 2, 8))

df %>% find_duplicates()

Add single element to array in numpy

Try this:

np.concatenate((a, np.array([a[0]])))

http://docs.scipy.org/doc/numpy/reference/generated/numpy.concatenate.html

concatenate needs both elements to be numpy arrays; however, a[0] is not an array. That is why it does not work.

Java 32-bit vs 64-bit compatibility

Yes, Java bytecode (and source code) is platform independent, assuming you use platform independent libraries. 32 vs. 64 bit shouldn't matter.

Convert data file to blob

A file object is an instance of Blob but a blob object is not an instance of File

new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true

new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false

new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false

If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
    let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
    console.log(blob);
};
reader.readAsArrayBuffer(file);

As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.

let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];

file.arrayBuffer().then((arrayBuffer) => {
    let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
    console.log(blob);
});

If your environment supports async/await you can use a one-liner like below

let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));

alert() not working in Chrome

Here is a snippet that does not need ajQuery and will enable alerts in a disabled iframe (like on codepen)

for (var i = 0; i < document.getElementsByTagName('iframe').length; i++) {
    document.getElementsByTagName('iframe')[i].setAttribute('sandbox','allow-modals');
}

Here is a codepen demo working with an alert() after this fix as well: http://codepen.io/nicholasabrams/pen/vNpoBr?editors=001

jQuery .attr("disabled", "disabled") not working in Chrome

Here:
http://jsbin.com/urize4/edit

Live Preview
http://jsbin.com/urize4/

You should use "readonly" instead like:

$("input[type='text']").attr("readonly", "true");

Play audio from a stream using C#

Edit: Answer updated to reflect changes in recent versions of NAudio

It's possible using the NAudio open source .NET audio library I have written. It looks for an ACM codec on your PC to do the conversion. The Mp3FileReader supplied with NAudio currently expects to be able to reposition within the source stream (it builds an index of MP3 frames up front), so it is not appropriate for streaming over the network. However, you can still use the MP3Frame and AcmMp3FrameDecompressor classes in NAudio to decompress streamed MP3 on the fly.

I have posted an article on my blog explaining how to play back an MP3 stream using NAudio. Essentially you have one thread downloading MP3 frames, decompressing them and storing them in a BufferedWaveProvider. Another thread then plays back using the BufferedWaveProvider as an input.

Visual Studio replace tab with 4 spaces?

First set in the following path Tools->Options->Text Editor->All Languages->Tabs if still didn't work modify as mentioned below Go to Edit->Advanced->Set Indentation ->Spaces

How to pass password to scp?

Here's a poor man's Linux/Python/Expect-like example based on this blog post: Upgrading simple shells to fully interactive TTYs. I needed this for old machines where I can't install Expect or add modules to Python.

Code:

(
    echo 'scp [email protected]:./install.sh .'
    sleep 5
    echo 'scp-passwd'
    sleep 5
    echo 'exit'
) |

python -c 'import pty; pty.spawn("/usr/bin/bash")'

Output:

scp [email protected]:install.sh .
bash-4.2$ scp [email protected]:install.sh .
Password: 
install.sh                                 100%   15KB 236.2KB/s   00:00    
bash-4.2$ exit
exit

How do I float a div to the center?

There is no float: center; in css. Use margin: 0 auto; instead. So like this:

.mydivclass {
    margin: 0 auto;
 }

Excel is not updating cells, options > formula > workbook calculation set to automatic

Go to Files->Options->Formulas-> Calculation Options / Set Workbook calculation to Automatic

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

Create a data.frame with m columns and 2 rows

For completeness:

Along the lines of Chase's answer, I usually use as.data.frame to coerce the matrix to a data.frame:

m <- as.data.frame(matrix(0, ncol = 30, nrow = 2))

EDIT: speed test data.frame vs. as.data.frame

system.time(replicate(10000, data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  8.005   0.108   8.165 

system.time(replicate(10000, as.data.frame(matrix(0, ncol = 30, nrow = 2))))
   user  system elapsed 
  3.759   0.048   3.802 

Yes, it appears to be faster (by about 2 times).

Android Studio how to run gradle sync manually?

In Android Studio 3.3 it is here:

enter image description here

According to the answer https://stackoverflow.com/a/49576954/2914140 in Android Studio 3.1 it is here:

enter image description here

This command is moved to File > Sync Project with Gradle Files.

enter image description here

Https Connection Android

Sources that helped me get to work with my self signed certificate on my AWS Apache server and connect with HttpsURLConnection from android device:

SSL on aws instance - amazon tutorial on ssl
Android Security with HTTPS and SSL - creating your own trust manager on client for accepting your certificate
Creating self signed certificate - easy script for creating your certificates

Then I did the following:

  1. Made sure the server supports https (sudo yum install -y mod24_ssl)
  2. Put this script in a file create_my_certs.sh:
#!/bin/bash
FQDN=$1

# make directories to work from
mkdir -p server/ client/ all/

# Create your very own Root Certificate Authority
openssl genrsa \
  -out all/my-private-root-ca.privkey.pem \
  2048

# Self-sign your Root Certificate Authority
# Since this is private, the details can be as bogus as you like
openssl req \
  -x509 \
  -new \
  -nodes \
  -key all/my-private-root-ca.privkey.pem \
  -days 1024 \
  -out all/my-private-root-ca.cert.pem \
  -subj "/C=US/ST=Utah/L=Provo/O=ACME Signing Authority Inc/CN=example.com"

# Create a Device Certificate for each domain,
# such as example.com, *.example.com, awesome.example.com
# NOTE: You MUST match CN to the domain name or ip address you want to use
openssl genrsa \
  -out all/privkey.pem \
  2048

# Create a request from your Device, which your Root CA will sign
openssl req -new \
  -key all/privkey.pem \
  -out all/csr.pem \
  -subj "/C=US/ST=Utah/L=Provo/O=ACME Tech Inc/CN=${FQDN}"

# Sign the request from Device with your Root CA
openssl x509 \
  -req -in all/csr.pem \
  -CA all/my-private-root-ca.cert.pem \
  -CAkey all/my-private-root-ca.privkey.pem \
  -CAcreateserial \
  -out all/cert.pem \
  -days 500

# Put things in their proper place
rsync -a all/{privkey,cert}.pem server/
cat all/cert.pem > server/fullchain.pem         # we have no intermediates in this case
rsync -a all/my-private-root-ca.cert.pem server/
rsync -a all/my-private-root-ca.cert.pem client/
  1. Run bash create_my_certs.sh yourdomain.com
  2. Place the certificates in their proper place on the server (you can find configuration in /etc/httpd/conf.d/ssl.conf). All these should be set:
    SSLCertificateFile
    SSLCertificateKeyFile
    SSLCertificateChainFile
    SSLCACertificateFile

  3. Restart httpd using sudo service httpd restart and make sure httpd started:
    Stopping httpd: [ OK ]
    Starting httpd: [ OK ]

  4. Copy my-private-root-ca.cert to your android project assets folder

  5. Create your trust manager:

    SSLContext SSLContext;

    CertificateFactory cf = CertificateFactory.getInstance("X.509"); InputStream caInput = context.getAssets().open("my-private-root-ca.cert.pem"); Certificate ca; try { ca = cf.generateCertificate(caInput); } finally { caInput.close(); }

      // Create a KeyStore containing our trusted CAs
      String keyStoreType = KeyStore.getDefaultType();
      KeyStore keyStore = KeyStore.getInstance(keyStoreType);
      keyStore.load(null, null);
      keyStore.setCertificateEntry("ca", ca);
    
      // Create a TrustManager that trusts the CAs in our KeyStore
      String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
      TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
      tmf.init(keyStore);
    
      // Create an SSLContext that uses our TrustManager
      SSLContext = SSLContext.getInstance("TLS");
      SSSLContext.init(null, tmf.getTrustManagers(), null);
    
  6. And make the connection using HttpsURLConnection:

    HttpsURLConnection connection = (HttpsURLConnection) url.openConnection(); connection.setSSLSocketFactory(SSLContext.getSocketFactory());

  7. Thats it, try your https connection.

How do I pass multiple attributes into an Angular.js attribute directive?

This worked for me and I think is more HTML5 compliant. You should change your html to use 'data-' prefix

<div data-example-directive data-number="99"></div>

And within the directive read the variable's value:

scope: {
        number : "=",
        ....
    },

C++ Singleton design pattern

You could avoid memory allocation. There are many variants, all having problems in case of multithreading environment.

I prefer this kind of implementation (actually, it is not correctly said I prefer, because I avoid singletons as much as possible):

class Singleton
{
private:
   Singleton();

public:
   static Singleton& instance()
   {
      static Singleton INSTANCE;
      return INSTANCE;
   }
};

It has no dynamic memory allocation.

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

How do I break a string in YAML over multiple lines?

None of the above solutions worked for me, in a YAML file within a Jekyll project. After trying many options, I realized that an HTML injection with <br> might do as well, since in the end everything is rendered to HTML:

name: | In a village of La Mancha <br> whose name I don't <br> want to remember.

At least it works for me. No idea on the problems associated to this approach.

Insert all values of a table into another table in SQL

 Dim ofd As New OpenFileDialog
                ofd.Filter = "*.mdb|*.MDB"
                ofd.FilterIndex = (2)
                ofd.FileName = "bd1.mdb"
                ofd.Title = "SELECCIONE LA BASE DE DATOS ORIGEN (bd1.mdb)"
                ofd.ShowDialog()
                Dim conexion1 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd.FileName
                Dim conn As New OdbcConnection()
                conn.ConnectionString = conexion1
                conn.Open()



            'EN ESTE CODIGO SOLO SE AGREGAN LOS DATOS'
            Dim ofd2 As New OpenFileDialog
            ofd2.Filter = "*.mdb|*.MDB"
            ofd2.FilterIndex = (2)
            ofd2.FileName = "bd1.mdb"
            ofd2.Title = "SELECCIONE LA BASE DE DATOS DESTINO (bd1.mdb)"
            ofd2.ShowDialog()
            Dim conexion2 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd2.FileName
            Dim conn2 As New OdbcConnection()
            conn2.ConnectionString = conexion2
            Dim cmd2 As New OdbcCommand
            Dim CADENA2 As String

            CADENA2 = "INSERT INTO EXISTENCIA IN '" + ofd2.FileName + "' SELECT * FROM EXISTENCIA IN '" + ofd.FileName + "'"


            cmd2.CommandText = CADENA2
            cmd2.Connection = conn2
            conn2.Open()
            Dim dA2 As New OdbcDataAdapter
            dA2.SelectCommand = cmd2
            Dim midataset2 As New DataSet
            dA2.Fill(midataset2, "EXISTENCIA")

How can I disable a specific LI element inside a UL?

If you still want to show the item but make it not clickable and look disabled with CSS:

CSS:

.disabled {
    pointer-events:none; //This makes it not clickable
    opacity:0.6;         //This grays it out to look disabled
}

HTML:

<li class="disabled">Disabled List Item</li>

Also, if you are using BootStrap, they already have a class called disabled for this purpose. See this example.

As @LV98 pointed out, users could change this on the client side and submit a selection you weren't expecting. You will want to validate at the server as well.

Assigning multiple styles on an HTML element

You needed to do it like this:

_x000D_
_x000D_
<h2 style="text-align: center;font-family: Tahoma">TITLE</h2>
_x000D_
_x000D_
_x000D_

Hope it helped.

How can I put the current running linux process in background?

Suspend the process with CTRL+Z then use the command bg to resume it in background. For example:

sleep 60
^Z  #Suspend character shown after hitting CTRL+Z
[1]+  Stopped  sleep 60  #Message showing stopped process info
bg  #Resume current job (last job stopped)

More about job control and bg usage in bash manual page:

JOB CONTROL
Typing the suspend character (typically ^Z, Control-Z) while a process is running causes that process to be stopped and returns control to bash. [...] The user may then manipulate the state of this job, using the bg command to continue it in the background, [...]. A ^Z takes effect immediately, and has the additional side effect of causing pending output and typeahead to be discarded.

bg [jobspec ...]
Resume each suspended job jobspec in the background, as if it had been started with &. If jobspec is not present, the shell's notion of the current job is used.

EDIT

To start a process where you can even kill the terminal and it still carries on running

nohup [command] [-args] > [filename] 2>&1 &

e.g.

nohup /home/edheal/myprog -arg1 -arg2 > /home/edheal/output.txt 2>&1 &

To just ignore the output (not very wise) change the filename to /dev/null

To get the error message set to a different file change the &1 to a filename.

In addition: You can use the jobs command to see an indexed list of those backgrounded processes. And you can kill a backgrounded process by running kill %1 or kill %2 with the number being the index of the process.

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

Regex for numbers only

Use the beginning and end anchors.

Regex regex = new Regex(@"^\d$");

Use "^\d+$" if you need to match more than one digit.


Note that "\d" will match [0-9] and other digit characters like the Eastern Arabic numerals ??????????. Use "^[0-9]+$" to restrict matches to just the Arabic numerals 0 - 9.


If you need to include any numeric representations other than just digits (like decimal values for starters), then see @tchrist's comprehensive guide to parsing numbers with regular expressions.

Create directory if it does not exist

Here's a simple one that worked for me. It checks whether the path exists, and if it doesn't, it will create not only the root path, but all sub-directories also:

$rptpath = "C:\temp\reports\exchange"

if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory}

lodash multi-column sortBy descending

As of lodash 3.5.0 you can use sortByOrder (renamed orderBy in v4.3.0):

var data = _.sortByOrder(array_of_objects, ['type','name'], [true, false]);

Since version 3.10.0 you can even use standard semantics for ordering (asc, desc):

var data = _.sortByOrder(array_of_objects, ['type','name'], ['asc', 'desc']);

In version 4 of lodash this method has been renamed orderBy:

var data = _.orderBy(array_of_objects, ['type','name'], ['asc', 'desc']);

Which Radio button in the group is checked?

You could use LINQ:

var checkedButton = container.Controls.OfType<RadioButton>()
                                      .FirstOrDefault(r => r.Checked);

Note that this requires that all of the radio buttons be directly in the same container (eg, Panel or Form), and that there is only one group in the container. If that is not the case, you could make List<RadioButton>s in your constructor for each group, then write list.FirstOrDefault(r => r.Checked).

Find by key deep in a nested array

Recursion is your friend. I updated the function to account for property arrays:

function getObject(theObject) {
    var result = null;
    if(theObject instanceof Array) {
        for(var i = 0; i < theObject.length; i++) {
            result = getObject(theObject[i]);
            if (result) {
                break;
            }   
        }
    }
    else
    {
        for(var prop in theObject) {
            console.log(prop + ': ' + theObject[prop]);
            if(prop == 'id') {
                if(theObject[prop] == 1) {
                    return theObject;
                }
            }
            if(theObject[prop] instanceof Object || theObject[prop] instanceof Array) {
                result = getObject(theObject[prop]);
                if (result) {
                    break;
                }
            } 
        }
    }
    return result;
}

updated jsFiddle: http://jsfiddle.net/FM3qu/7/

Error in installation a R package

In my case, the installation of nlme package is in trouble:

mv: cannot move '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/nlme' 
to '/home/guanshim/R/x86_64-pc-linux-gnu-library/3.4/00LOCK-nlme/nlme': 
Permission denied

Using Ubuntu 18.04, CTRL+ALT+T to open a terminal window:

sudo R
install.packages('nlme')
q()

How to use Bootstrap in an Angular project?

Provided you use the Angular-CLI to generate new projects, there's another way to make bootstrap accessible in Angular 2/4.

  1. Via command line interface navigate to the project folder. Then use npm to install bootstrap:
    $ npm install --save bootstrap. The --save option will make bootstrap appear in the dependencies.
  2. Edit the .angular-cli.json file, which configures your project. It's inside the project directory. Add a reference to the "styles" array. The reference has to be the relative path to the bootstrap file downloaded with npm. In my case it's: "../node_modules/bootstrap/dist/css/bootstrap.min.css",

My example .angular-cli.json:

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
    "name": "bootstrap-test"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.app.json",
      "testTsconfig": "tsconfig.spec.json",
      "prefix": "app",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.min.css",
        "styles.css"
      ],
      "scripts": [],
      "environmentSource": "environments/environment.ts",
      "environments": {
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
  "e2e": {
    "protractor": {
      "config": "./protractor.conf.js"
    }
  },
  "lint": [
    {
      "project": "src/tsconfig.app.json"
    },
    {
      "project": "src/tsconfig.spec.json"
    },
    {
      "project": "e2e/tsconfig.e2e.json"
    }
  ],
  "test": {
    "karma": {
      "config": "./karma.conf.js"
    }
  },
  "defaults": {
    "styleExt": "css",
    "component": {}
  }
}

Now bootstrap should be part of your default settings.

Screenshot sizes for publishing android app on Google Play

When I publish apps I use the following screenshot sizes:

Phone: 1080 x 1920 I prepare 8 images with title, some fancy background and a screenshot inside a smartphone mockup. So it's more than a simple screenshot. It gives some nice branding and helps you to stand out from other apps out there.

Tablet 7": 1200 x 1920 - I do actually a couple of raw screenshots of 7" emulator so that the user could know how the layout will appear on his device. No fancy design with titles etc.

Tablet 10": 1800 x 2560 - same thing here, just a couple of raw screenshots.

all in .png format. Hope this helps.

TABLOCK vs TABLOCKX

Big difference, TABLOCK will try to grab "shared" locks, and TABLOCKX exclusive locks.

If you are in a transaction and you grab an exclusive lock on a table, EG:

SELECT 1 FROM TABLE WITH (TABLOCKX)

No other processes will be able to grab any locks on the table, meaning all queries attempting to talk to the table will be blocked until the transaction commits.

TABLOCK only grabs a shared lock, shared locks are released after a statement is executed if your transaction isolation is READ COMMITTED (default). If your isolation level is higher, for example: SERIALIZABLE, shared locks are held until the end of a transaction.


Shared locks are, hmmm, shared. Meaning 2 transactions can both read data from the table at the same time if they both hold a S or IS lock on the table (via TABLOCK). However, if transaction A holds a shared lock on a table, transaction B will not be able to grab an exclusive lock until all shared locks are released. Read about which locks are compatible with which at msdn.


Both hints cause the db to bypass taking more granular locks (like row or page level locks). In principle, more granular locks allow you better concurrency. So for example, one transaction could be updating row 100 in your table and another row 1000, at the same time from two transactions (it gets tricky with page locks, but lets skip that).

In general granular locks is what you want, but sometimes you may want to reduce db concurrency to increase performance of a particular operation and eliminate the chance of deadlocks.

In general you would not use TABLOCK or TABLOCKX unless you absolutely needed it for some edge case.

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

Cannot connect to Database server (mysql workbench)

I had a similar issue on Mac OS and I was able to fix it this way:

From the terminal, run:

mysql -u root -p -h 127.0.0.1 -P 3306

Then, I was asked to enter the password. I just pressed enter since no password was setup.

I got a message as follows:

Welcome to the MySQL monitor. Commands end with ; or \g. Your MySQL connection id is 181. Server version: 8.0.11 Homebrew.

If you succeeded to log into mysql>, run the following command:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

You should get a message like this:

Query OK, 0 rows affected (0.19 sec)

Now, your password is "password" and your username is "root".

Happy coding :)

json.dump throwing "TypeError: {...} is not JSON serializable" on seemingly valid object?

In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.

How can I mock requests and the response?

If you want to mock a fake response, another way to do it is to simply instantiate an instance of the base HttpResponse class, like so:

from django.http.response import HttpResponseBase

self.fake_response = HttpResponseBase()

Remove the last line from a file in Bash

awk 'NR>1{print buf}{buf = $0}'

Essentially, this code says the following:

For each line after the first, print the buffered line

for each line, reset the buffer

The buffer is lagged by one line, hence you end up printing lines 1 to n-1

How can I reset or revert a file to a specific revision?

In order to go to a previous commit version of the file, get the commit number, say eb917a1 then

git checkout eb917a1 YourFileName

If you just need to go back to the last commited version

git reset HEAD YourFileName
git checkout YourFileName

This will simply take you to the last committed state of the file

How to insert DECIMAL into MySQL database

Yes, 4,2 means "4 digits total, 2 of which are after the decimal place". That translates to a number in the format of 00.00. Beyond that, you'll have to show us your SQL query. PHP won't translate 3.80 into 99.99 without good reason. Perhaps you've misaligned your fields/values in the query and are trying to insert a larger number that belongs in another field.

'this' is undefined in JavaScript class methods

This question has been answered, but maybe this might someone else coming here.

I also had an issue where this is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:

import MyClass from "./myClass"

// 'this' is not defined here:
const { aMethod } = new MyClass()
aMethod() // error: 'this' is not defined

// So instead, init as you would normally:
const myClass = new MyClass()
myClass.aMethod() // OK

How to use jQuery to select a dropdown option?

if your options have a value, you can do this:

$('select').val("the-value-of-the-option-you-want-to-select");

'select' would be the id of your select or a class selector. or if there is just one select, you can use the tag as it is in the example.

Set a button background image iPhone programmatically

This will work

UIImage *buttonImage = [UIImage imageNamed:@"imageName.png"];
[btn setImage:buttonImage forState:UIControlStateNormal];
[self.view addSubview:btn];

How to execute a Ruby script in Terminal?

Just invoke ruby XXXXX.rb in terminal, if the interpreter is in your $PATH variable.

( this can hardly be a rails thing, until you have it running. )

Prevent Bootstrap Modal from disappearing when clicking outside or pressing escape?

jQuery('#modal_ajax').modal('show', {backdrop: 'static', keyboard: false});

Displaying one div on top of another

Use CSS position: absolute; followed by top: 0px; left 0px; in the style attribute of each DIV. Replace the pixel values with whatever you want.

You can use z-index: x; to set the vertical "order" (which one is "on top"). Replace x with a number, higher numbers are on top of lower numbers.

Here is how your new code would look:

<div>
  <div id="backdrop" style="z-index: 1; position: absolute; top: 0px; left: 0px;"><img alt="" src='/backdrop.png' /></div>
  <div id="curtain" style="z-index: 2; position: absolute; top: 0px; left: 0px; background-image:url(/curtain.png);background-position:100px 200px; height:250px; width:500px;">&nbsp;</div>
</div>

Blue and Purple Default links, how to remove?

<a href="https://www." style="color: inherit;"target="_blank">

For CSS inline style, this worked best for me.

SQL Server Installation - What is the Installation Media Folder?

If you've downloaded SQL from the Microsoft site, rename the file to a zip file and then you can extract the files inside to a folder, then choose that one when you "Browse for SQL server Installation Media"

SQLEXPRADV_x64_ENU.exe > SQLEXPRADV_x64_ENU.zip

7zip will open it (standard Windows zip doesn't work though)

Extract to something like C:\SQLInstallMedia

You will get folders like 1033_enu_lp, resources, x64 and a bunch of files.

How to pass parameters to ThreadStart method in Thread?

Look at this example:

public void RunWorker()
{
    Thread newThread = new Thread(WorkerMethod);
    newThread.Start(new Parameter());
}

public void WorkerMethod(object parameterObj)
{
    var parameter = (Parameter)parameterObj;
    // do your job!
}

You are first creating a thread by passing delegate to worker method and then starts it with a Thread.Start method which takes your object as parameter.

So in your case you should use it like this:

    Thread thread = new Thread(download);
    thread.Start(filename);

But your 'download' method still needs to take object, not string as a parameter. You can cast it to string in your method body.

Setting up MySQL and importing dump within Dockerfile

I used docker-entrypoint-initdb.d approach (Thanks to @Kuhess) But in my case I want to create my DB based on some parameters I defined in .env file so I did these

1) First I define .env file something like this in my docker root project directory

MYSQL_DATABASE=my_db_name
MYSQL_USER=user_test
MYSQL_PASSWORD=test
MYSQL_ROOT_PASSWORD=test
MYSQL_PORT=3306

2) Then I define my docker-compose.yml file. So I used the args directive to define my environment variables and I set them from .env file

version: '2'
services:
### MySQL Container
    mysql:
        build:
            context: ./mysql
            args:
                - MYSQL_DATABASE=${MYSQL_DATABASE}
                - MYSQL_USER=${MYSQL_USER}
                - MYSQL_PASSWORD=${MYSQL_PASSWORD}
                - MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD}
        ports:
            - "${MYSQL_PORT}:3306"

3) Then I define a mysql folder that includes a Dockerfile. So the Dockerfile is this

FROM mysql:5.7
RUN chown -R mysql:root /var/lib/mysql/

ARG MYSQL_DATABASE
ARG MYSQL_USER
ARG MYSQL_PASSWORD
ARG MYSQL_ROOT_PASSWORD

ENV MYSQL_DATABASE=$MYSQL_DATABASE
ENV MYSQL_USER=$MYSQL_USER
ENV MYSQL_PASSWORD=$MYSQL_PASSWORD
ENV MYSQL_ROOT_PASSWORD=$MYSQL_ROOT_PASSWORD

ADD data.sql /etc/mysql/data.sql
RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql
RUN cp /etc/mysql/data.sql /docker-entrypoint-initdb.d

EXPOSE 3306

4) Now I use mysqldump to dump my db and put the data.sql inside mysql folder

mysqldump -h <server name> -u<user> -p <db name> > data.sql

The file is just a normal sql dump file but I add 2 lines at the beginning so the file would look like this

--
-- Create a database using `MYSQL_DATABASE` placeholder
--
CREATE DATABASE IF NOT EXISTS `MYSQL_DATABASE`;
USE `MYSQL_DATABASE`;

-- Rest of queries
DROP TABLE IF EXISTS `x`;
CREATE TABLE `x` (..)
LOCK TABLES `x` WRITE;
INSERT INTO `x` VALUES ...;
...
...
...

So what happening is that I used "RUN sed -i 's/MYSQL_DATABASE/'$MYSQL_DATABASE'/g' /etc/mysql/data.sql" command to replace the MYSQL_DATABASE placeholder with the name of my DB that I have set it in .env file.

|- docker-compose.yml
|- .env
|- mysql
     |- Dockerfile
     |- data.sql

Now you are ready to build and run your container

Replace multiple whitespaces with single whitespace in JavaScript string

How about this one?

"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')

outputs "my test string with crazy stuff is cool "

This one gets rid of any tabs as well

Changing Background Image with CSS3 Animations

The linear timing function will animate the defined properties linearly. For the background-image it seems to have this fade/resize effect while changing the frames of you animation (not sure if it is standard behavior, I would go with @Chukie B's approach).

If you use the steps function, it will animate discretely. See the timing function documentation on MDN for more detail. For you case, do like this:

-webkit-animation-timing-function: steps(1,end);
animation-timing-function: steps(1,end);

See this jsFiddle.

I'm not sure if it is standard behavior either, but when you say that there will be only one step, it allows you to change the starting point in the @keyframes section. This way you can define each frame of you animation.

Django: TemplateSyntaxError: Could not parse the remainder

There should not be a space after name.

Incorrect:

{% url 'author' name = p.article_author.name.username %}

Correct:

{% url 'author' name=p.article_author.name.username %}

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

C++: How to round a double to an int?

add 0.5 before casting (if x > 0) or subtract 0.5 (if x < 0), because the compiler will always truncate.

float x = 55; // stored as 54.999999...
x = x + 0.5 - (x<0); // x is now 55.499999...
int y = (int)x; // truncated to 55

C++11 also introduces std::round, which likely uses a similar logic of adding 0.5 to |x| under the hood (see the link if interested) but is obviously more robust.

A follow up question might be why the float isn't stored as exactly 55. For an explanation, see this stackoverflow answer.

Node.js - get raw request body using Express

This is a variation on hexacyanide's answer above. This middleware also handles the 'data' event but does not wait for the data to be consumed before calling 'next'. This way both this middleware and bodyParser may coexist, consuming the stream in parallel.

app.use(function(req, res, next) {
  req.rawBody = '';
  req.setEncoding('utf8');

  req.on('data', function(chunk) { 
    req.rawBody += chunk;
  });

  next();
});
app.use(express.bodyParser());

CSS media queries for screen sizes

Put it all in one document and use this:

/* Smartphones (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 320px) 
and (max-device-width : 480px) {
  /* Styles */
}

/* Smartphones (landscape) ----------- */
@media only screen 
and (min-width : 321px) {
  /* Styles */
}

/* Smartphones (portrait) ----------- */
@media only screen 
and (max-width : 320px) {
  /* Styles */
}

/* iPads (portrait and landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) {
  /* Styles */
}

/* iPads (landscape) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) {
  /* Styles */
}

/* iPads (portrait) ----------- */
@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) {
  /* Styles */
}

/* Desktops and laptops ----------- */
@media only screen 
and (min-width : 1224px) {
  /* Styles */
}

/* Large screens ----------- */
@media only screen 
and (min-width : 1824px) {
  /* Styles */
}

/* iPhone 4 - 5s ----------- */
@media
only screen and (-webkit-min-device-pixel-ratio : 1.5),
only screen and (min-device-pixel-ratio : 1.5) {
  /* Styles */
}

/* iPhone 6 ----------- */
@media
only screen and (max-device-width: 667px) 
only screen and (-webkit-device-pixel-ratio: 2) {
  /* Styles */
}

/* iPhone 6+ ----------- */
@media
only screen and (min-device-width : 414px) 
only screen and (-webkit-device-pixel-ratio: 3) {
  /*** You've spent way too much on a phone ***/
}

/* Samsung Galaxy S7 Edge ----------- */
@media only screen
and (-webkit-min-device-pixel-ratio: 3),
and (min-resolution: 192dpi)and (max-width:640px) {
 /* Styles */
}

Source: http://css-tricks.com/snippets/css/media-queries-for-standard-devices/

At this point, I would definitely consider using em values instead of pixels. For more information, check this post: https://zellwk.com/blog/media-query-units/.

How to generate a create table script for an existing table in phpmyadmin?

  1. SHOW CREATE TABLE your_table_name => Press GO button

After show table, above the table ( +options ) Hyperlink is there.

  1. Press (+options) Hyperlink then appear some options select (Full texts) => Press GO button.

Installing a specific version of angular with angular cli

use the following command to install the specific version. say you want to install angular/cli version 1.6.8 then enter the following command :

sudo npm install -g @angular/[email protected]

this will install angular/cli version 1.6.8

Decimal precision and scale in EF Code First

You can always tell EF to do this with conventions in the Context class in the OnModelCreating function as follows:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    // <... other configurations ...>
    // modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
    // modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();
    // modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();

    // Configure Decimal to always have a precision of 18 and a scale of 4
    modelBuilder.Conventions.Remove<DecimalPropertyConvention>();
    modelBuilder.Conventions.Add(new DecimalPropertyConvention(18, 4));

    base.OnModelCreating(modelBuilder);
}

This only applies to Code First EF fyi and applies to all decimal types mapped to the db.

How to use shell commands in Makefile

With:

FILES = $(shell ls)

indented underneath all like that, it's a build command. So this expands $(shell ls), then tries to run the command FILES ....

If FILES is supposed to be a make variable, these variables need to be assigned outside the recipe portion, e.g.:

FILES = $(shell ls)
all:
        echo $(FILES)

Of course, that means that FILES will be set to "output from ls" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ... to avoid this, for efficiency and/or correctness.1)

If FILES is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:

all:
        FILES="$(shell ls)"

However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:

        FILES="$(shell ls)"; echo $$FILES

This is all a bit silly since the shell will expand * (and other shell glob expressions) for you in the first place, so you can just:

        echo *

as your shell command.

Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls is not completely reliable (some details depend on file names and sometimes even the version of ls; some versions of ls attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard) and $(subst ...) to accomplish everything inside make itself (avoiding any "weird characters in file name" issues). (In sh scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0 to avoid tripping over blanks, newlines, control characters, and so on.)


1The GNU Make documentation notes further that POSIX make added ::= assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make variants support ::= assignment, although GNU make does today, with the same meaning as :=, i.e., do the assignment right now with expansion.

Note that VAR := $(shell command args...) can also be spelled VAR != command args... in several make variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell) so using VAR != command args... is superior in both being shorter and working in more variants.

Locate the nginx.conf file my nginx is actually using

% ps -o args -C nginx
COMMAND
build/sbin/nginx -c ../test.conf

If nginx was run without the -c option, then you can use the -V option to find out the configure arguments that were set to non-standard values. Among them the most interesting for you are:

--prefix=PATH                      set installation prefix
--sbin-path=PATH                   set nginx binary pathname
--conf-path=PATH                   set nginx.conf pathname

PNG transparency issue in IE8

My scenario:

  • I had a background image that had a 24bit alpha png that was set to an anchor link.
  • The anchor was being faded in on hover using Jquery.

eg.

a.button { background-image: url(this.png; }

I found that applying the mark-up provided by Dan Tello didn't work.

However, by placing a span within the anchor element, and setting the background-image to that element I was able to achieve a good result using Dan Tello's markup.

eg.

a.button span { background-image: url(this.png; }

Why am I getting "IndentationError: expected an indented block"?

You might want to check you spaces and tabs. A tab is a default of 4 spaces. However, your "if" and "elif" match, so I am not quite sure why. Go into Options in the top bar, and click "Configure IDLE". Check the Indentation Width on the right in Fonts/Tabs, and make sure your indents have that many spaces.

How to format dateTime in django template?

{{ wpis.entry.lastChangeDate|date:"SHORT_DATETIME_FORMAT" }}

String compare in Perl with "eq" vs "=="

First, eq is for comparing strings; == is for comparing numbers.

Even if the "if" condition is satisfied, it doesn't evaluate the "then" block.

I think your problem is that your variables don't contain what you think they do. I think your $str1 or $str2 contains something like "taste\n" or so. Check them by printing before your if: print "str1='$str1'\n";.

The trailing newline can be removed with the chomp($str1); function.

Can "list_display" in a Django ModelAdmin display attributes of ForeignKey fields?

Despite all the great answers above and due to me being new to Django, I was still stuck. Here's my explanation from a very newbie perspective.

models.py

class Author(models.Model):
    name = models.CharField(max_length=255)

class Book(models.Model):
    author = models.ForeignKey(Author)
    title = models.CharField(max_length=255)

admin.py (Incorrect Way) - you think it would work by using 'model__field' to reference, but it doesn't

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'author__name', ]

admin.site.register(Book, BookAdmin)

admin.py (Correct Way) - this is how you reference a foreign key name the Django way

class BookAdmin(admin.ModelAdmin):
    model = Book
    list_display = ['title', 'get_name', ]

    def get_name(self, obj):
        return obj.author.name
    get_name.admin_order_field  = 'author'  #Allows column order sorting
    get_name.short_description = 'Author Name'  #Renames column head

    #Filtering on side - for some reason, this works
    #list_filter = ['title', 'author__name']

admin.site.register(Book, BookAdmin)

For additional reference, see the Django model link here

How to easily initialize a list of Tuples?

c# 7.0 lets you do this:

  var tupleList = new List<(int, string)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

If you don't need a List, but just an array, you can do:

  var tupleList = new(int, string)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

And if you don't like "Item1" and "Item2", you can do:

  var tupleList = new List<(int Index, string Name)>
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

or for an array:

  var tupleList = new (int Index, string Name)[]
  {
      (1, "cow"),
      (5, "chickens"),
      (1, "airplane")
  };

which lets you do: tupleList[0].Index and tupleList[0].Name

Framework 4.6.2 and below

You must install System.ValueTuple from the Nuget Package Manager.

Framework 4.7 and above

It is built into the framework. Do not install System.ValueTuple. In fact, remove it and delete it from the bin directory.

note: In real life, I wouldn't be able to choose between cow, chickens or airplane. I would be really torn.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

How to name and retrieve a stash by name in git?

So, I'm not sure why there's so much consternation on this topic. I can name a git stash with both a push and the deprecated save, and I can use a regex to pull it back with an apply:

Git stash method to use a name to apply

$ git stash push -m "john-hancock"

$ git stash apply stash^{/john-hancock}

As it has been mentioned before, the save command is deprecated, but it still works, so you can used this on older systems where you can't update them with a push call. Unlike the push command, the -m switch isn't required with save.

// save is deprecated but still functional  
$ git stash save john-hancock

This is Git 2.2 and Windows 10.

Visual Proof

Here's a beautiful animated GIF demonstrating the process.

Animated GIF showing a git stash apply using an identifiable name.

Sequence of events

The GIF runs quickly, but if you look, the process is this:

  1. The ls command shows 4 files in the directory
  2. touch example.html adds a 5th file
  3. git stash push -m "john-hancock" -a (The -a includes untracked files)
  4. The ls command shows 4 files after the stash, meaning the stash and the implicit hard reset worked
  5. git stash apply stash^{/john-hancock} runs
  6. The ls command lists 5 files, showing the example.html file was brought back, meaning the git stash apply command worked.

Does this even make sense?

To be frank, I'm not sure what the benefit of this approach is though. There's value in giving the stash a name, but not the retrieval. Maybe to script the shelve and unshelve process it'd be helpful, but it's still way easier to just pop a stash by name.

$ git stash pop 3
$ git stash apply 3

That looks way easier to me than the regex.

Python Git Module experiences?

The git interaction library part of StGit is actually pretty good. However, it isn't broken out as a separate package but if there is sufficient interest, I'm sure that can be fixed.

It has very nice abstractions for representing commits, trees etc, and for creating new commits and trees.

How to switch to new window in Selenium for Python?

window_handles should give you the references to all open windows.

this is what the docu has to say about switching windows.

NSNotificationCenter addObserver in Swift

NSNotificationCenter add observer syntax in Swift 4.0 for iOS 11

  NotificationCenter.default.addObserver(self, selector: #selector(keyboardShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)

This is for keyboardWillShow notification name type. Other type can be selected from the available option

the Selector is of type @objc func which handle how the keyboard will show ( this is your user function )

Scrolling an iframe with JavaScript?

I've also had trouble using any type of javascript "scrollTo" function in an iframe on an iPad. Finally found an "old" solution to the problem, just hash to an anchor.

In my situation after an ajax return my error messages were set to display at the top of the iframe but if the user had scrolled down in what is an admittedly long form the submission goes out and the error appears "above the fold". Additionally, assuming the user did scroll way down the top level page was scrolled away from 0,0 and was also hidden.

I added

<a name="ptop"></a>

to the top of my iframe document and

<a name="atop"></a>

to the top of my top level page

then

    $(document).ready(function(){
      $("form").bind("ajax:complete",
        function() {
          location.hash = "#";
          top.location.hash = "#";
          setTimeout('location.hash="#ptop"',150);
          setTimeout('top.location.hash="#atop"',350);
        }
      )
    });

in the iframe.

You have to hash the iframe before the top page or only the iframe will scroll and the top will remain hidden but while it's a tiny bit "jumpy" due to the timeout intervals it works. I imagine tags throughout would allow various "scrollTo" points.

Selenium and xPath - locating a link by containing text

@FindBy(xpath = "//span[@class='y2' and contains(text(), 'Your Text')] ") 
private WebElementFacade emailLinkToVerifyAccount;

This approach will work for you, hopefully.

Android - How to achieve setOnClickListener in Kotlin?

findViewById<Button>(R.id.signUp)?.setOnClickListener(
    Toast.makeText(mActivity, "Button Clicked", Toast.LENGTH_LONG).show()
)

Change CSS properties on click

With jquery you can do it like:

$('img').click(function(){
    $('#foo').css('background-color', 'red').css('color', 'white');
});

this applies for all img tags you should set an id attribute for it like image and then:

$('#image').click(function(){
    $('#foo').css('background-color', 'red').css('color', 'white');
});

php - push array into array - key issue

Don't use array_values on your $row

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       array_push($res_arr_values, $row);
   }

Also, the preferred way to add a value to an array is writing $array[] = $value;, not using array_push

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
   {
       $res_arr_values[] = $row;
   }

And a further optimization is not to call mysql_fetch_array($result, MYSQL_ASSOC) but to use mysql_fetch_assoc($result) directly.

$res_arr_values = array();
while ($row = mysql_fetch_assoc($result))
   {
       $res_arr_values[] = $row;
   }

Why number 9 in kill -9 command in unix?

There were 8 other signals they came up with first.

Can a Byte[] Array be written to a file in C#?

Based on the first sentence of the question: "I'm trying to write out a Byte[] array representing a complete file to a file."

The path of least resistance would be:

File.WriteAllBytes(string path, byte[] bytes)

Documented here:

System.IO.File.WriteAllBytes - MSDN

ThreadStart with parameters

class Program
{
    static void Main(string[] args)
    {
        Thread t = new Thread(new ParameterizedThreadStart(ThreadMethod));

        t.Start("My Parameter");
    }

    static void ThreadMethod(object parameter)
    {
        // parameter equals to "My Parameter"
    }
}

GridView Hide Column by code

There is a small change to happen, it will not come under rowdatabound, first all the rows should get bound, only then could we hide that. So it will be a separate method after the grid is dataBound.

How often should Oracle database statistics be run?

Make sure to balance the risk that fresh statistics cause undesirable changes to query plans against the risk that stale statistics can themselves cause query plans to change.

Imagine you have a bug database with a table ISSUE and a column CREATE_DATE where the values in the column increase more or less monotonically. Now, assume that there is a histogram on this column that tells Oracle that the values for this column are uniformly distributed between January 1, 2008 and September 17, 2008. This makes it possible for the optimizer to reasonably estimate the number of rows that would be returned if you were looking for all issues created last week (i.e. September 7 - 13). If the application continues to be used and the statistics are never updated, though, this histogram will be less and less accurate. So the optimizer will expect queries for "issues created last week" to be less and less accurate over time and may eventually cause Oracle to change the query plan negatively.

How to draw lines in Java

You can use the getGraphics method of the component on which you would like to draw. This in turn should allow you to draw lines and make other things which are available through the Graphics class

Use css gradient over background image

The accepted answer works well. Just for completeness (and since I like it's shortness), I wanted to share how to to it with compass (SCSS/SASS):

body{
  $colorStart: rgba(0,0,0,0);
  $colorEnd: rgba(0,0,0,0.8);
  @include background-image(linear-gradient(to bottom, $colorStart, $colorEnd), url("bg.jpg"));
}