Programs & Examples On #Zend framework mvc

Undoing accidental git stash pop

If your merge was not too complicated another option would be to:

  1. Move all the changes including the merge changes back to stash using "git stash"
  2. Run the merge again and commit your changes (without the changes from the dropped stash)
  3. Run a "git stash pop" which should ignore all the changes from your previous merge since the files are identical now.

After that you are left with only the changes from the stash you dropped too early.

iPhone UILabel text soft shadow

_nameLabel = [[UILabel alloc] initWithFrame:CGRectZero];
_nameLabel.font = [UIFont boldSystemFontOfSize:19.0f];
_nameLabel.textColor = [UIColor whiteColor];
_nameLabel.backgroundColor = [UIColor clearColor];
_nameLabel.shadowColor = [UIColor colorWithWhite:0 alpha:0.2];
_nameLabel.shadowOffset = CGSizeMake(0, 1);

i think you should use the [UIColor colorWithWhite:0 alpha:0.2] to set the alpha value.

In what cases will HTTP_REFERER be empty

I have found the browser referer implementation to be really inconsistent.

For example, an anchor element with the "download" attribute works as expected in Safari and sends the referer, but in Chrome the referer will be empty or "-" in the web server logs.

<a href="http://foo.com/foo" download="bar">click to download</a>

Is broken in Chrome - no referer sent.

Determine the number of rows in a range

Function ListRowCount(ByVal FirstCellName as String) as Long
    With thisworkbook.Names(FirstCellName).RefersToRange
        If isempty(.Offset(1,0).value) Then 
            ListRowCount = 1
        Else
            ListRowCount = .End(xlDown).row - .row + 1
        End If
    End With
End Function

But if you are damn sure there's nothing around the list, then just thisworkbook.Names(FirstCellName).RefersToRange.CurrentRegion.rows.count

How to check a radio button with jQuery?

$("#radio_1").attr('checked', true);
//or
$("#radio_1").attr('checked', 'checked');

JavaScript adding decimal numbers issue

This is common issue with floating points.

Use toFixed in combination with parseFloat.

Here is example in JavaScript:

function roundNumber(number, decimals) {
    var newnumber = new Number(number+'').toFixed(parseInt(decimals));
    return parseFloat(newnumber); 
}

0.1 + 0.2;                    //=> 0.30000000000000004
roundNumber( 0.1 + 0.2, 12 ); //=> 0.3

Reading/writing an INI file

I want to introduce an IniParser library I've created completely in c#, so it contains no dependencies in any OS, which makes it Mono compatible. Open Source with MIT license -so it can be used in any code.

You can check out the source in GitHub, and it is also available as a NuGet package

It's heavily configurable, and really simple to use.

Sorry for the shameless plug but I hope it can be of help of anyone revisiting this answer.

Python Math - TypeError: 'NoneType' object is not subscriptable

lista = list.sort(lista)

This should be

lista.sort()

The .sort() method is in-place, and returns None. If you want something not in-place, which returns a value, you could use

sorted_list = sorted(lista)

Aside #1: please don't call your lists list. That clobbers the builtin list type.

Aside #2: I'm not sure what this line is meant to do:

print str("value 1a")+str(" + ")+str("value 2")+str(" = ")+str("value 3a ")+str("value 4")+str("\n")

is it simply

print "value 1a + value 2 = value 3a value 4"

? In other words, I don't know why you're calling str on things which are already str.

Aside #3: sometimes you use print("something") (Python 3 syntax) and sometimes you use print "something" (Python 2). The latter would give you a SyntaxError in py3, so you must be running 2.*, in which case you probably don't want to get in the habit or you'll wind up printing tuples, with extra parentheses. I admit that it'll work well enough here, because if there's only one element in the parentheses it's not interpreted as a tuple, but it looks strange to the pythonic eye..


The exception TypeError: 'NoneType' object is not subscriptable happens because the value of lista is actually None. You can reproduce TypeError that you get in your code if you try this at the Python command line:

None[0]

The reason that lista gets set to None is because the return value of list.sort() is None... it does not return a sorted copy of the original list. Instead, as the documentation points out, the list gets sorted in-place instead of a copy being made (this is for efficiency reasons).

If you do not want to alter the original version you can use

other_list = sorted(lista)

Get a list of all git commits, including the 'lost' ones

git log --reflog

saved me! I lost mine while merging HEAD and could not find my lates commit! Not showing in source tree but git log --reflog show all my local commits before

jQuery: Can I call delay() between addClass() and such?

Try this:

function removeClassDelayed(jqObj, c, to) {    
    setTimeout(function() { jqObj.removeClass(c); }, to);
}
removeClassDelayed($("#div"), "error", 1000);

How do you generate a random double uniformly distributed between 0 and 1 from C++?

You could try the Mersenne Twister algorithm.

http://en.wikipedia.org/wiki/Mersenne_twister

It has a good blend of speed and randomness, and a GPL implementation.

Spring Boot application can't resolve the org.springframework.boot package

This answer may be out of topic for most of readers. In my case the dependency didn't update and "mvn clean" didn't work since my wifi network at the office is highly securised, leaving a "connection timed out". (same respect github pushes and pulls don't work) I just moved to teathering with my phone and it works. Stupid, out of topic for most, but it may help some very specific cases.

IPhone/IPad: How to get screen width programmatically?

use:

NSLog(@"%f",[[UIScreen mainScreen] bounds].size.width) ;

jQuery events .load(), .ready(), .unload()

window load will wait for all resources to be loaded.

document ready waits for the document to be initialized.

unload well, waits till the document is being unloaded.

the order is: document ready, window load, ... ... ... ... window unload.

always use document ready unless you need to wait for your images to load.

shorthand for document ready:

$(function(){
    // yay!
});

The listener supports no services

You need to add your ORACLE_HOME definition in your listener.ora file. Right now its not registered with any ORACLE_HOME.

Sample listener.ora

abc =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = abc.kma.com)(PORT = 1521))
    )
  )

SID_LIST_abc =
  (SID_LIST =
    (SID_DESC =
      (ORACLE_HOME= /abc/DbTier/11.2.0)
      (SID_NAME = abc)
    )
  )

conversion from string to json object android

