Programs & Examples On #Mod fastcgi

nginx: connect() failed (111: Connection refused) while connecting to upstream

I had the same problem when I wrote two upstreams in NGINX conf

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
    server 127.0.0.1:9000;
}

...

fastcgi_pass php_upstream;

but in /etc/php/7.3/fpm/pool.d/www.conf I listened the socket only

listen = /var/run/php/my.site.sock

So I need just socket, no any 127.0.0.1:9000, and I just removed IP+port upstream

upstream php_upstream {
    server unix:/var/run/php/my.site.sock;
}

This could be rewritten without an upstream

fastcgi_pass unix:/var/run/php/my.site.sock;

What is the difference between fastcgi and fpm?

Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable

whereas

PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments

However, there are pros and cons to both and one should choose as per their specific use case.

I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.

Multiple files upload (Array) with CodeIgniter 2.0

I have used below code in my custom library
call that from my controller like below,

function __construct() {<br />
   &nbsp;&nbsp;&nbsp; parent::__construct();<br />
   &nbsp;&nbsp;&nbsp;   $this->load->library('CommonMethods');<br />
}<br />

$config = array();<br />
$config['upload_path'] = 'assets/upload/images/';<br />
$config['allowed_types'] = 'gif|jpg|png|jpeg';<br />
$config['max_width'] = 150;<br />
$config['max_height'] = 150;<br />
$config['encrypt_name'] = TRUE;<br />
$config['overwrite'] = FALSE;<br />

// upload multiplefiles<br />
$fileUploadResponse = $this->commonmethods->do_upload_multiple_files('profile_picture', $config);

/**
 * do_upload_multiple_files - Multiple Methods
 * @param type $fieldName
 * @param type $options
 * @return type
 */
public function do_upload_multiple_files($fieldName, $options) {

    $response = array();
    $files = $_FILES;
    $cpt = count($_FILES[$fieldName]['name']);
    for($i=0; $i<$cpt; $i++)
    {           
        $_FILES[$fieldName]['name']= $files[$fieldName]['name'][$i];
        $_FILES[$fieldName]['type']= $files[$fieldName]['type'][$i];
        $_FILES[$fieldName]['tmp_name']= $files[$fieldName]['tmp_name'][$i];
        $_FILES[$fieldName]['error']= $files[$fieldName]['error'][$i];
        $_FILES[$fieldName]['size']= $files[$fieldName]['size'][$i];    

        $this->CI->load->library('upload');
        $this->CI->upload->initialize($options);

        //upload the image
        if (!$this->CI->upload->do_upload($fieldName)) {
            $response['erros'][] = $this->CI->upload->display_errors();
        } else {
            $response['result'][] = $this->CI->upload->data();
        }
    }

    return $response;
}

Making RGB color in Xcode

Objective-C

You have to give the values between 0 and 1.0. So divide the RGB values by 255.

myLabel.textColor= [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1] ;

Update:

You can also use this macro

#define Rgb2UIColor(r, g, b)  [UIColor colorWithRed:((r) / 255.0) green:((g) / 255.0) blue:((b) / 255.0) alpha:1.0]

and you can call in any of your class like this

 myLabel.textColor = Rgb2UIColor(160, 97, 5);

Swift

This is the normal color synax

myLabel.textColor = UIColor(red: (160/255.0), green: (97/255.0), blue: (5/255.0), alpha: 1.0) 
//The values should be between 0 to 1

Swift is not much friendly with macros

Complex macros are used in C and Objective-C but have no counterpart in Swift. Complex macros are macros that do not define constants, including parenthesized, function-like macros. You use complex macros in C and Objective-C to avoid type-checking constraints or to avoid retyping large amounts of boilerplate code. However, macros can make debugging and refactoring difficult. In Swift, you can use functions and generics to achieve the same results without any compromises. Therefore, the complex macros that are in C and Objective-C source files are not made available to your Swift code.

So we use extension for this

extension UIColor {
    convenience init(_ r: Double,_ g: Double,_ b: Double,_ a: Double) {
        self.init(red: r/255, green: g/255, blue: b/255, alpha: a)
    }
}

You can use it like

myLabel.textColor = UIColor(160.0, 97.0, 5.0, 1.0)

Python: What OS am I running on?

I am using the WLST tool that comes with weblogic, and it doesn't implement the platform package.

wls:/offline> import os
wls:/offline> print os.name
java 
wls:/offline> import sys
wls:/offline> print sys.platform
'java1.5.0_11'

Apart from patching the system javaos.py (issue with os.system() on windows 2003 with jdk1.5) (which I can't do, I have to use weblogic out of the box), this is what I use:

def iswindows():
  os = java.lang.System.getProperty( "os.name" )
  return "win" in os.lower()

How to play .wav files with java

A class that will play a WAV file, blocking until the sound has finished playing:

class Sound implements Playable {

    private final Path wavPath;
    private final CyclicBarrier barrier = new CyclicBarrier(2);

    Sound(final Path wavPath) {

        this.wavPath = wavPath;
    }

    @Override
    public void play() throws LineUnavailableException, IOException, UnsupportedAudioFileException {

        try (final AudioInputStream audioIn = AudioSystem.getAudioInputStream(wavPath.toFile());
             final Clip clip = AudioSystem.getClip()) {

            listenForEndOf(clip);
            clip.open(audioIn);
            clip.start();
            waitForSoundEnd();
        }
    }

    private void listenForEndOf(final Clip clip) {

        clip.addLineListener(event -> {
            if (event.getType() == LineEvent.Type.STOP) waitOnBarrier();
        });
    }

    private void waitOnBarrier() {

        try {

            barrier.await();
        } catch (final InterruptedException ignored) {
        } catch (final BrokenBarrierException e) {

            throw new RuntimeException(e);
        }
    }

    private void waitForSoundEnd() {

        waitOnBarrier();
    }
}

how to create dynamic two dimensional array in java?

How about making a custom class containing an array, and use the array of your custom class.

Reorder / reset auto increment primary key

You could drop the primary key column and re-create it. All the ids should then be reassigned in order.

However this is probably a bad idea in most situations. If you have other tables that have foreign keys to this table then it will definitely not work.

How to get input text value from inside td

Maybe this will help.

var inputVal = $(this).closest('tr').find("td:eq(x) input").val();

What is the maximum length of a table name in Oracle?

Oracle database object names maximum length is 30 bytes.

Object Name Rules: http://docs.oracle.com/database/121/SQLRF/sql_elements008.htm

What does void* mean and how to use it?

Using a void * means that the function can take a pointer that doesn't need to be a specific type. For example, in socket functions, you have

send(void * pData, int nLength)

this means you can call it in many ways, for example

char * data = "blah";
send(data, strlen(data));

POINT p;
p.x = 1;
p.y = 2;
send(&p, sizeof(POINT));

The container 'Maven Dependencies' references non existing library - STS

I finally found my maven repo mirror is down. I changed to another one, problem solved.

How do I center list items inside a UL element?

I have run into this issue before and found that sometimes padding is the issue.

By removing padding from the ul, any li's set to inline-block will be nicely centred:

_x000D_
_x000D_
* {_x000D_
 box-sizing: border-box;_x000D_
}_x000D_
_x000D_
ul {_x000D_
 width: 120px;_x000D_
 margin: auto;_x000D_
 text-align: center;_x000D_
 border: 1px solid black;_x000D_
}_x000D_
_x000D_
li {_x000D_
 display: inline-block;_x000D_
}_x000D_
_x000D_
ul.no_pad {_x000D_
 padding: 0;_x000D_
}_x000D_
_x000D_
p {_x000D_
 margin: auto;_x000D_
 text-align: center;_x000D_
}_x000D_
_x000D_
.break {_x000D_
 margin: 50px 10px;_x000D_
}
_x000D_
<div>  _x000D_
  <p>With Padding (Default Style)</p>_x000D_
            <ul class="with_pad">_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
            </ul>_x000D_
  <div class="break"></div>_x000D_
  <p>No Padding (Padding: 0)</p>_x000D_
   <ul class="no_pad">_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
                <li>x</li>_x000D_
            </ul>_x000D_
 <div>
_x000D_
_x000D_
_x000D_

Hope that helps anyone running into this same issue :)

Cheers,

Jake

using facebook sdk in Android studio

Facebook has indeed added the SDK to the Maven Central repositories. To configure your project using the maven repo's instance, you'll need to do 2 things:

  1. In your projects top-level build.gradle file, add the Maven Central repositories. Mine looks like this:

    repositories {
        jcenter()       // This is the default repo
        mavenCentral()  //  This is the Maven Central repo
    }
    
  2. In the app-level build.grade file, add the Facebook sdk dependency:

    dependencies {
    
        compile 'com.facebook.android:facebook-android-sdk:4.5.0' // Adjust the version accordingly
        // All your other dependencies.
    }
    

You can also adjust the specific Facebook SDK version as well. For a list of available versions in the maven repository click this link.

How can I pass command-line arguments to a Perl program?

You pass them in just like you're thinking, and in your script, you get them from the array @ARGV. Like so:

my $numArgs = $#ARGV + 1;
print "thanks, you gave me $numArgs command-line arguments.\n";

foreach my $argnum (0 .. $#ARGV) {

   print "$ARGV[$argnum]\n";

}

From here.

SVN Error - Not a working copy

I just got "not a working copy", and for me the reason was the Automouter on Unix. Just a fresh "cd /path/to/work/directory" did the trick.

Conversion failed when converting the varchar value 'simple, ' to data type int

Given that you're only converting to ints to then perform a comparison, I'd just switch the table definition around to using varchar also:

Create table #myTempTable
(
num varchar(12)
)
insert into #myTempTable (num) values (1),(2),(3),(4),(5)

and remove all of the attempted CONVERTs from the rest of the query.

 SELECT a.name, a.value AS value, COUNT(*) AS pocet   
 FROM 
 (SELECT item.name, value.value 
  FROM mdl_feedback AS feedback 
  INNER JOIN mdl_feedback_item AS item 
       ON feedback.id = item.feedback
  INNER JOIN mdl_feedback_value AS value 
       ON item.id = value.item 
   WHERE item.typ = 'multichoicerated' AND item.feedback IN (43)
 ) AS a 
 INNER JOIN #myTempTable 
     on a.value = #myTempTable.num
 GROUP BY a.name, a.value ORDER BY a.name

How to set different colors in HTML in one statement?

Use the span tag

<style>
    .redText
    {
        color:red;
    }
    .blackText
    {
        color:black;
        font-weight:bold;
    }
</style>

<span class="redText">My Name is:</span>&nbsp;<span class="blackText">Tintincute</span>

It's also a good idea to avoid inline styling. Use a custom CSS class instead.

stringstream, string, and char* conversion confusion

In this line:

const char* cstr2 = ss.str().c_str();

ss.str() will make a copy of the contents of the stringstream. When you call c_str() on the same line, you'll be referencing legitimate data, but after that line the string will be destroyed, leaving your char* to point to unowned memory.

Excel VBA Macro: User Defined Type Not Defined

I am late for the party. Try replacing as below, mine worked perfectly- "DOMDocument" to "MSXML2.DOMDocument60" "XMLHTTP" to "MSXML2.XMLHTTP60"

how to evenly distribute elements in a div next to each other?

Make all spans used inline-block elements. Create an empty stretch span with a 100% width beneath the list of spans containing the menu items. Next make the div containing the spans text-align: justified. This would then force the inline-block elements [your menu items] to evenly distribute.

https://jsfiddle.net/freedawirl/bh0eadzz/3/

  <div id="container">

          <div class="social">
            <a href="#" target="_blank" aria-label="facebook-link">
            <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="twitter-link">
                <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="youtube-link">
                <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="pinterest-link">
                 <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="snapchat-link">
                <img src="http://placehold.it/40x40">
            </a>
            <a href="#" target="_blank" aria-label="blog-link">
                 <img src="http://placehold.it/40x40">
            </a>

            <a href="#" aria-label="phone-link">
                 <img src="http://placehold.it/40x40">
            </a>
            <span class="stretch"></span>
          </div>
             </div>

How to move div vertically down using CSS

if div.title is a div then put this:

left: 0;
bottom: 0;

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

Another "Up Tick" for AR..., but if you don't have to use interop I would avoid it altogether. This product is actually quite interesting: http://www.clearoffice.com/ and it provides a very intuitive, fully managed, api for manipulation excel files and seems to be free. (at least for the time being) SpreadSheetGear is also excellent but pricey.

my two cents.

multi line comment vb.net in Visual studio 2010

The only way is to highlight the lines to comment and press

ctrl + k, ctrl + c

or after highlighted press the toolbar option to comment out the selected lines.

The icons look like this enter image description here

Member '<method>' cannot be accessed with an instance reference

This causes the error:

MyClass aCoolObj = new MyClass();
aCoolObj.MyCoolStaticMethod();

This is the fix:

MyClass.MyCoolStaticMethod();

Explanation:

You can't call a static method from an instance of an object. The whole point of static methods is to not be tied to instances of objects, but instead to persist through all instances of that object, and/or to be used without any instances of the object.

How can I write data attributes using Angular?

Use attribute binding syntax instead

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    [attr.data-sectionvalue]="section.value">{{ section.text }}</li>  
</ol>

or

