Programs & Examples On #Specification pattern

LINQ to Entities does not recognize the method

As you've figured out, Entity Framework can't actually run your C# code as part of its query. It has to be able to convert the query to an actual SQL statement. In order for that to work, you will have to restructure your query expression into an expression that Entity Framework can handle.

public System.Linq.Expressions.Expression<Func<Charity, bool>> IsSatisfied()
{
    string name = this.charityName;
    string referenceNumber = this.referenceNumber;
    return p => 
        (string.IsNullOrEmpty(name) || 
            p.registeredName.ToLower().Contains(name.ToLower()) ||
            p.alias.ToLower().Contains(name.ToLower()) ||
            p.charityId.ToLower().Contains(name.ToLower())) &&
        (string.IsNullOrEmpty(referenceNumber) ||
            p.charityReference.ToLower().Contains(referenceNumber.ToLower()));
}

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

How to debug a stored procedure in Toad?

Open a PL/SQL object in the Editor.

Click on the main toolbar or select Session | Toggle Compiling with Debug. This enables debugging.

Compile the object on the database.

Select one of the following options on the Execute toolbar to begin debugging: Execute PL/SQL with debugger () Step over Step into Run to cursor

java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

I'm using Mac OS X Yosemite and Netbeans 8.02, I got the same error and the simple solution I have found is like above, this is useful when you need to include native library in the project. So do the next for Netbeans:

1.- Right click on the Project
2.- Properties
3.- Click on RUN
4.- VM Options: java -Djava.library.path="your_path"
5.- for example in my case: java -Djava.library.path=</Users/Lexynux/NetBeansProjects/NAO/libs>
6.- Ok

I hope it could be useful for someone. The link where I found the solution is here: java.library.path – What is it and how to use

Java String import

Java compiler imports 3 packages by default. 1. The package without name 2. The java.lang package(That's why you can declare String, Integer, System classes without import) 3. The current package (current file's package)

That's why you don't need to declare import statement for the java.lang package.

Get GPS location from the web browser

If you use the Geolocation API, it would be as simple as using the following code.

navigator.geolocation.getCurrentPosition(function(location) {
  console.log(location.coords.latitude);
  console.log(location.coords.longitude);
  console.log(location.coords.accuracy);
});

You may also be able to use Google's Client Location API.

This issue has been discussed in Is it possible to detect a mobile browser's GPS location? and Get position data from mobile browser. You can find more information there.

Adding blank spaces to layout

This can by be achieved by using space or view.

Space is lightweight but not much flexible.

View occupies a rectangular area on the screen and is responsible for drawing and event handling. View is more customizable, you can add background, draw shapes like space.

Implementing Space :

(Eg: Space For 20 vertical and 10 horizontal density pixels)

<Space
  android:layout_width="10dp"
  android:layout_height="20dp"/>

Implementing View :

(Eg: View For 20 vertical and 10 horizontal density pixels including a background color)

  <View
       android:layout_width="10dp"
       android:layout_height="20dp"
       android:background="@color/bg_color"/>

Space for string formatting using HTML entity:

&#160; for non-breakable whitespace. &#032; for regular space.

BeanFactory not initialized or already closed - call 'refresh' before

In my case, the error was valid and it was due to using try with resource

 try (ConfigurableApplicationContext cxt = new ClassPathXmlApplicationContext(
                    "classpath:application-main-config.xml")) {..
}

It auto closes the stream which should not happen if I want to reuse this context in other beans.

How can I generate a list of files with their absolute path in Linux?

You can do

ls -1 |xargs realpath

If you need to specify an absolute path or relative path You can do that as well

 ls -1 $FILEPATH |xargs realpath

Current date and time as string

I wanted to use the C++11 answer, but I could not because GCC 4.9 does not support std::put_time.

std::put_time implementation status in GCC?

I ended up using some C++11 to slightly improve the non-C++11 answer. For those that can't use GCC 5, but would still like some C++11 in their date/time format:

 std::array<char, 64> buffer;
 buffer.fill(0);
 time_t rawtime;
 time(&rawtime);
 const auto timeinfo = localtime(&rawtime);
 strftime(buffer.data(), sizeof(buffer), "%d-%m-%Y %H-%M-%S", timeinfo);
 std::string timeStr(buffer.data());

Is there a WebSocket client implemented for Python?

  1. Take a look at the echo client under http://code.google.com/p/pywebsocket/ It's a Google project.
  2. A good search in github is: https://github.com/search?type=Everything&language=python&q=websocket&repo=&langOverride=&x=14&y=29&start_value=1 it returns clients and servers.
  3. Bret Taylor also implemented web sockets over Tornado (Python). His blog post at: Web Sockets in Tornado and a client implementation API is shown at tornado.websocket in the client side support section.

Create <div> and append <div> dynamically

var iDiv = document.createElement('div');

iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

var div2 = document.createElement('div');

div2.className = 'block-2';
iDiv.appendChild(div2);

How to make git mark a deleted and a new file as a file move?

Use git mv command to move the files, instead of the OS move commands: https://git-scm.com/docs/git-mv

Please note that git mv command only exists in Git versions 1.8.5 and up. So you may have to update your Git to use this command.

Docker-compose: node_modules not present in a volume after npm install succeeds

There is also some simple solution without mapping node_module directory into another volume. It's about to move installing npm packages into final CMD command.

Disadvantage of this approach:

  • run npm install each time you run container (switching from npm to yarn might also speed up this process a bit).

worker/Dockerfile

FROM node:0.12
WORKDIR /worker
COPY package.json /worker/
COPY . /worker/
CMD /bin/bash -c 'npm install; npm start'

docker-compose.yml

redis:
    image: redis
worker:
    build: ./worker
    ports:
        - "9730:9730"
    volumes:
        - worker/:/worker/
    links:
        - redis

Angular 2 - How to navigate to another route using this.router.parent.navigate('/about')?

Also can use without parent

say router definition like:

{path:'/about',    name: 'About',   component: AboutComponent}

then can navigate by name instead of path

goToAboutPage() {
    this.router.navigate(['About']); // here "About" is name not path
}

Updated for V2.3.0

In Routing from v2.0 name property no more exist. route define without name property. so you should use path instead of name. this.router.navigate(['/path']) and no leading slash for path so use path: 'about' instead of path: '/about'

router definition like:

{path:'about', component: AboutComponent}

then can navigate by path

goToAboutPage() {
    this.router.navigate(['/about']); // here "About" is path
}

Convert stdClass object to array in PHP

There are two simple ways to convert stdClass Object to an Array

$array = get_object_vars($obj);

and other is

$array = json_decode(json_encode($obj), true);

or you can simply create array using foreach loop

$array = array();
foreach($obj as $key){
    $array[] = $key;
}
print_r($array);

How to get ip address of a server on Centos 7 in bash

Run this command to show ip4 and ip6:

ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1

Convert from enum ordinal to enum type

Every enum has name(), which gives a string with the name of enum member.

Given enum Suit{Heart, Spade, Club, Diamond}, Suit.Heart.name() will give Heart.

Every enum has a valueOf() method, which takes an enum type and a string, to perform the reverse operation:

Enum.valueOf(Suit.class, "Heart") returns Suit.Heart.

Why anyone would use ordinals is beyond me. It may be nanoseconds faster, but it is not safe, if the enum members change, as another developer may not be aware some code is relying on ordinal values (especially in the JSP page cited in the question, network and database overhead completely dominates the time, not using an integer over a string).

CSS Background Image Not Displaying

background : url (/img.. )

NOTE: If you have your css in a different folder, ensure that you start the image path with THE FORWARD SLASH.

It worked for me. !

Generating statistics from Git repository

I'm doing a git repository statistics generator in ruby, it's called git_stats.

You can find examples generated for some repositories on project page.

Here is a list of what it can do:

  • General statistics
    • Total files (text and binary)
    • Total lines (added and deleted)
    • Total commits
    • Authors
  • Activity (total and per author)
    • Commits by date
    • Commits by hour of day
    • Commits by day of week
    • Commits by hour of week
    • Commits by month of year
    • Commits by year
    • Commits by year and month
  • Authors
    • Commits by author
    • Lines added by author
    • Lines deleted by author
    • Lines changed by author
  • Files and lines
    • By date
    • By extension

If you have any idea what to add or improve please let me know, I would appreciate any feedback.

call javascript function onchange event of dropdown list

You just try this, Its so easy

 <script>

  $("#YourDropDownId").change(function () {
            alert($("#YourDropDownId").val());
        });

</script>

What is w3wp.exe?

w3wp.exe is a process associated with the application pool in IIS. If you have more than one application pool, you will have more than one instance of w3wp.exe running. This process usually allocates large amounts of resources. It is important for the stable and secure running of your computer and should not be terminated.

You can get more information on w3wp.exe here

http://www.processlibrary.com/en/directory/files/w3wp/25761/

C++ - How to append a char to char*?

char ch = 't';
char chArray[2];
sprintf(chArray, "%c", ch);
char chOutput[10]="tes";
strcat(chOutput, chArray);
cout<<chOutput;

OUTPUT:

test

Applying a single font to an entire website with CSS

Ok so I was having this issue where I tried several different options.

The font i'm using is Ubuntu-LI , I created a font folder in my working directory. under the folder fonts

I was able to apply it... eventually here is my working code

I wanted this to apply to my entire website so I put it at the top of the css doc. above all of the Div tags (not that it matters, just know that any individual fonts you assign post your script will take precedence)

@font-face{
    font-family: "Ubuntu-LI";
    src: url("/fonts/Ubuntu/(Ubuntu-LI.ttf"),
    url("../fonts/Ubuntu/Ubuntu-LI.ttf");
}

*{
    font-family:"Ubuntu-LI";
}

If i then wanted all of my H1 tags to be something else lets say sans sarif I would do something like

h1{
   font-family: Sans-sarif;
}

From which case only my H1 tags would be the sans-sarif font and the rest of my page would be the Ubuntu-LI font

The service cannot be started, either because it is disabled or because it has no enabled devices associated with it

This error can occur on anything that requires elevated privileges in Windows.

It happens when the "Application Information" service is disabled in Windows services. There are a few viruses that use this as an attack vector to prevent people from removing the virus. It also prevents people from installing software to remove viruses.

The normal way to fix this would be to run services.msc, or to go into Administrative Tools and run "Services". However, you will not be able to do that if the "Application Information" service is disabled.

Instead, reboot your computer into Safe Mode (reboot and press F8 until the Windows boot menu appears, select Safe Mode with Networking). Then run services.msc and look for services that are designated as "Disabled" in the Startup Type column. Change these "Disabled" services to "Automatic".

Make sure the "Application Information" service is set to a Startup Type of "Automatic".

When you are done enabling your services, click Ok at the bottom of the tool and reboot your computer back into normal mode. The problem should be resolved when Windows reboots.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Easiest way to use this function is to start by 'Recording a Macro'. Once you start recording, save the file to the location you want, with the name you want, and then of course set the file type, most likely 'Excel Macro Enabled Workbook' ~ 'XLSM'

Stop recording and you can start inspecting your code.

I wrote the code below which allows you to save a workbook using the path where the file was originally located, naming it as "Event [date in cell "A1"]"

Option Explicit

Sub SaveFile()

Dim fdate As Date
Dim fname As String
Dim path As String

fdate = Range("A1").Value
path = Application.ActiveWorkbook.path

If fdate > 0 Then
    fname = "Event " & fdate
    Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname, _
        FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
Else
    MsgBox "Chose a date for the event", vbOKOnly
End If

End Sub

Copy the code into a new module and then write a date in cell "A1" e.g. 01-01-2016 -> assign the sub to a button and run. [Note] you need to make a save file before this script will work, because a new workbook is saved to the default autosave location!

Angular 2 Hover event

@Component({
    selector: 'drag-drop',
    template: `
        <h1>Drag 'n Drop</h1>
        <div #container 
             class="container"
             (mousemove)="onMouseMove( container)">
            <div #draggable 
                 class="draggable"
                 (mousedown)="onMouseButton( container)"
                 (mouseup)="onMouseButton( container)">
            </div>
        </div>`,

})