You just need the lines of code as below:

   try {
        String myjsonString = "{\"phonetype\":\"N95\",\"cat\":\"WP\"}";
        JSONObject jsonObject = new JSONObject(myjsonString );
        //displaying the JSONObject as a String
        Log.d("JSONObject = ", jsonObject.toString());
        //getting specific key values
        Log.d("phonetype = ", jsonObject.getString("phonetype"));
        Log.d("cat = ", jsonObject.getString("cat");
    }catch (Exception ex) {
         StringWriter stringWriter = new StringWriter();
         ex.printStackTrace(new PrintWriter(stringWriter));
         Log.e("exception ::: ", stringwriter.toString());
    }

Waiting until two async blocks are executed before starting another block

Another GCD alternative is a barrier:

dispatch_queue_t queue = dispatch_queue_create("com.company.app.queue", DISPATCH_QUEUE_CONCURRENT);

dispatch_async(queue, ^{ 
    NSLog(@"start one!\n");  
    sleep(4);  
    NSLog(@"end one!\n");
});

dispatch_async(queue, ^{  
    NSLog(@"start two!\n");  
    sleep(2);  
    NSLog(@"end two!\n"); 
});

dispatch_barrier_async(queue, ^{  
    NSLog(@"Hi, I'm the final block!\n");  
});

Just create a concurrent queue, dispatch your two blocks, and then dispatch the final block with barrier, which will make it wait for the other two to finish.

How to save a data.frame in R?

If you are only saving a single object (your data frame), you could also use saveRDS.
To save:

saveRDS(foo, file="data.Rda")

Then read it with:

bar <- readRDS(file="data.Rda")

The difference between saveRDS and save is that in the former only one object can be saved and the name of the object is not forced to be the same after you load it.

PHP - If variable is not empty, echo some html code

i hope this will work too, try using"is_null"

<?php 
$web = the_field('website');
if (!is_null($web)) {
?>

....html code here

<?php
} else { 
    echo "Niente";
}
?>

http://php.net/manual/en/function.is-null.php

hope that suits you..

How to switch activity without animation in Android?

You can create a style,

 <style name="noAnimTheme" parent="android:Theme">
   <item name="android:windowAnimationStyle">@null</item>
</style>

and set it as theme for your activity in the manifest:

   <activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
    </activity>

You can also define a style to specify custom entry and exit animations. http://developer.android.com/reference/android/R.attr.html#windowEnterAnimation

How to add a title to a html select tag

Typically, I would suggest that you use the <optgroup> option, as that gives some nice styling and indenting to the element.

The HTML element creates a grouping of options within a element. (Source: MDN Web Docs: <optgroup>.

But, since an <optgroup> cannot be a selected value, you can make an <option selected disabled> and then stylize it with CSS so that it behaves like an <optgroup>....

_x000D_
_x000D_
.optionGroup {
    font-weight: bold;
    font-style: italic;
}
_x000D_
<select>
    <option class="optionGroup" selected disabled>Choose one</option>
    <option value="sydney" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Sydney</option>
    <option value="melbourne" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Melbourne</option>
    <option value="cromwell" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Cromwell</option>
    <option value="queenstown" class="optionChild">&nbsp;&nbsp;&nbsp;&nbsp;Queenstown</option>
</select>
_x000D_
_x000D_
_x000D_

How do you auto format code in Visual Studio?

Its Shift + Alt + F in windows

But you can always double check by doing following.

  1. Go to View > Command Palette or press Ctrl + Shift + P
  2. Search for Format Document
  3. You can press that to Auto Format Code or its Hot Key, written in front of it.

Should operator<< be implemented as a friend or as a member function?

You can not do it as a member function, because the implicit this parameter is the left hand side of the <<-operator. (Hence, you would need to add it as a member function to the ostream-class. Not good :)

Could you do it as a free function without friending it? That's what I prefer, because it makes it clear that this is an integration with ostream, and not a core functionality of your class.

What is the iPad user agent?

Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10

How do C++ class members get initialized if I don't do it explicitly?

Members with a constructor will have their default constructor called for initialisation.

You cannot depend on the contents of the other types.

Check if a column contains text using SQL

Try this:

SElECT * FROM STUDENTS WHERE LEN(CAST(STUDENTID AS VARCHAR)) > 0

With this you get the rows where STUDENTID contains text

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

How to pass parameters to a modal?

The other one doesn't work. According to the docs this is the way you should do it.

angular.module('plunker', ['ui.bootstrap']);
var ModalDemoCtrl = function ($scope, $modal) {

    var modalInstance = $modal.open({
      templateUrl: 'myModalContent.html',
      controller: ModalInstanceCtrl,
      resolve: {
        test: function () {
          return 'test variable';
        }
      }
    });
};

var ModalInstanceCtrl = function ($scope, $modalInstance, test) {

  $scope.test = test;
};

See plunkr

VB.NET - If string contains "value1" or "value2"

 If strMyString.Tostring.Contains("Something") or strMyString.Tostring.Contains("Something2") Then


     End if

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

wordpress contactform7 textarea cols and rows change in smaller screens

Code will be As below.

[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->

[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->

[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->

[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->

For Details: https://contactform7.com/text-fields/

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

Try : java -version , then if you see java 11

try to delete with terminal : cd /Library/Java/JavaVirtualMachines rm -rf openjdk-11.0.1.jdk

if it doesn't try delete manually: 1) click on finder 2) go to folder 3) post /Library/Java/JavaVirtualMachines 4) delete java 11 .

then try java version and you will see : java version "1.8.0_191"

What are all the common ways to read a file in Ruby?

I usually do this:

open(path_in_string, &:read)

This will give you the whole text as a string object. It works only under Ruby 1.9.

Need to perform Wildcard (*,?, etc) search on a string using Regex

All upper code is not correct to the end.

This is because when searching zz*foo* or zz* you will not get correct results.

And if you search "abcd*" in "abcd" in TotalCommander will he find a abcd file so all upper code is wrong.

Here is the correct code.

public string WildcardToRegex(string pattern)
{             
    string result= Regex.Escape(pattern).
        Replace(@"\*", ".+?").
        Replace(@"\?", "."); 

    if (result.EndsWith(".+?"))
    {
        result = result.Remove(result.Length - 3, 3);
        result += ".*";
    }

    return result;
}

Hamcrest compare collections

Make sure that the Objects in your list have equals() defined on them. Then

assertThat(generatedList, is(equalTo(expectedList)));

works.

How to transfer data from JSP to servlet when submitting HTML form

Create a class which extends HttpServlet and put @WebServlet annotation on it containing the desired URL the servlet should listen on.

@WebServlet("/yourServletURL")
public class YourServlet extends HttpServlet {}

And just let <form action> point to this URL. I would also recommend to use POST method for non-idempotent requests. You should make sure that you have specified the name attribute of the HTML form input fields (<input>, <select>, <textarea> and <button>). This represents the HTTP request parameter name. Finally, you also need to make sure that the input fields of interest are enclosed inside the desired form and thus not outside.

Here are some examples of various HTML form input fields:

<form action="${pageContext.request.contextPath}/yourServletURL" method="post">
    <p>Normal text field.        
    <input type="text" name="name" /></p>

    <p>Secret text field.        
    <input type="password" name="pass" /></p>

    <p>Single-selection radiobuttons.        
    <input type="radio" name="gender" value="M" /> Male
    <input type="radio" name="gender" value="F" /> Female</p>

    <p>Single-selection checkbox.
    <input type="checkbox" name="agree" /> Agree?</p>

    <p>Multi-selection checkboxes.
    <input type="checkbox" name="role" value="USER" /> User
    <input type="checkbox" name="role" value="ADMIN" /> Admin</p>

    <p>Single-selection dropdown.
    <select name="countryCode">
        <option value="NL">Netherlands</option>
        <option value="US">United States</option>
    </select></p>

    <p>Multi-selection listbox.
    <select name="animalId" multiple="true" size="2">
        <option value="1">Cat</option>
        <option value="2">Dog</option>
    </select></p>

    <p>Text area.
    <textarea name="message"></textarea></p>

    <p>Submit button.
    <input type="submit" name="submit" value="submit" /></p>
</form>

Create a doPost() method in your servlet which grabs the submitted input values as request parameters keyed by the input field's name (not id!). You can use request.getParameter() to get submitted value from single-value fields and request.getParameterValues() to get submitted values from multi-value fields.

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String name = request.getParameter("name");
    String pass = request.getParameter("pass");
    String gender = request.getParameter("gender");
    boolean agree = request.getParameter("agree") != null;
    String[] roles = request.getParameterValues("role");
    String countryCode = request.getParameter("countryCode");
    String[] animalIds = request.getParameterValues("animalId");
    String message = request.getParameter("message");
    boolean submitButtonPressed = request.getParameter("submit") != null;
    // ...
}

Do if necessary some validation and finally persist it in the DB the usual JDBC/DAO way.

User user = new User(name, pass, roles);
userDAO.save(user);

See also:

How to retry after exception?

The more "functional" approach without using those ugly while loops:

def tryAgain(retries=0):
    if retries > 10: return
    try:
        # Do stuff
    except:
        retries+=1
        tryAgain(retries)

tryAgain()

How do I build JSON dynamically in javascript?

As myJSON is an object you can just set its properties, for example:

myJSON.list1 = ["1","2"];

If you dont know the name of the properties, you have to use the array access syntax:

myJSON['list'+listnum] = ["1","2"];

If you want to add an element to one of the properties, you can do;

myJSON.list1.push("3");

how to make a full screen div, and prevent size to be changed by content?

I use this approach for drawing a modal overlay.

.fullDiv { width:100%; height:100%; position:fixed }

I believe the distinction here is the use of position:fixed which may or may not be applicable to your use case.

I also add z-index:1000; background:rgba(50,50,50,.7);

Then, the modal content can live inside that div, and any content that was already on the page remains visible in the background but covered by the overlay fully while scrolling.

How to generate a unique hash code for string input in android...?

You can use this code for generating has code for a given string.

int hash = 7;
for (int i = 0; i < strlen; i++) {
    hash = hash*31 + charAt(i);
}

How do I make background-size work in IE?

Thanks to this post, my full css for cross browser happiness is:

<style>
    .backgroundpic {
        background-image: url('img/home.jpg');
        background-size: cover;
        filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
        src='img/home.jpg',
        sizingMethod='scale');
    }
</style>

It's been so long since I've worked on this piece of code, but I'd like to add for more browser compatibility I've appended this to my CSS for more browser compatibility:

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;

how to check the version of jar file?

You can filter version from the MANIFEST file using

unzip -p my.jar META-INF/MANIFEST.MF | grep 'Bundle-Version'

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

Warning about `$HTTP_RAW_POST_DATA` being deprecated

If you are using WAMP...

you should add or uncomment the property always_populate_raw_post_data in php.ini and set its value to -1. In my case php.ini is located in:

C:\wamp64\bin\php\php5.6.25\php.ini

..but if you are still getting the warning (as I was)

You should also set always_populate_raw_post_data = -1 in phpForApache.ini:

C:\wamp64\bin\php\php5.6.25\phpForApache.ini

If you can't find this file, open a browser window and go to:

http://localhost/?phpinfo=1

and look for the value of Loaded Configuration File key. In my case the php.ini used by WAMP is located in:

C:\wamp64\bin\apache\apache2.4.23\bin\php.ini (symlink to C:\wamp64\bin\php\php5.6.25\phpForApache.ini)

Finally restart WAMP (or click restart all services)

How to target the href to div

Put for div same name as in href target.

ex: <div name="link"> and <a href="#link">

How to call a method after a delay in Android

final Handler handler = new Handler(); 
Timer t = new Timer(); 
t.schedule(new TimerTask() { 
    public void run() { 
        handler.post(new Runnable() { 
            public void run() { 
                //DO SOME ACTIONS HERE , THIS ACTIONS WILL WILL EXECUTE AFTER 5 SECONDS...
            }
        }); 
    } 
}, 5000); 

Get random integer in range (x, y]?

Random generator = new Random(); 
int i = generator.nextInt(10) + 1;

Dataset - Vehicle make/model/year (free)

These guys have an API that will give the results. It's also free to use.

http://www.carqueryapi.com

Note: they also provide data source download in xls or sql format at a premium price. but these data also provides technical specifications for all the make model and trim options.

Limit number of characters allowed in form input text field

<input type="text" maxlength="5">

the maximum amount of letters that can be in the input is 5.

how to dynamically add options to an existing select in vanilla javascript

This tutorial shows exactly what you need to do: Add options to an HTML select box with javascript

Basically:

 daySelect = document.getElementById('daySelect');
 daySelect.options[daySelect.options.length] = new Option('Text 1', 'Value1');

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Your PersonSheets has a property int Id, Id isn't in the post, so modelbinding fails. Make Id nullable (int?) or send atleast Id = 0 with the POst .

Center the content inside a column in Bootstrap 4

Really simple answer in bootstrap 4, change this

<row>
  ...
</row>

to this

<row justify-content-center>
  ...
</row>

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

Where it is documented:

From the API documentation under the has_many association in "Module ActiveRecord::Associations::ClassMethods"

collection.build(attributes = {}, …) Returns one or more new objects of the collection type that have been instantiated with attributes and linked to this object through a foreign key, but have not yet been saved. Note: This only works if an associated object already exists, not if it‘s nil!

The answer to building in the opposite direction is a slightly altered syntax. In your example with the dogs,

Class Dog
   has_many :tags
   belongs_to :person
end

Class Person
  has_many :dogs
end

d = Dog.new
d.build_person(:attributes => "go", :here => "like normal")

or even

t = Tag.new
t.build_dog(:name => "Rover", :breed => "Maltese")

You can also use create_dog to have it saved instantly (much like the corresponding "create" method you can call on the collection)

How is rails smart enough? It's magic (or more accurately, I just don't know, would love to find out!)

What's the best way to convert a number to a string in JavaScript?

Explicit conversions are very clear to someone that's new to the language. Using type coercion, as others have suggested, leads to ambiguity if a developer is not aware of the coercion rules. Ultimately developer time is more costly than CPU time, so I'd optimize for the former at the cost of the latter. That being said, in this case the difference is likely negligible, but if not I'm sure there are some decent JavaScript compressors that will optimize this sort of thing.

So, for the above reasons I'd go with: n.toString() or String(n). String(n) is probably a better choice because it won't fail if n is null or undefined.

How to call another components function in angular2

If com1 and com2 are siblings you can use

@component({
  selector:'com1',
})
export class com1{
  function1(){...}
}

com2 emits an event using an EventEmitter

@component({
  selector:'com2',
  template: `<button (click)="function2()">click</button>`
)
export class com2{
  @Output() myEvent = new EventEmitter();
  function2(){...
    this.myEvent.emit(null)
  }
}

Here the parent component adds an event binding to listen to myEvent events and then calls com1.function1() when such an event happens. #com1 is a template variable that allows to refer to this element from elsewhere in the template. We use this to make function1() the event handler for myEvent of com2:

@component({
  selector:'parent',
  template: `<com1 #com1></com1><com2 (myEvent)="com1.function1()"></com2>`
)
export class com2{
}

For other options to communicate between components see also component-interaction

Is there a "standard" format for command line/shell help text?

We are running Linux, a mostly POSIX-compliant OS. POSIX standards it should be: Utility Argument Syntax.

  • An option is a hyphen followed by a single alphanumeric character, like this: -o.
  • An option may require an argument (which must appear immediately after the option); for example, -o argument or -oargument.
  • Options that do not require arguments can be grouped after a hyphen, so, for example, -lst is equivalent to -t -l -s.
  • Options can appear in any order; thus -lst is equivalent to -tls.
  • Options can appear multiple times.
  • Options precede other nonoption arguments: -lst nonoption.
  • The -- argument terminates options.
  • The - option is typically used to represent one of the standard input streams.

ERROR 1064 (42000): You have an error in your SQL syntax;

Try this:

Use back-ticks for NAME

CREATE TABLE `teachers` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `addr` varchar(255) NOT NULL,
  `phone` int(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

Array Index Out of Bounds Exception (Java)

import java.io.*;
import java.util.Scanner;
class ar1 {
    public static void main(String[] args) {
        //Scanner sc=new Scanner(System.in);
        int[] a={10,20,30,40,12,32};
        int bi=0,sm=0;
        //bi=sc.nextInt();
        //sm=sc.nextInt();
        for(int i=0;i<=a.length-1;i++) {
            if(a[i]>a[i+1]) 
                bi=a[i];

            if(a[i]<a[i+1])
                sm=a[i];
        }
        System.out.println("big"+bi+"small"+sm);
    }
}

What is %0|%0 and how does it work?

It's a logic bomb, it keeps recreating itself and takes up all your CPU resources. It overloads your computer with too many processes and it forces it to shut down. If you make a batch file with this in it and start it you can end it using taskmgr. You have to do this pretty quickly or your computer will be too slow to do anything.

css transition opacity fade background

Wrap your image with a span element with a black background.

_x000D_
_x000D_
.img-wrapper {
  display: inline-block;
  background: #000;
}

.item-fade {
  vertical-align: top;
  transition: opacity 0.3s;
  -webkit-transition: opacity 0.3s;
  opacity: 1;
}

.item-fade:hover {
  opacity: 0.2;
}
_x000D_
<span class="img-wrapper">
   <img class="item-fade" src="http://placehold.it/100x100/cf5" />
</span>
_x000D_
_x000D_
_x000D_

Getting rid of bullet points from <ul>

I had an identical problem.

The solution was that the bullet was added via a background image, NOT via list-style-type. A quick 'background: none' and Bob's your uncle!

Change onclick action with a Javascript function

Your code is calling the function and assigning the return value to onClick, also it should be 'onclick'. This is how it should look.

document.getElementById("a").onclick = Bar;

Looking at your other code you probably want to do something like this:

document.getElementById(id+"Button").onclick = function() { HideError(id); }

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

This code works for me:

import groovy.io.FileType

def list = []

def dir = new File("path_to_parent_dir")
dir.eachFileRecurse (FileType.FILES) { file ->
  list << file
}

Afterwards the list variable contains all files (java.io.File) of the given directory and its subdirectories:

list.each {
  println it.path
}

Find PHP version on windows command line

It is most likely that php is not in your specified path.

Try to issue the php command with the full path, for example:

C:\> "C:\Program Files\php\php.exe" -v

Please note, that this is just an example, your php installation might be in a different directory.

PHP exec() vs system() vs passthru()

It really all comes down to how you want to handle output that the command might return and whether you want your PHP script to wait for the callee program to finish or not.

  • exec executes a command and passes output to the caller (or returns it in an optional variable).

  • passthru is similar to the exec() function in that it executes a command . This function should be used in place of exec() or system() when the output from the Unix command is binary data which needs to be passed directly back to the browser.

  • system executes an external program and displays the output, but only the last line.

If you need to execute a command and have all the data from the command passed directly back without any interference, use the passthru() function.

PHP date add 5 year to current date

Modifying dates based on this post
strtotime() is really powerful and allows you to modify/transform dates easily with it’s relative expressions too:

Procedural

    $dateString = '2011-05-01 09:22:34';
    $t = strtotime($dateString);
    $t2 = strtotime('-3 days', $t);
    echo date('r', $t2) . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100

DateTime

    $dateString = '2011-05-01 09:22:34';
    $dt = new DateTime($dateString);
    $dt->modify('-3 days');
    echo $dt->format('r') . PHP_EOL; // returns: Thu, 28 Apr 2011 09:22:34 +0100

The stuff you can throw at strtotime() is quite surprising and very human readable. Have a look at this example looking for Tuesday next week.

Procedural

    $t = strtotime("Tuesday next week");
    echo date('r', $t) . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100

DateTime

    $dt = new DateTime("Tuesday next week");
    echo $dt->format('r') . PHP_EOL; // returns: Tue, 10 May 2011 00:00:00 +0100

Note that these examples above are being returned relative to the time now. The full list of time formats that strtotime() and the DateTime constructor takes are listed on the PHP Supported Date and Time Formats page.

Another example, suitable for your case could be: based on this post

    <?php
    //How to get the day 3 days from now:
    $today = date("j");
    $thisMonth = date("n");
    $thisYear = date("Y");
    echo date("F j Y", mktime(0,0,0, $thisMonth, $today+3, $thisYear)); 

    //1 week from now:
    list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
    echo date("F j Y", mktime(0,0,0, $thisMonth, $today+7, $thisYear));

    //4 months from now:
    list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
    echo date("F j Y", mktime(0,0,0, $thisMonth+4, $today, $thisYear)); 

    //3 years, 2 months and 35 days from now:
    list($today,$thisMonth,$thisYear) = explode(" ", date("j n Y"));
    echo date("F j Y", mktime(0,0,0, $thisMonth+2, $today+35, $thisYear+3));
    ?>

Add a UIView above all, even the navigation bar

In Swift 4.2 and Xcode 10

var spinnerView: UIView? //This is your view

spinnerView = UIView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: UIScreen.main.bounds.size.height))
//Based on your requirement change width and height like self.view.bounds.size.width
spinnerView?.backgroundColor = UIColor.black.withAlphaComponent(0.6)
//        self.view.addSubview(spinnerView)
let currentWindow: UIWindow? = UIApplication.shared.keyWindow
currentWindow?.addSubview(spinnerView!)

In Objective C

UIView *spinnerView;//This is your view

self.spinnerView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, UIScreen.mainScreen.bounds.size.width, UIScreen.mainScreen.bounds.size.height)];  
//Based on your requirement change width and height like self.view.bounds.size.width
self.spinnerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.6];
// [self.view addSubview:self.spinnerView];
UIWindow *currentWindow = [UIApplication sharedApplication].keyWindow;
[currentWindow addSubview:self.spinnerView];

This can work either Portrait OR Landscape mode only.

One more simple code is:

yourViewName.layer.zPosition = 1//Change you view name

Why do many examples use `fig, ax = plt.subplots()` in Matplotlib/pyplot/python

Just a supplement here.

The following question is that what if I want more subplots in the figure?

As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2) to set a group of subplots with grid(2,2) in one figure object.