<ol class="viewer-nav"><li *ngFor="let section of sections" 
    attr.data-sectionvalue="{{section.value}}">{{ section.text }}</li>  
</ol>

See also :

Select * from subquery

You can select every column from that sub-query by aliasing it and adding the alias before the *:

SELECT t.*, a+b AS total_sum
FROM
(
   SELECT SUM(column1) AS a, SUM(column2) AS b
   FROM table
) t

Round double value to 2 decimal places

For Swift there is a simple solution if you can't either import Foundation, use round() and/or does not want a String (usually the case when you're in Playground):

var number = 31.726354765
var intNumber = Int(number * 1000.0)
var roundedNumber = Double(intNumber) / 1000.0

result: 31.726

Difference between spring @Controller and @RestController annotation

  • @Controller is used to mark classes as Spring MVC Controller.
  • @RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations (see: Javadoc)

So the following two controller definitions should do the same

@Controller
@ResponseBody
public class MyController { }

@RestController
public class MyRestController { }

How to get the full URL of a Drupal page?

Try the following:

url($_GET['q'], array('absolute' => true));

Get Date in YYYYMMDD format in windows batch file

If, after reading the other questions and viewing the links mentioned in the comment sections, you still can't figure it out, read on.

First of all, where you're going wrong is the offset.

It should look more like this...

set mydate=%date:~10,4%%date:~6,2%/%date:~4,2%
echo %mydate%

If the date was Tue 12/02/2013 then it would display it as 2013/02/12.

To remove the slashes, the code would look more like

set mydate=%date:~10,4%%date:~7,2%%date:~4,2%
echo %mydate%

which would output 20130212

And a hint for doing it in the future, if mydate equals something like %date:~10,4%%date:~7,2% or the like, you probably forgot a tilde (~).

how do I join two lists using linq or lambda expressions

 public class State
        {
            public int SID { get; set; }
            public string SName { get; set; }
            public string SCode { get; set; }
            public string SAbbrevation { get; set; }
        }

        public class Country
        {
            public int CID { get; set; }
            public string CName { get; set; }
            public string CAbbrevation { get; set; }
        }


 List<State> states = new List<State>()
            {
               new  State{  SID=1,SName="Telangana",SCode="+91",SAbbrevation="TG"},
               new  State{  SID=2,SName="Texas",SCode="512",SAbbrevation="TS"},
            };

            List<Country> coutries = new List<Country>()
            {
               new Country{CID=1,CName="India",CAbbrevation="IND"},
               new Country{CID=2,CName="US of America",CAbbrevation="USA"},
            };

            var res = coutries.Join(states, a => a.CID, b => b.SID, (a, b) => new {a.CName,b.SName}).ToList();

What is output buffering?

I know that this is an old question but I wanted to write my answer for visual learners. I couldn't find any diagrams explaining output buffering on the worldwide-web so I made a diagram myself in Windows mspaint.exe.

If output buffering is turned off, then echo will send data immediately to the Browser.

enter image description here

If output buffering is turned on, then an echo will send data to the output buffer before sending it to the Browser.

enter image description here

phpinfo

To see whether Output buffering is turned on / off please refer to phpinfo at the core section. The output_buffering directive will tell you if Output buffering is on/off.

enter image description here In this case the output_buffering value is 4096 which means that the buffer size is 4 KB. It also means that Output buffering is turned on, on the Web server.

php.ini

It's possible to turn on/off and change buffer size by changing the value of the output_buffering directive. Just find it in php.ini, change it to the setting of your choice, and restart the Web server. You can find a sample of my php.ini below.

; Output buffering is a mechanism for controlling how much output data
; (excluding headers and cookies) PHP should keep internally before pushing that
; data to the client. If your application's output exceeds this setting, PHP
; will send that data in chunks of roughly the size you specify.
; Turning on this setting and managing its maximum buffer size can yield some
; interesting side-effects depending on your application and web server.
; You may be able to send headers and cookies after you've already sent output
; through print or echo. You also may see performance benefits if your server is
; emitting less packets due to buffered output versus PHP streaming the output
; as it gets it. On production servers, 4096 bytes is a good setting for performance
; reasons.
; Note: Output buffering can also be controlled via Output Buffering Control
;   functions.
; Possible Values:
;   On = Enabled and buffer is unlimited. (Use with caution)
;   Off = Disabled
;   Integer = Enables the buffer and sets its maximum size in bytes.
; Note: This directive is hardcoded to Off for the CLI SAPI
; Default Value: Off
; Development Value: 4096
; Production Value: 4096
; http://php.net/output-buffering
output_buffering = 4096

The directive output_buffering is not the only configurable directive regarding Output buffering. You can find other configurable Output buffering directives here: http://php.net/manual/en/outcontrol.configuration.php

Example: ob_get_clean()

Below you can see how to capture an echo and manipulate it before sending it to the browser.

// Turn on output buffering  
ob_start();  

echo 'Hello World';  // save to output buffer

$output = ob_get_clean();  // Get content from the output buffer, and discard the output buffer ...
$output = strtoupper($output); // manipulate the output  

echo $output;  // send to output stream / Browser

// OUTPUT:  
HELLO WORLD

Examples: Hackingwithphp.com

More info about Output buffer with examples can be found here:

http://www.hackingwithphp.com/13/0/0/output-buffering

ES6 Class Multiple inheritance

Justin Fagnani describes a very clean (imho) way to compose multiple classes into one using the fact that in ES2015, classes can be created with class expressions.

Expressions vs declarations

Basically, just like you can create a function with an expression:

function myFunction() {}      // function declaration
var myFunction = function(){} // function expression

you can do the same with classes:

class MyClass {}             // class declaration
var MyClass = class {}       // class expression

The expression is evaluated at runtime, when the code executes, whereas a declaration is executed beforehand.

Using class expressions to create mixins

You can use this to create a function that dynamically creates a class only when the function is called:

function createClassExtending(superclass) {
  return class AwesomeClass extends superclass {
    // you class body here as usual
  }
}

The cool thing about it is that you can define the whole class beforehand and only decide on which class it should extend by the time you call the function:

class A {}
class B {}
var ExtendingA = createClassExtending(A)
var ExtendingB = createClassExtending(B)

If you want to mix multiple classes together, because ES6 classes only support single inheritance, you need to create a chain of classes that contains all the classes you want to mix together. So let's say you want to create a class C that extends both A and B, you could do this:

class A {}
class B extends A {}
class C extends B {}  // C extends both A and B

The problem with this is that it's very static. If you later decide you want to make a class D that extends B but not A, you have a problem.

But with some smart trickery using the fact that classes can be expressions, you can solve this by creating A and B not directly as classes, but as class factories (using arrow functions for brevity):

class Base {} // some base class to keep the arrow functions simple
var A = (superclass) => class A extends superclass
var B = (superclass) => class B extends superclass
var C = B(A(Base))
var D = B(Base)

Notice how we only decide at the last moment which classes to include in the hierarchy.

Count Rows in Doctrine QueryBuilder

To count items after some number of items (offset), $qb->setFirstResults() cannot be applied in this case, as it works not as a condition of query, but as an offset of query result for a range of items selected (i. e. setFirstResult cannot be used togather with COUNT at all). So to count items, which are left I simply did the following:

   //in repository class:
   $count = $qb->select('count(p.id)')
      ->from('Products', 'p')
      ->getQuery()
      ->getSingleScalarResult();

    return $count;

    //in controller class:
    $count = $this->em->getRepository('RepositoryBundle')->...

    return $count-$offset;

Anybody knows more clean way to do it?

How to fix/convert space indentation in Sublime Text?

You have to add this code to your custom key bindings:

{ "keys": ["ctrl+f12"], "command": "set_setting", "args": {"setting": "tab_size", "value": 4} }

by pressing ctrl+f12, it will reindent your file to a tab size of 4. if you want a different tab size, you just change the "value" number. Te format is a simple json.

Split string into individual words Java

To include any separators between words (like everything except all lower case and upper case letters), we can do:

String mystring = "hi, there,hi Leo";
String[] arr = mystring.split("[^a-zA-Z]+");
for(int i = 0; i < arr.length; i += 1)
{
     System.out.println(arr[i]);
}

Here the regex means that the separators will be anything that is not a upper or lower case letter [^a-zA-Z], in groups of at least one [+].

Ternary operator in PowerShell

I too, looked for a better answer, and while the solution in Edward's post is "ok", I came up with a far more natural solution in this blog post

Short and sweet:

# ---------------------------------------------------------------------------
# Name:   Invoke-Assignment
# Alias:  =
# Author: Garrett Serack (@FearTheCowboy)
# Desc:   Enables expressions like the C# operators: 
#         Ternary: 
#             <condition> ? <trueresult> : <falseresult> 
#             e.g. 
#                status = (age > 50) ? "old" : "young";
#         Null-Coalescing 
#             <value> ?? <value-if-value-is-null>
#             e.g.
#                name = GetName() ?? "No Name";
#             
# Ternary Usage:  
#         $status == ($age > 50) ? "old" : "young"
#
# Null Coalescing Usage:
#         $name = (get-name) ? "No Name" 
# ---------------------------------------------------------------------------

# returns the evaluated value of the parameter passed in, 
# executing it, if it is a scriptblock   
function eval($item) {
    if( $item -ne $null ) {
        if( $item -is "ScriptBlock" ) {
            return & $item
        }
        return $item
    }
    return $null
}

# an extended assignment function; implements logic for Ternarys and Null-Coalescing expressions
function Invoke-Assignment {
    if( $args ) {
        # ternary
        if ($p = [array]::IndexOf($args,'?' )+1) {
            if (eval($args[0])) {
                return eval($args[$p])
            } 
            return eval($args[([array]::IndexOf($args,':',$p))+1]) 
        }

        # null-coalescing
        if ($p = ([array]::IndexOf($args,'??',$p)+1)) {
            if ($result = eval($args[0])) {
                return $result
            } 
            return eval($args[$p])
        } 

        # neither ternary or null-coalescing, just a value  
        return eval($args[0])
    }
    return $null
}

# alias the function to the equals sign (which doesn't impede the normal use of = )
set-alias = Invoke-Assignment -Option AllScope -Description "FearTheCowboy's Invoke-Assignment."

Which makes it easy to do stuff like (more examples in blog post):

$message == ($age > 50) ? "Old Man" :"Young Dude" 

How to convert a GUID to a string in C#?

you are missing () on the end of ToString.

What is “the inverse side of the association” in a bidirectional JPA OneToMany/ManyToOne association?

To understand this, you must take a step back. In OO, the customer owns the orders (orders are a list in the customer object). There can't be an order without a customer. So the customer seems to be the owner of the orders.

But in the SQL world, one item will actually contain a pointer to the other. Since there is 1 customer for N orders, each order contains a foreign key to the customer it belongs to. This is the "connection" and this means the order "owns" (or literally contains) the connection (information). This is exactly the opposite from the OO/model world.

This may help to understand:

public class Customer {
     // This field doesn't exist in the database
     // It is simulated with a SQL query
     // "OO speak": Customer owns the orders
     private List<Order> orders;
}

public class Order {
     // This field actually exists in the DB
     // In a purely OO model, we could omit it
     // "DB speak": Order contains a foreign key to customer
     private Customer customer;
}

The inverse side is the OO "owner" of the object, in this case the customer. The customer has no columns in the table to store the orders, so you must tell it where in the order table it can save this data (which happens via mappedBy).

Another common example are trees with nodes which can be both parents and children. In this case, the two fields are used in one class:

public class Node {
    // Again, this is managed by Hibernate.
    // There is no matching column in the database.
    @OneToMany(cascade = CascadeType.ALL) // mappedBy is only necessary when there are two fields with the type "Node"
    private List<Node> children;

    // This field exists in the database.
    // For the OO model, it's not really necessary and in fact
    // some XML implementations omit it to save memory.
    // Of course, that limits your options to navigate the tree.
    @ManyToOne
    private Node parent;
}

This explains for the "foreign key" many-to-one design works. There is a second approach which uses another table to maintain the relations. That means, for our first example, you have three tables: The one with customers, the one with orders and a two-column table with pairs of primary keys (customerPK, orderPK).

This approach is more flexible than the one above (it can easily handle one-to-one, many-to-one, one-to-many and even many-to-many). The price is that

  • it's a bit slower (having to maintain another table and joins uses three tables instead of just two),
  • the join syntax is more complex (which can be tedious if you have to manually write many queries, for example when you try to debug something)
  • it's more error prone because you can suddenly get too many or too few results when something goes wrong in the code which manages the connection table.

That's why I rarely recommend this approach.

How do you execute SQL from within a bash script?

I'm slightly confused. You should be able to call sqlplus from within the bash script. This may be what you were doing with your first statement

Try Executing the following within your bash script:

#!/bin/bash          
echo Start Executing SQL commands
sqlplus <user>/<password> @file-with-sql-1.sql
sqlplus <user>/<password> @file-with-sql-2.sql

If you want to be able to pass data into your scripts you can do it via SQLPlus by passing arguments into the script:

Contents of file-with-sql-1.sql

 select * from users where username='&1';

Then change the bash script to call sqlplus passing in the value

#!/bin/bash

MY_USER=bob
sqlplus <user>/<password> @file-with-sql-1.sql $MY_USER