http://lishman.io/angular-2-event-binding

Datetime BETWEEN statement not working in SQL Server

Does the second query return any results from the 17th, or just from the 18th?

The first query will only return results from the 17th, or midnight on the 18th.

Try this instead

select * 
from LOGS 
where check_in >= CONVERT(datetime,'2013-10-17') 
and check_in< CONVERT(datetime,'2013-10-19')

How can I stop a running MySQL query?

If you have mysqladmin available, you may get the list of queries with:

> mysqladmin -uUSERNAME -pPASSWORD pr

+-----+------+-----------------+--------+---------+------+--------------+------------------+
| Id  | User | Host            | db     | Command | Time | State        | Info             |
+-----+------+-----------------+--------+---------+------+--------------+------------------+
| 137 | beet | localhost:53535 | people | Query   | 292  | Sending data | DELETE FROM      |
| 145 | root | localhost:55745 |        | Query   | 0    |              | show processlist |
+-----+------+-----------------+--------+---------+------+--------------+------------------+

Then you may stop the mysql process that is hosting the long running query:

> mysqladmin -uUSERNAME -pPASSWORD kill 137

java.lang.ClassNotFoundException: org.springframework.web.context.ContextLoaderListener

For me the fix was to right click on my webapp module > Maven > Update Project

AngularJS check if form is valid in controller

Here is another solution

Set a hidden scope variable in your html then you can use it from your controller:

<span style="display:none" >{{ formValid = myForm.$valid}}</span>

Here is the full working example:

_x000D_
_x000D_
angular.module('App', [])_x000D_
.controller('myController', function($scope) {_x000D_
  $scope.userType = 'guest';_x000D_
  $scope.formValid = false;_x000D_
  console.info('Ctrl init, no form.');_x000D_
  _x000D_
  $scope.$watch('myForm', function() {_x000D_
    console.info('myForm watch');_x000D_
    console.log($scope.formValid);_x000D_
  });_x000D_
  _x000D_
  $scope.isFormValid = function() {_x000D_
    //test the new scope variable_x000D_
    console.log('form valid?: ', $scope.formValid);_x000D_
  };_x000D_
});
_x000D_
<!doctype html>_x000D_
<html ng-app="App">_x000D_
<head>_x000D_
 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.1/angular.min.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<form name="myForm" ng-controller="myController">_x000D_
  userType: <input name="input" ng-model="userType" required>_x000D_
  <span class="error" ng-show="myForm.input.$error.required">Required!</span><br>_x000D_
  <tt>userType = {{userType}}</tt><br>_x000D_
  <tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>_x000D_
  <tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>_x000D_
  <tt>myForm.$valid = {{myForm.$valid}}</tt><br>_x000D_
  <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>_x000D_
  _x000D_
  _x000D_
  /*-- Hidden Variable formValid to use in your controller --*/_x000D_
  <span style="display:none" >{{ formValid = myForm.$valid}}</span>_x000D_
  _x000D_
  _x000D_
  <br/>_x000D_
  <button ng-click="isFormValid()">Check Valid</button>_x000D_
 </form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I install the yaml package for Python?

There are three YAML capable packages. Syck (pip install syck) which implements the YAML 1.0 specification from 2002; PyYAML (pip install pyyaml) which follows the YAML 1.1 specification from 2004; and ruamel.yaml which follows the latest (YAML 1.2, from 2009) specification.

You can install the YAML 1.2 compatible package with pip install ruamel.yaml or if you are running a modern version of Debian/Ubuntu (or derivative) with:

sudo apt-get install python-ruamel.yaml

Simple way to find if two different lists contain exactly the same elements?

Sample code:

public static '<'T'>' boolean isListDifferent(List'<'T'>' previousList,
        List'<'T'>' newList) {

    int sizePrevoisList = -1;
    int sizeNewList = -1;

    if (previousList != null && !previousList.isEmpty()) {
        sizePrevoisList = previousList.size();
    }
    if (newList != null && !newList.isEmpty()) {
        sizeNewList = newList.size();
    }

    if ((sizePrevoisList == -1) && (sizeNewList == -1)) {
        return false;
    }

    if (sizeNewList != sizePrevoisList) {
        return true;
    }

    List n_prevois = new ArrayList(previousList);
    List n_new = new ArrayList(newList);

    try {
        Collections.sort(n_prevois);
        Collections.sort(n_new);
    } catch (ClassCastException exp) {
        return true;
    }

    for (int i = 0; i < sizeNewList; i++) {
        Object obj_prevois = n_prevois.get(i);
        Object obj_new = n_new.get(i);
        if (obj_new.equals(obj_prevois)) {
            // Object are same
        } else {
            return true;
        }
    }

    return false;
}

Server configuration is missing in Eclipse

This happens when Eclipse shuts down incorrectly - delete the server and then re-create it again.

Node.js + Nginx - What now?

You could also use node.js to generate static files into a directory served by nginx. Of course, some dynamic parts of your site could be served by node, and some by nginx (static).

Having some of them served by nginx increases your performance..

ValueError: invalid literal for int () with base 10

I am creating a program that reads a file and if the first line of the file is not blank, it reads the next four lines. Calculations are performed on those lines and then the next line is read.

Something like this should work:

for line in infile:
    next_lines = []
    if line.strip():
        for i in xrange(4):
            try:
                next_lines.append(infile.next())
            except StopIteration:
                break
    # Do your calculation with "4 lines" here

Prepend line to beginning of a file

with open("fruits.txt", "r+") as file:
    file.write("bab111y")
    file.seek(0)
    content = file.read()
    print(content)

FULL OUTER JOIN vs. FULL JOIN

Actually they are the same. LEFT OUTER JOIN is same as LEFT JOIN and RIGHT OUTER JOIN is same as RIGHT JOIN. It is more informative way to compare from INNER Join.

See this Wikipedia article for details.

Declaring and using MySQL varchar variables

I ran into the same problem using MySQL Workbench. According to the MySQL documentation, the DECLARE "statement declares local variables within stored programs." That apparently means it is only guaranteed to work with stored procedures/functions.

The solution for me was to simply remove the DECLARE statement, and introduce the variable in the SET statement. For your code that would mean:

-- DECLARE FOO varchar(7); 
-- DECLARE oldFOO varchar(7);

-- the @ symbol is required
SET @FOO = '138'; 
SET @oldFOO = CONCAT('0', FOO);

UPDATE mypermits SET person = FOO WHERE person = oldFOO;

How to specify in crontab by what user to run script?

Mike's suggestion sounds like the "right way". I came across this thread wanting to specify the user to run vncserver under on reboot and wanted to keep all my cron jobs in one place.

I was getting the following error for the VNC cron:

vncserver: The USER environment variable is not set. E.g.:

In my case, I was able to use sudo to specify who to run the task as.

@reboot sudo -u [someone] vncserver ...

Head and tail in one line

>>> mylist = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
>>> head, tail = mylist[0], mylist[1:]
>>> head
1
>>> tail
[1, 2, 3, 5, 8, 13, 21, 34, 55]

Select columns from result set of stored procedure

It might be helpful to know why this is so difficult. A stored procedure may only return text (print 'text'), or may return multiple tables, or may return no tables at all.

So something like SELECT * FROM (exec sp_tables) Table1 will not work

what are the .map files used for in Bootstrap 3.x?

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

This article explains Source Maps using a practical approach.

How can I get a specific field of a csv file?

import csv
mycsv = csv.reader(open(myfilepath))
for row in mycsv:
   text = row[1]

Following the comments to the SO question here, a best, more robust code would be:

import csv
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    for row in mycsv:
        text = row[1]
        ............

Update: If what the OP actually wants is the last string in the last row of the csv file, there are several aproaches that not necesarily needs csv. For example,

fulltxt = open(mifilepath, 'rb').read()
laststring = fulltxt.split(',')[-1]

This is not good for very big files because you load the complete text in memory but could be ok for small files. Note that laststring could include a newline character so strip it before use.

And finally if what the OP wants is the second string in line n (for n=2):

Update 2: This is now the same code than the one in the answer from J.F.Sebastian. (The credit is for him):

import csv
line_number = 2     
with open(myfilepath, 'rb') as f:
    mycsv = csv.reader(f)
    mycsv = list(mycsv)
    text = mycsv[line_number][1]
    ............

How can I get nth element from a list?

The straight answer was already given: Use !!.

However newbies often tend to overuse this operator, which is expensive in Haskell (because you work on single linked lists, not on arrays). There are several useful techniques to avoid this, the easiest one is using zip. If you write zip ["foo","bar","baz"] [0..], you get a new list with the indices "attached" to each element in a pair: [("foo",0),("bar",1),("baz",2)], which is often exactly what you need.

Check if the number is integer

you can use simple if condition like:

if(round(var) != var)­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­

How to check if a double value has no decimal part

Use number formatter to format the value, as required. Please check this.

Concatenating multiple text files into a single file in Bash

You can do like this: cat [directory_path]/**/*.[h,m] > test.txt

if you use {} to include the extension of the files you want to find, there is a sequencing problem.

What is special about /dev/tty?

The 'c' means it's a character special file.

Getting a slice of keys from a map

You also can take an array of keys with type []Value by method MapKeys of struct Value from package "reflect":

package main

import (
    "fmt"
    "reflect"
)

func main() {
    abc := map[string]int{
        "a": 1,
        "b": 2,
        "c": 3,
    }

    keys := reflect.ValueOf(abc).MapKeys()

    fmt.Println(keys) // [a b c]
}

Error during installing HAXM, VT-X not working

for Mac users, install the Intel HAXM kernel extension to allow the emulator to make use of CPU virtualization extensions.

The steps to configure VM acceleration are as follows:

  1. Open the SDK Manager.
  2. Click the SDK Update Sites tab and then select Intel HAXM.
  3. Click OK.
  4. After the download finishes, execute the installer. For example, it might be in this location: sdk/extras/intel/Hardware_Accelerated_Execution_Manager/IntelHAXM_version.dmg.
    To begin installation, in the Finder, double-click the IntelHAXM.dmg file and then the IntelHAXM.mpkg file.
  5. Follow the on-screen instructions to complete the installation.
  6. After installation finishes, confirm that the new kernel extension is operating correctly by opening a terminal window and running the following command:
    kextstat | grep intel You should see a status message containing the following extension name, indicating that the kernel extension is loaded:
    com.intel.kext.intelhaxm

Reference:
https://developer.android.com/studio/run/emulator-acceleration.html#vm-mac

PostgreSQL: Show tables in PostgreSQL

select 
  * 
from 
  pg_catalog.pg_tables 
where 
  schemaname != 'information_schema' 
  and schemaname != 'pg_catalog';

Convert base-2 binary number string to int

Using int with base is the right way to go. I used to do this before I found int takes base also. It is basically a reduce applied on a list comprehension of the primitive way of converting binary to decimal ( e.g. 110 = 2**0 * 0 + 2 ** 1 * 1 + 2 ** 2 * 1)

add = lambda x,y : x + y
reduce(add, [int(x) * 2 ** y for x, y in zip(list(binstr), range(len(binstr) - 1, -1, -1))])

How to change value of a request parameter in laravel

If you use custom requests for validation, for replace data for validation, or to set default data (for checkboxes or other) use override method prepareForValidation().

namespace App\Http\Requests\Admin\Category;
    
class CategoryRequest extends AbstractRequest
{
    protected function prepareForValidation()
    {
        if ( ! $this->get('url')) {
            $this->merge([
                'url' => $this->get('name'),
            ]);
        }
        $this->merge([
            'url'    => \Str::slug($this->get('url')),
            'active' => (int)$this->get('active'),
        ]);
    }
}

I hope this information will be useful to somebody.

How can I format DateTime to web UTC format?

You want to use DateTimeOffset class.

var date = new DateTimeOffset(2009, 9, 1, 0, 0, 0, 0, new TimeSpan(0L));
var stringDate = date.ToString("u");

sorry I missed your original formatting with the miliseconds