Then as we know, the fig, ax = plt.subplots() returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2) firstly.

ValueError: not enough values to unpack (expected 4, got 2)

It raises a error, but no worry, because we now see that plt.subplots() actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.

So let's try this again:

fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)

and check the type:

type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>

Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:

fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)

So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.

Hope this would be helpful for you.

Spark SQL: apply aggregate functions to a list of columns

Current answers are perfectly correct on how to create the aggregations, but none actually address the column alias/renaming that is also requested in the question.

Typically, this is how I handle this case:

val dimensionFields = List("col1")
val metrics = List("col2", "col3", "col4")
val columnOfInterests = dimensions ++ metrics

val df = spark.read.table("some_table"). 
    .select(columnOfInterests.map(c => col(c)):_*)
    .groupBy(dimensions.map(d => col(d)): _*)
    .agg(metrics.map( m => m -> "sum").toMap)
    .toDF(columnOfInterests:_*)    // that's the interesting part

The last line essentially renames every columns of the aggregated dataframe to the original fields, essentially changing sum(col2) and sum(col3) to simply col2 and col3.

Count all duplicates of each value

SELECT number, COUNT(*)
    FROM YourTable
    GROUP BY number
    ORDER BY number

Refresh or force redraw the fragment

To solve the problem, I use this:

Fragment frg = null;
frg = getFragmentManager().findFragmentByTag("Feedback");
final android.support.v4.app.FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.detach(frg);
ft.attach(frg);
ft.commit();

How to get CPU temperature?

It's depends on if your computer support WMI. My computer can't run this WMI demo too.

But I successfully get the CPU temperature via Open Hardware Monitor. Add the Openhardwaremonitor reference in Visual Studio. It's easier. Try this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using OpenHardwareMonitor.Hardware;
namespace Get_CPU_Temp5
{
   class Program
   {
       public class UpdateVisitor : IVisitor
       {
           public void VisitComputer(IComputer computer)
           {
               computer.Traverse(this);
           }
           public void VisitHardware(IHardware hardware)
           {
               hardware.Update();
               foreach (IHardware subHardware in hardware.SubHardware) subHardware.Accept(this);
           }
           public void VisitSensor(ISensor sensor) { }
           public void VisitParameter(IParameter parameter) { }
       }
       static void GetSystemInfo()
       {
           UpdateVisitor updateVisitor = new UpdateVisitor();
           Computer computer = new Computer();
           computer.Open();
           computer.CPUEnabled = true;
           computer.Accept(updateVisitor);
           for (int i = 0; i < computer.Hardware.Length; i++)
           {
               if (computer.Hardware[i].HardwareType == HardwareType.CPU)
               {
                   for (int j = 0; j < computer.Hardware[i].Sensors.Length; j++)
                   {
                       if (computer.Hardware[i].Sensors[j].SensorType == SensorType.Temperature)
                               Console.WriteLine(computer.Hardware[i].Sensors[j].Name + ":" + computer.Hardware[i].Sensors[j].Value.ToString() + "\r");
                   }
               }
           }
           computer.Close();
       }
       static void Main(string[] args)
       {
           while (true)
           {
               GetSystemInfo();
           }
       }
   }
}

You need to run this demo as administrator.

You can see the tutorial here: http://www.lattepanda.com/topic-f11t3004.html

relative path in require_once doesn't work

I just came across this same problem, where it was all working fine, up until the point I had an includes within another includes.

require_once '../script/pdocrud.php';  //This worked fine up until I had an includes within another includes, then I got this error:
Fatal error: require_once() [function.require]: Failed opening required '../script/pdocrud.php' (include_path='.:/opt/php52/lib/php')

Solution 1. (undesired hardcoding of my public html folder name, but it works):

require_once $_SERVER["DOCUMENT_ROOT"] . '/orders.simplystyles.com/script/pdocrud.php';

Solution 2. (undesired comment above about DIR only working since php 5.3, but it works):

require_once __DIR__. '/../script/pdocrud.php';

Solution 3. (I can't see any downsides, and it works perfectly in my php 5.3):

require_once dirname(__FILE__). '/../script/pdocrud.php';

How to Return partial view of another controller by controller?

Normally the views belong with a specific matching controller that supports its data requirements, or the view belongs in the Views/Shared folder if shared between controllers (hence the name).

"Answer" (but not recommended - see below):

You can refer to views/partial views from another controller, by specifying the full path (including extension) like:

return PartialView("~/views/ABC/XXX.cshtml", zyxmodel);

or a relative path (no extension), based on the answer by @Max Toro

return PartialView("../ABC/XXX", zyxmodel);

BUT THIS IS NOT A GOOD IDEA ANYWAY

*Note: These are the only two syntax that work. not ABC\\XXX or ABC/XXX or any other variation as those are all relative paths and do not find a match.

Better Alternatives:

You can use Html.Renderpartial in your view instead, but it requires the extension as well:

Html.RenderPartial("~/Views/ControllerName/ViewName.cshtml", modeldata);

Use @Html.Partial for inline Razor syntax:

@Html.Partial("~/Views/ControllerName/ViewName.cshtml", modeldata)

You can use the ../controller/view syntax with no extension (again credit to @Max Toro):

@Html.Partial("../ControllerName/ViewName", modeldata)

Note: Apparently RenderPartial is slightly faster than Partial, but that is not important.

If you want to actually call the other controller, use:

@Html.Action("action", "controller", parameters)

Recommended solution: @Html.Action

My personal preference is to use @Html.Action as it allows each controller to manage its own views, rather than cross-referencing views from other controllers (which leads to a large spaghetti-like mess).

You would normally pass just the required key values (like any other view) e.g. for your example:

@Html.Action("XXX", "ABC", new {id = model.xyzId })

This will execute the ABC.XXX action and render the result in-place. This allows the views and controllers to remain separately self-contained (i.e. reusable).

Update Sep 2014:

I have just hit a situation where I could not use @Html.Action, but needed to create a view path based on a action and controller names. To that end I added this simple View extension method to UrlHelper so you can say return PartialView(Url.View("actionName", "controllerName"), modelData):

public static class UrlHelperExtension
{
    /// <summary>
    /// Return a view path based on an action name and controller name
    /// </summary>
    /// <param name="url">Context for extension method</param>
    /// <param name="action">Action name</param>
    /// <param name="controller">Controller name</param>
    /// <returns>A string in the form "~/views/{controller}/{action}.cshtml</returns>
    public static string View(this UrlHelper url, string action, string controller)
    {
        return string.Format("~/Views/{1}/{0}.cshtml", action, controller);
    }
}

How to replace <span style="font-weight: bold;">foo</span> by <strong>foo</strong> using PHP and regex?

$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);

Note: only work for your example.

The simplest way to resize an UIImage?

The simplest way is to set the frame of your UIImageView and set the contentMode to one of the resizing options.

Or you can use this utility method, if you actually need to resize an image:

+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize {
    //UIGraphicsBeginImageContext(newSize);
    // In next line, pass 0.0 to use the current device's pixel scaling factor (and thus account for Retina resolution).
    // Pass 1.0 to force exact pixel size.
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();    
    UIGraphicsEndImageContext();
    return newImage;
}

Example usage:

#import "MYUtil.h"
…
UIImage *myIcon = [MYUtil imageWithImage:myUIImageInstance scaledToSize:CGSizeMake(20, 20)];

The way to check a HDFS directory's size?

% of used space on Hadoop cluster
sudo -u hdfs hadoop fs –df

Capacity under specific folder:
sudo -u hdfs hadoop fs -du -h /user

Using 24 hour time in bootstrap timepicker

The below code is correct answer for me.

 $('#datetimepicker6').datetimepicker({
                    format : 'YYYY-MM-DD HH:mm'
                });

"unrecognized import path" with go get

The issues are relating to an invalid GOROOT.

I think you installed Go in /usr/local/go.
So change your GOROOT path to the value of /usr/local/go/bin.

It seems that you meant to have your workspace (GOPATH) located at /home/me/go.

This might fix your problem.
Add this to the bottom of your bash profile, located here => $HOME/.profile

export GOROOT=/usr/local/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin

Make sure to remove the old references of GOROOT.

Then try installing web.go again.

If that doesn't work, then have Ubuntu install Go for you.

sudo apt-get install golang

Video tutorial: http://www.youtube.com/watch?v=2PATwIfO5ag

How to simulate a mouse click using JavaScript?

From the Mozilla Developer Network (MDN) documentation, HTMLElement.click() is what you're looking for. You can find out more events here.

Skip first entry in for loop in python?

To skip the first element in Python you can simply write

for car in cars[1:]:
    # Do What Ever you want

or to skip the last elem

for car in cars[:-1]:
    # Do What Ever you want

You can use this concept for any sequence.

Android Studio Could not initialize class org.codehaus.groovy.runtime.InvokerHelper

When you upgrade to the latest version of the gradle in the gradle-wrapper.properties file i.e. distributionUrl=https\://services.gradle.org/distributions/gradle-6.6.1-bin.zip please do not forget to change the gradle version in the build.gradle file as well

wrapper {
    gradleVersion = '6.6.1'
}

how to kill the tty in unix

you do not need to know pts number, just type:

ps all | grep bash

then:

kill pid1 pid2 pid3 ...

Display a tooltip over a button using Windows Forms

Based on DaveK's answer, I created a control extension:

public static void SetToolTip(this Control control, string txt)
{
    new ToolTip().SetToolTip(control, txt);
}

Then you can set the tooltip for any control with a single line:

this.MyButton.SetToolTip("Hello world");

CSS technique for a horizontal line with words in the middle

Ok, this one is more complicated but it works in everything but IE<8

<div><span>text TEXT</span></div>

div {
    text-align: center;
    position: relative;
}
span {
    display: inline-block;    
}
span:before,
span:after {
    border-top: 1px solid black;
    display: block;
    height: 1px;
    content: " ";
    width: 40%;
    position: absolute;
    left: 0;
    top: 1.2em;
}
span:after {
   right: 0;  
   left: auto; 
}

The :before and :after elements are positioned absolutely so we can pull one to the left and one to the right. Also, the width (40% in this case) is very dependent of the width of the text inside.. have to think about a solution for that. At least the top: 1.2em makes sure the lines stay more or less in the center of the text even if you have different font size.

It does seem to work well though: http://jsfiddle.net/tUGrf/3/

How to call javascript from a href?

The proper way to invoke javascript code when clicking a link would be to add an onclick handler:

<a href="#" onclick="myFunction()">LinkText</a>

Although an even "more proper" way would be to get it out of the html all together and add the handler with another javascript when the dom is loaded.

How to temporarily disable a click handler in jQuery?

You can unbind your handler with .off, but there's a caveat; if you're doing this just prevent the handler from being triggered again while it's already running, you need to defer rebinding the handler.

For example, consider this code, which uses a 5-second hot sleep to simulate something synchronous and computationally expensive being done from within the handler (like heavy DOM manipulation, say):

<button id="foo">Click Me!</div>
<script>
    function waitForFiveSeconds() {
        var startTime = new Date();
        while (new Date() - startTime < 5000) {}
    }
    $('#foo').click(function handler() {
        // BAD CODE, DON'T COPY AND PASTE ME!
        $('#foo').off('click');
        console.log('Hello, World!');
        waitForFiveSeconds();
        $('#foo').click(handler);
    });
</script>

This won't work. As you can see if you try it out in this JSFiddle, if you click the button while the handler is already executing, the handler will execute a second time once the first execution finishes. What's more, at least in Chrome and Firefox, this would be true even if you didn't use jQuery and used addEventListener and removeEventListener to add and remove the handler instead. The browser executes the handler after the first click, unbinding and rebinding the handler, and then handles the second click and checks whether there's a click handler to execute.

To get around this, you need to defer rebinding of the handler using setTimeout, so that clicks that happen while the first handler is executing will be processed before you reattach the handler.

<button id="foo">Click Me!</div>
<script>
    function waitForFiveSeconds() {
        var startTime = new Date();
        while (new Date() - startTime < 5000) {}
    }
    $('#foo').click(function handler() {
        $('#foo').off('click');
        console.log('Hello, World!');
        waitForFiveSeconds();

        // Defer rebinding the handler, so that any clicks that happened while
        // it was unbound get processed first.
        setTimeout(function () {
            $('#foo').click(handler);
        }, 0);
    });
</script>

You can see this in action at this modified JSFiddle.

Naturally, this is unnecessary if what you're doing in your handler is already asynchronous, since then you're already yielding control to the browser and letting it flush all the click events before you rebind your handler. For instance, code like this will work fine without a setTimeout call:

<button id="foo">Save Stuff</div>
<script>
    $('#foo').click(function handler() {
        $('#foo').off('click');
        $.post( "/some_api/save_stuff", function() {
            $('#foo').click(handler);
        });
    });