Insert/Update/Delete with function in SQL Server

You can't update tables from a function like you would a stored procedure, but you CAN update table variables.

So for example, you can't do this in your function:

create table MyTable
(
    ID int,
    column1 varchar(100)
)
update [MyTable]
set column1='My value'

but you can do:

declare @myTable table
(
    ID int,
    column1 varchar(100)
)

Update @myTable
set column1='My value'

How to dynamically allocate memory space for a string and get that string from user?

Below is the code for creating dynamic string :

void main()
{
  char *str, c;
  int i = 0, j = 1;

  str = (char*)malloc(sizeof(char));

  printf("Enter String : ");

  while (c != '\n') {
    // read the input from keyboard standard input
    c = getc(stdin);

    // re-allocate (resize) memory for character read to be stored
    str = (char*)realloc(str, j * sizeof(char));

    // store read character by making pointer point to c
    str[i] = c;

    i++;
    j++;
  }

  str[i] = '\0'; // at the end append null character to mark end of string

  printf("\nThe entered string is : %s", str);

  free(str); // important step the pointer declared must be made free
}

Android - Start service on boot

I've had success without the full package, do you know where the call chain is getting interrupted? If you debug with Log()'s, at what point does it no longer work?

I think it may be in your IntentService, this all looks fine.

How to list AD group membership for AD users using input list?

Get-ADPrincipalGroupMembership username | select name

Got it from another answer but the script works magic. :)

How to force a WPF binding to refresh?

I was fetching data from backend and updated the screen with just one line of code. It worked. Not sure, why we need to implement Interface. (windows 10, UWP)

    private void populateInCurrentScreen()
    {
        (this.FindName("Dets") as Grid).Visibility = Visibility.Visible;
        this.Bindings.Update();
    }

iPhone is not available. Please reconnect the device

If you are on iOS 13.5 and Xcode 11.5, removing the device and adding it again fixed it for me.

Invisible characters - ASCII

Other answers are correct -- whether a character is invisible or not depends on what font you use. This seems to be a pretty good list to me of characters that are truly invisible (not even space). It contains some chars that the other lists are missing.

            '\u2060', // Word Joiner
            '\u2061', // FUNCTION APPLICATION
            '\u2062', // INVISIBLE TIMES
            '\u2063', // INVISIBLE SEPARATOR
            '\u2064', // INVISIBLE PLUS
            '\u2066', // LEFT - TO - RIGHT ISOLATE
            '\u2067', // RIGHT - TO - LEFT ISOLATE
            '\u2068', // FIRST STRONG ISOLATE
            '\u2069', // POP DIRECTIONAL ISOLATE
            '\u206A', // INHIBIT SYMMETRIC SWAPPING
            '\u206B', // ACTIVATE SYMMETRIC SWAPPING
            '\u206C', // INHIBIT ARABIC FORM SHAPING
            '\u206D', // ACTIVATE ARABIC FORM SHAPING
            '\u206E', // NATIONAL DIGIT SHAPES
            '\u206F', // NOMINAL DIGIT SHAPES
            '\u200B', // Zero-Width Space
            '\u200C', // Zero Width Non-Joiner
            '\u200D', // Zero Width Joiner
            '\u200E', // Left-To-Right Mark
            '\u200F', // Right-To-Left Mark
            '\u061C', // Arabic Letter Mark
            '\uFEFF', // Byte Order Mark
            '\u180E', // Mongolian Vowel Separator
            '\u00AD'  // soft-hyphen

Using npm behind corporate proxy .pac

Adding the lines below in the .typingsrc file helped me.

{
    "rejectUnauthorized": false,
    "registryURL" :"http://api.typings.org/"
 }

PHP Composer behind http proxy

iconoclast's answer did not work for me.

I upgraded my php from 5.3.* (xampp 1.7.4) to 5.5.* (xampp 1.8.3) and the problem was solved.

Try iconoclast's answer first, if it doesn't work then upgrading might solve the problem.

How to make a simple image upload using Javascript/HTML

<li class="list-group-item active"><h5>Feaured Image</h5></li>
            <li class="list-group-item">
                <div class="input-group mb-3">
                    <div class="custom-file ">
                        <input type="file"  class="custom-file-input" name="thumbnail" id="thumbnail">
                        <label class="custom-file-label" for="thumbnail">Choose file</label>
                    </div>
                </div>
                <div class="img-thumbnail  text-center">
                    <img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
                </div>
            </li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
    var file = $(this).get(0).files;
    var reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.addEventListener("load", function(e) {
    var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>

Django 1.7 - makemigrations not detecting changes

Following worked for me:

  1. Add the app name to settings.py
  2. use 'python manage.py makemigrations'
  3. use 'python manage.py migrate'

Worked for me: Python 3.4, Django 1.10

get all the images from a folder in php

you can do it simply with PHP opendir function.

example:

$handle = opendir(dirname(realpath(__FILE__)).'/pictures/');
while($file = readdir($handle)){
  if($file !== '.' && $file !== '..'){
    echo '<img src="pictures/'.$file.'" border="0" />';
  }
}

MVC 3: How to render a view without its layout page when loaded via ajax?

You don't have to create an empty view for this.

In the controller:

if (Request.IsAjaxRequest())
  return PartialView();
else
  return View();

returning a PartialViewResult will override the layout definition when rendering the respons.

MySQL - Operand should contain 1 column(s)

COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by,
    users.id AS posted_by_id
    FROM users
    WHERE users.id = posts.posted_by)

Well, you can’t get multiple columns from one subquery like that. Luckily, the second column is already posts.posted_by! So:

SELECT
topics.id,
topics.name,
topics.post_count,
topics.view_count,
posts.posted_by
COUNT( posts.solved_post ) AS solved_post,
(SELECT users.username AS posted_by_username
    FROM users
    WHERE users.id = posts.posted_by)
...

Draw a line in a div

_x000D_
_x000D_
$('.line').click(function() {_x000D_
  $(this).toggleClass('red');_x000D_
});
_x000D_
.line {_x000D_
  border: 0;_x000D_
  background-color: #000;_x000D_
  height: 3px;_x000D_
  cursor: pointer;_x000D_
}_x000D_
.red {_x000D_
  background-color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<hr class="line"></hr>_x000D_
<p>click the line</p>
_x000D_
_x000D_
_x000D_

Split by comma and strip whitespace in Python

re (as in regular expressions) allows splitting on multiple characters at once:

$ string = "blah, lots  ,  of ,  spaces, here "
$ re.split(', ',string)
['blah', 'lots  ', ' of ', ' spaces', 'here ']

This doesn't work well for your example string, but works nicely for a comma-space separated list. For your example string, you can combine the re.split power to split on regex patterns to get a "split-on-this-or-that" effect.

$ re.split('[, ]',string)
['blah',
 '',
 'lots',
 '',
 '',
 '',
 '',
 'of',
 '',
 '',
 '',
 'spaces',
 '',
 'here',
 '']

Unfortunately, that's ugly, but a filter will do the trick:

$ filter(None, re.split('[, ]',string))
['blah', 'lots', 'of', 'spaces', 'here']

Voila!

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

How to send POST in angularjs with multiple params?

Here is the direct solution:

// POST api/<controller>
[HttpPost, Route("postproducts/{product1}/{product2}")]
public void PostProducts([FromUri]Product product, Product product2)
{
    Product productOne = product; 
    Product productTwo = product2; 
}

$scope.url = 'http://localhost:53263/api/Products/' +
                 $scope.product + '/' + $scope.product2
$http.post($scope.url)
    .success(function(response) {
        alert("success") 
    })
    .error(function() { alert("fail") });
};

If you are sane you do this:

var $scope.products.product1 = product1;
var $scope.products.product2 = product2;

And then send products in the body (like a balla).

C# testing to see if a string is an integer?

private bool isNumber(object p_Value)
    {
        try
        {
            if (int.Parse(p_Value.ToString()).GetType().Equals(typeof(int)))
                return true;
            else
                return false;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

Something I wrote a while back. Some good examples above but just my 2 cents worth.

How to Delete Session Cookie?

There are known issues with IE and Opera not removing session cookies when setting the expire date to the past (which is what the jQuery cookie plugin does)

This works fine in Safari and Mozilla/FireFox.

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

open program minimized via command prompt

Try:

start  "" "C:\Program Files (x86)\Microsoft Office\Office12\WINWORD.EXE" --new-window/min

I had the same problem, but I was trying to open chrome.exe maximized. If I put the /min anywhere else in the command line, like before or after the empty title, it was ignored.

How to increase dbms_output buffer?

When buffer size gets full. There are several options you can try:

1) Increase the size of the DBMS_OUTPUT buffer to 1,000,000

2) Try filtering the data written to the buffer - possibly there is a loop that writes to DBMS_OUTPUT and you do not need this data.

3) Call ENABLE at various checkpoints within your code. Each call will clear the buffer.

DBMS_OUTPUT.ENABLE(NULL) will default to 20000 for backwards compatibility Oracle documentation on dbms_output

You can also create your custom output display.something like below snippets

create or replace procedure cust_output(input_string in varchar2 )
is 

   out_string_in long default in_string; 
   string_lenth number; 
   loop_count number default 0; 

begin 

   str_len := length(out_string_in);

   while loop_count < str_len
   loop 
      dbms_output.put_line( substr( out_string_in, loop_count +1, 255 ) ); 
      loop_count := loop_count +255; 
   end loop; 
end;

Link -Ref :Alternative to dbms_output.putline @ By: Alexander

Regex for string not ending with given suffix

The question is old but I could not find a better solution I post mine here. Find all USB drives but not listing the partitions, thus removing the "part[0-9]" from the results. I ended up doing two grep, the last negates the result:

ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -vE "part[0-9]*$"

This results on my system:

pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0

If I only want the partitions I could do:

ls -1 /dev/disk/by-path/* | grep -P "\-usb\-" | grep -E "part[0-9]*$"

Where I get:

pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part1
pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0-part2

And when I do:

readlink -f /dev/disk/by-path/pci-0000:00:0b.0-usb-0:1:1.0-scsi-0:0:0:0

I get:

/dev/sdb

Do Swift-based applications work on OS X 10.9/iOS 7 and lower?

When it comes to Swift Frameworks. As for today, with Xcode version 6.1.1 (6A2008a), if the Swift framework is targeted to iOS 7.1, linker report warning

ld: warning: embedded dylibs/frameworks only run on iOS 8 or later.

and application can't be submitted to AppStore. Check this issue : Lint to prevent dynamic libraries and frameworks from passing with iOS 7

Capture Signature using HTML5 and iPad

The options already listed are very good, however here a few more on this topic that I've researched and came across.

1) http://perfectionkills.com/exploring-canvas-drawing-techniques/
2) http://mcc.id.au/2010/signature.html
3) https://zipso.net/a-simple-touchscreen-sketchpad-using-javascript-and-html5/

And as always you may want to save the canvas to image:
http://www.html5canvastutorials.com/advanced/html5-canvas-save-drawing-as-an-image/

good luck and happy signing

JOIN two SELECT statement results

SELECT t1.ks, t1.[# Tasks], COALESCE(t2.[# Late], 0) AS [# Late]
FROM 
    (SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1
LEFT JOIN
    (SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON (t1.ks = t2.ks);

regular expression for DOT

[+*?.] Most special characters have no meaning inside the square brackets. This expression matches any of +, *, ? or the dot.

Why does CSS not support negative padding?

This could help, by the way:

The box-sizing CSS property is used to alter the default CSS box model used to calculate widths and heights of elements.

http://www.w3.org/TR/css3-ui/#box-sizing
https://developer.mozilla.org/En/CSS/Box-sizing

Merging dictionaries in C#

The party's pretty much dead now, but here's an "improved" version of user166390 that made its way into my extension library. Apart from some details, I added a delegate to calculate the merged value.

/// <summary>
/// Merges a dictionary against an array of other dictionaries.
/// </summary>
/// <typeparam name="TResult">The type of the resulting dictionary.</typeparam>
/// <typeparam name="TKey">The type of the key in the resulting dictionary.</typeparam>
/// <typeparam name="TValue">The type of the value in the resulting dictionary.</typeparam>
/// <param name="source">The source dictionary.</param>
/// <param name="mergeBehavior">A delegate returning the merged value. (Parameters in order: The current key, The current value, The previous value)</param>
/// <param name="mergers">Dictionaries to merge against.</param>
/// <returns>The merged dictionary.</returns>
public static TResult MergeLeft<TResult, TKey, TValue>(
    this TResult source,
    Func<TKey, TValue, TValue, TValue> mergeBehavior,
    params IDictionary<TKey, TValue>[] mergers)
    where TResult : IDictionary<TKey, TValue>, new()
{
    var result = new TResult();
    var sources = new List<IDictionary<TKey, TValue>> { source }
        .Concat(mergers);

    foreach (var kv in sources.SelectMany(src => src))
    {
        TValue previousValue;
        result.TryGetValue(kv.Key, out previousValue);
        result[kv.Key] = mergeBehavior(kv.Key, kv.Value, previousValue);
    }

    return result;
}

Pro JavaScript programmer interview questions (with answers)

Basic JS programmming

  • Scope of variable
  • What is Associative Array? How do we use it?

OOPS JS

  • Difference between Classic Inheritance and Prototypical Inheritance
  • What is difference between private variable, public variable and static variable? How we achieve this in JS?
  • How to add/remove properties to object in run time?
  • How to achieve inheritance ?
  • How to extend built-in objects?
  • Why extending array is bad idea?

DOM and JS

  • Difference between browser detection and feature detection
  • DOM Event Propagation
  • Event Delegation
  • Event bubbling V/s Event Capturing

Misc

  • Graceful Degradation V/s Progressive Enhancement

Create hive table using "as select" or "like" and also specify delimiter

Both the answers provided above work fine.

  1. CREATE TABLE person AS select * from employee;
  2. CREATE TABLE person LIKE employee;

How to use a RELATIVE path with AuthUserFile in htaccess?

For just in case people are looking for solution for this:

<If "req('Host') = 'www.example.com'">
    Authtype Basic
    AuthName "user and password"
    AuthUserFile /var/www/www.example.com/.htpasswd
    Require valid-user
</If>

Pointers, smart pointers or shared pointers?

To add a small bit to Sydius' answer, smart pointers will often provide a more stable solution by catching many easy to make errors. Raw pointers will have some perfromance advantages and can be more flexible in certain circumstances. You may also be forced to use raw pointers when linking into certain 3rd party libraries.

Android Studio - Importing external Library/Jar

Here is how I got it going specifically for the admob sdk jar file:

  1. Drag your jar file into the libs folder.
  2. Right click on the jar file and select Add Library now the jar file is a library lets add it to the compile path
  3. Open the build.gradle file (note there are two build.gradle files at least, don't use the root one use the one in your project scope).
  4. Find the dependencies section (for me i was trying to the admob -GoogleAdMobAdsSdk jar file) e.g.

    dependencies {
       compile files('libs/android-support-v4.jar','libs/GoogleAdMobAdsSdk-6.3.1.jar')
    }
    
  5. Last go into settings.gradle and ensure it looks something like this:

    include ':yourproject', ':yourproject:libs:GoogleAdMobAdsSdk-6.3.1'
    
  6. Finally, Go to Build -> Rebuild Project

CSS Float: Floating an image to the left of the text

Check out this sample: http://jsfiddle.net/Epgvc/1/

I just floated the title to the left and added a clear:both div to the bottom..

Enabling HTTPS on express.js

This is how its working for me. The redirection used will redirect all the normal http as well.

const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const http = require('http');
const app = express();
var request = require('request');
//For https
const https = require('https');
var fs = require('fs');
var options = {
  key: fs.readFileSync('certificates/private.key'),
  cert: fs.readFileSync('certificates/certificate.crt'),
  ca: fs.readFileSync('certificates/ca_bundle.crt')
};

// API file for interacting with MongoDB
const api = require('./server/routes/api');

// Parsers
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

// Angular DIST output folder
app.use(express.static(path.join(__dirname, 'dist')));

// API location
app.use('/api', api);

// Send all other requests to the Angular app
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist/index.html'));
});
app.use(function(req,resp,next){
  if (req.headers['x-forwarded-proto'] == 'http') {
      return resp.redirect(301, 'https://' + req.headers.host + '/');
  } else {
      return next();
  }
});


http.createServer(app).listen(80)
https.createServer(options, app).listen(443);

What is the difference between match_parent and fill_parent?

FILL_PARENT is deprecated from the API level 8 and higher and it is renamed for the upper versions as MATCH_PARENT

Both are same FILL_PARENT and MATCH_PARENT,FILL_PARENT was used in the lower version less than API level 8 and MATCH_PATENT are used in higher API level greater than 8.

FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)

fill_parent: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by match_parent.

For more details please visit this page

Calling javascript function in iframe

objectframe.contentWindow.Reset() you need reference to the top level element in the frame first.

Laravel Mail::send() sending to multiple to or bcc addresses

With Laravel 5.6, if you want pass multiple emails with names, you need to pass array of associative arrays. Example pushing multiple recipients into the $to array:

$to[] = array('email' => $email, 'name' => $name);

Fixed two recipients:

$to = [['email' => '[email protected]', 'name' => 'User One'], 
       ['email' => '[email protected]', 'name' => 'User Two']];

The 'name' key is not mandatory. You can set it to 'name' => NULL or do not add to the associative array, then only 'email' will be used.

List directory in Go

Even simpler, use path/filepath:

package main    

import (
    "fmt"
    "log"
    "path/filepath"
)

func main() {
    files, err := filepath.Glob("*")
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(files) // contains a list of all files in the current directory
}

PHP Change Array Keys

You could create a new array containing that array, so:

<?php
$array = array();
$array['name'] = $oldArray;
?>

.do extension in web pages?

".do" is the "standard" extension mapped to for Struts Java platform. See http://struts.apache.org/ .

Docker build gives "unable to prepare context: context must be a directory: /Users/tempUser/git/docker/Dockerfile"

It's simple, whenever Docker build is run, docker wants to know, what's the image name, so we need to pass -t : . Now make sure you are in the same directory where you have your Dockerfile and run

docker build -t <image_name>:<version> . Example docker build -t my_apache:latest . assuming you are in the same directory as your Dockerfile otherwise pass -f flag and the Dockerfile.

docker build -t my_apache:latest -f ~/Users/documents/myapache/Dockerfile

Pythonic way to find maximum value and its index in a list?

This answer is 33 times faster than @Escualo assuming that the list is very large, and assuming that it's already an np.array(). I had to turn down the number of test runs because the test is looking at 10000000 elements not just 100.

import random
from datetime import datetime
import operator
import numpy as np

def explicit(l):
    max_val = max(l)
    max_idx = l.index(max_val)
    return max_idx, max_val

def implicit(l):
    max_idx, max_val = max(enumerate(l), key=operator.itemgetter(1))
    return max_idx, max_val

def npmax(l):
    max_idx = np.argmax(l)
    max_val = l[max_idx]
    return (max_idx, max_val)

if __name__ == "__main__":
    from timeit import Timer

t = Timer("npmax(l)", "from __main__ import explicit, implicit, npmax; "
      "import random; import operator; import numpy as np;"
      "l = np.array([random.random() for _ in xrange(10000000)])")
print "Npmax: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("explicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Explicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

t = Timer("implicit(l)", "from __main__ import explicit, implicit; "
      "import random; import operator;"
      "l = [random.random() for _ in xrange(10000000)]")
print "Implicit: %.2f msec/pass" % (1000  * t.timeit(number=10)/10 )

Results on my computer:

Npmax: 8.78 msec/pass
Explicit: 290.01 msec/pass
Implicit: 790.27 msec/pass

Integer to IP Address - C

Here's a simple method to do it: The (ip >> 8), (ip >> 16) and (ip >> 24) moves the 2nd, 3rd and 4th bytes into the lower order byte, while the & 0xFF isolates the least significant byte at each step.

void print_ip(unsigned int ip)
{
    unsigned char bytes[4];
    bytes[0] = ip & 0xFF;
    bytes[1] = (ip >> 8) & 0xFF;
    bytes[2] = (ip >> 16) & 0xFF;
    bytes[3] = (ip >> 24) & 0xFF;   
    printf("%d.%d.%d.%d\n", bytes[3], bytes[2], bytes[1], bytes[0]);        
}

There is an implied bytes[0] = (ip >> 0) & 0xFF; at the first step.

Use snprintf() to print it to a string.

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

how to convert numeric to nvarchar in sql command

select convert(nvarchar(255), 4343)

Should do the trick.

Generating a random & unique 8 character string using MySQL

To create a random 10 digit alphanumeric, excluding lookalike chars 01oOlI:

LPAD(LEFT(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(TO_BASE64(UNHEX(MD5(RAND()))), "/", ""), "+", ""), "=", ""), "O", ""), "l", ""), "I", ""), "1", ""), "0", ""), "o", ""), 10), 10, 0)

This is exactly what I needed to create a voucher code. Confusing characters are removed to reduce errors when typing it into a voucher code form.

Hopes this helps somebody, based on Jan Uhlig's brilliant answer.

Please see Jan's answer for a breakdown on how this code works.

How to get exact browser name and version?

Use 51Degrees.com device detection solution to detect browser name, vendor and version.

First, follow the 4-step guide to incorporate device detector in to your project. When I say incorporate I mean download archive with PHP code and database file, extract them and include 2 files. That's all there is to do to incorporate.

Once that's done you can use the following properties to get browser information:
$_51d['BrowserName'] - Gives you the name of the browser (Safari, Molto, Motorola, MStarBrowser etc).
$_51d['BrowserVendor'] - Gives you the company who created browser.
$_51d['BrowserVersion'] - Version number of the browser

How to catch an Exception from a thread

Exception handling in Thread : By default run() method doesn’t throw any exception, so all checked exceptions inside the run method has to be caught and handled there only and for runtime exceptions we can use UncaughtExceptionHandler. UncaughtExceptionHandler is an interface provided by Java to handle exceptions in a Thread run method. So we can implement this interface and set back our implementing class back to Thread object using setUncaughtExceptionHandler() method. But this handler has to be set before we call start() on the tread.

if we don’t set uncaughtExceptionHandler then the Threads ThreadGroup acts as a handler.

 public class FirstThread extends Thread {

int count = 0;

@Override
public void run() {
    while (true) {
        System.out.println("FirstThread doing something urgent, count : "
                + (count++));
        throw new RuntimeException();
    }

}

public static void main(String[] args) {
    FirstThread t1 = new FirstThread();
    t1.setUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            System.out.printf("Exception thrown by %s with id : %d",
                    t.getName(), t.getId());
            System.out.println("\n"+e.getClass());
        }
    });
    t1.start();
}
}

Nice explanation given at http://coder2design.com/thread-creation/#exceptions

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

jQuery counting elements by class - what is the best way to implement this?

Getting a count of the number of elements that refer to the same class is as simple as this

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
        <script type="text/javascript">

            $(document).ready(function() {
                alert( $(".red").length );
            });

        </script>
    </head>
    <body>

        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
        <p class="red">Test</p>
        <p class="red">Test</p>
        <p class="red anotherclass">Test</p>
    </body>
</html>

Docker is in volume in use, but there aren't any Docker containers

Perhaps the volume was created via docker-compose? If so, it should get removed by:

docker-compose down --volumes

Credit to Niels Bech Nielsen!

Query an XDocument for elements by name at any depth

(Code and Instructions is for C# and may need to be slightly altered for other languages)

This example works perfect if you want to read from a Parent Node that has many children, for example look at the following XML;

<?xml version="1.0" encoding="UTF-8"?> 
<emails>
    <emailAddress>[email protected]</emailAddress>
    <emailAddress>[email protected]</emailAddress>
    <emailAddress>rgreen@set_ig.ca</emailAddress> 
</emails>

Now with this code below (keeping in mind that the XML File is stored in resources (See the links at end of snippet for help on resources) You can obtain each email address within the "emails" tag.

XDocument doc = XDocument.Parse(Properties.Resources.EmailAddresses);

var emailAddresses = (from emails in doc.Descendants("emailAddress")
                      select emails.Value);

foreach (var email in emailAddresses)
{
    //Comment out if using WPF or Windows Form project
    Console.WriteLine(email.ToString());

   //Remove comment if using WPF or Windows Form project
   //MessageBox.Show(email.ToString());
}

Results

  1. [email protected]
  2. [email protected]
  3. rgreen@set_ig.ca

Note: For Console Application and WPF or Windows Forms you must add the "using System.Xml.Linq;" Using directive at the top of your project, for Console you will also need to add a reference to this namespace before adding the Using directive. Also for Console there will be no Resource file by default under the "Properties folder" so you have to manually add the Resource file. The MSDN articles below, explain this in detail.

Adding and Editing Resources

How to: Add or Remove Resources

How do I search for names with apostrophe in SQL Server?

select * from Header where userID like '%''%'

Hope this helps.

How do I get the last character of a string using an Excel function?

Looks like the answer above was a little incomplete try the following:-

=RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))

Obviously, this is for cell A2...

What this does is uses a combination of Right and Len - Len is the length of a string and in this case, we want to remove all but one from that... clearly, if you wanted the last two characters you'd change the -1 to -2 etc etc etc.

After the length has been determined and the portion of that which is required - then the Right command will display the information you need.

This works well combined with an IF statement - I use this to find out if the last character of a string of text is a specific character and remove it if it is. See, the example below for stripping out commas from the end of a text string...

=IF(RIGHT(A2,(LEN(A2)-(LEN(A2)-1)))=",",LEFT(A2,(LEN(A2)-1)),A2)

How to access to a child method from the parent in vue.js

Parent-Child communication in VueJS

Given a root Vue instance is accessible by all descendants via this.$root, a parent component can access child components via the this.$children array, and a child component can access it's parent via this.$parent, your first instinct might be to access these components directly.

The VueJS documentation warns against this specifically for two very good reasons:

  • It tightly couples the parent to the child (and vice versa)
  • You can't rely on the parent's state, given that it can be modified by a child component.

The solution is to use Vue's custom event interface

The event interface implemented by Vue allows you to communicate up and down the component tree. Leveraging the custom event interface gives you access to four methods:

  1. $on() - allows you to declare a listener on your Vue instance with which to listen to events
  2. $emit() - allows you to trigger events on the same instance (self)

Example using $on() and $emit():

_x000D_
_x000D_
const events = new Vue({}),_x000D_
    parentComponent = new Vue({_x000D_
      el: '#parent',_x000D_
      ready() {_x000D_
        events.$on('eventGreet', () => {_x000D_
          this.parentMsg = `I heard the greeting event from Child component ${++this.counter} times..`;_x000D_
        });_x000D_
      },_x000D_
      data: {_x000D_
        parentMsg: 'I am listening for an event..',_x000D_
        counter: 0_x000D_
      }_x000D_
    }),_x000D_
    childComponent = new Vue({_x000D_
      el: '#child',_x000D_
      methods: {_x000D_
      greet: function () {_x000D_
        events.$emit('eventGreet');_x000D_
        this.childMsg = `I am firing greeting event ${++this.counter} times..`;_x000D_
      }_x000D_
    },_x000D_
    data: {_x000D_
      childMsg: 'I am getting ready to fire an event.',_x000D_
      counter: 0_x000D_
    }_x000D_
  });
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.28/vue.min.js"></script>_x000D_
_x000D_
<div id="parent">_x000D_
  <h2>Parent Component</h2>_x000D_
  <p>{{parentMsg}}</p>_x000D_
</div>_x000D_
_x000D_
<div id="child">_x000D_
  <h2>Child Component</h2>_x000D_
  <p>{{childMsg}}</p>_x000D_
  <button v-on:click="greet">Greet</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Answer taken from the original post: Communicating between components in VueJS

How to print a linebreak in a python function?

\n is an escape sequence, denoted by the backslash. A normal forward slash, such as /n will not do the job. In your code you are using /n instead of \n.

Android: android.content.res.Resources$NotFoundException: String resource ID #0x5

Another scenario that can cause this exception is with DataBinding, that is when you use something like this in your layout

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android">

    <data>

        <variable
            name="model"
            type="point.to.your.model"/>
    </data>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:text="@{model.someIntegerVariable}"/>

</layout>

Notice that the variable I'm using is an Integer and I'm assigning it to the text field of the TextView. Since the TextView already has a method with signature of setText(int) it will use this method instead of using the setText(String) and cast the value. Thus the TextView thinks of your input number as a resource value which obviously is not valid.

Solution is to cast your int value to string like this

android:text="@{String.valueOf(model.someIntegerVariable)}"

How to install toolbox for MATLAB

first, you need to find the toolbox that you need. There are many people developing 3rd party toolboxes for Matlab, so there isn't just one single place where you can find "the image processing toolbox". That said, a good place to start looking is the Matlab Central which is a Mathworks-run site for exchanging all kinds of Matlab-related material.

Once you find a toolbox you want, it will be in some compressed format, and its developers might have a "readme" file that details on how to install it. If it isn't the case, a generic way to attempt installation is to place the toolbox in any directory on your drive, and then add it to Matlab path, e.g., going to File -> Set Path... -> Add Folder or Add with Subfolders (I'm writing for memory but this is definitely close).

Otherwise, you can extract all .m files in your working directory, if you don't want to use downloaded toolbox in more than one project.

Display date in dd/mm/yyyy format in vb.net

Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")

Check link below

how to modify an existing check constraint?

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

Combine two columns and add into one new column

Did you check the string concatenation function? Something like:

update table_c set column_a = column_b || column_c 

should work. More here

How do I select a sibling element using jQuery?

jQuery provides a method called "siblings()" which helps us to return all sibling elements of the selected element. For example, if you want to apply CSS to the sibling selectors, you can use this method. Below is an example which illustrates this. You can try this example and play with it to learn how it works.

$("p").siblings("h4").css({"color": "red", "border": "2px solid red"});

What does $1 [QSA,L] mean in my .htaccess file?

Not the place to give a complete tutorial, but here it is in short;

RewriteCond basically means "execute the next RewriteRule only if this is true". The !-l path is the condition that the request is not for a link (! means not, -l means link)

The RewriteRule basically means that if the request is done that matches ^(.+)$ (matches any URL except the server root), it will be rewritten as index.php?url=$1 which means a request for ollewill be rewritten as index.php?url=olle).

QSA means that if there's a query string passed with the original URL, it will be appended to the rewrite (olle?p=1 will be rewritten as index.php?url=olle&p=1.

L means if the rule matches, don't process any more RewriteRules below this one.

For more complete info on this, follow the links above. The rewrite support can be a bit hard to grasp, but there are quite a few examples on stackoverflow to learn from.

label or @html.Label ASP.net MVC 4

In the case of your label snippet, it doesn't really matter. I would go for the simpler syntax (plain HTML).

Most helper methods also don't allow you to surround another element. This can be a consideration when choosing to use/not use one.

Strongly-Typed Equivalents

However, it's worth noting that what you use the @Html.[Element]For<T>() methods that you gain important features. Note the "For" at the end of the method name.

Example:

@Html.TextBoxFor( o => o.FirstName )

This will handle ID/Name creation based on object hierarchy (which is critical for model binding). It will also add unobtrusive validation attributes. These methods take an Expression as an argument which refers to a property within the model. The metadata of this property is obtained by the MVC framework, and as such it "knows" more about the property than its string-argument counterpart.

It also allows you to deal with UI code in a strongly-typed fashion. Visual Studio will highlight syntax errors, whereas it cannot do so with a string. Views can also be optionally compiled along with the solution, allowing for additional compile-time checks.

Other Considerations

Occasionally a HTML helper method will also perform additional tasks which are useful, such as Html.Checkbox and Html.CheckboxFor which also create a hidden field to go along with the checkbox. Another example are the URL-related methods (such as for a hyperlink) which are route-aware.

<!-- bad -->
<a href="/foo/bar/123">my link</a>

<!-- good -->
@Html.ActionLink( "my link", "foo", "bar", new{ id=123 } )

<!-- also fine (perhaps you want to wrap something with the anchor) -->
<a href="@Url.Action( "foo", "bar", new{ id=123 } )"><span>my link</span></a>

There is a slight performance benefit to using plain HTML versus code which must be executed whenever the view is rendered, although this should not be the deciding factor.

Difference between Mutable objects and Immutable objects

Mutable objects have fields that can be changed, immutable objects have no fields that can be changed after the object is created.

A very simple immutable object is a object without any field. (For example a simple Comparator Implementation).

class Mutable{
  private int value;

  public Mutable(int value) {
     this.value = value;
  }

  //getter and setter for value
}

class Immutable {
  private final int value;

  public Immutable(int value) {
     this.value = value;
  }

  //only getter
}

What's the difference between all the Selection Segues?

For those who prefer a bit more practical learning, select the segue in dock, open the attribute inspector and switch between different kinds of segues (dropdown "Kind"). This will reveal options specific for each of them: for example you can see that "present modally" allows you to choose a transition type etc.

jQuery post() with serialize and extra data

$.ajax({    
    type: 'POST',  
    url: 'test.php',  
    data:$("#Test-form").serialize(),  
    dataType:'json',
     beforeSend:function(xhr, settings){
     settings.data += '&moreinfo=MoreData';
     },
    success:function(data){
            //  json response  
    },
    error: function(data) { 
        // if error occured
    }
    });

How to create an email form that can send email using html

Html by itself will not send email. You will need something that connects to a SMTP server to send an email. Hence Outlook pops up with mailto: else your form goes to the server which has a script that sends email.

Binding ng-model inside ng-repeat loop in AngularJS

For each iteration of the ng-repeat loop, line is a reference to an object in your array. Therefore, to preview the value, use {{line.text}}.

Similarly, to databind to the text, databind to the same: ng-model="line.text". You don't need to use value when using ng-model (actually you shouldn't).

Fiddle.

For a more in-depth look at scopes and ng-repeat, see What are the nuances of scope prototypal / prototypical inheritance in AngularJS?, section ng-repeat.

CSS: how to add white space before element's content?

Since you are looking for adding space between elements you may need something as simple as a margin-left or padding-left. Here are examples of both http://jsfiddle.net/BGHqn/3/

This will add 10 pixels to the left of the paragraph element

p {
    margin-left: 10px;
 }

or if you just want some padding within your paragraph element

p {
    padding-left: 10px;
}

Why aren't programs written in Assembly more often?

Assembly is not portable between different microprocessors.

Return array from function

Your BlockID function uses the undefined variable images, which will lead to an error. Also, you should not use an Array here - JavaScripts key-value-maps are plain objects:

function BlockID() {
    return {
        "s": "Images/Block_01.png",
        "g": "Images/Block_02.png",
        "C": "Images/Block_03.png",
        "d": "Images/Block_04.png"
    };
}

How to set the max size of upload file

For Spring Boot 2.+, make sure you are using spring.servlet instead of spring.http.

---
spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB

If you have to use tomcat, you might end up creating EmbeddedServletContainerCustomizer, which is not really nice thing to do.

If you can live without tomat, you could replace tomcat with e.g. undertow and avoid this issue at all.

How to go to a specific element on page?

If the element is currently not visible on the page, you can use the native scrollIntoView() method.

$('#div_' + element_id)[0].scrollIntoView( true );

Where true means align to the top of the page, and false is align to bottom.

Otherwise, there's a scrollTo() plugin for jQuery you can use.

Or maybe just get the top position()(docs) of the element, and set the scrollTop()(docs) to that position:

var top = $('#div_' + element_id).position().top;
$(window).scrollTop( top );

Bootstrap button drop-down inside responsive table not visible because of scroll

In my case, this works fine:

.table-responsive {
  overflow-y: visible !important;
}

Switch on Enum in Java

You actually can switch on enums, but you can't switch on Strings until Java 7. You might consider using polymorphic method dispatch with Java enums rather than an explicit switch. Note that enums are objects in Java, not just symbols for ints like they are in C/C++. You can have a method on an enum type, then instead of writing a switch, just call the method - one line of code: done!

enum MyEnum {
    SOME_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("first enum constant behavior!");
        }
    },
    ANOTHER_ENUM_CONSTANT {
        @Override
        public void method() {
            System.out.println("second enum constant behavior!");
        }
    }; // note the semi-colon after the final constant, not just a comma!
    public abstract void method(); // could also be in an interface that MyEnum implements
}

void aMethodSomewhere(final MyEnum e) {
    doSomeStuff();
    e.method(); // here is where the switch would be, now it's one line of code!
    doSomeOtherStuff();
}

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Add Favicon to Website

Simply put a file named favicon.ico in the webroot.

If you want to know more, please start reading:

How to decompile to java files intellij idea

To use the IntelliJ Java decompiler from the command line for a jar package follow the instructions provided here: https://github.com/JetBrains/intellij-community/tree/master/plugins/java-decompiler/engine

How do I make a WinForms app go Full Screen

And for the menustrip-question, try set

MenuStrip1.Parent = Nothing

when in fullscreen mode, it should then disapear.

And when exiting fullscreenmode, reset the menustrip1.parent to the form again and the menustrip will be normal again.

Rails Root directory path?

You can use:

Rails.root

But to to join the assets you can use:

Rails.root.join(*%w( app assets))

Hopefully this helps you.

How to change text color of cmd with windows batch script every 1 second

@echo off
set NUM=0 1 2 3 4 5 6 7 8 9 A B C D E F 31 32 33 34 35 36 37 41 42 43 44 45 46 90 91 92 93 94 95 96 97 100 101 102 103 104 105 106 107 
for %%x in (%NUM%) do ( 
    for %%y in (%NUM%) do (
        color %%x%%y
cls
echo Himel Sarkar
        timeout 1 >nul
    )
)

pause

jquery onclick change css background image

Use your jquery like this

$('.home').css({'background-image':'url(images/tabs3.png)'});

Insert ellipsis (...) into HTML tag if content too wide

DO THE ELLIPSIS USING ONLY CSS

<html>
<head>
<style type="text/css">
#ellipsisdiv {
    width:200px;
    white-space: nowrap;  
    overflow: hidden;  
    text-overflow: ellipsis;  
}  
</style>
</head>
<body>
<div id="ellipsisdiv">
This content is more than 200px and see how the the ellipsis comes at the end when the content width exceeds the div width.
</div>
</body>
</html>

*This code works on most current browsers. If you experience any problem with Opera and IE (which probably you won't), add these in the style:

-o-text-overflow: ellipsis;  
-ms-text-overflow: ellipsis;

* This feature is part of CSS3. Its complete syntax is:

text-overflow: clip|ellipsis|string;

How to install trusted CA certificate on Android device?

There is a MUCH easier solution to this than posted here, or in related threads. If you are using a webview (as I am), you can achieve this by executing a JAVASCRIPT function within it. If you are not using a webview, you might want to create a hidden one for this purpose. Here's a function that works in just about any browser (or webview) to kickoff ca installation (generally through the shared os cert repository, including on a Droid). It uses a nice trick with iFrames. Just pass the url to a .crt file to this function:

function installTrustedRootCert( rootCertUrl ){
    id = "rootCertInstaller";
    iframe = document.getElementById( id );
    if( iframe != null ) document.body.removeChild( iframe );
    iframe = document.createElement( "iframe" );
    iframe.id = id;
    iframe.style.display = "none";
    document.body.appendChild( iframe );
    iframe.src = rootCertUrl;
}

UPDATE:

The iframe trick works on Droids with API 19 and up, but older versions of the webview won't work like this. The general idea still works though - just download/open the file with a webview and then let the os take over. This may be an easier and more universal solution (in the actual java now):

 public static void installTrustedRootCert( final String certAddress ){
     WebView certWebView = new WebView( instance_ );
     certWebView.loadUrl( certAddress );
 }

Note that instance_ is a reference to the Activity. This works perfectly if you know the url to the cert. In my case, however, I resolve that dynamically with the server side software. I had to add a fair amount of additional code to intercept a redirection url and call this in a manner which did not cause a crash based on a threading complication, but I won't add all that confusion here...

Background color for Tk in Python

widget['bg'] = '#000000'

or

widget['background'] = '#000000'

would also work as hex-valued colors are also accepted.

How to get the request parameters in Symfony 2?

For symfony 4 users:

$query = $request->query->get('query');

Node: log in a file instead of the console

Update 2013 - This was written around Node v0.2 and v0.4; There are much better utilites now around logging. I highly recommend Winston

Update Late 2013 - We still use winston, but now with a logger library to wrap the functionality around logging of custom objects and formatting. Here is a sample of our logger.js https://gist.github.com/rtgibbons/7354879


Should be as simple as this.

var access = fs.createWriteStream(dir + '/node.access.log', { flags: 'a' })
      , error = fs.createWriteStream(dir + '/node.error.log', { flags: 'a' });

// redirect stdout / stderr
proc.stdout.pipe(access);
proc.stderr.pipe(error);

Order data frame rows according to vector with specific order

Here's a similar system for the situation where you have a variable you want to sort by, initially, but then you want to sort by a secondary variable according to the order that this secondary variable first appears in the initial sort.

In the function below, the initial sort variable is called order_by and the secondary variable is called order_along - as in "order by this variable along its initial order".

library(dplyr, warn.conflicts = FALSE)
df <- structure(
  list(
    msoa11hclnm = c(
      "Bewbush", "Tilgate", "Felpham",
      "Selsey", "Brunswick", "Ratton", "Ore", "Polegate", "Mile Oak",
      "Upperton", "Arundel", "Kemptown"
    ),
    lad20nm = c(
      "Crawley", "Crawley",
      "Arun", "Chichester", "Brighton and Hove", "Eastbourne", "Hastings",
      "Wealden", "Brighton and Hove", "Eastbourne", "Arun", "Brighton and Hove"
    ),
    shape_area = c(
      1328821, 3089180, 3540014, 9738033, 448888, 10152663, 5517102,
      7036428, 5656430, 2653589, 72832514, 826151
    )
  ),
  row.names = c(NA, -12L), class = "data.frame"
)

this does not give me what I need:

df %>% 
  dplyr::arrange(shape_area, lad20nm)
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3      Bewbush           Crawley    1328821
#> 4     Upperton        Eastbourne    2653589
#> 5      Tilgate           Crawley    3089180
#> 6      Felpham              Arun    3540014
#> 7          Ore          Hastings    5517102
#> 8     Mile Oak Brighton and Hove    5656430
#> 9     Polegate           Wealden    7036428
#> 10      Selsey        Chichester    9738033
#> 11      Ratton        Eastbourne   10152663
#> 12     Arundel              Arun   72832514

Here’s a function:

order_along <- function(df, order_along, order_by) {
  cols <- colnames(df)
  
  df <- df %>%
    dplyr::arrange({{ order_by }})
  
  df %>% 
    dplyr::select({{ order_along }}) %>% 
    dplyr::distinct() %>% 
    dplyr::full_join(df) %>% 
    dplyr::select(dplyr::all_of(cols))
  
}

order_along(df, lad20nm, shape_area)
#> Joining, by = "lad20nm"
#>    msoa11hclnm           lad20nm shape_area
#> 1    Brunswick Brighton and Hove     448888
#> 2     Kemptown Brighton and Hove     826151
#> 3     Mile Oak Brighton and Hove    5656430
#> 4      Bewbush           Crawley    1328821
#> 5      Tilgate           Crawley    3089180
#> 6     Upperton        Eastbourne    2653589
#> 7       Ratton        Eastbourne   10152663
#> 8      Felpham              Arun    3540014
#> 9      Arundel              Arun   72832514
#> 10         Ore          Hastings    5517102
#> 11    Polegate           Wealden    7036428
#> 12      Selsey        Chichester    9738033

Created on 2021-01-12 by the reprex package (v0.3.0)

Java Loop every minute

You can use Timer

Timer timer = new Timer();

timer.schedule( new TimerTask() {
    public void run() {
       // do your work 
    }
 }, 0, 60*1000);

When the times comes

  timer.cancel();

To shut it down.

Apply .gitignore on an existing repository already tracking large number of files

I think this is an easy way for adding a .gitignore file to an existing repository.

Prerequisite:

You need a browser to access your github account.

Steps

  1. Create a new file in your required (existing) project and name it .gitignore. You will a get suggestive prompt for .gitignore templates as soon as you name the file as .gitignore. Either use these templates or use gitignore.io to generate the content of your gitignore file.
  2. Commit the changes.
  3. Now clone this repository.

Have fun!

View's getWidth() and getHeight() returns 0

Maybe this helps someone:

Create an extension function for the View class

filename: ViewExt.kt

fun View.afterLayout(what: () -> Unit) {
    if(isLaidOut) {
        what.invoke()
    } else {
        viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                viewTreeObserver.removeOnGlobalLayoutListener(this)
                what.invoke()
            }
        })
    }
}

This can then be used on any view with:

view.afterLayout {
    do something with view.height
}

What does it mean when MySQL is in the state "Sending data"?

This is quite a misleading status. It should be called "reading and filtering data".

This means that MySQL has some data stored on the disk (or in memory) which is yet to be read and sent over. It may be the table itself, an index, a temporary table, a sorted output etc.

If you have a 1M records table (without an index) of which you need only one record, MySQL will still output the status as "sending data" while scanning the table, despite the fact it has not sent anything yet.

How to create an array from a CSV file using PHP and the fgetcsv function

Like you said in your title, fgetcsv is the way to go. It's pretty darn easy to use.

$file = fopen('myCSVFile.csv', 'r');
while (($line = fgetcsv($file)) !== FALSE) {
  //$line is an array of the csv elements
  print_r($line);
}
fclose($file);

You'll want to put more error checking in there in case fopen() fails, but this works to read a CSV file line by line and parse the line into an array.

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

Remove decimal values using SQL query

If it's a decimal data type and you know it will never contain decimal places you can consider setting the scale property to 0. For example to decimal(18, 0). This will save you from replacing the ".00" characters and the query will be faster. In such case, don't forget to to check if the "prevent saving option" is disabled (SSMS menu "Tools>Options>Designers>Table and database designer>prevent saving changes that require table re-creation").

Othewise, you of course remove it using SQL query:

select replace(cast([height] as varchar), '.00', '') from table

Are multi-line strings allowed in JSON?

Try this, it also handles the single quote which is failed to parse by JSON.parse() method and also supports the UTF-8 character code.

    parseJSON = function() {
        var data = {};
        var reader = new FileReader();
        reader.onload = function() {
            try {
                data = JSON.parse(reader.result.replace(/'/g, "\""));
            } catch (ex) {
                console.log('error' + ex);
            }
        };
        reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

I had the same issue. The reason was the corporate proxy issue. Solution was to set the proxy setting as @rsp says.

npm config set proxy http://example.com:8080
npm config set https-proxy http://example.com:8080

But later I face the same issue. This time reason was my password contains a special character.

In this command you can’t provide a password with special character

. So solution is to provide percentage encoded special character in the password.

For example # has to provide as %23

https://www.w3schools.com/tags/ref_urlencode.asp

WCF vs ASP.NET Web API

The new ASP.NET Web API is a continuation of the previous WCF Web API project (although some of the concepts have changed).

WCF was originally created to enable SOAP-based services. For simpler RESTful or RPCish services (think clients like jQuery) ASP.NET Web API should be good choice.


For us, WCF is used for SOAP and Web API for REST. I wish Web API supported SOAP too. We are not using advanced features of WCF. Here is comparison from MSDN:

enter image description here


ASP.net Web API is all about HTTP and REST based GET,POST,PUT,DELETE with well know ASP.net MVC style of programming and JSON returnable; web API is for all the light weight process and pure HTTP based components. For one to go ahead with WCF even for simple or simplest single web service it will bring all the extra baggage. For light weight simple service for ajax or dynamic calls always WebApi just solves the need. This neatly complements or helps in parallel to the ASP.net MVC.

Check out the podcast : Hanselminutes Podcast 264 - This is not your father's WCF - All about the WebAPI with Glenn Block by Scott Hanselman for more information.


In the scenarios listed below you should go for WCF:

  1. If you need to send data on protocols like TCP, MSMQ or MIME
  2. If the consuming client just knows how to consume SOAP messages

WEB API is a framework for developing RESTful/HTTP services.

There are so many clients that do not understand SOAP like Browsers, HTML5, in those cases WEB APIs are a good choice.

HTTP services header specifies how to secure service, how to cache the information, type of the message body and HTTP body can specify any type of content like HTML not just XML as SOAP services.

Synchronization vs Lock

Major difference between lock and synchronized:

  • with locks, you can release and acquire the locks in any order.
  • with synchronized, you can release the locks only in the order it was acquired.

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

For those who may find this later, after .NET version 4.6, I was running into this problem as well.

Make sure that you check your web.config file for the following lines:

<compilation debug="true" targetFramework="4.5">
...
<httpRuntime targetFramework="4.5" />

If you are running 4.6.x or a higher version of .NET on the server, make sure you adjust these targetFramework values to match the version of the framework on your server. If your versions read less than 4.6.x, then I would recommend you upgrade .NET and use the newer version unless your code is dependent on an older version (which, in that case, you should consider updating it).

I changed the targetFrameworks to 4.7.2 and the problem disappeared:

<compilation debug="true" targetFramework="4.7.2">
...
<httpRuntime targetFramework="4.7.2" />

The newer frameworks sort this issue out by using the best protocol available and blocking insecure or obsolete ones. If the remote service you are trying to connect to or call is giving this error, it could be that they don't support the old protocols anymore.

Check if xdebug is working

Try as following, should return "exists" or "non exists":

<?php
echo (extension_loaded('xdebug') ? '' : 'non '), 'exists';

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib for this package in weblogic.xml:

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
    </prefer-application-packages>

maybe <prefer-web-inf-classes>true</prefer-web-inf-classes> would work too.

How to get folder directory from HTML input type "file" or any other way?

Eventhough it is an old question, this may help someone.

We can choose multiple files while browsing for a file using "multiple"

<input type="file" name="datafile" size="40"  multiple> 

Calculate a Running Total in SQL Server

Here are 2 simple ways to calculate running total:

Approach 1: It can be written this way if your DBMS supports Analytical Functions

SELECT     id
           ,somedate
           ,somevalue
           ,runningtotal = SUM(somevalue) OVER (ORDER BY somedate ASC)
FROM       TestTable

Approach 2: You can make use of OUTER APPLY if your database version / DBMS itself does not support Analytical Functions

SELECT     T.id
           ,T.somedate
           ,T.somevalue
           ,runningtotal = OA.runningtotal
FROM       TestTable T
           OUTER APPLY (
                           SELECT   runningtotal = SUM(TI.somevalue)
                           FROM     TestTable TI
                           WHERE    TI.somedate <= S.somedate
                       ) OA;

Note:- If you have to calculate the running total for different partitions separately, it can be done as posted here: Calculating Running totals across rows and grouping by ID

How do I enable MSDTC on SQL Server?

Use this for windows Server 2008 r2 and Windows Server 2012 R2

  1. Click Start, click Run, type dcomcnfg and then click OK to open Component Services.

  2. In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.

  3. Right click Local DTC and click Properties to display the Local DTC Properties dialog box.

  4. Click the Security tab.

  5. Check mark "Network DTC Access" checkbox.

  6. Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.

  7. Click Apply, OK.

  8. A message will pop up about restarting the service.

  9. Click OK and That's all.

Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx

Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe

Git mergetool generates unwanted .orig files

To be clear, the correct git command is:

git config --global mergetool.keepBackup false

Both of the other answers have typos in the command line that will cause it to fail or not work correctly.

MySQL Orderby a number, Nulls last

Something like

SELECT * FROM tablename where visible=1 ORDER BY COALESCE(position, 999999999) ASC, id DESC

Replace 999999999 with what ever the max value for the field is

Insecure content in iframe on secure page

Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:

  • Prepare your proxy server - install IIS, Apache
  • Get valid SSL certificate to avoid security errors (free from startssl.com for example)
  • Write a wrapper, which will download insecure content (how to below)
  • From your site/app get https://yourproxy.com/?page=http://insecurepage.com

If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php


Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an iframe embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.

The best solution I created is to simply use google as the ssl proxy...

https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky

Tested and works in firefox.

Other Methods:

  • Use a Third party such as embed.ly (but it it really only good for well known http APIs).

  • Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)

    https://example.com That has a iframe linking to...

    https://example.com/utilities/redirect.html Which has a simple js redirect script like...

    document.location.href ="http://thenonsslsite.com";

  • Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.

  • You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.

Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).

The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.

Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.

align textbox and text/labels in html?

You have two boxes, left and right, for each label/input pair. Both boxes are in one row and have fixed width. Now, you just have to make label text float to the right with text-align: right;

Here's a simple example:

http://jsfiddle.net/qP46X/

Min/Max-value validators in asp.net mvc

jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:

public class MaxAttribute : ValidationAttribute, IClientValidatable
{
    private readonly int maxValue;

    public MaxAttribute(int maxValue)
    {
        this.maxValue = maxValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();

        rule.ErrorMessage = ErrorMessageString, maxValue;

        rule.ValidationType = "max";
        rule.ValidationParameters.Add("max", maxValue);
        yield return rule;
    }

    public override bool IsValid(object value)
    {
        return (int)value <= maxValue;
    }
}

Adapter:

$.validator.unobtrusive.adapters.add(
   'max',
   ['max'],
   function (options) {
       options.rules['max'] = parseInt(options.params['max'], 10);
       options.messages['max'] = options.message;
   });

Min attribute would be very similar.

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

I use this one all the time:

public static void DelimitedAppend(this StringBuilder sb, string value, string delimiter)
{
    if (sb.Length > 0)
        sb.Append(delimiter);
    sb.Append(value);
}

This just ensures that the delimiter is not inserted when the string is empty. For example, to create a comma-seperated list of words:

var farmAnimals = new[] { new { Species = "Dog", IsTasty = false }, new { Species = "Cat", IsTasty = false }, new { Species = "Chicken", IsTasty = true }, };
var soupIngredients = new StringBuilder();
foreach (var edible in farmAnimals.Where(farmAnimal => farmAnimal.IsTasty))
    soupIngredients.DelimitedAppend(edible.Species, ", ");

Do you recommend using semicolons after every statement in JavaScript?

JavaScript automatically inserts semicolons whilst interpreting your code, so if you put the value of the return statement below the line, it won't be returned:

Your Code:

return
5

JavaScript Interpretation:

return;
5;

Thus, nothing is returned, because of JavaScript's auto semicolon insertion

REST API Authentication

Here's a guided approach.

Your authentication service issues a JWT token that is signed using a secret that is also available in your API service. The reason they need to be there too is that you will need to verify the tokens received to make sure you created them. The nice thing about JWTs is that their payload can hold claims as to what the user is authorised to access should different users have different access control levels.

That architecture renders authentication stateless: No need to store any tokens in a database unless you would like to handle token blacklisting (think banning users). Being stateless is crucial if you ever need to scale. That also frees up your API service from having to call the authentication server at all as the information they need for both authentication and authorisation are in the issued token.

Flow (no refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server.
  2. User uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.

There are a couple of issues here. Namely, that auth token in the wrong hands provides unlimited access to a malicious user to pretend they are the affected user and call your APIs indefinitely. To handle that, tokens have an expiry date and clients are forced to request new tokens whenever expiry happens. That expiry is part of the token's payload. But if tokens are short-lived, do we require users to authenticate with their usernames and password every time? No. We do not want to ask a user for their password every 30min to an hour, and we do not want to persist that password anywhere in the client. To get around that issue, we introduce the concept of refresh tokens. They are longer lived tokens that serve one purpose: act as a user's password, authenticate them to get a new token. Downside is that with this architecture your authentication server needs to persist these refresh token in a database.

New flow (with refresh tokens):

  1. User authenticates with the authentication server (eg: POST /auth/login) and receives a JWT token generated and signed by the auth server, alongside a long lived (eg: 6 months) refresh token that they store securely
  2. Whenever the user needs to make an API request, the token's expiry is checked. Assuming it has not yet expired, user uses that token to talk to your API and assuming user is authorised), gets and posts the necessary resources.
  3. If the token has indeed expired, there is a need to refresh your token, user calls authentication server (EG: POST / auth/token) and passes the securely stored refresh token. Response is a new access token issued.
  4. Use that new token to talk to your API image servers.

OPTIONAL (banning users)

How do we ban users? Using that model there is no easy way to do so. Enhancement: Every persisted refresh token includes a blacklisted field and only issue new tokens if the refresh token isn't black listed.

Things to consider:

  • You may want to rotate refresh token. To do so, blacklist the refresh token each time your user needs a new access token. That way refresh tokens can only be used once. Downside you will end up with a lot more refresh tokens but that can easily be solved with a job that clears blacklisted refresh tokens (eg: once a day)
  • You may want to consider setting a maximum number of allowed refresh tokens issued per user (say 10 or 20) as you issue a new one every time they login (with username and password). This number depends on your flow, how many clients a user may use (web, mobile, etc) and other factors.
  • Logout endpoint in your authentication service may or may not blacklist refresh tokens. Something to think about.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

This is how I managed to do what I was trying to do:

[Test]
public void TransferHandlesDisconnect()
{
    // ... set up config here
    var methodTester = new Mock<Transfer>(configInfo);
    methodTester.CallBase = true;
    methodTester
        .Setup(m => 
            m.GetFile(
                It.IsAny<IFileConnection>(), 
                It.IsAny<string>(), 
                It.IsAny<string>()
            ))
        .Throws<System.IO.IOException>();

    methodTester.Object.TransferFiles("foo1", "foo2");
    Assert.IsTrue(methodTester.Object.Status == TransferStatus.TransferInterrupted);
}

If there is a problem with this method, I would like to know; the other answers suggest I am doing this wrong, but this was exactly what I was trying to do.

How do I create a timeline chart which shows multiple events? Eg. Metallica Band members timeline on wiki

A Stacked bar chart should suffice:

Setup data as follows

Name    Start       End         Duration (End - Start)
Fred    1/01/1981   1/06/1985    1612   
Bill    1/07/1985   1/11/2000    5602  
Joe     1/01/1980   1/12/2001    8005  
Jim     1/03/1999   1/01/2000    306  
  1. Plot Start and Duration as a stacked bar chart
  2. Set the X-Axis minimum to the desired start date
  3. Set the Fill Colour of thestart range to no fill
  4. Set the Fill of individual bars to suit

(example prepared in Excel 2010)

enter image description here

How to secure RESTful web services?

There's another, very secure method. It's client certificates. Know how servers present an SSL Cert when you contact them on https? Well servers can request a cert from a client so they know the client is who they say they are. Clients generate certs and give them to you over a secure channel (like coming into your office with a USB key - preferably a non-trojaned USB key).

You load the public key of the cert client certificates (and their signer's certificate(s), if necessary) into your web server, and the web server won't accept connections from anyone except the people who have the corresponding private keys for the certs it knows about. It runs on the HTTPS layer, so you may even be able to completely skip application-level authentication like OAuth (depending on your requirements). You can abstract a layer away and create a local Certificate Authority and sign Cert Requests from clients, allowing you to skip the 'make them come into the office' and 'load certs onto the server' steps.

Pain the neck? Absolutely. Good for everything? Nope. Very secure? Yup.

It does rely on clients keeping their certificates safe however (they can't post their private keys online), and it's usually used when you sell a service to clients rather then letting anyone register and connect.

Anyway, it may not be the solution you're looking for (it probably isn't to be honest), but it's another option.

ping: google.com: Temporary failure in name resolution

I've faced the exactly same problem but I've fixed it with another approache.

Using Ubuntu 18.04, first disable systemd-resolved service.

sudo systemctl disable systemd-resolved.service

Stop the service

sudo systemctl stop systemd-resolved.service

Then, remove the link to /run/systemd/resolve/stub-resolv.conf in /etc/resolv.conf

sudo rm /etc/resolv.conf

Add a manually created resolv.conf in /etc/

sudo vim /etc/resolv.conf

Add your prefered DNS server there

nameserver 208.67.222.222

I've tested this with success.

How can I lock a file using java (if possible)

FileChannel.lock is probably what you want.

try (
    FileInputStream in = new FileInputStream(file);
    java.nio.channels.FileLock lock = in.getChannel().lock();
    Reader reader = new InputStreamReader(in, charset)
) {
    ...
}

(Disclaimer: Code not compiled and certainly not tested.)

Note the section entitled "platform dependencies" in the API doc for FileLock.

Spring: Why do we autowire the interface and not the implemented class?

How does spring know which polymorphic type to use.

As long as there is only a single implementation of the interface and that implementation is annotated with @Component with Spring's component scan enabled, Spring framework can find out the (interface, implementation) pair. If component scan is not enabled, then you have to define the bean explicitly in your application-config.xml (or equivalent spring configuration file).

Do I need @Qualifier or @Resource?

Once you have more than one implementation, then you need to qualify each of them and during auto-wiring, you would need to use the @Qualifier annotation to inject the right implementation, along with @Autowired annotation. If you are using @Resource (J2EE semantics), then you should specify the bean name using the name attribute of this annotation.

Why do we autowire the interface and not the implemented class?

Firstly, it is always a good practice to code to interfaces in general. Secondly, in case of spring, you can inject any implementation at runtime. A typical use case is to inject mock implementation during testing stage.

interface IA
{
  public void someFunction();
}


class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Your bean configuration should look like this:

<bean id="b" class="B" />
<bean id="c" class="C" />
<bean id="runner" class="MyRunner" />

Alternatively, if you enabled component scan on the package where these are present, then you should qualify each class with @Component as follows:

interface IA
{
  public void someFunction();
}

@Component(value="b")
class B implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someBfunc()
  {
     //doing b things
  }
}


@Component(value="c")
class C implements IA
{
  public void someFunction()
  {
    //busy code block
  }
  public void someCfunc()
  {
     //doing C things
  }
}

@Component    
class MyRunner
{
     @Autowire
     @Qualifier("b") 
     IA worker;

     ....
     worker.someFunction();
}

Then worker in MyRunner will be injected with an instance of type B.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

<uses-library
            android:name="com.google.android.maps"
            android:required="false" />

if required is true, maybe you need to change

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

You must check if result returned by mysql_query is false.

$r = mysql_qyery("...");
if ($r) {
  mysql_fetch_assoc($r);
}

You can use @mysql_fetch_assoc($r) to avoid error displaying.

How to check if a value exists in an object using JavaScript

You can try this:

function checkIfExistingValue(obj, key, value) {
    return obj.hasOwnProperty(key) && obj[key] === value;
}
var test = [{name : "jack", sex: F}, {name: "joe", sex: M}]
console.log(test.some(function(person) { return checkIfExistingValue(person, "name", "jack"); }));

Adjust plot title (main) position

To summarize and explain visually how it works. Code construction is as follows:

par(mar = c(3,2,2,1))
barplot(...all parameters...)
title("Title text", adj = 0.5, line = 0)

explanation:

par(mar = c(low, left, top, right)) - margins of the graph area.

title("text" - title text
      adj  = from left (0) to right (1) with anything in between: 0.1, 0.2, etc...
      line = positive values move title text up, negative - down)

enter image description here

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

Library not loaded: libmysqlclient.16.dylib error when trying to run 'rails server' on OS X 10.6 with mysql2 gem

If you're using OSX and installed mysql using brew, you can:

brew link mysql

If you're having trouble with the version (I had mysql 5.7 running while my gem required 5.6.25), you can

brew unlink mysql
brew switch mysql 5.6.25

how to add value to combobox item

Now you can use insert method instead add

' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")

Grunt watch error - Waiting...Fatal error: watch ENOSPC

Any time you need to run sudo something ... to fix something, you should be pausing to think about what's going on. While the accepted answer here is perfectly valid, it's treating the symptom rather than the problem. Sorta the equivalent of buying bigger saddlebags to solve the problem of: error, cannot load more garbage onto pony. Pony has so much garbage already loaded, that pony is fainting with exhaustion.

An alternative (perhaps comparable to taking excess garbage off of pony and placing in the dump), is to run:

npm dedupe

Then go congratulate yourself for making pony happy.

How do I read from parameters.yml in a controller in symfony2?

I send you an example with swiftmailer:

parameters.yml

recipients: [email1, email2, email3]

services:

your_service_name:
        class: your_namespace
        arguments: ["%recipients%"]

the class of the service:

protected $recipients;

public function __construct($recipients)
{
    $this->recipients = $recipients;
}

No module named setuptools

The PyPA recommended tool for installing and managing Python packages is pip. pip is included with Python 3.4 (PEP 453), but for older versions here's how to install it (on Windows, using Python 3.3):

Download https://bootstrap.pypa.io/get-pip.py

>c:\Python33\python.exe get-pip.py
Downloading/unpacking pip
Downloading/unpacking setuptools
Installing collected packages: pip, setuptools
Successfully installed pip setuptools
Cleaning up...

Sample usage:

>c:\Python33\Scripts\pip.exe install pymysql
Downloading/unpacking pymysql
Installing collected packages: pymysql
Successfully installed pymysql
Cleaning up...

In your case it would be this (it appears that pip caches independent of Python version):

C:\Python27>python.exe \code\Python\get-pip.py
Requirement already up-to-date: pip in c:\python27\lib\site-packages
Collecting wheel
  Downloading wheel-0.29.0-py2.py3-none-any.whl (66kB)
    100% |################################| 69kB 255kB/s
Installing collected packages: wheel
Successfully installed wheel-0.29.0

C:\Python27>cd Scripts

C:\Python27\Scripts>pip install twilio
Collecting twilio
  Using cached twilio-5.3.0.tar.gz
Collecting httplib2>=0.7 (from twilio)
  Using cached httplib2-0.9.2.tar.gz
Collecting six (from twilio)
  Using cached six-1.10.0-py2.py3-none-any.whl
Collecting pytz (from twilio)
  Using cached pytz-2015.7-py2.py3-none-any.whl
Building wheels for collected packages: twilio, httplib2
  Running setup.py bdist_wheel for twilio ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e0\f2\a7\c57f6d153c440b93bd24c1243123f276dcacbf43cc43b7f906
  Running setup.py bdist_wheel for httplib2 ... done
  Stored in directory: C:\Users\Cees.Timmerman\AppData\Local\pip\Cache\wheels\e1\a3\05\e66aad1380335ee0a823c8f1b9006efa577236a24b3cb1eade
Successfully built twilio httplib2
Installing collected packages: httplib2, six, pytz, twilio
Successfully installed httplib2-0.9.2 pytz-2015.7 six-1.10.0 twilio-5.3.0

Converts scss to css

This is an online/offline solution and very easy to convert. SCSS to CSS converter

enter image description here

How do we download a blob url video

There are a variety of ways to get the URL .m3u8 either by viewing the source of a page, looking at the Network tab in the Developer Tools in Chrome, or using a plugin such as HDL/HLS Video Downloader.

With the .m3u8 URL in hand you can then use ffmpeg to download the video to a file like so:

$ ffmpeg -i 'https://url/to/some/file.m3u8' -bsf:a aac_adtstoasc \
    -vcodec copy -c copy -crf 50 file.mp4

React.js, wait for setState to finish before triggering a function?

setState() has an optional callback parameter that you can use for this. You only need to change your code slightly, to this:

// Form Input
this.setState(
  {
    originId: input.originId,
    destinationId: input.destinationId,
    radius: input.radius,
    search: input.search
  },
  this.findRoutes         // here is where you put the callback
);

Notice the call to findRoutes is now inside the setState() call, as the second parameter.
Without () because you are passing the function.

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

How to call jQuery function onclick?

try this ..

HTML

<input type="submit" value="submit" name="submit" id="submit">

jQuery

$(document).ready(function () {
    $('#submit').click(function () {
        var url = $(location).attr('href');
        $('#spn_url').html('<strong>' + url + '</strong>');
    });
});

How to get the current taxonomy term ID (not the slug) in WordPress?

It's the term slug you want.Looks like you can get the id like this if that's what you need:

function get_term_link( $term, $taxonomy = '' ) {
    global $wp_rewrite;

    if ( !is_object($term) ) {
        if ( is_int( $term ) ) {
            $term = get_term( $term, $taxonomy );
        } else {
            $term = get_term_by( 'slug', $term, $taxonomy );
        }
    }

Update style of a component onScroll in React.js

To expand on @Austin's answer, you should add this.handleScroll = this.handleScroll.bind(this) to your constructor:

constructor(props){
    this.handleScroll = this.handleScroll.bind(this)
}
componentDidMount: function() {
    window.addEventListener('scroll', this.handleScroll);
},

componentWillUnmount: function() {
    window.removeEventListener('scroll', this.handleScroll);
},

handleScroll: function(event) {
    let scrollTop = event.srcElement.body.scrollTop,
        itemTranslate = Math.min(0, scrollTop/3 - 60);

    this.setState({
      transform: itemTranslate
    });
},
...

This gives handleScroll() access to the proper scope when called from the event listener.

Also be aware you cannot do the .bind(this) in the addEventListener or removeEventListener methods because they will each return references to different functions and the event will not be removed when the component unmounts.

How to apply two CSS classes to a single element

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
.color_x000D_
{background-color:#21B286;}_x000D_
.box_x000D_
{_x000D_
  width:"100%";_x000D_
  height:"100px";_x000D_
  font-size: 16px;_x000D_
  text-align:center;_x000D_
  line-height:1.19em;_x000D_
}_x000D_
.box.color_x000D_
{_x000D_
width:"100%";_x000D_
height:"100px";_x000D_
font-size:16px;_x000D_
color:#000000;_x000D_
text-align:center;_x000D_
}
_x000D_
<div class="box color">orderlist</div>
_x000D_
_x000D_
_x000D_

Add a CSS border on hover without moving the element

Try this it might solve your problem.

Css:

.item{padding-top:1px;}

.jobs .item:hover {
    background: #e1e1e1;
    border-top: 1px solid #d0d0d0;
    padding-top:0;
}

HTML:

<div class="jobs">
    <div class="item">
        content goes here
    </div>
</div>

See fiddle for output: http://jsfiddle.net/dLDNA/

How can I align text directly beneath an image?

You can use HTML5 <figcaption>:

<figure>
  <img src="img.jpg" alt="my img"/>
  <figcaption> Your text </figcaption>
</figure>

Working example.

Selenium Webdriver: Entering text into text field

Agree with Subir Kumar Sao and Faiz.

element_enter.findElement(By.xpath("//html/body/div[1]/div[3]/div[1]/form/div/div/input")).sendKeys(barcode);

Parsing JSON with Unix tools

You've asked how to shoot yourself in the foot and I'm here to provide the ammo:

curl -s 'http://twitter.com/users/username.json' | sed -e 's/[{}]/''/g' | awk -v RS=',"' -F: '/^text/ {print $2}'

You could use tr -d '{}' instead of sed. But leaving them out completely seems to have the desired effect as well.

If you want to strip off the outer quotes, pipe the result of the above through sed 's/\(^"\|"$\)//g'

I think others have sounded sufficient alarm. I'll be standing by with a cell phone to call an ambulance. Fire when ready.

Why is semicolon allowed in this python snippet?

Python uses the ; as a separator, not a terminator. You can also use them at the end of a line, which makes them look like a statement terminator, but this is legal only because blank statements are legal in Python -- a line that contains a semicolon at the end is two statements, the second one blank.

How to output a multiline string in Bash?

Here documents are often used for this purpose.

cat << EOF
usage: up [--level <n>| -n <levels>][--help][--version]

Report bugs to: 
up home page:
EOF

They are supported in all Bourne-derived shells including all versions of Bash.

Address validation using Google Maps API

The answer depends upon the degree of confidence you place in the data and how your data is being used. For example, if you're using it for mailing or shipping, you'll want to be be confident that the data is correct. If you're just using it as another fraud-prevention mechanism then you could potentially allow a degree of error to creep into the data.

If you want any degree of real accuracy, you're need to go with a service that does real address verification and you're going to have to pay for it. As has been mentioned by Adam, address verification and validation at first seems simple and easy, but it's a black hole fraught with challenges and, unless you've some underlying data to work with, virtually impossible to do by yourself. Trust me, you're actually saving money by using a service. You're welcome to go down this road yourself to experience what I mean, but I can guarantee you'll see the light, so to speak, after even a few hours (or days) of spinning your wheels.

I should mention that I'm the founder of SmartyStreets. We do address validation and verification addresses and we offer this for the USA and international as well. I'm more than happy to personally answer any questions you have on the topic of address cleansing, standardization, and validation.

Get the position of a div/span tag

As Alex noted you can use jQuery offset() to get the position relative to the document flow. Use position() for its x,y coordinates relative to the parent.

EDIT: Switched document.ready for window.load because load waits for all of the elements so you get their size instead of simply preparing the DOM. In my experience, load results in fewer incorrectly Javascript positioned elements.

$(window).load(function(){ 
  // Log the position with jQuery
  var position = $('#myDivInQuestion').position();
  console.log('X: ' + position.left + ", Y: " + position.top );
});

General guidelines to avoid memory leaks in C++

Tips in order of Importance:

-Tip#1 Always remember to declare your destructors "virtual".

-Tip#2 Use RAII

-Tip#3 Use boost's smartpointers

-Tip#4 Don't write your own buggy Smartpointers, use boost (on a project I'm on right now I can't use boost, and I've suffered having to debug my own smart pointers, I would definately not take the same route again, but then again right now I can't add boost to our dependencies)

-Tip#5 If its some casual/non-performance critical (as in games with thousands of objects) work look at Thorsten Ottosen's boost pointer container

-Tip#6 Find a leak detection header for your platform of choice such as Visual Leak Detection's "vld" header

Specifying an Index (Non-Unique Key) Using JPA

It's not possible to do that using JPA annotation. And this make sense: where a UniqueConstraint clearly define a business rules, an index is just a way to make search faster. So this should really be done by a DBA.

Django - what is the difference between render(), render_to_response() and direct_to_template()?

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render

render(request, template[, dictionary][, context_instance][, content_type][, status][, current_app])

render() is a brand spanking new shortcut for render_to_response in 1.3 that will automatically use RequestContext that I will most definitely be using from now on.


2020 EDIT: It should be noted that render_to_response() was removed in Django 3.0

https://docs.djangoproject.com/en/1.8/topics/http/shortcuts/#render-to-response

render_to_response(template[, dictionary][, context_instance][, mimetype])¶

render_to_response is your standard render function used in the tutorials and such. To use RequestContext you'd have to specify context_instance=RequestContext(request)


https://docs.djangoproject.com/en/1.8/ref/generic-views/#django-views-generic-simple-direct-to-template

direct_to_template is a generic view that I use in my views (as opposed to in my urls) because like the new render() function, it automatically uses RequestContext and all its context_processors.

But direct_to_template should be avoided as function based generic views are deprecated. Either use render or an actual class, see https://docs.djangoproject.com/en/1.3/topics/generic-views-migration/

I'm happy I haven't typed RequestContext in a long, long time.

Regex Email validation

This regex works perfectly:

bool IsValidEmail(string email)
{
    return Regex.IsMatch(email, @"^[\w!#$%&'*+\-/=?\^_`{|}~]+(\.[\w!#$%&'*+\-/=?\^_`{|}~]+)*@((([\-\w]+\.)+[a-zA-Z]{2,4})|(([0-9]{1,3}\.){3}[0-9]{1,3}))\z");
}

MySQL DAYOFWEEK() - my week begins with monday

You can easily use the MODE argument:

MySQL :: MySQL 5.5 Reference Manual :: 12.7 Date and Time Functions

If the mode argument is omitted, the value of the default_week_format system variable is used:

MySQL :: MySQL 5.1 Reference Manual :: 5.1.4 Server System Variables

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

The project JsonSubTypes implement a generic converter that handle this feature with the helps of attributes.

For the concrete sample provided here is how it works:

    [JsonConverter(typeof(JsonSubtypes))]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Employee), "JobTitle")]
    [JsonSubtypes.KnownSubTypeWithProperty(typeof(Artist), "Skill")]
    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

    public class Employee : Person
    {
        public string Department { get; set; }
        public string JobTitle { get; set; }
    }

    public class Artist : Person
    {
        public string Skill { get; set; }
    }

    [TestMethod]
    public void Demo()
    {
        string json = "[{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Department\":\"Department1\",\"JobTitle\":\"JobTitle1\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}," +
                      "{\"Skill\":\"Painter\",\"FirstName\":\"FirstName1\",\"LastName\":\"LastName1\"}]";


        var persons = JsonConvert.DeserializeObject<IReadOnlyCollection<Person>>(json);
        Assert.AreEqual("Painter", (persons.Last() as Artist)?.Skill);
    }

PHP multiline string with PHP

To do that, you must remove all ' charachters in your string or use an escape character. Like:

<?php
    echo '<?php
              echo \'hello world\';
          ?>';
?>

Calling a stored procedure in Oracle with IN and OUT parameters

If you set the server output in ON mode before the entire code, it works, otherwise put_line() will not work. Try it!

The code is,

set serveroutput on;
CREATE OR REPLACE PROCEDURE PROC1(invoicenr IN NUMBER, amnt OUT NUMBER)
AS BEGIN
SELECT AMOUNT INTO amnt FROM INVOICE WHERE INVOICE_NR = invoicenr;
END;

And then call the function as it is:

DECLARE
amount NUMBER;
BEGIN
PROC1(1000001, amount);
dbms_output.put_line(amount);
END;

How do I merge changes to a single file, rather than merging commits?

Here's what I do in these situations. It's a kludge but it works just fine for me.

  1. Create another branch based off of your working branch.
  2. git pull/git merge the revision (SHA1) which contains the file you want to copy. So this will merge all of your changes, but we are only using this branch to grab the one file.
  3. Fix up any Conflicts etc. investigate your file.
  4. checkout your working branch
  5. Checkout the file commited from your merge.
  6. Commit it.

I tried patching and my situation was too ugly for it. So in short it would look like this:

Working Branch: A Experimental Branch: B (contains file.txt which has changes I want to fold in.)

git checkout A

Create new branch based on A:

git checkout -b tempAB

Merge B into tempAB

git merge B

Copy the sha1 hash of the merge:

git log

commit 8dad944210dfb901695975886737dc35614fa94e
Merge: ea3aec1 0f76e61
Author: matthewe <[email protected]>
Date:   Wed Oct 3 15:13:24 2012 -0700

Merge branch 'B' into tempAB

Checkout your working branch:

git checkout A

Checkout your fixed-up file:

git checkout 7e65b5a52e5f8b1979d75dffbbe4f7ee7dad5017 file.txt

And there you should have it. Commit your result.