var stringDate = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");

How to use Visual Studio Code as Default Editor for Git

I opened up my .gitconfig and amended it with:

[core]
    editor = 'C:/Users/miqid/AppData/Local/Code/app-0.1.0/Code.exe'

That did it for me (I'm on Windows 8).

However, I noticed that after I tried an arbitrary git commit that in my Git Bash console I see the following message:

[9168:0504/160114:INFO:renderer_main.cc(212)] Renderer process started

Unsure of what the ramifications of this might be.

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

An explicit value for the identity column in table can only be specified when a column list is used and IDENTITY_INSERT is ON SQL Server

SET IDENTITY_INSERT tableA ON

INSERT Into tableA ([id], [c2], [c3], [c4], [c5] ) 
SELECT [id], [c2], [c3], [c4], [c5] FROM tableB

Not like this

INSERT INTO tableA
SELECT * FROM tableB

SET IDENTITY_INSERT tableA OFF

Android/Java - Date Difference in days

There's a simple solution, that at least for me, is the only feasible solution.

The problem is that all the answers I see being tossed around - using Joda, or Calendar, or Date, or whatever - only take the amount of milliseconds into consideration. They end up counting the number of 24-hour cycles between two dates, rather than the actual number of days. So something from Jan 1st 11pm to Jan 2nd 1am will return 0 days.

To count the actual number of days between startDate and endDate, simply do:

// Find the sequential day from a date, essentially resetting time to start of the day
long startDay = startDate.getTime() / 1000 / 60 / 60 / 24;
long endDay = endDate.getTime() / 1000 / 60 / 60 / 24;

// Find the difference, duh
long daysBetween = endDay - startDay;

This will return "1" between Jan 2nd and Jan 1st. If you need to count the end day, just add 1 to daysBetween (I needed to do that in my code since I wanted to count the total number of days in the range).

This is somewhat similar to what Daniel has suggested but smaller code I suppose.

How to use bootstrap datepicker

Just add this below JS file

<script type="text/javascript">
    $(document).ready(function () {
        $('your input's id or class with # or .').datepicker({
            format: "dd/mm/yyyy"
        });
    });
</script>

Django Rest Framework -- no module named rest_framework

rest_framework module

Try pressing the icon given if you are getting the following error:

"ModuleNotFoundError: No module named 'rest_framework'"

It will ask you to import the given package, that is rest_framework and run the code again.

This worked for me and trying to solve that error for a couple of days.

Verify ImageMagick installation

In Bash you can check if Imagick is an installed module:

$ php -m | grep imagick

If the response is blank it is not installed.

What does CultureInfo.InvariantCulture mean?

JetBrains offer a reasonable explanation,

"Ad-hoc conversion of data structures to text is largely dependent on the current culture, and may lead to unintended results when the code is executed on a machine whose locale differs from that of the original developer. To prevent ambiguities, ReSharper warns you of any instances in code where such a problem may occur."

but if I am working on a site I know will be in English only, I just ignore the suggestion.

Failed to decode downloaded font

I also had same problem but i have solved by adding 'Content-Type' : 'application/x-font-ttf' in response header for all .ttf files

What is the size of ActionBar in pixels?

One of the Honeycomb samples refers to ?android:attr/actionBarSize

dyld: Library not loaded ... Reason: Image not found

Is there an easy way to fix this?

I just used brew upgrade <the tool>. In my case, brew upgrade tmux.

Android Layout Weight

i would suppose to set the EditTexts width to wrap_content and put the two buttons into a LinearLayout whose width is fill_parent and weight set to 1.

CORS - How do 'preflight' an httprequest?

During the preflight request, you should see the following two headers: Access-Control-Request-Method and Access-Control-Request-Headers. These request headers are asking the server for permissions to make the actual request. Your preflight response needs to acknowledge these headers in order for the actual request to work.

For example, suppose the browser makes a request with the following headers:

Origin: http://yourdomain.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: X-Custom-Header

Your server should then respond with the following headers:

Access-Control-Allow-Origin: http://yourdomain.com
Access-Control-Allow-Methods: GET, POST
Access-Control-Allow-Headers: X-Custom-Header

Pay special attention to the Access-Control-Allow-Headers response header. The value of this header should be the same headers in the Access-Control-Request-Headers request header, and it can not be '*'.

Once you send this response to the preflight request, the browser will make the actual request. You can learn more about CORS here: http://www.html5rocks.com/en/tutorials/cors/

Plot inline or a separate window using Matplotlib in Spyder IDE

Go to Tools >> Preferences >> IPython console >> Graphics >> Backend:Inline, change "Inline" to "Automatic", click "OK"

Reset the kernel at the console, and the plot will appear in a separate window

scroll image with continuous scrolling using marquee tag

You cannot scroll images continuously using the HTML marquee tag - it must have JavaScript added for the continuous scrolling functionality.

There is a JavaScript plugin called crawler.js available on the dynamic drive forum for achieving this functionality. This plugin was created by John Davenport Scheuer and has been modified over time to suit new browsers.

I have also implemented this plugin into my blog to document all the steps to use this plugin. Here is the sample code:

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

<div id="mycrawler2" style="margin-top: -3px; " class="productswesupport">
    <img src="assets/images/products/ie.png" />
    <img src="assets/images/products/browser.png" />
    <img src="assets/images/products/chrome.png" />
    <img src="assets/images/products/safari.png" />
</div>

Here is the plugin configration:

marqueeInit({
    uniqueid: 'mycrawler2',
    style: {
    },
    inc: 5, //speed - pixel increment for each iteration of this marquee's movement
    mouse: 'cursor driven', //mouseover behavior ('pause' 'cursor driven' or false)
    moveatleast: 2,
    neutral: 150,
    savedirection: true,
    random: true
});

How to convert a single char into an int

You can make use of atoi() function

#include <stdlib.h>
#include <stdio.h>
int main(int argc, char* argv[]){
    int num ;
    num = atoi(argv[1]);
    printf("\n%d", num);
}

Magento - Retrieve products with a specific attribute value

To Get TEXT attributes added from admin to front end on product listing page.

Thanks Anita Mourya

I have found there is two methods. Let say product attribute called "na_author" is added from backend as text field.

METHOD 1

on list.phtml

<?php $i=0; foreach ($_productCollection as $_product): ?>

FOR EACH PRODUCT LOAD BY SKU AND GET ATTRIBUTE INSIDE FOREACH

<?php
$product = Mage::getModel('catalog/product')->loadByAttribute('sku',$_product->getSku());
$author = $product['na_author'];
?>

<?php
if($author!=""){echo "<br /><span class='home_book_author'>By ".$author ."</span>";} else{echo "";}
?>

METHOD 2

Mage/Catalog/Block/Product/List.phtml OVER RIDE and set in 'local folder'

i.e. Copy From

Mage/Catalog/Block/Product/List.phtml

and PASTE TO

app/code/local/Mage/Catalog/Block/Product/List.phtml

change the function by adding 2 lines shown in bold below.

protected function _getProductCollection()
{
       if (is_null($this->_productCollection)) {
           $layer = Mage::getSingleton('catalog/layer');
           /* @var $layer Mage_Catalog_Model_Layer */
           if ($this->getShowRootCategory()) {
               $this->setCategoryId(Mage::app()->getStore()->getRootCategoryId());
           }

           // if this is a product view page
           if (Mage::registry('product')) {
               // get collection of categories this product is associated with
               $categories = Mage::registry('product')->getCategoryCollection()
                   ->setPage(1, 1)
                   ->load();
               // if the product is associated with any category
               if ($categories->count()) {
                   // show products from this category
                   $this->setCategoryId(current($categories->getIterator()));
               }
           }

           $origCategory = null;
           if ($this->getCategoryId()) {
               $category = Mage::getModel('catalog/category')->load($this->getCategoryId());

               if ($category->getId()) {
                   $origCategory = $layer->getCurrentCategory();
                   $layer->setCurrentCategory($category);
               }
           }
           $this->_productCollection = $layer->getProductCollection();

           $this->prepareSortableFieldsByCategory($layer->getCurrentCategory());

           if ($origCategory) {
               $layer->setCurrentCategory($origCategory);
           }
       }
       **//CMI-PK added na_author to filter on product listing page//
       $this->_productCollection->addAttributeToSelect('na_author');**
       return $this->_productCollection;

}

and you will be happy to see it....!!

error: package javax.servlet does not exist

The answer provided by @Matthias Herlitzius is mostly correct. Just for further clarity.

The servlet-api jar is best left up to the server to manage see here for detail

With that said, the dependency to add may vary according to your server/container. For example in Wildfly the dependency would be

<dependency>
    <groupId>org.jboss.spec.javax.servlet</groupId>
    <artifactId>jboss-servlet-api_3.1_spec</artifactId>
    <scope>provided</scope>
</dependency>

So becareful to check how your container has provided the servlet implementation.

What are .a and .so files?

They are used in the linking stage. .a files are statically linked, and .so files are sort-of linked, so that the library is needed whenever you run the exe.

You can find where they are stored by looking at any of the lib directories... /usr/lib and /lib have most of them, and there is also the LIBRARY_PATH environment variable.

How can I display just a portion of an image in HTML/CSS?

Another alternative is the following, although not the cleanest as it assumes the image to be the only element in a container, such as in this case:

<header class="siteHeader">
  <img src="img" class="siteLogo" />
</header>

You can then use the container as a mask with the desired size, and surround the image with a negative margin to move it into the right position:

.siteHeader{
    width: 50px;
    height: 50px;
    overflow: hidden;
}

.siteHeader .siteLogo{
    margin: -100px;
}

Demo can be seen in this JSFiddle.

Only seems to work in IE>9, and probably all significant versions of all other browsers.

Show/hide forms using buttons and JavaScript

There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

_x000D_
_x000D_
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
    document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
    stuff hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

How to show a GUI message box from a bash script in linux?

Zenity is really the exact tool that I think that you are looking for.

or

zenity --help

How to rename a file using Python

os.rename(old, new)

This is found in the Python docs: http://docs.python.org/library/os.html

Print in one line dynamically

In [9]: print?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function print>
Namespace:      Python builtin
Docstring:
    print(value, ..., sep=' ', end='\n', file=sys.stdout)

Prints the values to a stream, or to sys.stdout by default.
Optional keyword arguments:
file: a file-like object (stream); defaults to the current sys.stdout.
sep:  string inserted between values, default a space.
end:  string appended after the last value, default a newline.

PHP Get URL with Parameter

for complette URL with protocol, servername and parameters:

 $base_url = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 'https' : 'http' ) . '://' .  $_SERVER['HTTP_HOST'];
 $url = $base_url . $_SERVER["REQUEST_URI"];

Android Service needs to run always (Never pause or stop)

Add this in manifest.

      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />

Add a service class.

public class YourServiceName extends Service {


    @Override
    public void onCreate() {
        super.onCreate();

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer 
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful

      return START_STICKY;
    }

}

How to mute an html5 video player using jQuery

$("video").prop('muted', true); //mute

AND

$("video").prop('muted', false); //unmute

See all events here

(side note: use attr if in jQuery < 1.6)

vertical & horizontal lines in matplotlib

The pyplot functions you are calling, axhline() and axvline() draw lines that span a portion of the axis range, regardless of coordinates. The parameters xmin or ymin use value 0.0 as the minimum of the axis and 1.0 as the maximum of the axis.

Instead, use plt.plot((x1, x2), (y1, y2), 'k-') to draw a line from the point (x1, y1) to the point (x2, y2) in color k. See pyplot.plot.

POST request with a simple string in body with Alamofire

let parameters = ["foo": "bar"]
              
    // All three of these calls are equivalent
    AF.request("https://httpbin.org/post", method: .post, parameters: parameters)
    AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder.default)
    AF.request("https://httpbin.org/post", method: .post, parameters: parameters, encoder: URLEncodedFormParameterEncoder(destination: .httpBody))
    
    

Passing variable number of arguments around

You can try macro also.