</script>

What does a circled plus mean?

People are saying that the symbol doesn't mean addition. This is true, but doesn't explain why a plus-like symbol is used for something that isn't addition.

The answer is that for modulo addition of 1-bit values, 0+0 == 1+1 == 0, and 0+1 == 1+0 == 1. Those are the same values as XOR.

So, plus in a circle in this context means "bitwise addition modulo-2". Which is, as everyone says, XOR for integers. It's common in mathematics to use plus in a circle for an operation which is a sort of addition, but isn't regular integer addition.

Get value from a string after a special character

Assuming you have your hidden input in a jQuery object $myHidden, you then use JavaScript (not jQuery) to get the part after ?:

var myVal = $myHidden.val ();
var tmp = myVal.substr ( myVal.indexOf ( '?' ) + 1 ); // tmp now contains whatever is after ?

SQL Server: How to use UNION with two queries that BOTH have a WHERE clause?

declare @T1 table(ID int, ReceivedDate datetime, [type] varchar(10))
declare @T2 table(ID int, ReceivedDate datetime, [type] varchar(10))

insert into @T1 values(1, '20010101', '1')
insert into @T1 values(2, '20010102', '1')
insert into @T1 values(3, '20010103', '1')

insert into @T2 values(10, '20010101', '2')
insert into @T2 values(20, '20010102', '2')
insert into @T2 values(30, '20010103', '2')

;with cte1 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T1
  where [type] = '1'
),
cte2 as
(
  select *,
    row_number() over(order by ReceivedDate desc) as rn
  from @T2
  where [type] = '2'
)
select *
from cte1
where rn <= 2
union all
select *
from cte2
where rn <= 2

MySQL - SELECT * INTO OUTFILE LOCAL ?

You can achieve what you want with the mysql console with the -s (--silent) option passed in.

It's probably a good idea to also pass in the -r (--raw) option so that special characters don't get escaped. You can use this to pipe queries like you're wanting.

mysql -u username -h hostname -p -s -r -e "select concat('this',' ','works')"

EDIT: Also, if you want to remove the column name from your output, just add another -s (mysql -ss -r etc.)

How to compile a 64-bit application using Visual C++ 2010 Express?

64-bit tools are not available on Visual C++ Express by default. To enable 64-bit tools on Visual C++ Express, install the Windows Software Development Kit (SDK) in addition to Visual C++ Express. Otherwise, an error occurs when you attempt to configure a project to target a 64-bit platform using Visual C++ Express.

How to: Configure Visual C++ Projects to Target 64-Bit Platforms

Ref: http://msdn.microsoft.com/en-us/library/9yb4317s.aspx

How to handle calendar TimeZones using Java?

public static Calendar convertToGmt(Calendar cal) {

    Date date = cal.getTime();
    TimeZone tz = cal.getTimeZone();

    log.debug("input calendar has date [" + date + "]");

    //Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT 
    long msFromEpochGmt = date.getTime();

    //gives you the current offset in ms from GMT at the current date
    int offsetFromUTC = tz.getOffset(msFromEpochGmt);
    log.debug("offset is " + offsetFromUTC);

    //create a new calendar in GMT timezone, set to this date and add the offset
    Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
    gmtCal.setTime(date);
    gmtCal.add(Calendar.MILLISECOND, offsetFromUTC);

    log.debug("Created GMT cal with date [" + gmtCal.getTime() + "]");

    return gmtCal;
}

Here's the output if I pass the current time ("12:09:05 EDT" from Calendar.getInstance()) in:

DEBUG - input calendar has date [Thu Oct 23 12:09:05 EDT 2008]
DEBUG - offset is -14400000
DEBUG - Created GMT cal with date [Thu Oct 23 08:09:05 EDT 2008]

12:09:05 GMT is 8:09:05 EDT.

The confusing part here is that Calendar.getTime() returns you a Date in your current timezone, and also that there is no method to modify the timezone of a calendar and have the underlying date rolled also. Depending on what type of parameter your web service takes, your may just want to have the WS deal in terms of milliseconds from epoch.

ReferenceError: variable is not defined

Got the error (in the function init) with the following code ;

"use strict" ;

var hdr ;

function init(){ // called on load
    hdr = document.getElementById("hdr");
}

... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30

The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1

The fix for this was to change

var hdr ;

to

var hdr = null ;

How to use if-else logic in Java 8 stream forEach

In most cases, when you find yourself using forEach on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.

Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Maps and Lists, but no out of-the-box collector for combining two different collectors, based on a predicate.

Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as

Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
    .collect(conditional(entry -> entry.getValue() != null,
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
            Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;

But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:

List<KeyType> myList=animalMap.entrySet().stream()
    .filter(pair -> pair.getValue() == null)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

animalMap.keySet().removeAll(myList);

Note that you can remove mappings to null even without having the list of the other keys:

animalMap.values().removeIf(Objects::isNull);

or

animalMap.values().removeAll(Collections.singleton(null));

If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy is going into the right direction, but you may simplify it:

Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
    .collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());

The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

Getting the .Text value from a TextBox

if(sender is TextBox) {
 var text = (sender as TextBox).Text;
}

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

This is a known bug on Linux Debian. I solved using the create_tables.sql in the official package and changing pma_ with pma__ inside /etc/phpmyadmin/config.inc.php

How to change btn color in Bootstrap

2019 Update for Bootstrap 4

Now that Bootstrap 4 uses SASS, you can easily change the primary button color using the button-variant mixins:

$mynewcolor:#77cccc;

.btn-primary {
    @include button-variant($mynewcolor, darken($mynewcolor, 7.5%), darken($mynewcolor, 10%), lighten($mynewcolor,5%), lighten($mynewcolor, 10%), darken($mynewcolor,30%));
}
    
.btn-outline-primary {
    @include button-outline-variant($mynewcolor, #222222, lighten($mynewcolor,5%), $mynewcolor);
}

https://codeply.com/go/2bHYxYSC0n (SASS demo)

This SASS compiles into the following CSS...

.btn-primary {
    color: #212529;
    background-color: #7cc;
    border-color: #5bc2c2
}

.btn-primary:hover {
    color: #212529;
    background-color: #52bebe;
    border-color: #8ad3d3
}

.btn-primary:focus,
.btn-primary.focus {
    box-shadow: 0 0 0 .2rem rgba(91, 194, 194, 0.5)
}

.btn-primary.disabled,
.btn-primary:disabled {
    color: #212529;
    background-color: #7cc;
    border-color: #5bc2c2
}

.btn-primary:not(:disabled):not(.disabled):active,
.btn-primary:not(:disabled):not(.disabled).active,
.show>.btn-primary.dropdown-toggle {
    color: #212529;
    background-color: #9cdada;
    border-color: #2e7c7c
}

.btn-primary:not(:disabled):not(.disabled):active:focus,
.btn-primary:not(:disabled):not(.disabled).active:focus,
.show>.btn-primary.dropdown-toggle:focus {
    box-shadow: 0 0 0 .2rem rgba(91, 194, 194, 0.5)
}

.btn-outline-primary {
    color: #7cc;
    background-color: transparent;
    background-image: none;
    border-color: #7cc
}

.btn-outline-primary:hover {
    color: #222;
    background-color: #8ad3d3;
    border-color: #7cc
}

.btn-outline-primary:focus,
.btn-outline-primary.focus {
    box-shadow: 0 0 0 .2rem rgba(119, 204, 204, 0.5)
}

.btn-outline-primary.disabled,
.btn-outline-primary:disabled {
    color: #7cc;
    background-color: transparent
}

.btn-outline-primary:not(:disabled):not(.disabled):active,
.btn-outline-primary:not(:disabled):not(.disabled).active,
.show>.btn-outline-primary.dropdown-toggle {
    color: #212529;
    background-color: #8ad3d3;
    border-color: #7cc
}

.btn-outline-primary:not(:disabled):not(.disabled):active:focus,
.btn-outline-primary:not(:disabled):not(.disabled).active:focus,
.show>.btn-outline-primary.dropdown-toggle:focus {
    box-shadow: 0 0 0 .2rem rgba(119, 204, 204, 0.5)
}

https://codeply.com/go/lD3tUE01lo (CSS demo)


To change the primary color for all classes see: Customizing Bootstrap CSS template and How to change the bootstrap primary color?

Converting newline formatting from Mac to Windows

This is an improved version of Anne's answer -- if you use perl, you can do the edit on the file 'in-place' rather than generating a new file:

perl -pi -e 's/\r\n|\n|\r/\r\n/g' file-to-convert  # Convert to DOS
perl -pi -e 's/\r\n|\n|\r/\n/g'   file-to-convert  # Convert to UNIX

Trigger insert old values- values that was updated

ALTER trigger ETU on Employee FOR UPDATE AS insert into Log (EmployeeId, LogDate, OldName) select EmployeeId, getdate(), name from deleted go

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

You are looking for this solution :

StaticDataTableViewController 2.0

https://github.com/xelvenone/StaticDataTableViewController

which can show/hide/reload any static cell(s) with or without animation!

[self cell:self.outletToMyStaticCell1 setHidden:hide]; 
[self cell:self.outletToMyStaticCell2 setHidden:hide]; 
[self reloadDataAnimated:YES];

Note to always use only (reloadDataAnimated:YES/NO) (dont call [self.tableView reloadData] directly)

This doesn't use the hacky solution with setting height to 0 and allows you to animate the change and hide whole sections

HTML image bottom alignment inside DIV container

Flexboxes can accomplish this by using align-items: flex-end; with display: flex; or display: inline-flex;

div#imageContainer {
    height: 160px;  
    align-items: flex-end;
    display: flex;

    /* This is the default value, so you only need to explicitly set it if it's already being set to something else elsewhere. */
    /*flex-direction: row;*/
}

JSFiddle example

CSS-Tricks has a good guide for flexboxes

Change value of variable with dplyr

We can use replace to change the values in 'mpg' to NA that corresponds to cyl==4.

mtcars %>%
     mutate(mpg=replace(mpg, cyl==4, NA)) %>%
     as.data.frame()

Regex to extract URLs from href attribute in HTML with Python

import re

url = '<p>Hello World</p><a href="http://example.com">More Examples</a><a href="http://example2.com">Even More Examples</a>'

urls = re.findall('https?://(?:[-\w.]|(?:%[\da-fA-F]{2}))+', url)

>>> print urls
['http://example.com', 'http://example2.com']

How do I configure Apache 2 to run Perl CGI scripts?

(Google search brought me to this question even though I did not ask for perl)

I had a problem with running scripts (albeit bash not perl). Apache had a config of ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/ however Apache error log showed File does not exist: /var/www/cgi-bin/test.html.

Tried putting the script in both /usr/lib/cgi-bin/ and /var/www/cgi-bin/ but neither were working.

After a prolonged googling session what cracked it for me was sudo a2enmod cgi and everything fell into place using /usr/lib/cgi-bin/.

VS2010 command prompt gives error: Cannot determine the location of the VS Common Tools folder

I had this not too long ago as a result of registry editing being blocked by a group policy.

The specific problem is that reg is denied access to the registry. I solved this by replicating the 'reg.exe' using Microsoft.Win32.Registry in a C# program, and then substituting all calls to reg, with my alternative program. You need to update:

  • VCVarsQuery.bat
  • VsDevCmd.bat
  • VsVars32.bat

In the %VSxxxCOMNTOOLS% folder (usually resolves to something like C:\Program Files (x86)\Microsoft Visual Studio XX.X\Common7\Tools)

    static int Main(string[] args)
    {
        try
        {
            var targetRegistry = args[1].Substring(0, 4);
            var targetKey = args[1].Substring(5);

            string targetValue = null;
            if (args[2].ToLower() == "/v")
            {
                targetValue = args[3];
            }
            else
            {
                return 1;
            }

            var hkey = targetRegistry == "HKLM" ? Registry.LocalMachine : Registry.CurrentUser;
            var key = hkey.OpenSubKey(targetKey);



            var result = key.GetValue(targetValue);
            Console.WriteLine();
            Console.WriteLine(key.Name);
            Console.WriteLine("    {0}    REG_SZ    {2}", targetValue, key.GetValueKind(targetValue), result);
            Console.WriteLine();
            Console.WriteLine();

            return 0;
        }
        catch
        {
            return 1;
        }
    }

In cases like this, you can also use my alternative reg implementation here.

Password encryption/decryption code in .NET

 string clearText = txtPassword.Text;
        string EncryptionKey = "MAKV2SPBNI99212";
        byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                clearText = Convert.ToBase64String(ms.ToArray());
            }
        }

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

For everyone who is encountering this and wants to accept the risk to test it, there is a solution: go to Incognito mode in Chrome and you'll be able to open "Advanced" and click "Proceed to some.url".