#define NONE    0x00
#define DBG     0x1F
#define INFO    0x0F
#define ERR     0x07
#define EMR     0x03
#define CRIT    0x01

#define DEBUG_LEVEL ERR

#define WHERESTR "[FILE : %s, FUNC : %s, LINE : %d]: "
#define WHEREARG __FILE__,__func__,__LINE__
#define DEBUG(...)  fprintf(stderr, __VA_ARGS__)
#define DEBUG_PRINT(X, _fmt, ...)  if((DEBUG_LEVEL & X) == X) \
                                      DEBUG(WHERESTR _fmt, WHEREARG,__VA_ARGS__)

int main()
{
    int x=10;
    DEBUG_PRINT(DBG, "i am x %d\n", x);
    return 0;
}

How to call a Parent Class's method from Child Class in Python?

There is a super() in python also.

Example for how a super class method is called from a sub class method

class Dog(object):
    name = ''
    moves = []

    def __init__(self, name):
        self.name = name

    def moves_setup(self,x):
        self.moves.append('walk')
        self.moves.append('run')
        self.moves.append(x)
    def get_moves(self):
        return self.moves

class Superdog(Dog):

    #Let's try to append new fly ability to our Superdog
    def moves_setup(self):
        #Set default moves by calling method of parent class
        super().moves_setup("hello world")
        self.moves.append('fly')
dog = Superdog('Freddy')
print (dog.name)
dog.moves_setup()
print (dog.get_moves()) 

This example is similar to the one explained above.However there is one difference that super doesn't have any arguments passed to it.This above code is executable in python 3.4 version.

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

SCRIPT

 <script type="text/javascript">
    $(function(){
        $("#gender").val("Male").attr("selected","selected");
    });
 </script>

HTML

<select id="gender" selected="selected">
    <option>--Select--</option>
    <option value="1">Male</option>
    <option value="2">Female</option>
</select>

Click Here More Details

Resizing an Image without losing any quality

Are you resizing larger, or smaller? By a small % or by a larger factor like 2x, 3x? What do you mean by quality for your application? And what type of images - photographs, hard-edged line drawings, or what? Writing your own low-level pixel grinding code or trying to do it as much as possible with existing libraries (.net or whatever)?

There is a large body of knowledge on this topic. The key concept is interpolation.

Browsing recommendations:
* http://www.all-in-one.ee/~dersch/interpolator/interpolator.html
* http://www.cambridgeincolour.com/tutorials/image-interpolation.htm
* for C#: https://secure.codeproject.com/KB/GDI-plus/imageprocessing4.aspx?display=PrintAll&fid=3657&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26&select=629945 * this is java-specific but might be educational - http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

I finally figured out the right answer to this question today.

<plugin>
    <groupId>org.apache.cxf</groupId>
    <artifactId>cxf-codegen-plugin</artifactId>
    <version>${cxf.version}</version>
    <executions>
        <execution>
            <id>generate-sources</id>
            <phase>generate-sources</phase>
            <configuration> 
                <sourceRoot>${project.build.directory}/generated-sources/cxf</sourceRoot>
                <wsdlOptions>
                    <wsdlOption>
                        <wsdl>${project.basedir}/src/main/resources/wsdl/FooService.wsdl</wsdl>
                        <wsdlLocation>classpath:wsdl/FooService.wsdl</wsdlLocation>
                    </wsdlOption>
                </wsdlOptions>
            </configuration>
            <goals>
                <goal>wsdl2java</goal>
            </goals>
        </execution>
    </executions>
</plugin>

Notice that I have prefixed the value in wsdlLocation with classpath:. This tells the plugin that the wsdl will be on the classpath instead of an absolute path. Then it will generate code similar to this:

@WebServiceClient(name = "FooService", 
                  wsdlLocation = "classpath:wsdl/FooService.wsdl",
                  targetNamespace = "http://org/example/foo") 
public class Foo_Service extends Service {

    public final static URL WSDL_LOCATION;

    public final static QName SERVICE = new QName("http://org/example/foo", "Foo");
    public final static QName FooSOAPOverHTTP = new QName("http://org/example/foo", "Foo_SOAPOverHTTP");
    static {
        URL url = Foo_Service.class.getClassLoader().getResource("wsdl/FooService.wsdl");
        if (url == null) {
            java.util.logging.Logger.getLogger(Foo_Service.class.getName())
                .log(java.util.logging.Level.INFO, 
                     "Can not initialize the default wsdl from {0}", "classpath:wsdl/FooService.wsdl");
        }       
        WSDL_LOCATION = url;
    }

Note that this only works with version 2.4.1 or newer of the cxf-codegen-plugin.

How to efficiently calculate a running standard deviation?

The Python runstats Module is for just this sort of thing. Install runstats from PyPI:

pip install runstats

Runstats summaries can produce the mean, variance, standard deviation, skewness, and kurtosis in a single pass of data. We can use this to create your "running" version.

from runstats import Statistics

stats = [Statistics() for num in range(len(data[0]))]

for row in data:

    for index, val in enumerate(row):
        stats[index].push(val)

    for index, stat in enumerate(stats):
        print 'Index', index, 'mean:', stat.mean()
        print 'Index', index, 'standard deviation:', stat.stddev()

Statistics summaries are based on the Knuth and Welford method for computing standard deviation in one pass as described in the Art of Computer Programming, Vol 2, p. 232, 3rd edition. The benefit of this is numerically stable and accurate results.

Disclaimer: I am the author the Python runstats module.

Storyboard - refer to ViewController in AppDelegate

If you use XCode 5 you should do it in a different way.

  • Select your UIViewController in UIStoryboard
  • Go to the Identity Inspector on the right top pane
  • Check the Use Storyboard ID checkbox
  • Write a unique id to the Storyboard ID field

Then write your code.

// Override point for customization after application launch.

if (<your implementation>) {
    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" 
                                                             bundle: nil];
    YourViewController *yourController = (YourViewController *)[mainStoryboard 
      instantiateViewControllerWithIdentifier:@"YourViewControllerID"];
    self.window.rootViewController = yourController;
}

return YES;

MYSQL order by both Ascending and Descending sorting

You can do that in this way:

ORDER BY `products`.`product_category_id` DESC ,`naam` ASC

Have a look at ORDER BY Optimization

How to make child process die after parent exits?

I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions.

The trick is:

  • process A is started
  • process A creates a pipe P (and never reads from it)
  • process A forks into process B
  • process B creates a new session
  • process B allocates a virtual terminal for that new session
  • process B installs SIGCHLD handler to die when the child exits
  • process B sets a SIGPIPE handler
  • process B forks into process C
  • process C does whatever it needs (e.g. exec()s the unmodified binary or runs whatever logic)
  • process B writes to pipe P (and blocks that way)
  • process A wait()s on process B and exits when it dies

That way:

  • if process A dies: process B gets a SIGPIPE and dies
  • if process B dies: process A's wait() returns and dies, process C gets a SIGHUP (because when the session leader of a session with a terminal attached dies, all processes in the foreground process group get a SIGHUP)
  • if process C dies: process B gets a SIGCHLD and dies, so process A dies

Shortcomings:

  • process C can't handle SIGHUP
  • process C will be run in a different session
  • process C can't use session/process group API because it'll break the brittle setup
  • creating a terminal for every such operation is not the best idea ever

How to replace an entire line in a text file by line number

I actually used this script to replace a line of code in the cron file on our company's UNIX servers awhile back. We executed it as normal shell script and had no problems:

#Create temporary file with new line in place
cat /dir/file | sed -e "s/the_original_line/the_new_line/" > /dir/temp_file
#Copy the new file over the original file
mv /dir/temp_file /dir/file

This doesn't go by line number, but you can easily switch to a line number based system by putting the line number before the s/ and placing a wildcard in place of the_original_line.

Object does not support item assignment error

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

The import com.google.android.gms cannot be resolved

Above solutions should solve your problem. If these do not, make sure you update your Android sdk using SDK manager and install the latest lib project and then repeat the above steps again.

How do I check for equality using Spark Dataframe without SQL Query?

We can write multiple Filter/where conditions in Dataframe.

For example:

table1_df
.filter($"Col_1_name" === "buddy")  // check for equal to string
.filter($"Col_2_name" === "A")
.filter(not($"Col_2_name".contains(" .sql")))  // filter a string which is    not relevent
.filter("Col_2_name is not null")   // no null filter
.take(5).foreach(println)

Can we have multiple <tbody> in same <table>?

According to this example it can be done: w3-struct-tables.

How do I create a MongoDB dump of my database?

There is a utility called : mongodump On the mongo command line you can type :

>./mongodump

The above will create a dump of all the databases on your localhost. To make dump of a single collection use:

./mongodump --db blog --collection posts

Have a look at : mongodump

What does the "assert" keyword do?

Use this version of the assert statement to provide a detail message for the AssertionError. The system passes the value of Expression2 to the appropriate AssertionError constructor, which uses the string representation of the value as the error's detail message.

The purpose of the detail message is to capture and communicate the details of the assertion failure. The message should allow you to diagnose and ultimately fix the error that led the assertion to fail. Note that the detail message is not a user-level error message, so it is generally unnecessary to make these messages understandable in isolation, or to internationalize them. The detail message is meant to be interpreted in the context of a full stack trace, in conjunction with the source code containing the failed assertion.

JavaDoc

How to align matching values in two columns in Excel, and bring along associated values in other columns

Skip all of this. Download Microsoft FUZZY LOOKUP add in. Create tables using your columns. Create a new worksheet. INPUT tables into the tool. Click all corresponding columns check boxes. Use slider for exact matches. HIT go and wait for the magic.

Create nice column output in python

Since Python 2.6+, you can use a format string in the following way to set the columns to a minimum of 20 characters and align text to right.

table_data = [
    ['a', 'b', 'c'],
    ['aaaaaaaaaa', 'b', 'c'], 
    ['a', 'bbbbbbbbbb', 'c']
]
for row in table_data:
    print("{: >20} {: >20} {: >20}".format(*row))

Output:

               a                    b                    c
      aaaaaaaaaa                    b                    c
               a           bbbbbbbbbb                    c