This can be helpful if you need to check some website which you are maintaining yourself and just testing as a developer (and when you don't yet have proper development certificate configured).

Of course this is NOT FOR PEOPLE using a website in production where this error indicates that there is a problem with website security.

Angular ngClass and click event for toggling class

ngClass should be wrapped in square brackets as this is a property binding. Try this:

<div class="my_class" (click)="clickEvent($event)"  [ngClass]="{'active': toggle}">                
     Some content
</div>

In your component:

     //define the toogle property
     private toggle : boolean = false;

    //define your method
    clickEvent(event){
       //if you just want to toggle the class; change toggle variable.
       this.toggle = !this.toggle;       
    }

Hope that helps.

std::string formatting like sprintf

_return.desc = (boost::format("fail to detect. cv_result = %d") % st_result).str();

C/C++ check if one bit is set in, i.e. int variable

You could "simulate" shifting and masking: if((0x5e/(2*2*2))%2) ...

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

The only solution I have found is not to set the index to a previous frame and wait (then OpenCV stops reading frames, anyway), but to initialize the capture one more time. So, it looks like this:

cap = cv2.VideoCapture(camera_url)
while True:
    ret, frame = cap.read()

    if not ret:
        cap = cv.VideoCapture(camera_url)
        continue

    # do your processing here

And it works perfectly!

"git checkout <commit id>" is changing branch to "no branch"

By checking out to one of the commits in the history you are moving your git into so called 'detached state', which looks like is not what you want. Use this single command to create a new branch on one of the commits from the history:

git checkout -b <new_branch_name> <SHA1>

Can I have H2 autocreate a schema in an in-memory database?

"By default, when an application calls DriverManager.getConnection(url, ...) and the database specified in the URL does not yet exist, a new (empty) database is created."—H2 Database.

Addendum: @Thomas Mueller shows how to Execute SQL on Connection, but I sometimes just create and populate in the code, as suggested below.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/** @see http://stackoverflow.com/questions/5225700 */
public class H2MemTest {

    public static void main(String[] args) throws Exception {
        Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
        Statement st = conn.createStatement();
        st.execute("create table customer(id integer, name varchar(10))");
        st.execute("insert into customer values (1, 'Thomas')");
        Statement stmt = conn.createStatement();
        ResultSet rset = stmt.executeQuery("select name from customer");
        while (rset.next()) {
            String name = rset.getString(1);
            System.out.println(name);
        }
    }
}

Why is printing "B" dramatically slower than printing "#"?

Pure speculation is that you're using a terminal that attempts to do word-wrapping rather than character-wrapping, and treats B as a word character but # as a non-word character. So when it reaches the end of a line and searches for a place to break the line, it sees a # almost immediately and happily breaks there; whereas with the B, it has to keep searching for longer, and may have more text to wrap (which may be expensive on some terminals, e.g., outputting backspaces, then outputting spaces to overwrite the letters being wrapped).

But that's pure speculation.

Resize an Array while keeping current elements in Java?

You can't resize an array in Java. You'd need to either:

  1. Create a new array of the desired size, and copy the contents from the original array to the new array, using java.lang.System.arraycopy(...);

  2. Use the java.util.ArrayList<T> class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.

  3. Use java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.

Appending an element to the end of a list in Scala

This is similar to one of the answers but in different way :

scala> val x = List(1,2,3)
x: List[Int] = List(1, 2, 3)

scala> val y = x ::: 4 :: Nil
y: List[Int] = List(1, 2, 3, 4)

EF LINQ include multiple and nested entities

You can also try

db.Courses.Include("Modules.Chapters").Single(c => c.Id == id);

java.lang.VerifyError: Expecting a stackmap frame at branch target JDK 1.7

This ERROR can happen when you use Mockito to mock final classes.

Consider using Mockito inline or Powermock instead.

Retrieving the output of subprocess.call()

I have the following solution. It captures the exit code, the stdout, and the stderr too of the executed external command:

import shlex
from subprocess import Popen, PIPE

def get_exitcode_stdout_stderr(cmd):
    """
    Execute the external command and get its exitcode, stdout and stderr.
    """
    args = shlex.split(cmd)

    proc = Popen(args, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    exitcode = proc.returncode
    #
    return exitcode, out, err

cmd = "..."  # arbitrary external command, e.g. "python mytest.py"
exitcode, out, err = get_exitcode_stdout_stderr(cmd)

I also have a blog post on it here.

Edit: the solution was updated to a newer one that doesn't need to write to temp. files.

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

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

From documentation -

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

From urllib2 documentation -

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

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

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

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

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

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

Kotlin - How to correctly concatenate a String

There are various way to concatenate strings in kotlin Example -

a = "Hello" , b= "World"
  1. Using + operator a+b

  2. Using plus() operator

    a.plus(b)

Note - + is internally converted to .plus() method only

In above 2 methods, a new string object is created as strings are immutable. if we want to modify the existing string, we can use StringBuilder

StringBuilder str = StringBuilder("Hello").append("World")

seek() function?

The seek function expect's an offset in bytes.

Ascii File Example:

So if you have a text file with the following content:

simple.txt

abc

You can jump 1 byte to skip over the first character as following:

fp = open('simple.txt', 'r')
fp.seek(1)
print fp.readline()
>>> bc

Binary file example gathering width :

fp = open('afile.png', 'rb')
fp.seek(16)
print 'width: {0}'.format(struct.unpack('>i', fp.read(4))[0])
print 'height: ', struct.unpack('>i', fp.read(4))[0]

Note: Once you call read you are changing the position of the read-head, which act's like seek.

Simple Android grid example using RecyclerView with GridLayoutManager (like the old GridView)

Set in RecyclerView initialization

recyclerView.setLayoutManager(new GridLayoutManager(this, 4));

Apply jQuery datepicker to multiple instances

When adding datepicker at runtime generated input textboxes you have to check if it already contains datepicker then first remove class hasDatepicker then apply datePicker to it.

function convertTxtToDate() {
        $('.dateTxt').each(function () {
            if ($(this).hasClass('hasDatepicker')) {
                $(this).removeClass('hasDatepicker');
            } 
             $(this).datepicker();
        });
    } 

Bootstrap 3 dropdown select

We just switched our site to bootstrap 3 and we have a bunch of forms...wasn't fun but once you get the hang it's not too bad.

Is this what you are looking for? Demo Here

<div class="form-group">
  <label class="control-label col-sm-offset-2 col-sm-2" for="company">Company</label>
  <div class="col-sm-6 col-md-4">
    <select id="company" class="form-control">
      <option>small</option>
      <option>medium</option>
      <option>large</option>
    </select> 
  </div>
</div>

Understanding PrimeFaces process/update and JSF f:ajax execute/render attributes

<p:commandXxx process> <p:ajax process> <f:ajax execute>

The process attribute is server side and can only affect UIComponents implementing EditableValueHolder (input fields) or ActionSource (command fields). The process attribute tells JSF, using a space-separated list of client IDs, which components exactly must be processed through the entire JSF lifecycle upon (partial) form submit.

JSF will then apply the request values (finding HTTP request parameter based on component's own client ID and then either setting it as submitted value in case of EditableValueHolder components or queueing a new ActionEvent in case of ActionSource components), perform conversion, validation and updating the model values (EditableValueHolder components only) and finally invoke the queued ActionEvent (ActionSource components only). JSF will skip processing of all other components which are not covered by process attribute. Also, components whose rendered attribute evaluates to false during apply request values phase will also be skipped as part of safeguard against tampered requests.

Note that it's in case of ActionSource components (such as <p:commandButton>) very important that you also include the component itself in the process attribute, particularly if you intend to invoke the action associated with the component. So the below example which intends to process only certain input component(s) when a certain command component is invoked ain't gonna work:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="foo" action="#{bean.action}" />

It would only process the #{bean.foo} and not the #{bean.action}. You'd need to include the command component itself as well:

<p:inputText id="foo" value="#{bean.foo}" />
<p:commandButton process="@this foo" action="#{bean.action}" />

Or, as you apparently found out, using @parent if they happen to be the only components having a common parent:

<p:panel><!-- Type doesn't matter, as long as it's a common parent. -->
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@parent" action="#{bean.action}" />
</p:panel>

Or, if they both happen to be the only components of the parent UIForm component, then you can also use @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" />
    <p:commandButton process="@form" action="#{bean.action}" />
</h:form>

This is sometimes undesirable if the form contains more input components which you'd like to skip in processing, more than often in cases when you'd like to update another input component(s) or some UI section based on the current input component in an ajax listener method. You namely don't want that validation errors on other input components are preventing the ajax listener method from being executed.

Then there's the @all. This has no special effect in process attribute, but only in update attribute. A process="@all" behaves exactly the same as process="@form". HTML doesn't support submitting multiple forms at once anyway.

There's by the way also a @none which may be useful in case you absolutely don't need to process anything, but only want to update some specific parts via update, particularly those sections whose content doesn't depend on submitted values or action listeners.

Noted should be that the process attribute has no influence on the HTTP request payload (the amount of request parameters). Meaning, the default HTML behavior of sending "everything" contained within the HTML representation of the <h:form> will be not be affected. In case you have a large form, and want to reduce the HTTP request payload to only these absolutely necessary in processing, i.e. only these covered by process attribute, then you can set the partialSubmit attribute in PrimeFaces Ajax components as in <p:commandXxx ... partialSubmit="true"> or <p:ajax ... partialSubmit="true">. You can also configure this 'globally' by editing web.xml and add

<context-param>
    <param-name>primefaces.SUBMIT</param-name>
    <param-value>partial</param-value>
</context-param>

Alternatively, you can also use <o:form> of OmniFaces 3.0+ which defaults to this behavior.

The standard JSF equivalent to the PrimeFaces specific process is execute from <f:ajax execute>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Also, it may be useful to know that <p:commandXxx process> defaults to @form while <p:ajax process> and <f:ajax execute> defaults to @this. Finally, it's also useful to know that process supports the so-called "PrimeFaces Selectors", see also How do PrimeFaces Selectors as in update="@(.myClass)" work?


<p:commandXxx update> <p:ajax update> <f:ajax render>

The update attribute is client side and can affect the HTML representation of all UIComponents. The update attribute tells JavaScript (the one responsible for handling the ajax request/response), using a space-separated list of client IDs, which parts in the HTML DOM tree need to be updated as response to the form submit.

JSF will then prepare the right ajax response for that, containing only the requested parts to update. JSF will skip all other components which are not covered by update attribute in the ajax response, hereby keeping the response payload small. Also, components whose rendered attribute evaluates to false during render response phase will be skipped. Note that even though it would return true, JavaScript cannot update it in the HTML DOM tree if it was initially false. You'd need to wrap it or update its parent instead. See also Ajax update/render does not work on a component which has rendered attribute.

Usually, you'd like to update only the components which really need to be "refreshed" in the client side upon (partial) form submit. The example below updates the entire parent form via @form:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@form" />
</h:form>

(note that process attribute is omitted as that defaults to @form already)

Whilst that may work fine, the update of input and command components is in this particular example unnecessary. Unless you change the model values foo and bar inside action method (which would in turn be unintuitive in UX perspective), there's no point of updating them. The message components are the only which really need to be updated:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="foo_m bar_m" />
</h:form>

However, that gets tedious when you have many of them. That's one of the reasons why PrimeFaces Selectors exist. Those message components have in the generated HTML output a common style class of ui-message, so the following should also do:

<h:form>
    <p:inputText id="foo" value="#{bean.foo}" required="true" />
    <p:message id="foo_m" for="foo" />
    <p:inputText id="bar" value="#{bean.bar}" required="true" />
    <p:message id="bar_m" for="bar" />
    <p:commandButton action="#{bean.action}" update="@(.ui-message)" />
</h:form>

(note that you should keep the IDs on message components, otherwise @(...) won't work! Again, see How do PrimeFaces Selectors as in update="@(.myClass)" work? for detail)

The @parent updates only the parent component, which thus covers the current component and all siblings and their children. This is more useful if you have separated the form in sane groups with each its own responsibility. The @this updates, obviously, only the current component. Normally, this is only necessary when you need to change one of the component's own HTML attributes in the action method. E.g.

<p:commandButton action="#{bean.action}" update="@this" 
    oncomplete="doSomething('#{bean.value}')" />

Imagine that the oncomplete needs to work with the value which is changed in action, then this construct wouldn't have worked if the component isn't updated, for the simple reason that oncomplete is part of generated HTML output (and thus all EL expressions in there are evaluated during render response).

The @all updates the entire document, which should be used with care. Normally, you'd like to use a true GET request for this instead by either a plain link (<a> or <h:link>) or a redirect-after-POST by ?faces-redirect=true or ExternalContext#redirect(). In effects, process="@form" update="@all" has exactly the same effect as a non-ajax (non-partial) submit. In my entire JSF career, the only sensible use case I encountered for @all is to display an error page in its entirety in case an exception occurs during an ajax request. See also What is the correct way to deal with JSF 2.0 exceptions for AJAXified components?

The standard JSF equivalent to the PrimeFaces specific update is render from <f:ajax render>. It behaves exactly the same except that it doesn't support a comma-separated string while the PrimeFaces one does (although I personally recommend to just stick to space-separated convention), nor the @parent keyword. Both update and render defaults to @none (which is, "nothing").


See also:

Maven: best way of linking custom external JAR to my project?

The most efficient and cleanest way I have found to deal with this problem is by using Github Packages

  1. Create a simple empty public/private repository on GitHub as per your requirement whether you want your external jar to be publicly hosted or not.

  2. Run below maven command to deploy you external jar in above created github repository

    mvn deploy:deploy-file \ -DgroupId= your-group-id \ -DartifactId= your-artifact-id \ -Dversion= 1.0.0 -Dpackaging= jar -Dfile= path-to-file \ -DrepositoryId= id-to-map-on-server-section-of-settings.xml \ -Durl=https://maven.pkg.github.com/github-username/github-reponame-created-in-above-step

    Above command will deploy you external jar in GitHub repository mentioned in -Durl=. You can refer this link on How to deploy dependencies as GitHub Packages GitHub Package Deployment Tutorial

  3. After that you can add the dependency using groupId,artifactId and version mentioned in above step in maven pom.xml and run mvn install

  4. Maven will fetch the dependency of external jar from GitHub Packages registry and provide in your maven project.

  5. For this to work you will also need to configure you maven's settings.xml to fetch from GitHub Package registry.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

SELECT definition, uses_ansi_nulls, uses_quoted_identifier, is_schema_bound  
FROM sys.sql_modules  
WHERE object_id = OBJECT_ID('your View Name');  

How do I split a multi-line string into multiple lines?

Like the others said:

inputString.split('\n')  # --> ['Line 1', 'Line 2', 'Line 3']

This is identical to the above, but the string module's functions are deprecated and should be avoided:

import string
string.split(inputString, '\n')  # --> ['Line 1', 'Line 2', 'Line 3']

Alternatively, if you want each line to include the break sequence (CR,LF,CRLF), use the splitlines method with a True argument:

inputString.splitlines(True)  # --> ['Line 1\n', 'Line 2\n', 'Line 3']

ORACLE IIF Statement

Two other alternatives:

  1. a combination of NULLIF and NVL2. You can only use this if emp_id is NOT NULL, which it is in your case:

    select nvl2(nullif(emp_id,1),'False','True') from employee;
    
  2. simple CASE expression (Mt. Schneiders used a so-called searched CASE expression)

    select case emp_id when 1 then 'True' else 'False' end from employee;
    

What's the quickest way to multiply multiple cells by another number?

If it doesn't need to be a macro, then just put =A1*1.1 into (say) D7, then drag the formula fill handle across, then down.

Is there a float input type in HTML5?

I do so

 <input id="relacionac" name="relacionac" type="number" min="0.4" max="0.7" placeholder="0,40-0,70" class="form-control input-md" step="0.01">

then, I define min in 0.4 and max in 0.7 with step 0.01: 0.4, 0.41, 0,42 ... 0.7

Create a GUID in Java

It depends what kind of UUID you want.

  • The standard Java UUID class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID instances from long, byte[] or String representations, and provide some appropriate accessors.)

  • The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.

For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

Repeat String - Javascript

Use Lodash for Javascript utility functionality, like repeating strings.

Lodash provides nice performance and ECMAScript compatibility.

I highly recommend it for UI development and it works well server side, too.

Here's how to repeat the string "yo" 2 times using Lodash:

> _.repeat('yo', 2)
"yoyo"

How to find the .NET framework version of a Visual Studio project?

You can't change the targeted version of either Windows or the .NET Framework if you create your project in Visual Studio 2013. That option is not available anymore.

Look that link from Microsoft: http://msdn.microsoft.com/en-us/library/bb398202.aspx

How do I import a sql data file into SQL Server?

If your file is a large file, 50MB+, then I recommend you use sqlcmd, the command line utility that comes bundled with SQL Server. It is easy to use and it handles large files well. I tried it yesterday with a 22GB file using the following command:

sqlcmd -S SERVERNAME\INSTANCE_NAME -i C:\path\mysqlfile.sql -o C:\path\output_file.txt

The command above assumes that your server name is SERVERNAME, that you SQL Server installation uses the instance name INSTANCE_NAME, and that windows auth is the default auth method. After execution output.txt will contain something like the following:

...
(1 rows affected)
Processed 100 total records

(1 rows affected)
Processed 200 total records

(1 rows affected)
Processed 300 total records
...

use readfileonline.com if you need to see the contents of huge files.

UPDATE

This link provides more command line options and details such as username and password:

https://dba.stackexchange.com/questions/44101/importing-sql-server-database-from-a-sql-file

What's the difference between a mock & stub?

I have used python examples in my answer to illustrate the differences.

Stub - Stubbing is a software development technique used to implement methods of classes early in the development life-cycle. They are used commonly as placeholders for implementation of a known interface, where the interface is finalized or known but the implementation is not yet known or finalized. You begin with stubs, which simply means that you only write the definition of a function down and leave the actual code for later. The advantage is that you won't forget methods and you can continue to think about your design while seeing it in code. You can also have your stub return a static response so that the response can be used by other parts of your code immediately. Stub objects provide a valid response, but it's static no matter what input you pass in, you'll always get the same response:

class Foo(object):
    def bar1(self):
        pass

    def bar2(self):
        #or ...
        raise NotImplementedError

    def bar3(self):
        #or return dummy data
        return "Dummy Data"

Mock objects are used in mock test cases they validate that certain methods are called on those objects. Mock objects are simulated objects that mimic the behaviour of real objects in controlled ways. You typically creates a mock object to test the behaviour of some other object. Mocks let us simulate resources that are either unavailable or too unwieldy for unit testing.

mymodule.py:

import os
import os.path

def rm(filename):
    if os.path.isfile(filename):
        os.remove(filename)

test.py:

from mymodule import rm
import mock
import unittest

class RmTestCase(unittest.TestCase):
    @mock.patch('mymodule.os')
    def test_rm(self, mock_os):
        rm("any path")
        # test that rm called os.remove with the right parameters
        mock_os.remove.assert_called_with("any path")

if __name__ == '__main__':
    unittest.main()

This is a very basic example that just runs rm and asserts the parameter it was called with. You can use mock with objects not just functions as shown here, and you can also return a value so a mock object can be used to replace a stub for testing.

More on unittest.mock, note in python 2.x mock is not included in unittest but is a downloadable module that can be downloaded via pip (pip install mock).

I have also read "The Art of Unit Testing" by Roy Osherove and I think it would be great if a similar book was written using Python and Python examples. If anyone knows of such a book please do share. Cheers :)

I need to get all the cookies from the browser

  1. You can't see cookies for other sites.
  2. You can't see HttpOnly cookies.
  3. All the cookies you can see are in the document.cookie property, which contains a semicolon separated list of name=value pairs.

How to do a subquery in LINQ?

This is how I've been doing subqueries in LINQ, I think this should get what you want. You can replace the explicit CompanyRoleId == 2... with another subquery for the different roles you want or join it as well.

from u in Users
join c in (
    from crt in CompanyRolesToUsers
    where CompanyRoleId == 2
    || CompanyRoleId == 3
    || CompanyRoleId == 4) on u.UserId equals c.UserId
where u.lastname.Contains("fra")
select u;

How do I read a date in Excel format in Python?

If you have a datetime column in excel file. Then below code will fix it. I went through a lot of answers on StackOverflow and nothing fixed it. I thought file is corrupted.

from datetime import datetime
jsts = 1468629431.0
datetime.fromtimestamp(jsts) 

How to convert column with string type to int form in pyspark data frame?

from pyspark.sql.types import IntegerType
data_df = data_df.withColumn("Plays", data_df["Plays"].cast(IntegerType()))
data_df = data_df.withColumn("drafts", data_df["drafts"].cast(IntegerType()))

You can run loop for each column but this is the simplest way to convert string column into integer.

How is malloc() implemented internally?

The sbrksystem call moves the "border" of the data segment. This means it moves a border of an area in which a program may read/write data (letting it grow or shrink, although AFAIK no malloc really gives memory segments back to the kernel with that method). Aside from that, there's also mmap which is used to map files into memory but is also used to allocate memory (if you need to allocate shared memory, mmap is how you do it).

So you have two methods of getting more memory from the kernel: sbrk and mmap. There are various strategies on how to organize the memory that you've got from the kernel.

One naive way is to partition it into zones, often called "buckets", which are dedicated to certain structure sizes. For example, a malloc implementation could create buckets for 16, 64, 256 and 1024 byte structures. If you ask malloc to give you memory of a given size it rounds that number up to the next bucket size and then gives you an element from that bucket. If you need a bigger area malloc could use mmap to allocate directly with the kernel. If the bucket of a certain size is empty malloc could use sbrk to get more space for a new bucket.

There are various malloc designs and there is propably no one true way of implementing malloc as you need to make a compromise between speed, overhead and avoiding fragmentation/space effectiveness. For example, if a bucket runs out of elements an implementation might get an element from a bigger bucket, split it up and add it to the bucket that ran out of elements. This would be quite space efficient but would not be possible with every design. If you just get another bucket via sbrk/mmap that might be faster and even easier, but not as space efficient. Also, the design must of course take into account that "free" needs to make space available to malloc again somehow. You don't just hand out memory without reusing it.

If you're interested, the OpenSER/Kamailio SIP proxy has two malloc implementations (they need their own because they make heavy use of shared memory and the system malloc doesn't support shared memory). See: https://github.com/OpenSIPS/opensips/tree/master/mem

Then you could also have a look at the GNU libc malloc implementation, but that one is very complicated, IIRC.

illegal character in path

I usualy would enter the path like this ....

FileInfo fi = new FileInfo(@"C:\Program Files (x86)\test software\myapp\demo.exe"); 

Did you register the @ at the beginning of the string? ;-)

Launch Minecraft from command line - username and password as prefix

To run Minecraft with Forge (change C:\Users\nov11\AppData\Roaming/.minecraft/to your MineCraft path :) [Just for people who are a bit too lazy to search on Google...] Special thanks to ammarx for his TagAPI_3 (Github) which was used to create this command. Arguments are separated line by line to make it easier to find useful ones.

java
-Xms1024M
-Xmx1024M
-XX:HeapDumpPath=MojangTricksIntelDriversForPerformance_javaw.exe_minecraft.exe.heapdump
-Djava.library.path=C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/natives
-cp
C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraftforge/forge/1.12.2-14.23.5.2775/forge-1.12.2-14.23.5.2775.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/ow2/asm/asm-all/5.2/asm-all-5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/jline/jline/3.5.1/jline-3.5.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/akka/akka-actor_2.11/2.3.3/akka-actor_2.11-2.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/typesafe/config/1.2.1/config-1.2.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-actors-migration_2.11/1.1.0/scala-actors-migration_2.11-1.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-compiler/2.11.1/scala-compiler-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-library_2.11/1.0.2/scala-continuations-library_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/plugins/scala-continuations-plugin_2.11.1/1.0.2/scala-continuations-plugin_2.11.1-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-library/2.11.1/scala-library-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-parser-combinators_2.11/1.0.1/scala-parser-combinators_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-reflect/2.11.1/scala-reflect-2.11.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-swing_2.11/1.0.1/scala-swing_2.11-1.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/scala-lang/scala-xml_2.11/1.0.2/scala-xml_2.11-1.0.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/lzma/lzma/0.0.1/lzma-0.0.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/java3d/vecmath/1.5.2/vecmath-1.5.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/trove4j/trove4j/3.0.3/trove4j-3.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/maven/maven-artifact/3.5.3/maven-artifact-3.5.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/patchy/1.1/patchy-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/oshi-project/oshi-core/1.1/oshi-core-1.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/jna/4.4.0/jna-4.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/dev/jna/platform/3.4.0/platform-3.4.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/ibm/icu/icu4j-core-mojang/51.2/icu4j-core-mojang-51.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/sf/jopt-simple/jopt-simple/5.0.3/jopt-simple-5.0.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecjorbis/20101023/codecjorbis-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/codecwav/20101023/codecwav-20101023.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/libraryjavasound/20101123/libraryjavasound-20101123.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/librarylwjglopenal/20100824/librarylwjglopenal-20100824.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/paulscode/soundsystem/20120107/soundsystem-20120107.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/io/netty/netty-all/4.1.9.Final/netty-all-4.1.9.Final.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/guava/guava/21.0/guava-21.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-lang3/3.5/commons-lang3-3.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-io/commons-io/2.5/commons-io-2.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-codec/commons-codec/1.10/commons-codec-1.10.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jinput/jinput/2.0.5/jinput-2.0.5.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/net/java/jutils/jutils/1.0.0/jutils-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/google/code/gson/gson/2.8.0/gson-2.8.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/authlib/1.5.25/authlib-1.5.25.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/realms/1.10.22/realms-1.10.22.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/commons/commons-compress/1.8.1/commons-compress-1.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpclient/4.3.3/httpclient-4.3.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/httpcomponents/httpcore/4.3.2/httpcore-4.3.2.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/it/unimi/dsi/fastutil/7.1.0/fastutil-7.1.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-api/2.8.1/log4j-api-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/apache/logging/log4j/log4j-core/2.8.1/log4j-core-2.8.1.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.4-nightly-20150209/lwjgl-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.4-nightly-20150209/lwjgl_util-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl-platform/2.9.4-nightly-20150209/lwjgl-platform-2.9.4-nightly-20150209.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl/2.9.2-nightly-20140822/lwjgl-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/org/lwjgl/lwjgl/lwjgl_util/2.9.2-nightly-20140822/lwjgl_util-2.9.2-nightly-20140822.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/com/mojang/text2speech/1.10.3/text2speech-1.10.3.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/libraries/ca/weblite/java-objc-bridge/1.0.0/java-objc-bridge-1.0.0.jar;C:\Users\nov11\AppData\Roaming/.minecraft/versions/1.12.2/1.12.2.jar
net.minecraft.launchwrapper.Launch
--width
854
--height
480
--username
Ishikawa
--version
1.12.2-forge1.12.2-14.23.5.2775
--gameDir
C:\Users\nov11\AppData\Roaming/.minecraft
--assetsDir
C:\Users\nov11\AppData\Roaming/.minecraft/assets
--assetIndex
1.12
--uuid
N/A
--accessToken
aeef7bc935f9420eb6314dea7ad7e1e5
--userType
mojang
--tweakClass
net.minecraftforge.fml.common.launcher.FMLTweaker
--versionType
Forge

Just when other solutions don't work. accessToken and uuid can be acquired from Mojang Servers, check other anwsers for details.

Edit (26.11.2018): I've also created Launcher Framework in C# (.NET Framework 3.5), which you can also check to see how launcher should work Available Here

Pass props to parent component in React.js

It appears there's a simple answer. Consider this:

var Child = React.createClass({
  render: function() {
    <a onClick={this.props.onClick.bind(null, this)}>Click me</a>
  }
});

var Parent = React.createClass({
  onClick: function(component, event) {
    component.props // #=> {Object...}
  },
  render: function() {
    <Child onClick={this.onClick} />
  }
});