Module is not available, misspelled or forgot to load (but I didn't)

Using AngularJS 1.6.9+

There is one more incident, it also happen when you declare variable name different of module name.

var indexPageApp = angular.module('indexApp', []);

to get rid of this error,

Error: [$injector:nomod] Module 'indexPageApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

change the module name similar to var declared name or vice versa -

var indexPageApp = angular.module('indexPageApp', []);

Accessing @attribute from SimpleXML

You can just do:

echo $xml['token'];

How can I show and hide elements based on selected option with jQuery?

<script>  
$(document).ready(function(){
    $('#colorselector').on('change', function() {
      if ( this.value == 'red')
      {
        $("#divid").show();
      }
      else
      {
        $("#divid").hide();
      }
    });
});
</script>

Do like this for every value

How to count down in for loop?

First I recommand you can try use print and observe the action:

for i in range(0, 5, 1):
    print i

the result:

0
1
2
3
4

You can understand the function principle. In fact, range scan range is from 0 to 5-1. It equals 0 <= i < 5

When you really understand for-loop in python, I think its time we get back to business. Let's focus your problem.

You want to use a DECREMENT for-loop in python. I suggest a for-loop tutorial for example.

for i in range(5, 0, -1):
    print i

the result:

5
4
3
2
1

Thus it can be seen, it equals 5 >= i > 0

You want to implement your java code in python:

for (int index = last-1; index >= posn; index--)

It should code this:

for i in range(last-1, posn-1, -1)

Getting vertical gridlines to appear in line plot in matplotlib

Short answer (read below for more info):

ax.grid(axis='both', which='both')

enter image description here

What you do is correct and it should work.

However, since the X axis in your example is a DateTime axis the Major tick-marks (most probably) are appearing only at the both ends of the X axis. The other visible tick-marks are Minor tick-marks.

The ax.grid() method, by default, draws grid lines on Major tick-marks. Therefore, nothing appears in your plot.

Use the code below to highlight the tick-marks. Majors will be Blue while Minors are Red.

ax.tick_params(which='both', width=3)
ax.tick_params(which='major', length=20, color='b')
ax.tick_params(which='minor', length=10, color='r')

Now to force the grid lines to be appear also on the Minor tick-marks, pass the which='minor' to the method:

ax.grid(b=True, which='minor', axis='x', color='#000000', linestyle='--')

or simply use which='both' to draw both Major and Minor grid lines. And this a more elegant grid line:

ax.grid(b=True, which='minor', axis='both', color='#888888', linestyle='--')
ax.grid(b=True, which='major', axis='both', color='#000000', linestyle='-')

Sorting arraylist in alphabetical order (case insensitive)

KOTLIN DEVELOPERS

For Custome List, if you want to sort based on one String then you can use this:

phoneContactArrayList.sortWith(Comparator { item, t1 ->
        val s1: String = item.phoneContactUserName
        val s2: String = t1.phoneContactUserName
        s1.compareTo(s2, ignoreCase = true)
    })

How can I play sound in Java?

A bad example:

import  sun.audio.*;    //import the sun.audio package
import  java.io.*;

//** add this into your application code as appropriate
// Open an input stream  to the audio file.
InputStream in = new FileInputStream(Filename);

// Create an AudioStream object from the input stream.
AudioStream as = new AudioStream(in);         

// Use the static class member "player" from class AudioPlayer to play
// clip.
AudioPlayer.player.start(as);            

// Similarly, to stop the audio.
AudioPlayer.player.stop(as); 

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

try this

echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";

How do I supply an initial value to a text field?

inside class,

  final usernameController = TextEditingController(text: 'bhanuka');

TextField,

   child: new TextField(
        controller: usernameController,
    ...
)

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

You can use the built-in CSS class pre-scrollable in bootstrap 3 inside the span element of the dropdown and it works immediately without implementing custom css.

 <ul class="dropdown-menu pre-scrollable">
                <li>item 1 </li>
                <li>item 2 </li>

 </ul>

C# '@' before a String

It means to interpret the string literally (that is, you cannot escape any characters within the string if you use the @ prefix). It enhances readability in cases where it can be used.

For example, if you were working with a UNC path, this:

@"\\servername\share\folder"

is nicer than this:

"\\\\servername\\share\\folder"

var.replace is not a function

Replace wouldn't replace numbers. It replaces strings only.

This should work.

function trim(str) {
    return str.toString().replace(/^\s+|\s+$/g,'');
}

If you only want to trim the string. You can simply use "str.trim()"

Change the background color of CardView programmatically

In Kotlin, I was able to change the background color like this:

var card: CardView = itemView.findViewById(com.mullr.neurd.R.id.learn_def_card)
card.setCardBackgroundColor(ContextCompat.getColor(main,R.color.selected))

Then if you want to remove the color, you can do this:

card.setCardBackgroundColor(Color.TRANSPARENT)

Using this method I was able to create a selection animation.
https://gfycat.com/equalcarefreekitten

How to uncheck checked radio button

Radio buttons are meant to be required options... If you want them to be unchecked, use a checkbox, there is no need to complicate things and allow users to uncheck a radio button; removing the JQuery allows you to select from one of them

use localStorage across subdomains

this kind of solution causes many problems like this. for consistency and SEO considerations redirect on the main domain is the best solution.

do it redirection at the server level

How To Redirect www to Non-www with Nginx

https://www.digitalocean.com/community/tutorials/how-to-redirect-www-to-non-www-with-nginx-on-centos-7

or any other level like route 53 if are using

How can I check if a scrollbar is visible?

Find a parent of current element that has vertical scrolling or body.

$.fn.scrollableParent = function() {
    var $parents = this.parents();

    var $scrollable = $parents.filter(function(idx) {
        return this.scrollHeight > this.offsetHeight && this.offsetWidth !== this.clientWidth;
    }).first();

    if ($scrollable.length === 0) {
        $scrollable = $('html, body');
    }
    return $scrollable;
};

It may be used to autoscroll to current element via:

var $scrollable = $elem.scrollableParent();
$scrollable.scrollTop($elem.position().top);

Automatically open Chrome developer tools when new tab/new window is opened

On opening the developer tools, with the developer tools window in focus, press F1. This will open a settings page. Check the "Auto-open DevTools for popups".

This worked for me.

Screenshot

Work on a remote project with Eclipse via SSH

I tried ssh -X but it was unbearably slow.

I also tried RSE, but it didn't even support building the project with a Makefile (I'm being told that this has changed since I posted my answer, but I haven't tried that out)

I read that NX is faster than X11 forwarding, but I couldn't get it to work.

Finally, I found out that my server supports X2Go (the link has install instructions if yours does not). Now I only had to:

  • download and unpack Eclipse on the server,
  • install X2Go on my local machine (sudo apt-get install x2goclient on Ubuntu),
  • configure the connection (host, auto-login with ssh key, choose to run Eclipse).

Everything is just as if I was working on a local machine, including building, debugging, and code indexing. And there are no noticeable lags.

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database

If you are getting this after replacing your database files using the Device File Explorer, sometimes this happens due to permissions and SELinux security contexts. The Device File Explorer (as of AS3.6.3) will upload them with root permissions/rwxrwxrwx set for all (777). Look around in your app folders for the user id used for your app. Execute the following commands in terminal:

   adb devices
   emulator-5554
   adb root
   adb -s emulator-5554 shell
   cd /data/data/com.yourorg.yourapp
   ls -l

You'll get a listing like:

drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 cache
drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 code_cache
drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 databases
drwxrwx--x 2 u0_a85 u0_a85 4096 2020-04-23 16:09 shared_prefs

u0_a85 (or whatever it might be) will be the app owner and group id. Delete your databases on the device, drop in your replacement database files using Device File Explorer, and in terminal, execute the following (keeping in mind the owner id):

cd databases
chown u0_a85 *.db; chgrp u0_a85 *.db; chmod 600 *.db; restorecon *.db

This changes the database files to their appropriate owner/group id, RW permissions, and resets the SELinux security contexts for those files. Although I have had success replacing database files NOT having to do this, this problem seems to happen randomly enough that doing this works.

How to add content to html body using JS?

Try the following syntax:

document.body.innerHTML += "<p>My new content</p>";

How to get span tag inside a div in jQuery and assign a text?

$("#message > span").text("your text");

or

$("#message").find("span").text("your text");

or

$("span","#message").text("your text");

or

$("#message > a.close-notify").siblings('span').text("your text");

Preferred Java way to ping an HTTP URL for availability

The following code performs a HEAD request to check whether the website is available or not.

public static boolean isReachable(String targetUrl) throws IOException
{
    HttpURLConnection httpUrlConnection = (HttpURLConnection) new URL(
            targetUrl).openConnection();
    httpUrlConnection.setRequestMethod("HEAD");

    try
    {
        int responseCode = httpUrlConnection.getResponseCode();

        return responseCode == HttpURLConnection.HTTP_OK;
    } catch (UnknownHostException noInternetConnection)
    {
        return false;
    }
}

How can I update my ADT in Eclipse?

Running as administrator then following other comments fixed the problem for me :)

Font awesome is not showing icon

_x000D_
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.11.2/js/all.js" integrity="sha256-2JRzNxMJiS0aHOJjG+liqsEOuBb6++9cY4dSOyiijX4=" crossorigin="anonymous"></script>
_x000D_
_x000D_
_x000D_

LINQ Group By and select collection

you can achive it with group join

var result = (from c in Customers
          join oi in OrderItems on c.Id equals oi.Order.Customer.Id into g
          Select new { customer = c, orderItems = g});

c is Customer and g is the customers order items.

CSS - Syntax to select a class within an id

.navigationLevel2 li { color: #aa0000 }

"fatal: Not a git repository (or any of the parent directories)" from git status

I had another problem. I was in a git directory, but got there through a symlink. I had to go into the directory directly (i.e. not through the symlink) then it worked fine.

Is there a job scheduler library for node.js?

later.js is a pretty good JavaScript "scheduler" library. Can run on Node.js or in a web browser.

How do you detect the clearing of a "search" HTML5 input?

document.querySelectorAll('input[type=search]').forEach(function (input) {
   input.addEventListener('mouseup', function (e) {
                if (input.value.length > 0) {
                    setTimeout(function () {
                        if (input.value.length === 0) {
                            //do reset action here
                        }
                    }, 5);
                }
            });
}

ECMASCRIPT 2016

Plot correlation matrix using pandas

You can use imshow() method from matplotlib

import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('ggplot')

plt.imshow(X.corr(), cmap=plt.cm.Reds, interpolation='nearest')
plt.colorbar()
tick_marks = [i for i in range(len(X.columns))]
plt.xticks(tick_marks, X.columns, rotation='vertical')
plt.yticks(tick_marks, X.columns)
plt.show()

get all the images from a folder in php

Check if exist, put all files in array, preg grep all JPG files, echo new array For all images could try this:

$images=preg_grep('/\.(jpg|jpeg|png|gif)(?:[\?\#].*)?$/i', $files);


if ($handle = opendir('/path/to/folder')) {

    while (false !== ($entry = readdir($handle))) {
        $files[] = $entry;
    }
    $images=preg_grep('/\.jpg$/i', $files);

    foreach($images as $image)
    {
    echo $image;
    }
    closedir($handle);
}

Configure hibernate to connect to database via JNDI Datasource

Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">



  <jee:jndi-lookup id="dataSource"
                 jndi-name="Give_DataSource_Path_From_Your_Server"
                 expected-type="javax.sql.DataSource" />


Hope It will help someone.Thanks!

iPhone UILabel text soft shadow

While it's impossible to set a blur radius directly on UILabel, you definitely could change it by manipulating CALayer.

Just set:

//Required properties
customLabel.layer.shadowRadius = 5.0 //set shadow radius to your desired value.
customLabel.layer.shadowOpacity = 1.0 //Choose an opacity. Make sure it's visible (default is 0.0)

//Other options
customLabel.layer.shadowOffset = CGSize(width: 10, height: 10)
customLabel.layer.shadowColor = UIColor.black.cgColor
customLabel.layer.masksToBounds = false

What I hope will help someone and other answers failed to clarify is that it will not work if you also set UILabel Shadow Color property directly on Interface Builder while trying to setup .layer.shadowRadius.

So if setting label.layer.shadowRadius didn't work, please verify Shadow Color for this UILabel on Interface Builder. It should be set to default. And then, please, if you want a shadow color other than black, set this color also through .layer property.

enter image description here

Illegal character in path at index 16

I got this error today and unlike all the above answers my error was due to a new reason.

In my Japanese translation strings.xml file, I had removed a required string.

Some how android mixed up all the other string and this caused an error.

The solution was to include all the strings from my normal, English strings.xml

Including those strings which weren't translated to Japanese.

How to import JsonConvert in C# application?

If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            return Json(lstAccounts);
        }
    }
}

If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            //This line is different !! 
            return new JsonConvert.SerializeObject(lstAccounts);
        }
    }
}

More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

Programmatically set TextBlock Foreground Color

Foreground needs a Brush, so you can use

textBlock.Foreground = Brushes.Navy;

If you want to use the color from RGB or ARGB then

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(System.Windows.Media.Color.FromArgb(100, 255, 125, 35)); 

or

textBlock.Foreground = new System.Windows.Media.SolidColorBrush(Colors.Navy); 

To get the Color from Hex

textBlock.Foreground = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFDFD991")); 

Creating virtual directories in IIS express

A new option is Jexus Manager for IIS Express,

https://blog.lextudio.com/2014/10/jexus-manager-for-iis-express/

It is just the management tool you know how to use.

Chrome's remote debugging (USB debugging) not working for Samsung Galaxy S3 running android 4.3

For me the solution was to download the Android SDK and launch adb devices which started the adb daemon.

How to send password securely over HTTP?