The key is calling bind(null, this) on the this.props.onClick event, passed from the parent. Now, the onClick function accepts arguments component, AND event. I think that's the best of all worlds.

UPDATE: 9/1/2015

This was a bad idea: letting child implementation details leak in to the parent was never a good path. See Sebastien Lorber's answer.

How to get the PYTHONPATH in shell?

Python, at startup, loads a bunch of values into sys.path (which is "implemented" via a list of strings), including:

  • various hardcoded places
  • the value of $PYTHONPATH
  • probably some stuff from startup files (I'm not sure if Python has rcfiles)

$PYTHONPATH is only one part of the eventual value of sys.path.

If you're after the value of sys.path, the best way would be to ask Python (thanks @Codemonkey):

python -c "import sys; print sys.path"

Adjust UILabel height depending on the text

myLabel.text = "your very long text"
myLabel.numberOfLines = 0
myLabel.lineBreakMode = NSLineBreakMode.ByWordWrapping

Please set constraints for UILable in storyboard including top left bottom right

MVC4 input field placeholder

The correct solution to get the Prompt value in a non-templated control context is:

@Html.TextBoxFor(model => model.Email, 
    new { placeholder = ModelMetadata.FromLambdaExpression(m => m.Email, ViewData).Watermark }
)

This will also not double-escape the watermark text.

Angular 2 - Checking for server errors from subscribe

You can achieve with following way

    this.projectService.create(project)
    .subscribe(
        result => {
         console.log(result);
        },
        error => {
            console.log(error);
            this.errors = error
        }
    ); 
}

if (!this.errors) {
    //route to new page
}

Center button under form in bootstrap

I do it like this <center></center>

<div class="form-actions">
            <center>
                    <button type="submit" class="submit btn btn-primary ">
                        Sign In <i class="icon-angle-right"></i>
                    </button>
            </center>
</div>

How to get the category title in a post in Wordpress?

You can use

<?php the_category(', '); ?>

which would output them in a comma separated list.

You can also do the same for tags as well:

<?php the_tags('<em>:</em>', ', ', ''); ?>

LEFT JOIN vs. LEFT OUTER JOIN in SQL Server

There are mainly three types of JOIN

  1. Inner: fetches data, that are present in both tables
    • Only JOIN means INNER JOIN
  2. Outer: are of three types

    • LEFT OUTER - - fetches data present only in left table & matching condition
    • RIGHT OUTER - - fetches data present only in right table & matching condition
    • FULL OUTER - - fetches data present any or both table
    • (LEFT or RIGHT or FULL) OUTER JOIN can be written w/o writing "OUTER"
  3. Cross Join: joins everything to everything

MVC4 StyleBundle not resolving images

Grinn solution is great.

However it doesn't work for me when there are parent folder relative references in the url. i.e. url('../../images/car.png')

So, I slightly changed the Include method in order to resolve the paths for each regex match, allowing relative paths and also to optionally embed the images in the css.

I also changed the IF DEBUG to check BundleTable.EnableOptimizations instead of HttpContext.Current.IsDebuggingEnabled.

    public new Bundle Include(params string[] virtualPaths)
    {
        if (!BundleTable.EnableOptimizations)
        {
            // Debugging. Bundling will not occur so act normal and no one gets hurt. 
            base.Include(virtualPaths.ToArray());
            return this;
        }
        var bundlePaths = new List<string>();
        var server = HttpContext.Current.Server;
        var pattern = new Regex(@"url\s*\(\s*([""']?)([^:)]+)\1\s*\)", RegexOptions.IgnoreCase);
        foreach (var path in virtualPaths)
        {
            var contents = File.ReadAllText(server.MapPath(path));
            var matches = pattern.Matches(contents);
            // Ignore the file if no matches
            if (matches.Count == 0)
            {
                bundlePaths.Add(path);
                continue;
            }
            var bundlePath = (System.IO.Path.GetDirectoryName(path) ?? string.Empty).Replace(@"\", "/") + "/";
            var bundleUrlPath = VirtualPathUtility.ToAbsolute(bundlePath);
            var bundleFilePath = string.Format("{0}{1}.bundle{2}",
                                               bundlePath,
                                               System.IO.Path.GetFileNameWithoutExtension(path),
                                               System.IO.Path.GetExtension(path));
            // Transform the url (works with relative path to parent folder "../")
            contents = pattern.Replace(contents, m =>
            {
                var relativeUrl = m.Groups[2].Value;
                var urlReplace = GetUrlReplace(bundleUrlPath, relativeUrl, server);
                return string.Format("url({0}{1}{0})", m.Groups[1].Value, urlReplace);
            });
            File.WriteAllText(server.MapPath(bundleFilePath), contents);
            bundlePaths.Add(bundleFilePath);
        }
        base.Include(bundlePaths.ToArray());
        return this;
    }


    private string GetUrlReplace(string bundleUrlPath, string relativeUrl, HttpServerUtility server)
    {
        // Return the absolute uri
        Uri baseUri = new Uri("http://dummy.org");
        var absoluteUrl = new Uri(new Uri(baseUri, bundleUrlPath), relativeUrl).AbsolutePath;
        var localPath = server.MapPath(absoluteUrl);
        if (IsEmbedEnabled && File.Exists(localPath))
        {
            var fi = new FileInfo(localPath);
            if (fi.Length < 0x4000)
            {
                // Embed the image in uri
                string contentType = GetContentType(fi.Extension);
                if (null != contentType)
                {
                    var base64 = Convert.ToBase64String(File.ReadAllBytes(localPath));
                    // Return the serialized image
                    return string.Format("data:{0};base64,{1}", contentType, base64);
                }
            }
        }
        // Return the absolute uri 
        return absoluteUrl;
    }

Hope it helps, regards.

Getting Image from API in Angular 4/5+?

There is no need to use angular http, you can get with js native functions

_x000D_
_x000D_
// you will ned this function to fetch the image blob._x000D_
async function getImage(url, fileName) {_x000D_
     // on the first then you will return blob from response_x000D_
    return await fetch(url).then(r => r.blob())_x000D_
    .then((blob) => { // on the second, you just create a file from that blob, getting the type and name that intend to inform_x000D_
         _x000D_
        return new File([blob], fileName+'.'+   blob.type.split('/')[1]) ;_x000D_
    });_x000D_
}_x000D_
_x000D_
// example url_x000D_
var url = 'https://img.freepik.com/vetores-gratis/icone-realista-quebrado-vidro-fosco_1284-12125.jpg';_x000D_
_x000D_
// calling the function_x000D_
getImage(url, 'your-name-image').then(function(file) {_x000D_
_x000D_
    // with file reader you will transform the file in a data url file;_x000D_
    var reader = new FileReader();_x000D_
    reader.readAsDataURL(file);_x000D_
    reader.onloadend = () => {_x000D_
    _x000D_
    // just putting the data url to img element_x000D_
        document.querySelector('#image').src = reader.result ;_x000D_
    }_x000D_
})
_x000D_
<img src="" id="image"/>
_x000D_
_x000D_
_x000D_

How to pass argument to Makefile from command line?

Here is a generic working solution based on @Beta's

I'm using GNU Make 4.1 with SHELL=/bin/bash atop my Makefile, so YMMV!

This allows us to accept extra arguments (by doing nothing when we get a job that doesn't match, rather than throwing an error).

%:
    @:

And this is a macro which gets the args for us:

args = `arg="$(filter-out $@,$(MAKECMDGOALS))" && echo $${arg:-${1}}`

Here is a job which might call this one:

test:
    @echo $(call args,defaultstring)

The result would be:

$ make test
defaultstring
$ make test hi
hi

Note! You might be better off using a "Taskfile", which is a bash pattern that works similarly to make, only without the nuances of Maketools. See https://github.com/adriancooney/Taskfile

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

Does Hibernate create tables in the database automatically

yes you can use

<property name="hbm2ddl.auto" value="create"/>

Compile to stand alone exe for C# app in Visual Studio 2010

Press the start button in visual studio. Then go to the location where your solution is stored and open the folder of your main project then the bin folder. If your application was running in debug mode then go to the debug folder. If running in release mode then go to the release folder. You should find your exe there.

Resource u'tokenizers/punkt/english.pickle' not found

I faced same issue. After downloading everything, still 'punkt' error was there. I searched package on my windows machine at C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers and I can see 'punkt.zip' present there. I realized that somehow the zip has not been extracted into C:\Users\vaibhav\AppData\Roaming\nltk_data\tokenizers\punk. Once I extracted the zip, it worked like music.

React this.setState is not a function

You no need to assign this to a local variable if you use arrow function. Arrow functions takes binding automatically and you can stay away with scope related issues.

Below code explains how to use arrow function in different scenarios

componentDidMount = () => {

    VK.init(() => {
        console.info("API initialisation successful");
        VK.api('users.get',{fields: 'photo_50'},(data) => {
            if(data.response){
                that.setState({ //this available here and you can do setState
                    FirstName: data.response[0].first_name
                });
                console.info(that.state.FirstName);
            }
        });
    }, () => {
        console.info("API initialisation failed");

    }, '5.34');
 },

Parsing HTTP Response in Python

json works with Unicode text in Python 3 (JSON format itself is defined only in terms of Unicode text) and therefore you need to decode bytes received in HTTP response. r.headers.get_content_charset('utf-8') gets your the character encoding:

#!/usr/bin/env python3
import io
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r, \
     io.TextIOWrapper(r, encoding=r.headers.get_content_charset('utf-8')) as file:
    result = json.load(file)
print(result['headers']['User-Agent'])

It is not necessary to use io.TextIOWrapper here:

#!/usr/bin/env python3
import json
from urllib.request import urlopen

with urlopen('https://httpbin.org/get') as r:
    result = json.loads(r.read().decode(r.headers.get_content_charset('utf-8')))
print(result['headers']['User-Agent'])

Adding IN clause List to a JPA Query

public List<DealInfo> getDealInfos(List<String> dealIds) {
        String queryStr = "SELECT NEW com.admin.entity.DealInfo(deal.url, deal.url, deal.url, deal.url, deal.price, deal.value) " + "FROM Deal AS deal where deal.id in :inclList";
        TypedQuery<DealInfo> query = em.createQuery(queryStr, DealInfo.class);
        query.setParameter("inclList", dealIds);
        return query.getResultList();
    }

Works for me with JPA 2, Jboss 7.0.2

How to pass IEnumerable list to controller in MVC including checkbox state?

Use a list instead and replace your foreach loop with a for loop:

@model IList<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()

    @for (var i = 0; i < Model.Count; i++) 
    {
        <tr>
            <td>
                @Html.HiddenFor(x => x[i].IP)           
                @Html.CheckBoxFor(x => x[i].Checked)
            </td>
            <td>
                @Html.DisplayFor(x => x[i].IP)
            </td>
        </tr>
    }
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

Alternatively you could use an editor template:

@model IEnumerable<BlockedIPViewModel>

@using (Html.BeginForm()) 
{ 
    @Html.AntiForgeryToken()
    @Html.EditorForModel()   
    <div>
        <input type="submit" value="Unblock IPs" />
    </div>
}

and then define the template ~/Views/Shared/EditorTemplates/BlockedIPViewModel.cshtml which will automatically be rendered for each element of the collection:

@model BlockedIPViewModel
<tr>
    <td>
        @Html.HiddenFor(x => x.IP)
        @Html.CheckBoxFor(x => x.Checked)
    </td>
    <td>
        @Html.DisplayFor(x => x.IP)
    </td>
</tr>

The reason you were getting null in your controller is because you didn't respect the naming convention for your input fields that the default model binder expects to successfully bind to a list. I invite you to read the following article.

Once you have read it, look at the generated HTML (and more specifically the names of the input fields) with my example and yours. Then compare and you will understand why yours doesn't work.

IntelliJ IDEA generating serialVersionUID

In addition you can add live template that will do the work.

To do it press Ctrl+Alt+S -> "Live Templates" section -> other (or w/e you wish)

And then create a new one with a definition like this:

private static final long serialVersionUID = 1L;
$END$

Then select definition scope and save it as 'serial'

Now you can type serialTAB in class body.

Changing text of UIButton programmatically swift

Swift 5.0

// Standard State
myButton.setTitle("Title", for: .normal)

Convert InputStream to byte array in Java

This is my copy-paste version:

@SuppressWarnings("empty-statement")
public static byte[] inputStreamToByte(InputStream is) throws IOException {
    if (is == null) {
        return null;
    }
    // Define a size if you have an idea of it.
    ByteArrayOutputStream r = new ByteArrayOutputStream(2048);
    byte[] read = new byte[512]; // Your buffer size.
    for (int i; -1 != (i = is.read(read)); r.write(read, 0, i));
    is.close();
    return r.toByteArray();
}

Responsive Bootstrap Jumbotron Background Image

I found that this worked perfectly for me:

.jumbotron {
background-image: url(/img/Jumbotron.jpg);
background-size: cover;
height: 100%;}

You can resize your screen and it will always take up 100% of the window.

One line if/else condition in linux shell scripting

You can use like bellow:

(( var0 = var1<98?9:21 ))

the same as

if [ "$var1" -lt 98 ]; then
   var0=9
else
   var0=21
fi

extends

condition?result-if-true:result-if-false

I found the interested thing on the book "Advanced Bash-Scripting Guide"

How can one display images side by side in a GitHub README.md?

If, like me, you found that @wiggin answer didn't work and images still did not appear in-line, you can use the 'align' property of the html image tag and some breaks to achieve the desired effect, for example:

# Title

<img align="left" src="./documentation/images/A.jpg" alt="Made with Angular" title="Angular" hspace="20"/>
<img align="left" src="./documentation/images/B.png" alt="Made with Bootstrap" title="Bootstrap" hspace="20"/>
<img align="left" src="./documentation/images/C.png" alt="Developed using Browsersync" title="Browsersync" hspace="20"/>
<br/><br/><br/><br/><br/>

## Table of Contents...

Obviously, you have to use more breaks depending on how big the images are: awful yes, but it worked for me so I thought I'd share.

Non-alphanumeric list order from os.listdir()

Per the documentation:

os.listdir(path)

Return a list containing the names of the entries in the directory given by path. The list is in arbitrary order. It does not include the special entries '.' and '..' even if they are present in the directory.

Order cannot be relied upon and is an artifact of the filesystem.

To sort the result, use sorted(os.listdir(path)).

Creating a data frame from two vectors using cbind

Vectors and matrices can only be of a single type and cbind and rbind on vectors will give matrices. In these cases, the numeric values will be promoted to character values since that type will hold all the values.

(Note that in your rbind example, the promotion happens within the c call:

> c(10, "[]", "[[1,2]]")
[1] "10"      "[]"      "[[1,2]]"

If you want a rectangular structure where the columns can be different types, you want a data.frame. Any of the following should get you what you want:

> x = data.frame(v1=c(10, 20), v2=c("[]", "[]"), v3=c("[[1,2]]","[[1,3]]"))
> x
  v1 v2      v3
1 10 [] [[1,2]]
2 20 [] [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ v1: num  10 20
 $ v2: Factor w/ 1 level "[]": 1 1
 $ v3: Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using specifically the data.frame version of cbind)

> x = cbind.data.frame(c(10, 20), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c(10, 20) c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c(10, 20)              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

or (using cbind, but making the first a data.frame so that it combines as data.frames do):

> x = cbind(data.frame(c(10, 20)), c("[]", "[]"), c("[[1,2]]","[[1,3]]"))
> x
  c.10..20. c("[]", "[]") c("[[1,2]]", "[[1,3]]")
1        10            []                 [[1,2]]
2        20            []                 [[1,3]]
> str(x)
'data.frame':   2 obs. of  3 variables:
 $ c.10..20.              : num  10 20
 $ c("[]", "[]")          : Factor w/ 1 level "[]": 1 1
 $ c("[[1,2]]", "[[1,3]]"): Factor w/ 2 levels "[[1,2]]","[[1,3]]": 1 2

referenced before assignment error in python

I found this post through the fact that I had this error myself in my own code and I know that it has been a while since this was posted and you already got some answers and fixed issue for that situation but just wanted to explain how I fixed it just in case it could help someone else!! Basically what I thought at first was that the code editor as was using REPL.it as was making something for a friend and knew that she wouldn't want to have to download like a code editor anyways the point is I thought that it couldn't handle the code because the complexity was at 139 at that point got even higher afterwards, but then I began experimenting and realized that within my set of functions just outside of a true loop within my a_loop function for that letter to register it needed to define it! So basically I wasn't defining the Value in this case a counting feature actually within the code! I would share my code here but it's kind of personal as in the print statements and also it's 2349 lines long and yeah anyway hope this helps! Also recommend using if you can in my case for some of the code I could, putting it into way more scripts if you can to make it easier on your brain! Once again hope this helps, if you have any questions, please feel free to ask and I will answer to the best of my ability! I hope this helps!!!

-Sam

"No rule to make target 'install'"... But Makefile exists

Could you provide a whole makefile? But right now I can tell - you should check that "install" target already exists. So, check Makefile whether it contains a

install: (anything there)

line. If not, there is no such target and so make has right. Probably you should use just "make" command to compile and then use it as is or install yourself, manually.

Install is not any standard of make, it is just a common target, that could exists, but not necessary.

SQL Server - INNER JOIN WITH DISTINCT

select distinct a.FirstName, a.LastName, v.District from AddTbl a inner join ValTbl v on a.LastName = v.LastName order by a.FirstName;

hope this helps

How to save a figure in MATLAB from the command line?

Use saveas:

h=figure;
plot(x,y,'-bs','Linewidth',1.4,'Markersize',10);
% ...
saveas(h,name,'fig')
saveas(h,name,'jpg')

This way, the figure is plotted, and automatically saved to '.jpg' and '.fig'. You don't need to wait for the plot to appear and click 'save as' in the menu. Way to go if you need to plot/save a lot of figures.

If you really do not want to let the plot appear (it has to be loaded anyway, can't avoid that, else there is also nothing to save), you can hide it:

h=figure('visible','off')

How do you determine what SQL Tables have an identity column programmatically

Another way (for 2000 / 2005/2012/2014):

IF ((SELECT OBJECTPROPERTY( OBJECT_ID(N'table_name_here'), 'TableHasIdentity')) = 1)
    PRINT 'Yes'
ELSE
    PRINT 'No'

NOTE: table_name_here should be schema.table, unless the schema is dbo.

System.IO.IOException: file used by another process

Sounds like an external process (AV?) is locking it, but can't you avoid the problem in the first place?

private static bool modifyFile(FileInfo file, string extractedMethod, string modifiedMethod)
{
    try
    {
        string contents = File.ReadAllText(file.FullName);
        Console.WriteLine("input : {0}", contents);
        contents = contents.Replace(extractedMethod, modifiedMethod);
        Console.WriteLine("replaced String {0}", contents);
        File.WriteAllText(file.FullName, contents);
        return true;
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.ToString());
        return false;
    }
}

What is the advantage of using REST instead of non-REST HTTP?

Simply put, REST means using HTTP the way it's meant to be.

Have a look at Roy Fielding's dissertation about REST. I think that every person that is doing web development should read it.

As a note, Roy Fielding is one of the key drivers behind the HTTP protocol, as well.

To name some of the advandages:

  • Simple.
  • You can make good use of HTTP cache and proxy server to help you handle high load.
  • It helps you organize even a very complex application into simple resources.
  • It makes it easy for new clients to use your application, even if you haven't designed it specifically for them (probably, because they weren't around when you created your app).

Gson and deserializing an array of objects with arrays in it

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

Spring application context external properties?

This question is kind of old, but wanted to share something which worked for me. Hope it will be useful for people who are searching for some information accessing properties in an external location.

This is what has worked for me.

  1. Property file contents:

    PROVIDER_URL=t3://localhost:8003,localhost:8004
    
  2. applicationContext.xml file contents: (Spring 3.2.3)

    Note: ${user.home} is a system property from OS.

    <context:property-placeholder system-properties-mode="OVERRIDE" location="file:${user.home}/myapp/latest/bin/my-env.properties"/>
    
    <bean id="appsclusterJndiTemplate" class="org.springframework.jndi.JndiTemplate">
        <property name="environment">
            <props>
                <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
                <prop key="java.naming.provider.url">${PROVIDER_URL}</prop>
            </props>
        </property>
    </bean>
    

${PROVIDER_URL} got replaced with the value in the properties the file

MySQl Error #1064

Sometimes when your table has a similar name to the database name you should use back tick. so instead of:

INSERT INTO books.book(field1, field2) VALUES ('value1', 'value2');

You should have this:

INSERT INTO `books`.`book`(`field1`, `field2`) VALUES ('value1', 'value2');

Java ArrayList copy

Yes l1 and l2 will point to the same reference, same object.

If you want to create a new ArrayList based on the other ArrayList you do this:

List<String> l1 = new ArrayList<String>();
l1.add("Hello");
l1.add("World");
List<String> l2 = new ArrayList<String>(l1); //A new arrayList.
l2.add("Everybody");

The result will be l1 will still have 2 elements and l2 will have 3 elements.

Background image jumps when address bar hides iOS/Android/Mobile Chrome

I created a vanilla javascript solution to using VH units. Using VH pretty much anywhere is effected by address bars minimizing on scroll. To fix the jank that shows when the page redraws, I've got this js here that will grab all your elements using VH units (if you give them the class .vh-fix), and give them inlined pixel heights. Essentially freezing them at the height we want. You could do this on rotation or on viewport size change to stay responsive.

var els = document.querySelectorAll('.vh-fix')
if (!els.length) return

for (var i = 0; i < els.length; i++) {
  var el = els[i]
  if (el.nodeName === 'IMG') {
    el.onload = function() {
      this.style.height = this.clientHeight + 'px'
    }
  } else {
    el.style.height = el.clientHeight + 'px'
  }
}

This has solved all my use cases, hope it helps.

How to install gdb (debugger) in Mac OSX El Capitan?

Here's a blog post explains it very well:

http://panks.me/posts/2013/11/install-gdb-on-os-x-mavericks-from-source/

And the way I get it working:

  1. Create a coding signing certificate via KeyChain Access:

    1.1 From the Menu, select KeyChain Access > Certificate Assistant > Create a Certificate...

    1.2 Follow the wizard to create a certificate and let's name it gdb-cert, the Identity Type is Self Signed Root, and the Certificate Type is Code Signing and select the Let me override defaults.

    1.3 Click several times on Continue until you get to the Specify a Location For The Certificate screen, then set Keychain to System.

  2. Install gdb via Homebrew: brew install gdb

  3. Restart taskgated: sudo killall taskgated && exit

  4. Reopen a Terminal window and type sudo codesign -vfs gdb-cert /usr/local/bin/gdb

check if array is empty (vba excel)

I would do this as

if isnumeric(ubound(a)) = False then msgbox "a is empty!"

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

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

try this query below:

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

What is a loop invariant?

The meaning of invariant is never change

Here the loop invariant means "The change which happen to variable in the loop(increment or decrement) is not changing the loop condition i.e the condition is satisfying " so that the loop invariant concept has came

jQuery AJAX cross domain

I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.

  • server script (.php, .jsp, ...) must return http response header Access-Control-Allow-Origin: *
  • before using jQuery ajax set this flag in javascript: jQuery.support.cors = true;
  • you may set flag once or everytime before using jQuery ajax function
  • now I can read .xml document in IE and Firefox. Other browsers I did not test.
  • response document can be plain/text, xml, json or anything else

Here is an example jQuery ajax call with some debug sysouts.

jQuery.support.cors = true;
$.ajax({
    url: "http://localhost/getxml.php",
    data: { "id":"doc1", "rows":"100" },
    type: "GET",
    timeout: 30000,
    dataType: "text", // "xml", "json"
    success: function(data) {
        // show text reply as-is (debug)
        alert(data);

        // show xml field values (debug)
        //alert( $(data).find("title").text() );

        // loop JSON array (debug)
        //var str="";
        //$.each(data.items, function(i,item) {
        //  str += item.title + "\n";
        //});
        //alert(str);
    },
    error: function(jqXHR, textStatus, ex) {
        alert(textStatus + "," + ex + "," + jqXHR.responseText);
    }
});

Automate scp file transfer using a shell script

here's bash code for SCP with a .pem key file. Just save it to a script.sh file then run with 'sh script.sh'

Enjoy

#!/bin/bash
#Error function
function die(){
echo "$1"
exit 1
}

Host=ec2-53-298-45-63.us-west-1.compute.amazonaws.com
User=ubuntu
#Directory at sent destination
SendDirectory=scp
#File to send at host
FileName=filetosend.txt
#Key file
Key=MyKeyFile.pem

echo "Aperture in Process...";

#The code that will send your file scp
scp -i $Key $FileName $User@$Host:$SendDirectory || \
die "@@@@@@@Houston we have problem"

echo "########Aperture Complete#########";

How do multiple clients connect simultaneously to one port, say 80, on a server?

First off, a "port" is just a number. All a "connection to a port" really represents is a packet which has that number specified in its "destination port" header field.

Now, there are two answers to your question, one for stateful protocols and one for stateless protocols.

For a stateless protocol (ie UDP), there is no problem because "connections" don't exist - multiple people can send packets to the same port, and their packets will arrive in whatever sequence. Nobody is ever in the "connected" state.

For a stateful protocol (like TCP), a connection is identified by a 4-tuple consisting of source and destination ports and source and destination IP addresses. So, if two different machines connect to the same port on a third machine, there are two distinct connections because the source IPs differ. If the same machine (or two behind NAT or otherwise sharing the same IP address) connects twice to a single remote end, the connections are differentiated by source port (which is generally a random high-numbered port).

Simply, if I connect to the same web server twice from my client, the two connections will have different source ports from my perspective and destination ports from the web server's. So there is no ambiguity, even though both connections have the same source and destination IP addresses.

Ports are a way to multiplex IP addresses so that different applications can listen on the same IP address/protocol pair. Unless an application defines its own higher-level protocol, there is no way to multiplex a port. If two connections using the same protocol simultaneously have identical source and destination IPs and identical source and destination ports, they must be the same connection.

Unescape HTML entities in Javascript?

I use this in my project: inspired by other answers but with an extra secure parameter, can be useful when you deal with decorated characters

var decodeEntities=(function(){

    var el=document.createElement('div');
    return function(str, safeEscape){

        if(str && typeof str === 'string'){

            str=str.replace(/\</g, '&lt;');

            el.innerHTML=str;
            if(el.innerText){

                str=el.innerText;
                el.innerText='';
            }
            else if(el.textContent){

                str=el.textContent;
                el.textContent='';
            }

            if(safeEscape)
                str=str.replace(/\</g, '&lt;');
        }
        return str;
    }
})();

And it's usable like:

var label='safe <b> character &eacute;ntity</b>';
var safehtml='<div title="'+decodeEntities(label)+'">'+decodeEntities(label, true)+'</div>';

Join String list elements with a delimiter in one step

You can use : org.springframework.util.StringUtils;

String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);

Parsing query strings on Android

On Android:

import android.net.Uri;

[...]

Uri uri=Uri.parse(url_string);
uri.getQueryParameter("para1");