If your webhost allows it, or you will need to deal with sensitive data, then use HTTPS, period. (It's often required by the law afaik).

Otherwise if you want to do something over HTTP. I would do something like this.

  1. The server embeds its public key into the login page.
  2. The client populates the login form and clicks submit.
  3. An AJAX request gets the current timestamp from the server.
  4. Client side script concatenates the credentials, the timestamp and a salt (hashed from analog data eg. mouse movements, key press events), encrypts it using the public key.
  5. Submits the resulting hash.
  6. Server decrypts the hash
  7. Checks if the timestamp is recent enough (allows a short 5-10 second window only). Rejects the login if the timestamp is too old.
  8. Stores the hash for 20 seconds. Rejects the same hash for login during this interval.
  9. Authenticates the user.

So this way the password is protected and the same authentication hash cannot be replayed.

About the security of the session token. That's a bit harder. But it's possible to make reusing a stolen session token a bit harder.

  1. The server sets an extra session cookie which contains a random string.
  2. The browser sends back this cookie on the next request.
  3. The server checks the value in the cookie, if it's different then it destroys the session, otherwise all is okay.
  4. The server sets the cookie again with different text.

So if the session token got stolen, and a request is sent up by someone else, then on the original user's next request the session will be destroyed. So if the user actively browsing the site, clicking on links often, then the thief won't go far with the stolen token. This scheme can be fortified by requiring another authentication for the sensitive operations (like account deletion).

EDIT: Please note this doesn't prevent MITM attacks if the attacker sets up their own page with a different public key and proxies requests to the server. To protect against this the public key must be pinned in the browser's local storage or within the app to detect these kind of tricks.

About the implementation: RSA is probably to most known algorithm, but it's quite slow for long keys. I don't know how fast a PHP or Javascript implementation of would be. But probably there are a faster algorithms.

How eliminate the tab space in the column in SQL Server 2008

Try this code

SELECT REPLACE([Column], char(9), '') From [dbo.Table] 

char(9) is the TAB character

Closing a file after File.Create

File.Create(string) returns an instance of the FileStream class. You can call the Stream.Close() method on this object in order to close it and release resources that it's using:

var myFile = File.Create(myPath);
myFile.Close();

However, since FileStream implements IDisposable, you can take advantage of the using statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:

using (var myFile = File.Create(myPath))
{
   // interact with myFile here, it will be disposed automatically
}

How can get the text of a div tag using only javascript (no jQuery)

You can use innerHTML(then parse text from HTML) or use innerText.

let textContentWithHTMLTags = document.querySelector('div').innerHTML; 
let textContent = document.querySelector('div').innerText;

console.log(textContentWithHTMLTags, textContent);

innerHTML and innerText is supported by all browser(except FireFox < 44) including IE6.

Plot Normal distribution with Matplotlib

Note: This solution is using pylab, not matplotlib.pyplot

You may try using hist to put your data info along with the fitted curve as below:

import numpy as np
import scipy.stats as stats
import pylab as pl

h = sorted([186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180])  #sorted

fit = stats.norm.pdf(h, np.mean(h), np.std(h))  #this is a fitting indeed

pl.plot(h,fit,'-o')

pl.hist(h,normed=True)      #use this to draw histogram of your data

pl.show()                   #use may also need add this 

enter image description here

JavaScript: filter() for Objects

Like everyone said, do not screw around with prototype. Instead, simply write a function to do so. Here is my version with lodash:

import each from 'lodash/each';
import get from 'lodash/get';

const myFilteredResults = results => {
  const filteredResults = [];

  each(results, obj => {
    // filter by whatever logic you want.

    // sample example
    const someBoolean = get(obj, 'some_boolean', '');

    if (someBoolean) {
      filteredResults.push(obj);
    }
  });

  return filteredResults;
};

How to Remove Array Element and Then Re-Index Array?

Unset($array[0]); 

Sort($array); 

I don't know why this is being downvoted, but if anyone has bothered to try it, you will notice that it works. Using sort on an array reassigns the keys of the the array. The only drawback is it sorts the values. Since the keys will obviously be reassigned, even with array_values, it does not matter is the values are being sorted or not.

Ignore .pyc files in git repository

Thanks @Enrico for the answer.

Note if you're using virtualenv you will have several more .pyc files within the directory you're currently in, which will be captured by his find command.

For example:

./app.pyc
./lib/python2.7/_weakrefset.pyc
./lib/python2.7/abc.pyc
./lib/python2.7/codecs.pyc
./lib/python2.7/copy_reg.pyc
./lib/python2.7/site-packages/alembic/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/__init__.pyc
./lib/python2.7/site-packages/alembic/autogenerate/api.pyc

I suppose it's harmless to remove all the files, but if you only want to remove the .pyc files in your main directory, then just do

find "*.pyc" -exec git rm -f "{}" \;

This will remove just the app.pyc file from the git repository.

How to read fetch(PDO::FETCH_ASSOC);

/* Design Pattern "table-data gateway" */

class Gateway
{
    protected $connection = null;

    public function __construct()
    {
        $this->connection = new PDO("mysql:host=localhost; dbname=db_users", 'root', '');
    }

    public function loadAll()
    {
        $sql = 'SELECT * FROM users';
        $rows = $this->connection->query($sql);

        return $rows;
    }

    public function loadById($id)
    {
        $sql = 'SELECT * FROM users WHERE user_id = ' . (int) $id;
        $result = $this->connection->query($sql);

        return $result->fetch(PDO::FETCH_ASSOC);
        // http://php.net/manual/en/pdostatement.fetch.php //                   
    }
}

/* Print all row with column 'user_id' only */

$gateway  = new Gateway();
$users    = $gateway->loadAll();

$no = 1;
foreach ($users as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value['user_id'] . '<br />';
    $no++;
}

/* Print user_id = 1 with all column */

$user = $gateway->loadById(1);

$no = 1;
foreach ($user as $key => $value) {
    echo $no . '. ' . $key . ' => ' . $value . '<br />';
    $no++;
}

/* Print user_id = 1 with column 'email and password' */

$user = $gateway->loadById(1);

echo $user['email'];
echo $user['password'];

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

If you have Cygwin installed in your PC, you can simply use the supplied executable for touch (also via windows command prompt):

C:\cygwin64\bin\touch.exe <file_path>

Android ImageView Zoom-in and Zoom-Out

Make two java classes

Zoom class

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;

public class Zoom extends View {

    private Drawable image;
    ImageButton img,img1;
    private int zoomControler=20;

    public Zoom(Context context){
            super(context);

            image=context.getResources().getDrawable(R.drawable.j);
            //image=context.getResources().getDrawable(R.drawable.icon);

            setFocusable(true);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        //here u can control the width and height of the images........ this line is very important
        image.setBounds((getWidth()/2)-zoomControler, (getHeight()/2)-zoomControler, (getWidth()/2)+zoomControler, (getHeight()/2)+zoomControler);
        image.draw(canvas);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

            if(keyCode==KeyEvent.KEYCODE_DPAD_UP){
                    // zoom in
                    zoomControler+=10;
            }
            if(keyCode==KeyEvent.KEYCODE_DPAD_DOWN){
                    // zoom out
                    zoomControler-=10;
            }
            if(zoomControler<10){
                    zoomControler=10;
            }

            invalidate();
            return true;
    }
}

make second class

import android.app.Activity;
import android.os.Bundle;

public class Zoomexample extends Activity {
   /** Called when the activity is first created. */

   @Override
   public void onCreate(Bundle icicle) {
       super.onCreate(icicle);
       setContentView(new Zoom(this));
   }
}

Set color of TextView span in Android

Just to add to the accepted answer, as all the answers seem to talk about android.graphics.Color only: what if the color I want is defined in res/values/colors.xml?

For example, consider Material Design colors defined in colors.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="md_blue_500">#2196F3</color>
</resources>

(android_material_design_colours.xml is your best friend)

Then use ContextCompat.getColor(getContext(), R.color.md_blue_500) where you would use Color.BLUE, so that:

wordtoSpan.setSpan(new ForegroundColorSpan(Color.BLUE), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

becomes:

wordtoSpan.setSpan(new ForegroundColorSpan(ContextCompat.getColor(getContext(), R.color.md_blue_500)), 15, 30, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

Where I found that:

How can I shuffle the lines of a text file on the Unix command line or in a shell script?

Perl one-liner would be a simple version of Maxim's solution

perl -MList::Util=shuffle -e 'print shuffle(<STDIN>);' < myfile

How to generate a random string of 20 characters

Here you go. Just specify the chars you want to allow on the first line.

char[] chars = "abcdefghijklmnopqrstuvwxyz".toCharArray();
StringBuilder sb = new StringBuilder(20);
Random random = new Random();
for (int i = 0; i < 20; i++) {
    char c = chars[random.nextInt(chars.length)];
    sb.append(c);
}
String output = sb.toString();
System.out.println(output);

If you are using this to generate something sensitive like a password reset URL or session ID cookie or temporary password reset, be sure to use java.security.SecureRandom instead. Values produced by java.util.Random and java.util.concurrent.ThreadLocalRandom are mathematically predictable.

how do I create an infinite loop in JavaScript

You can also use a while loop:

while (true) {
    //your code
}

Swift - encode URL

Swift 4:

It depends by the encoding rules followed by your server.

Apple offer this class method, but it don't report wich kind of RCF protocol it follows.

var escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

Following this useful tool you should guarantee the encoding of these chars for your parameters:

  • $ (Dollar Sign) becomes %24
  • & (Ampersand) becomes %26
  • + (Plus) becomes %2B
  • , (Comma) becomes %2C
  • : (Colon) becomes %3A
  • ; (Semi-Colon) becomes %3B
  • = (Equals) becomes %3D
  • ? (Question Mark) becomes %3F
  • @ (Commercial A / At) becomes %40

In other words, speaking about URL encoding, you should following the RFC 1738 protocol.

And Swift don't cover the encoding of the + char for example, but it works well with these three @ : ? chars.

So, to correctly encoding each your parameter , the .urlHostAllowed option is not enough, you should add also the special chars as for example:

encodedParameter = parameter.replacingOccurrences(of: "+", with: "%2B")

Hope this helps someone who become crazy to search these informations.

Accessing post variables using Java Servlets

POST variables should be accessible via the request object: HttpRequest.getParameterMap(). The exception is if the form is sending multipart MIME data (the FORM has enctype="multipart/form-data"). In that case, you need to parse the byte stream with a MIME parser. You can write your own or use an existing one like the Apache Commons File Upload API.

Spring Boot - How to log all requests and responses with exceptions in single place?

Don't write any Interceptors, Filters, Components, Aspects, etc., this is a very common problem and has been solved many times over.

Spring Boot has a modules called Actuator, which provides HTTP request logging out of the box. There's an endpoint mapped to /trace (SB1.x) or /actuator/httptrace (SB2.0+) which will show you last 100 HTTP requests. You can customize it to log each request, or write to a DB.

To get the endpoints you want, you'll need the spring-boot-starter-actuator dependency, and also to "whitelist" the endpoints you're looking for, and possibly setup or disable security for it.

Also, where will this application run? Will you be using a PaaS? Hosting providers, Heroku for example, provide request logging as part of their service and you don't need to do any coding whatsoever then.

yum error "Cannot retrieve metalink for repository: epel. Please verify its path and try again" updating ContextBroker

You just needed to update ca-certificates package. Before that just disable all repos with https that are failing. That's why solution with commenting mirrorlist or using http instead https would work also.

For example if you need to disable only epel repo:

yum --disablerepo=epel -y update  ca-certificates

This will also help wget, curl, and anything else that uses SSL certificates.

Array of an unknown length in C#

You can create an array with the size set to a variable, i.e.

int size = 50;
string[] words = new string[size]; // contains 50 strings

However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.

jQuery show/hide options from one select drop down, when option on other select dropdown is slected

Try -

$("#column_select").change(function () {
    $("#layout_select").children('option').hide();
    $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
})  

If you were going to use this solution you'd need to hide all of the elements apart from the one with the 'none' value in your document.ready function -

$(document).ready(function() {
    $("#layout_select").children('option:gt(0)').hide();
    $("#column_select").change(function() {
        $("#layout_select").children('option').hide();
        $("#layout_select").children("option[value^=" + $(this).val() + "]").show()
    })
})

Demo - http://jsfiddle.net/Mxkfr/2

EDIT

I might have got a bit carried away with this, but here's a further example that uses a cache of the original select list options to ensure that the 'layout_select' list is completely reset/cleared (including the 'none' option) after the 'column_select' list is changed -

$(document).ready(function() {
    var optarray = $("#layout_select").children('option').map(function() {
        return {
            "value": this.value,
            "option": "<option value='" + this.value + "'>" + this.text + "</option>"
        }
    })

    $("#column_select").change(function() {
        $("#layout_select").children('option').remove();
        var addoptarr = [];
        for (i = 0; i < optarray.length; i++) {
            if (optarray[i].value.indexOf($(this).val()) > -1) {
                addoptarr.push(optarray[i].option);
            }
        }
        $("#layout_select").html(addoptarr.join(''))
    }).change();
})

Demo - http://jsfiddle.net/N7Xpb/1/

Streaming a video file to an html5 video player with Node.js so that the video controls continue to work?

The Accept Ranges header (the bit in writeHead()) is required for the HTML5 video controls to work.

I think instead of just blindly send the full file, you should first check the Accept Ranges header in the REQUEST, then read in and send just that bit. fs.createReadStream support start, and end option for that.

So I tried an example and it works. The code is not pretty but it is easy to understand. First we process the range header to get the start/end position. Then we use fs.stat to get the size of the file without reading the whole file into memory. Finally, use fs.createReadStream to send the requested part to the client.

var fs = require("fs"),
    http = require("http"),
    url = require("url"),
    path = require("path");

http.createServer(function (req, res) {
  if (req.url != "/movie.mp4") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end('<video src="http://localhost:8888/movie.mp4" controls></video>');
  } else {
    var file = path.resolve(__dirname,"movie.mp4");
    fs.stat(file, function(err, stats) {
      if (err) {
        if (err.code === 'ENOENT') {
          // 404 Error if file not found
          return res.sendStatus(404);
        }
      res.end(err);
      }
      var range = req.headers.range;
      if (!range) {
       // 416 Wrong range
       return res.sendStatus(416);
      }
      var positions = range.replace(/bytes=/, "").split("-");
      var start = parseInt(positions[0], 10);
      var total = stats.size;
      var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
      var chunksize = (end - start) + 1;

      res.writeHead(206, {
        "Content-Range": "bytes " + start + "-" + end + "/" + total,
        "Accept-Ranges": "bytes",
        "Content-Length": chunksize,
        "Content-Type": "video/mp4"
      });

      var stream = fs.createReadStream(file, { start: start, end: end })
        .on("open", function() {
          stream.pipe(res);
        }).on("error", function(err) {
          res.end(err);
        });
    });
  }
}).listen(8888);

HashMap allows duplicates?

Hashmap type Overwrite that key if hashmap key is same key

map.put("1","1111");
map.put("1","2222");

output

key:value
1:2222

How can I slice an ArrayList out of an ArrayList in Java?

Although this post is very old. In case if somebody is looking for this..

Guava facilitates partitioning the List into sublists of a specified size

List<Integer> intList = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8);
    List<List<Integer>> subSets = Lists.partition(intList, 3);

What is the difference between a mutable and immutable string in C#?

Strings are mutable because .NET use string pool behind the scene. It means :

string name = "My Country";
string name2 = "My Country";

Both name and name2 are referring to same memory location from string pool. Now suppose you want to change name2 to :

name2 = "My Loving Country";

It will look in to string pool for the string "My Loving Country", if found you will get the reference of it other wise new string "My Loving Country" will be created in string pool and name2 will get reference of it. But it this whole process "My Country" was not changed because other variable like name is still using it. And that is the reason why string are IMMUTABLE.

StringBuilder works in different manner and don't use string pool. When we create any instance of StringBuilder :

var address  = new StringBuilder(500);

It allocate memory chunk of size 500 bytes for this instance and all operation just modify this memory location and this memory not shared with any other object. And that is the reason why StringBuilder is MUTABLE.

I hope it will help.

Write in body request with HttpClient

Extending your code (assuming that the XML you want to send is in xmlString) :

String xmlString = "</xml>";
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpRequest = new HttpPost(this.url);
httpRequest.setHeader("Content-Type", "application/xml");
StringEntity xmlEntity = new StringEntity(xmlString);
httpRequest.setEntity(xmlEntity );
HttpResponse httpresponse = httpclient.execute(httppost);

Spring boot - Not a managed type

I think replacing @ComponentScan with @ComponentScan("com.nervy.dialer.domain") will work.

Edit :

I have added a sample application to demonstrate how to set up a pooled datasource connection with BoneCP.

The application has the same structure with yours. I hope this will help you to resolve your configuration problems

How can I view the allocation unit size of a NTFS partition in Vista?

Another way to find it quickly via the GUI on any windows system:

  1. create a text file, type a word or two (or random text) in it, and save it.

  2. Right-click on the file to show Properties.

  3. "Size on disk" = allocation unit.

What is the difference between Google App Engine and Google Compute Engine?

App Engine is a Platform-as-a-Service. It means that you simply deploy your code, and the platform does everything else for you. For example, if your app becomes very successful, App Engine will automatically create more instances to handle the increased volume.

Read more about App Engine

Compute Engine is an Infrastructure-as-a-Service. You have to create and configure your own virtual machine instances. It gives you more flexibility and generally costs much less than App Engine. The drawback is that you have to manage your app and virtual machines yourself.

Read more about Compute Engine

You can mix both App Engine and Compute Engine, if necessary. They both work well with the other parts of the Google Cloud Platform.

EDIT (May 2016):

One more important distinction: projects running on App Engine can scale down to zero instances if no requests are coming in. This is extremely useful at the development stage as you can go for weeks without going over the generous free quota of instance-hours. Flexible runtime (i.e. "managed VMs") require at least one instance to run constantly.

EDIT (April 2017):

Cloud Functions (currently in beta) is the next level up from App Engine in terms of abstraction - no instances! It allows developers to deploy bite-size pieces of code that execute in response to different events, which may include HTTP requests, changes in Cloud Storage, etc.

The biggest difference with App Engine is that functions are priced per 100 milliseconds, while App Engine's instances shut down only after 15 minutes of inactivity. Another advantage is that Cloud Functions execute immediately, while a call to App Engine may require a new instance - and cold-starting a new instance may take a few seconds or longer (depending on runtime and your code).

This makes Cloud Functions ideal for (a) rare calls - no need to keep an instance live just in case something happens, (b) rapidly changing loads where instances are often spinning and shutting down, and possibly more use cases.

Read more about Cloud Functions

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

I would say echo() ing them directly into the Javascript source code is the most reliable and downward compatible way. Stay with that unless you have a good reason not to.

How do I register a .NET DLL file in the GAC?

As ando said, just drag and drop the assembly to the C:\windows\assembly folder. It works.

Unable to use Intellij with a generated sources folder

The fix

Go to Project Structure - Modules - Source Folders and find the target/generated-sources/antlr4/com/mycompany - click Edit properties and set Package prefix to com.mycompany.

This is exactly the reason why we can set Package prefix on source dirs.


Different but related problem here

Input button target="_blank" isn't causing the link to load in a new window/tab

Just use the javascript window.open function with the second parameter at "_blank"

<button onClick="javascript:window.open('http://www.facebook.com', '_blank');">facebook</button>

How to call a shell script from python code?

I'm running python 3.5 and subprocess.call(['./test.sh']) doesn't work for me.

I give you three solutions depends on what you wanna do with the output.

1 - call script. You will see output in your terminal. output is a number.

import subprocess 
output = subprocess.call(['test.sh'])

2 - call and dump execution and error into string. You don't see execution in your terminal unless you print(stdout). Shell=True as argument in Popen doesn't work for me.

import subprocess
from subprocess import Popen, PIPE

session = subprocess.Popen(['test.sh'], stdout=PIPE, stderr=PIPE)
stdout, stderr = session.communicate()

if stderr:
    raise Exception("Error "+str(stderr))

3 - call script and dump the echo commands of temp.txt in temp_file

import subprocess
temp_file = open("temp.txt",'w')
subprocess.call([executable], stdout=temp_file)
with open("temp.txt",'r') as file:
    output = file.read()
print(output)

Don't forget to take a look at the doc subprocess

Initialize/reset struct to zero/null

Define a const static instance of the struct with the initial values and then simply assign this value to your variable whenever you want to reset it.

For example:

static const struct x EmptyStruct;

Here I am relying on static initialization to set my initial values, but you could use a struct initializer if you want different initial values.

Then, each time round the loop you can write:

myStructVariable = EmptyStruct;

Display current date and time without punctuation

Without punctuation (as @Burusothman has mentioned):

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

O/P:

20170115072120

With punctuation:

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

O/P:

2017-01-15 07:25:33

Access Controller method from another controller in Laravel 5

You can access your controller method like this:

app('App\Http\Controllers\PrintReportController')->getPrintReport();

This will work, but it's bad in terms of code organisation (remember to use the right namespace for your PrintReportController)

You can extend the PrintReportController so SubmitPerformanceController will inherit that method

class SubmitPerformanceController extends PrintReportController {
     // ....
}

But this will also inherit all other methods from PrintReportController.

The best approach will be to create a trait (e.g. in app/Traits), implement the logic there and tell your controllers to use it:

trait PrintReport {

    public function getPrintReport() {
        // .....
    }
}

Tell your controllers to use this trait:

class PrintReportController extends Controller {
     use PrintReport;
}

class SubmitPerformanceController extends Controller {
     use PrintReport;
}

Both solutions make SubmitPerformanceController to have getPrintReport method so you can call it with $this->getPrintReport(); from within the controller or directly as a route (if you mapped it in the routes.php)

You can read more about traits here.

Running an outside program (executable) in Python?

Is that trying to execute C:\Documents with arguments of "and", "Settings/flow_model/flow.exe"?

Also, you might consider subprocess.call().

Regex to get the words after matching string

This might work out for you depending on which language you are using:

(?<=Object Name:).*

It's a positive lookbehind assertion. More information could be found here.

It won't work with JavaScript though. In your comment I read that you're using it for logstash. If you are using GROK parsing for logstash then it would work. You can verify it yourself here:

https://grokdebug.herokuapp.com/

Enter image description here

How to make custom error pages work in ASP.NET MVC 4

I had everything set up, but still couldn't see proper error pages for status code 500 on our staging server, despite the fact everything worked fine on local development servers.

I found this blog post from Rick Strahl that helped me.

I needed to add Response.TrySkipIisCustomErrors = true; to my custom error handling code.

How to parse JSON using Node.js?

If the JSON source file is pretty big, may want to consider the asynchronous route via native async / await approach with Node.js 8.0 as follows

const fs = require('fs')

const fsReadFile = (fileName) => {
    fileName = `${__dirname}/${fileName}`
    return new Promise((resolve, reject) => {
        fs.readFile(fileName, 'utf8', (error, data) => {
            if (!error && data) {
                resolve(data)
            } else {
                reject(error);
            }
        });
    })
}

async function parseJSON(fileName) {
    try {
        return JSON.parse(await fsReadFile(fileName));
    } catch (err) {
        return { Error: `Something has gone wrong: ${err}` };
    }
}

parseJSON('veryBigFile.json')
    .then(res => console.log(res))
    .catch(err => console.log(err))

How to get height of <div> in px dimension

For those looking for a plain JS solution:

let el = document.querySelector("#myElementId");

// including the element's border
let width = el.offsetWidth;
let height = el.offsetHeight;

// not including the element's border:
let width = el.clientWidth;
let height = el.clientHeight;

Check out this article for more details.

how to sort order of LEFT JOIN in SQL query?

Try using MAX with a GROUP BY.

SELECT u.userName, MAX(c.carPrice)
FROM users u
    LEFT JOIN cars c ON u.id = c.belongsToUser
WHERE u.id = 4;
GROUP BY u.userName;

Further information on GROUP BY

The group by clause is used to split the selected records into groups based on unique combinations of the group by columns. This then allows us to use aggregate functions (eg. MAX, MIN, SUM, AVG, ...) that will be applied to each group of records in turn. The database will return a single result record for each grouping.

For example, if we have a set of records representing temperatures over time and location in a table like this:

Location   Time    Temperature
--------   ----    -----------
London     12:00          10.0
Bristol    12:00          12.0
Glasgow    12:00           5.0
London     13:00          14.0
Bristol    13:00          13.0
Glasgow    13:00           7.0
...

Then if we want to find the maximum temperature by location, then we need to split the temperature records into groupings, where each record in a particular group has the same location. We then want to find the maximum temperature of each group. The query to do this would be as follows:

SELECT Location, MAX(Temperature)
FROM Temperatures
GROUP BY Location;

List all files and directories in a directory + subdirectories

With this you can just run them and chosse the sub folder when console run

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using data.Patcher; // The patcher XML
namespace PatchBuilder
{
class Program
{
    static void Main(string[] args)
    {
        string patchDir;
        if (args.Length == 0)
        {
            Console.WriteLine("Give the patch directory in argument");
            patchDir = Console.ReadLine();
        }
        else
        {
            patchDir = args[0];
        }

        if (File.Exists(Path.Combine(patchDir, "patch.xml")))
            File.Delete(Path.Combine(patchDir, "patch.xml"));

        var files = Directory.EnumerateFiles(patchDir, "*", SearchOption.AllDirectories).OrderBy(p => p).ToList();

        foreach (var file in files.Where(file => file.StartsWith("patch\\Resources")).ToArray())
        {
            files.Remove(file);
            files.Add(file);
        }

        var tasks = new List<MetaFileEntry>();
        using (var md5Hasher = MD5.Create())
        {
            for (int i = 0; i < files.Count; i++)
            {
                var file = files[i];

                if ((File.GetAttributes(file) & FileAttributes.Hidden) != 0)
                    continue;

                var content = File.ReadAllBytes(file);
                var md5Hasher2 = MD5.Create();

                var task =
                    new MetaFileEntry
                    {
                        LocalURL = GetRelativePath(file, patchDir + "\\"),
                        RelativeURL = GetRelativePath(file, patchDir + "\\"),
                        FileMD5 = Convert.ToBase64String(md5Hasher2.ComputeHash(content)),
                        FileSize = content.Length,
                    };

                md5Hasher2.Dispose();

                var pathBytes = Encoding.UTF8.GetBytes(task.LocalURL.ToLower());
                md5Hasher.TransformBlock(pathBytes, 0, pathBytes.Length, pathBytes, 0);
                if (i == files.Count - 1)
                    md5Hasher.TransformFinalBlock(content, 0, content.Length);
                else
                    md5Hasher.TransformBlock(content, 0, content.Length, content, 0);

                tasks.Add(task);
                Console.WriteLine(@"Add " + task.RelativeURL);
            }

            var patch = new MetaFile
            {
                Tasks = tasks.ToArray(),
                FolderChecksum = BitConverter.ToString(md5Hasher.Hash).Replace("-", "").ToLower(),
            };


            //XmlUtils.Serialize(Path.Combine(patchDir, "patch.xml"), patch);
            Console.WriteLine(@"Created Patch in {0} !", Path.Combine(patchDir, "patch.xml"));
        }

        Console.Read();
    }

    static string GetRelativePath(string fullPath, string relativeTo)
    {
        var foldersSplitted = fullPath.Split(new[] { relativeTo.Replace("/", "\\").Replace("\\\\", "\\") }, StringSplitOptions.RemoveEmptyEntries); // cut the source path and the "rest" of the path

        return foldersSplitted.Length > 0 ? foldersSplitted.Last() : ""; // return the "rest"
    }
}
}

and this the patchar for XML export

using System.Xml.Serialization;

namespace data.Patcher
{
    public class MetaFile
    {

        [XmlArray("Tasks")]
        public MetaFileEntry[] Tasks
        {
            get;
            set;
        }

        [XmlAttribute("checksum")]
        public string FolderChecksum
        {
            get;
            set;
        }
    }
}

Regular expression for address field validation

Regular expression for simple address validation

^[#.0-9a-zA-Z\s,-]+$

E.g. for Address match case

#1, North Street, Chennai - 11 

E.g. for Address not match case

$1, North Street, Chennai @ 11

Custom toast on Android: a simple example

val inflater = layoutInflater
val container: ViewGroup = findViewById(R.id.custom_toast_container)
val layout: ViewGroup = inflater.inflate(R.layout.custom_toast, container)
val text: TextView = layout.findViewById(R.id.text)
text.text = "This is a custom toast"
with (Toast(applicationContext)) {
    setGravity(Gravity.CENTER_VERTICAL, 0, 0)
    duration = Toast.LENGTH_LONG
    view = layout
    show()
}

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:id="@+id/custom_toast_container"
              android:orientation="horizontal"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:padding="8dp"
              android:background="#DAAA"
              >
    <ImageView android:src="@drawable/droid"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:layout_marginRight="8dp"
               />
    <TextView android:id="@+id/text"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textColor="#FFF"
              />
</LinearLayout>

Reference : https://developer.android.com/guide/topics/ui/notifiers/toasts

How can I load the contents of a text file into a batch file variable?

You can use:

set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i

Best data type to store money values in MySQL

If your application needs to handle money values up to a trillion then this should work: 13,2 If you need to comply with GAAP (Generally Accepted Accounting Principles) then use: 13,4

Usually you should sum your money values at 13,4 before rounding of the output to 13,2.

Force youtube embed to start in 720p

This is an embed example of video played in HD 1080.

<iframe width="560" height="315" src="http://youtube.com/v/IplDUxTQxsE&vq=hd1080" frameborder="0" allowfullscreen="1"></iframe>

Let's break apart the code:http://youtube.com/v/ video_id &vq=hd1080

Video id for that video: IplDUxTQxsE you will see this type of random code in the link of every YouTube video.

So far so good, this trick works for playing full HD videos directly on webpages!

You can change the quality to 720 too. &vq=hd720

SQL to Entity Framework Count Group-By

A useful extension is to collect the results in a Dictionary for fast lookup (e.g. in a loop):

var resultDict = _dbContext.Projects
    .Where(p => p.Status == ProjectStatus.Active)
    .GroupBy(f => f.Country)
    .Select(g => new { country = g.Key, count = g.Count() })
    .ToDictionary(k => k.country, i => i.count);

Originally found here: http://www.snippetsource.net/Snippet/140/groupby-and-count-with-ef-in-c

How do I use a C# Class Library in a project?

Here is a good article on creating and adding a class library. Even shows how to create Methods through the method wizard and how to use it in the application

Single TextView with multiple colored text

I have done this, try it:

TextView textView=(TextView)findViewById(R.id.yourTextView);//init

//here I am appending two string into my textView with two diff colors.
//I have done from fragment so I used here getActivity(), 
//If you are trying it from Activity then pass className.this or this; 

textView.append(TextViewUtils.getColoredString(getString(R.string.preString),ContextCompat.getColor(getActivity(),R.color.firstColor)));
textView.append(TextViewUtils.getColoredString(getString(R.string.postString),ContextCompat.getColor(getActivity(),R.color.secondColor)));

Inside your TextViewUtils class add this method:

 /***
 *
 * @param mString this will setup to your textView
 * @param colorId  text will fill with this color.
 * @return string with color, it will append to textView.
 */
public static Spannable getColoredString(String mString, int colorId) {
    Spannable spannable = new SpannableString(mString);
    spannable.setSpan(new ForegroundColorSpan(colorId), 0, spannable.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    Log.d(TAG,spannable.toString());
    return spannable;
}

C++: Rounding up to the nearest multiple of a number

For negative numToRound:

It should be really easy to do this but the standard modulo % operator doesn't handle negative numbers like one might expect. For instance -14 % 12 = -2 and not 10. First thing to do is to get modulo operator that never returns negative numbers. Then roundUp is really simple.

public static int mod(int x, int n) 
{
    return ((x % n) + n) % n;
}

public static int roundUp(int numToRound, int multiple) 
{
    return numRound + mod(-numToRound, multiple);
}

drag drop files into standard html file input

I know some trick works in Chrome:

When dropping files into drop zone you get a dataTransfer.files object, that is a FileList type of object, that contains all the files you dragged. Meanwhile, <input type="file" /> element has the property files, that is the same FileList type object.

So, you can simply assign the dataTransfer.files object to the input.files property.

Encrypt and Decrypt in Java

public class GenerateEncryptedPassword {

    public static void main(String[] args){

        Scanner sc= new Scanner(System.in);    
        System.out.println("Please enter the password that needs to be encrypted :");
        String input = sc.next();

        try {
            String encryptedPassword= AESencrp.encrypt(input);
            System.out.println("Encrypted password generated is :"+encryptedPassword);
        } catch (Exception ex) {
            Logger.getLogger(GenerateEncryptedPassword.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}

How do I use TensorFlow GPU?

Strangely, even though the tensorflow website 1 mentions that CUDA 10.1 is compatible with tensorflow-gpu-1.13.1, it doesn't work so far. tensorflow-gpu gets installed properly though but it throws out weird errors when running.

So far, the best configuration to run tensorflow with GPU is CUDA 9.0 with tensorflow_gpu-1.12.0 under python3.6.

Following this configuration with the steps mentioned in https://stackoverflow.com/a/51307381/2562870 (the answer above), worked for me :)

How to convert byte array to string and vice versa?

Why was the problem: As someone already specified: If you start with a byte[] and it does not in fact contain text data, there is no "proper conversion". Strings are for text, byte[] is for binary data, and the only really sensible thing to do is to avoid converting between them unless you absolutely have to.

I was observing this problem when I was trying to create byte[] from a pdf file and then converting it to String and then taking the String as input and converting back to file.

So make sure your encoding and decoding logic is same as I did. I explicitly encoded the byte[] to Base64 and decoded it to create the file again.

Use-case: Due to some limitation I was trying to sent byte[] in request(POST) and the process was as follows:

PDF File >> Base64.encodeBase64(byte[]) >> String >> Send in request(POST) >> receive String >> Base64.decodeBase64(byte[]) >> create binary

Try this and this worked for me..

File file = new File("filePath");

        byte[] byteArray = new byte[(int) file.length()];

        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(byteArray);

            String byteArrayStr= new String(Base64.encodeBase64(byteArray));

            FileOutputStream fos = new FileOutputStream("newFilePath");
            fos.write(Base64.decodeBase64(byteArrayStr.getBytes()));
            fos.close();
        } 
        catch (FileNotFoundException e) {
            System.out.println("File Not Found.");
            e.printStackTrace();
        }
        catch (IOException e1) {
            System.out.println("Error Reading The File.");
            e1.printStackTrace();
        }

Where is the application.properties file in a Spring Boot project?

You can also create the application.properties file manually.

SpringApplication will load properties from application.properties files in the following locations and add them to the Spring Environment:

  • A /config subdirectory of the current directory.
  • The current directory
  • A classpath /config package
  • The classpath root

The list is ordered by precedence (properties defined in locations higher in the list override those defined in lower locations). (From the Spring boot features external configuration doc page)

So just go ahead and create it

Convert XmlDocument to String

As an extension method:

public static class Extensions
{
    public static string AsString(this XmlDocument xmlDoc)
    {
        using (StringWriter sw = new StringWriter())
        {
            using (XmlTextWriter tx = new XmlTextWriter(sw))
            {
                xmlDoc.WriteTo(tx);
                string strXmlText = sw.ToString();
                return strXmlText;
            }
        }
    }
}

Now to use simply:

yourXmlDoc.AsString()

How to Flatten a Multidimensional Array?

Here's a simplistic approach:

$My_Array = array(1,2,array(3,4, array(5,6,7), 8), 9);

function checkArray($value) {
    foreach ($value as $var) {
        if ( is_array($var) ) {
            checkArray($var);
        } else {
            echo $var;
        }
    }
}

checkArray($My_Array);